All files / src/lib/edc remove-participant.ts

93.18% Statements 41/44
84.21% Branches 32/38
100% Functions 9/9
95% Lines 38/40

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                                            3x   3x                             3x 4x   3x 1x                 7x 7x   1x     6x 6x 7x 1x           5x 5x 16x 16x 13x   3x 1x       5x           5x 5x         5x 5x 5x     5x   1x   1x                           5x 1x 1x           1x             5x 5x           5x 5x           5x    
/**
 * Removing a participant the hub onboarded (ADR-085 step 3, #973).
 *
 * Only a context registered through /onboarding can be removed: it carries
 * `registeredAt` (provision.ts and CFM's connector activity both write it).
 * The seeded participants carry none and stay, or every suite would lose its
 * provider and consumer.
 *
 * The order is the reverse of provisioning, the control plane context last,
 * so a removal that stops halfway can be run again: the context, which the
 * check above reads, is still there.
 *
 * With CFM_TENANT_URL set, the Tenant Manager's tenant and profile are removed
 * first, best effort (cfm-provision.ts, removeFromCfm). CFM 0.0.7's dispose
 * removes nothing on the stack (it reaches no agent with the context id), so
 * the hub removes the rest itself either way.
 */
import { edcClient } from "@/lib/edc";
import { getContext, type HubContext } from "@/lib/edc/participants";
import { cfmProvisioning, removeFromCfm } from "@/lib/edc/cfm-provision";
import type { ProvisionStep } from "@/lib/edc/provision";
 
const ISSUER_CTX = process.env.EDC_ISSUER_CTX || "issuer";
const SIGLET_MANAGEMENT_URL =
  process.env.SIGLET_MANAGEMENT_URL || "http://siglet:8083";
 
/** No context with that id: 404. */
export class ParticipantNotFound extends Error {}
 
/** A context the hub did not onboard: 409, nothing is touched. */
export class RemovalRefused extends Error {}
 
export interface Removed {
  contextId: string;
  did: string;
  steps: ProvisionStep[];
}
 
/** An answer of the EDC client that says the thing is not there. */
const notFound = (err: unknown) =>
  err instanceof Error && /: 404 /.test(err.message);
 
const detail = (err: unknown) =>
  err instanceof Error ? err.message.split("\n")[0] : String(err);
 
/**
 * Removes one onboarded participant. Throws ParticipantNotFound or
 * RemovalRefused before touching anything; afterwards it reports every step,
 * and a step that fails does not stop the others.
 */
export async function removeParticipant(contextId: string): Promise<Removed> {
  let ctx: HubContext;
  try {
    ctx = await getContext(contextId);
  } catch (err) {
    Eif (notFound(err)) throw new ParticipantNotFound(contextId);
    throw err;
  }
  Iif (!ctx || !ctx["@id"]) throw new ParticipantNotFound(contextId);
  const did = ctx.identity ?? "";
  if (typeof ctx.properties?.registeredAt !== "string") {
    throw new RemovalRefused(
      "only a participant registered through /onboarding can be removed; " +
        "the seeded participants stay",
    );
  }
 
  const steps: ProvisionStep[] = [];
  const run = async (step: string, fn: () => Promise<unknown>) => {
    try {
      await fn();
      steps.push({ step, ok: true });
    } catch (err) {
      if (notFound(err)) steps.push({ step, ok: true, detail: "not there" });
      else steps.push({ step, ok: false, detail: detail(err) });
    }
  };
 
  if (cfmProvisioning() && did) steps.push(...(await removeFromCfm(did)));
 
  // provision.ts keys the holder by the context id. CFM's registration agent
  // keys it by the DID, whose '%3A' the IssuerService refuses in a path
  // (400 "Ambiguous URI path encoding"), so that holder cannot be removed
  // through the API; it is reported, not hidden.
  await run("issuer holder", () =>
    edcClient.issuer(
      `/v1/participants/${ISSUER_CTX}/holders/${encodeURIComponent(contextId)}`,
      "DELETE",
    ),
  );
  Eif (did) {
    try {
      const holders = await edcClient.issuer<
        { holderId?: string; did?: string }[]
      >(`/v1/participants/${ISSUER_CTX}/holders/query`, "POST", {});
      if (
        Array.isArray(holders) &&
        holders.some((h) => h.did === did && h.holderId !== contextId)
      ) {
        steps.push({
          step: "issuer holder keyed by DID",
          ok: false,
          detail:
            "the IssuerService cannot delete a holder whose id holds '%3A' through its API",
        });
      }
    } catch {
      // the query is a report, not a step of the removal
    }
  }
 
  // Only CFM's siglet agent writes a transfer type mapping, so this runs only
  // when the hub provisions through CFM.
  if (cfmProvisioning()) {
    await run("siglet transfer type mapping", async () => {
      const res = await fetch(
        `${SIGLET_MANAGEMENT_URL}/transfer-type-mappings/${encodeURIComponent(
          contextId,
        )}`,
        { method: "DELETE", cache: "no-store" },
      );
      Iif (!res.ok && res.status !== 404) {
        throw new Error(`siglet answered ${res.status}`);
      }
    });
  }
 
  // Takes the participant's keys, STS client and credentials with it.
  await run("IdentityHub participant", () =>
    edcClient.identity(
      `/v1/participants/${encodeURIComponent(contextId)}`,
      "DELETE",
    ),
  );
 
  await run("control plane context", () =>
    edcClient.management(
      `/v5/participants/${encodeURIComponent(contextId)}`,
      "DELETE",
    ),
  );
 
  return { contextId, did, steps };
}