fix(02-12.1): check record context before an idempotent replay

- evaluate the fence in the wrapper above findCached, so a stale request
  neither replays a body, learns a cell exists, nor inserts a claim
- return the refusal rather than throwing: one route composes the
  wrapper outside apiHandler, where a throw escapes the envelope
- read the claim and the session's own context on one session lookup
This commit is contained in:
Marc-André Bombeck committed 2026-08-06 18:54:20 +02:00
1 parent 45fec0fc1b
commit 3a99de312e
18 files changed
+731 -128

No files matched your search

@@ -139,7 +139,7 @@ describe("the acting-account carrier is read in one place", () => {
* Who may ask "which record does this request claim" without an auth
* context in hand.
*
* `readClaimedActingAccount()` answers before any grant check has run, so a
* `readClaimedRecordContext()` answers before any grant check has run, so a
* caller that treats its answer as permission has skipped the only thing
* that grants any. Exactly one caller exists, beside the file that declares
* it: the idempotency wrapper, which uses the claim to pick a cache cell and
@@ -147,9 +147,17 @@ describe("the acting-account carrier is read in one place", () => {
* acting account has an auth context by then and goes through
* `requireRecordAuth`, which checks a live grant before returning. A second
* caller here is a design question, not a patch.
*
* The matcher names the v1.36.0 spelling (`readClaimedActingAccount`) as well
* as today's. That function was removed in v1.37.0 when the wrapper started
* needing the session's record context on the same read; matching both means
* a reintroduced narrow copy trips this leg instead of quietly becoming a
* second answer.
*/
it("the unchecked claim has exactly two consumers", () => {
const consumers = filesMatching(/readClaimedActingAccount/);
const consumers = filesMatching(
/readClaimedRecordContext|readClaimedActingAccount/,
);
expect(consumers.length).toBeGreaterThan(0);
expect(consumers).toEqual([
"lib/auth/acting-carrier.ts",
@@ -215,10 +215,32 @@ describe("the epoch has one writer and a closed reader set", () => {
"lib/api-handler.ts",
// Compares it. The one place that decides anything from it.
"lib/sharing/record-session-fence.ts",
// Reads it off the same session lookup the idempotency wrapper already
// makes, so the fence can be evaluated above the replay cache without a
// second round trip.
"lib/auth/acting-carrier.ts",
].sort(),
);
});
it("is consulted by the idempotency wrapper, above the cache", () => {
const src = read("lib/idempotency.ts");
const fence = src.indexOf("refuseStaleRecordSessionClaim(claim)");
const cache = src.indexOf("findCached(ctx)");
const claimRow = src.indexOf("claimKey(ctx)");
expect(fence).toBeGreaterThan(-1);
expect(cache).toBeGreaterThan(-1);
expect(claimRow).toBeGreaterThan(-1);
// A stale request must not learn whether a cell exists, replay a body out
// of one, or insert a claim row. The runtime proof is the zero-call
// instrument in `src/lib/__tests__/idempotency.test.ts`; this is the
// tripwire that says the line moved.
expect(fence).toBeLessThan(cache);
expect(fence).toBeLessThan(claimRow);
// And it comes from the fence module, not from a second copy of the rule.
expect(src).toContain('from "@/lib/sharing/record-session-fence"');
});
it("does not leak the raw counter into the browser's vocabulary", () => {
// The client never names the epoch as a column. It receives
// `recordSession: { epoch, scope }` and asserts it back as a header, which
+160
View File
@@ -26,6 +26,11 @@ vi.mock("@/lib/db", () => ({
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
// v1.37.0 — the record-session fence stamps the response echo on the
// request-scoped wide event. There is no event outside a request scope and
// the fence handles that with an optional call, so `undefined` is the honest
// stub rather than a fake builder.
getEvent: vi.fn(() => undefined),
}));
vi.mock("@/lib/auth/session", () => ({
@@ -674,3 +679,158 @@ describe("withIdempotency — record-scoped cells", () => {
expect(prisma.idempotencyKey.create).not.toHaveBeenCalled();
});
});
/**
* v1.37.0 — the record-session fence, above the replay cache.
*
* The property is a PLACEMENT, and a status-code assertion cannot see it: a
* wrapper that read the cell, replayed nothing, released its claim and then
* returned 409 would look identical from outside. `findCached` and `claimKey`
* are module-private, so the instrument is one layer lower and falsifiable: the
* two Prisma calls they make must receive zero calls for a refused request and
* non-zero for a passing one.
*
* The first draft of this plan proposed asserting "no row exists for the target
* cell" instead. That assertion cannot fail: `releaseClaim` deletes the pending
* row whenever the handler throws, so it would pass with the fence placed after
* `claimKey` too.
*
* Break it by moving the fence call below `findCached` in `withIdempotency`:
* the `findUnique` zero-call assertion fails.
*/
describe("the record-session fence sits above the replay cache", () => {
function fencedSession(recordEpoch: number, actingAsUserId: string | null) {
vi.mocked(getSession).mockResolvedValue({
session: {
id: "s-1",
expiresAt: new Date(Date.now() + 60_000),
actingAsUserId,
recordEpoch,
},
user: { id: "u-1" },
} as never);
}
function asserts(epoch: string | null, scope: string | null) {
vi.mocked(headers).mockResolvedValue({
get: vi.fn((name: string) => {
if (name.toLowerCase() === "x-healthlog-record-epoch") return epoch;
if (name.toLowerCase() === "x-healthlog-record-scope") return scope;
return null;
}),
} as never);
}
it("refuses a stale claim without reading or claiming a cell", async () => {
fencedSession(4, "owner-1");
asserts("3", "owner-1");
const handler = vi.fn(async () =>
NextResponse.json({ data: "ok", error: null }, { status: 201 }),
);
const wrapped = withIdempotency<[NextRequest]>(handler);
const res = await wrapped(
makeRequest("POST", { "idempotency-key": "abc-12345678" }),
);
expect(res.status).toBe(409);
expect((await res.json()).meta.errorCode).toBe("sharing.session.changed");
// The placement, stated as the only thing that can prove it.
expect(prisma.idempotencyKey.findUnique).not.toHaveBeenCalled();
expect(prisma.idempotencyKey.create).not.toHaveBeenCalled();
// And the side effect the whole wrapper exists to run once never ran.
expect(handler).not.toHaveBeenCalled();
});
it("POSITIVE CONTROL: a matching claim reads the cell and claims it", async () => {
// Without this the assertion above would pass for a wrapper that never
// touched the cache at all.
fencedSession(4, "owner-1");
asserts("4", "owner-1");
const handler = vi.fn(async () =>
NextResponse.json({ data: "ok", error: null }, { status: 201 }),
);
const wrapped = withIdempotency<[NextRequest]>(handler);
const res = await wrapped(
makeRequest("POST", { "idempotency-key": "abc-12345678" }),
);
expect(res.status).toBe(201);
expect(prisma.idempotencyKey.findUnique).toHaveBeenCalledTimes(1);
expect(prisma.idempotencyKey.create).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledTimes(1);
});
it("lets an unfenced client through to the route's own refusal", async () => {
// `unfenced-client` is deliberately NOT refused here: the route owns the
// 403 a pre-fence bundle recovers from, together with its annotation and
// audit posture. The wrapper still files the cell, because the handler is
// about to answer.
fencedSession(4, "owner-1");
asserts(null, null);
const handler = vi.fn(async () =>
NextResponse.json(
{ data: null, error: "Account access denied" },
{ status: 403 },
),
);
const wrapped = withIdempotency<[NextRequest]>(handler);
const res = await wrapped(
makeRequest("POST", { "idempotency-key": "abc-12345678" }),
);
expect(res.status).toBe(403);
expect(handler).toHaveBeenCalledTimes(1);
});
it("leaves a never-switched session byte-identical", async () => {
fencedSession(0, null);
asserts(null, null);
const handler = vi.fn(async () =>
NextResponse.json({ data: "ok", error: null }, { status: 201 }),
);
const wrapped = withIdempotency<[NextRequest]>(handler);
const res = await wrapped(
makeRequest("POST", { "idempotency-key": "abc-12345678" }),
);
expect(res.status).toBe(201);
expect(prisma.idempotencyKey.findUnique).toHaveBeenCalledTimes(1);
expect(prisma.idempotencyKey.create).toHaveBeenCalledTimes(1);
});
it("leaves the Bearer transport byte-identical", async () => {
// No session row at all, so no context to be stale about — and a fence
// header on this transport is neither read nor honoured.
vi.mocked(getSession).mockResolvedValue(null);
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
userId: "u-bearer",
revoked: false,
expiresAt: null,
} as never);
vi.mocked(headers).mockResolvedValue({
get: vi.fn((name: string) => {
if (name.toLowerCase() === "authorization")
return `Bearer hlk_${"a".repeat(64)}`;
if (name.toLowerCase() === "x-healthlog-record-epoch") return "1";
if (name.toLowerCase() === "x-healthlog-record-scope") return "owner-1";
return null;
}),
} as never);
const handler = vi.fn(async () =>
NextResponse.json({ data: "ok", error: null }, { status: 201 }),
);
const wrapped = withIdempotency<[NextRequest]>(handler);
const res = await wrapped(
makeRequest("POST", { "idempotency-key": "abc-12345678" }),
);
expect(res.status).toBe(201);
expect(prisma.idempotencyKey.findUnique).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledTimes(1);
});
});
+36 -6
View File
@@ -191,9 +191,33 @@ export async function getUnswitchedSession(): Promise<Awaited<
* unswitched own-record request. The grant check happens later, inside the
* handler, on every request.
*/
export async function readClaimedActingAccount(): Promise<
string | null | undefined
> {
/**
* v1.37.0 — and, on the same read, what that request's session actually holds.
*
* This replaced a narrower `readClaimedActingAccount()` that returned only the
* claim. The idempotency wrapper — still the one caller — now needs a second
* fact: the session's own record context, so the record-session fence can be
* evaluated above the replay cache. Widening the existing function rather than
* adding a second one is what keeps that from costing a second `getSession()`
* on every idempotent write, and keeps "what does this request say it is acting
* as" to one implementation, which is the thing this file exists to ensure.
*
* The narrow function is gone rather than kept as a shim: it had no caller left,
* and a wrapper nobody calls is a second answer waiting for somebody to reach
* for it.
*/
export interface ClaimedRecordContext {
/** The claimed record, or `undefined` when the carrier was unsafe to resolve. */
claimedRecord: string | null | undefined;
/** Which credential the request authenticated with. */
transport: "cookie" | "bearer";
/** The session's selector-move counter. Always 0 on the Bearer transport. */
sessionEpoch: number;
/** The account the session is pointed at, or null. Always null on Bearer. */
sessionScope: string | null;
}
export async function readClaimedRecordContext(): Promise<ClaimedRecordContext> {
const header = await readSelectorHeader();
let session: Awaited<ReturnType<typeof getSession>> = null;
try {
@@ -204,11 +228,17 @@ export async function readClaimedActingAccount(): Promise<
// unauthenticated request claims nothing.
session = null;
}
const transport: "cookie" | "bearer" = session ? "cookie" : "bearer";
const carrier = decideActingCarrier({
transport: session ? "cookie" : "bearer",
transport,
stamped: session?.session.actingAsUserId ?? null,
header,
});
if (carrier.kind === "misplaced-header") return undefined;
return carrierTarget(carrier);
return {
claimedRecord:
carrier.kind === "misplaced-header" ? undefined : carrierTarget(carrier),
transport,
sessionEpoch: session?.session.recordEpoch ?? 0,
sessionScope: session?.session.actingAsUserId ?? null,
};
}
+25 -3
View File
@@ -18,9 +18,10 @@ import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
import {
readClaimedActingAccount,
readClaimedRecordContext,
selectorNamesAnAccount,
} from "@/lib/auth/acting-carrier";
import { refuseStaleRecordSessionClaim } from "@/lib/sharing/record-session-fence";
import { hashToken } from "@/lib/auth/hmac";
import { annotate } from "@/lib/logging/context";
import { isP2002 } from "@/lib/prisma-errors";
@@ -327,7 +328,7 @@ export function isCachableStatus(status: number): boolean {
* the handler again and creating duplicate measurements (audit C-4).
*
* It resolves the CALLER and only the caller — which record they are aiming at
* is a separate question, answered by `readClaimedActingAccount()` above and
* is a separate question, answered by `readClaimedRecordContext()` above and
* folded into the key. Neither answer authorises anything: the handler runs
* its own `requireAuth()` / `requireRecordAuth()` either way.
*
@@ -456,7 +457,28 @@ export function withIdempotency<
// A claim only chooses the cache cell. It never carries authority: a
// completed delegated cell is checked against the current grant again
// immediately before its body can be returned below.
const claimedRecord = await readClaimedActingAccount();
const claim = await readClaimedRecordContext();
// v1.37.0 — the record-session fence, evaluated HERE and not one line
// lower. A stale request must not learn whether a cell exists, must not
// replay a body out of one, and must not insert a claim row — so the
// verdict sits above `findCached` and above the two carrier arms below,
// which choose the cell. It is the second, independent evaluation of the
// same client assertion (the handler's own `requireRecordAuth` is the
// other) and nothing is carried between them; see the note on
// `refuseStaleRecordSessionClaim`.
//
// Only `stale` refuses here. An `unfenced-client` verdict falls through so
// the route issues the 403 a pre-fence bundle already recovers from, with
// the annotation and audit posture that belong to the route.
//
// A never-switched session and every Bearer request are untouched: both
// pass the verdict without a header, which is what keeps every existing
// own-record and delegated-cell contract byte-identical.
const staleContext = await refuseStaleRecordSessionClaim(claim);
if (staleContext) return staleContext;
const claimedRecord = claim.claimedRecord;
if (claimedRecord === undefined) {
// The carrier cannot safely name a record. In particular, a selector on
// a cookie request is a misplaced claim, not an own-record request.
+71 -17
View File
@@ -40,9 +40,11 @@
* discards a response whose echoed context contradicts the one it is now on.
*/
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import {
RECORD_EPOCH_HEADER,
RECORD_FENCE_ERROR_CODE,
RECORD_SCOPE_HEADER,
parseAssertedContext,
recordScopeHeaderValue,
@@ -143,23 +145,10 @@ export function recordSessionForPayload(
export async function assertRecordSessionFence(
auth: AuthContext,
): Promise<void> {
const transport = auth.authMethod === "bearer" ? "bearer" : "cookie";
const sessionEpoch = auth.session.recordEpoch ?? 0;
const sessionScope = auth.session.actingAsUserId ?? null;
// Stamped before the verdict, so a refusal echoes the truth too. The Bearer
// transport carries no session context to echo and gets none: the frozen
// native contract sends no fence header and receives none back.
if (transport === "cookie") {
getEvent()?.setRecordContext({ epoch: sessionEpoch, scope: sessionScope });
}
const asserted = await readAssertedRecordContext();
const verdict = recordSessionFenceVerdict({
transport,
sessionEpoch,
sessionScope,
asserted,
const verdict = await decide({
transport: auth.authMethod === "bearer" ? "bearer" : "cookie",
sessionEpoch: auth.session.recordEpoch ?? 0,
sessionScope: auth.session.actingAsUserId ?? null,
});
if (verdict === "pass") return;
@@ -183,3 +172,68 @@ export async function assertRecordSessionFence(
annotate({ meta: { sharing_refusal: "unfenced_client" } });
throw new SharingAccessDeniedError();
}
/**
* The same verdict, for the idempotency wrapper, returning bytes instead of
* throwing.
*
* `withIdempotency` is composed OUTSIDE `apiHandler` on at least one route
* (`POST /api/admin/backups/[id]/restore`), so a throw from the wrapper would
* escape the envelope and become a 500 rather than the documented refusal. It
* therefore returns a response, hand-built to the same
* `{ data, error, meta.errorCode }` shape `apiHandler`'s `SharingAuthError` arm
* emits, so a client cannot tell which layer refused it.
*
* Only the `stale` arm produces a response. `unfenced-client` deliberately
* falls through to the handler, whose `requireRecordAuth` issues the 403 a
* pre-fence bundle recovers from — along with the wide-event annotation and the
* audit posture that belong to the route, not to a cache wrapper.
*
* This is the SECOND, INDEPENDENT evaluation of the fence on such a request,
* and its result is deliberately NOT carried into the handler's own. Carrying
* it would need request-scoped mutable state shared across the wrapper/handler
* boundary, which is a second source of truth for the same question. Two
* independent evaluations against the same client assertion are sufficient: a
* switch landing between the two fails the second, so no handler body runs
* under a scope the asserted epoch does not imply.
*/
export async function refuseStaleRecordSessionClaim(
claim: RecordSessionInputs,
): Promise<Response | null> {
const verdict = await decide(claim);
if (verdict !== "stale") return null;
annotate({ meta: { sharing_refusal: "record_context_stale_idempotent" } });
return NextResponse.json(
{
data: null,
error: "The record this session is on has changed",
meta: { errorCode: RECORD_FENCE_ERROR_CODE },
},
{ status: 409 },
);
}
/** What the fence needs to know about the session, from either caller. */
interface RecordSessionInputs {
transport: "cookie" | "bearer";
sessionEpoch: number;
sessionScope: string | null;
}
/** Stamp the echo and read the verdict. The one place either happens. */
async function decide(input: RecordSessionInputs) {
// Stamped before the verdict, so a refusal echoes the truth too. The Bearer
// transport carries no session context to echo and gets none: the frozen
// native contract sends no fence header and receives none back.
if (input.transport === "cookie") {
getEvent()?.setRecordContext({
epoch: input.sessionEpoch,
scope: input.sessionScope,
});
}
return recordSessionFenceVerdict({
...input,
asserted: await readAssertedRecordContext(),
});
}