All files / src/lib odrl-engine.ts

97.36% Statements 37/38
88.88% Branches 16/18
100% Functions 2/2
96.66% Lines 29/30

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    4x                                   4x                                     10x         4x                                                                             10x       10x   10x                                                     9x 3x                           6x 6x 6x 6x 6x 6x 6x 6x   6x 9x 9x 9x 9x 9x 9x 9x 9x     6x                       1x 1x                          
import { runQuery } from "@/lib/neo4j";
 
const IS_STATIC = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
 
/* ── Types ─────────────────────────────────────────────────────── */
 
export interface OdrlScope {
  participantId: string;
  participantName: string;
  permissions: string[];
  prohibitions: string[];
  accessibleDatasets: string[];
  temporalLimit: string | null;
  policyIds: string[];
  hasActiveContract: boolean;
  hdabApproved: boolean;
}
 
/* ── Participant mapping ───────────────────────────────────────── */
 
const USERNAME_TO_DID: Record<string, string> = {
  "admin@edc.demo": "did:web:alpha-klinik.de:participant",
  "dr.schmidt@alphaklinik.de": "did:web:alpha-klinik.de:participant",
  "nurse.weber@alphaklinik.de": "did:web:alpha-klinik.de:participant",
  "researcher@pharmaco.de": "did:web:pharmaco.de:research",
  "hdab.officer@medreg.de": "did:web:medreg.de:hdab",
  "dr.janssen@lmc.nl": "did:web:lmc.nl:clinic",
  "patient.mueller@demo.ehds": "did:web:alpha-klinik.de:participant",
  "tc.operator@medreg.de": "did:web:medreg.de:hdab",
};
 
/**
 * Map a session username + roles to the corresponding participant DID.
 * Falls back to a generic participant DID if no mapping exists.
 */
export function userToParticipantId(
  username: string,
  _roles: string[],
): string {
  return USERNAME_TO_DID[username] ?? `did:web:unknown:${username}`;
}
 
/* ── Static fallback ───────────────────────────────────────────── */
 
const STATIC_SCOPE: OdrlScope = {
  participantId: "did:web:pharmaco.de:research",
  participantName: "PharmaCo Research AG",
  permissions: [
    "scientific_research",
    "statistics",
    "policy_support",
    "education",
    "ai_training",
  ],
  prohibitions: [
    "re_identification",
    "commercial_exploitation_without_approval",
  ],
  accessibleDatasets: [
    "dataset-synthea-fhir-r4-2026",
    "dataset-synthea-omop-2026",
  ],
  temporalLimit: "2027-12-31T23:59:59",
  policyIds: ["policy-ehds-art53-synthetic-2026"],
  hasActiveContract: true,
  hdabApproved: true,
};
 
/* ── Core resolver ─────────────────────────────────────────────── */
 
/**
 * Resolve the effective ODRL scope for a participant.
 *
 * Walks the Neo4j graph:
 *   Participant → Contract → DataProduct → GOVERNED_BY → OdrlPolicy
 *   HDABApproval → GRANTS_ACCESS_TO → HealthDataset
 *
 * Returns the union of all permissions, prohibitions, and accessible
 * datasets for the caller's active contracts.
 */
export async function resolveOdrlScope(
  participantId: string,
): Promise<OdrlScope> {
  Iif (IS_STATIC) {
    return STATIC_SCOPE;
  }
 
  try {
    // Query the ODRL policy chain for this participant
    const rows = await runQuery<{
      participantName: string;
      policyId: string;
      permissions: string[];
      prohibitions: string[];
      temporalLimit: string | null;
      datasetId: string | null;
      contractStatus: string | null;
      approvalStatus: string | null;
    }>(
      `MATCH (p:Participant)
       WHERE p.participantId = $participantId
          OR p.did = $participantId
       OPTIONAL MATCH (p)-[:OFFERS|CONSUMES]->(:DataProduct)-[:GOVERNED_BY]->(pol:OdrlPolicy)
       OPTIONAL MATCH (p)-[:HAS_CONTRACT]->(c:Contract)-[:COVERS|GOVERNS]->(:DataProduct)-[:DESCRIBED_BY]->(ds:HealthDataset)
       OPTIONAL MATCH (approval:HDABApproval)-[:GRANTS_ACCESS_TO]->(ds)
       RETURN p.name AS participantName,
              pol.policyId AS policyId,
              coalesce(pol.ehdsPermissions, []) AS permissions,
              coalesce(pol.ehdsProhibitions, []) AS prohibitions,
              toString(pol.temporalLimit) AS temporalLimit,
              coalesce(ds.datasetId, ds.id) AS datasetId,
              c.status AS contractStatus,
              approval.status AS approvalStatus`,
      { participantId },
    );
 
    if (rows.length === 0) {
      return {
        participantId,
        participantName: participantId,
        permissions: [],
        prohibitions: [],
        accessibleDatasets: [],
        temporalLimit: null,
        policyIds: [],
        hasActiveContract: false,
        hdabApproved: false,
      };
    }
 
    // Aggregate across all matching rows
    const permissionSet = new Set<string>();
    const prohibitionSet = new Set<string>();
    const datasetSet = new Set<string>();
    const policySet = new Set<string>();
    let temporalLimit: string | null = null;
    let hasActiveContract = false;
    let hdabApproved = false;
    let participantName = participantId;
 
    for (const row of rows) {
      Eif (row.participantName) participantName = row.participantName;
      if (row.policyId) policySet.add(row.policyId);
      for (const p of row.permissions) permissionSet.add(p);
      for (const p of row.prohibitions) prohibitionSet.add(p);
      if (row.datasetId) datasetSet.add(row.datasetId);
      if (row.temporalLimit) temporalLimit = row.temporalLimit;
      if (row.contractStatus === "ACTIVE") hasActiveContract = true;
      if (row.approvalStatus === "approved") hdabApproved = true;
    }
 
    return {
      participantId,
      participantName,
      permissions: [...permissionSet],
      prohibitions: [...prohibitionSet],
      accessibleDatasets: [...datasetSet],
      temporalLimit,
      policyIds: [...policySet],
      hasActiveContract,
      hdabApproved,
    };
  } catch (err) {
    console.error("resolveOdrlScope error:", err);
    return {
      participantId,
      participantName: participantId,
      permissions: [],
      prohibitions: [],
      accessibleDatasets: [],
      temporalLimit: null,
      policyIds: [],
      hasActiveContract: false,
      hdabApproved: false,
    };
  }
}