fix(server): tighten the guard, audit and token paths

Permissions cached an empty map before it had loaded, so a DB error during
the load cached permissive defaults and every later check answered from that
cache - fail-open, and it never expired. The rate limiter grew its per-IP map
forever; the GC the legacy version had was dropped in the fold. Idempotency
did a check-then-insert, so two concurrent duplicates both ran the handler.

Audit rows recorded whatever X-Forwarded-For said, which the client writes,
and the request-body debug logger redacted by exact key match - it missed
refresh tokens, api keys and PKCE verifiers. FORCE_HTTPS built its redirect
from the client's Host header. CSP asked for unsafe-eval on top of the
wasm-unsafe-eval it actually needs.

The OAuth deny path redirected to an unvalidated URI, ws-token minting had
no rate limit at all, and PKCE was skipped when code_verifier was absent
rather than refused. An MCP session resumed with a token whose scopes had
since been reduced kept the capability set it was created with, and the
session cap was checked before the async registration that increments it.

Plugin frame containment was lexical, so a symlink out of the directory was
never noticed, and instance config accepted keys the manifest never
declared.
This commit is contained in:
Maurice
2026-08-23 09:47:58 +02:00
committed by Maurice
parent 4bfb277423
commit 8e5fdaa877
28 changed files with 671 additions and 140 deletions
@@ -1,6 +1,7 @@
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';
import type { Request, Response } from 'express';
import { Observable, of } from 'rxjs';
import { Observable, from, of } from 'rxjs';
import { finalize, switchMap } from 'rxjs/operators';
import { DatabaseService } from '../database/database.service';
/**
@@ -16,8 +17,17 @@ import { DatabaseService } from '../database/database.service';
* - non-mutating method, or no key, or no authenticated user -> pass through
* - key longer than the cap -> 400 with the exact legacy message
* - (key, user, method, path) already stored -> replay the cached response
* - the same key still in flight -> wait for it, then replay its response
* - otherwise -> capture a successful JSON response under the key
*
* The in-flight step is the one thing the Express wrapper did not do. The row
* only exists once the first request answers, so two overlapping replays of one
* key (two tabs draining the same offline queue, or a client retrying after a
* timeout) both missed the SELECT and both ran the handler — the duplicate
* write the key exists to prevent. Waiting keeps the promise the client was
* given: the second caller gets the first one's response, not a new error to
* interpret.
*
* Capturing wraps `res.json`, so 204 / `res.end()` responses are not cached —
* matching the Express wrapper, which only fires on `res.json`.
*/
@@ -26,6 +36,14 @@ const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
const MAX_KEY_LENGTH = 128;
const MAX_CACHED_BODY_BYTES = 256 * 1024;
/**
* (user, method, path, key) of every request currently running, resolved when it
* answers. In memory rather than a reservation row on purpose: better-sqlite3 is
* synchronous and the whole overlap lives inside one process, so a crash cannot
* leave a key wedged for the table's 30-day TTL.
*/
const inFlight = new Map<string, Promise<void>>();
interface IdempotencyRow {
status_code: number;
response_body: string;
@@ -53,17 +71,51 @@ export class IdempotencyInterceptor implements NestInterceptor {
throw new HttpException({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' }, 400);
}
// Scope the lookup by method + path as well as user, so the same key replayed
// against a different endpoint can't return an unrelated cached body.
const existing = this.database.get<IdempotencyRow>(
const existing = this.lookup(key, userId, req);
if (existing) return this.replay(existing, res);
const signature = `${userId}|${req.method}|${req.path}|${key}`;
const pending = inFlight.get(signature);
if (pending) {
return from(pending).pipe(
switchMap(() => {
const stored = this.lookup(key, userId, req);
if (stored) return this.replay(stored, res);
// The first request answered without caching anything (it failed, or
// it never went through res.json). Run this one normally rather than
// inventing a response for it.
return this.run(signature, key, userId, req, res, next);
}),
);
}
return this.run(signature, key, userId, req, res, next);
}
/**
* Scope the lookup by method + path as well as user, so the same key replayed
* against a different endpoint can't return an unrelated cached body.
*/
private lookup(key: string, userId: number, req: Request): IdempotencyRow | undefined {
return this.database.get<IdempotencyRow>(
'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?',
key, userId, req.method, req.path,
);
if (existing) {
res.status(existing.status_code);
return of(JSON.parse(existing.response_body));
}
}
private replay(row: IdempotencyRow, res: Response): Observable<unknown> {
res.status(row.status_code);
return of(JSON.parse(row.response_body));
}
private run(
signature: string,
key: string,
userId: number,
req: Request,
res: Response,
next: CallHandler,
): Observable<unknown> {
const originalJson = res.json.bind(res);
const database = this.database;
res.json = function (body: unknown): Response {
@@ -84,6 +136,14 @@ export class IdempotencyInterceptor implements NestInterceptor {
return originalJson(body);
};
return next.handle();
let done!: () => void;
inFlight.set(signature, new Promise<void>((resolve) => { done = resolve; }));
return next.handle().pipe(
finalize(() => {
inFlight.delete(signature);
done();
}),
);
}
}
+20 -5
View File
@@ -7,14 +7,19 @@ interface Attempt { count: number; first: number }
* `rateLimiter`. Each named bucket keeps its own attempt map; `check` returns
* false once a key exceeds `max` within `windowMs` (the caller answers 429).
*
* The legacy route also ran a setInterval to garbage-collect expired records;
* that was pure memory housekeeping (the window check below already treats an
* expired record as fresh), so it is intentionally omitted — the limit
* behaviour is identical and there's no dangling timer to leak in tests.
* The legacy route ran a setInterval to garbage-collect expired records. There
* is no timer here — a dangling one leaks in tests — but the housekeeping is
* back as a lazy sweep driven by the `now` the caller already passes: keys are
* per-IP and proxy-header derived, so without it a bucket grows for every
* address that ever knocked and never shrinks again. An expired record is
* treated as fresh by the window check below, so dropping it changes nothing
* about who gets a 429.
*/
@Injectable()
export class RateLimitService {
private readonly buckets = new Map<string, Map<string, Attempt>>();
/** Last sweep per bucket, so a busy bucket doesn't keep a quiet one from being cleaned. */
private readonly lastSweep = new Map<string, number>();
private store(bucket: string): Map<string, Attempt> {
let s = this.buckets.get(bucket);
@@ -25,6 +30,7 @@ export class RateLimitService {
/** Returns true when the request is allowed, false when it should be rejected (429). */
check(bucket: string, key: string, max: number, windowMs: number, now: number): boolean {
const store = this.store(bucket);
this.sweep(bucket, store, windowMs, now);
const record = store.get(key);
if (record && record.count >= max && now - record.first < windowMs) {
return false;
@@ -37,9 +43,18 @@ export class RateLimitService {
return true;
}
/** Drops records whose window has elapsed, at most once per window per bucket. */
private sweep(bucket: string, store: Map<string, Attempt>, windowMs: number, now: number): void {
if (now - (this.lastSweep.get(bucket) ?? 0) < windowMs) return;
for (const [k, record] of store) {
if (now - record.first >= windowMs) store.delete(k);
}
this.lastSweep.set(bucket, now);
}
/** Test helper: clear a bucket (mirrors the legacy exported maps used for resets). */
reset(bucket?: string): void {
if (bucket) this.buckets.get(bucket)?.clear();
else this.buckets.clear();
else { this.buckets.clear(); this.lastSweep.clear(); }
}
}