All files / src/app/api/nlq route.ts

88.23% Statements 30/34
62.96% Branches 17/27
100% Functions 2/2
93.33% Lines 28/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                7x     8x 8x   8x 8x     8x 8x               8x           8x 1x         7x 1x 1x   6x       6x                               5x       5x 1x 1x   4x   1x 1x         1x 1x   1x 1x 1x 1x              
import { NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { resolveOdrlScope, userToParticipantId } from "@/lib/odrl-engine";
import { gateSecondaryUse } from "@/lib/permit-gate";
import { NEO4J_PROXY_URL, callerHeaders, loadTestHeaders } from "@/lib/proxy";
import { seesPatientIdentity } from "@/lib/patient-identity";
import { speColdStartGate } from "@/lib/spe-power";
 
export const dynamic = "force-dynamic";
 
export async function POST(request: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    const body = await request.json();
 
    // Resolve caller's ODRL scope and forward to neo4j-proxy
    const { session } = auth;
    const participantId = userToParticipantId(
      session.user.email ?? session.user.name ?? session.user.id,
      session.roles,
    );
    // Art. 61(1): a data user queries the secure processing environment only
    // under a data permit. The access body's refusal or revocation stops the
    // query here, with the article (issue #206, M3). A dataset named in the
    // body is checked strictly, as for a transfer.
    const gate = await gateSecondaryUse({
      consumerDid: participantId,
      roles: session.roles,
      datasetId: typeof body.datasetId === "string" ? body.datasetId : null,
      what: "query",
    });
    if (!gate.allowed) {
      return NextResponse.json(gate.body, { status: gate.status });
    }
    // A federated question asks every SPE workspace; a stopped one is
    // started (when the caller may) and the caller told to come back
    // (ADR-072). Without `federated` the hub graph answers, no workspace.
    if (body.federated === true) {
      const coldStart = await speColdStartGate(session.roles);
      Eif (coldStart) return coldStart;
    }
    const odrlScope = await resolveOdrlScope(participantId);
 
    // The proxy records the query as a TransferEvent; the gate's headers give
    // the record its permit, dataset and purpose.
    const resp = await fetch(`${NEO4J_PROXY_URL}/nlq`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Participant": participantId,
        // Whether this caller may see who a patient is (#475). The proxy
        // refuses any query that would show it unless this says "shown".
        "X-Patient-Identity": seesPatientIdentity(session.roles)
          ? "shown"
          : "withheld",
        ...gate.headers,
        ...loadTestHeaders(request),
        ...callerHeaders(session),
      },
      body: JSON.stringify({ ...body, odrlScope }),
    });
    const data = await resp.json();
    // A template that asks every SPE (spe_access) goes federated in the
    // proxy without the flag; when that failed, a stopped workspace is the
    // likely cause, and the caller gets the cold-start answer instead.
    if (resp.status >= 500 && body.federated !== true) {
      const coldStart = await speColdStartGate(session.roles);
      Eif (coldStart) return coldStart;
    }
    return NextResponse.json(data, { status: resp.status });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "NLQ proxy error";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}
 
export async function GET() {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    const resp = await fetch(`${NEO4J_PROXY_URL}/nlq/templates`);
    const data = await resp.json();
    return NextResponse.json(data);
  } catch (err: unknown) {
    const message =
      err instanceof Error ? err.message : "NLQ templates proxy error";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}