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

96.55% Statements 56/58
84.61% Branches 33/39
100% Functions 8/8
100% Lines 53/53

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                                    3x               20x 20x   20x 20x                 16x 30x 22x 16x   8x 20x 3x                   16x 2x 2x   1x           16x 18x 18x                     16x 12x               4x 4x 2x 2x   2x         2x               4x                 8x 8x           8x 3x 3x 3x         5x                                     10x 10x     10x 10x   1x   30x 9x 9x 9x 3x           6x     6x     10x           4x                               2x 1x                           1x 1x                    
import { NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { PROVISIONING_HOURS } from "@/lib/provisioning";
import { provisionParticipant, ProvisioningError } from "@/lib/edc/provision";
import {
  cfmProvisioning,
  cfmStatesByDid,
  provisionThroughCfm,
  type CfmState,
} from "@/lib/edc/cfm-provision";
import {
  listContexts,
  contextNames,
  type HubContext,
} from "@/lib/edc/participants";
import { promises as fs } from "fs";
import path from "path";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/participants — List all participant contexts (EDC-V Management API)
 * with their display names: the context's own properties for a participant
 * onboarded through the hub, the seeded five's names otherwise (ADR-078).
 */
export async function GET() {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    const participants = await listContexts();
 
    // Enrich each participant with a displayName. ACTIVATED contexts win, so
    // the stale CREATED ones a re-seed leaves on the compose stack stay hidden.
    // When none is ACTIVATED, the CREATED ones are the real contexts: on Azure
    // all of them have stayed CREATED since the 2026-10-28 re-seed and still
    // answer DSP catalog requests. Dropping them served the compose stack's
    // mock participants, whose ids and DIDs do not exist there, so every
    // catalog request fell back to the demo catalogue (#876).
    const all = participants;
    const stateOf = (p: HubContext) => p.state;
    const activated = all.filter((p) => stateOf(p) === "ACTIVATED");
    const usable = activated.length
      ? activated
      : all.filter((p) => stateOf(p) === "CREATED");
    if (!activated.length && usable.length) {
      console.warn(
        `Management API answered with no ACTIVATED participant context; ` +
          `using ${usable.length} CREATED context(s) (#876).`,
      );
    }
    // With CFM_TENANT_URL set, each context also says what CFM holds for it
    // (ADR-085 step 3): `cfm` is its profile's state, or null for a context
    // CFM did not provision, such as the seeded five. A Tenant Manager that
    // does not answer leaves `cfm` out rather than failing the list.
    let cfm: Map<string, CfmState> | undefined;
    if (cfmProvisioning()) {
      try {
        cfm = await cfmStatesByDid();
      } catch (err) {
        console.warn(
          "CFM Tenant Manager not reachable; listing without it:",
          err,
        );
      }
    }
    const enriched = usable.map((p) => {
      const { did, slug, displayName, role } = contextNames(p);
      return {
        ...p,
        participantId: p["@id"],
        displayName,
        role,
        slug,
        identity: did,
        ...(cfm ? { cfm: (did && cfm.get(did)) || null } : {}),
      };
    });
 
    if (enriched.length > 0) {
      return NextResponse.json(enriched);
    }
 
    // Say which of the two very different cases this is. Both used to end in
    // the same mock fallback and the same shrug of a log line, which is how
    // the live site listed fixtures for months without anyone noticing
    // (#317). "The API answered and nothing is activated" is a seeding or
    // lifecycle problem; "the API did not answer" is a transport one.
    const total = participants.length;
    if (total > 0) {
      const states = [
        ...new Set(participants.map((p) => p.state ?? "unknown")),
      ].sort();
      console.warn(
        `Management API answered with ${total} participant context(s), none ACTIVATED ` +
          `or CREATED (states: ${states.join(", ")}). Serving mock data.`,
      );
    } else {
      console.warn(
        "Management API answered with an empty participant list. Serving mock data. " +
          "The control plane holds no contexts; see #316 for how they are seeded.",
      );
    }
  } catch (err) {
    // A throw here is transport, not state: a wrong port or a wrong API
    // version segment both land in this branch (#307, #317).
    console.error(
      "Management API unreachable, serving mock data. Check EDC_MANAGEMENT_URL " +
        "(the Management API is on the control plane's 8081, not the ingress " +
        "FQDN) and EDC_MGMT_API_VERSION (the deployment serves v4alpha):",
      err,
    );
  }
 
  // Fall back to bundled mock data so the UI works offline / pre-seed
  try {
    const mockPath = path.join(
      process.cwd(),
      "public",
      "mock",
      "participants.json",
    );
    const raw = await fs.readFile(mockPath, "utf-8");
    const mock = JSON.parse(raw);
    console.warn("Serving mock participants");
    return NextResponse.json(mock);
  } catch {
    // Mock file not available either
  }
 
  return NextResponse.json(
    { error: "Failed to list participants" },
    { status: 502 },
  );
}
 
/**
 * POST /api/participants — Provision a participant on the control plane.
 *
 * Body: { displayName, organization, role, ehdsParticipantType }
 *
 * The hub provisions it itself, without CFM (ADR-078, lib/edc/provision.ts):
 * control plane context, IdentityHub participant with DID and key, context
 * config and DSP profile, data plane, issuer holder, and a MembershipCredential
 * requested over DCP. A failed step undoes the ones before it, so the answer is
 * a whole participant or none. The credential arrives a few seconds later;
 * /api/participants/me says when it has.
 */
export async function POST(req: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  let body: Record<string, unknown>;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }
  const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
  const displayName = str(body.displayName);
  const role = str(body.role);
  if (!displayName || !role) {
    return NextResponse.json(
      { error: "displayName and role are required" },
      { status: 400 },
    );
  }
 
  try {
    // CFM_TENANT_URL set: through CFM's Tenant Manager (ADR-085); else the
    // hub provisions the participant itself (ADR-078).
    const provision = cfmProvisioning()
      ? provisionThroughCfm
      : provisionParticipant;
    const { contextId, did, steps } = await provision({
      displayName,
      organization: str(body.organization),
      role,
      ehdsParticipantType: str(body.ehdsParticipantType),
    });
    return NextResponse.json(
      {
        tenantId: contextId,
        participantId: contextId,
        did,
        displayName,
        role,
        status: "provisioning",
        provisioned: true,
        steps,
      },
      { status: 201 },
    );
  } catch (err) {
    // A control plane that does not answer is a stopped stack (off hours,
    // ADR-053), not a refused registration: say so and record nothing.
    if (err instanceof ProvisioningError && err.unreachable) {
      return NextResponse.json(
        {
          error: "The provisioning stack is not running",
          detail:
            "The control plane did not answer, so nothing was registered. " +
            `${PROVISIONING_HOURS} Please register again then.`,
          upstreamError: err.message,
        },
        { status: 503 },
      );
    }
    // Detail first: "Failed to create participant" on its own reads as though
    // the form input were at fault (issue #203). The steps say what was
    // created and undone.
    console.error("Failed to create participant:", err);
    return NextResponse.json(
      {
        error: "Failed to create participant",
        detail: err instanceof Error ? err.message : String(err),
        ...(err instanceof ProvisioningError ? { steps: err.steps } : {}),
      },
      { status: 502 },
    );
  }
}