All files / src/lib/edc provision.ts

98.59% Statements 70/71
88.63% Branches 39/44
100% Functions 21/21
100% Lines 69/69

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                                        14x       14x     14x   14x 14x   14x   14x 14x                                                         10x 10x   10x         14x 3x             39x 39x   5x           19x                     19x                                                                       15x                                             13x     13x 12x   13x 1x   12x                   19x 19x 19x 19x   19x 104x 104x 96x   8x 8x 8x 11x 11x 10x   1x             8x                     19x 19x                   16x 19x 16x     5x       16x 16x         15x   4x       15x 15x             14x 14x               14x 14x                               13x   13x             13x     2x             13x 13x   12x                                   11x         17x 17x     15x   2x      
import { edcClient, EDC_CONTEXT } from "@/lib/edc";
import { newDidSlug } from "@/lib/cfm-participant";
 
/**
 * Provisioning a dataspace participant on EDC 1.0, without CFM (ADR-078).
 *
 * The same sequence the seeds run, measured green on 1.0 from empty databases
 * (#881): 05-cp-participants.sh, seed-identityhub-participants.sh,
 * seed-cp-participant-config.sh, seed-issuer-holders.sh and
 * request-participant-credentials.sh. A failed step undoes the steps before
 * it, in reverse order, so a registration leaves a whole participant or none.
 * The MembershipCredential is requested, not awaited: the issuer delivers it
 * over DCP a few seconds later, and /api/participants/me reports when it has.
 *
 * Not yet: the participant's signing-key mapping in siglet, which renewing an
 * access token after its hour needs (#881 finding 23). siglet accepts only key
 * names without '%' and '#', and signs through Vault Transit.
 */
 
const DID_BASE =
  process.env.EDC_DID_BASE ||
  process.env.CFM_DID_BASE ||
  "did:web:identityhub%3A7083";
const CREDENTIAL_SERVICE_BASE =
  process.env.EDC_CREDENTIAL_SERVICE_BASE ||
  "http://identityhub:7082/api/credentials/v1/participants";
const PROTOCOL_BASE =
  process.env.EDC_PROTOCOL_BASE || "http://controlplane:8082/api/dsp";
const STS_TOKEN_URL =
  process.env.EDC_STS_TOKEN_URL || "http://identityhub:7084/api/sts/token";
const DSP_PROFILE = process.env.DSP_PROFILE || "http-dsp-profile-2025-1";
const SIGLET_SIGNALING_URL =
  process.env.SIGLET_SIGNALING_URL || "http://siglet:8081/api/v1";
const ISSUER_DID =
  process.env.EDC_ISSUER_DID || "did:web:issuerservice%3A10016:issuer";
const ISSUER_CTX = process.env.EDC_ISSUER_CTX || "issuer";
 
export interface Registration {
  displayName: string;
  organization?: string;
  role: string;
  ehdsParticipantType?: string;
}
 
export interface ProvisionStep {
  step: string;
  ok: boolean;
  detail?: string;
}
 
export interface Provisioned {
  contextId: string;
  did: string;
  steps: ProvisionStep[];
}
 
/**
 * A step failed; `steps` says which, and what was undone. `unreachable` when
 * the first step got no answer at all: a stopped stack (ADR-053's off hours),
 * not a refused registration.
 */
export class ProvisioningError extends Error {
  constructor(
    message: string,
    readonly steps: ProvisionStep[],
    readonly unreachable = false,
  ) {
    super(message);
  }
}
 
/** apiRequest's own error for an HTTP answer; anything else is transport. */
const answered = (err: unknown) =>
  err instanceof Error && err.message.startsWith("EDC API error");
 
/**
 * A 2xx whose body is empty or not JSON is a success: apiRequest skips the
 * parse only for a 204, and its JSON parse throws a SyntaxError otherwise.
 */
async function bodyNotNeeded(call: Promise<unknown>): Promise<void> {
  try {
    await call;
  } catch (err) {
    if (!(err instanceof SyntaxError)) throw err;
  }
}
 
/** The registration's details, kept on the control plane's context. */
function contextProperties(r: Registration): Record<string, string> {
  return {
    displayName: r.displayName,
    organization: r.organization || r.displayName,
    role: r.role,
    ehdsParticipantType: r.ehdsParticipantType || r.role,
    registeredAt: new Date().toISOString(),
  };
}
 
/** The IdentityHub manifest: DID, a generated key, and the two endpoints. */
export function identityManifest(contextId: string, did: string) {
  return {
    participantContextId: contextId,
    did,
    active: true,
    roles: ["participant"],
    serviceEndpoints: [
      {
        type: "CredentialService",
        serviceEndpoint: `${CREDENTIAL_SERVICE_BASE}/${contextId}`,
        id: `${contextId}-credentialservice`,
      },
      {
        type: "ProtocolEndpoint",
        serviceEndpoint: `${PROTOCOL_BASE}/${contextId}/${DSP_PROFILE}`,
        id: `${contextId}-dsp`,
      },
    ],
    keys: [
      {
        keyId: `${did}#key1`,
        // A fresh Vault alias per context: 1.0 will not generate a key under
        // an alias Vault already holds (#881 finding 18). Without the DID: the
        // compose Vault's file storage turns an alias of 93 characters or more
        // into a file name over 255 bytes ("file name too long"), and a
        // registered name makes a DID of up to 74 (measured 2026-11-05).
        privateKeyAlias: `${contextId}-key1`,
        active: true,
        keyGeneratorParams: { algorithm: "EdDSA" },
        usage: ["sign_token", "sign_presentation", "sign_credentials"],
      },
    ],
  };
}
 
/** The STS settings the control plane needs before it can send DSP for the context. */
function stsConfig(contextId: string, did: string) {
  return {
    "@context": [EDC_CONTEXT],
    "@type": "ParticipantContextConfig",
    entries: {
      "edc.participant.id": did,
      "edc.iam.issuer.id": did,
      "edc.iam.sts.oauth.client.id": did,
      "edc.iam.sts.oauth.token.url": STS_TOKEN_URL,
      "edc.iam.sts.oauth.client.secret.alias": `${contextId}-sts-client-secret`,
    },
    privateEntries: {},
  };
}
 
/** The MembershipCredential definition on the issuer, by type, as the seed finds it. */
/**
 * The issuer's MembershipCredential definition: its id, and the format it
 * issues in. The request names that format. From IdentityHub 1.0.0-RC6 a
 * definition takes the format of the issuer's DCP profile (VC2_0_JOSE by
 * default, IdentityHub #1248), and the holder refuses a delivered credential
 * whose format differs from the request with 403 (RC5 accepted it).
 */
async function membershipDefinition(): Promise<{ id: string; format: string }> {
  const defs = await edcClient.issuer<
    { id?: string; credentialType?: string; format?: string }[]
  >(`/v1/participants/${ISSUER_CTX}/credentialdefinitions/query`, "POST", {});
  const def = (Array.isArray(defs) ? defs : []).find(
    (d) => d.credentialType === "MembershipCredential",
  );
  if (!def?.id) {
    throw new Error("the issuer has no MembershipCredential definition");
  }
  return { id: def.id, format: def.format || "VC1_0_JWT" };
}
 
/**
 * Provisions one participant. Throws ProvisioningError after undoing what it
 * had created; on success the credential request is on its way.
 */
export async function provisionParticipant(
  r: Registration,
): Promise<Provisioned> {
  const did = `${DID_BASE}:${newDidSlug(r.displayName)}`;
  const steps: ProvisionStep[] = [];
  const undo: { step: string; run: () => Promise<unknown> }[] = [];
  let contextId = "";
 
  const run = async (step: string, fn: () => Promise<unknown>) => {
    try {
      await fn();
      steps.push({ step, ok: true });
    } catch (err) {
      const detail = err instanceof Error ? err.message : String(err);
      steps.push({ step, ok: false, detail });
      for (const u of undo.reverse()) {
        try {
          await u.run();
          steps.push({ step: `undo: ${u.step}`, ok: true });
        } catch (e) {
          steps.push({
            step: `undo: ${u.step}`,
            ok: false,
            detail: e instanceof Error ? e.message : String(e),
          });
        }
      }
      throw new ProvisioningError(
        `${step} failed: ${detail}`,
        steps,
        steps.length === 1 && !answered(err),
      );
    }
  };
 
  // The context stays CREATED: 1.0 accepts a PUT to ACTIVATED with 204 and
  // keeps the state (measured 2026-11-05), as it does for the seeded five, and
  // GET /api/participants lists CREATED contexts when none is ACTIVATED.
  await run("control plane context", async () => {
    const created = await edcClient.management<{ "@id"?: string }>(
      "/v5/participants",
      "POST",
      {
        "@context": [EDC_CONTEXT],
        "@type": "ParticipantContext",
        identity: did,
        properties: contextProperties(r),
      },
    );
    contextId = created?.["@id"] ?? "";
    Iif (!contextId) throw new Error("the control plane returned no context id");
    undo.push({
      step: "control plane context",
      run: () =>
        edcClient.management(`/v5/participants/${contextId}`, "DELETE"),
    });
  });
 
  await run("IdentityHub participant", async () => {
    await edcClient.identity(
      "/v1/participants",
      "POST",
      identityManifest(contextId, did),
    );
    undo.push({
      step: "IdentityHub participant",
      run: () => edcClient.identity(`/v1/participants/${contextId}`, "DELETE"),
    });
  });
 
  await run("context config", () =>
    edcClient.management(
      `/v5/participants/${contextId}/config`,
      "PUT",
      stsConfig(contextId, did),
    ),
  );
 
  await run("DSP profile", () =>
    edcClient.management(`/v5/participants/${contextId}/profiles`, "PUT", {
      "@context": [EDC_CONTEXT],
      "@type": "AssociateDataspaceProfile",
      profiles: [DSP_PROFILE],
    }),
  );
 
  // 1.0 answers 200 with an empty body here, not 204 (measured 2026-11-05).
  await run("data plane (siglet)", () =>
    bodyNotNeeded(
      edcClient.management(`/v5/participants/${contextId}/dataplanes`, "PUT", {
        dataplaneId: `siglet-${contextId}`,
        endpoint: `${SIGLET_SIGNALING_URL}/${contextId}/dataflows`,
        // RC6 renamed transferTypes to profiles (Connector #6196); EDC ignores
        // the field it does not know, so both keep RC5 (Azure) and RC6 working.
        profiles: ["HttpData-PULL"],
        transferTypes: ["HttpData-PULL"],
      }),
    ),
  );
 
  // Keyed by the context id, not the DID as the seeds do: a did:web carries
  // '%3A', and the IssuerService's Jetty refuses any path holding '%25' (400
  // "Ambiguous URI path encoding"), so a holder keyed by its DID can never be
  // deleted again. The issuer finds the holder by its DID either way.
  await run("issuer holder", async () => {
    // Created answers 2xx with an empty body (measured 2026-11-05).
    await bodyNotNeeded(
      edcClient.issuer(`/v1/participants/${ISSUER_CTX}/holders`, "POST", {
        holderId: contextId,
        did,
        name: r.displayName,
      }),
    );
    undo.push({
      step: "issuer holder",
      run: () =>
        edcClient.issuer(
          `/v1/participants/${ISSUER_CTX}/holders/${contextId}`,
          "DELETE",
        ),
    });
  });
 
  await run("MembershipCredential request", async () => {
    const definition = await membershipDefinition();
    // A 2xx whose body is the bare holderPid, not JSON, is a success.
    await bodyNotNeeded(
      edcClient.identity(
        `/v1/participants/${contextId}/credentials/request`,
        "POST",
        {
          issuerDid: ISSUER_DID,
          credentials: [
            {
              id: definition.id,
              type: "MembershipCredential",
              format: definition.format,
            },
          ],
        },
      ),
    );
  });
 
  return { contextId, did, steps };
}
 
/** Whether a participant holds a MembershipCredential the issuer delivered. */
export async function holdsMembership(contextId: string): Promise<boolean> {
  try {
    const creds = await edcClient.identity<
      { verifiableCredential?: { credential?: { type?: string[] } } }[]
    >(`/v1/participants/${contextId}/credentials?type=MembershipCredential`);
    return Array.isArray(creds) && creds.length > 0;
  } catch {
    return false;
  }
}