Refuse what these four routes used to absorb in silence

Four surfaces answered a bad request by quietly substituting a good one. Each
fix comes with the test that catches it, and each test was confirmed red
against the old behaviour before the fix went back in.

`PATCH /api/user/ai-provider` inspected its body key by key with `typeof`
guards, so a numeric `model` or a boolean `baseUrl` failed every guard,
produced no entry in the update, and the write went ahead without it — a 200
that says "saved" for a field that was discarded. A body of nothing but such
keys came back as "No valid fields" naming none of them. The real schema now
lives in `src/lib/validations/ai-provider.ts`, the route runs one `safeParse`,
and a mismatch is the multi-issue 422 every sibling answers with. The accepted
field set is unchanged, and the object is deliberately not strict: an unknown
key has always been ignored here and still is. The one thing the schema has to
carry that no other does is that this body holds plaintext credentials, so no
rule may interpolate the value it rejected — noted where the next `.refine()`
would go.

`?slice=` on `/api/analytics` was compared against one literal and fell
through to the DEFAULT body on anything else, so `?slice=summary` answered 200
after running the heaviest chain on the surface. Invisible and expensive at
once. Closed enum, 422 on anything outside it.

`?metricType=` and `?limit=` on `/api/personal-records` were parsed
defensively, which read as robustness and behaved as silence — and in one
direction it was worse than silence: dropping an unrecognised `metricType`
WIDENS the read to every metric, so a typo returned more of the record than
was asked for. Both refuse now, and the 500 ceiling refuses rather than
clamps, because serving a different number of rows than were requested is the
same quiet substitution. No caller in the tree sends a value the new rules
reject.

`POST /api/ingest/medication` bucketed on the client address, so a household
running a chat bridge, a button and a home-automation rule — the normal
deployment for this route — put all three in one 60/min cell and let the
chattiest starve the rest. It already resolves a per-caller identity two lines
further down and threw it away; the bucket is that token now. A request that
resolves no token keeps the per-IP bucket it always had, through the shared
anonymous helper, so a flood is still capped and a broken proxy chain
collapses into the tight global cell rather than a shared "unknown" one. Its
429 goes through `apiError` and carries `meta` like every other refusal.

Two older tests pinned the defects by name — "drops an unknown metricType
silently" and "falls back to default on garbage ?limit" — and one pinned a
throw where the rest of the surface returns an envelope. All three are
rewritten with the reason beside them.

The generated YAML is deliberately not in this commit.
This commit is contained in:
Marc-André Bombeck committed 2026-08-22 13:23:48 +02:00
1 parent 49da15feaa
commit bb9bf0ba68
15 files changed
+682 -255

No files matched your search

@@ -32,6 +32,7 @@ vi.mock("@/lib/auth/audit", () => ({
vi.mock("@/lib/auth/hmac", () => ({ hashToken: (s: string) => `hash(${s})` }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
checkAuthSurfaceRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/app-settings", () => ({
@@ -62,16 +63,19 @@ vi.mock("next/headers", () => ({
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { checkAuthSurfaceRateLimit, checkRateLimit } from "@/lib/rate-limit";
import { isApiGloballyEnabled } from "@/lib/app-settings";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
function postReq(body: unknown): NextRequest {
function postReq(
body: unknown,
bearer: string | null = "hlk_test_token",
): NextRequest {
return new NextRequest("http://localhost/api/ingest/medication", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: "Bearer hlk_test_token",
...(bearer === null ? {} : { authorization: `Bearer ${bearer}` }),
},
body: JSON.stringify(body),
});
@@ -80,6 +84,10 @@ function postReq(body: unknown): NextRequest {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: true,
ip: "203.0.113.7",
} as never);
vi.mocked(isApiGloballyEnabled).mockResolvedValue(true);
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
id: "tok-1",
@@ -190,6 +198,10 @@ describe("POST /api/ingest/medication — slot attribution + convergence (v1.16.
function wireHappyPath() {
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: true,
ip: "203.0.113.7",
} as never);
vi.mocked(isApiGloballyEnabled).mockResolvedValue(true);
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
id: "tok-1",
@@ -433,3 +445,136 @@ describe("POST /api/ingest/medication — idempotency-key stability floor", () =
expect(prisma.medicationIntakeEvent.create).toHaveBeenCalledTimes(1);
});
});
/**
* A bridge is identified by its TOKEN, not by the address it dials from.
*
* The bucket used to be `ingest:${ip}`, so a household running a chat bridge,
* a button and a home-automation rule — the normal deployment for this route,
* not an edge case — put all three in one 60/min cell and let the chattiest
* of them starve the other two. What makes it a defect rather than a
* trade-off is that the route already resolves a per-caller identity two
* lines further down and threw it away.
*
* The fallback matters as much as the fix: a request that resolves no token
* has no identity but its address, and must stay capped on it. Keying the
* failure path on anything shared — or on nothing — would hand an
* unauthenticated flood a free pass, or collapse every anonymous caller in
* the world into one cell, which is worse than what it replaces.
*/
describe("POST /api/ingest/medication — the rate-limit bucket", () => {
it("keys the bucket on the token, not on the client IP", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValue(null as never);
await POST(
postReq({ medicationName: "Metformin", idempotencyKey: "k-stable-001" }),
);
expect(vi.mocked(checkRateLimit)).toHaveBeenCalledTimes(1);
const [key, limit, windowMs] = vi.mocked(checkRateLimit).mock.calls[0];
expect(key).toBe("ingest:token:tok-1");
expect(limit).toBe(60);
expect(windowMs).toBe(60_000);
// The address must not appear in the key at all — that is the whole
// point. A NAT'd sibling on the same address gets its own cell.
expect(key).not.toContain("203.0.113");
});
it("gives two tokens on one address two independent buckets", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValue(null as never);
vi.mocked(prisma.apiToken.findUnique)
.mockResolvedValueOnce({
id: "tok-bridge",
userId: "user-1",
permissions: ["*"],
revoked: false,
expiresAt: null,
lastUsedAt: null,
} as never)
.mockResolvedValueOnce({
id: "tok-button",
userId: "user-1",
permissions: ["*"],
revoked: false,
expiresAt: null,
lastUsedAt: null,
} as never);
await POST(postReq({ medicationName: "A", idempotencyKey: "k-aaaa-001" }));
await POST(postReq({ medicationName: "B", idempotencyKey: "k-bbbb-001" }));
const keys = vi.mocked(checkRateLimit).mock.calls.map(([k]) => k);
expect(keys).toEqual([
"ingest:token:tok-bridge",
"ingest:token:tok-button",
]);
expect(new Set(keys).size).toBe(2);
});
it("refuses an exhausted token bucket with the standard envelope", async () => {
vi.mocked(checkRateLimit).mockResolvedValue({
allowed: false,
remaining: 0,
resetAt: Date.now() + 30_000,
} as never);
const res = await POST(
postReq({ medicationName: "Metformin", idempotencyKey: "k-stable-002" }),
);
expect(res.status).toBe(429);
const body = (await res.json()) as {
data: null;
error: string;
meta?: { errorCode?: string };
};
expect(body.data).toBeNull();
// The 429 was hand-rolled through `NextResponse.json` and carried no
// `meta`, so a client branching on `errorCode` could not see it.
expect(body.meta?.errorCode).toBe("ingest.rate_limited");
expect(prisma.medication.findFirst).not.toHaveBeenCalled();
});
it("falls back to the per-IP bucket when no token is presented", async () => {
const res = await POST(
postReq(
{ medicationName: "Metformin", idempotencyKey: "k-anon-0001" },
null,
),
);
expect(res.status).toBe(401);
// The anonymous path must still be capped, and on the address — the only
// identity such a request has.
expect(vi.mocked(checkAuthSurfaceRateLimit)).toHaveBeenCalledTimes(1);
const [, prefix, limit, windowMs] = vi.mocked(checkAuthSurfaceRateLimit)
.mock.calls[0];
expect(prefix).toBe("ingest:ip");
expect(limit).toBe(60);
expect(windowMs).toBe(60_000);
// No token resolved, so no token bucket was charged.
expect(vi.mocked(checkRateLimit)).not.toHaveBeenCalled();
});
it("falls back to the per-IP bucket when the token does not resolve", async () => {
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue(null as never);
const res = await POST(
postReq({ medicationName: "Metformin", idempotencyKey: "k-bogus-001" }),
);
expect(res.status).toBe(401);
expect(vi.mocked(checkAuthSurfaceRateLimit)).toHaveBeenCalledTimes(1);
expect(vi.mocked(checkRateLimit)).not.toHaveBeenCalled();
});
it("caps an invalid-token flood before it can answer 401 forever", async () => {
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue(null as never);
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: false,
remaining: 0,
resetAt: Date.now() + 30_000,
ip: "203.0.113.7",
} as never);
const res = await POST(
postReq({ medicationName: "Metformin", idempotencyKey: "k-flood-001" }),
);
expect(res.status).toBe(429);
});
});
+65 -15
View File
@@ -11,7 +11,12 @@ import {
sanitiseZodIssues,
} from "@/lib/api-response";
import { hashToken } from "@/lib/auth/hmac";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import {
checkAuthSurfaceRateLimit,
checkRateLimit,
rateLimitHeaders,
type RateLimitResult,
} from "@/lib/rate-limit";
import { externalIntakeSchema } from "@/lib/validations/medication";
import {
unstableExternalIdMeta,
@@ -26,13 +31,49 @@ import {
import { consumeForIntake } from "@/lib/medications/inventory/consumption";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { NextRequest, NextResponse } from "next/server";
import { NextRequest } from "next/server";
const RATE_LIMIT = 60;
const RATE_WINDOW_MS = 60 * 1000;
/** The 429, with the standard headers and the standard error envelope. */
function tooManyRequests(rl: RateLimitResult) {
const response = apiError("Rate limit exceeded", 429, {
errorCode: "ingest.rate_limited",
});
for (const [key, value] of Object.entries(rateLimitHeaders(rl))) {
response.headers.set(key, value);
}
return response;
}
/**
* Refuse a caller that presented no usable token, capped on the way out.
*
* The bucket is the caller's ADDRESS, because that is the only identity an
* unauthenticated request has. `checkAuthSurfaceRateLimit` is the shared
* helper for exactly this shape: it keys on the trusted-proxy IP normally,
* and when the proxy chain does not match the configured hop count it routes
* every anonymous caller into one tight global bucket instead of the
* free-for-all that a shared `"unknown"` cell would be.
*/
async function refuseUnauthenticated(request: NextRequest, message: string) {
const rl = await checkAuthSurfaceRateLimit(
request,
"ingest:ip",
RATE_LIMIT,
RATE_WINDOW_MS,
);
if (!rl.allowed) return tooManyRequests(rl);
return apiError(message, 401);
}
/**
* External medication ingest endpoint.
* Auth: Bearer token (hashed and looked up in api_tokens table).
* Idempotent via idempotencyKey.
* Rate limit: 60 requests per minute per IP.
* Rate limit: 60 requests per minute per TOKEN (per client IP for a request
* that presents no valid one).
*/
export const POST = apiHandler(async (request: NextRequest) => {
annotate({ action: { name: "ingest.medication" } });
@@ -43,19 +84,10 @@ export const POST = apiHandler(async (request: NextRequest) => {
const ip = getClientIp(request);
// Rate limiting: 60 requests per minute per IP
const rl = await checkRateLimit(`ingest:${ip}`, 60, 60 * 1000);
if (!rl.allowed) {
return NextResponse.json(
{ data: null, error: "Rate limit exceeded" },
{ status: 429, headers: rateLimitHeaders(rl) },
);
}
// Extract bearer token
const authHeader = request.headers.get("authorization");
if (!authHeader?.startsWith("Bearer ")) {
return apiError("Authorization header required", 401);
return refuseUnauthenticated(request, "Authorization header required");
}
const token = authHeader.slice(7);
@@ -74,13 +106,31 @@ export const POST = apiHandler(async (request: NextRequest) => {
});
if (!apiToken || apiToken.revoked) {
return apiError("Invalid or revoked token", 401);
return refuseUnauthenticated(request, "Invalid or revoked token");
}
if (apiToken.expiresAt && apiToken.expiresAt < new Date()) {
return apiError("Token expired", 401);
return refuseUnauthenticated(request, "Token expired");
}
// A bridge is identified by its TOKEN, not by the address it dials from.
// The bucket used to be `ingest:${ip}`, so every integration behind one
// NAT shared a single 60/min cell and one chatty bridge starved the rest —
// and a household running a chat bridge, a button and a home-automation
// rule is the normal deployment here, not an edge case.
//
// The identity is only known after the lookup, so the lookup now runs
// before the limiter: one indexed single-row read ahead of what was
// already an upsert against `rate_limits`. A caller whose token does not
// resolve is still capped on the per-IP bucket it was always capped on,
// one step earlier than it reaches anything expensive.
const rl = await checkRateLimit(
`ingest:token:${apiToken.id}`,
RATE_LIMIT,
RATE_WINDOW_MS,
);
if (!rl.allowed) return tooManyRequests(rl);
if (
!apiToken.permissions.includes("*") &&
!apiToken.permissions.includes("medication:ingest")