From d09d1ccce1d88bdd6ba4987001e4846389a57a23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Sun, 6 Dec 2026 22:28:13 +0700 Subject: [PATCH 1/6] fix(gateway): harden proxy fidelity, retries and failure attribution --- src/gateway/errors.ts | 26 +- src/gateway/forward-headers.ts | 7 + src/gateway/models-route.ts | 6 +- src/gateway/normalize.ts | 33 +- src/gateway/not-found.ts | 49 ++- src/gateway/preauth.ts | 21 +- src/gateway/proxy.ts | 258 ++++++++++++--- src/gateway/rotation.ts | 15 +- src/util/errors.ts | 84 ++++- src/util/upstream.ts | 55 +++- tests/gateway-hardening.test.ts | 493 ++++++++++++++++++++++++++++ tests/gateway-normalize.test.ts | 93 ++++++ tests/gateway-proxy-helpers.test.ts | 73 ++++ tests/gateway-rotation.test.ts | 43 +++ tests/util-errors.test.ts | 129 ++++++++ tests/util-upstream.test.ts | 60 ++++ 16 files changed, 1349 insertions(+), 96 deletions(-) create mode 100644 tests/gateway-hardening.test.ts create mode 100644 tests/util-errors.test.ts diff --git a/src/gateway/errors.ts b/src/gateway/errors.ts index 1bf3b8b..b45e19f 100644 --- a/src/gateway/errors.ts +++ b/src/gateway/errors.ts @@ -32,17 +32,27 @@ export function installGatewayErrorHandler(scope: FastifyInstance, ctx: AppConte const surface = surfaceForUrl(request.url); const errorStatus = (error as FastifyError).statusCode; const status = error instanceof ApiError ? error.status : typeof errorStatus === 'number' ? errorStatus : 500; + const fastifyCode = (error as FastifyError).code; + // A-11: the body-limit failure must not expose the Fastify internal code + // (`FST_ERR_CTP_BODY_TOO_LARGE`) or claim a generic invalid request. + const payloadTooLarge = status === 413 || fastifyCode === 'FST_ERR_CTP_BODY_TOO_LARGE'; const apiError = error instanceof ApiError ? error - : new ApiError( - status >= 500 ? 'api_error' : 'invalid_request_error', - status >= 500 ? 'Internal server error.' : error.message, - { - status, - code: status >= 500 ? 'internal_error' : ((error as FastifyError).code ?? 'invalid_request'), - }, - ); + : payloadTooLarge + ? new ApiError( + 'invalid_request_error', + `Request body is too large; the configured body limit (BODY_LIMIT) is ${ctx.config.bodyLimit} bytes.`, + { status: 413, code: 'payload_too_large' }, + ) + : new ApiError( + status >= 500 ? 'api_error' : 'invalid_request_error', + status >= 500 ? 'Internal server error.' : error.message, + { + status, + code: status >= 500 ? 'internal_error' : (fastifyCode ?? 'invalid_request'), + }, + ); if (status >= 500) scope.log.error({ err: error, url: request.url }, 'gateway request failed'); if (reply.raw.headersSent || reply.raw.writableEnded) return; const state = request.gateway; diff --git a/src/gateway/forward-headers.ts b/src/gateway/forward-headers.ts index fdee0a0..2fb6ec2 100644 --- a/src/gateway/forward-headers.ts +++ b/src/gateway/forward-headers.ts @@ -17,6 +17,13 @@ const FORWARDED_HEADERS = [ 'openai-beta', 'accept', 'accept-language', + // A-09: provider-identity/attribution headers are client-supplied and carry no + // credential; dropping them broke project-scoped OpenAI routing and OpenRouter + // attribution. + 'openai-organization', + 'openai-project', + 'http-referer', + 'x-title', 'x-request-id', 'traceparent', 'tracestate', diff --git a/src/gateway/models-route.ts b/src/gateway/models-route.ts index 8502ad8..25443f8 100644 --- a/src/gateway/models-route.ts +++ b/src/gateway/models-route.ts @@ -43,7 +43,7 @@ export function toModelObject(model: ModelRow): Record { * Provider/attempts headers describe a proxied call, so they are never set here * (FIX-15); every `/v1/models*` response carries only the request id. */ -function finishModelsRequest( +export function finishModelsRequest( ctx: AppContext, request: FastifyRequest, reply: FastifyReply, @@ -73,7 +73,9 @@ function finishModelsRequest( return; } reply.header(ROUTER_REQUEST_ID_HEADER, state.requestId); - void reply.status(input.status); + // A-12: `reply.status()` returns the reply, so the call must not be discarded and + // the caller's status has to be applied before `send` runs. + reply.status(input.status); } export function registerModelsRoutes(app: FastifyInstance, ctx: AppContext): void { diff --git a/src/gateway/normalize.ts b/src/gateway/normalize.ts index 3fce890..b2cf207 100644 --- a/src/gateway/normalize.ts +++ b/src/gateway/normalize.ts @@ -10,6 +10,12 @@ export interface NormalizedBody { appliedEffort: string | null; /** True when `stream_options.include_usage` had to be injected. */ usageInjected: boolean; + /** + * A-04: true when this normalization actually changed the payload (model-id trim, + * reasoning-hint removal/rewrite or usage injection). The proxy picks raw bytes vs + * the normalized object from this flag instead of re-serializing both bodies. + */ + changed: boolean; } function asJson(value: unknown): Json | null { @@ -64,27 +70,39 @@ export function normalizeBody( options: { countTokens?: boolean } = {}, ): NormalizedBody { const next: Json = { ...body }; + let changed = false; // GW-11: the gateway routes and logs the trimmed model id, so the trimmed id is // also what the provider must receive (`" x "` would otherwise be rejected). if (typeof next.model === 'string' && next.model !== next.model.trim() && next.model.trim().length > 0) { next.model = next.model.trim(); + changed = true; } let requestedEffort = requestedEffortFor(surface, body); let appliedEffort: string | null = null; if (model && model.reasoning.supported === false) { - // Non-reasoning models: providers reject unknown reasoning hints. - delete next.reasoning_effort; - delete next.reasoning; - delete next.thinking; + // Non-reasoning models: providers reject unknown reasoning hints. Only a key that + // is actually present counts as a change (`undefined` is dropped by JSON anyway). + for (const key of ['reasoning_effort', 'reasoning', 'thinking']) { + if (next[key] !== undefined) { + delete next[key]; + changed = true; + } + } requestedEffort = null; } else if (model && model.reasoning.supported) { if (surface === 'chat' && requestedEffort !== null) { appliedEffort = resolveEffort(requestedEffort, model.reasoning.efforts); - if (appliedEffort !== null) next.reasoning_effort = appliedEffort; + if (appliedEffort !== null) { + if (next.reasoning_effort !== appliedEffort) changed = true; + next.reasoning_effort = appliedEffort; + } } else if (surface === 'responses' && requestedEffort !== null) { appliedEffort = resolveEffort(requestedEffort, model.reasoning.efforts); - if (appliedEffort !== null) next.reasoning = { ...(asJson(body.reasoning) ?? {}), effort: appliedEffort }; + if (appliedEffort !== null) { + if (asJson(body.reasoning)?.effort !== appliedEffort) changed = true; + next.reasoning = { ...(asJson(body.reasoning) ?? {}), effort: appliedEffort }; + } } // messages: `thinking` is passed through untouched, the budget is authoritative. } @@ -95,8 +113,9 @@ export function normalizeBody( if (existing?.include_usage !== true) { next.stream_options = { ...(existing ?? {}), include_usage: true }; usageInjected = true; + changed = true; } } - return { body: next, requestedEffort, appliedEffort, usageInjected }; + return { body: next, requestedEffort, appliedEffort, usageInjected, changed }; } diff --git a/src/gateway/not-found.ts b/src/gateway/not-found.ts index 27d6f0a..0cef54a 100644 --- a/src/gateway/not-found.ts +++ b/src/gateway/not-found.ts @@ -5,6 +5,33 @@ import { sendApiError, surfaceForUrl } from './errors.js'; import { recordRequestLog } from './logging.js'; import { gatewayState } from './preauth.js'; +interface KnownRoute { + /** Path (no query string) matcher. */ + match: (path: string) => boolean; + methods: readonly string[]; +} + +/** + * A-13: real gateway routes keyed by path, so a known path called with the wrong + * method gets a `405` + `Allow` instead of a misleading `404 unknown_endpoint`. + * `HEAD` is implied by `GET`, matching Fastify's exposeHeadRoutes default. + */ +const KNOWN_GATEWAY_ROUTES: readonly KnownRoute[] = [ + { match: (path) => path === '/v1/chat/completions', methods: ['POST'] }, + { match: (path) => path === '/v1/responses', methods: ['POST'] }, + { match: (path) => path === '/v1/messages', methods: ['POST'] }, + { match: (path) => path === '/v1/messages/count_tokens', methods: ['POST'] }, + { match: (path) => path === '/v1/models', methods: ['GET', 'HEAD'] }, + { match: (path) => path.startsWith('/v1/models/'), methods: ['GET', 'HEAD'] }, +]; + +function knownMethodsFor(path: string): readonly string[] | null { + for (const route of KNOWN_GATEWAY_ROUTES) { + if (route.match(path)) return route.methods; + } + return null; +} + /** * GW-04: unknown `/v1/*` paths used to fall through to the root not-found handler, * which runs outside the gateway scope — so the API-key hook never ran (anonymous @@ -12,15 +39,27 @@ import { gatewayState } from './preauth.js'; * * This catch-all lives inside the authenticated gateway scope and is registered * last, so real routes always win. It still writes exactly one log row and answers - * with the surface-shaped error envelope. + * with the surface-shaped error envelope; a known path with an unsupported method + * answers `405` plus an `Allow` header (A-13). */ export function registerUnknownGatewayRoutes(app: FastifyInstance, ctx: AppContext): void { const handler = async (request: FastifyRequest, reply: FastifyReply): Promise => { const state = gatewayState(request); const surface = surfaceForUrl(request.url); - const error = new ApiError('not_found_error', `Unknown endpoint: ${request.method} ${request.url}`, { - code: 'unknown_endpoint', - }); + const queryIndex = request.url.indexOf('?'); + const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); + const allowed = knownMethodsFor(path); + const error = + allowed === null + ? new ApiError('not_found_error', `Unknown endpoint: ${request.method} ${request.url}`, { + code: 'unknown_endpoint', + }) + : new ApiError( + 'invalid_request_error', + `${request.method} is not allowed on ${path}; supported method(s): ${allowed.join(', ')}.`, + { status: 405, code: 'method_not_allowed' }, + ); + if (allowed !== null) reply.header('allow', allowed.join(', ')); const userAgent = request.headers['user-agent']; state.logged = true; recordRequestLog(ctx, { @@ -45,4 +84,4 @@ export function registerUnknownGatewayRoutes(app: FastifyInstance, ctx: AppConte app.all('/v1/*', handler); // `/v1` itself is not covered by the wildcard; it is just as unknown. app.all('/v1', handler); -} \ No newline at end of file +} diff --git a/src/gateway/preauth.ts b/src/gateway/preauth.ts index d22035b..b26356b 100644 --- a/src/gateway/preauth.ts +++ b/src/gateway/preauth.ts @@ -81,10 +81,8 @@ function rejectUnauthenticated( const surface = surfaceForUrl(request.url); const userAgent = request.headers['user-agent']; - // Rejected calls still occupied an inbound socket; the pair keeps the counter - // accounting symmetric with the route handlers and floors at zero. - incActiveRequests(); - decActiveRequests(); + // The active-request counter is owned by the gateway onRequest/onResponse hooks + // (A-03), so a rejection here is already accounted for. // Every log row gets its paired start event, rejections included, so SSE // consumers never see an orphan `request:end`. @@ -136,6 +134,21 @@ export function gatewayState(request: FastifyRequest): GatewayRequestState { * when the client body is not valid UTF-8. */ export function installGatewayHooks(scope: FastifyInstance, ctx: AppContext): void { + // A-03: the whole gateway lifecycle (models routes and pre-attempt rejections + // included) is bracketed by exactly one inc/dec pair. The counting hook runs + // before authentication so a rejected request is still counted while in flight. + scope.addHook('onRequest', async (_request: FastifyRequest, reply: FastifyReply) => { + incActiveRequests(); + let released = false; + const release = (): void => { + if (released) return; + released = true; + decActiveRequests(); + }; + // `close` fires once for a finished, aborted, hijacked or injected response, so + // the counter is always released exactly once per request. + reply.raw.once('close', release); + }); scope.addHook('onRequest', createPreAuthHook(ctx)); // Encapsulated to this scope: admin keeps its own lenient parser. diff --git a/src/gateway/proxy.ts b/src/gateway/proxy.ts index 7f29140..f3f902d 100644 --- a/src/gateway/proxy.ts +++ b/src/gateway/proxy.ts @@ -1,7 +1,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; -import { decActiveRequests, incActiveRequests, type AppContext } from '../core/context.js'; +import type { AppContext } from '../core/context.js'; import type { ApiKeyRow, Json, ProviderRow, Surface, Usage } from '../types.js'; -import { ApiError, isRetryableStatus, upstreamErrorFrom } from '../util/errors.js'; +import { ApiError, isRetryableStatus, scrubSecrets, upstreamErrorFrom } from '../util/errors.js'; import { SseParser } from '../util/sse.js'; import { upstreamFetch, type UpstreamResponse } from '../util/upstream.js'; import { forwardHeaders } from './forward-headers.js'; @@ -48,15 +48,63 @@ const PROXY_ROUTES: ProxyRoute[] = [ }, ]; -/** Decodes `retry-after` (delta seconds or HTTP-date) into milliseconds. */ -export function retryAfterMs(value: string | null, now = Date.now()): number | null { +/** A-01: ceiling for an upstream `Retry-After`; a broken provider cannot pin a year-long cooldown. */ +export const MAX_RETRY_AFTER_MS = 3_600_000; + +export interface ParsedRetryAfter { + /** Clamped millisecond value used for the cooldown. */ + ms: number; + /** True when the raw upstream value exceeded `MAX_RETRY_AFTER_MS` and was clamped. */ + capped: boolean; + /** Raw header value, for a single debug log at the call site. */ + raw: string; +} + +/** + * A-01: decodes `retry-after` (delta seconds or HTTP-date) and clamps it to + * `MAX_RETRY_AFTER_MS` on both branches. + */ +export function parseRetryAfter(value: string | null, now = Date.now()): ParsedRetryAfter | null { if (value === null) return null; + const raw = value.trim(); + if (raw.length === 0) return null; + let ms: number | null = null; + if (/^\d+$/.test(raw)) { + ms = Number.parseInt(raw, 10) * 1000; + } else { + const date = Date.parse(raw); + if (Number.isFinite(date)) ms = Math.max(0, date - now); + } + if (ms === null || Number.isNaN(ms)) return null; + if (ms > MAX_RETRY_AFTER_MS) return { ms: MAX_RETRY_AFTER_MS, capped: true, raw }; + return { ms, capped: false, raw }; +} + +/** Decodes `retry-after` into (clamped) milliseconds. */ +export function retryAfterMs(value: string | null, now = Date.now()): number | null { + const parsed = parseRetryAfter(value, now); + return parsed === null ? null : parsed.ms; +} + +/** `upstream_response_max_bytes` maximum (1 GiB); `0` disables the cap. */ +export const MAX_UPSTREAM_RESPONSE_BYTES = 1_073_741_824; +/** Smallest meaningful non-zero cap (1 KiB); smaller values are ignored. */ +export const MIN_UPSTREAM_RESPONSE_BYTES = 1_024; + +/** + * A-06: parses the `upstream_response_max_bytes` setting. `0` (the default) means + * unlimited; a non-zero cap must be within 1 KiB..1 GiB. Anything else falls back to + * the documented default (`0`) instead of failing every request on a bad setting. + */ +export function parseUpstreamResponseMaxBytes(value: string | null | undefined): number { + if (value === null || value === undefined) return 0; const trimmed = value.trim(); - if (trimmed.length === 0) return null; - if (/^\d+$/.test(trimmed)) return Number.parseInt(trimmed, 10) * 1000; - const date = Date.parse(trimmed); - if (!Number.isFinite(date)) return null; - return Math.max(0, date - now); + if (!/^\d+$/.test(trimmed)) return 0; + const parsed = Number.parseInt(trimmed, 10); + if (!Number.isFinite(parsed)) return 0; + if (parsed === 0) return 0; + if (parsed < MIN_UPSTREAM_RESPONSE_BYTES || parsed > MAX_UPSTREAM_RESPONSE_BYTES) return 0; + return parsed; } function isTimeoutReason(reason: string | null): boolean { @@ -227,6 +275,8 @@ async function readResponseText(response: Response): Promise { interface AttemptOptions { requestId: string; attempt: number; + /** Upstream path, including the client's raw query string (A-08). */ + path: string; /** Total deadline for the whole upstream exchange (headers + body). */ timeoutMs: number; cooldownMs: number; @@ -252,7 +302,7 @@ async function runAttempt( upstream = await upstreamFetch({ baseUrl: provider.baseUrl, apiKey: provider.apiKey, - path: route.upstreamPath, + path: options.path, method: 'POST', ...(options.rawBody !== null ? { rawBody: options.rawBody } : { body: options.body }), headers: options.headers, @@ -302,7 +352,7 @@ async function runAttempt( status: 502, code: 'upstream_redirect', }) - : upstreamErrorFrom(upstream.status, text, provider.name); + : upstreamErrorFrom(upstream.status, text, provider.name, [provider.apiKey]); ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, @@ -333,10 +383,18 @@ async function runAttempt( } if (isRetryableStatus(upstream.status)) { - // FEAT-01: an upstream Retry-After is authoritative when longer than the - // configured cooldown, so the provider is not retried before it recovers. - const retryAfter = retryAfterMs(upstream.headers.get('retry-after')); - const cooldownMs = retryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, retryAfter); + // FEAT-01/A-01: an upstream Retry-After is authoritative when longer than the + // configured cooldown, but it is clamped so a hostile value cannot pin the + // provider in cooldown forever. + const parsedRetryAfter = parseRetryAfter(upstream.headers.get('retry-after')); + if (parsedRetryAfter?.capped === true) { + ctx.logger.debug( + { providerId: provider.id, retryAfter: parsedRetryAfter.raw, cappedMs: parsedRetryAfter.ms }, + 'upstream Retry-After clamped', + ); + } + const cooldownMs = + parsedRetryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, parsedRetryAfter.ms); ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, cooldownMs); emitProvider(ctx, { providerId: provider.id, @@ -397,7 +455,11 @@ async function runAttempt( const apiError = error instanceof ApiError ? error - : new ApiError('connection_error', error instanceof Error ? error.message : String(error)); + : new ApiError( + 'connection_error', + // Defence in depth (A-05/A-10): a runtime message must never carry the key. + scrubSecrets(error instanceof Error ? error.message : String(error), [provider.apiKey]), + ); ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, @@ -457,33 +519,58 @@ export function stripXOpencode(value: unknown): unknown { return changed ? out : value; } -/** Removes provider-internal `x_opencode` keys, keeping all other bytes when possible. */ -export function stripTopLevelXOpencode(buffer: Buffer): Buffer { - const text = buffer.toString('utf8'); - if (!text.includes('x_opencode')) return buffer; +/** + * A-06: string form of `stripTopLevelXOpencode`. The caller decodes the body once and + * reuses the returned text for the usage parse instead of decoding it twice. + */ +export function stripXOpencodeText(text: string): { text: string; changed: boolean } { + if (!text.includes('x_opencode')) return { text, changed: false }; try { const parsed = JSON.parse(text) as unknown; const stripped = stripXOpencode(parsed); - if (stripped !== parsed) return Buffer.from(JSON.stringify(stripped), 'utf8'); + if (stripped !== parsed) return { text: JSON.stringify(stripped), changed: true }; } catch { /* not JSON, forward untouched */ } - return buffer; + return { text, changed: false }; +} + +/** Removes provider-internal `x_opencode` keys, keeping all other bytes when possible. */ +export function stripTopLevelXOpencode(buffer: Buffer): Buffer { + const result = stripXOpencodeText(buffer.toString('utf8')); + return result.changed ? Buffer.from(result.text, 'utf8') : buffer; } -/** Rewrites a single SSE frame only when it carries a provider `x_opencode` key. */ +/** + * A-07: rewrites a single SSE frame only when it carries a provider `x_opencode` key. + * Every `data:` line of the frame is joined (SSE semantics) before parsing, and a + * change is re-emitted as one canonical `data:` line; an untouched frame is returned + * byte-identical so invalid UTF-8 / BOMs are never re-encoded. + */ export function rewriteSseFrame(frame: string): string { if (!frame.includes('x_opencode')) return frame; const lines = frame.split('\n'); - const index = lines.findIndex((line) => line.startsWith('data:')); - if (index === -1) return frame; - const payload = lines[index]!.slice(5).replace(/^ /, ''); + const dataIndexes: number[] = []; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]!.endsWith('\r') ? lines[index]!.slice(0, -1) : lines[index]!; + if (line.startsWith('data:')) dataIndexes.push(index); + } + if (dataIndexes.length === 0) return frame; + const payload = dataIndexes + .map((index) => { + const line = lines[index]!; + const body = (line.endsWith('\r') ? line.slice(0, -1) : line).slice(5).replace(/^ /, ''); + return body; + }) + .join('\n'); if (!payload.startsWith('{')) return frame; try { const parsed = JSON.parse(payload) as unknown; const stripped = stripXOpencode(parsed); if (stripped === parsed) return frame; - lines[index] = `data: ${JSON.stringify(stripped)}`; + lines[dataIndexes[0]!] = `data: ${JSON.stringify(stripped)}`; + // Drop the remaining data lines; a single canonical line stands for the frame. + for (let index = dataIndexes.length - 1; index >= 1; index -= 1) lines.splice(dataIndexes[index]!, 1); return lines.join('\n'); } catch { return frame; @@ -509,13 +596,37 @@ function writeFrame(reply: FastifyReply, frame: Buffer, delimiter: Buffer): bool } } -/** Returns the byte range of the frame terminator, favouring CRLFCRLF when earlier. */ -function nextBoundary(buffer: Buffer): { index: number; length: number } | null { - const lf = buffer.indexOf('\n\n'); - const crlf = buffer.indexOf('\r\n\r\n'); - if (lf === -1 && crlf === -1) return null; - if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 }; - return { index: lf, length: 2 }; +/** + * A-07: returns the byte range of the earliest SSE frame terminator. All separators + * Node streams may emit are recognized (`\r\n\r\n`, `\n\n`, `\r\n\n`, `\n\r\n`, `\r\r`), + * so a provider using a mixed line ending no longer stalls until the idle timeout. + */ +export function nextBoundary(buffer: Buffer): { index: number; length: number } | null { + let index = 0; + while (index < buffer.length) { + // Jump between candidate line-ending bytes so large frames are not scanned byte + // by byte in JS (the buffers can be up to the SSE frame cap). + const lf = buffer.indexOf(0x0a, index); + const cr = buffer.indexOf(0x0d, index); + if (lf === -1 && cr === -1) return null; + index = cr === -1 ? lf : lf === -1 ? cr : Math.min(lf, cr); + const byte = buffer[index]!; + const second = buffer[index + 1]; + if (byte === 0x0a) { + // \n\n / \n\r\n + if (second === 0x0a) return { index, length: 2 }; + if (second === 0x0d && buffer[index + 2] === 0x0a) return { index, length: 3 }; + } else { + // \r\r / \r\n\r\n / \r\n\n + if (second === 0x0d) return { index, length: 2 }; + if (second === 0x0a) { + if (buffer[index + 2] === 0x0d && buffer[index + 3] === 0x0a) return { index, length: 4 }; + if (buffer[index + 2] === 0x0a) return { index, length: 3 }; + } + } + index += 1; + } + return null; } /** @@ -799,10 +910,22 @@ async function jsonSurface( upstream: UpstreamResponse, attempts: number, ttfbMs: number, + maxBytes: number, ): Promise { let buffer: Buffer; try { - buffer = stripTopLevelXOpencode(Buffer.from(await upstream.response.arrayBuffer())); + // A-06: refuse an upstream that already declares an oversized body before it is + // buffered at all; the cap is opt-in (`0` = unlimited). + const declared = Number(upstream.headers.get('content-length')); + if (maxBytes > 0 && Number.isFinite(declared) && declared > maxBytes) { + try { + await upstream.response.body?.cancel(); + } catch { + /* body already gone */ + } + return tooLargeOutcome(ttfbMs, maxBytes); + } + buffer = Buffer.from(await upstream.response.arrayBuffer()); } catch (error) { // Nothing has been written to the client yet, so the caller can still return // an error response; a timeout must not surface as the upstream's 2xx status. @@ -820,18 +943,25 @@ async function jsonSurface( } finally { disposeUpstream(upstream); } - const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); + // Decode the buffered body exactly once and reuse the text for the x_opencode strip + // and the usage parse (A-06); the original bytes are kept for byte-faithful output. + const decoded = buffer.toString('utf8'); + const stripped = stripXOpencodeText(decoded); + const bodyText = stripped.text; + const body = stripped.changed ? Buffer.from(bodyText, 'utf8') : buffer; + if (maxBytes > 0 && body.byteLength > maxBytes) return tooLargeOutcome(ttfbMs, maxBytes); + const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(bodyText))); // GW-09: forward the upstream retry/rate-limit/request-id headers; the router and // the rewritten body (content-type/length) always win. const headers = forwardedResponseHeaders(upstream.headers, { 'content-type': upstream.headers.get('content-type') ?? 'application/json', - 'content-length': String(buffer.byteLength), + 'content-length': String(body.byteLength), ...routerHeaders(provider, requestId, attempts), }); try { reply.hijack(); reply.raw.writeHead(upstream.status, headers); - reply.raw.end(buffer); + reply.raw.end(body); } catch (error) { return { status: upstream.status, @@ -856,13 +986,18 @@ async function jsonSurface( }; } -/** - * `normalizeBody` returned a shallow copy; the raw bytes can only be reused when - * no logical change happened. The JSON round-trip is the documented comparison - * (FIX-09) and only decides *which* representation is sent, never rewrites it. - */ -function hasLogicalChange(original: Json, normalized: Json): boolean { - return JSON.stringify(normalized) !== JSON.stringify(original); +/** A-06: failure outcome for an upstream body that exceeds the configured cap. */ +function tooLargeOutcome(ttfbMs: number | null, maxBytes: number): SurfaceOutcome { + return { + status: 502, + ok: false, + aborted: false, + timedOut: false, + ttfbMs, + usage: emptyUsage(), + errorCode: 'upstream_response_too_large', + errorMessage: `Upstream response exceeds the configured upstream_response_max_bytes limit (${maxBytes} bytes).`, + }; } /* -------------------------------------------------------------------- handler */ @@ -881,8 +1016,6 @@ async function handleProxyRequest( const userAgentHeader = request.headers['user-agent']; const clientUserAgent = typeof userAgentHeader === 'string' ? userAgentHeader : null; - incActiveRequests(); - const key: ApiKeyRow | null = state.key; let modelId: string | null = null; let stream = false; @@ -937,8 +1070,12 @@ async function handleProxyRequest( const normalized = normalizeBody(surface, body, model, { countTokens: route.countTokens === true }); const normalizedBody = normalized.body; const rawBody = state.rawBody; - // Forward the client bytes verbatim whenever normalization changed nothing. - const upstreamBody = rawBody !== null && !hasLogicalChange(body, normalizedBody) ? null : normalizedBody; + // Forward the client bytes verbatim when normalization changed nothing; the + // explicit flag replaces the old double JSON.stringify comparison (A-04). + const upstreamBody = rawBody !== null && !normalized.changed ? null : normalizedBody; + // A-08: provider-specific query flags (`?beta=true`, `?version=…`) must survive. + const queryIndex = request.url.indexOf('?'); + const upstreamPath = `${route.upstreamPath}${queryIndex === -1 ? '' : request.url.slice(queryIndex)}`; const cooldownMs = Math.max(0, ctx.repo.getInt('provider_cooldown_ms', 60_000)); const maxRetries = Math.max(1, ctx.repo.getInt('max_retries', 3)); @@ -950,6 +1087,10 @@ async function handleProxyRequest( ctx.repo.getInt('stream_idle_timeout_ms', DEFAULT_STREAM_IDLE_MS), ); const upstreamUserAgent = ctx.repo.getSetting('upstream_user_agent') ?? 'opencode-router/1.0'; + // A-06: opt-in ceiling for buffered (non-streaming) upstream response bodies. + const upstreamResponseMaxBytes = parseUpstreamResponseMaxBytes( + ctx.repo.getSetting('upstream_response_max_bytes'), + ); const strategy = parseRotationStrategy(ctx.repo.getSetting('rotation_strategy')); const requestHeaders = forwardHeaders(request.headers, { acceptJson: !stream || route.countTokens === true }); @@ -985,6 +1126,7 @@ async function handleProxyRequest( const attempt = await runAttempt(ctx, fresh, route, { requestId, attempt: attemptNo, + path: upstreamPath, timeoutMs, cooldownMs, userAgent: upstreamUserAgent, @@ -1022,7 +1164,16 @@ async function handleProxyRequest( guard, idleMs: streamIdleMs, }) - : await jsonSurface(reply, surface, requestId, fresh, attempt.response, attempts, attempt.latencyMs); + : await jsonSurface( + reply, + surface, + requestId, + fresh, + attempt.response, + attempts, + attempt.latencyMs, + upstreamResponseMaxBytes, + ); usage = outcome.usage; ttfbMs = outcome.ttfbMs; logStatus = outcome.status; @@ -1068,6 +1219,9 @@ async function handleProxyRequest( throw fatalError; } else if (attempts > 0 && everyFailureRateLimited && lastStatus === 429) { // FEAT-06: hand SDK clients a concrete backoff instead of a hot retry loop. + // A-02: real attempts happened, so the log row and router headers are + // attributed to the last provider that answered. + provider = lastAttemptProvider; const cooldownUntil = smallestCooldownUntil(ctx.repo.listProviders()); const retryAfter = retryAfterSeconds(cooldownUntil); reply.header('retry-after', String(retryAfter)); @@ -1086,6 +1240,9 @@ async function handleProxyRequest( code: 'upstream_timeout', }); } else { + // A-02: attribute the aggregated failure to the last attempted provider + // (null when nothing was attempted, e.g. every candidate cooling down). + provider = lastAttemptProvider; // A 3xx from upstream is never replayed to the client as a redirect // (FIX-08), so only real error statuses are forwarded. const status = lastStatus !== null && lastStatus >= 400 ? lastStatus : (lastError?.status ?? 502); @@ -1127,7 +1284,6 @@ async function handleProxyRequest( } } finally { guard?.dispose(); - decActiveRequests(); state.logged = true; recordRequestLog(ctx, { requestId, diff --git a/src/gateway/rotation.ts b/src/gateway/rotation.ts index 4e8697c..f89776f 100644 --- a/src/gateway/rotation.ts +++ b/src/gateway/rotation.ts @@ -26,10 +26,10 @@ export function enabledProviders(providers: ProviderRow[]): ProviderRow[] { } /** Fisher-Yates shuffle on a copy; the cursor is meaningless for `random`. */ -function shuffled(providers: ProviderRow[]): ProviderRow[] { +function shuffled(providers: ProviderRow[], random: () => number): ProviderRow[] { const items = [...providers]; for (let index = items.length - 1; index > 0; index -= 1) { - const swap = Math.floor(Math.random() * (index + 1)); + const swap = Math.floor(random() * (index + 1)); const current = items[index]!; items[index] = items[swap]!; items[swap] = current; @@ -37,6 +37,11 @@ function shuffled(providers: ProviderRow[]): ProviderRow[] { return items; } +/** Test seam for the random strategy (A-15): production callers keep `Math.random`. */ +export interface RotationOptions { + random?: () => number; +} + /** * Puts the candidates in attempt order for the configured strategy: * @@ -48,9 +53,10 @@ function shuffled(providers: ProviderRow[]): ProviderRow[] { function orderedProviders( providers: ProviderRow[], strategy: RotationStrategy = 'round-robin', + random: () => number = Math.random, ): ProviderRow[] { if (providers.length === 0) return []; - if (strategy === 'random') return shuffled(providers); + if (strategy === 'random') return shuffled(providers, random); if (strategy === 'priority') return [...providers]; const start = cursor % providers.length; cursor = (start + 1) % providers.length; @@ -76,10 +82,11 @@ export function orderProviders( providers: ProviderRow[], now = Date.now(), strategy: RotationStrategy = 'round-robin', + options: RotationOptions = {}, ): ProviderRotation { const enabled = enabledProviders(providers); if (enabled.length === 0) return { candidates: [], cooldownFallback: false }; - const ordered = orderedProviders(enabled, strategy); + const ordered = orderedProviders(enabled, strategy, options.random); const warm = ordered.filter((provider) => provider.cooldownUntil === null || provider.cooldownUntil <= now); if (warm.length > 0) return { candidates: warm, cooldownFallback: false }; const leastCooling = [...ordered].sort((a, b) => (a.cooldownUntil ?? 0) - (b.cooldownUntil ?? 0)); diff --git a/src/util/errors.ts b/src/util/errors.ts index 56ce087..5f300f9 100644 --- a/src/util/errors.ts +++ b/src/util/errors.ts @@ -12,6 +12,20 @@ export type ErrorType = | 'connection_error' | 'upstream_error'; +/** Runtime membership set for the `ErrorType` union (A-05: never trust a provider's `type`). */ +const ERROR_TYPES: ReadonlySet = new Set([ + 'invalid_request_error', + 'authentication_error', + 'permission_error', + 'not_found_error', + 'rate_limit_error', + 'overloaded_error', + 'api_error', + 'timeout_error', + 'connection_error', + 'upstream_error', +]); + const STATUS_BY_TYPE: Record = { invalid_request_error: 400, authentication_error: 401, @@ -71,11 +85,69 @@ export function errorTypeForStatus(status: number): ErrorType { return 'api_error'; } +/** True when a provider-supplied `type` is one of the documented envelope types (A-05). */ +export function isErrorType(value: unknown): value is ErrorType { + return typeof value === 'string' && ERROR_TYPES.has(value); +} + +/** + * A-14: every `5xx` is retryable per SPEC §2.1 step 8 (`501`/`505`/`507`/... included); + * `408`/`409`/`425`/`429` are retryable without being server errors. + */ export function isRetryableStatus(status: number): boolean { - return status === 408 || status === 409 || status === 425 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504 || status === 529; + if (status === 408 || status === 409 || status === 425 || status === 429) return true; + return status >= 500 && status <= 599; +} + +/** Longest upstream error message persisted to `request_logs`/`providers.last_error`. */ +export const MAX_ERROR_MESSAGE_LENGTH = 500; + +const REDACTED = '[redacted]'; +// Credential shapes an upstream may echo back: auth header echoes, `Bearer …` and +// `sk-…` style tokens. The configured provider key is removed literally too. +const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/=-]{4,}/gi; +const SK_TOKEN = /\bsk-[A-Za-z0-9._-]{4,}/g; +const NAMED_SECRET = /\b(authorization|x-api-key|api[_-]?key)("?\s*[:=]\s*"?)[^"'\s,;}]+/gi; + +/** + * A-05: replaces every known credential (the configured provider key plus + * `Bearer …`/`sk-…`/`x-api-key`-shaped tokens) before an upstream message is + * persisted, logged or returned to a client. + */ +export function scrubSecrets(text: string, secrets: readonly string[] = []): string { + let out = text; + for (const secret of secrets) { + if (secret.length === 0) continue; + out = out.split(secret).join(REDACTED); + } + out = out.replace(BEARER_TOKEN, `Bearer ${REDACTED}`); + out = out.replace(SK_TOKEN, REDACTED); + out = out.replace(NAMED_SECRET, (_match, name: string, separator: string) => `${name}${separator}${REDACTED}`); + return out; +} + +/** + * A-05: control characters are removed, credentials scrubbed, and the result is + * clamped to `MAX_ERROR_MESSAGE_LENGTH`. Scrubbing runs before the clamp so a key + * cannot survive by straddling the cut. + */ +export function sanitizeErrorMessage(text: string, secrets: readonly string[] = []): string { + const printable = text.replace(/[\u0000-\u001F\u007F]/g, ''); + const scrubbed = scrubSecrets(printable, secrets); + return scrubbed.length > MAX_ERROR_MESSAGE_LENGTH ? scrubbed.slice(0, MAX_ERROR_MESSAGE_LENGTH) : scrubbed; } -export function upstreamErrorFrom(status: number, body: string, provider: string): ApiError { +/** + * Maps an upstream error body onto an `ApiError`. `secrets` are scrubbed from the + * resulting message so a provider echoing the request cannot leak its own key into + * `request_logs`, `providers.last_error` or a client-visible body (A-05). + */ +export function upstreamErrorFrom( + status: number, + body: string, + provider: string, + secrets: readonly string[] = [], +): ApiError { let message = `Upstream provider "${provider}" returned HTTP ${status}`; let type: ErrorType = errorTypeForStatus(status); let code: string | null = null; @@ -85,12 +157,14 @@ export function upstreamErrorFrom(status: number, body: string, provider: string if (typeof nested.message === 'string') message = nested.message; if (typeof parsed.type === 'string' && parsed.type === 'error') { const inner = parsed.error as Record | undefined; - if (inner && typeof inner.type === 'string') type = inner.type as ErrorType; + // An unknown type must never reach `ApiError.toJSON` as an undeclared value. + if (inner && isErrorType(inner.type)) type = inner.type; + else if (inner && typeof inner.type === 'string') type = 'api_error'; if (inner && typeof inner.message === 'string') message = inner.message; } if (typeof nested.code === 'string' || typeof nested.code === 'number') code = String(nested.code); } catch { - if (body.trim().length > 0) message = body.trim().slice(0, 500); + if (body.trim().length > 0) message = body.trim(); } - return new ApiError(type, message, { status, code: code ?? undefined }); + return new ApiError(type, sanitizeErrorMessage(message, secrets), { status, code: code ?? undefined }); } diff --git a/src/util/upstream.ts b/src/util/upstream.ts index 1c3e785..eb659e3 100644 --- a/src/util/upstream.ts +++ b/src/util/upstream.ts @@ -1,10 +1,35 @@ -import { ApiError } from './errors.js'; +import { ApiError, scrubSecrets } from './errors.js'; +/** + * Joins a provider base URL with an upstream path, keeping a query string that is + * already part of the base and appending with `&` instead of a second `?` (A-08). + */ export function joinUrl(baseUrl: string, path: string): string { - const base = baseUrl.replace(/\/+$/, ''); const suffix = path.startsWith('/') ? path : `/${path}`; + const queryIndex = baseUrl.indexOf('?'); + const basePath = queryIndex === -1 ? baseUrl : baseUrl.slice(0, queryIndex); + const baseQuery = queryIndex === -1 ? '' : baseUrl.slice(queryIndex + 1); + const base = basePath.replace(/\/+$/, ''); // A base that already ends in /v1 should not get a duplicated prefix. - return `${base}${suffix}`; + const joined = `${base}${suffix}`; + if (baseQuery.length === 0) return joined; + return joined.includes('?') ? `${joined}&${baseQuery}` : `${joined}?${baseQuery}`; +} + +/** + * A-10: a provider key with CR/LF/NUL would be smuggled into a header value; strip + * those characters before the credential is used. + */ +export function sanitizeCredential(value: string): string { + return value.replace(/[\r\n\0]/g, ''); +} + +/** + * Header values Node accepts: horizontal tab plus ASCII 0x20-0x7E and Latin-1 + * 0x80-0xFF. Anything else makes `fetch` throw with the raw value in the message. + */ +export function isValidHeaderValue(value: string): boolean { + return !/[^\t\x20-\x7E\x80-\xFF]/.test(value); } export interface UpstreamRequest { @@ -85,6 +110,16 @@ export function redactMessage(message: string, url: string): string { */ export async function upstreamFetch(req: UpstreamRequest): Promise { const url = joinUrl(req.baseUrl, req.path); + // A-10: a malformed key must fail with a fixed, value-free error instead of an + // undici `Headers.append` TypeError whose message quotes the raw credential. + const apiKey = sanitizeCredential(req.apiKey); + const authorization = `Bearer ${apiKey}`; + if (!isValidHeaderValue(authorization) || !isValidHeaderValue(apiKey)) { + throw new ApiError('api_error', 'Provider credentials are invalid', { + status: 502, + code: 'invalid_provider_credentials', + }); + } const controller = new AbortController(); let abortReason: string | null = null; const abortWith = (reason: string): void => { @@ -113,8 +148,8 @@ export async function upstreamFetch(req: UpstreamRequest): Promise; +} + +type MockHandler = (req: IncomingMessage, res: ServerResponse, body: Buffer) => void | Promise; + +const upstreams: MockUpstream[] = []; + +/** Loopback mock provider on an ephemeral port (never a fixed port). */ +async function startUpstream(handler: MockHandler): Promise { + const requests: MockRequest[] = []; + const server: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + const body = Buffer.concat(chunks); + requests.push({ url: req.url ?? '', headers: req.headers, body }); + void handler(req, res, body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + const upstream: MockUpstream = { + baseUrl: `http://127.0.0.1:${port}/v1`, + port, + requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; + upstreams.push(upstream); + return upstream; +} + +function jsonResponse(res: ServerResponse, status: number, payload: unknown, headers: Record = {}): void { + const body = Buffer.from(JSON.stringify(payload)); + res.writeHead(status, { 'content-type': 'application/json', 'content-length': String(body.length), ...headers }); + res.end(body); +} + +async function waitFor(fn: () => T | null | undefined | false, label: string, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = fn(); + if (value) return value as T; + if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } +} + +let db: TestDb; +let app: FastifyInstance; +let ctx: AppContext; +let origin: string; +let port: number; +let apiKey: string; +/** A-03: counter samples taken by a root onSend hook while each request is in flight. */ +const activeSamples: number[] = []; + +function config() { + return testConfig(db.dataDir); +} + +async function buildApp(): Promise { + const cfg = config(); + app = Fastify({ logger: false, bodyLimit: cfg.bodyLimit }); + // Registered on the root before the encapsulated gateway scope so the hook is + // inherited by it and samples the counter while the request is still in flight. + app.addHook('preHandler', (_request, _reply, done) => { + activeSamples.push(getActiveRequests()); + done(); + }); + ctx = { + config: cfg, + db: db.handle, + repo: db.repo, + events: new EventBus(), + logger: app.log, + startedAt: Date.now(), + }; + await registerGatewayRoutes(app, ctx); + await app.listen({ port: 0, host: '127.0.0.1' }); + port = (app.server.address() as AddressInfo).port; + origin = `http://127.0.0.1:${port}`; +} + +function addProvider(id: string, baseUrl: string, priority: number, key = 'sk-provider'): void { + db.repo.createProvider({ id, name: id, baseUrl, apiKey: key, priority }); +} + +function gatewayFetch(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers); + if (!headers.has('authorization')) headers.set('authorization', `Bearer ${apiKey}`); + if (init.body !== undefined && !headers.has('content-type')) headers.set('content-type', 'application/json'); + return fetch(`${origin}${path}`, { ...init, headers }); +} + +const chatBody = (patch: Record = {}): string => + JSON.stringify({ model: 'test/model', messages: [{ role: 'user', content: 'ping' }], ...patch }); + +const CHAT = '/v1/chat/completions'; + +beforeEach(async () => { + db = createTestDb('okr-hardening-'); + db.repo.upsertModel({ id: 'test/model', name: 'Test Model' }); + apiKey = db.repo.createApiKey('tests').plaintext; + db.repo.setSetting('rotation_strategy', 'priority'); + activeSamples.length = 0; + await buildApp(); +}); + +afterEach(async () => { + await app.close(); + // A-03: every request must release the shared counter, otherwise later tests lie. + await waitFor(() => getActiveRequests() === 0, 'active request counter released'); + db.cleanup(); + for (const upstream of upstreams.splice(0)) await upstream.close(); +}); + +describe('A-01 bounded Retry-After', () => { + it('A-01: clamps a numeric Retry-After above one hour before writing the cooldown', async () => { + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 429, { error: { message: 'slow down' } }, { 'retry-after': '31536000' }); + }); + addProvider('p1', upstream.baseUrl, 1); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + + const provider = db.repo.getProvider('p1'); + expect(provider?.cooldownUntil).not.toBeNull(); + const remaining = provider!.cooldownUntil! - Date.now(); + expect(remaining).toBeLessThanOrEqual(MAX_RETRY_AFTER_MS + 2_000); + expect(remaining).toBeGreaterThan(MAX_RETRY_AFTER_MS - 5_000); + }); + + it('A-01: clamps an HTTP-date Retry-After above one hour before writing the cooldown', async () => { + const farFuture = new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000).toUTCString(); + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 429, { error: { message: 'slow down' } }, { 'retry-after': farFuture }); + }); + addProvider('p1', upstream.baseUrl, 1); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + + const remaining = db.repo.getProvider('p1')!.cooldownUntil! - Date.now(); + expect(remaining).toBeLessThanOrEqual(MAX_RETRY_AFTER_MS + 2_000); + expect(remaining).toBeGreaterThan(MAX_RETRY_AFTER_MS - 5_000); + }); +}); + +describe('A-02 failed-attempt provider attribution', () => { + it('A-02: attributes the aggregated failure and all router headers to the last provider', async () => { + // Loopback port 1 refuses immediately: two "dead" providers with real attempts. + addProvider('dead-a', 'http://127.0.0.1:1/v1', 1); + addProvider('dead-b', 'http://127.0.0.1:1/v1', 2); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(502); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('all_providers_failed'); + + expect(response.headers.get('x-opencode-router-provider')).toBe('dead-b'); + expect(response.headers.get('x-opencode-router-name')).toBe('dead-b'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + expect(response.headers.get('x-opencode-router-request-id')).toBeTruthy(); + + const logs = db.repo.listLogs({}).rows; + expect(logs).toHaveLength(1); + expect(logs[0]!.providerId).toBe('dead-b'); + expect(logs[0]!.providerName).toBe('dead-b'); + expect(logs[0]!.attempts).toBe(2); + expect(db.repo.listAttempts(logs[0]!.id)).toHaveLength(2); + }); +}); + +describe('A-03 active request accounting', () => { + it('A-03: counts a slow proxied request and a models request, then returns to zero', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const upstream = await startUpstream(async (_req, res) => { + await gate; + jsonResponse(res, 200, { id: 'x', usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }); + }); + addProvider('p-slow', upstream.baseUrl, 1); + + expect(getActiveRequests()).toBe(0); + const pending = gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + await waitFor(() => getActiveRequests() === 1, 'in-flight proxied request counted'); + release(); + const response = await pending; + expect(response.status).toBe(200); + await response.json(); + await waitFor(() => getActiveRequests() === 0, 'completed proxied request released'); + + // Models reads are counted too: the preHandler sample proves the counter was held + // held while the models handler produced its payload, and it is 0 afterwards. + activeSamples.length = 0; + const models = await gatewayFetch('/v1/models'); + expect(models.status).toBe(200); + await models.json(); + expect(activeSamples).toContain(1); + expect(getActiveRequests()).toBe(0); + }); +}); + +describe('A-04 single normalization decision', () => { + it('A-04: forwards an untouched body byte-for-byte and a changed body as normalized JSON', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const untouched = Buffer.from('{ "model" : "test/model" , "messages" : [ ] }'); + const first = await gatewayFetch(CHAT, { method: 'POST', body: untouched.toString('utf8') }); + expect(first.status).toBe(200); + await first.json(); + expect(upstream.requests[0]!.body.equals(untouched)).toBe(true); + + // A padded model id is rewritten, so the normalized object (not the raw bytes) is sent. + const padded = Buffer.from('{ "model" : " test/model " , "messages" : [ ] }'); + const second = await gatewayFetch(CHAT, { method: 'POST', body: padded.toString('utf8') }); + expect(second.status).toBe(200); + await second.json(); + const forwarded = upstream.requests[1]!.body; + expect(forwarded.equals(padded)).toBe(false); + expect(JSON.parse(forwarded.toString('utf8'))).toEqual({ model: 'test/model', messages: [] }); + }); +}); + +describe('A-05 bounded and scrubbed upstream error text', () => { + it('A-05: clamps, scrubs and validates errors from a 200 kB upstream body', async () => { + const secret = 'sk-live-super-secret-value'; + const huge = `${secret} ${'x'.repeat(200_000)}`; + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 500, { type: 'error', error: { type: 'mystery_type', message: huge, code: 'boom' } }); + }); + addProvider('p1', upstream.baseUrl, 1, secret); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(500); + const text = await response.text(); + expect(text).not.toContain(secret); + expect(text).not.toContain('x'.repeat(600)); + expect(text).toContain('[redacted]'); + const body = JSON.parse(text) as { error?: { type?: string; message?: string } }; + expect(body.error?.type).toBe('api_error'); + expect(body.error?.message?.length).toBeLessThanOrEqual(500); + + const log = db.repo.listLogs({}).rows[0]!; + expect(log.errorMessage!.length).toBeLessThanOrEqual(500); + expect(log.errorMessage).not.toContain(secret); + expect(db.repo.getProvider('p1')!.lastError).not.toContain(secret); + expect(db.repo.getProvider('p1')!.lastError).toContain('[redacted]'); + }); +}); + +describe('A-06 non-stream response ceiling', () => { + it('A-06: fails with 502 upstream_response_too_large when the cap is below the body size', async () => { + const payload = { id: 'big', pad: 'x'.repeat(4_096) }; + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, payload)); + addProvider('p1', upstream.baseUrl, 1); + + const unlimited = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(unlimited.status).toBe(200); + expect(((await unlimited.json()) as { pad: string }).pad).toHaveLength(4_096); + + db.repo.setSetting('upstream_response_max_bytes', '1024'); + const capped = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(capped.status).toBe(502); + const body = (await capped.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('upstream_response_too_large'); + const cappedLog = db.repo.listLogs({}).rows.find((row) => row.errorCode === 'upstream_response_too_large'); + expect(cappedLog).toBeDefined(); + expect(cappedLog!.status).toBe(502); + }); + + it('A-06: decodes a buffered upstream body exactly once', async () => { + const payload = { id: 'x'.repeat(4_093) }; + const serialized = Buffer.from(JSON.stringify(payload)); + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, payload)); + addProvider('p1', upstream.baseUrl, 1); + + const spy = vi.spyOn(Buffer.prototype, 'toString'); + try { + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + await response.json(); + const decodes = (spy.mock.contexts as unknown[]).filter( + (context) => Buffer.isBuffer(context) && context.byteLength === serialized.byteLength, + ).length; + expect(decodes).toBe(1); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('A-07 SSE frame boundaries', () => { + it('A-07: forwards a frame terminated with a mixed line ending without waiting for an idle timeout', async () => { + await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"id":"a"}\r\n\n'); + // Keep the connection open: only the boundary scanner can release this frame. + }); + const upstream = upstreams[upstreams.length - 1]!; + addProvider('p1', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: chatBody({ stream: true }), + headers: { accept: 'text/event-stream' }, + }); + expect(response.status).toBe(200); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + const collected = await Promise.race([ + (async () => { + let text = ''; + for (;;) { + const chunk = await reader.read(); + if (chunk.done) return text; + text += decoder.decode(chunk.value, { stream: true }); + if (text.includes('{"id":"a"}')) return text; + } + })(), + new Promise((resolve) => setTimeout(() => resolve(''), 3_000)), + ]); + await reader.cancel().catch(() => undefined); + expect(collected).toContain('{"id":"a"}'); + }); +}); + +describe('A-08 query-string forwarding', () => { + it('A-08: forwards the client query string on the proxied surfaces', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const chat = await gatewayFetch(`${CHAT}?beta=true`, { method: 'POST', body: chatBody() }); + expect(chat.status).toBe(200); + expect(upstream.requests[0]!.url).toBe('/v1/chat/completions?beta=true'); + + const messages = await gatewayFetch('/v1/messages?version=2025-01-01', { + method: 'POST', + body: JSON.stringify({ + model: 'test/model', + max_tokens: 8, + messages: [{ role: 'user', content: 'ping' }], + }), + }); + expect(messages.status).toBe(200); + expect(upstream.requests[1]!.url).toBe('/v1/messages?version=2025-01-01'); + }); +}); + +describe('A-09 forwarded client headers', () => { + it('A-09: forwards provider-identity headers and never client credentials or host', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: chatBody(), + headers: { + 'openai-organization': 'org-123', + 'openai-project': 'proj-456', + 'http-referer': 'https://app.example/', + 'x-title': 'My App', + // The client's own gateway credential must never be relayed upstream. + 'x-api-key': apiKey, + }, + }); + expect(response.status).toBe(200); + const headers = upstream.requests[0]!.headers; + expect(headers['openai-organization']).toBe('org-123'); + expect(headers['openai-project']).toBe('proj-456'); + expect(headers['http-referer']).toBe('https://app.example/'); + expect(headers['x-title']).toBe('My App'); + // Router credentials always win; the gateway client key never reaches the provider. + expect(headers['authorization']).toBe('Bearer sk-provider'); + expect(headers['x-api-key']).toBe('sk-provider'); + expect(headers['x-api-key']).not.toBe(apiKey); + expect(headers['host']).toBe(`127.0.0.1:${upstream.port}`); + }); +}); + +describe('A-11 payload too large mapping', () => { + it('A-11: answers 413 payload_too_large without leaking the Fastify internal code', async () => { + addProvider('p1', 'http://127.0.0.1:1/v1', 1); + const oversized = JSON.stringify({ model: 'test/model', pad: 'x'.repeat(4_096) }); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: oversized }); + expect(response.status).toBe(413); + const text = await response.text(); + expect(text).not.toContain('FST_ERR'); + const body = JSON.parse(text) as { error?: { code?: string; message?: string } }; + expect(body.error?.code).toBe('payload_too_large'); + expect(body.error?.message).toContain(String(ctx.config.bodyLimit)); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); + +describe('A-12 models helper status', () => { + it('A-12: applies a non-200 status passed to finishModelsRequest', async () => { + const probe = Fastify({ logger: false }); + probe.get('/probe', async (request, reply) => { + request.gateway = { + requestId: 'probe-request', + startedAt: Date.now(), + key: null, + logged: false, + rawBody: null, + }; + finishModelsRequest(ctx, request, reply, { status: 201, ok: true, model: null }); + await reply.send({ object: 'list', data: [] }); + }); + const response = await probe.inject({ method: 'GET', url: '/probe' }); + await probe.close(); + expect(response.statusCode).toBe(201); + expect(response.json()).toEqual({ object: 'list', data: [] }); + expect(response.headers['x-opencode-router-request-id']).toBe('probe-request'); + }); +}); + +describe('A-13 method not allowed', () => { + it('A-13: answers 405 with Allow on known paths and 404 unknown_endpoint elsewhere', async () => { + addProvider('p1', 'http://127.0.0.1:1/v1', 1); + + const put = await gatewayFetch(CHAT, { method: 'PUT', body: chatBody() }); + expect(put.status).toBe(405); + expect(put.headers.get('allow')).toBe('POST'); + expect(((await put.json()) as { error?: { code?: string } }).error?.code).toBe('method_not_allowed'); + + const options = await gatewayFetch(CHAT, { method: 'OPTIONS' }); + expect(options.status).toBe(405); + expect(options.headers.get('allow')).toBe('POST'); + + const unknown = await gatewayFetch('/v1/nope'); + expect(unknown.status).toBe(404); + expect(((await unknown.json()) as { error?: { code?: string } }).error?.code).toBe('unknown_endpoint'); + + // Exactly one log row per client request, method failures included. + expect(db.repo.listLogs({}).total).toBe(3); + }); +}); + +describe('A-14 all-5xx failover', () => { + it('A-14: fails over to the next provider on an upstream 501', async () => { + const bad = await startUpstream((_req, res) => { + jsonResponse(res, 501, { error: { message: 'not implemented' } }); + }); + const good = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'ok' })); + addProvider('bad', bad.baseUrl, 1); + addProvider('good', good.baseUrl, 2); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(((await response.json()) as { id: string }).id).toBe('ok'); + expect(response.headers.get('x-opencode-router-provider')).toBe('good'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + + const log = db.repo.listLogs({}).rows[0]!; + expect(log.attempts).toBe(2); + const attempts = db.repo.listAttempts(log.id).sort((a, b) => a.attempt - b.attempt); + expect(attempts.map((attempt) => attempt.status)).toEqual([501, 200]); + }); +}); \ No newline at end of file diff --git a/tests/gateway-normalize.test.ts b/tests/gateway-normalize.test.ts index 860e29a..0113bca 100644 --- a/tests/gateway-normalize.test.ts +++ b/tests/gateway-normalize.test.ts @@ -148,6 +148,99 @@ describe('normalizeBody', () => { }); }); +describe('A-04 explicit change flag', () => { + interface Fixture { + label: string; + surface: 'chat' | 'responses' | 'messages'; + body: Json; + model: ModelRow | null; + } + + const fixtures: Fixture[] = [ + { label: 'untouched', surface: 'chat', body: { model: 'm', messages: [] }, model: null }, + { label: 'model trim', surface: 'chat', body: { model: ' m ' }, model: null }, + { label: 'model already trimmed', surface: 'chat', body: { model: 'm' }, model: null }, + { label: 'usage injection', surface: 'chat', body: { model: 'm', stream: true }, model: null }, + { + label: 'usage already present', + surface: 'chat', + body: { model: 'm', stream: true, stream_options: { include_usage: true } }, + model: null, + }, + { + label: 'non-reasoning hint removal', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'high', reasoning: { effort: 'high' }, thinking: { type: 'enabled' } }, + model: plainModel, + }, + { + label: 'non-reasoning without hints', + surface: 'chat', + body: { model: 'm' }, + model: plainModel, + }, + { + label: 'chat effort rewrite', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'xhigh' }, + model: reasoningModel, + }, + { + label: 'chat effort already supported', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'high' }, + model: reasoningModel, + }, + { + label: 'responses effort rewrite', + surface: 'responses', + body: { model: 'm', reasoning: { effort: 'xhigh', summary: 'auto' } }, + model: reasoningModel, + }, + { + label: 'responses effort already supported', + surface: 'responses', + body: { model: 'm', reasoning: { effort: 'high', summary: 'auto' } }, + model: reasoningModel, + }, + { + label: 'messages thinking passthrough', + surface: 'messages', + body: { model: 'm', thinking: { type: 'enabled', budget_tokens: 8_000 } }, + model: reasoningModel, + }, + { + label: 'undefined reasoning hint', + surface: 'chat', + body: { model: 'm', reasoning_effort: undefined }, + model: plainModel, + }, + ]; + + it('A-04: the flag agrees with the old serialized-body comparison on a fixture table', () => { + for (const fixture of fixtures) { + const out = normalizeBody(fixture.surface, fixture.body, fixture.model); + const oldChanged = JSON.stringify(out.body) !== JSON.stringify(fixture.body); + expect(out.changed, fixture.label).toBe(oldChanged); + } + }); + + it('A-04: flags reasoning removal, effort rewrite, model trim and usage injection', () => { + expect(normalizeBody('chat', { model: ' m ' }, null).changed).toBe(true); + expect(normalizeBody('chat', { model: 'm' }, null).changed).toBe(false); + expect(normalizeBody('chat', { model: 'm', stream: true }, null).changed).toBe(true); + expect( + normalizeBody('chat', { model: 'm', stream: true, stream_options: { include_usage: true } }, null).changed, + ).toBe(false); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'high', thinking: {} }, plainModel).changed).toBe( + true, + ); + expect(normalizeBody('chat', { model: 'm' }, plainModel).changed).toBe(false); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'xhigh' }, reasoningModel).changed).toBe(true); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'high' }, reasoningModel).changed).toBe(false); + }); +}); + describe('model id normalization (GW-11)', () => { it('forwards the trimmed model id', () => { const out = normalizeBody('chat', { model: ' opencode/flint ' }, null); diff --git a/tests/gateway-proxy-helpers.test.ts b/tests/gateway-proxy-helpers.test.ts index 73394f0..7b4537b 100644 --- a/tests/gateway-proxy-helpers.test.ts +++ b/tests/gateway-proxy-helpers.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from 'vitest'; import { + MAX_RETRY_AFTER_MS, + MAX_UPSTREAM_RESPONSE_BYTES, bodyReadFailureStatus, forwardedResponseHeaders, + nextBoundary, + parseRetryAfter, + parseUpstreamResponseMaxBytes, retryAfterMs, retryAfterSeconds, rewriteSseFrame, @@ -107,6 +112,74 @@ describe('retryAfterMs', () => { expect(retryAfterMs('')).toBeNull(); expect(retryAfterMs('soon')).toBeNull(); }); + + it('A-01: clamps numeric and HTTP-date values above the one-hour cap', () => { + expect(MAX_RETRY_AFTER_MS).toBe(3_600_000); + expect(retryAfterMs('31536000')).toBe(MAX_RETRY_AFTER_MS); + expect(retryAfterMs('9'.repeat(400))).toBe(MAX_RETRY_AFTER_MS); + const now = 1_700_000_000_000; + const farFuture = new Date(now + 10 * 365 * 24 * 3600 * 1000).toUTCString(); + expect(retryAfterMs(farFuture, now)).toBe(MAX_RETRY_AFTER_MS); + // Exactly at the cap is not clamped; below it is untouched. + expect(retryAfterMs('3600')).toBe(3_600_000); + expect(retryAfterMs('3599')).toBe(3_599_000); + }); + + it('A-01: reports whether the parsed value was capped', () => { + expect(parseRetryAfter('31536000')).toMatchObject({ ms: MAX_RETRY_AFTER_MS, capped: true }); + expect(parseRetryAfter('2')).toMatchObject({ ms: 2_000, capped: false }); + expect(parseRetryAfter('soon')).toBeNull(); + expect(parseRetryAfter(null)).toBeNull(); + }); +}); + +describe('A-06 upstream_response_max_bytes parsing', () => { + it('A-06: accepts 0 and the 1 KiB..1 GiB range, ignoring everything else', () => { + expect(parseUpstreamResponseMaxBytes(null)).toBe(0); + expect(parseUpstreamResponseMaxBytes(undefined)).toBe(0); + expect(parseUpstreamResponseMaxBytes('0')).toBe(0); + expect(parseUpstreamResponseMaxBytes('1024')).toBe(1_024); + expect(parseUpstreamResponseMaxBytes(String(MAX_UPSTREAM_RESPONSE_BYTES))).toBe(MAX_UPSTREAM_RESPONSE_BYTES); + expect(parseUpstreamResponseMaxBytes('1023')).toBe(0); + expect(parseUpstreamResponseMaxBytes(String(MAX_UPSTREAM_RESPONSE_BYTES + 1))).toBe(0); + expect(parseUpstreamResponseMaxBytes('abc')).toBe(0); + expect(parseUpstreamResponseMaxBytes('-5')).toBe(0); + }); +}); + +describe('A-07 SSE frame boundaries', () => { + it('A-07: recognises every supported terminator shape', () => { + const terminators: Array<[string, number]> = [ + ['\n\n', 2], + ['\r\n\r\n', 4], + ['\r\n\n', 3], + ['\n\r\n', 3], + ['\r\r', 2], + ]; + for (const [terminator, length] of terminators) { + const buffer = Buffer.from(`data: {"a":1}${terminator}rest`); + const boundary = nextBoundary(buffer); + expect(boundary, JSON.stringify(terminator)).not.toBeNull(); + expect(boundary!.length).toBe(length); + expect(buffer.subarray(boundary!.index, boundary!.index + length).toString('utf8')).toBe(terminator); + } + expect(nextBoundary(Buffer.from('data: {"a":1}'))).toBeNull(); + }); + + it('A-07: strips x_opencode from a frame with two data lines and rewrites one canonical line', () => { + const frame = 'data: {"id":"x",\ndata: "x_opencode":{"session_id":"s"}}'; + const out = rewriteSseFrame(frame); + expect(out).not.toBe(frame); + expect(out).not.toContain('x_opencode'); + expect(out.split('\n')).toHaveLength(1); + expect(JSON.parse(out.slice(5).trim())).toEqual({ id: 'x' }); + }); + + it('A-07: leaves a frame without x_opencode byte-identical', () => { + const frame = 'event: message\ndata: {"id":"x","choices":[{"delta":"日本語"}]}'; + expect(rewriteSseFrame(frame)).toBe(frame); + expect(rewriteSseFrame('data: {"x_opencode"')).toBe('data: {"x_opencode"'); + }); }); describe('bodyReadFailureStatus (GW-03)', () => { diff --git a/tests/gateway-rotation.test.ts b/tests/gateway-rotation.test.ts index da71c71..de235e5 100644 --- a/tests/gateway-rotation.test.ts +++ b/tests/gateway-rotation.test.ts @@ -42,6 +42,49 @@ describe('orderProviders random', () => { expect(ids(ordered).sort()).toEqual(['a', 'b', 'c', 'd']); } }); + + it('A-15: produces the exact permutation for an injected RNG sequence', () => { + const candidates = [provider('a'), provider('b'), provider('c'), provider('d')]; + const rotation = orderProviders(candidates, 0, 'random', { random: () => 0 }); + // Fisher-Yates with random() === 0 swaps every index with 0: d,c,b,a -> b,c,d,a. + expect(ids(rotation.candidates)).toEqual(['b', 'c', 'd', 'a']); + + const sequence = [0.9, 0.2, 0.5]; + let index = 0; + const second = orderProviders(candidates, 0, 'random', { random: () => sequence[index++] ?? 0 }); + expect(ids(second.candidates)).toEqual(['c', 'b', 'a', 'd']); + }); + + it('A-15: still applies cooldown skipping and fallback with an injected RNG', () => { + const now = 1_000_000; + const warm = orderProviders( + [provider('warm'), provider('cool', { cooldownUntil: now + 5_000 })], + now, + 'random', + { random: () => 0 }, + ); + expect(warm.cooldownFallback).toBe(false); + expect(ids(warm.candidates)).toEqual(['warm']); + + const fallback = orderProviders( + [ + provider('late', { cooldownUntil: now + 60_000 }), + provider('soon', { cooldownUntil: now + 1_000 }), + ], + now, + 'random', + { random: () => 0 }, + ); + expect(fallback.cooldownFallback).toBe(true); + expect(ids(fallback.candidates)).toEqual(['soon', 'late']); + }); + + it('A-15: production default still uses Math.random and shuffles a copy', () => { + const candidates = [provider('a'), provider('b'), provider('c')]; + const rotation = orderProviders(candidates, 0, 'random'); + expect(ids(rotation.candidates).sort()).toEqual(['a', 'b', 'c']); + expect(ids(candidates)).toEqual(['a', 'b', 'c']); + }); }); describe('orderProviders cooldown handling', () => { diff --git a/tests/util-errors.test.ts b/tests/util-errors.test.ts new file mode 100644 index 0000000..af88f93 --- /dev/null +++ b/tests/util-errors.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import { + ApiError, + MAX_ERROR_MESSAGE_LENGTH, + isErrorType, + isRetryableStatus, + sanitizeErrorMessage, + scrubSecrets, + upstreamErrorFrom, +} from '../src/util/errors.js'; + +describe('isRetryableStatus (A-14)', () => { + it('A-14: treats every 5xx as retryable and keeps 408/409/425/429', () => { + for (const status of [500, 501, 502, 505, 507, 508, 510, 511, 599]) { + expect(isRetryableStatus(status), `status ${status}`).toBe(true); + } + expect(isRetryableStatus(408)).toBe(true); + expect(isRetryableStatus(409)).toBe(true); + expect(isRetryableStatus(425)).toBe(true); + expect(isRetryableStatus(429)).toBe(true); + expect(isRetryableStatus(529)).toBe(true); + }); + + it('A-14: keeps client errors and boundary statuses non-retryable', () => { + expect(isRetryableStatus(400)).toBe(false); + expect(isRetryableStatus(404)).toBe(false); + expect(isRetryableStatus(422)).toBe(false); + expect(isRetryableStatus(499)).toBe(false); + expect(isRetryableStatus(399)).toBe(false); + expect(isRetryableStatus(600)).toBe(false); + }); +}); + +describe('type validation (A-05)', () => { + it('A-05: only accepts the documented ErrorType union', () => { + expect(isErrorType('api_error')).toBe(true); + expect(isErrorType('rate_limit_error')).toBe(true); + expect(isErrorType('mystery_type')).toBe(false); + expect(isErrorType(7)).toBe(false); + expect(isErrorType(null)).toBe(false); + }); + + it('A-05: maps an unknown upstream type to api_error instead of casting it', () => { + const error = upstreamErrorFrom( + 400, + JSON.stringify({ type: 'error', error: { type: 'mystery_type', message: 'boom' } }), + 'p1', + ); + expect(error).toBeInstanceOf(ApiError); + expect(error.type).toBe('api_error'); + expect(error.message).toBe('boom'); + + const known = upstreamErrorFrom( + 400, + JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: 'bad' } }), + 'p1', + ); + expect(known.type).toBe('invalid_request_error'); + }); +}); + +describe('message clamping (A-05)', () => { + it('A-05: clamps a 200 kB upstream message to 500 chars after control-character stripping', () => { + const huge = `start${'a'.repeat(200_000)}end`; + const error = upstreamErrorFrom(500, JSON.stringify({ error: { message: huge } }), 'p1'); + expect(error.message.length).toBe(MAX_ERROR_MESSAGE_LENGTH); + expect(error.message.startsWith('start')).toBe(true); + expect(error.message).not.toContain('end'); + }); + + it('A-05: strips control characters from upstream bodies and defaults the message', () => { + const error = upstreamErrorFrom(502, 'line\u0000one\u0007two\nthree', 'p1'); + expect(error.message).toBe('lineonetwothree'); + expect(error.message).not.toMatch(/[\u0000-\u001F\u007F]/); + }); +}); + +describe('scrubSecrets (A-05)', () => { + it('A-05: replaces the configured provider key with [redacted]', () => { + const key = 'sk-live-super-secret-value'; + const text = `provider echoed Authorization: Bearer ${key} and said ${key}`; + const scrubbed = scrubSecrets(text, [key]); + expect(scrubbed).not.toContain(key); + expect(scrubbed).toContain('[redacted]'); + }); + + it('A-05: redacts credential-shaped tokens even without a configured secret', () => { + const scrubbed = scrubSecrets( + 'Bearer abcdef123456 sk-proj-abcdef123456 x-api-key: sk-other-123456 authorization=Bearer%20tok', + ); + expect(scrubbed).not.toContain('abcdef123456'); + expect(scrubbed).not.toContain('sk-proj-abcdef123456'); + expect(scrubbed).not.toContain('sk-other-123456'); + expect(scrubbed).toContain('[redacted]'); + }); + + it('A-05: sanitizeErrorMessage scrubs before clamping so a key cannot survive the cut', () => { + const key = 'sk-secret-that-sits-right-at-the-boundary'; + const text = `${'b'.repeat(MAX_ERROR_MESSAGE_LENGTH - 10)}${key}`; + const sanitized = sanitizeErrorMessage(text, [key]); + expect(sanitized.length).toBeLessThanOrEqual(MAX_ERROR_MESSAGE_LENGTH); + expect(sanitized).not.toContain(key); + expect(sanitized).not.toContain('sk-secret'); + }); + + it('A-05: upstreamErrorFrom scrubs the configured key from JSON and plain-text bodies', () => { + const key = 'sk-provider-9f8e7d6c'; + const json = upstreamErrorFrom( + 500, + JSON.stringify({ error: { message: `upstream rejected key ${key}` } }), + 'p1', + [key], + ); + expect(json.message).not.toContain(key); + expect(json.message).toContain('[redacted]'); + + const plain = upstreamErrorFrom(500, `raw body with ${key}`, 'p1', [key]); + expect(plain.message).not.toContain(key); + + const anthropic = upstreamErrorFrom( + 500, + JSON.stringify({ type: 'error', error: { type: 'overloaded_error', message: `key ${key}` } }), + 'p1', + [key], + ); + expect(anthropic.type).toBe('overloaded_error'); + expect(anthropic.message).not.toContain(key); + }); +}); \ No newline at end of file diff --git a/tests/util-upstream.test.ts b/tests/util-upstream.test.ts index ee18f41..925f1a8 100644 --- a/tests/util-upstream.test.ts +++ b/tests/util-upstream.test.ts @@ -48,6 +48,66 @@ describe('joinUrl', () => { expect(joinUrl('https://x.example/v1/', 'chat/completions')).toBe('https://x.example/v1/chat/completions'); expect(joinUrl('https://x.example', '/v1/models')).toBe('https://x.example/v1/models'); }); + + it('A-08: keeps a base query string and appends a path query with &', () => { + expect(joinUrl('https://host/v1?key=x', '/messages')).toBe('https://host/v1/messages?key=x'); + expect(joinUrl('https://host/v1?key=x', '/messages?beta=true')).toBe( + 'https://host/v1/messages?beta=true&key=x', + ); + expect(joinUrl('https://host/v1?', '/messages')).toBe('https://host/v1/messages'); + expect(joinUrl('https://host', '/messages?beta=true')).toBe('https://host/messages?beta=true'); + }); +}); + +describe('provider credential validation (A-10)', () => { + it('A-10: fails with a fixed 502 that never embeds an invalid key', async () => { + const hits: string[] = []; + const server = await listen((req, res) => { + hits.push(req.url ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + const key = 'sk-bad\u0001key'; + const error = await upstreamFetch({ + baseUrl: server.base, + apiKey: key, + path: '/chat/completions', + body: { model: 'm' }, + timeoutMs: 2_000, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ApiError); + expect((error as ApiError).status).toBe(502); + expect((error as ApiError).code).toBe('invalid_provider_credentials'); + expect((error as ApiError).message).toBe('Provider credentials are invalid'); + expect((error as ApiError).message).not.toContain('sk-bad'); + expect((error as ApiError).message).not.toContain('\u0001'); + // The malformed credential never reached the network. + expect(hits).toEqual([]); + }); + + it('A-10: strips CR/LF/NUL from the key before building the auth headers', async () => { + let captured: IncomingMessage['headers'] | null = null; + const server = await listen((req, res) => { + captured = req.headers; + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-abc\r\nx-injected: 1\0', + path: '/chat/completions', + body: { model: 'm' }, + timeoutMs: 2_000, + }); + await response.response.text(); + response.dispose(); + + expect(captured).not.toBeNull(); + expect(captured!['x-injected']).toBeUndefined(); + expect(captured!['authorization']).toBe('Bearer sk-abcx-injected: 1'); + expect(captured!['x-api-key']).toBe('sk-abcx-injected: 1'); + }); }); describe('upstreamFetch redirects', () => { From 148f84e48cdc674759cbab54223b23b8451d86b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Sun, 6 Dec 2026 22:28:21 +0700 Subject: [PATCH 2/6] fix(admin): validate credentials, guard SSRF/CSRF and fix sync accounting --- src/admin/auth.ts | 64 ++- src/admin/diagnostics.ts | 215 +++++++++ src/admin/models.ts | 50 ++- src/admin/providers.ts | 51 ++- src/admin/scheduler.ts | 136 ++++-- src/admin/settings.ts | 27 +- src/admin/stats.ts | 25 +- src/admin/sync.ts | 232 +++++++++- src/admin/util.ts | 65 ++- src/index.ts | 9 +- tests/admin-hardening.test.ts | 820 ++++++++++++++++++++++++++++++++++ tests/admin-scheduler.test.ts | 311 +++++++++++++ 12 files changed, 1910 insertions(+), 95 deletions(-) create mode 100644 src/admin/diagnostics.ts create mode 100644 tests/admin-hardening.test.ts create mode 100644 tests/admin-scheduler.test.ts diff --git a/src/admin/auth.ts b/src/admin/auth.ts index e66491f..4058efb 100644 --- a/src/admin/auth.ts +++ b/src/admin/auth.ts @@ -10,8 +10,15 @@ import { clearSessionCookie, createSession, resolveSession, setSessionCookie } f export const LOGIN_WINDOW_MS = 5 * 60 * 1000; export const LOGIN_MAX_ATTEMPTS = 10; -/** FEAT-08: global failure cap, so one botnet cannot hammer the login from many IPs. */ -export const LOGIN_GLOBAL_MAX_ATTEMPTS = 50; +/** + * FEAT-08/AD-21: process-wide failure cap. It stays well above the per-IP cap so a + * distributed bot cannot lock the operator out; 50 used to be reachable by a single + * attacker and turned the guard into a denial of service against the dashboard. + */ +export const LOGIN_GLOBAL_MAX_ATTEMPTS = 500; + +/** Methods whose execution must be same-origin when a dashboard session is present. */ +const MUTATING_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']); interface AttemptRecord { count: number; @@ -97,6 +104,50 @@ function pruneAttempts(): void { } } +/** + * AD-21: CSRF defence in depth on top of `SameSite=Lax`. A mutation is rejected when + * the browser says it is cross-site or when the `Origin` host differs from the host + * the request was addressed to (an explicitly configured `PUBLIC_URL` wins, because + * a TLS-terminating proxy may rewrite `Host`). + * + * A missing `Origin` (curl, the e2e suite, same-origin `fetch` without the header) is + * allowed; this guard is a veto, never an authentication bypass. + */ +export function isCrossSiteRequest(ctx: AppContext, request: FastifyRequest): boolean { + const fetchSite = request.headers['sec-fetch-site']; + const site = Array.isArray(fetchSite) ? fetchSite[0] : fetchSite; + if (typeof site === 'string' && site.trim().toLowerCase() === 'cross-site') return true; + + const originHeader = request.headers.origin; + const origin = Array.isArray(originHeader) ? originHeader[0] : originHeader; + if (typeof origin !== 'string' || origin.length === 0) return false; + + let originHost: string; + try { + originHost = new URL(origin).host.toLowerCase(); + } catch { + // `Origin: null` (sandboxed frame, data: URL) and junk have no usable host. + return true; + } + if (originHost.length === 0) return true; + return originHost !== expectedHost(ctx, request); +} + +function expectedHost(ctx: AppContext, request: FastifyRequest): string { + const publicUrl = ctx.config.publicUrl; + if (publicUrl) { + try { + const host = new URL(publicUrl).host.toLowerCase(); + if (host.length > 0) return host; + } catch { + /* fall back to the Host header */ + } + } + const hostHeader = request.headers.host; + const host = Array.isArray(hostHeader) ? hostHeader[0] : hostHeader; + return typeof host === 'string' ? host.toLowerCase() : ''; +} + /** `onRequest` hook: rejects unauthenticated requests with `401 unauthorized`. */ export function createAuthGuard(ctx: AppContext) { return async function authGuard(request: FastifyRequest, reply: FastifyReply): Promise { @@ -111,6 +162,15 @@ export function createAuthGuard(ctx: AppContext) { return; } request.adminSession = resolved.session; + // Only session-authenticated mutations are gated: the public login/logout/session + // routes returned above, so a legitimate cross-site login page keeps working. + if (MUTATING_METHODS.has(request.method) && isCrossSiteRequest(ctx, request)) { + audit(ctx, 'auth.csrf.rejected', null, `${request.method} ${normalizeAdminPath(request.url)}`, request); + await reply.status(403).send({ + error: { message: 'Cross-site request rejected', code: 'cross_site_request' }, + }); + return; + } ctx.repo.touchSession(resolved.session.id); }; } diff --git a/src/admin/diagnostics.ts b/src/admin/diagnostics.ts new file mode 100644 index 0000000..8d5e1fa --- /dev/null +++ b/src/admin/diagnostics.ts @@ -0,0 +1,215 @@ +/** + * AD-18: `GET /admin/api/diagnostics` — one self-check endpoint for operators. + * + * Reports what the background scheduler last did, what the storage engine looks + * like and a list of pass/warn checks (default password, empty catalog, clock + * skew, active cooldowns...). It never returns a secret: no key material, no + * session ids and no upstream credentials. + */ +import { statSync } from 'node:fs'; +import type { AppContext } from '../core/context.js'; +import { verifyDashboardPassword } from '../core/seed.js'; +import { SCHEMA_VERSION } from '../db/schema.js'; +import { ADMIN_VERSION } from './util.js'; +import { getSchedulerStatus, type SchedulerStatus } from './scheduler.js'; + +export type DiagnosticStatus = 'ok' | 'warn' | 'fail'; + +export interface DiagnosticCheck { + id: string; + status: DiagnosticStatus; + detail: string; +} + +export interface DiagnosticsReport { + scheduler: SchedulerStatus; + storage: { + dbPath: string; + walSizeBytes: number; + dbSizeBytes: number; + busyTimeoutMs: number; + logRows: number; + attemptRows: number; + sessionRows: number; + oldestLogTs: number | null; + }; + checks: DiagnosticCheck[]; +} + +/** Schema generation this build understands, mirrored by `PRAGMA user_version`. */ +export const EXPECTED_SCHEMA_USER_VERSION = SCHEMA_VERSION; +/** Tables a usable database must have; a missing one means a partial/foreign file. */ +const REQUIRED_TABLES = [ + 'settings', + 'providers', + 'models', + 'api_keys', + 'request_logs', + 'request_attempts', + 'sessions', + 'audit_logs', +] as const; +/** Tolerated difference between the wall clock and the newest recorded timestamp. */ +export const CLOCK_SKEW_TOLERANCE_MS = 60_000; + +function queryNumber(ctx: AppContext, sql: string): number | null { + try { + const row = ctx.db.db.prepare(sql).get() as Record | undefined; + if (!row) return null; + const value = Object.values(row)[0]; + if (value === null || value === undefined) return null; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; + } catch { + return null; + } +} + +/** True when `sqlite_master` knows about `table` (partial/foreign files answer false). */ +function tableExists(ctx: AppContext, table: string): boolean { + try { + const row = ctx.db.db + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?") + .get(table) as Record | undefined; + return row !== undefined; + } catch { + return false; + } +} + +/** + * Runs a repository read, falling back when the database cannot answer it (missing + * table, foreign file). Diagnostics must describe a broken database, not fail on it. + */ +function safeRead(read: () => T, fallback: T): T { + try { + return read(); + } catch { + return fallback; + } +} + +function fileSize(path: string): number { + try { + return statSync(path).size; + } catch { + return 0; + } +} + +function busyTimeoutMs(ctx: AppContext): number { + return queryNumber(ctx, 'PRAGMA busy_timeout') ?? 0; +} + +function newestRecordedTs(ctx: AppContext): number | null { + const logTs = queryNumber(ctx, 'SELECT MAX(ts) AS c FROM request_logs'); + const auditTs = queryNumber(ctx, 'SELECT MAX(ts) AS c FROM audit_logs'); + const newest = Math.max(logTs ?? 0, auditTs ?? 0); + return newest > 0 ? newest : null; +} + +function buildChecks(ctx: AppContext): DiagnosticCheck[] { + const checks: DiagnosticCheck[] = []; + const now = Date.now(); + + // 1. Default dashboard password. + const defaultPasswordInUse = safeRead( + () => verifyDashboardPassword(ctx, ctx.config.defaultDashboardPassword), + false, + ); + checks.push({ + id: 'password.default', + status: defaultPasswordInUse ? 'warn' : 'ok', + detail: defaultPasswordInUse + ? 'The default dashboard password is still in use; change it in Settings > Security' + : 'The dashboard password is not the built-in default', + }); + + // 2. Enabled provider. The reads below are guarded: a database missing a table (or + // written by a foreign build) must still produce a report instead of a 500 — that is + // exactly the situation this endpoint exists to diagnose. + const providers = safeRead(() => ctx.repo.listProviders(), []); + const enabledProviders = providers.filter((provider) => provider.enabled); + checks.push({ + id: 'providers.enabled', + status: enabledProviders.length > 0 ? 'ok' : 'warn', + detail: + enabledProviders.length > 0 + ? `${enabledProviders.length} enabled provider(s)` + : 'No enabled provider: the gateway cannot serve any request', + }); + + // 3. Active gateway key. + const keysActive = safeRead(() => ctx.repo.countActiveApiKeys(), 0); + checks.push({ + id: 'keys.active', + status: keysActive > 0 ? 'ok' : 'warn', + detail: keysActive > 0 ? `${keysActive} active gateway key(s)` : 'No active gateway key', + }); + + // 4. Enabled model. + const modelsEnabled = safeRead(() => ctx.repo.enabledModelIds().length, 0); + checks.push({ + id: 'models.enabled', + status: modelsEnabled > 0 ? 'ok' : 'warn', + detail: modelsEnabled > 0 ? `${modelsEnabled} enabled model(s)` : 'No enabled model', + }); + + // 5. Schema generation vs this build, plus the tables a usable file must contain. + const userVersion = queryNumber(ctx, 'PRAGMA user_version') ?? 0; + const missingTables = REQUIRED_TABLES.filter((table) => !tableExists(ctx, table)); + const schemaOk = userVersion === EXPECTED_SCHEMA_USER_VERSION && missingTables.length === 0; + checks.push({ + id: 'version.schema', + status: schemaOk ? 'ok' : 'warn', + detail: schemaOk + ? `schema user_version=${userVersion}, api ${ADMIN_VERSION}` + : missingTables.length > 0 + ? `schema user_version=${userVersion} is missing table(s): ${missingTables.join(', ')}` + : `schema user_version=${userVersion} (expected ${EXPECTED_SCHEMA_USER_VERSION}) for api ${ADMIN_VERSION}; docs may be stale`, + }); + + // 6. Clock skew against the newest recorded timestamp. + const newest = newestRecordedTs(ctx); + const skewed = newest !== null && newest > now + CLOCK_SKEW_TOLERANCE_MS; + checks.push({ + id: 'clock.skew', + status: skewed ? 'warn' : 'ok', + detail: skewed + ? `Newest recorded timestamp is ${Math.round((newest - now) / 1000)}s in the future; check the system clock` + : 'System clock is consistent with recorded timestamps', + }); + + // 7. Providers currently cooling down. + const cooling = providers.filter( + (provider) => provider.cooldownUntil !== null && provider.cooldownUntil > now, + ); + checks.push({ + id: 'providers.cooldown', + status: cooling.length === 0 ? 'ok' : 'warn', + detail: + cooling.length === 0 + ? 'No provider is cooling down' + : `${cooling.length} provider(s) cooling down: ${cooling.map((provider) => provider.id).join(', ')}`, + }); + + return checks; +} + +export function buildDiagnostics(ctx: AppContext): DiagnosticsReport { + const storage: DiagnosticsReport['storage'] = { + dbPath: ctx.config.dbPath, + walSizeBytes: fileSize(`${ctx.config.dbPath}-wal`), + dbSizeBytes: fileSize(ctx.config.dbPath), + busyTimeoutMs: busyTimeoutMs(ctx), + logRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM request_logs') ?? 0, + attemptRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM request_attempts') ?? 0, + sessionRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM sessions') ?? 0, + oldestLogTs: queryNumber(ctx, 'SELECT MIN(ts) AS c FROM request_logs'), + }; + return { + scheduler: getSchedulerStatus(ctx), + storage, + checks: buildChecks(ctx), + }; +} diff --git a/src/admin/models.ts b/src/admin/models.ts index e066fef..f7fd3d6 100644 --- a/src/admin/models.ts +++ b/src/admin/models.ts @@ -21,6 +21,7 @@ import { import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT, + syncAllEnabledProviders, syncFailureMessage, syncProviderModels, } from './sync.js'; @@ -38,7 +39,9 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo scope.get('/models', async () => ({ models: ctx.repo.listModels(), syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + // AD-20: an empty value means "no syncing provider" (a deleted provider is + // cleared to ''), which the dashboard must render as null. + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, providers: ctx.repo.listProviders().map((provider) => ({ id: provider.id, name: provider.name })), })); @@ -140,13 +143,23 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo scope.post('/models/sync', async (request) => { const body = jsonBody(request); const requestedId = asString(body.providerId); - const provider = requestedId - ? ctx.repo.getProvider(requestedId) - : ctx.repo.listProviders().find((candidate) => candidate.enabled); - if (!provider) { - if (requestedId) throw new HttpError(404, 'provider_not_found', `Provider "${requestedId}" not found`); - fail(400, 'no_provider', 'No provider configured. Add one in the Providers tab first.'); + if (requestedId === null) { + // AD-17: a bare "sync" refreshes every enabled provider, not just the first. + if (ctx.repo.listProviders().every((candidate) => !candidate.enabled)) { + fail(400, 'no_provider', 'No provider configured. Add one in the Providers tab first.'); + } + const all = await syncAllEnabledProviders(ctx); + audit( + ctx, + 'model.sync', + null, + `providers=${all.providers.length} failed=${all.providers.filter((outcome) => !outcome.ok).length} added=${all.added} updated=${all.updated} removed=${all.removed} total=${all.total}`, + request, + ); + return all; } + const provider = ctx.repo.getProvider(requestedId); + if (!provider) throw new HttpError(404, 'provider_not_found', `Provider "${requestedId}" not found`); let result; try { result = await syncProviderModels(ctx, provider); @@ -160,19 +173,24 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo ); throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } - ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); - ctx.events.emitProvider({ - providerId: provider.id, - state: 'ok', - status: 200, - message: null, - ts: Date.now(), - }); + // AD-16: an unrecognized upstream catalog is a warning, not a healthy round-trip. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } audit( ctx, 'model.sync', provider.id, - `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + result.warning !== undefined + ? `warning=${result.warning}` + : `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, request, ); return result; diff --git a/src/admin/providers.ts b/src/admin/providers.ts index 1ecb6ff..0de4a09 100644 --- a/src/admin/providers.ts +++ b/src/admin/providers.ts @@ -10,6 +10,7 @@ import { asBool, asInt, asString, + assertApiKey, assertNoControlChars, assertPublicProviderUrl, audit, @@ -19,7 +20,14 @@ import { maskApiKey, requireString, } from './util.js'; -import { probeAndRecord, probeProvider, recordProbeSuccess, syncFailureMessage, syncProviderModels } from './sync.js'; +import { + SETTING_MODELS_SYNC_PROVIDER_ID, + probeAndRecord, + probeProvider, + recordProbeSuccess, + syncFailureMessage, + syncProviderModels, +} from './sync.js'; export interface ProviderView { id: string; @@ -107,6 +115,9 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); const apiKey = asString(body.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); + // AD-13: reject control/non-ASCII/over-long keys before they reach `fetch`, whose + // thrown message would otherwise echo the raw key. + assertApiKey(apiKey); const enabled = body.enabled === undefined ? true : asBool(body.enabled); if (enabled === null) fail(400, 'invalid_request', 'enabled must be true or false'); const priority = body.priority === undefined ? 100 : priorityFrom(body.priority); @@ -140,6 +151,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (body.apiKey !== undefined) { const apiKey = asString(body.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey must be a non-empty string'); + assertApiKey(apiKey); patch.apiKey = apiKey; changed.push('apiKey'); } @@ -170,7 +182,17 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): const id = (request.params as { id: string }).id; const current = loadProvider(ctx, id); // AD-02: the provider's synced models go with it (no FK constraints exist). - const { modelsRemoved } = ctx.repo.deleteProviderWithModels(id); + // AD-20: `models_sync_provider_id` must not keep pointing at the deleted provider; + // clearing it happens in the same transaction as the delete. + const { modelsRemoved } = ctx.repo.transaction(() => { + const removed = ctx.repo.deleteProviderWithModels(id); + if (ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) === id) { + // The settings table has no delete helper; the empty value reads as `null` in + // every admin view (`GET /admin/api/models`, `/settings`, `/bootstrap`). + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, ''); + } + return removed; + }); audit(ctx, 'provider.delete', id, `${current.name} modelsRemoved=${modelsRemoved}`, request); return { ok: true, modelsRemoved }; }); @@ -182,6 +204,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): const baseUrl = httpBaseUrl(body.baseUrl); assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); let apiKey = asString(body.apiKey); + if (apiKey) assertApiKey(apiKey); if (!apiKey) { const id = asString(body.id); if (!id) fail(400, 'invalid_request', 'apiKey is required'); @@ -254,19 +277,25 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): ); throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } - ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); - ctx.events.emitProvider({ - providerId: provider.id, - state: 'ok', - status: 200, - message: null, - ts: Date.now(), - }); + // AD-16: an unrecognized upstream catalog is a warning, not a success — never + // record it as a healthy provider round-trip. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } audit( ctx, 'provider.sync', provider.id, - `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + result.warning !== undefined + ? `warning=${result.warning}` + : `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, request, ); return result; diff --git a/src/admin/scheduler.ts b/src/admin/scheduler.ts index 5e2e15f..c56d0e0 100644 --- a/src/admin/scheduler.ts +++ b/src/admin/scheduler.ts @@ -1,17 +1,18 @@ /** * Background maintenance for the admin layer. * - * - syncs provider models on the `model_sync_interval_ms` cadence when - * `auto_sync_models` is enabled and an enabled provider exists; + * - syncs every enabled provider's models on the `model_sync_interval_ms` cadence + * when `auto_sync_models` is enabled (AD-17); * - probes providers whose cooldown expired and clears it when they answer again - * (FEAT-02), so a rate-limited provider is not skipped until the next sync; + * (FEAT-02), so a rate-limited provider is not skipped until the next sync. A + * cursor rotates over the cooling candidates so a large tail is not starved; * - purges expired dashboard sessions every 10 minutes. * * All timers are `unref()`ed and every callback is wrapped so nothing throws * out of an interval. The returned function stops the scheduler cleanly. */ import type { AppContext } from '../core/context.js'; -import { probeAndRecord, syncProviderModels } from './sync.js'; +import { probeAndRecord, syncAllEnabledProviders } from './sync.js'; const MIN_SYNC_INTERVAL_MS = 30_000; const TICK_MS = 30_000; @@ -22,11 +23,66 @@ const COOLDOWN_PROBES_PER_TICK = 3; /** A recovery probe only needs to prove the provider answers `GET /models`. */ const COOLDOWN_PROBE_TIMEOUT_MS = 5_000; +export interface SchedulerStatus { + running: boolean; + lastSyncAt: number | null; + lastSyncError: string | null; + /** Milliseconds until the next scheduled sync, or null when it is not scheduled. */ + nextSyncInMs: number | null; + lastRecoveryAt: number | null; +} + +/** + * AD-18: `/admin/api/diagnostics` reports what the scheduler last did. The state is + * process-wide (one scheduler per process) and reset by every `startScheduler`. + */ +let runtime: { + running: boolean; + startedAt: number; + lastSyncAt: number | null; + lastSyncError: string | null; + lastRecoveryAt: number | null; +} = { running: false, startedAt: 0, lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; + +/** Test/ops helper: forget the observed scheduler state. */ +export function resetSchedulerStatus(): void { + runtime = { running: false, startedAt: 0, lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; +} + +export function getSchedulerStatus(ctx: AppContext): SchedulerStatus { + const configured = ctx.repo.getInt('model_sync_interval_ms', 300_000); + const intervalMs = Math.max(MIN_SYNC_INTERVAL_MS, Number.isFinite(configured) ? configured : 300_000); + const autoSync = ctx.repo.getBool('auto_sync_models'); + let nextSyncInMs: number | null = null; + if (runtime.running && autoSync) { + // Before the first sync the initial delay is the next attempt; afterwards the + // regular interval counts from the last successful/attempted sync. + const base = runtime.lastSyncAt ?? runtime.startedAt; + const nextAt = base + (runtime.lastSyncAt === null ? INITIAL_SYNC_DELAY_MS : intervalMs); + nextSyncInMs = Math.max(0, nextAt - Date.now()); + } + return { + running: runtime.running, + lastSyncAt: runtime.lastSyncAt, + lastSyncError: runtime.lastSyncError, + nextSyncInMs, + lastRecoveryAt: runtime.lastRecoveryAt, + }; +} + export function startScheduler(ctx: AppContext): () => void { let stopped = false; let syncing = false; let recovering = false; let lastSyncAt = 0; + /** + * AD-19: round-robin cursor over the cooling candidates. Providers probed in the + * current round are remembered by id, so the tail is reached on the next tick and + * no provider is probed twice while another has not been tried yet. + */ + let probedThisRound = new Set(); + + runtime = { running: true, startedAt: Date.now(), lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; const log = (level: 'info' | 'warn', message: string, extra?: Record): void => { try { @@ -45,23 +101,25 @@ export function startScheduler(ctx: AppContext): () => void { const intervalMs = Math.max(MIN_SYNC_INTERVAL_MS, Number.isFinite(configured) ? configured : 300_000); const now = Date.now(); if (now - lastSyncAt < intervalMs) return; - const provider = ctx.repo.listProviders().find((candidate) => candidate.enabled); - if (!provider) return; + if (ctx.repo.listProviders().every((provider) => !provider.enabled)) return; syncing = true; lastSyncAt = now; - const result = await syncProviderModels(ctx, provider); + runtime.lastSyncAt = now; + // AD-17: sync every enabled provider, not just the first one in the list. + const result = await syncAllEnabledProviders(ctx); + runtime.lastSyncError = null; log('info', 'auto-synced provider models', { - providerId: result.providerId, + providers: result.providers.length, + failed: result.providers.filter((outcome) => !outcome.ok).length, added: result.added, updated: result.updated, removed: result.removed, total: result.total, - latencyMs: result.latencyMs, }); } catch (error) { - log('warn', 'scheduled model sync failed', { - error: error instanceof Error ? error.message : String(error), - }); + const message = error instanceof Error ? error.message : String(error); + runtime.lastSyncError = message; + log('warn', 'scheduled model sync failed', { error: message }); } finally { syncing = false; } @@ -84,27 +142,46 @@ export function startScheduler(ctx: AppContext): () => void { provider.status === 'cooldown' && provider.cooldownUntil !== null && provider.cooldownUntil <= now, - ) - .slice(0, COOLDOWN_PROBES_PER_TICK); - if (cooled.length === 0) return; + ); + if (cooled.length === 0) { + probedThisRound.clear(); + return; + } + // Skip candidates already probed in this round; start a new round once every + // current candidate has had a turn. + const remaining = cooled.filter((provider) => !probedThisRound.has(provider.id)); + if (remaining.length === 0) { + probedThisRound.clear(); + } + const batch = (remaining.length === 0 ? cooled : remaining).slice(0, COOLDOWN_PROBES_PER_TICK); + for (const provider of batch) probedThisRound.add(provider.id); recovering = true; - for (const provider of cooled) { + for (const provider of batch) { if (stopped) return; - const probe = await probeAndRecord(ctx, provider, { - cooldownMs: 0, - timeoutMs: COOLDOWN_PROBE_TIMEOUT_MS, - log: (detail) => log('warn', 'cooldown recovery probe failed', { providerId: provider.id, detail }), - }); - if (probe.ok) { - ctx.repo.updateProvider(provider.id, { cooldownUntil: null, status: 'ok' }); - ctx.events.emitProvider({ + try { + const probe = await probeAndRecord(ctx, provider, { + cooldownMs: 0, + timeoutMs: COOLDOWN_PROBE_TIMEOUT_MS, + log: (detail) => log('warn', 'cooldown recovery probe failed', { providerId: provider.id, detail }), + }); + if (probe.ok) { + ctx.repo.updateProvider(provider.id, { cooldownUntil: null, status: 'ok' }); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: probe.status, + message: null, + ts: Date.now(), + }); + runtime.lastRecoveryAt = Date.now(); + log('info', 'provider recovered from cooldown', { providerId: provider.id, latencyMs: probe.latencyMs }); + } + } catch (error) { + // One unroutable row (SSRF guard, driver error) must not abort the sweep. + log('warn', 'cooldown recovery probe failed', { providerId: provider.id, - state: 'ok', - status: probe.status, - message: null, - ts: Date.now(), + detail: error instanceof Error ? error.message : String(error), }); - log('info', 'provider recovered from cooldown', { providerId: provider.id, latencyMs: probe.latencyMs }); } } } catch (error) { @@ -143,6 +220,7 @@ export function startScheduler(ctx: AppContext): () => void { return () => { if (stopped) return; stopped = true; + runtime.running = false; clearInterval(syncTimer); clearInterval(purgeTimer); clearTimeout(initialTimer); diff --git a/src/admin/settings.ts b/src/admin/settings.ts index 5347f4e..908dc84 100644 --- a/src/admin/settings.ts +++ b/src/admin/settings.ts @@ -21,6 +21,7 @@ import { audit, fail, jsonBody, + queryInt, sanitizeSettings, settingTimestamp, } from './util.js'; @@ -28,7 +29,14 @@ import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT } from './syn const BOOL_SETTINGS = new Set(['auto_sync_models', 'model_allow_unknown']); -const INT_SETTINGS: Record = { +interface IntSetting { + min: number; + max: number; + /** When set, values below it are only valid as exactly `0` (an "off" sentinel). */ + zeroOrMin?: number; +} + +const INT_SETTINGS: Record = { max_retries: { min: 1, max: 10 }, provider_cooldown_ms: { min: 0, max: 3_600_000 }, request_timeout_ms: { min: 1_000, max: 3_600_000 }, @@ -37,6 +45,8 @@ const INT_SETTINGS: Record = { audit_retention_days: { min: 1, max: 3_650 }, // GW-05: per-chunk SSE idle deadline, well below the total request timeout. stream_idle_timeout_ms: { min: 1_000, max: 3_600_000 }, + // 0 means "unlimited"; any real cap must be at least 1 KiB so a normal response fits. + upstream_response_max_bytes: { min: 0, max: 1_073_741_824, zeroOrMin: 1_024 }, }; const ROTATION_STRATEGIES = new Set(['round-robin', 'priority', 'random']); @@ -62,6 +72,13 @@ function validateSetting(key: string, value: unknown): string | null { if (range) { const parsed = asInt(value); if (parsed === null) fail(400, 'invalid_request', `${key} must be an integer`); + if (range.zeroOrMin !== undefined && parsed !== 0 && parsed < range.zeroOrMin) { + fail( + 400, + 'invalid_request', + `${key} must be 0 (unlimited) or between ${range.zeroOrMin} and ${range.max}`, + ); + } if (parsed < range.min || parsed > range.max) { fail(400, 'invalid_request', `${key} must be between ${range.min} and ${range.max}`); } @@ -115,7 +132,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): sessionsActive: sessions.length, }, syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, }; }); @@ -215,8 +232,10 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): }); scope.get('/audit', async (request) => { - const requested = asInt((request.query as Record).limit) ?? 100; - const limit = Math.min(Math.max(requested, 1), 500); + // AD-22: `limit=abc`/`limit=-5` used to fall back silently; `/logs` rejects them, + // so both routes now share the documented 1..500 range. + const query = request.query as Record; + const limit = query.limit === undefined ? 100 : queryInt(query.limit, 'limit', 1, 500); return { items: ctx.repo.listAudit(limit) }; }); } diff --git a/src/admin/stats.ts b/src/admin/stats.ts index 205c708..e048078 100644 --- a/src/admin/stats.ts +++ b/src/admin/stats.ts @@ -10,13 +10,14 @@ import type { SessionRow } from '../types.js'; import { formatSseJson } from '../util/sse.js'; import { ADMIN_VERSION, - asInt, buildHealth, + queryInt, queryOf, sanitizeSettings, settingTimestamp, activeKeyCount, } from './util.js'; +import { buildDiagnostics } from './diagnostics.js'; import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT } from './sync.js'; interface WindowConfig { @@ -88,11 +89,11 @@ export function eventStreamAuthorized(ctx: AppContext, session: SessionRow | nul /** Per-client cap on frames buffered while `drain` is pending. */ const EVENTS_QUEUE_LIMIT = 256; -function cachedOverview(ctx: AppContext, key: string, config: WindowConfig): StatsOverview { +function cachedOverview(ctx: AppContext, key: string, config: WindowConfig, activeRequests: number): StatsOverview { const now = Date.now(); const cached = statsCache.get(key); if (cached && now - cached.at < STATS_CACHE_TTL_MS) return cached.overview; - const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, getActiveRequests()); + const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, activeRequests); statsCache.set(key, { at: now, overview }); return overview; } @@ -137,22 +138,30 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo modelCount: models.length, keyCount: keys.length, syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, activeRequests: getActiveRequests(), settings: sanitizeSettings(ctx.repo.allSettings()).settings, }; }); + // AD-18: single self-check endpoint for operators; session-protected, `limit`-free. + scope.get('/diagnostics', async () => buildDiagnostics(ctx)); + scope.get('/stats', async (request) => { const { key, config } = windowFrom(request); - const overview = cachedOverview(ctx, key, config); + // AD-14: one snapshot of the live counter feeds both the body and `health`, so a + // cached aggregate can never disagree with the live field inside one response. + const activeRequests = getActiveRequests(); + const overview = cachedOverview(ctx, key, config, activeRequests); // `overview` already carries requestsLast60s/errorsLast60s from statsOverview. - return { ...overview, health: buildHealth(ctx), window: key }; + return { ...overview, activeRequests, health: buildHealth(ctx, activeRequests), window: key }; }); scope.get('/activity', async (request) => { - const requested = asInt(queryOf(request).limit) ?? 20; - const limit = Math.min(Math.max(requested, 1), 100); + // AD-22: reject junk/out-of-range limits like `/logs` does (documented 1..500) + // instead of silently clamping them. + const query = queryOf(request); + const limit = query.limit === undefined ? 20 : queryInt(query.limit, 'limit', 1, 500); const now = Date.now(); const logItems = ctx.repo.listLogs({ limit }).rows.map((row) => ({ diff --git a/src/admin/sync.ts b/src/admin/sync.ts index 214b73d..6631f0c 100644 --- a/src/admin/sync.ts +++ b/src/admin/sync.ts @@ -7,7 +7,7 @@ import type { ProviderRow } from '../types.js'; import { upstreamErrorFrom } from '../util/errors.js'; import { extractModels, type NormalizedModel } from '../util/models.js'; import { readJsonBody, upstreamFetch } from '../util/upstream.js'; -import { assertPublicProviderUrl } from './util.js'; +import { HttpError, assertPublicProviderUrl } from './util.js'; export const SYNC_TIMEOUT_MS = 20_000; @@ -25,6 +25,11 @@ export interface ProviderProbe { status: number; latencyMs: number; models: NormalizedModel[]; + /** + * AD-16: true when the 2xx body contained a recognizable model array, even an + * empty one. `false` means `{}`/HTML/`{data:null}` and must not prune the catalog. + */ + catalogLocated: boolean; /** Client-safe failure message ('' on success); never contains the response body. */ error: string; /** Server-side detail (upstream body excerpt); never returned to clients. */ @@ -40,6 +45,30 @@ export interface SyncResult { syncedAt: number; /** Extra: upstream `/models` round-trip measured for this sync. */ latencyMs: number; + /** + * AD-16: present when the upstream answered 2xx without a recognizable model + * list. The catalog is left untouched and `models_synced_at` is not advanced. + */ + warning?: string; +} + +/** Client-safe warning for an upstream 2xx body that is not a model list. */ +export const UNRECOGNIZED_CATALOG_WARNING = + 'Upstream returned no recognizable model list; the synced catalog was left unchanged'; + +/** + * AD-16: separates "explicit empty catalog" (prune as usual) from "unrecognized + * payload" (`{}`, HTML, `{data:null}`), which must never wipe synced rows. + */ +function locateModels(payload: unknown): { models: NormalizedModel[]; located: boolean } { + if (Array.isArray(payload)) return { models: extractModels(payload), located: true }; + if (payload !== null && typeof payload === 'object') { + const record = payload as Record; + if (Array.isArray(record.data) || Array.isArray(record.models)) { + return { models: extractModels(payload), located: true }; + } + } + return { models: extractModels(payload), located: false }; } /** Client-facing probe failure message — deliberately generic (no body echo). */ @@ -53,8 +82,8 @@ export function syncFailureMessage(providerName: string): string { } /** Detailed upstream error text; kept for logs only, never sent to clients. */ -function errorMessageFrom(status: number, body: string, baseUrl: string): string { - return upstreamErrorFrom(status, body, baseUrl).message; +function errorMessageFrom(status: number, body: string, baseUrl: string, secrets: readonly string[] = []): string { + return upstreamErrorFrom(status, body, baseUrl, secrets).message; } /** GETs `{baseUrl}/models` and reports success, latency and parsed models. */ @@ -71,33 +100,48 @@ export async function probeProvider( method: 'GET', timeoutMs, }); - const latencyMs = Date.now() - started; - if (!response.ok) { - let body = ''; - try { - body = await response.response.text(); - response.dispose(); - } catch { - body = ''; + // AD-15: the body read can throw (aborted socket, bad encoding); `dispose()` must + // still run so the abort/timeout machinery is released instead of leaking. + try { + const latencyMs = Date.now() - started; + if (!response.ok) { + let body = ''; + try { + body = await response.response.text(); + } catch { + body = ''; + } + return { + ok: false, + status: response.status, + latencyMs, + models: [], + catalogLocated: false, + error: probeFailureMessage(response.status), + detail: errorMessageFrom(response.status, body, credentials.baseUrl, [credentials.apiKey]), + }; } + const payload = await readJsonBody(response.response); + const located = locateModels(payload); return { - ok: false, + ok: true, status: response.status, latencyMs, - models: [], - error: probeFailureMessage(response.status), - detail: errorMessageFrom(response.status, body, credentials.baseUrl), + models: located.models, + catalogLocated: located.located, + error: '', + detail: null, }; + } finally { + response.dispose(); } - const payload = await readJsonBody(response.response); - response.dispose(); - return { ok: true, status: response.status, latencyMs, models: extractModels(payload), error: '', detail: null }; } catch (error) { return { ok: false, status: 0, latencyMs: Date.now() - started, models: [], + catalogLocated: false, error: probeFailureMessage(0), detail: error instanceof Error ? error.message : String(error), }; @@ -157,6 +201,9 @@ export async function probeAndRecord( timeoutMs?: number; }, ): Promise { + // AD-03: the scheduler probes stored rows directly, so the SSRF guard lives on the + // shared path instead of only on the routes. + assertPublicProviderUrl(provider.baseUrl, ctx.config.providerAllowPrivateHosts); const probe = await probeProvider( { baseUrl: provider.baseUrl, apiKey: provider.apiKey }, options.timeoutMs, @@ -192,6 +239,25 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) throw new Error(syncFailureMessage(provider.name)); } + if (!probe.catalogLocated) { + // AD-16: a 2xx without a model array (`{}`, HTML, `{data:null}`) is a failed sync, + // not an empty catalog: keep every row and leave `models_synced_at` untouched. + ctx.logger?.warn?.( + { providerId: provider.id, status: probe.status, detail: probe.detail }, + 'provider model sync returned an unrecognized catalog', + ); + return { + added: 0, + updated: 0, + removed: 0, + total: 0, + providerId: provider.id, + syncedAt: Date.now(), + latencyMs: probe.latencyMs, + warning: UNRECOGNIZED_CATALOG_WARNING, + }; + } + const syncedAt = Date.now(); // OPT-10: the caller already holds the row snapshot, so each upsert skips its own // `getModel`; the whole write set is one transaction (no partially synced catalog). @@ -246,3 +312,133 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) latencyMs: probe.latencyMs, }; } + +/* ------------------------------------------------------ multi-provider sync (AD-17) */ + +/** Per-provider outcome of `syncAllEnabledProviders`. */ +export interface ProviderSyncOutcome { + providerId: string; + providerName: string; + ok: boolean; + /** Set when the upstream answered 2xx without a recognizable model list. */ + warning: string | null; + /** Client-safe failure message; the upstream detail stays in the server log. */ + error: string | null; + added: number; + updated: number; + removed: number; + total: number; + latencyMs: number; +} + +export interface SyncAllResult extends SyncResult { + /** Additive per-provider report; one entry per enabled provider, in list order. */ + providers: ProviderSyncOutcome[]; +} + +/** Two concurrent upstream round-trips keep a big catalog calm without serializing it. */ +export const SYNC_ALL_CONCURRENCY = 2; + +/** + * AD-17: `runModelSync`/`maybeSync` used to sync only the first enabled provider, so + * multi-provider deployments kept stale catalogs for every other one. Each provider + * is synced with the same single-provider path (one transaction each) and a failure + * for one provider never aborts the others. + */ +export async function syncAllEnabledProviders( + ctx: AppContext, + options: { concurrency?: number } = {}, +): Promise { + const providers = ctx.repo.listProviders().filter((provider) => provider.enabled); + const concurrency = Math.max( + 1, + Math.min(options.concurrency ?? SYNC_ALL_CONCURRENCY, providers.length || 1), + ); + const outcomes: ProviderSyncOutcome[] = []; + let cursor = 0; + + const worker = async (): Promise => { + while (cursor < providers.length) { + const index = cursor; + cursor += 1; + const provider = providers[index]!; + try { + const result = await syncProviderModels(ctx, provider); + outcomes[index] = { + providerId: provider.id, + providerName: provider.name, + ok: result.warning === undefined, + warning: result.warning ?? null, + error: null, + added: result.added, + updated: result.updated, + removed: result.removed, + total: result.total, + latencyMs: result.latencyMs, + }; + // Parity with the single-provider sync route: a healthy round-trip refreshes + // the provider's health counters, and an unrecognized catalog does not. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } + } catch (error) { + // The SSRF guard raises an authored HttpError (client-safe); every other + // failure is reported with the generic sync message and logged in detail. + const message = error instanceof HttpError ? error.message : syncFailureMessage(provider.name); + ctx.logger?.warn?.( + { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, + 'provider model sync failed', + ); + outcomes[index] = { + providerId: provider.id, + providerName: provider.name, + ok: false, + warning: null, + error: message, + added: 0, + updated: 0, + removed: 0, + total: 0, + latencyMs: 0, + }; + } + } + }; + + await Promise.all(Array.from({ length: concurrency }, () => worker())); + + const succeeded = outcomes.filter((outcome) => outcome.ok); + const added = outcomes.reduce((sum, outcome) => sum + outcome.added, 0); + const updated = outcomes.reduce((sum, outcome) => sum + outcome.updated, 0); + const removed = outcomes.reduce((sum, outcome) => sum + outcome.removed, 0); + const total = outcomes.reduce((sum, outcome) => sum + outcome.total, 0); + const syncedAt = Date.now(); + + // A single enabled provider keeps the existing `models_sync_provider_id` semantics + // (written by `syncProviderModels` itself). With several providers no single id is + // meaningful, so the stamp is refreshed and the provider attribution cleared. + if (providers.length > 1 && succeeded.length > 0) { + ctx.repo.transaction(() => { + ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, succeeded.length === 1 ? succeeded[0]!.providerId : ''); + }); + } + + return { + added, + updated, + removed, + total, + providerId: succeeded.length === 1 ? succeeded[0]!.providerId : '', + syncedAt, + latencyMs: outcomes.reduce((max, outcome) => Math.max(max, outcome.latencyMs), 0), + providers: outcomes, + }; +} diff --git a/src/admin/util.ts b/src/admin/util.ts index 24382b2..bfd86ff 100644 --- a/src/admin/util.ts +++ b/src/admin/util.ts @@ -103,15 +103,28 @@ export function optionalInt(value: unknown, field: string): number | null { return parsed; } +/** + * AD-12: the largest timestamp any client may filter on (9999-12-31T23:59:59.999Z). + * Without a bound a 400-digit `?since=` parsed to `Infinity` and silently returned + * an empty page instead of a `400`. + */ +export const MAX_TIMESTAMP_MS = 253_402_300_799_999; + export function asTimestamp(value: unknown): number | null { if (value === null || value === undefined || value === '') return null; - if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'number' && Number.isFinite(value)) { + return value >= 0 && value <= MAX_TIMESTAMP_MS ? Math.trunc(value) : null; + } if (typeof value === 'string') { const trimmed = value.trim(); if (trimmed.length === 0) return null; - if (/^\d+$/.test(trimmed)) return Number(trimmed); + if (/^\d+$/.test(trimmed)) { + const parsed = Number(trimmed); + if (!Number.isFinite(parsed) || parsed > MAX_TIMESTAMP_MS) return null; + return parsed; + } const parsed = Date.parse(trimmed); - if (Number.isFinite(parsed)) return parsed; + if (Number.isFinite(parsed) && parsed >= 0 && parsed <= MAX_TIMESTAMP_MS) return parsed; } return null; } @@ -151,12 +164,18 @@ const BLOCKED_V4: Array<{ bytes: number[]; bits: number }> = [ { bytes: [10, 0, 0, 0], bits: 8 }, { bytes: [172, 16, 0, 0], bits: 12 }, { bytes: [192, 168, 0, 0], bits: 16 }, + { bytes: [100, 64, 0, 0], bits: 10 }, // CGNAT (RFC 6598) / Tailscale + { bytes: [192, 0, 0, 0], bits: 24 }, // IETF protocol assignments (RFC 6890) + { bytes: [198, 18, 0, 0], bits: 15 }, // benchmarking (RFC 2544) ]; const BLOCKED_V6: Array<{ bytes: number[]; bits: number }> = [ + { bytes: v6Bytes('::'), bits: 128 }, // unspecified { bytes: v6Bytes('::1'), bits: 128 }, // loopback { bytes: v6Bytes('fc00::'), bits: 7 }, // unique-local { bytes: v6Bytes('fe80::'), bits: 10 }, // link-local + { bytes: v6Bytes('64:ff9b::'), bits: 96 }, // NAT64 (RFC 6052) + { bytes: v6Bytes('2002::'), bits: 16 }, // 6to4 (RFC 3056) ]; function v6Bytes(address: string): number[] { @@ -265,6 +284,26 @@ export function assertNoControlChars(value: string, field: string): void { } } +/** GW-10/AD-13: an API key is sent as an HTTP header, so it must be printable ASCII. */ +export const MAX_API_KEY_LENGTH = 4096; + +const PRINTABLE_ASCII = /^[\u0020-\u007e]+$/; + +/** + * Validates a user-submitted provider key without ever echoing it. A control + * character (CR/LF) makes `fetch` throw with the raw key in the message, and a + * non-ASCII byte throws `ERR_INVALID_CHAR` on the header write. + */ +export function assertApiKey(value: string, field = 'apiKey'): void { + assertNoControlChars(value, field); + if (!PRINTABLE_ASCII.test(value)) { + fail(400, 'invalid_request', `${field} must contain printable ASCII characters only`); + } + if (value.length > MAX_API_KEY_LENGTH) { + fail(400, 'invalid_request', `${field} must be at most ${MAX_API_KEY_LENGTH} characters`); + } +} + export function httpBaseUrl(value: unknown): string { const url = requireString(value, 'baseUrl'); assertNoControlChars(url, 'baseUrl'); @@ -402,7 +441,12 @@ export function activeKeyCount(ctx: AppContext): number { return ctx.repo.countActiveApiKeys(); } -export function buildHealth(ctx: AppContext): HealthSnapshot { +/** + * AD-14: `/stats` caches the expensive aggregates for ~2 s but reports + * `health.activeRequests` live. Both fields must come from one read of the + * counter, so callers pass the value they already snapshotted. + */ +export function buildHealth(ctx: AppContext, activeRequests: number = getActiveRequests()): HealthSnapshot { const now = Date.now(); const providers: ProviderHealthEntry[] = ctx.repo.listProviders().map((provider) => ({ id: provider.id, @@ -426,7 +470,7 @@ export function buildHealth(ctx: AppContext): HealthSnapshot { } return { status, - activeRequests: getActiveRequests(), + activeRequests, providers, modelsEnabled: ctx.repo.enabledModelIds().length, keysActive: activeKeyCount(ctx), @@ -445,6 +489,9 @@ export function settingTimestamp(ctx: AppContext, key: string): number | null { return Number.isFinite(parsed) ? parsed : null; } +/** AD-23: maximum accepted `/logs?search=` length (the query is a full table scan). */ +export const MAX_LOG_SEARCH_LENGTH = 200; + export function parseLogQuery(request: FastifyRequest): LogQuery { const query = queryOf(request); const surfaceRaw = asString(query.surface); @@ -459,6 +506,12 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { const stream = query.stream === undefined ? null : asBool(query.stream); if (ok === null && query.ok !== undefined) fail(400, 'invalid_request', 'ok must be true or false'); if (stream === null && query.stream !== undefined) fail(400, 'invalid_request', 'stream must be true or false'); + const search = asString(query.search); + // AD-23: `search` is a `LIKE '%…%'` scan; bound its length so a caller cannot hand + // the database an arbitrarily large pattern. + if (search !== null && search.length > MAX_LOG_SEARCH_LENGTH) { + fail(400, 'invalid_request', `search must be at most ${MAX_LOG_SEARCH_LENGTH} characters`); + } return { limit, offset, @@ -468,7 +521,7 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { keyId: asString(query.keyId), ok, stream, - search: asString(query.search), + search, since: queryTimestamp(query.since, 'since'), until: queryTimestamp(query.until, 'until'), }; diff --git a/src/index.ts b/src/index.ts index 1c0ed63..ba534d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ import { loadConfig } from './config.js'; import { openDatabase } from './db/index.js'; import { Repo } from './db/repos.js'; import { EventBus } from './core/events.js'; -import { seedDefaults, pruneLogs } from './core/seed.js'; +import { seedDefaults, pruneLogs, verifyDashboardPassword } from './core/seed.js'; import { registerGracefulShutdown } from './core/shutdown.js'; import { buildServer } from './server.js'; import { startScheduler } from './admin/scheduler.js'; @@ -26,6 +26,13 @@ async function main(): Promise { const app = await buildServer(ctx); seedDefaults(ctx); + // SEC-09: the shipped default password opens every fresh install, so say so loudly. + // A warning (not a failure) keeps first-run usable while making the risk visible. + if (verifyDashboardPassword(ctx, ctx.config.defaultDashboardPassword)) { + app.log.warn( + 'The dashboard password is still the built-in default. Change it in Settings > Security, or set DASHBOARD_PASSWORD before the first boot.', + ); + } const stopScheduler = startScheduler(ctx); app.addHook('onClose', async () => { diff --git a/tests/admin-hardening.test.ts b/tests/admin-hardening.test.ts new file mode 100644 index 0000000..2cddbfc --- /dev/null +++ b/tests/admin-hardening.test.ts @@ -0,0 +1,820 @@ +/** + * Route/unit coverage for the Stream B2 hardening items: + * B-05 sync prune guard, B-06 multi-provider sync, B-08 probe dispose, B-09 + * timestamp finiteness, B-10 dangling sync provider, B-11 apiKey validation, + * B-12 SSRF ranges, B-13 shared probe SSRF guard, B-14 login global cap, + * B-15 CSRF guard, B-16 limit validation, B-17 activeRequests consistency, + * B-18 search bound and B-20 `/admin/api/diagnostics`. + */ +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import fastifyCookie from '@fastify/cookie'; +import Fastify, { type FastifyInstance, type LightMyRequestResponse } from 'fastify'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const upstream = vi.hoisted(() => ({ + status: 200, + payload: { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] } as unknown, + textThrows: false, + calls: [] as Array<{ baseUrl: string; apiKey: string; path: string }>, + disposed: 0, + byBaseUrl: null as null | ((baseUrl: string) => { status: number; payload: unknown }), +})); + +vi.mock('../src/util/upstream.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + upstreamFetch: async (request: { baseUrl: string; apiKey: string; path: string }) => { + upstream.calls.push({ baseUrl: request.baseUrl, apiKey: request.apiKey, path: request.path }); + const override = upstream.byBaseUrl?.(request.baseUrl); + const status = override ? override.status : upstream.status; + const payload = override ? override.payload : upstream.payload; + const body = typeof payload === 'string' ? payload : JSON.stringify(payload); + return { + status, + ok: status >= 200 && status < 300, + headers: new Headers({ 'content-type': 'application/json' }), + response: { + text: async () => { + if (upstream.textThrows) throw new Error('socket closed while reading'); + return body; + }, + json: async () => JSON.parse(body), + }, + dispose: () => { + upstream.disposed += 1; + }, + abort: () => {}, + abortReason: null, + }; + }, + }; +}); + +import { + LOGIN_GLOBAL_MAX_ATTEMPTS, + LOGIN_MAX_ATTEMPTS, + checkLoginRateLimit, + recordLoginFailure, + resetLoginAttempts, +} from '../src/admin/auth.js'; +import { registerAdminRoutes } from '../src/admin/index.js'; +import { SESSION_COOKIE, buildSessionCookie } from '../src/admin/session.js'; +import { clearStatsCache } from '../src/admin/stats.js'; +import { probeProvider, probeAndRecord } from '../src/admin/sync.js'; +import { + HttpError, + MAX_API_KEY_LENGTH, + assertApiKey, + assertPublicProviderUrl, + asTimestamp, +} from '../src/admin/util.js'; +import type { AppConfig } from '../src/config.js'; +import { decActiveRequests, incActiveRequests, type AppContext } from '../src/core/context.js'; +import { EventBus } from '../src/core/events.js'; +import { openDatabase, type DbHandle } from '../src/db/index.js'; +import { Repo } from '../src/db/repos.js'; +import { SCHEMA_VERSION } from '../src/db/schema.js'; +import type { ProviderRow, RequestLogRow } from '../src/types.js'; +import { provider, testConfig } from './helpers.js'; + +interface TestApp { + app: FastifyInstance; + ctx: AppContext; + repo: Repo; + handle: DbHandle; + dataDir: string; + cookie(): string; + login(password?: string): Promise; + request( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise; + json( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise; + close(): Promise; +} + +async function buildAdminApp(configOverrides: Partial = {}): Promise { + const dataDir = mkdtempSync(join(tmpdir(), 'okr-hardening-')); + const config: AppConfig = { ...testConfig(dataDir), bodyLimit: 64 * 1024, ...configOverrides }; + const handle = openDatabase(config); + const repo = new Repo(handle.db); + const ctx: AppContext = { + config, + db: handle, + repo, + events: new EventBus(), + logger: null as never, + startedAt: Date.now(), + }; + const app = Fastify({ logger: false, bodyLimit: config.bodyLimit, trustProxy: config.trustProxy }); + ctx.logger = app.log; + await app.register(fastifyCookie); + await registerAdminRoutes(app, ctx); + + const request = async ( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise => + app.inject({ + method: method as 'GET', + url, + ...(payload === undefined ? {} : { payload: payload as object }), + ...(cookie === undefined && headers === undefined + ? {} + : { headers: { ...(cookie === undefined ? {} : { cookie }), ...(headers ?? {}) } }), + }); + + return { + app, + ctx, + repo, + handle, + dataDir, + cookie(): string { + const session = repo.createSession({ + id: randomUUID(), + ttlMs: config.sessionTtlMs, + clientIp: '127.0.0.1', + userAgent: 'vitest', + }); + return `${SESSION_COOKIE}=${buildSessionCookie(ctx.db.secret, session.id, session.expiresAt)}`; + }, + async login(password = '123456'): Promise { + const response = await request('POST', '/admin/api/login', { password }); + const cookie = response.cookies.find((item) => item.name === SESSION_COOKIE); + if (!cookie) throw new Error(`login failed: ${response.statusCode} ${response.body}`); + return `${SESSION_COOKIE}=${cookie.value}`; + }, + request, + async json( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise { + const response = await request(method, url, payload, cookie, headers); + return JSON.parse(response.body) as T; + }, + async close(): Promise { + await app.close(); + handle.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }, + }; +} + +let app: TestApp; + +beforeEach(async () => { + resetLoginAttempts(); + clearStatsCache(); + upstream.status = 200; + upstream.payload = { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] }; + upstream.textThrows = false; + upstream.calls = []; + upstream.disposed = 0; + upstream.byBaseUrl = null; + app = await buildAdminApp(); +}); + +afterEach(async () => { + await app.close(); +}); + +function seedProvider(id = 'p1', baseUrl = 'https://api.example.com/v1'): ProviderRow { + return app.repo.createProvider({ id, name: id.toUpperCase(), baseUrl, apiKey: 'stored-secret-key' }); +} + +/* ------------------------------------------------------------------- B-05 */ + +describe('B-05 sync prune guard', () => { + it('keeps the synced catalog when the upstream body is unrecognized', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual-1' }); + app.repo.setSetting('models_synced_at', '1111'); + app.repo.setSetting('models_sync_provider_id', 'p1'); + + for (const payload of [{}, 'not json', { data: null }]) { + upstream.payload = payload; + const body = await app.json<{ added: number; removed: number; warning?: string }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body.added).toBe(0); + expect(body.removed).toBe(0); + expect(body.warning).toContain('no recognizable model list'); + } + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['manual-1', 'sync-1']); + expect(app.repo.getSetting('models_synced_at')).toBe('1111'); + }); + + it('prunes the catalog for an explicit empty model array', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual-1' }); + + upstream.payload = { data: [] }; + const body = await app.json<{ removed: number; warning?: string }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body.warning).toBeUndefined(); + expect(body.removed).toBe(1); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['manual-1']); + expect(app.repo.getSetting('models_synced_at')).not.toBeNull(); + }); +}); + +/* ------------------------------------------------------------------- B-06 */ + +describe('B-06 multi-provider sync', () => { + it('syncs every enabled provider and reports per-provider results', async () => { + seedProvider('p1', 'https://p1.example.com/v1'); + seedProvider('p2', 'https://p2.example.com/v1'); + upstream.byBaseUrl = (baseUrl) => + baseUrl.includes('p1') + ? { status: 200, payload: { data: [{ id: 'm-p1' }] } } + : { status: 200, payload: { data: [{ id: 'm-p2' }] } }; + + const body = await app.json<{ + providers: Array<{ providerId: string; ok: boolean; added: number }>; + added: number; + }>('POST', '/admin/api/models/sync', undefined, app.cookie()); + + expect(body.providers).toHaveLength(2); + expect(body.providers.map((entry) => entry.providerId).sort()).toEqual(['p1', 'p2']); + expect(body.providers.every((entry) => entry.ok)).toBe(true); + expect(body.added).toBe(2); + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['m-p1', 'm-p2']); + // A multi-provider sync cannot attribute the catalog to one provider. + const models = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(models.syncProviderId).toBeNull(); + }); + + it('keeps the other providers when one sync fails', async () => { + seedProvider('p1', 'https://p1.example.com/v1'); + seedProvider('p2', 'https://p2.example.com/v1'); + upstream.byBaseUrl = (baseUrl) => + baseUrl.includes('p1') + ? { status: 200, payload: { data: [{ id: 'm-p1' }] } } + : { status: 500, payload: 'boom: internals' }; + + const body = await app.json<{ + providers: Array<{ providerId: string; ok: boolean; error: string | null }>; + }>('POST', '/admin/api/models/sync', undefined, app.cookie()); + const p1 = body.providers.find((entry) => entry.providerId === 'p1'); + const p2 = body.providers.find((entry) => entry.providerId === 'p2'); + expect(p1?.ok).toBe(true); + expect(p2?.ok).toBe(false); + expect(p2?.error).not.toContain('boom'); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['m-p1']); + }); +}); + +/* ------------------------------------------------------------------- B-08 */ + +describe('B-08 probe dispose', () => { + it('disposes the upstream response when the body read throws', async () => { + upstream.status = 200; + upstream.textThrows = true; + const probe = await probeProvider({ baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + expect(probe.ok).toBe(false); + expect(upstream.disposed).toBe(1); + }); +}); + +/* ------------------------------------------------------------------- B-09 */ + +describe('B-09 timestamp finiteness', () => { + it('rejects overflowing digit strings and numeric values', () => { + expect(asTimestamp('1'.repeat(400))).toBeNull(); + expect(asTimestamp('99999999999999999999')).toBeNull(); + expect(asTimestamp(Number.MAX_VALUE)).toBeNull(); + expect(asTimestamp(-5)).toBeNull(); + }); + + it('still parses a valid epoch ms and ISO date', () => { + expect(asTimestamp(1_700_000_000_000)).toBe(1_700_000_000_000); + expect(asTimestamp('1700000000000')).toBe(1_700_000_000_000); + expect(asTimestamp('2026-01-02T03:04:05Z')).toBe(Date.parse('2026-01-02T03:04:05Z')); + }); + + it('returns 400 from /logs for an out-of-range ?since=', async () => { + const cookie = app.cookie(); + for (const value of ['99999999999999999999', '1'.repeat(400)]) { + const response = await app.request('GET', `/admin/api/logs?since=${value}`, undefined, cookie); + expect(response.statusCode, value).toBe(400); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('invalid_request'); + } + const ok = await app.request('GET', '/admin/api/logs?since=1700000000000', undefined, cookie); + expect(ok.statusCode).toBe(200); + }); +}); + +/* ------------------------------------------------------------------- B-10 */ + +describe('B-10 dangling sync provider id', () => { + it('clears models_sync_provider_id when its provider is deleted', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.setSetting('models_synced_at', '2222'); + app.repo.setSetting('models_sync_provider_id', 'p1'); + + const deleted = await app.request('DELETE', '/admin/api/providers/p1', undefined, app.cookie()); + expect(deleted.statusCode).toBe(200); + const models = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(models.syncProviderId).toBeNull(); + // Deleting an unrelated provider must not clear the current sync provider id. + seedProvider('p2'); + seedProvider('p3'); + app.repo.setSetting('models_sync_provider_id', 'p2'); + const unrelated = await app.request('DELETE', '/admin/api/providers/p3', undefined, app.cookie()); + expect(unrelated.statusCode).toBe(200); + const after = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(after.syncProviderId).toBe('p2'); + }); +}); + +/* ------------------------------------------------------------------- B-11 */ + +describe('B-11 apiKey validation', () => { + it('rejects control, non-ASCII, empty and over-long keys without echoing them', async () => { + const cookie = app.cookie(); + const payloads: Array<{ apiKey: string; label: string }> = [ + { apiKey: 'SECRET-CONTROL\u0001', label: 'control' }, + { apiKey: 'SECRET-LATIN-\u00e9', label: 'latin-1' }, + { apiKey: 'SECRET\nNEWLINE', label: 'newline' }, + { apiKey: '', label: 'empty' }, + ]; + for (const { apiKey, label } of payloads) { + const response = await app.request( + 'POST', + '/admin/api/providers', + { name: 'p', baseUrl: 'https://api.example.com/v1', apiKey }, + cookie, + ); + expect(response.statusCode, label).toBe(400); + expect(response.body).not.toContain('SECRET'); + } + expect(app.repo.listProviders()).toHaveLength(0); + + // Over-long keys are rejected by the route (harness body limit is 64 KiB). + const longResponse = await app.request( + 'POST', + '/admin/api/providers', + { name: 'p', baseUrl: 'https://api.example.com/v1', apiKey: 'k'.repeat(MAX_API_KEY_LENGTH + 1) }, + cookie, + ); + expect(longResponse.statusCode).toBe(400); + expect(longResponse.body).not.toContain('kkkk'); + expect(() => assertApiKey('k'.repeat(MAX_API_KEY_LENGTH + 1))).toThrow(HttpError); + expect(MAX_API_KEY_LENGTH).toBe(4096); + }); + + it('accepts a normal key on create and patch', async () => { + const cookie = app.cookie(); + const created = await app.request( + 'POST', + '/admin/api/providers', + { id: 'p', name: 'p', baseUrl: 'https://api.example.com/v1', apiKey: 'sk-normal-key-123' }, + cookie, + ); + expect(created.statusCode).toBe(200); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-normal-key-123'); + + const patched = await app.request('PATCH', '/admin/api/providers/p', { apiKey: 'sk-rotated-key-456' }, cookie); + expect(patched.statusCode).toBe(200); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-rotated-key-456'); + + const rejected = await app.request('PATCH', '/admin/api/providers/p', { apiKey: 'bad\u00e9key' }, cookie); + expect(rejected.statusCode).toBe(400); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-rotated-key-456'); + }); +}); + +/* ------------------------------------------------------------------- B-12 */ + +describe('B-12 SSRF ranges', () => { + const blockedUrls = [ + 'http://100.64.0.1/v1', // CGNAT / Tailscale + 'http://100.127.255.254/v1', + 'http://192.0.0.5/v1', // IETF protocol assignments + 'http://198.18.0.1/v1', // benchmarking + 'http://198.19.255.255/v1', + 'http://[::]/v1', // unspecified + 'http://[64:ff9b::1]/v1', // NAT64 + 'http://[2002::1]/v1', // 6to4 + // Previously blocked ranges must stay blocked. + 'http://127.0.0.1/v1', + 'http://10.0.0.5/v1', + 'http://172.16.0.5/v1', + 'http://192.168.1.5/v1', + 'http://169.254.1.5/v1', + 'http://0.0.0.0/v1', + 'http://[::1]/v1', + 'http://[fc00::1]/v1', + 'http://[fe80::1]/v1', + ]; + + it('blocks the new CGNAT, IETF, benchmarking and IPv6 ranges', () => { + for (const url of blockedUrls) { + expect(() => assertPublicProviderUrl(url, false), url).toThrow(HttpError); + try { + assertPublicProviderUrl(url, false); + } catch (error) { + expect((error as HttpError).code).toBe('invalid_request'); + } + } + }); + + it('keeps public addresses allowed and the escape hatch working', () => { + for (const url of ['https://8.8.8.8/v1', 'https://1.1.1.1/v1', 'https://[2606:4700:4700::1111]/v1', 'https://api.example.com/v1']) { + expect(() => assertPublicProviderUrl(url, false), url).not.toThrow(); + } + expect(() => assertPublicProviderUrl('http://127.0.0.1/v1', true)).not.toThrow(); + }); +}); + +/* ------------------------------------------------------------------- B-13 */ + +describe('B-13 shared probe SSRF guard', () => { + it('refuses to probe a private stored provider and records no failure', async () => { + const recorded: string[] = []; + const ctx = { + config: { providerAllowPrivateHosts: false }, + repo: { + recordProviderFailure: (...args: unknown[]) => { + recorded.push(String(args[0])); + }, + recordProviderSuccess: () => {}, + }, + events: { emitProvider: () => {} }, + logger: { warn: () => {} }, + } as unknown as AppContext; + const row = provider('legacy', { baseUrl: 'http://127.0.0.1:9/v1' }); + + await expect(probeAndRecord(ctx, row, { cooldownMs: 0, log: () => {} })).rejects.toThrow(HttpError); + expect(upstream.calls).toHaveLength(0); + expect(recorded).toHaveLength(0); + }); +}); + +/* ------------------------------------------------------------------- B-14 */ + +describe('B-14 login global cap', () => { + it('keeps the raised global cap well above the per-IP cap', () => { + expect(LOGIN_MAX_ATTEMPTS).toBe(10); + expect(LOGIN_GLOBAL_MAX_ATTEMPTS).toBe(500); + }); + + it('lets the operator log in after 50 failures from distinct IPs', async () => { + for (let index = 0; index < 50; index += 1) recordLoginFailure(`198.51.100.${index}`); + // The per-IP counter for the dashboard IP is untouched and the global cap holds. + expect(checkLoginRateLimit('203.0.113.9')).toBeNull(); + const response = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(response.statusCode).toBe(200); + }); + + it('still blocks a single IP after 10 failures', async () => { + for (let index = 0; index < LOGIN_MAX_ATTEMPTS; index += 1) { + const failed = await app.request('POST', '/admin/api/login', { password: 'wrong' }); + expect(failed.statusCode).toBe(401); + } + expect(checkLoginRateLimit('127.0.0.1')?.scope).toBe('ip'); + const response = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(response.statusCode).toBe(429); + }); +}); + +/* ------------------------------------------------------------------- B-15 */ + +describe('B-15 CSRF guard', () => { + it('rejects a cross-origin Origin on a session-authenticated mutation', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '7' }, cookie, { + origin: 'https://evil.example.com', + }); + expect(response.statusCode).toBe(403); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('cross_site_request'); + // No state change. + expect(app.repo.getSetting('max_retries')).toBe('3'); + }); + + it('rejects Sec-Fetch-Site: cross-site', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '7' }, cookie, { + 'sec-fetch-site': 'cross-site', + }); + expect(response.statusCode).toBe(403); + expect(app.repo.getSetting('max_retries')).toBe('3'); + }); + + it('allows same-origin, absent Origin and same-origin Sec-Fetch-Site', async () => { + const cookie = app.cookie(); + const sameOrigin = await app.request('PATCH', '/admin/api/settings', { max_retries: '4' }, cookie, { + host: 'router.test', + origin: 'http://router.test', + }); + expect(sameOrigin.statusCode).toBe(200); + + const absent = await app.request('PATCH', '/admin/api/settings', { max_retries: '5' }, cookie); + expect(absent.statusCode).toBe(200); + + const sameSite = await app.request('PATCH', '/admin/api/settings', { max_retries: '6' }, cookie, { + 'sec-fetch-site': 'same-origin', + }); + expect(sameSite.statusCode).toBe(200); + expect(app.repo.getSetting('max_retries')).toBe('6'); + }); + + it('keeps POST /admin/api/login reachable cross-site', async () => { + const response = await app.request('POST', '/admin/api/login', { password: '123456' }, undefined, { + origin: 'https://some-login-page.example', + 'sec-fetch-site': 'cross-site', + }); + expect(response.statusCode).toBe(200); + }); + + it('trusts PUBLIC_URL over the Host header when configured', async () => { + const behindProxy = await buildAdminApp({ publicUrl: 'https://router.example.com' }); + try { + const cookie = behindProxy.cookie(); + const response = await behindProxy.request('PATCH', '/admin/api/settings', { max_retries: '8' }, cookie, { + host: '10.0.0.5:20125', + origin: 'https://router.example.com', + }); + expect(response.statusCode).toBe(200); + expect(behindProxy.repo.getSetting('max_retries')).toBe('8'); + } finally { + await behindProxy.close(); + } + }); +}); + +/* ------------------------------------------------------------------- B-16 */ + +describe('B-16 limit validation', () => { + it('rejects junk limits on /audit and /activity', async () => { + const cookie = app.cookie(); + for (const path of ['/admin/api/audit', '/admin/api/activity']) { + for (const limit of ['abc', '-1', '0', '1000']) { + const response = await app.request('GET', `${path}?limit=${limit}`, undefined, cookie); + expect(response.statusCode, `${path}?limit=${limit}`).toBe(400); + } + const ok = await app.request('GET', `${path}?limit=20`, undefined, cookie); + expect(ok.statusCode).toBe(200); + const absent = await app.request('GET', path, undefined, cookie); + expect(absent.statusCode).toBe(200); + } + }); +}); + +/* ------------------------------------------------------------------- B-17 */ + +describe('B-17 activeRequests consistency', () => { + it('reports cache-independent activeRequests in the body and health', async () => { + const cookie = app.cookie(); + // Prime the 2 s aggregate cache. + const first = await app.json<{ activeRequests: number; health: { activeRequests: number } }>( + 'GET', + '/admin/api/stats', + undefined, + cookie, + ); + const base = first.activeRequests; + expect(first.health.activeRequests).toBe(base); + + incActiveRequests(); + try { + // A cache hit must still report the live counter in both fields. + const cached = await app.json<{ activeRequests: number; health: { activeRequests: number } }>( + 'GET', + '/admin/api/stats?window=1h', + undefined, + cookie, + ); + expect(cached.activeRequests).toBe(base + 1); + expect(cached.health.activeRequests).toBe(base + 1); + } finally { + decActiveRequests(); + clearStatsCache(); + } + }); +}); + +/* ------------------------------------------------------------------- B-18 */ + +function logRow(overrides: Partial & { id: string }): RequestLogRow { + return { + ts: Date.now(), + keyId: 'k1', + keyName: 'e2e', + providerId: 'p1', + providerName: 'Primary', + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 10, + ttfbMs: 5, + inputTokens: 1, + outputTokens: 2, + totalTokens: 3, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: '127.0.0.1', + userAgent: 'test', + ...overrides, + }; +} + +describe('B-18 log search/model filters', () => { + it('matches `model` case-insensitively on a substring with a consistent total', async () => { + const now = Date.now(); + app.repo.insertLog(logRow({ id: 'm1', ts: now - 3_000, model: 'opencode/flint-40b-free' })); + app.repo.insertLog(logRow({ id: 'm2', ts: now - 2_000, model: 'OPENCODE/Flint-Large' })); + app.repo.insertLog(logRow({ id: 'm3', ts: now - 1_000, model: 'other/model' })); + + const cookie = app.cookie(); + const lower = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=flint', + undefined, + cookie, + ); + expect(lower.total).toBe(2); + expect(lower.logs.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + const paged = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=flint&limit=1', + undefined, + cookie, + ); + expect(paged.total).toBe(2); + expect(paged.logs).toHaveLength(1); + }); + + it('treats % and _ in the model filter as literals', async () => { + app.repo.insertLog(logRow({ id: 'pct', model: 'vendor/a%b' })); + app.repo.insertLog(logRow({ id: 'plain', model: 'vendor/axb' })); + const body = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=a%25b', + undefined, + app.cookie(), + ); + expect(body.total).toBe(1); + expect(body.logs[0]?.id).toBe('pct'); + }); + + it('rejects an over-long search term', async () => { + const cookie = app.cookie(); + const response = await app.request('GET', `/admin/api/logs?search=${'a'.repeat(201)}`, undefined, cookie); + expect(response.statusCode).toBe(400); + expect((JSON.parse(response.body) as { error: { message: string } }).error.message).toContain('at most 200'); + const ok = await app.request('GET', `/admin/api/logs?search=${'a'.repeat(200)}`, undefined, cookie); + expect(ok.statusCode).toBe(200); + }); +}); + +/* ------------------------------------------------- upstream_response_max_bytes */ + +describe('upstream_response_max_bytes validation', () => { + it('accepts exactly 0 (unlimited) or 1024..1073741824', async () => { + const cookie = app.cookie(); + for (const value of ['1024', '1073741824', '0']) { + const response = await app.request('PATCH', '/admin/api/settings', { upstream_response_max_bytes: value }, cookie); + expect(response.statusCode, value).toBe(200); + expect(app.repo.getSetting('upstream_response_max_bytes')).toBe(value); + } + for (const value of ['1', '1023', '1073741825', '-1', 'abc']) { + const response = await app.request('PATCH', '/admin/api/settings', { upstream_response_max_bytes: value }, cookie); + expect(response.statusCode, value).toBe(400); + const body = JSON.parse(response.body) as { error: { code: string } }; + expect(body.error.code, value).toBe('invalid_request'); + } + // The last successful write is untouched by the rejected patches. + expect(app.repo.getSetting('upstream_response_max_bytes')).toBe('0'); + }); +}); + +/* ------------------------------------------------------------------- B-20 */ + +describe('B-20 GET /admin/api/diagnostics', () => { + it('requires a dashboard session', async () => { + const response = await app.request('GET', '/admin/api/diagnostics'); + expect(response.statusCode).toBe(401); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('unauthorized'); + }); + + it('returns the documented shape with the expected warnings on a fresh database', async () => { + const body = await app.json<{ + scheduler: Record; + storage: Record; + checks: Array<{ id: string; status: string; detail: string }>; + }>('GET', '/admin/api/diagnostics', undefined, app.cookie()); + + expect(Object.keys(body).sort()).toEqual(['checks', 'scheduler', 'storage']); + expect(body.scheduler).toEqual({ + running: false, + lastSyncAt: null, + lastSyncError: null, + nextSyncInMs: null, + lastRecoveryAt: null, + }); + expect(body.storage).toMatchObject({ + dbPath: expect.any(String), + walSizeBytes: expect.any(Number), + dbSizeBytes: expect.any(Number), + busyTimeoutMs: expect.any(Number), + logRows: 0, + attemptRows: 0, + sessionRows: expect.any(Number), + oldestLogTs: null, + }); + expect(body.storage.dbSizeBytes as number).toBeGreaterThan(0); + + expect(body.checks.map((check) => check.id)).toEqual([ + 'password.default', + 'providers.enabled', + 'keys.active', + 'models.enabled', + 'version.schema', + 'clock.skew', + 'providers.cooldown', + ]); + const statuses = Object.fromEntries(body.checks.map((check) => [check.id, check.status])); + expect(statuses).toEqual({ + 'password.default': 'warn', + 'providers.enabled': 'warn', + 'keys.active': 'warn', + 'models.enabled': 'warn', + 'version.schema': 'ok', + 'clock.skew': 'ok', + 'providers.cooldown': 'ok', + }); + expect(body.checks.every((check) => check.detail.length > 0)).toBe(true); + + // No secret material is part of the report. + const serialized = JSON.stringify(body); + expect(serialized).not.toContain('dashboard_password_hash'); + expect(serialized).not.toContain(app.ctx.db.secret); + }); + + it('warns when the data file is missing a required table', async () => { + app.ctx.db.db.exec('DROP TABLE models'); + const body = await app.json<{ checks: Array<{ id: string; status: string; detail: string }> }>( + 'GET', + '/admin/api/diagnostics', + undefined, + app.cookie(), + ); + const schemaCheck = body.checks.find((check) => check.id === 'version.schema'); + expect(schemaCheck?.status).toBe('warn'); + expect(schemaCheck?.detail).toContain('models'); + }); + + it('warns when the data file declares a different schema generation', async () => { + app.ctx.db.db.exec('PRAGMA user_version = 99'); + try { + const body = await app.json<{ checks: Array<{ id: string; status: string; detail: string }> }>( + 'GET', + '/admin/api/diagnostics', + undefined, + app.cookie(), + ); + const schemaCheck = body.checks.find((check) => check.id === 'version.schema'); + expect(schemaCheck?.status).toBe('warn'); + expect(schemaCheck?.detail).toContain('99'); + } finally { + app.ctx.db.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`); + } + }); +}); \ No newline at end of file diff --git a/tests/admin-scheduler.test.ts b/tests/admin-scheduler.test.ts new file mode 100644 index 0000000..73b2d55 --- /dev/null +++ b/tests/admin-scheduler.test.ts @@ -0,0 +1,311 @@ +/** + * AD-19: `src/admin/scheduler.ts` used to have zero coverage. These tests drive + * `startScheduler` with fake timers and assert the interval floor, the no-overlap + * guard, the never-throw wrapper, the session purge cadence, the cooldown sweep + * cursor, `stop()` and the `unref()` of every timer. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const sync = vi.hoisted(() => ({ + syncCalls: 0, + probeCalls: [] as string[], + /** Replaces the sync implementation; throw to exercise the failure path. */ + syncImpl: null as null | (() => Promise), + /** Replaces the probe implementation. */ + probeImpl: null as null | ((providerId: string) => Promise), +})); + +vi.mock('../src/admin/sync.js', () => ({ + syncAllEnabledProviders: async () => { + sync.syncCalls += 1; + if (sync.syncImpl) return await sync.syncImpl(); + return { added: 0, updated: 0, removed: 0, total: 0, providerId: '', syncedAt: Date.now(), latencyMs: 1, providers: [] }; + }, + probeAndRecord: async (_ctx: unknown, provider: { id: string }) => { + sync.probeCalls.push(provider.id); + if (sync.probeImpl) return await sync.probeImpl(provider.id); + return { ok: true, status: 200, latencyMs: 1, models: [], catalogLocated: true, error: '', detail: null }; + }, +})); + +import { getSchedulerStatus, resetSchedulerStatus, startScheduler } from '../src/admin/scheduler.js'; +import type { AppContext } from '../src/core/context.js'; +import type { ProviderRow } from '../src/types.js'; +import { provider } from './helpers.js'; + +interface FakeRepo { + providers: ProviderRow[]; + settings: Record; + purged: number; + updates: Array<{ id: string; patch: Record }>; + getBool(key: string): boolean; + getInt(key: string, fallback: number): number; + listProviders(): ProviderRow[]; + purgeExpiredSessions(): void; + updateProvider(id: string, patch: Record): void; +} + +interface FakeHarness { + ctx: AppContext; + repo: FakeRepo; + emitted: string[]; + warnings: string[]; +} + +function makeHarness(options: { providers?: ProviderRow[]; settings?: Record } = {}): FakeHarness { + const settings: Record = { + auto_sync_models: 'true', + model_sync_interval_ms: '300000', + ...options.settings, + }; + const emitted: string[] = []; + const warnings: string[] = []; + const repo: FakeRepo = { + providers: options.providers ?? [provider('p1')], + settings, + purged: 0, + updates: [], + getBool(key) { + return settings[key] === 'true'; + }, + getInt(key, fallback) { + const parsed = Number.parseInt(settings[key] ?? '', 10); + return Number.isFinite(parsed) ? parsed : fallback; + }, + listProviders() { + return repo.providers; + }, + purgeExpiredSessions() { + repo.purged += 1; + }, + updateProvider(id, patch) { + repo.updates.push({ id, patch }); + const row = repo.providers.find((candidate) => candidate.id === id); + if (row) Object.assign(row, patch); + }, + }; + const events = { + emitProvider: (event: { providerId: string }) => { + emitted.push(event.providerId); + }, + }; + const logger = { + info: () => {}, + warn: (extra: unknown, message?: string) => { + warnings.push(message ?? String(extra)); + }, + }; + const ctx = { + config: { providerAllowPrivateHosts: false }, + repo, + events, + logger, + } as unknown as AppContext; + return { ctx, repo, emitted, warnings }; +} + +const liveStops: Array<() => void> = []; + +function start(harness: FakeHarness): () => void { + const stop = startScheduler(harness.ctx); + liveStops.push(stop); + return stop; +} + +beforeEach(() => { + sync.syncCalls = 0; + sync.probeCalls = []; + sync.syncImpl = null; + sync.probeImpl = null; + resetSchedulerStatus(); +}); + +afterEach(() => { + while (liveStops.length > 0) liveStops.pop()!(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +describe('startScheduler', () => { + it('applies the 30 s minimum sync interval', async () => { + vi.useFakeTimers(); + const harness = makeHarness({ settings: { model_sync_interval_ms: '1000' } }); + start(harness); + + // Initial timer fires 5 s after boot. + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + + // t=30 s: only 25 s since the last sync, so the configured 1 s must not win. + await vi.advanceTimersByTimeAsync(25_000); + expect(sync.syncCalls).toBe(1); + + // t=60 s: 55 s since the last sync, the 30 s floor is satisfied. + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.syncCalls).toBe(2); + }); + + it('never overlaps two syncs when one tick is slow', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + sync.syncImpl = async () => { + await gate; + return { providers: [] }; + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + + // Two more ticks pass while the first sync is still in flight. + await vi.advanceTimersByTimeAsync(60_000); + expect(sync.syncCalls).toBe(1); + + release(); + await vi.advanceTimersByTimeAsync(0); + }); + + it('never throws out of a tick and records the last sync error', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + sync.syncImpl = async () => { + throw new Error('upstream exploded'); + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + expect(harness.warnings).toContain('scheduled model sync failed'); + expect(getSchedulerStatus(harness.ctx).lastSyncError).toBe('upstream exploded'); + + // The next interval still runs: one failure must not stop the scheduler. + await vi.advanceTimersByTimeAsync(330_000); + expect(sync.syncCalls).toBe(2); + }); + + it('purges expired sessions every 10 minutes', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + start(harness); + + await vi.advanceTimersByTimeAsync(10 * 60 * 1000); + expect(harness.repo.purged).toBe(1); + await vi.advanceTimersByTimeAsync(10 * 60 * 1000); + expect(harness.repo.purged).toBe(2); + }); + + it('recovers cooldowns and rotates the probe cursor over every provider', async () => { + vi.useFakeTimers(); + const cooling = ['p1', 'p2', 'p3', 'p4', 'p5'].map((id) => + provider(id, { status: 'cooldown', cooldownUntil: Date.now() - 1 }), + ); + const harness = makeHarness({ providers: cooling }); + start(harness); + + // Tick 1 probes the first three cooling providers. + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.probeCalls).toEqual(['p1', 'p2', 'p3']); + + // Tick 2 probes the remaining two; three consecutive ticks are disjoint and + // cover all five (tick 3 has nothing left to recover). + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.probeCalls).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.probeCalls).toHaveLength(5); + + expect(harness.emitted).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + expect(harness.repo.updates.map((update) => update.id)).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + for (const update of harness.repo.updates) { + expect(update.patch).toEqual({ cooldownUntil: null, status: 'ok' }); + } + expect(getSchedulerStatus(harness.ctx).lastRecoveryAt).not.toBeNull(); + }); + + it('survives a throwing probe without aborting the sweep', async () => { + vi.useFakeTimers(); + const cooling = ['p1', 'p2'].map((id) => provider(id, { status: 'cooldown', cooldownUntil: Date.now() - 1 })); + const harness = makeHarness({ providers: cooling }); + sync.probeImpl = async (providerId) => { + if (providerId === 'p1') throw new Error('ssrf guard'); + return { ok: true, status: 200, latencyMs: 1, models: [], catalogLocated: true, error: '', detail: null }; + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.probeCalls).toEqual(['p1', 'p2']); + expect(harness.repo.updates.map((update) => update.id)).toEqual(['p2']); + }); + + it('stop() clears every timer and stops all work', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + const stop = start(harness); + expect(vi.getTimerCount()).toBe(3); + + stop(); + expect(vi.getTimerCount()).toBe(0); + expect(getSchedulerStatus(harness.ctx).running).toBe(false); + + await vi.advanceTimersByTimeAsync(60 * 60 * 1000); + expect(sync.syncCalls).toBe(0); + expect(harness.repo.purged).toBe(0); + + // Idempotent. + expect(() => stop()).not.toThrow(); + }); + + it('unrefs every timer', () => { + vi.useRealTimers(); + const unrefed: boolean[] = []; + const wrap = unknown }>(timer: T): T => { + const index = unrefed.push(false) - 1; + const original = timer.unref?.bind(timer); + timer.unref = () => { + unrefed[index] = true; + original?.(); + return timer; + }; + return timer; + }; + const realSetInterval = globalThis.setInterval; + const realSetTimeout = globalThis.setTimeout; + vi.spyOn(globalThis, 'setInterval').mockImplementation(((handler: () => void, timeout?: number) => + wrap(realSetInterval(handler, timeout))) as typeof globalThis.setInterval); + vi.spyOn(globalThis, 'setTimeout').mockImplementation(((handler: () => void, timeout?: number) => + wrap(realSetTimeout(handler, timeout))) as typeof globalThis.setTimeout); + + const harness = makeHarness(); + const stop = start(harness); + + expect(unrefed).toHaveLength(3); + expect(unrefed).toEqual([true, true, true]); + stop(); + }); + + it('reports its runtime status', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + const before = getSchedulerStatus(harness.ctx); + expect(before).toEqual({ + running: false, + lastSyncAt: null, + lastSyncError: null, + nextSyncInMs: null, + lastRecoveryAt: null, + }); + + start(harness); + const running = getSchedulerStatus(harness.ctx); + expect(running.running).toBe(true); + expect(running.nextSyncInMs).toBeGreaterThanOrEqual(0); + + await vi.advanceTimersByTimeAsync(5_000); + const afterSync = getSchedulerStatus(harness.ctx); + expect(afterSync.lastSyncAt).not.toBeNull(); + expect(afterSync.nextSyncInMs).toBeGreaterThan(0); + }); +}); \ No newline at end of file From e4a012eff38daa55acaca91e52189b7d8fa78a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Sun, 6 Dec 2026 22:28:21 +0700 Subject: [PATCH 3/6] fix(db): bound log queries, keep cooldowns monotonic and wait on locks --- src/db/index.ts | 21 +- src/db/repos.ts | 103 +++++--- src/db/schema.ts | 14 ++ tests/db-hardening.test.ts | 481 +++++++++++++++++++++++++++++++++++++ 4 files changed, 584 insertions(+), 35 deletions(-) create mode 100644 tests/db-hardening.test.ts diff --git a/src/db/index.ts b/src/db/index.ts index 818c248..787a671 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -3,13 +3,25 @@ import { DatabaseSync } from 'node:sqlite'; import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { AppConfig } from '../config.js'; -import { SCHEMA_SQL } from './schema.js'; +import { SCHEMA_SQL, SCHEMA_VERSION } from './schema.js'; export interface DbHandle { db: DatabaseSync; secret: string; } +/** Current `PRAGMA user_version`, or `null` when the file cannot answer it. */ +function schemaUserVersion(db: DatabaseSync): number | null { + try { + const row = db.prepare('PRAGMA user_version').get() as Record | undefined; + const value = row === undefined ? undefined : Object.values(row)[0]; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; + } catch { + return null; + } +} + /** * Opens (creating if needed) the sqlite database, applies the schema and makes * sure a persistent signing secret exists. @@ -18,6 +30,13 @@ export function openDatabase(config: AppConfig): DbHandle { const db = new DatabaseSync(config.dbPath); db.exec(SCHEMA_SQL); + // Stamp the schema generation only when it differs: the write needs the header lock, + // and an already-initialized file must not take it on every boot (a second process + // may be applying the schema while another holds a transaction). + if (schemaUserVersion(db) !== SCHEMA_VERSION) { + db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`); + } + const secretFile = resolve(config.dataDir, '.secret'); let secret = config.secret; if (!secret && existsSync(secretFile)) { diff --git a/src/db/repos.ts b/src/db/repos.ts index 6695582..8c590c5 100644 --- a/src/db/repos.ts +++ b/src/db/repos.ts @@ -43,8 +43,17 @@ export const DEFAULT_SETTINGS: Record = { model_allow_unknown: 'false', upstream_user_agent: 'opencode-router/1.0', stream_idle_timeout_ms: '120000', + // A-06: `0` means unlimited; any other value caps the buffered upstream + // response (the gateway reads it with `getInt`). + upstream_response_max_bytes: '0', }; +/** Longest `search` term accepted by `listLogs` (the clause stays a LIKE scan). */ +const MAX_LOG_SEARCH_CHARS = 200; + +/** Escapes the LIKE metacharacters so a user-supplied `%`/`_`/`\` matches literally. */ +const escapeLike = (value: string): string => value.replace(/[\\%_]/g, (match) => `\\${match}`); + export interface LogQuery { limit?: number; offset?: number; @@ -320,10 +329,28 @@ export class Repo { status === 529 || status >= 500 || (status >= 300 && status < 400); + // B-01: the deadline is monotonic — a shorter cooldown (or the scheduler's + // `cooldownMs: 0` probe) must never lower a cooldown that is still in force. + // `cooldownMs <= 0` therefore pins the provider to `now` only when nothing is + // active; a non-cooling failure still clears the column as before. + const nextCooldown = coolDown ? now + cooldownMs : null; this.stmt( - `UPDATE providers SET status=?, cooldown_until=?, last_error=?, last_checked_at=?, - failure_count=failure_count+1, updated_at=? WHERE id=?`, - ).run(rateLimited ? 'cooldown' : 'error', coolDown ? now + cooldownMs : null, error.slice(0, 500), now, now, id); + `UPDATE providers SET status=?, + cooldown_until=CASE + WHEN ? IS NULL THEN NULL + WHEN cooldown_until IS NOT NULL AND cooldown_until > ? THEN cooldown_until + ELSE ? END, + last_error=?, last_checked_at=?, failure_count=failure_count+1, updated_at=? WHERE id=?`, + ).run( + rateLimited ? 'cooldown' : 'error', + nextCooldown, + now, + nextCooldown, + error.slice(0, 500), + now, + now, + id, + ); } /* -------------------------------------------------------------------- models */ @@ -736,8 +763,10 @@ export class Repo { params.push(query.surface); } if (query.model) { - where.push('model = ?'); - params.push(query.model); + // B-18: "Model contains" — `LIKE` is ASCII case-insensitive by default in + // SQLite and the ESCAPE clause keeps `%`/`_`/`\` in the filter literal. + where.push("model LIKE '%' || ? || '%' ESCAPE '\\'"); + params.push(escapeLike(query.model)); } if (query.providerId) { where.push('provider_id = ?'); @@ -763,12 +792,15 @@ export class Repo { where.push('ts <= ?'); params.push(query.until); } - if (query.search) { + // B-18: `search` stays a scan (no FTS in this schema); the length is bounded + // so a hostile term cannot force SQLite into a huge LIKE pattern. + const search = query.search ? query.search.slice(0, MAX_LOG_SEARCH_CHARS) : ''; + if (search) { // `%`/`_` in the search term must be literals, not wildcards. where.push( "(model LIKE ? ESCAPE '\\' OR key_name LIKE ? ESCAPE '\\' OR provider_name LIKE ? ESCAPE '\\' OR error_message LIKE ? ESCAPE '\\')", ); - const like = `%${query.search.replace(/[\\%_]/g, (match) => `\\${match}`)}%`; + const like = `%${escapeLike(search)}%`; params.push(like, like, like, like); } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; @@ -786,34 +818,26 @@ export class Repo { return row ? this.mapLog(row) : null; } + /** B-03: both deletes share one transaction, so a crash cannot orphan attempts. */ deleteLogsBefore(ts: number): number { - const res = this.stmt('DELETE FROM request_logs WHERE ts < ?').run(ts); - this.stmt('DELETE FROM request_attempts WHERE ts < ?').run(ts); - return Number(res.changes); + return this.transaction(() => { + const res = this.stmt('DELETE FROM request_logs WHERE ts < ?').run(ts); + this.stmt('DELETE FROM request_attempts WHERE ts < ?').run(ts); + return Number(res.changes); + }); } + /** B-03: transactional counterpart of `deleteLogsBefore`. */ clearLogs(): number { - const res = this.stmt('DELETE FROM request_logs').run(); - this.stmt('DELETE FROM request_attempts').run(); - return Number(res.changes); + return this.transaction(() => { + const res = this.stmt('DELETE FROM request_logs').run(); + this.stmt('DELETE FROM request_attempts').run(); + return Number(res.changes); + }); } /* --------------------------------------------------------------------- stats */ - /** - * Nearest-rank percentile over the rows `ts >= since` with a non-null latency. - * `count` is the caller's `COUNT(latency_ms)` for the same predicate, so the - * OFFSET stays a single indexed lookup per percentile. - */ - private latencyPercentile(since: number, count: number, p: number): number { - if (count <= 0) return 0; - const index = Math.min(count - 1, Math.floor((p / 100) * count)); - const row = this.stmt( - 'SELECT latency_ms FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL ORDER BY latency_ms ASC LIMIT 1 OFFSET ?', - ).get(since, index) as Row | undefined; - return row ? num(row.latency_ms) : 0; - } - statsOverview(windowMs: number, bucketMs: number, activeRequests: number): StatsOverview { const since = Date.now() - windowMs; const totalsRow = this.stmt( @@ -831,11 +855,22 @@ export class Repo { ) .get(since) as Row; - const latencies = this.stmt('SELECT COUNT(latency_ms) AS c FROM request_logs WHERE ts >= ?').get(since) as Row; - const latencyCount = num(latencies.c); - // OPT-03: `ORDER BY latency_ms LIMIT 1 OFFSET k` uses the index instead of - // materializing and sorting every latency value of the window in JS. - const percentile = (p: number): number => this.latencyPercentile(since, latencyCount, p); + // B-02: every percentile comes from one ordered pass. The previous version ran + // a full `ORDER BY latency_ms ... OFFSET` per percentile (plus a COUNT), i.e. + // two extra sorts per cache miss; the window function replaces all three with a + // single statement and returns the nearest-rank values of the old definition. + const percentileRow = this.stmt( + `SELECT + COALESCE(MAX(CASE WHEN rn = MIN(total - 1, CAST((total * 50) / 100 AS INTEGER)) THEN latency_ms END), 0) AS p50, + COALESCE(MAX(CASE WHEN rn = MIN(total - 1, CAST((total * 95) / 100 AS INTEGER)) THEN latency_ms END), 0) AS p95 + FROM ( + SELECT latency_ms, + ROW_NUMBER() OVER (ORDER BY latency_ms ASC) - 1 AS rn, + COUNT(*) OVER () AS total + FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL + )`, + ) + .get(since) as Row; const seriesRows = this.stmt( `SELECT CAST(ts / ? AS INTEGER) * ? AS bucket, @@ -941,8 +976,8 @@ export class Repo { reasoningTokens: num(totalsRow.reasoning_tokens), cachedTokens: num(totalsRow.cached_tokens), avgLatencyMs: Math.round(num(totalsRow.avg_latency)), - p50LatencyMs: percentile(50), - p95LatencyMs: percentile(95), + p50LatencyMs: num(percentileRow.p50), + p95LatencyMs: num(percentileRow.p95), avgTtfbMs: Math.round(num(totalsRow.avg_ttfb)), }, activeRequests, diff --git a/src/db/schema.ts b/src/db/schema.ts index 694a271..ef250e0 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -1,7 +1,21 @@ /** * SQLite schema. Executed idempotently on boot. */ + +/** + * Schema generation recorded in `PRAGMA user_version`. Bump it whenever a migration + * changes the shape of the database, so `/admin/api/diagnostics` can tell an operator + * that the data file was written by a different build. + * + * It is stamped by `openDatabase` (not by `SCHEMA_SQL`) because writing the header needs + * the database write lock: keeping the boot script lock-free when the file is already + * initialized lets a second process apply it while another holds a transaction. + */ +export const SCHEMA_VERSION = 1; + export const SCHEMA_SQL = ` +-- B-04: set before the WAL switch so lock contention during boot also waits. +PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; diff --git a/tests/db-hardening.test.ts b/tests/db-hardening.test.ts new file mode 100644 index 0000000..0ab0349 --- /dev/null +++ b/tests/db-hardening.test.ts @@ -0,0 +1,481 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Worker } from 'node:worker_threads'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { AttemptRow, RequestLogRow } from '../src/types.js'; +import { openDatabase, type DbHandle } from '../src/db/index.js'; +import { Repo } from '../src/db/repos.js'; +import { SCHEMA_SQL, SCHEMA_VERSION } from '../src/db/schema.js'; +import { createTestDb, testConfig, type TestDb } from './helpers.js'; + +let db: TestDb; + +beforeEach(() => { + db = createTestDb('okr-hardening-'); +}); + +afterEach(() => { + db.cleanup(); +}); + +function makeLog(overrides: Partial & { id: string }): RequestLogRow { + return { + ts: Date.now(), + keyId: 'k1', + keyName: 'e2e', + providerId: 'p1', + providerName: 'Primary', + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 10, + ttfbMs: 5, + inputTokens: 1, + outputTokens: 2, + totalTokens: 3, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: '127.0.0.1', + userAgent: 'test', + ...overrides, + }; +} + +function makeAttempt(overrides: Partial & { id: string; requestId: string }): AttemptRow { + return { + ts: Date.now(), + providerId: 'p1', + providerName: 'Primary', + attempt: 1, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 5, + ...overrides, + }; +} + +/* ------------------------------------------------------------------------ B-01 */ + +describe('B-01: monotonic provider cooldown', () => { + it('keeps a longer active cooldown when a shorter failure arrives', () => { + db.repo.createProvider({ id: 'p', name: 'p', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('p', 429, 'slow down', 60_000); + const long = db.repo.getProvider('p')!.cooldownUntil!; + expect(long).toBeGreaterThan(Date.now()); + + // 5 s must not shorten the 60 s deadline already in force. + db.repo.recordProviderFailure('p', 503, 'again', 5_000); + expect(db.repo.getProvider('p')!.cooldownUntil).toBe(long); + + // The scheduler's `cooldownMs: 0` probe must not clear an active cooldown either. + db.repo.recordProviderFailure('p', 429, 'probe', 0); + const after = db.repo.getProvider('p')!; + expect(after.cooldownUntil).toBe(long); + expect(after.failureCount).toBe(3); + expect(after.status).toBe('cooldown'); + expect(after.lastError).toBe('probe'); + }); + + it('pins cooldownMs <= 0 to now only when no cooldown is active', () => { + db.repo.createProvider({ id: 'q', name: 'q', baseUrl: 'http://x/v1', apiKey: 'k' }); + const before = Date.now(); + db.repo.recordProviderFailure('q', 429, 'rate limited', 0); + const until = db.repo.getProvider('q')!.cooldownUntil; + expect(until).not.toBeNull(); + expect(until!).toBeGreaterThanOrEqual(before); + expect(until!).toBeLessThanOrEqual(Date.now()); + }); + + it('still clears the deadline when the failure is not cooldown-worthy', () => { + db.repo.createProvider({ id: 'r', name: 'r', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('r', 429, 'slow down', 60_000); + expect(db.repo.getProvider('r')!.cooldownUntil).not.toBeNull(); + + db.repo.recordProviderFailure('r', 400, 'bad request', 60_000); + const row = db.repo.getProvider('r')!; + expect(row.cooldownUntil).toBeNull(); + expect(row.status).toBe('error'); + }); +}); + +/* ------------------------------------------------------------------------ B-02 */ + +/** Nearest-rank definition the old `latencyPercentile` implemented. */ +function referencePercentile(values: number[], p: number): number { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * values.length))] ?? 0; +} + +/** + * Wraps `prepare` so the test can count how often the ordered latency statement is + * prepared and executed. The repo caches statements, so a second query per + * `statsOverview` call only shows up on the execution counter. + */ +function instrumentLatencyQueries(target: TestDb): { + repo: Repo; + latencyPrepares: () => number; + latencyExecutions: () => number; +} { + let prepares = 0; + let executions = 0; + const ordered = (sql: string): boolean => /ORDER BY latency_ms/i.test(sql); + const original = target.handle.db.prepare.bind(target.handle.db); + (target.handle.db as unknown as { prepare: (sql: string) => unknown }).prepare = (sql: string) => { + if (ordered(sql)) prepares += 1; + const statement = original(sql) as { + get: (...args: unknown[]) => unknown; + all: (...args: unknown[]) => unknown; + run: (...args: unknown[]) => unknown; + }; + return new Proxy(statement, { + get(inner, property) { + const value = Reflect.get(inner, property) as unknown; + if (typeof value !== 'function') return value; + return (...args: unknown[]) => { + if (ordered(sql)) executions += 1; + return (value as (...rest: unknown[]) => unknown).apply(inner, args); + }; + }, + }); + }; + return { repo: new Repo(target.handle.db), latencyPrepares: () => prepares, latencyExecutions: () => executions }; +} + +describe('B-02: single-pass latency percentiles', () => { + it('keeps the nearest-rank values for odd, even and null-bearing fixtures', () => { + expect(db.repo.statsOverview(3_600_000, 60_000, 0).totals.p50LatencyMs).toBe(0); + + const fixtures: Array> = [ + [10, 20, 30], + [10, 30], + [1, 7, 3, null, 99, 42, 5, 13, 8, 21], + [5], + Array.from({ length: 24 }, (_, index) => (index * 7) % 23), + ]; + for (const [fixture, latencies] of fixtures.entries()) { + const fixtureDb = createTestDb(`okr-b02-${fixture}-`); + try { + latencies.forEach((latency, index) => { + fixtureDb.repo.insertLog( + makeLog({ id: `f${fixture}-${index}`, latencyMs: latency, ts: Date.now() - 1_000 }), + ); + }); + const present = latencies.filter((value): value is number => value !== null); + const stats = fixtureDb.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs, `fixture ${fixture} p50`).toBe(referencePercentile(present, 50)); + expect(stats.totals.p95LatencyMs, `fixture ${fixture} p95`).toBe(referencePercentile(present, 95)); + expect(stats.totals.requests).toBe(latencies.length); + } finally { + fixtureDb.cleanup(); + } + } + }); + + it('prepares and executes exactly one ordered latency statement per statsOverview call', () => { + const spyDb = createTestDb('okr-b02-spy-'); + try { + const spy = instrumentLatencyQueries(spyDb); + for (const [index, latency] of [10, 20, 30].entries()) { + spyDb.repo.insertLog(makeLog({ id: `s${index}`, latencyMs: latency, ts: Date.now() - 1_000 })); + } + + const stats = spy.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(20); + expect(stats.totals.p95LatencyMs).toBe(30); + expect(spy.latencyPrepares()).toBe(1); + expect(spy.latencyExecutions()).toBe(1); + + // A second call reuses the cached statement: still one statement per call. + spy.repo.statsOverview(3_600_000, 60_000, 0); + expect(spy.latencyPrepares()).toBe(1); + expect(spy.latencyExecutions()).toBe(2); + } finally { + spyDb.cleanup(); + } + }); +}); + +/* ------------------------------------------------------------------------ B-03 */ + +function trackTransactions(target: TestDb): { calls: string[]; restore: () => void } { + const calls: string[] = []; + const original = target.handle.db.exec.bind(target.handle.db); + (target.handle.db as unknown as { exec: (sql: string) => unknown }).exec = (sql: string) => { + calls.push(sql); + return original(sql); + }; + return { + calls, + restore: () => { + (target.handle.db as unknown as { exec: (sql: string) => unknown }).exec = original; + }, + }; +} + +describe('B-03: transactional log pruning', () => { + it('deleteLogsBefore wraps both deletes in one transaction and returns the request_logs count', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'r1', ts: now })); + db.repo.insertLog(makeLog({ id: 'r2', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'a1', requestId: 'r1', ts: now })); + + const tracked = trackTransactions(db); + let removed: number; + try { + removed = db.repo.deleteLogsBefore(now + 1); + } finally { + tracked.restore(); + } + expect(removed!).toBe(2); + expect(tracked.calls.filter((sql) => /^BEGIN/i.test(sql))).toHaveLength(1); + expect(tracked.calls.filter((sql) => /^COMMIT/i.test(sql))).toHaveLength(1); + expect(db.repo.listAttempts('r1')).toHaveLength(0); + }); + + it('clearLogs empties both tables and reports the request_logs count', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'c1', ts: now })); + db.repo.insertLog(makeLog({ id: 'c2', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'ca', requestId: 'c1', ts: now })); + + const tracked = trackTransactions(db); + let removed: number; + try { + removed = db.repo.clearLogs(); + } finally { + tracked.restore(); + } + expect(removed!).toBe(2); + expect(tracked.calls.filter((sql) => /^BEGIN/i.test(sql))).toHaveLength(1); + expect(tracked.calls.filter((sql) => /^COMMIT/i.test(sql))).toHaveLength(1); + expect(db.repo.listLogs({ limit: 10 }).total).toBe(0); + expect(db.repo.listAttempts('c1')).toHaveLength(0); + }); + + it('an outer transaction that throws rolls back the prune of both tables', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'keep-1', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'keep-a', requestId: 'keep-1', ts: now })); + + expect(() => + db.repo.transaction(() => { + db.repo.deleteLogsBefore(now + 1); + throw new Error('crash'); + }), + ).toThrow('crash'); + + expect(db.repo.listLogs({ limit: 10 }).total).toBe(1); + expect(db.repo.listAttempts('keep-1')).toHaveLength(1); + }); +}); + +/* ------------------------------------------------------------------------ B-04 */ + +const WRITE_WORKER = ` +const { DatabaseSync } = require('node:sqlite'); +const { parentPort, workerData } = require('node:worker_threads'); +const db = new DatabaseSync(workerData.dbPath); +try { + db.exec(workerData.schemaSql); + parentPort.postMessage({ phase: 'started' }); + const startedAt = Date.now(); + db.exec("INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('from-worker', 2, 'test', 'worker.insert', NULL, NULL)"); + parentPort.postMessage({ ok: true, waitedMs: Date.now() - startedAt }); +} catch (error) { + parentPort.postMessage({ ok: false, error: String((error && error.message) || error) }); +} finally { + db.close(); +} +`; + +interface WorkerOutcome { + ok?: boolean; + error?: string; + waitedMs?: number; + phase?: string; +} + +/** Runs the write in a real second connection so the busy handler can actually wait. */ +function startWriteWorker(dbPath: string, schemaSql: string): { started: Promise; result: Promise } { + const worker = new Worker(WRITE_WORKER, { eval: true, workerData: { dbPath, schemaSql } }); + let markStarted: () => void = () => {}; + const started = new Promise((resolve) => { + markStarted = resolve; + }); + const result = new Promise((resolve, reject) => { + worker.on('message', (message: WorkerOutcome) => { + if (message.phase === 'started') { + markStarted(); + return; + } + resolve(message); + void worker.terminate(); + }); + worker.on('error', reject); + }); + return { started, result }; +} + +function openOwnDb(prefix: string): { dbPath: string; handle: DbHandle; close: () => void } { + const dir = mkdtempSync(join(tmpdir(), prefix)); + const config = testConfig(dir); + const handle = openDatabase(config); + return { + dbPath: config.dbPath, + handle, + close: () => { + handle.db.close(); + rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +describe('B-04: PRAGMA busy_timeout in SCHEMA_SQL', () => { + it('ships the pragma and applies it to every connection opened by openDatabase', () => { + expect(SCHEMA_SQL).toContain('PRAGMA busy_timeout = 5000;'); + const own = openOwnDb('okr-b04-pragma-'); + try { + const row = own.handle.db.prepare('PRAGMA busy_timeout').get() as Record; + expect(Object.values(row)).toContain(5000); + } finally { + own.close(); + } + }); + + it('stamps the schema generation into PRAGMA user_version and re-stamps an older file', () => { + const dir = mkdtempSync(join(tmpdir(), 'okr-b04-version-')); + const config = testConfig(dir); + try { + const first = openDatabase(config); + const stamped = first.db.prepare('PRAGMA user_version').get() as Record; + expect(Object.values(stamped)).toContain(SCHEMA_VERSION); + // Simulate a file written by an older build: the next open must re-stamp it. + first.db.exec('PRAGMA user_version = 0'); + first.db.close(); + + const second = openDatabase(config); + try { + const restamped = second.db.prepare('PRAGMA user_version').get() as Record; + expect(Object.values(restamped)).toContain(SCHEMA_VERSION); + } finally { + second.db.close(); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('lets a second connection wait for the write lock instead of failing SQLITE_BUSY', async () => { + const own = openOwnDb('okr-b04-wait-'); + try { + own.handle.db.exec('BEGIN IMMEDIATE'); + own.handle.db.exec( + "INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('held', 1, 'test', 'hold', NULL, NULL)", + ); + + const worker = startWriteWorker(own.dbPath, SCHEMA_SQL); + await worker.started; + // Commit while the worker is blocked in ITS insert: with busy_timeout the + // worker retries internally and succeeds, without it the insert throws at once. + await new Promise((resolve) => setTimeout(resolve, 250)); + own.handle.db.exec('COMMIT'); + + const outcome = await worker.result; + expect(outcome.error).toBeUndefined(); + expect(outcome.ok).toBe(true); + expect(outcome.waitedMs ?? 0).toBeGreaterThan(50); + } finally { + try { + own.handle.db.exec('ROLLBACK'); + } catch { + /* already committed */ + } + own.close(); + } + }); + + it('control: the same second connection fails immediately with the pragma disabled', async () => { + const own = openOwnDb('okr-b04-control-'); + try { + own.handle.db.exec('BEGIN IMMEDIATE'); + own.handle.db.exec( + "INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('held-control', 1, 'test', 'hold', NULL, NULL)", + ); + + const worker = startWriteWorker(own.dbPath, 'PRAGMA busy_timeout = 0;'); + await worker.started; + const outcome = await worker.result; + expect(outcome.ok).toBe(false); + expect(outcome.error ?? '').toMatch(/locked|busy/i); + } finally { + try { + own.handle.db.exec('ROLLBACK'); + } catch { + /* nothing held */ + } + own.close(); + } + }); +}); + +/* ------------------------------------------------------------------------ B-18 */ + +describe('B-18: log query filters', () => { + it('matches `model` case-insensitively on a substring and keeps total consistent', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'm1', ts: now - 3_000, model: 'opencode/flint-40b-free' })); + db.repo.insertLog(makeLog({ id: 'm2', ts: now - 2_000, model: 'OPENCODE/Flint-Large' })); + db.repo.insertLog(makeLog({ id: 'm3', ts: now - 1_000, model: 'other/model' })); + + const lower = db.repo.listLogs({ model: 'flint' }); + expect(lower.total).toBe(2); + expect(lower.rows.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + const upper = db.repo.listLogs({ model: 'FLINT' }); + expect(upper.total).toBe(2); + expect(upper.rows.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + // `total` counts the whole filtered set, not just the returned page. + const paged = db.repo.listLogs({ model: 'flint', limit: 1, offset: 1 }); + expect(paged.total).toBe(2); + expect(paged.rows).toHaveLength(1); + + expect(db.repo.listLogs({ model: 'nothing-like-this' }).total).toBe(0); + }); + + it('treats `%`, `_` and `\\` in the model filter literally', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'lit1', ts: now - 3_000, model: 'a%b' })); + db.repo.insertLog(makeLog({ id: 'lit2', ts: now - 2_000, model: 'axb' })); + db.repo.insertLog(makeLog({ id: 'lit3', ts: now - 1_000, model: 'a_b' })); + + const percent = db.repo.listLogs({ model: '%' }); + expect(percent.total).toBe(1); + expect(percent.rows[0]?.id).toBe('lit1'); + + expect(db.repo.listLogs({ model: 'a_b' }).total).toBe(1); + expect(db.repo.listLogs({ model: 'a_b' }).rows[0]?.id).toBe('lit3'); + expect(db.repo.listLogs({ model: '_' }).total).toBe(1); + expect(db.repo.listLogs({ model: 'a\\b' }).total).toBe(0); + }); + + it('bounds the search term to 200 characters instead of scanning an unbounded LIKE', () => { + const long = 'a'.repeat(200); + db.repo.insertLog(makeLog({ id: 'search-1', ts: Date.now() - 1_000, model: long })); + + // The full term (203 chars) is not a substring of the row; only the bounded + // 200-char prefix is, so a match proves the length clamp is in place. + expect(db.repo.listLogs({ search: `${long}zzz` }).total).toBe(1); + expect(db.repo.listLogs({ search: long }).total).toBe(1); + expect(db.repo.listLogs({ search: 'zzz' }).total).toBe(0); + }); +}); From 8a763cee1864670ff8d9c2b4e6157eb7f5159b26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Sun, 6 Dec 2026 22:28:29 +0700 Subject: [PATCH 4/6] fix(web): fix dashboard a11y, state and data-correctness defects --- tests/web-a11y.test.ts | 172 +++++++ tests/web-lib-realtime.test.ts | 97 ++++ tests/web-lib-state.test.ts | 219 +++++++++ web/src/components/AnimatedNumber.tsx | 34 +- web/src/components/KpiCard.tsx | 8 +- web/src/components/SetupBanner.tsx | 25 +- web/src/components/charts/AreaChart.tsx | 12 +- web/src/components/layout/LiveIndicator.tsx | 38 +- web/src/components/layout/Topbar.tsx | 1 + web/src/components/ui/Card.tsx | 10 +- web/src/components/ui/Feedback.tsx | 27 +- web/src/components/ui/Input.tsx | 158 ++++--- web/src/components/ui/Modal.tsx | 19 +- web/src/components/ui/misc.tsx | 87 +--- web/src/lib/animation.ts | 32 ++ web/src/lib/api.ts | 7 - web/src/lib/auth-state.ts | 38 ++ web/src/lib/auth.tsx | 43 +- web/src/lib/field-aria.ts | 40 ++ web/src/lib/format.ts | 59 --- web/src/lib/hooks.ts | 64 --- web/src/lib/log-filter.ts | 131 ++++++ web/src/lib/readiness.tsx | 10 +- web/src/lib/realtime-policy.ts | 68 +++ web/src/lib/realtime.ts | 49 +- web/src/lib/scroll-lock.ts | 51 +++ web/src/lib/selection.ts | 26 ++ web/src/lib/series.ts | 28 ++ web/src/lib/stats-view.ts | 34 ++ web/src/lib/theme.ts | 6 - web/src/lib/types.ts | 18 - web/src/pages/Logs.tsx | 484 ++++++++++++++------ web/src/pages/Models.tsx | 98 ++-- web/src/pages/Overview.tsx | 67 ++- web/src/pages/Providers.tsx | 73 ++- web/src/pages/Settings.tsx | 260 ++++++++++- web/src/styles.css | 43 +- 37 files changed, 2014 insertions(+), 622 deletions(-) create mode 100644 tests/web-a11y.test.ts create mode 100644 tests/web-lib-realtime.test.ts create mode 100644 tests/web-lib-state.test.ts create mode 100644 web/src/lib/animation.ts create mode 100644 web/src/lib/auth-state.ts create mode 100644 web/src/lib/field-aria.ts create mode 100644 web/src/lib/log-filter.ts create mode 100644 web/src/lib/realtime-policy.ts create mode 100644 web/src/lib/scroll-lock.ts create mode 100644 web/src/lib/selection.ts create mode 100644 web/src/lib/series.ts create mode 100644 web/src/lib/stats-view.ts diff --git a/tests/web-a11y.test.ts b/tests/web-a11y.test.ts new file mode 100644 index 0000000..4e9f5cc --- /dev/null +++ b/tests/web-a11y.test.ts @@ -0,0 +1,172 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { fieldAriaIds, mergeDescribedBy } from '../web/src/lib/field-aria.js'; + +const webRoot = new URL('../web/src/', import.meta.url); +const stylesCss = readFileSync(fileURLToPath(new URL('styles.css', webRoot)), 'utf8'); +const inputSource = readFileSync(fileURLToPath(new URL('components/ui/Input.tsx', webRoot)), 'utf8'); +const miscSource = readFileSync(fileURLToPath(new URL('components/ui/misc.tsx', webRoot)), 'utf8'); + +/* ------------------------------------------------------------- CSS helpers */ + +function block(css: string, selector: string): string { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const match = new RegExp(`${escaped}\\s*\\{([\\s\\S]*?)\\n\\}`).exec(css); + if (!match?.[1]) throw new Error(`missing CSS block ${selector}`); + return match[1]; +} + +function token(cssBlock: string, name: string): string { + const match = new RegExp(`--${name}:\\s*([^;]+);`).exec(cssBlock); + if (!match?.[1]) throw new Error(`missing token --${name}`); + return match[1].trim(); +} + +function channel(value: number): number { + const srgb = value / 255; + return srgb <= 0.03928 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4; +} + +function luminance(hex: string): number { + const value = hex.replace('#', ''); + const r = Number.parseInt(value.slice(0, 2), 16); + const g = Number.parseInt(value.slice(2, 4), 16); + const b = Number.parseInt(value.slice(4, 6), 16); + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); +} + +/** WCAG 2.x contrast ratio between two opaque `#rrggbb` colours. */ +function contrastRatio(foreground: string, background: string): number { + const a = luminance(foreground); + const b = luminance(background); + const [hi, lo] = a >= b ? [a, b] : [b, a]; + return (hi + 0.05) / (lo + 0.05); +} + +const light = block(stylesCss, ':root'); +const dark = block(stylesCss, '.dark'); + +/* ------------------------------------------------------------------- tests */ + +describe('C-07 focus ring contrast', () => { + it('C-07: the ring clears the 3:1 non-text minimum on both surfaces', () => { + for (const [theme, tokens] of [ + ['light', light], + ['dark', dark], + ] as const) { + const ring = token(tokens, 'ring'); + expect(ring.startsWith('#'), `${theme} --ring must be an opaque hex colour`).toBe(true); + expect(contrastRatio(ring, token(tokens, 'bg')), `${theme} ring on --bg`).toBeGreaterThanOrEqual(3); + expect(contrastRatio(ring, token(tokens, 'bg-2')), `${theme} ring on --bg-2`).toBeGreaterThanOrEqual(3); + } + }); + + it('C-07: fields keep a keyboard focus indicator (no suppressed outline)', () => { + expect(block(stylesCss, '.input,\n.select,\n.textarea')).not.toContain('outline: none'); + const focusVisible = /\.input:focus-visible,\s*\n\.select:focus-visible,\s*\n\.textarea:focus-visible\s*\{([\s\S]*?)\n\}/.exec( + stylesCss, + ); + expect(focusVisible?.[1]).toContain('outline: 2px solid var(--ring)'); + expect(focusVisible?.[1]).toContain('outline-offset: 1px'); + }); +}); + +describe('C-16 subtle text contrast', () => { + it('C-16: --fg-subtle meets AA (4.5:1) on both surfaces in both themes', () => { + for (const [theme, tokens] of [ + ['light', light], + ['dark', dark], + ] as const) { + const subtle = token(tokens, 'fg-subtle'); + expect(contrastRatio(subtle, token(tokens, 'bg')), `${theme} subtle on --bg`).toBeGreaterThanOrEqual(4.5); + expect(contrastRatio(subtle, token(tokens, 'bg-2')), `${theme} subtle on --bg-2`).toBeGreaterThanOrEqual(4.5); + } + }); + + it('C-16: the hierarchy is preserved (muted stays stronger than subtle)', () => { + expect(contrastRatio(token(light, 'fg-muted'), token(light, 'bg'))).toBeGreaterThan( + contrastRatio(token(light, 'fg-subtle'), token(light, 'bg')), + ); + expect(contrastRatio(token(dark, 'fg-muted'), token(dark, 'bg'))).toBeGreaterThan( + contrastRatio(token(dark, 'fg-subtle'), token(dark, 'bg')), + ); + }); +}); + +describe('C-08 field aria wiring', () => { + it('C-08: an invalid field references its error node', () => { + const aria = fieldAriaIds('log-search', { hasError: true, hasHint: true }); + expect(aria.errorId).toBe('log-search-error'); + expect(aria.hintId).toBe('log-search-hint'); + expect(aria.describedBy).toBe('log-search-error'); + expect(aria.invalid).toBe(true); + }); + + it('C-08: a valid field with a hint describes the hint instead', () => { + const aria = fieldAriaIds('log-search', { hasHint: true }); + expect(aria.describedBy).toBe('log-search-hint'); + expect(aria.invalid).toBe(false); + }); + + it('C-08: a field with neither message describes nothing', () => { + expect(fieldAriaIds('x').describedBy).toBeUndefined(); + }); + + it('C-08: merging keeps caller ids and never duplicates', () => { + expect(mergeDescribedBy('external', 'field-hint')).toBe('external field-hint'); + expect(mergeDescribedBy(undefined, 'field-error')).toBe('field-error'); + expect(mergeDescribedBy('a a', 'a')).toBe('a'); + expect(mergeDescribedBy(undefined, undefined)).toBeUndefined(); + }); + + it('C-08: Field/controls consume the shared aria mapping', () => { + expect(inputSource).toContain('role="alert"'); + expect(inputSource).toContain('id={aria.errorId}'); + expect(inputSource).toContain('id={aria.hintId}'); + for (const component of ['TextInput', 'TextArea', 'Select']) { + expect(inputSource).toContain(`function ${component}(`); + } + expect(inputSource.match(/useControlAria\(/g)?.length ?? 0).toBeGreaterThanOrEqual(3); + }); +}); + +describe('C-09 switch semantics', () => { + const switchSource = /\nexport function Switch\(\{([\s\S]*?)\n\}\n/.exec(inputSource)?.[0] ?? ''; + + it('C-09: the switch is a role="switch" button wired to label and description', () => { + expect(switchSource).toContain('role="switch"'); + expect(switchSource).toContain('aria-checked={checked}'); + expect(switchSource).toContain('aria-labelledby={label ? labelId : undefined}'); + expect(switchSource).toContain('aria-describedby={description ? descriptionId : undefined}'); + }); + + it('C-09: no