All files / src/app/api/negotiations route.ts

98.19% Statements 109/111
91.13% Branches 72/79
100% Functions 12/12
100% Lines 104/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471                                        5x       5x     5x       14x 14x           14x 9x   5x                                           7x 7x       7x   3x                               48x 48x 48x 47x 1x     46x 45x       37x                                           18x 11x                     18x 16x 10x 10x   2x 1x 1x 1x                                                           39x 39x   39x   39x 2x             37x 37x 19x 19x 1x         18x     18x 11x   7x 7x         7x 7x 2x                   5x             18x 18x 3x     15x 15x 15x         9x 1x     6x                   15x 15x         39x 39x 6x   39x 39x 11x         39x           39x       41x 41x   41x 41x                   41x   41x 3x           38x 1x                           37x             41x   41x                                                         41x                 41x 41x           1x     36x 36x         23x                 23x             13x 13x 6x           6x     7x 13x   13x                                                         13x 13x                 7x     6x 6x     6x 6x 1x                 5x            
import { NextRequest, NextResponse } from "next/server";
import { DSP_PROTOCOL } from "@/lib/dsp-protocol";
import { edcClient, EDC_CONTEXT, newestFirstQuery } from "@/lib/edc";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import {
  auditCallbackAddresses,
  auditUnavailableResponse,
  recordDspEvent,
  recordDspEventAfter,
} from "@/lib/dsp-audit";
import { recordDemo, listDemo } from "@/lib/demo-records";
import { buildDemoCatalog, type DemoAssetEntry } from "@/lib/demo-catalog";
import { loadTestId } from "@/lib/proxy";
import { pageFrom } from "@/lib/list-page";
import { contextIdForDid, forgetContexts } from "@/lib/edc/context-lookup";
import { shareInFlight } from "@/lib/server-cache";
import { tagRows } from "@/lib/row-provenance";
import { promises as fs } from "fs";
import path from "path";
 
export const dynamic = "force-dynamic";
 
/** The connector's DSP base, as the containers next to it reach it. */
const DSP_BASE =
  process.env.EDC_PROTOCOL_URL || "http://controlplane:8082/api/dsp";
 
/** Before EDC 0.18 a participant's DSP address ended in the DSP version. */
const LEGACY_VERSION_SUFFIX = "/2025-1";
 
/** Load demo negotiations from the bundled mock JSON file. */
async function loadMockNegotiations(): Promise<unknown[]> {
  try {
    const mockPath = path.join(
      process.cwd(),
      "public",
      "mock",
      "negotiations.json",
    );
    const raw = await fs.readFile(mockPath, "utf-8");
    return JSON.parse(raw) as unknown[];
  } catch {
    return [];
  }
}
 
/**
 * Build a DSP catalog from the bundled demo assets.
 *
 * Why this exists: `/api/participants` falls back to `public/mock/participants.json`
 * whenever the connector reports no ACTIVATED or CREATED participant context.
 * Before #876 it did so on Azure, where every context stays CREATED. The
 * negotiate page then took one of those demo context ids and sent it to the
 * live connector, which answered `404 Not Found` because no such
 * context exists there. The id was never real, so the request could not have
 * succeeded.
 *
 * Serving the matching demo catalog keeps the walkthrough usable and, because the
 * response carries `demo: true`, the page says plainly where the data came from
 * rather than presenting it as a live catalog.
 */
async function loadDemoCatalog(
  providerDid: string,
): Promise<Record<string, unknown> | null> {
  try {
    const raw = await fs.readFile(
      path.join(process.cwd(), "public", "mock", "assets.json"),
      "utf-8",
    );
    return buildDemoCatalog(JSON.parse(raw) as DemoAssetEntry[], providerDid);
  } catch {
    return null;
  }
}
 
/**
 * Build the full per-participant DSP endpoint from a base URL + ctx ID.
 * EDC 0.18 format: {dspBase}/{providerCtxId}/{profileId}. The connector routes
 * /{participantContextId}/{profileId}/catalog|negotiations|transfers, so the
 * last segment is the profile id; /{ctx}/2025-1 answers 404 (#542). An address
 * still ending in /2025-1 has that segment replaced.
 *
 * Examples:
 *   buildDspEndpoint("http://controlplane:8082/api/dsp", "abc123")
 *   → "http://controlplane:8082/api/dsp/abc123/http-dsp-profile-2025-1"
 */
function buildDspEndpoint(base: string, ctxId: string): string {
  let clean = base; // strip trailing slashes; a loop, as /\/+$/ backtracks
  while (clean.endsWith("/")) clean = clean.slice(0, -1);
  if (clean.endsWith(`/${DSP_PROTOCOL}`)) return clean;
  if (clean.endsWith(LEGACY_VERSION_SUFFIX)) {
    return `${clean.slice(0, -LEGACY_VERSION_SUFFIX.length)}/${DSP_PROTOCOL}`;
  }
  // If ctxId already embedded, just add the profile id
  if (clean.includes(ctxId)) return `${clean}/${DSP_PROTOCOL}`;
  return `${clean}/${ctxId}/${DSP_PROTOCOL}`;
}
 
function isPlainObject(v: unknown): v is Record<string, unknown> {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}
 
/**
 * The provider's DSP catalogue, as the consumer context asks for it.
 *
 * The catalog request takes the provider's DSP address, which carries its
 * context id, while the page only knows the provider's DID. The id comes
 * from the kept context list (lib/edc/context-lookup.ts); before #1088 every
 * catalogue request listed every context first. When the request fails on a
 * kept id, the list is read afresh and the request tried once more, so a
 * stack reset costs one retry rather than a demo catalogue.
 *
 * Requests for the same catalogue at the same moment share one DSP request:
 * the answer depends on the consumer context and the provider only (the
 * control plane is called with the hub's service token, not the person's),
 * and nothing is kept once it has answered.
 */
async function requestCatalog(
  participantId: string,
  providerDid: string,
): Promise<unknown> {
  const ask = (providerCtx: string) =>
    edcClient.management(
      `/v5/participants/${participantId}/catalog/request`,
      "POST",
      {
        "@context": [EDC_CONTEXT],
        "@type": "CatalogRequest",
        counterPartyAddress: buildDspEndpoint(DSP_BASE, providerCtx),
        counterPartyId: providerDid,
        protocol: DSP_PROTOCOL,
      },
    );
  return shareInFlight(`catalog:${participantId}:${providerDid}`, async () => {
    const provider = await contextIdForDid(providerDid);
    try {
      return await ask(provider.id);
    } catch (err) {
      if (!provider.kept) throw err;
      forgetContexts();
      const fresh = await contextIdForDid(providerDid);
      return ask(fresh.id);
    }
  });
}
 
/**
 * POST /api/negotiations — Initiate a DSP-compliant contract negotiation.
 *
 * Body: {
 *   participantId:       consumer participant context @id
 *   counterPartyAddress: provider DSP address; the catalog's endpointURL, or omitted
 *                        for this deployment's own base (EDC_PROTOCOL_URL)
 *   counterPartyId:      provider participant context @id (their UUID)
 *   providerDid:         provider DID (used as ODRL assigner — required for DCP)
 *   offerId:             ODRL offer @id obtained from catalog (required for valid DSP flow)
 *   assetId:             target asset @id
 *   policyId:            alias for offerId (legacy)
 *   policy:              the offer's ODRL policy as the catalog gave it
 * }
 *
 * GET /api/negotiations?participantId=<id>[&limit=<n>&offset=<n>]: one page
 * of the participant's negotiations, newest first; `limit` 50 unless asked,
 * at most 200 (lib/list-page.ts). The demo and mock rows come on the first
 * page (offset 0) only.
 *
 * GET /api/negotiations?participantId=<id>&catalog=true&providerDid=<did>:
 * the provider's DSP catalogue for that consumer context.
 */
 
export async function GET(req: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  const participantId = req.nextUrl.searchParams.get("participantId");
 
  if (!participantId) {
    return NextResponse.json(
      { error: "participantId query parameter is required" },
      { status: 400 },
    );
  }
 
  // Catalog pre-fetch mode: ?catalog=true&providerDid=<did>
  const catalog = req.nextUrl.searchParams.get("catalog");
  if (catalog === "true") {
    const providerDid = req.nextUrl.searchParams.get("providerDid");
    if (!providerDid) {
      return NextResponse.json(
        { error: "providerDid is required for catalog fetch" },
        { status: 400 },
      );
    }
    try {
      // The v1alpha catalog-by-DID endpoint is gone in EDC 0.18 (404, #542);
      // catalog/request takes the provider's DSP address instead.
      const catalogData = await requestCatalog(participantId, providerDid);
      return NextResponse.json(catalogData);
    } catch (err) {
      console.error("Failed to fetch provider catalog:", err);
      const msg = err instanceof Error ? err.message : String(err);
 
      // The connector has no participant context for this id. That is expected
      // while the Azure EDC stack is unseeded, because the id came from the demo
      // participant list in the first place. Serve the demo catalog and label it.
      const demo = await loadDemoCatalog(providerDid);
      if (demo) {
        return NextResponse.json({
          ...demo,
          demoReason:
            "The connector has no participant context for this id, so these offers " +
            "come from the demonstrator's own catalogue rather than from a live DSP " +
            "request. Tracked in issue #876.",
          upstreamError: msg,
        });
      }
 
      return NextResponse.json(
        { error: "Failed to fetch provider catalog", detail: msg },
        { status: 502 },
      );
    }
  }
 
  const page = pageFrom(req.nextUrl.searchParams);
  if ("error" in page) {
    return NextResponse.json({ error: page.error }, { status: 400 });
  }
 
  let realNegotiations: unknown[] = [];
  try {
    realNegotiations = await edcClient.management<unknown[]>(
      `/v5/participants/${participantId}/contractnegotiations/request`,
      "POST",
      newestFirstQuery(page.limit, page.offset),
    );
    if (!Array.isArray(realNegotiations)) {
      realNegotiations = [];
    }
  } catch (err) {
    console.warn(
      "Controlplane negotiation list unavailable, using demo data:",
      err,
    );
  }
 
  // Negotiations this process recorded because the connector could not take
  // them (see lib/demo-records.ts). They come first: the newest is the one the
  // user just made, and the transfer page reads its agreements from this list.
  // Only the first page carries them, so a later page does not repeat them.
  const firstPage = page.offset === 0;
  const demoNegotiations = firstPage
    ? listDemo("negotiation", participantId)
    : [];
 
  // Merge with demo negotiations so the full workflow is always demonstrable
  const mockNegotiations = firstPage ? await loadMockNegotiations() : [];
  const realIds = new Set(
    realNegotiations.map((n) => (n as Record<string, unknown>)["@id"]),
  );
  const taken = new Set([...realIds, ...demoNegotiations.map((d) => d["@id"])]);
  const deduped = mockNegotiations.filter(
    (m) => !taken.has((m as Record<string, unknown>)["@id"]),
  );
  // Each row says where it came from and whether the detail route can serve
  // it: the list merges three sources, the detail route asks only the control
  // plane, and without this a person cannot tell which rows 502 (#358).
  const merged = [
    ...tagRows(demoNegotiations, "demo"),
    ...tagRows(realNegotiations, "controlplane"),
    ...tagRows(deduped, "mock"),
  ];
 
  return NextResponse.json(merged);
}
 
export async function POST(req: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    const body = await req.json();
    const {
      participantId,
      counterPartyAddress,
      counterPartyId,
      providerDid,
      offerId,
      assetId,
      policyId,
      policy: offeredPolicy,
    } = body;
 
    if (!participantId || !assetId) {
      return NextResponse.json(
        { error: "participantId and assetId are required" },
        { status: 400 },
      );
    }
 
    if (!offerId && !policyId) {
      return NextResponse.json(
        {
          error:
            "offerId is required — fetch the provider catalog first to get a valid ODRL offer @id",
        },
        { status: 400 },
      );
    }
 
    // Construct the full DSP endpoint: {dspBase}/{providerCtxId}/{profileId}.
    // Without an address, this deployment's own DSP base: the page used to
    // send a hard-coded http://controlplane:8082, the compose host, which does
    // not resolve on Azure (mvhd-controlplane), so every negotiation started
    // there stayed REQUESTING (#876).
    const dspEndpoint = buildDspEndpoint(
      counterPartyAddress || DSP_BASE,
      counterPartyId,
    );
 
    // The ODRL assigner must be the provider's DID (for DCP credential verification)
    // Fall back to counterPartyId UUID if no DID provided (will fail DCP auth)
    const assigner = providerDid || counterPartyId || "";
 
    const negotiationPayload = {
      "@context": [EDC_CONTEXT],
      "@type": "ContractRequest",
      counterPartyAddress: dspEndpoint,
      counterPartyId: counterPartyId || "",
      protocol: DSP_PROTOCOL,
      // The offer as the catalog gave it: the connector compares the request
      // with the policy it offered, so an offer with constraints, duties or
      // prohibitions (the standard policies, ADR-077) must come back whole.
      // Without one, the bare permission the seeded offers carried.
      policy: {
        ...(isPlainObject(offeredPolicy)
          ? offeredPolicy
          : // EDC-V requires a non-empty permission array.
            { permission: [{ action: "use" }] }),
        "@context": "http://www.w3.org/ns/odrl.jsonld",
        "@id": offerId || policyId,
        "@type": "Offer",
        assigner,
        target: assetId,
      },
      // Every state the connector moves this negotiation through reaches the
      // audit trail (ADR-045, #418).
      ...(auditCallbackAddresses("contract.negotiation").length > 0
        ? { callbackAddresses: auditCallbackAddresses("contract.negotiation") }
        : {}),
    };
 
    // On the audit trail before the connector is asked, or not at all.
    const audited = {
      process: "contract-negotiation" as const,
      loadTest: loadTestId(req),
      participantContext: participantId,
      consumerId: participantId,
      counterPartyId: counterPartyId || undefined,
      providerId: providerDid || undefined,
      assetId,
    };
    try {
      await recordDspEvent({
        ...audited,
        event: "requested",
        outcome: "success",
      });
    } catch (err) {
      return auditUnavailableResponse(err);
    }
 
    try {
      const result = await edcClient.management<Record<string, unknown>>(
        `/v5/participants/${participantId}/contractnegotiations`,
        "POST",
        negotiationPayload,
      );
      await recordDspEventAfter({
        ...audited,
        event: "initiated",
        outcome: "success",
        processId:
          result && typeof result["@id"] === "string"
            ? result["@id"]
            : undefined,
      });
      return NextResponse.json(result, { status: 201 });
    } catch (err) {
      // An offer that came from the demo catalogue cannot be negotiated against
      // the connector: neither the participant context nor the offer exists
      // there. Record it as a demo negotiation and label it, rather than ending
      // the walkthrough on a 502 the audience cannot act on. A real offer that
      // fails still fails, because that is a genuine fault worth seeing.
      const offer = String(offerId || policyId || "");
      if (!offer.startsWith("demo-offer:")) {
        await recordDspEventAfter({
          ...audited,
          event: "failed",
          outcome: "failure",
          reason: err instanceof Error ? err.message : String(err),
        });
        throw err;
      }
 
      const msg = err instanceof Error ? err.message : String(err);
      console.warn("Demo offer negotiated without a connector:", msg);
 
      const negotiation = {
        "@id": `demo-negotiation:${assetId}`,
        "@type": "ContractNegotiation",
        // Finalized, and carrying an agreement, because the next step of the
        // walkthrough builds its list from finalized negotiations that have one.
        // A demo negotiation left at REQUESTED is a dead end: nothing exists that
        // could ever advance it, so the transfer page never sees it and the flow
        // dies one click later. Both ids keep the demo- prefix so no later step
        // mistakes them for something a connector issued.
        state: "FINALIZED",
        contractAgreementId: `demo-agreement:${assetId}`,
        counterPartyId: counterPartyId || "",
        counterPartyAddress: dspEndpoint,
        protocol: DSP_PROTOCOL,
        assetId,
        offerId: offer,
        createdAt: Date.now(),
        demo: true,
        demoReason:
          "This offer came from the demonstrator's catalogue, so the request was " +
          "recorded here rather than sent to the connector, which has no participant " +
          "context for it. No DSP agreement was signed with anyone: the record is " +
          "finalized so that the transfer step has a contract to work with. " +
          "Tracked in issue #876.",
        upstreamError: msg,
      };
 
      // Nothing was written to the connector, so this process is the only place
      // the record can live until the next read (lib/demo-records.ts).
      recordDemo("negotiation", participantId, negotiation);
      await recordDspEventAfter({
        ...audited,
        event: "finalized",
        outcome: "success",
        processId: negotiation["@id"],
        agreementId: negotiation.contractAgreementId,
        demo: true,
      });
 
      return NextResponse.json(negotiation, { status: 201 });
    }
  } catch (err) {
    console.error("Failed to initiate negotiation:", err);
    const msg = err instanceof Error ? err.message : String(err);
    // The connector was reset after the page loaded: its participant
    // contexts have new ids, and the page still sends the old one (#876).
    const stale = /ParticipantContext with ID ([\w-]+) was not found/.exec(msg);
    if (stale) {
      return NextResponse.json(
        {
          error: "Not found",
          detail: `The connector no longer knows the participant context ${stale[1]}; it was reset after this page loaded. Reload the page and start the negotiation again.`,
          staleContext: stale[1],
        },
        { status: 409 },
      );
    }
    return NextResponse.json(
      { error: "Failed to initiate contract negotiation", detail: msg },
      { status: 502 },
    );
  }
}