mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
Cap how many live measurement tokens an account may hold
The mint's rate limit bounds a burst and does nothing about accumulation: a stuck automation retrying politely inside its 10-per-minute allowance still leaves several hundred live credentials behind in an afternoon, each one to be revoked by hand. Count live rows before the create and refuse at ten. Live, not minted-ever, so revoking frees a slot and an expired token stops occupying one — the ceiling bounds what currently exists rather than what the account has ever done. Scoped to measurements:write for a reason worth stating: signing in mints a wildcard access token per session and those accumulate on their own, so counting every row would let ordinary browser use exhaust the budget and then refuse a mint for a reason invisible to the person hitting it. 409 rather than 429. This is a conflict with the account's current state, not a rate: it does not clear by waiting, it clears by revoking, and a 429 would tell the caller the opposite of what is true. Placed after validation, so a malformed request hears about the malformation rather than the ceiling, and before the create, so hitting the limit costs no credential. Ten is set to catch a loop rather than to ration — a household running Home Assistant, a scale bridge and a couple of scripts sits at three or four, and it is not a security boundary since the holder can revoke and mint freely. Tests pin the boundary, the query shape and the ordering, and were mutation-checked: turning >= into > fails the ceiling case, and dropping the scope filter fails the query-shape case. The integration leg seeds a wildcard and an expired row as decoys, then revokes one live token and asserts exactly one slot opens — the leg that fails if the count is of mints rather than of tokens alive.
This commit is contained in:
1 parent
6db18d0b71
commit
371c0c49f1
4 files changed
+190
-1
No files matched your search
@@ -37,12 +37,17 @@ vi.mock("@/lib/logging/context", () => ({
|
||||
getEvent: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { apiToken: { count: vi.fn() } },
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { requireCookieAuth } from "@/lib/api-handler";
|
||||
import { issueApiToken } from "@/lib/auth/issue-token";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
|
||||
|
||||
const USER = { id: "user-1", role: "USER" as const };
|
||||
@@ -62,6 +67,8 @@ beforeEach(() => {
|
||||
vi.mocked(isApiGloballyEnabled).mockResolvedValue(true);
|
||||
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined as never);
|
||||
// Below the ceiling by default; the cases that care set their own count.
|
||||
vi.mocked(prisma.apiToken.count).mockResolvedValue(0 as never);
|
||||
vi.mocked(issueApiToken).mockResolvedValue({
|
||||
token: "hlk_" + "a".repeat(64),
|
||||
expiresAt: EXPIRES,
|
||||
@@ -145,6 +152,55 @@ describe("when it refuses", () => {
|
||||
expect(issueApiToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("409s at the live-token ceiling, without minting", async () => {
|
||||
vi.mocked(prisma.apiToken.count).mockResolvedValue(10 as never);
|
||||
const res = await POST(req({ name: "Scale" }) as never);
|
||||
|
||||
// 409, not 429: a conflict with the account's current state, whose remedy
|
||||
// is revoking rather than waiting. A 429 would say the opposite.
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).meta?.errorCode).toBe(
|
||||
"tokens.measurements.ceiling_reached",
|
||||
);
|
||||
expect(issueApiToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still mints on the last free slot", async () => {
|
||||
// The off-by-one that would make the ceiling nine. Worth pinning, because
|
||||
// `>=` versus `>` is invisible in review and only one of them is right.
|
||||
vi.mocked(prisma.apiToken.count).mockResolvedValue(9 as never);
|
||||
const res = await POST(req({ name: "Scale" }) as never);
|
||||
expect(res.status).toBe(201);
|
||||
});
|
||||
|
||||
it("counts only live tokens carrying this scope", async () => {
|
||||
// The whole shape of the query, asserted rather than assumed. Counting
|
||||
// every row would let the `["*"]` tokens a login mints consume the budget
|
||||
// and refuse a mint for a reason the person cannot see; counting revoked
|
||||
// or expired rows would mean revoking never frees a slot.
|
||||
await POST(req({ name: "Scale" }) as never);
|
||||
|
||||
const where = vi.mocked(prisma.apiToken.count).mock.calls[0][0]?.where;
|
||||
expect(where).toMatchObject({
|
||||
userId: USER.id,
|
||||
revoked: false,
|
||||
permissions: { has: MEASUREMENTS_WRITE_SCOPE },
|
||||
});
|
||||
expect(where?.OR).toEqual([
|
||||
{ expiresAt: null },
|
||||
{ expiresAt: { gt: expect.any(Date) } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks the ceiling only after the body validates", async () => {
|
||||
// A malformed request should hear about the malformation, not the
|
||||
// ceiling — and should not spend a query establishing it.
|
||||
vi.mocked(prisma.apiToken.count).mockResolvedValue(10 as never);
|
||||
const res = await POST(req({}) as never);
|
||||
expect(res.status).toBe(422);
|
||||
expect(prisma.apiToken.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores a scope the body tries to smuggle in", async () => {
|
||||
// There is no `scope` field to validate, so an unknown key is simply not
|
||||
// read — the permission array is a literal either way. Asserted because
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
} from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { issueApiToken } from "@/lib/auth/issue-token";
|
||||
import { isApiGloballyEnabled } from "@/lib/app-settings";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
@@ -62,6 +63,23 @@ const DEFAULT_EXPIRY_DAYS = 365;
|
||||
const MINT_RATE_LIMIT_MAX = 10;
|
||||
const MINT_RATE_LIMIT_WINDOW_MS = 60 * 1000;
|
||||
|
||||
/**
|
||||
* How many ingest tokens an account may hold at once.
|
||||
*
|
||||
* The rate limit above and this are different guards and neither substitutes
|
||||
* for the other. The bucket bounds a burst; it does nothing about
|
||||
* accumulation, and a stuck automation retrying politely inside its allowance
|
||||
* still reaches several hundred live credentials in an afternoon. This bounds
|
||||
* the standing set, so a runaway script meets a refusal rather than leaving a
|
||||
* thousand rows for somebody to revoke by hand.
|
||||
*
|
||||
* Ten is meant to be a number nobody legitimately reaches: a household running
|
||||
* Home Assistant, a scale bridge and a couple of scripts sits at three or four.
|
||||
* It is not a security boundary — the person can revoke and mint freely — so
|
||||
* it is set to catch a loop, not to ration.
|
||||
*/
|
||||
const MAX_LIVE_TOKENS = 10;
|
||||
|
||||
export const POST = apiHandler(async (request: NextRequest) => {
|
||||
// Cookie-only, and the reason is lifetime rather than reach.
|
||||
//
|
||||
@@ -102,6 +120,40 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
return returnAllZodIssues(parsed.error, 422);
|
||||
}
|
||||
|
||||
// Counted LIVE, not minted-ever, so revoking frees a slot and an expired
|
||||
// token stops occupying one — the ceiling bounds what currently exists
|
||||
// rather than what the account has ever done. Scoped to this grant for the
|
||||
// same reason: a login mints a `["*"]` access token per session and those
|
||||
// accumulate on their own, so counting every row would let ordinary browser
|
||||
// use exhaust the budget and then refuse a mint for a reason invisible to
|
||||
// the person hitting it.
|
||||
//
|
||||
// Placed after validation and before the create: a request that is going to
|
||||
// be refused should not cost a credential, and one that is malformed should
|
||||
// hear about the malformation rather than the ceiling.
|
||||
const live = await prisma.apiToken.count({
|
||||
where: {
|
||||
userId: user.id,
|
||||
revoked: false,
|
||||
permissions: { has: MEASUREMENTS_WRITE_SCOPE },
|
||||
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
|
||||
},
|
||||
});
|
||||
if (live >= MAX_LIVE_TOKENS) {
|
||||
annotate({
|
||||
action: { name: "tokens.measurements.create" },
|
||||
meta: { outcome: "ceiling_reached", live_token_count: live },
|
||||
});
|
||||
// 409 rather than 429: this is a conflict with the account's current
|
||||
// state, not a rate, and the remedy is to revoke one rather than to wait.
|
||||
// A 429 would tell the caller the opposite of what is true.
|
||||
return apiError(
|
||||
`You already have ${MAX_LIVE_TOKENS} measurement tokens. Revoke one before creating another.`,
|
||||
409,
|
||||
{ errorCode: "tokens.measurements.ceiling_reached" },
|
||||
);
|
||||
}
|
||||
|
||||
const issued = await issueApiToken({
|
||||
userId: user.id,
|
||||
name: parsed.data.name,
|
||||
|
||||
Reference in new issue
Block a user