Gate the FHIR REST face on the doctorReport module

/api/fhir/* serves the same whole-record aggregate as
/api/export/health-record -- right down to the decrypted insurance number
on the Patient resource -- but never consulted the module gate. The
export refuses with a 403 module.disabled envelope when the account turns
the doctor-report module off; the FHIR face happily returned the full
Bundle to the same token.

Gate all five data routes (Patient, Observation, MedicationStatement,
MedicationAdministration, $everything). Refuse rather than omit: a
whole-record export has no truthful partial answer, and unlike the sync
delta feed no background client depends on it draining to stay
consistent. The refusal reuses the shared module.disabled envelope so the
errorCode clients already branch on stays the same.

loadFhirContext gains a fail-closed assertion as a second layer. It is
the one door to the aggregate, so it refuses outright instead of trusting
that every future caller remembers its gate; reaching it means a route is
missing one, which is a bug to surface rather than a flow to serve.

The static CapabilityStatement at /api/fhir/metadata stays open -- server
metadata, no user data.
This commit is contained in:
Marc-André Bombeck committed 2026-07-19 01:39:58 +02:00
1 parent 076339c274
commit 4548df84bf
9 files changed
+368

No files matched your search

@@ -0,0 +1,83 @@
/**
* `loadFhirContext` — doctorReport module backstop.
*
* The loader is the one door to the whole-record aggregate the FHIR face
* serves, including the decrypted insurance number. Every `/api/fhir/*` data
* route carries its own `requireModuleEnabled` gate (that is what produces the
* clean 403); this test pins the SECOND layer — the loader refuses outright
* rather than trusting that every present and future caller remembered.
*
* The gate resolver is exercised for real; only its data sources are stubbed.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: vi.fn() },
cycleProfile: { findUnique: vi.fn() },
},
}));
vi.mock("@/lib/modules/operator-availability", async (importOriginal) => {
const actual =
await importOriginal<
typeof import("@/lib/modules/operator-availability")
>();
return { ...actual, getOperatorModuleAvailability: vi.fn() };
});
vi.mock("@/lib/doctor-report-data", () => ({
collectDoctorReportData: vi.fn(),
normaliseDateRange: vi.fn(() => ({ from: new Date(0), to: new Date() })),
}));
vi.mock("@/lib/crypto", () => ({ decrypt: vi.fn(() => "A123456789") }));
import { loadFhirContext } from "@/lib/fhir/rest";
import { MODULE_KEYS } from "@/lib/modules/gate";
import { getOperatorModuleAvailability } from "@/lib/modules/operator-availability";
import { collectDoctorReportData } from "@/lib/doctor-report-data";
import { prisma } from "@/lib/db";
function setDoctorReportModule(enabled: boolean): void {
vi.mocked(prisma.user.findUnique).mockImplementation((async (args: {
select?: Record<string, boolean>;
}) => {
// The gate's own read and the loader's identity read hit the same model.
if (args?.select?.modulePreferencesJson) {
return {
gender: null,
disableCoach: false,
modulePreferencesJson: enabled ? {} : { doctorReport: false },
};
}
return { insuranceNumberEncrypted: "cipher", locale: "de" };
}) as never);
vi.mocked(prisma.cycleProfile.findUnique).mockResolvedValue(null as never);
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getOperatorModuleAvailability).mockResolvedValue(
Object.fromEntries(MODULE_KEYS.map((k) => [k, true])) as never,
);
vi.mocked(collectDoctorReportData).mockResolvedValue({} as never);
});
describe("loadFhirContext — doctorReport backstop", () => {
it("refuses to assemble the record when the module is off", async () => {
setDoctorReportModule(false);
await expect(loadFhirContext("user-1")).rejects.toThrow(
/doctorReport.*disabled/,
);
// Nothing was aggregated and nothing was decrypted.
expect(collectDoctorReportData).not.toHaveBeenCalled();
});
it("assembles the record when the module is on", async () => {
setDoctorReportModule(true);
const ctx = await loadFhirContext("user-1");
expect(collectDoctorReportData).toHaveBeenCalledTimes(1);
expect(ctx.identity.insuranceNumber).toBe("A123456789");
});
});
+17
View File
@@ -22,6 +22,7 @@ import {
type DoctorReportData,
} from "@/lib/doctor-report-data";
import { GERMAN_ATC_DEFAULT_LOCALES } from "@/lib/fhir/resources";
import { isModuleEnabled } from "@/lib/modules/gate";
import type {
FhirBundleEntry,
FhirBundleLink,
@@ -182,12 +183,28 @@ export function operationOutcome(
* The window matches the document export's default (`normaliseDateRange`
* with no override). KVNR decryption is fail-soft: a key-rotation gap on a
* single row omits the identifier rather than 500-ing the read.
*
* MODULE BACKSTOP. Every `/api/fhir/*` data route calls
* `requireModuleEnabled(userId, "doctorReport")` itself, which is what
* produces the clean 403 envelope. This assertion is the second layer: the
* loader is the one door to the whole-record aggregate (including the
* decrypted insurance number), so it refuses outright rather than trusting
* that every present and future caller remembered the gate. It throws
* instead of returning an envelope because reaching it means a caller is
* missing its gate — a bug to surface, not a flow to serve.
*/
export async function loadFhirContext(userId: string): Promise<{
data: DoctorReportData;
identity: { insuranceNumber: string | null };
germanAtc: boolean;
}> {
if (!(await isModuleEnabled(userId, "doctorReport"))) {
throw new Error(
'loadFhirContext called with the "doctorReport" module disabled — ' +
"the calling route is missing its requireModuleEnabled gate",
);
}
const range = normaliseDateRange(undefined);
const [data, userRow] = await Promise.all([
collectDoctorReportData(userId, range, {}),