All files / src/lib permit-gate.ts

96.29% Statements 78/81
80.45% Branches 70/87
100% Functions 19/19
100% Lines 72/72

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                                                  17x                                                           16x                                         22x       3x 3x 3x     5x                 17x                 17x 1x             16x 17x 14x 2x           14x 12x 3x 3x 2x                     1x             9x 10x 10x   9x 1x                     8x 8x 4x 4x     2x 3x   2x 1x                                 1x             1x       2x                       4x 3x   17x 17x                                       2x 2x 2x 2x 2x                       2x 2x 2x   1x                   17x               12x 7x                                                                                   6x 2x             4x 4x           1x                         3x 2x                         1x     17x                                 4x 3x 3x 3x       3x 1x   2x 4x                                 2x 2x                                                               1x            
/**
 * The data permit gate.
 *
 * Regulation (EU) 2025/327: a health data user may access electronic health
 * data for secondary use only under a data permit issued by a health data
 * access body (Art. 61(1)); the body issues it after the Art. 68 assessment;
 * access then happens in a secure processing environment (Art. 73). In the
 * graph a permit is an HDABApproval with status APPROVED that APPROVES the
 * consumer's AccessApplication and GRANTS_ACCESS_TO the HealthDataset.
 *
 * POST /api/transfers calls checkPermit() before it does anything else, so a
 * refusal on /compliance really stops step 5 of the journey. Until issue #206
 * that page was read-only and the transfer route never looked at a permit.
 *
 * Dataset matching: the graph keys datasets as "dataset:synthea-fhir-r4-mvd";
 * EDC agreements carry asset ids like "fhir-cohort-bundle", and nothing links
 * the two yet. A caller that names the dataset (datasetId) gets a strict
 * check. A caller with only an asset id gets a best-effort match and, failing
 * that, any valid permit of the consumer; the result says which happened.
 */
import { runQuery } from "@/lib/neo4j";
import { DSP_PROTOCOL } from "@/lib/dsp-protocol";
import { parseGraphTime } from "@/lib/permits";
 
export const PERMIT_ARTICLE =
  "Regulation (EU) 2025/327, Art. 61(1) and Art. 68";
 
export interface PermitRow {
  permitId: string;
  status: string;
  datasetId: string | null;
  datasetTitle: string | null;
  validUntil: string | null;
  purpose: string | null;
  applicationId: string | null;
  revokedAt?: string | null;
  revocationReason?: string | null;
  /** The application invoked the Art. 71(4) exception (ADR-062). */
  art71Exception?: boolean | null;
}
 
export interface PermitCheck {
  allowed: boolean;
  consumerDid: string | null;
  permitId: string | null;
  datasetId: string | null;
  datasetMatched: boolean;
  validUntil: string | null;
  purpose: string | null;
  reason: string;
  article: string;
}
 
/** Every decision the access bodies have taken on this consumer's applications. */
export async function findPermits(consumerDid: string): Promise<PermitRow[]> {
  return runQuery<PermitRow>(
    `MATCH (consumer:Participant)
     WHERE coalesce(consumer.participantId, consumer.id) = $consumerDid
     MATCH (consumer)-[:SUBMITTED]->(app:AccessApplication)<-[:APPROVES]-(permit:HDABApproval)
     OPTIONAL MATCH (permit)-[:GRANTS_ACCESS_TO]->(ds:HealthDataset)
     RETURN permit.approvalId                                       AS permitId,
            toUpper(coalesce(permit.status, ''))                    AS status,
            coalesce(ds.datasetId, ds.id, app.datasetId)            AS datasetId,
            coalesce(ds.title, ds.name)                             AS datasetTitle,
            toString(permit.validUntil)                             AS validUntil,
            coalesce(permit.permittedPurpose, app.requestedPurpose) AS purpose,
            app.applicationId                                       AS applicationId,
            toString(permit.revokedAt)                              AS revokedAt,
            permit.revocationReason                                 AS revocationReason,
            app.art71Exception = true                               AS art71Exception
     ORDER BY permit.validUntil DESC`,
    { consumerDid },
  );
}
 
function norm(s: string | null | undefined): string {
  return (s ?? "").trim().toLowerCase();
}
 
function assetMatches(assetId: string, row: PermitRow): boolean {
  const a = norm(assetId);
  Iif (!a) return false;
  return [row.datasetId, row.datasetTitle]
    .map(norm)
    .filter(Boolean)
    .some((k) => k === a || k.includes(a) || a.includes(k));
}
 
export async function checkPermit(input: {
  consumerDid: string | null;
  datasetId?: string | null;
  assetId?: string | null;
  now?: Date;
}): Promise<PermitCheck> {
  const base: Omit<PermitCheck, "allowed" | "reason"> = {
    consumerDid: input.consumerDid,
    permitId: null,
    datasetId: null,
    datasetMatched: false,
    validUntil: null,
    purpose: null,
    article: PERMIT_ARTICLE,
  };
  if (!input.consumerDid) {
    return {
      ...base,
      allowed: false,
      reason:
        "The consumer of this contract could not be identified, so no data permit can be verified.",
    };
  }
  const now = (input.now ?? new Date()).getTime();
  const rows = await findPermits(input.consumerDid);
  if (rows.length === 0) {
    return {
      ...base,
      allowed: false,
      reason: `${input.consumerDid} holds no data permit: no health data access body has decided on an access application for this participant.`,
    };
  }
  const approved = rows.filter((r) => r.status === "APPROVED");
  if (approved.length === 0) {
    const revoked = rows.find((r) => r.status === "REVOKED");
    if (revoked) {
      return {
        ...base,
        allowed: false,
        permitId: revoked.permitId,
        reason: `Data permit ${revoked.permitId} was revoked on ${(
          revoked.revokedAt ?? ""
        ).slice(0, 10)} (Art. 63(3))${
          revoked.revocationReason ? `: ${revoked.revocationReason}` : ""
        }.`,
      };
    }
    return {
      ...base,
      allowed: false,
      permitId: rows[0].permitId,
      reason: `The health data access body refused the access application of ${input.consumerDid} (${rows[0].permitId}); no data permit exists.`,
    };
  }
  const valid = approved.filter((r) => {
    const t = parseGraphTime(r.validUntil);
    return t === null || t >= now;
  });
  if (valid.length === 0) {
    return {
      ...base,
      allowed: false,
      permitId: approved[0].permitId,
      validUntil: approved[0].validUntil,
      reason: `Data permit ${approved[0].permitId} expired on ${(
        approved[0].validUntil ?? ""
      ).slice(0, 10)}.`,
    };
  }
 
  const wanted = norm(input.datasetId);
  if (wanted) {
    const hit = valid.find((r) => norm(r.datasetId) === wanted);
    if (!hit) {
      // A permit for exactly this dataset that the body took back is the
      // reason that matters, not the other permits the consumer still holds.
      const revokedHere = rows.find(
        (r) => r.status === "REVOKED" && norm(r.datasetId) === wanted,
      );
      if (revokedHere) {
        return {
          ...base,
          allowed: false,
          permitId: revokedHere.permitId,
          datasetId: input.datasetId ?? null,
          reason: `Data permit ${revokedHere.permitId} for ${
            input.datasetId
          } was revoked on ${(revokedHere.revokedAt ?? "").slice(
            0,
            10,
          )} (Art. 63(3))${
            revokedHere.revocationReason
              ? `: ${revokedHere.revocationReason}`
              : ""
          }.`,
        };
      }
      return {
        ...base,
        allowed: false,
        datasetId: input.datasetId ?? null,
        reason: `${input.consumerDid} holds ${
          valid.length === 1 ? "a data permit" : "data permits"
        } for ${valid
          .map((r) => r.datasetId ?? "an unnamed dataset")
          .join(", ")}, none for ${input.datasetId}.`,
      };
    }
    return {
      ...base,
      allowed: true,
      permitId: hit.permitId,
      datasetId: hit.datasetId,
      datasetMatched: true,
      validUntil: hit.validUntil,
      purpose: hit.purpose,
      reason: `Covered by data permit ${hit.permitId} for ${hit.datasetId}.`,
    };
  }
 
  const byAsset = input.assetId
    ? valid.find((r) => assetMatches(input.assetId as string, r))
    : undefined;
  const chosen = byAsset ?? valid[0];
  return {
    ...base,
    allowed: true,
    permitId: chosen.permitId,
    datasetId: chosen.datasetId,
    datasetMatched: Boolean(byAsset),
    validUntil: chosen.validUntil,
    purpose: chosen.purpose,
    reason: byAsset
      ? `Covered by data permit ${chosen.permitId} for ${chosen.datasetId}.`
      : `Covered by data permit ${chosen.permitId}; the asset ${
          input.assetId ?? "(none)"
        } is not mapped to a dataset in the graph, so the permit's dataset ${
          chosen.datasetId ?? "(none)"
        } was not checked against it.`,
  };
}
 
/** The audit headers a permitted access carries to the neo4j-proxy. */
function permitHeaders(check: PermitCheck): Record<string, string> {
  Iif (!check.allowed || !check.permitId) return {};
  const headers: Record<string, string> = { "X-Permit": check.permitId };
  Eif (check.datasetId) headers["X-Dataset"] = check.datasetId;
  Eif (check.purpose) headers["X-Purpose"] = check.purpose;
  return headers;
}
 
/**
 * Headers that tell the neo4j-proxy which permit, dataset and purpose an
 * access runs under, so its audit record (TransferEvent) says more than the
 * endpoint. Empty when the consumer holds no valid permit. Never throws: an
 * audit detail must not break the query it describes.
 */
export async function activePermitHeaders(
  consumerDid: string | null,
): Promise<Record<string, string>> {
  Iif (!consumerDid) return {};
  try {
    return permitHeaders(await checkPermit({ consumerDid }));
  } catch {
    return {};
  }
}
 
/**
 * Whether Art. 61(1) applies to this caller. A health data user (DATA_USER)
 * accesses data for secondary use and needs a permit. A data holder looking
 * at its own data, the access body supervising, the trust centre operator
 * and the dataspace operator are not data users in that sense.
 */
const EXEMPT_ROLES = [
  "EDC_ADMIN",
  "DATA_HOLDER",
  "HDAB_AUTHORITY",
  "TRUST_CENTER_OPERATOR",
];
 
export function needsPermit(roles: string[]): boolean {
  return (
    roles.includes("DATA_USER") && !roles.some((r) => EXEMPT_ROLES.includes(r))
  );
}
 
export type SecondaryUseGate =
  | {
      allowed: true;
      /** The permit the access runs under; null when the caller is exempt. */
      check: PermitCheck | null;
      headers: Record<string, string>;
    }
  | {
      allowed: false;
      status: 403 | 503;
      body: {
        error: string;
        reason: string;
        article: string;
        consumerDid: string;
        permitId: string | null;
        odrlEnforced: true;
      };
    };
 
/**
 * The gate in front of the secure processing environment (Art. 73): the
 * query and analytics routes call it before they touch any data. A data
 * user without an approved, unexpired permit is refused with the article
 * (Art. 61(1)); the body's refusal or revocation on /compliance therefore
 * stops the next query, not only the next transfer (issue #206, M3 and M4).
 * When the caller names a dataset the check is strict on it, as it is for
 * transfers. An exempt caller passes and still gets the audit headers of
 * any permit it happens to hold.
 */
export async function gateSecondaryUse(input: {
  consumerDid: string;
  roles: string[];
  datasetId?: string | null;
  /** The word the refusal uses: "query", "analysis". */
  what: string;
  now?: Date;
}): Promise<SecondaryUseGate> {
  if (!needsPermit(input.roles)) {
    return {
      allowed: true,
      check: null,
      headers: await activePermitHeaders(input.consumerDid),
    };
  }
  let check: PermitCheck;
  try {
    check = await checkPermit({
      consumerDid: input.consumerDid,
      datasetId: input.datasetId ?? null,
      now: input.now,
    });
  } catch (err) {
    return {
      allowed: false,
      status: 503,
      body: {
        error: `The data permit register is unreachable; a ${input.what} is not allowed without it`,
        reason: err instanceof Error ? err.message : String(err),
        article: PERMIT_ARTICLE,
        consumerDid: input.consumerDid,
        permitId: null,
        odrlEnforced: true,
      },
    };
  }
  if (!check.allowed) {
    return {
      allowed: false,
      status: 403,
      body: {
        error: `No data permit covers this ${input.what}`,
        reason: check.reason,
        article: check.article,
        consumerDid: input.consumerDid,
        permitId: check.permitId,
        odrlEnforced: true,
      },
    };
  }
  return { allowed: true, check, headers: permitHeaders(check) };
}
 
const SLUG_TO_DID: Record<string, string> = {
  pharmaco: "did:web:pharmaco.de:research",
  "alpha-klinik": "did:web:alpha-klinik.de:participant",
  alphaklinik: "did:web:alpha-klinik.de:participant",
  lmc: "did:web:lmc.nl:clinic",
  medreg: "did:web:medreg.de:hdab",
  irs: "did:web:irs.fr:hdab",
};
 
/**
 * The consumer DID behind an agreement's counterparty id. EDC-V identities
 * look like "did:web:identityhub%3A7083:pharmaco"; the fixtures also carry
 * plain did:web ids. Null when nothing recognisable is there.
 */
export function didFromCounterParty(
  counterPartyId: string | null | undefined,
): string | null {
  if (!counterPartyId) return null;
  let decoded = counterPartyId;
  try {
    decoded = decodeURIComponent(counterPartyId);
  } catch {
    // keep the raw value
  }
  if (/^did:web:/i.test(decoded) && !/identityhub/i.test(decoded)) {
    return decoded;
  }
  const slug = decoded.split(":").pop()?.toLowerCase() ?? "";
  return SLUG_TO_DID[slug] ?? null;
}
 
/**
 * Record a permitted transfer in the audit graph so /admin/audit shows which
 * permit it ran under (Art. 73(1)(e)). Fire and forget: a failure here must
 * not undo a transfer the connector has already accepted.
 */
export async function recordPermittedTransfer(t: {
  transferId: string;
  contractId: string;
  assetId: string;
  consumerDid: string;
  permitId: string;
  datasetId: string | null;
  demo: boolean;
}): Promise<void> {
  try {
    await runQuery(
      `MERGE (t:DataTransfer {id: $transferId})
       SET t.status       = 'STARTED',
           t.timestamp    = toString(datetime()),
           t.transferDate = toString(date()),
           t.contractId   = $contractId,
           t.assetId      = $assetId,
           t.consumerDid  = $consumerDid,
           t.permitId     = $permitId,
           t.protocol     = $protocol,
           t.retainUntil  = toString(datetime() + duration({months: 12})),
           t.demo         = $demo
       WITH t
       OPTIONAL MATCH (consumer:Participant)
         WHERE coalesce(consumer.participantId, consumer.id) = $consumerDid
       FOREACH (_ IN CASE WHEN consumer IS NOT NULL THEN [1] ELSE [] END |
         MERGE (t)-[:TRANSFERRED_BY]->(consumer))
       WITH t
       OPTIONAL MATCH (permit:HDABApproval {approvalId: $permitId})
       FOREACH (_ IN CASE WHEN permit IS NOT NULL THEN [1] ELSE [] END |
         MERGE (t)-[:UNDER_PERMIT]->(permit))
       WITH t
       OPTIONAL MATCH (ds:HealthDataset)
         WHERE $datasetId IS NOT NULL AND coalesce(ds.datasetId, ds.id) = $datasetId
       FOREACH (_ IN CASE WHEN ds IS NOT NULL THEN [1] ELSE [] END |
         MERGE (t)-[:TRANSFERS]->(ds))`,
      // protocol is not part of the caller's shape: it is the dataspace
      // profile id the connector registers its dispatcher under, and it
      // belongs to the audit record rather than to the request (#180).
      { ...t, protocol: DSP_PROTOCOL },
    );
  } catch (err) {
    console.warn(
      "Could not record the permitted transfer in the audit graph:",
      err,
    );
  }
}