fix(medications): scope the intake idempotency key to its owner

`medication_intake_events.idempotency_key` carried a GLOBAL unique from
0001_init. The value is client-supplied, so two people running the same
client can mint the same key — and on a global unique the second one is
simply refused by the constraint. Their dose is not written and nothing
tells them so. The bulk drain made it worse: its replay probe read the
key with no user scope, resolved the first user's row, and reported the
second user's entry as a duplicate carrying a stranger's row id.

Migration 0273 replaces the global unique with `(user_id,
idempotency_key)`, the grain every other client-supplied identity on the
table already uses. Both unscoped reads in the bulk drain now key on the
composite; the other four reads were already narrowed by user.

On existing data this is a relaxation, so nothing needs reconciling: the
old constraint is strictly stronger than the new one, and no pair of rows
can violate an index the previous one already forbade. The migration
still carries a reconciliation step for a database whose global index was
dropped by hand at some point. It never deletes or rewrites a dose — it
clears the dedup HINT on the later row of a colliding pair and keeps
every intake event, timestamp, attribution and inventory stamp intact.
The new index is created before the old one is dropped, so a failure
aborts with the old protection still in place.

A structural guard freezes the read side: no `medicationIntakeEvent`
query may filter on the key without narrowing by `userId`.
This commit is contained in:
Marc-André Bombeck committed 2026-07-25 18:41:40 +02:00
1 parent 15b5f6f92f
commit 18691d4550
5 files changed
+428 -3

No files matched your search

@@ -298,6 +298,82 @@ describe("identities derived outside a Zod schema stay inside the floor", () =>
});
});
describe("the intake idempotency key is never read across users", () => {
/**
* `medication_intake_events.idempotency_key` carried a GLOBAL unique
* from 0001_init until migration 0273. Client-supplied keys on a global
* unique meant one user's key blocked another user's write outright,
* and an unscoped lookup resolved a stranger's row and handed back its
* id. The column is now unique per user; every read has to key on
* `(userId, idempotencyKey)` or the leak comes straight back.
*/
function intakeQueriesFilteringOnTheKey(): Array<{
file: string;
line: number;
scoped: boolean;
}> {
const out: Array<{ file: string; line: number; scoped: boolean }> = [];
for (const rel of sourceFiles()) {
const source = read(rel);
if (!source.includes("medicationIntakeEvent.")) continue;
const call = /medicationIntakeEvent\.(\w+)\(\s*\{/g;
let m: RegExpExecArray | null;
while ((m = call.exec(source)) !== null) {
// Walk to the matching brace so the window is the call, not a
// fixed slice that could bleed into the next statement.
let depth = 0;
let j = source.indexOf("{", m.index);
for (; j < source.length; j++) {
if (source[j] === "{") depth++;
else if (source[j] === "}" && --depth === 0) break;
}
const body = source.slice(m.index, j + 1);
const whereAt = body.indexOf("where");
if (whereAt === -1) continue;
const where = body.slice(whereAt, whereAt + 400);
if (!where.includes("idempotencyKey")) continue;
out.push({
file: rel,
line: source.slice(0, m.index).split("\n").length,
// Keyed on the row's own primary id is scoped by construction —
// that is an update-by-id that happens to WRITE the key.
scoped: where.includes("userId") || /where:\s*\{\s*id:/.test(where),
});
}
}
return out;
}
it("finds the reads at all (the matcher still matches)", () => {
const found = intakeQueriesFilteringOnTheKey();
expect(found.length).toBeGreaterThanOrEqual(6);
expect(found.map((f) => f.file)).toContain(
"app/api/medications/intake/bulk/route.ts",
);
});
it("every query filtering on the key also narrows by userId", () => {
const unscoped = intakeQueriesFilteringOnTheKey().filter((f) => !f.scoped);
expect(
unscoped,
"a medicationIntakeEvent query filters on idempotencyKey without a userId. " +
"The key is client-supplied and unique per USER (migration 0273); an " +
"unscoped read resolves another user's row.",
).toEqual([]);
});
it("the schema keeps the key unique per user, not globally", () => {
const schema = readFileSync(
join(process.cwd(), "prisma", "schema.prisma"),
"utf8",
);
expect(schema).toContain("@@unique([userId, idempotencyKey])");
expect(schema).not.toMatch(
/idempotencyKey\s+String\?\s+@unique\s+@map\("idempotency_key"\)/,
);
});
});
describe("the batch surfaces refuse per entry, never whole-batch", () => {
// Each of these drains a client sync queue. A schema-level refusal here
// would stop a whole batch of good rows because of one bad one, which is
+15 -2
View File
@@ -616,8 +616,16 @@ async function postBulk(request: NextRequest): Promise<Response> {
// by `source`. The partial unique index carries `source`, so it
// cannot catch this duplicate; the probe must.
if (entry.idempotencyKey) {
// Scoped to the caller. The key is client-supplied, so an
// unscoped read would resolve another user's row and hand its
// id back here (migration 0273 made the unique per user).
const replay = await prisma.medicationIntakeEvent.findUnique({
where: { idempotencyKey: entry.idempotencyKey },
where: {
userId_idempotencyKey: {
userId: user.id,
idempotencyKey: entry.idempotencyKey,
},
},
select: { id: true },
});
if (replay) {
@@ -793,7 +801,12 @@ async function postBulk(request: NextRequest): Promise<Response> {
) {
const existing = entry.idempotencyKey
? await prisma.medicationIntakeEvent.findUnique({
where: { idempotencyKey: entry.idempotencyKey },
where: {
userId_idempotencyKey: {
userId: user.id,
idempotencyKey: entry.idempotencyKey,
},
},
select: { id: true },
})
: // v1.28 — an Apple entry that raced the partial