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 | 2x 17x 17x 17x 1x 16x 1x 15x 14x 14x 14x 14x 1x 13x 2x 2x 2x 2x 15x 15x 15x 14x 9x 9x 2x 7x 17x 17x 15x 15x 15x 5x 3x 10x 3x 4x 4x 3x 1x 3x 9x 9x 9x 3x 9x 6x 6x 6x 2x 2x 2x 4x 14x 14x 13x 13x 13x 13x 4x 9x 9x 3x 6x 6x 6x 6x 4x 2x 2x | import { getServerSession } from "next-auth/next";
import { NextRequest, NextResponse } from "next/server";
import { edcClient, EDC_CONTEXT } from "@/lib/edc";
import { promises as fs } from "fs";
import path from "path";
import { authOptions } from "@/lib/auth";
/**
* Policies are visible to both EDC_ADMIN (dataspace operator) and
* HDAB_AUTHORITY (regulator inspecting EHDS Art. 46 ODRL terms attached to
* data permits). Mutations are kept admin-only via the per-method guard
* below.
*/
async function requirePoliciesRead(): Promise<NextResponse | null> {
const session = await getServerSession(authOptions);
const roles = (session as { roles?: string[] } | null)?.roles ?? [];
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (!roles.includes("EDC_ADMIN") && !roles.includes("HDAB_AUTHORITY")) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return null;
}
async function requirePoliciesWrite(): Promise<NextResponse | null> {
const session = await getServerSession(authOptions);
const roles = (session as { roles?: string[] } | null)?.roles ?? [];
Iif (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (!roles.includes("EDC_ADMIN")) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return null;
}
export const dynamic = "force-dynamic";
// ── Neo4j fallback helpers ─────────────────────────────────────────────────
const NEO4J_URL =
process.env.NEO4J_BOLT_URL || "bolt://health-dataspace-neo4j:7687";
const NEO4J_USER = process.env.NEO4J_USER || "neo4j";
const NEO4J_PASSWORD = process.env.NEO4J_PASSWORD || "healthdataspace";
async function neo4jCypher(
query: string,
parameters: Record<string, unknown> = {},
) {
const httpUrl = NEO4J_URL.replace("bolt://", "http://").replace(
":7687",
":7474",
);
const txUrl = `${httpUrl}/db/neo4j/tx/commit`;
const res = await fetch(txUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization:
"Basic " +
Buffer.from(`${NEO4J_USER}:${NEO4J_PASSWORD}`).toString("base64"),
},
body: JSON.stringify({ statements: [{ statement: query, parameters }] }),
});
if (!res.ok) throw new Error(`Neo4j HTTP API error: ${res.status}`);
const data = await res.json();
if (data.errors?.length > 0) {
throw new Error(`Cypher error: ${JSON.stringify(data.errors)}`);
}
return data.results;
}
/**
* GET /api/admin/policies?participantId=xxx — List policy definitions.
* Attempts EDC-V management API first; falls back to Neo4j if offline.
*/
export async function GET(request: NextRequest) {
const authError = await requirePoliciesRead();
if (authError) return authError;
const participantId = request.nextUrl.searchParams.get("participantId");
try {
if (participantId) {
const policies = await edcClient.management(
`/v5alpha/participants/${participantId}/policydefinitions/request`,
"POST",
{
"@context": [EDC_CONTEXT],
"@type": "QuerySpec",
filterExpression: [],
},
);
return NextResponse.json({ participantId, policies, source: "edc" });
}
const participants = await edcClient.management<
{ "@id": string; identity: string }[]
>("/v5alpha/participants");
const allPolicies = await Promise.all(
participants.map(async (p) => {
try {
const policies = await edcClient.management(
`/v5alpha/participants/${p["@id"]}/policydefinitions/request`,
"POST",
{
"@context": [EDC_CONTEXT],
"@type": "QuerySpec",
filterExpression: [],
},
);
return {
participantId: p["@id"],
identity: p.identity,
policies,
source: "edc",
};
} catch {
return {
participantId: p["@id"],
identity: p.identity,
policies: [],
error: "Failed to fetch policies",
};
}
}),
);
return NextResponse.json({ participants: allPolicies });
} catch {
// EDC-V is offline — read from Neo4j local registry
console.warn("EDC-V offline, reading policies from Neo4j");
try {
const rows = await neo4jCypher(
`MATCH (pol:OdrlPolicy)
${participantId ? "WHERE pol.participantId = $participantId" : ""}
OPTIONAL MATCH (pol)-[:BELONGS_TO]->(p:Participant)
RETURN pol { .*, participantName: p.name } AS policy
ORDER BY pol.createdAt DESC`,
participantId ? { participantId } : {},
);
const policies =
rows[0]?.data?.map((r: { row: unknown[] }) => r.row[0]) || [];
return NextResponse.json({ policies, source: "neo4j", offline: true });
} catch (neo4jErr) {
// Fall back to bundled mock data so the UI works offline
try {
const mockPath = path.join(
process.cwd(),
"public",
"mock",
"admin_policies.json",
);
const raw = await fs.readFile(mockPath, "utf-8");
const mock = JSON.parse(raw);
console.warn("EDC-V + Neo4j offline — serving mock policies");
return NextResponse.json(mock);
} catch {
// Mock file not available either
}
return NextResponse.json(
{ error: "Failed to list policies", detail: String(neo4jErr) },
{ status: 502 },
);
}
}
}
/**
* POST /api/admin/policies — Create a policy definition.
* Body: { participantId, policy: { ... } }
* Attempts EDC-V first; on failure stores the policy in Neo4j as OdrlPolicy node.
*/
export async function POST(request: NextRequest) {
const authError = await requirePoliciesWrite();
if (authError) return authError;
try {
const body = await request.json();
const { participantId, policy } = body;
if (!participantId || !policy) {
return NextResponse.json(
{ error: "participantId and policy are required" },
{ status: 400 },
);
}
try {
// Attempt EDC-V management API
const result = await edcClient.management(
`/v5alpha/participants/${participantId}/policydefinitions`,
"POST",
{ "@context": [EDC_CONTEXT], ...policy },
);
return NextResponse.json(result, { status: 201 });
} catch (edcErr) {
// EDC-V offline — persist policy in Neo4j local registry
console.warn(
"EDC-V offline, persisting policy in Neo4j local registry:",
edcErr,
);
const policyId =
(policy["@id"] as string) ||
(policy.id as string) ||
`policy:local:${Date.now()}`;
const now = new Date().toISOString();
await neo4jCypher(
`MERGE (pol:OdrlPolicy {id: $policyId})
SET pol.participantId = $participantId,
pol.policyJson = $policyJson,
pol.createdAt = $createdAt,
pol.source = 'local-registry'
WITH pol
OPTIONAL MATCH (p:Participant {participantId: $participantId})
FOREACH (_ IN CASE WHEN p IS NOT NULL THEN [1] ELSE [] END |
MERGE (pol)-[:BELONGS_TO]->(p)
)`,
{
policyId,
participantId,
policyJson: JSON.stringify(policy),
createdAt: now,
},
);
return NextResponse.json(
{
"@id": policyId,
source: "neo4j",
offline: true,
message:
"Policy saved to local Neo4j registry (EDC-V management API is offline)",
},
{ status: 201 },
);
}
} catch (err) {
console.error("Failed to create policy:", err);
return NextResponse.json(
{ error: "Failed to create policy" },
{ status: 502 },
);
}
}
/**
* PUT /api/admin/policies — Update an existing policy definition.
* Body: { participantId, policyId, policy: { ... } }
*/
export async function PUT(request: NextRequest) {
const authError = await requirePoliciesWrite();
if (authError) return authError;
try {
const body = await request.json();
const { participantId, policyId, policy } = body;
if (!participantId || !policy) {
return NextResponse.json(
{ error: "participantId and policy are required" },
{ status: 400 },
);
}
try {
// EDC-V: delete old + create new (no PATCH in EDC-V Management API)
if (policyId) {
await edcClient.management(
`/v5alpha/participants/${participantId}/policydefinitions/${policyId}`,
"DELETE",
);
}
const result = await edcClient.management(
`/v5alpha/participants/${participantId}/policydefinitions`,
"POST",
{ "@context": [EDC_CONTEXT], ...policy },
);
return NextResponse.json(result);
} catch {
// EDC-V offline — update in Neo4j
console.warn("EDC-V offline, updating policy in Neo4j local registry");
const newPolicyId =
(policy["@id"] as string) || policyId || `policy:local:${Date.now()}`;
const now = new Date().toISOString();
await neo4jCypher(
`MERGE (pol:OdrlPolicy {id: $policyId})
SET pol.participantId = $participantId,
pol.policyJson = $policyJson,
pol.updatedAt = $updatedAt,
pol.source = 'local-registry'`,
{
policyId: newPolicyId,
participantId,
policyJson: JSON.stringify(policy),
updatedAt: now,
},
);
return NextResponse.json({
"@id": newPolicyId,
source: "neo4j",
offline: true,
});
}
} catch (err) {
console.error("Failed to update policy:", err);
return NextResponse.json(
{ error: "Failed to update policy" },
{ status: 502 },
);
}
}
/**
* DELETE /api/admin/policies — Remove a policy definition.
* Body: { participantId, policyId }
*/
export async function DELETE(request: NextRequest) {
const authError = await requirePoliciesWrite();
if (authError) return authError;
try {
const body = await request.json();
const { participantId, policyId } = body;
if (!participantId || !policyId) {
return NextResponse.json(
{ error: "participantId and policyId are required" },
{ status: 400 },
);
}
try {
await edcClient.management(
`/v5alpha/participants/${participantId}/policydefinitions/${policyId}`,
"DELETE",
);
return NextResponse.json({ deleted: policyId });
} catch {
// EDC-V offline — delete from Neo4j
console.warn("EDC-V offline, deleting policy from Neo4j local registry");
await neo4jCypher(
`MATCH (pol:OdrlPolicy {id: $policyId})
DETACH DELETE pol`,
{ policyId },
);
return NextResponse.json({
deleted: policyId,
source: "neo4j",
offline: true,
});
}
} catch (err) {
console.error("Failed to delete policy:", err);
return NextResponse.json(
{ error: "Failed to delete policy" },
{ status: 502 },
);
}
}
|