fix(api): meter every authenticated write where the caller is resolved

169 of 364 mutating handlers met no rate limit, every PATCH and DELETE on
an [id] among them. The shared per-account write bucket (300 a minute,
keyed on the acting account) was called by hand in a dozen creates; it is
now charged by the identity resolvers for any POST, PUT, PATCH or DELETE,
once per request, so a route is metered by resolving its caller.

The bulk ingest routes the native client syncs through in bursts
(measurements, workouts, intake, mood and cycle bulk, nutrients, the ECG
sweep) declare writeBucket: "own" and keep their dedicated ceilings, so a
large HealthKit backfill cannot lock the person out of logging a dose. A
read-over-POST stays free.

write-rate-limit-guard fails on any mutating route that neither resolves
its caller through a metering resolver nor calls a limiter, unless it is
on a short reasoned exception list; an opt-out must be on its own reviewed
list and call its own limiter.
This commit is contained in:
Marc-André Bombeck committed 2026-10-20 13:53:54 +02:00
1 parent 3e9594b3b8
commit 39d23dbb7d
33 files changed
+730 -216

No files matched your search

@@ -33,6 +33,12 @@ vi.mock("@/lib/rate-limit", async (importOriginal) => ({
resetAt: new Date(Date.now() + 60_000),
})),
}));
// The real meter, so the ceiling is proven on the path it now takes: the route
// resolves its caller, the resolver charges the bucket. The unit setup stubs
// the meter for every other route test.
vi.mock("@/lib/auth/write-meter", async (importOriginal) =>
importOriginal<typeof import("@/lib/auth/write-meter")>(),
);
const tzMock = vi.hoisted(() => ({ zone: "UTC" }));
vi.mock("@/lib/tz/resolver", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/tz/resolver")>()),
@@ -216,7 +222,7 @@ describe("POST /api/labs/ocr/commit dedup across the user's day", () => {
});
describe("POST /api/labs/ocr/commit write ceiling", () => {
it("charges the shared per-account record-write bucket", async () => {
it("charges the shared per-account record-write bucket where the caller is resolved", async () => {
const res = await POST(postReq({ rows: [numericRow(95)] }));
expect(res.status).toBe(200);
expect(checkRecordWriteRateLimit).toHaveBeenCalledWith("user-1");
-13
View File
@@ -20,7 +20,6 @@ import { fireAndForget } from "@/lib/logging/fire-and-forget";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
@@ -31,7 +30,6 @@ import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
import { withIdempotency } from "@/lib/idempotency";
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
import { enqueueReminderSatisfy } from "@/lib/jobs/reminder-satisfy";
import { emitDataArrival } from "@/lib/arrivals/emit-shared";
import { rememberImportAlias } from "@/lib/labs/biomarker-aliases";
@@ -159,17 +157,6 @@ function inBatchKey(
async function commitOcrRows(request: NextRequest) {
const { user } = await requireAuth();
// Shared per-account write ceiling, the same bucket every other lab write
// charges (`POST /api/labs`, `POST /api/biomarkers`). A commit can write a
// whole report's rows and mint markers on the way, so it was the one lab
// write a looping client could repeat without any ceiling.
const writeRl = await checkRecordWriteRateLimit(user.id);
if (!writeRl.allowed) {
return apiError("Too many writes, try again later", 429, {
errorCode: "record_write.rate_limited",
});
}
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 256 * 1024,
});
+1 -12
View File
@@ -10,7 +10,6 @@ import {
safeJson,
sanitiseZodIssues,
} from "@/lib/api-response";
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { invalidateUserHealthScore } from "@/lib/cache/invalidate";
@@ -156,17 +155,7 @@ async function postLabResult(request: NextRequest) {
// it mints it under `user.id`: the marker joins the record's catalogue, not
// the caller's, which is the only reading of "add a result to your record"
// that leaves the owner with a usable catalogue afterwards.
const { user, actor } = await requireRecordAuth("write", "labs");
// Shared per-account write ceiling — see `checkRecordWriteRateLimit`. The
// batch siblings have always been capped; the per-record creates a looping
// client hits were not.
const writeRl = await checkRecordWriteRateLimit(actor.id);
if (!writeRl.allowed) {
return apiError("Too many writes, try again later", 429, {
errorCode: "record_write.rate_limited",
});
}
const { user } = await requireRecordAuth("write", "labs");
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,