mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
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:
1 parent
3e9594b3b8
commit
39d23dbb7d
33 files changed
+730
-216
No files matched your search
@@ -0,0 +1,102 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// The unit setup stubs the meter for every route test; this file is where the
|
||||
// real one is pinned.
|
||||
vi.mock("@/lib/auth/write-meter", async (importOriginal) =>
|
||||
importOriginal<typeof import("@/lib/auth/write-meter")>(),
|
||||
);
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
event: null as null | { getHttpMethod: () => string | undefined },
|
||||
allowed: true,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
getEvent: () => state.event,
|
||||
annotate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRecordWriteRateLimit: vi.fn(async () => ({
|
||||
allowed: state.allowed,
|
||||
limit: 300,
|
||||
remaining: state.allowed ? 299 : 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
})),
|
||||
}));
|
||||
|
||||
import {
|
||||
meterAccountWrite,
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
} from "../write-meter";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
import { HttpError } from "@/lib/api-errors";
|
||||
|
||||
function request(method: string | undefined) {
|
||||
state.event = { getHttpMethod: () => method };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(checkRecordWriteRateLimit).mockClear();
|
||||
state.allowed = true;
|
||||
state.event = null;
|
||||
});
|
||||
|
||||
describe("meterAccountWrite", () => {
|
||||
it.each(["POST", "PUT", "PATCH", "DELETE", "patch"])(
|
||||
"charges the acting account for a %s",
|
||||
async (method) => {
|
||||
request(method);
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledWith("account-1");
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["GET", "HEAD", "OPTIONS"])("leaves a %s alone", async (method) => {
|
||||
request(method);
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("charges nothing outside a request", async () => {
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("charges one request once, however many resolvers it passes", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1");
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(1);
|
||||
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1");
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("leaves a read-over-POST alone, and only the POST", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1", { readOverPost: true });
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
request("DELETE");
|
||||
await meterAccountWrite("account-1", { readOverPost: true });
|
||||
expect(checkRecordWriteRateLimit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves a route with its own bucket alone", async () => {
|
||||
request("POST");
|
||||
await meterAccountWrite("account-1", { writeBucket: "own" });
|
||||
expect(checkRecordWriteRateLimit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a spent bucket with 429 and the published code", async () => {
|
||||
state.allowed = false;
|
||||
request("PATCH");
|
||||
const refusal = await meterAccountWrite("account-1").catch((e) => e);
|
||||
expect(refusal).toBeInstanceOf(HttpError);
|
||||
expect((refusal as HttpError).statusCode).toBe(429);
|
||||
expect((refusal as HttpError).errorCode).toBe(
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* The shared per-account write ceiling, applied where the caller is resolved.
|
||||
*
|
||||
* `checkRecordWriteRateLimit` (300 writes a minute per acting account) used to
|
||||
* be called by hand in a dozen create routes, and the other mutating routes
|
||||
* had no ceiling at all: of 364 mutating handlers, 169 met no limiter, every
|
||||
* PATCH and DELETE on an `[id]` among them. A positive list of routes that
|
||||
* remember to call it can only fall behind the routes that exist, so the
|
||||
* ceiling now sits on the path every authenticated write already takes: the
|
||||
* identity resolvers in `src/lib/api-handler.ts` call {@link meterAccountWrite}
|
||||
* once the caller is known, and it charges the bucket for any request whose
|
||||
* method writes.
|
||||
*
|
||||
* What it does not do:
|
||||
*
|
||||
* - charge a read. GET, HEAD and OPTIONS pass untouched, and so does a POST a
|
||||
* route declared `readOverPost` (a search whose query must not stand in a
|
||||
* URL).
|
||||
* - charge one request twice. A route that resolves the caller through two
|
||||
* helpers (step-up on top of a session) is charged once.
|
||||
* - meter a route that declared its own bucket. The bulk ingest endpoints
|
||||
* the native client syncs through have dedicated ceilings sized for that
|
||||
* volume; charging the shared bucket as well would let a large HealthKit
|
||||
* backfill lock the person out of logging a single dose by hand. Declaring
|
||||
* `writeBucket: "own"` is frozen per route by
|
||||
* `src/__tests__/write-rate-limit-guard.test.ts`, which also requires the
|
||||
* route to call its own limiter.
|
||||
*
|
||||
* The bucket is keyed on the ACTING account, the precedent from the delegable
|
||||
* medication routes: a delegate spends their own allowance rather than the
|
||||
* record owner's, and cannot collect a fresh one by switching records. A
|
||||
* refused request is counted too, since the charge happens before the body is
|
||||
* read.
|
||||
*/
|
||||
import { HttpError } from "@/lib/api-errors";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { checkRecordWriteRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
/** The code a refusal by the shared write bucket carries. */
|
||||
export const RECORD_WRITE_RATE_LIMITED_CODE = "record_write.rate_limited";
|
||||
|
||||
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
||||
|
||||
/** Requests already charged, so a second resolver in one request is free. */
|
||||
const charged = new WeakSet<object>();
|
||||
|
||||
export interface WriteMeterOptions {
|
||||
/** The route answers this POST without writing (see `readOverPost`). */
|
||||
readOverPost?: true;
|
||||
/**
|
||||
* The route meters its writes with a dedicated bucket instead of the shared
|
||||
* one. Reviewed per route by the write rate-limit guard.
|
||||
*/
|
||||
writeBucket?: "own";
|
||||
}
|
||||
|
||||
/**
|
||||
* Charge the acting account's shared write bucket for this request, or refuse
|
||||
* it with 429 when the bucket is spent.
|
||||
*
|
||||
* Outside a request (no wide event, so no method) there is nothing to charge.
|
||||
*/
|
||||
export async function meterAccountWrite(
|
||||
accountId: string,
|
||||
options: WriteMeterOptions = {},
|
||||
): Promise<void> {
|
||||
const evt = getEvent();
|
||||
if (!evt) return;
|
||||
const method = (evt.getHttpMethod() ?? "").toUpperCase();
|
||||
if (!WRITE_METHODS.has(method)) return;
|
||||
if (options.readOverPost === true && method === "POST") return;
|
||||
if (options.writeBucket === "own") {
|
||||
annotate({ meta: { write_bucket: "own" } });
|
||||
return;
|
||||
}
|
||||
if (charged.has(evt)) return;
|
||||
charged.add(evt);
|
||||
|
||||
const rl = await checkRecordWriteRateLimit(accountId);
|
||||
if (!rl.allowed) {
|
||||
annotate({ meta: { record_write_rate_limited: true } });
|
||||
throw new HttpError(
|
||||
429,
|
||||
"Too many writes, try again later",
|
||||
RECORD_WRITE_RATE_LIMITED_CODE,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user