From 19968470e3a20aaeb6977fd7f9cbfb9e29a1cb7e 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 20:19:16 +0700 Subject: [PATCH 1/5] fix(gateway): fail over on provider timeouts and keep byte fidelity --- src/gateway/auth.ts | 9 +- src/gateway/forward-headers.ts | 15 +- src/gateway/index.ts | 3 + src/gateway/logging.ts | 29 +- src/gateway/normalize.ts | 5 + src/gateway/not-found.ts | 48 +++ src/gateway/preauth.ts | 29 +- src/gateway/proxy.ts | 226 ++++++++++--- src/util/upstream.ts | 57 +++- tests/gateway-auth.test.ts | 82 +++++ tests/gateway-normalize.test.ts | 23 ++ tests/gateway-proxy-helpers.test.ts | 102 +++++- tests/gateway-stream.test.ts | 476 ++++++++++++++++++++++++++++ tests/util-upstream.test.ts | 160 +++++++++- 14 files changed, 1195 insertions(+), 69 deletions(-) create mode 100644 src/gateway/not-found.ts create mode 100644 tests/gateway-auth.test.ts create mode 100644 tests/gateway-stream.test.ts diff --git a/src/gateway/auth.ts b/src/gateway/auth.ts index cbce7ce..f6dcebb 100644 --- a/src/gateway/auth.ts +++ b/src/gateway/auth.ts @@ -6,12 +6,17 @@ import { ApiError } from '../util/errors.js'; export const NO_API_KEY_MESSAGE = 'No gateway API key configured. Create one in the dashboard (API Keys tab).'; -/** Reads the gateway key from `Authorization: Bearer ` or `x-api-key`. */ +/** + * Reads the gateway key from `Authorization: Bearer ` or `x-api-key`. + * GW-13: any other `Authorization` scheme (Basic, Digest, a bare token) is treated + * as absent instead of being used verbatim as the key — SPEC §Auth documents + * `Bearer` or `x-api-key` only. + */ export function extractApiKey(headers: IncomingHttpHeaders): string | null { const authorization = headers.authorization; if (typeof authorization === 'string' && authorization.trim().length > 0) { const match = /^bearer\s+(.+)$/i.exec(authorization.trim()); - const token = (match?.[1] ?? authorization).trim(); + const token = match?.[1]?.trim() ?? ''; if (token.length > 0) return token; } const headerKey = headers['x-api-key']; diff --git a/src/gateway/forward-headers.ts b/src/gateway/forward-headers.ts index 21a9147..fdee0a0 100644 --- a/src/gateway/forward-headers.ts +++ b/src/gateway/forward-headers.ts @@ -10,6 +10,10 @@ import type { IncomingHttpHeaders } from 'node:http'; */ const FORWARDED_HEADERS = [ 'anthropic-beta', + // GW-07: the client's Anthropic API version + browser-access opt-in must reach + // the provider, otherwise newer API versions are unreachable. + 'anthropic-version', + 'anthropic-dangerous-direct-browser-access', 'openai-beta', 'accept', 'accept-language', @@ -31,14 +35,19 @@ function firstValue(value: string | string[] | undefined): string | null { /** * Builds the upstream header allowlist from the client headers. `accept` is only - * defaulted when streaming: a non-streaming client that sent its own `accept` - * keeps it, and the default is required for SSE providers that branch on it. + * defaulted to JSON for non-streaming calls here; a streaming default + * (`text/event-stream`) is applied by `upstreamFetch` (GW-06), so a client that + * did send its own `accept` keeps it on every surface. */ export function forwardHeaders(headers: IncomingHttpHeaders, options: { acceptJson?: boolean } = {}): Record { const out: Record = {}; for (const name of FORWARDED_HEADERS) { const value = firstValue(headers[name]); - if (value !== null) out[name] = value; + if (value === null) continue; + // A bare wildcard means "anything", so it must not shadow the concrete + // surface default (`application/json` / `text/event-stream`, GW-06). + if (name === 'accept' && value.trim() === '*/*') continue; + out[name] = value; } for (const [name, raw] of Object.entries(headers)) { const lower = name.toLowerCase(); diff --git a/src/gateway/index.ts b/src/gateway/index.ts index cc3aba9..816258c 100644 --- a/src/gateway/index.ts +++ b/src/gateway/index.ts @@ -2,6 +2,7 @@ import type { FastifyInstance } from 'fastify'; import type { AppContext } from '../core/context.js'; import { installGatewayErrorHandler } from './errors.js'; import { registerModelsRoutes } from './models-route.js'; +import { registerUnknownGatewayRoutes } from './not-found.js'; import { installGatewayHooks } from './preauth.js'; import { registerProxyRoutes } from './proxy.js'; @@ -27,5 +28,7 @@ export async function registerGatewayRoutes(app: FastifyInstance, ctx: AppContex installGatewayHooks(scope, ctx); registerProxyRoutes(scope, ctx); registerModelsRoutes(scope, ctx); + // Registered last so it only handles paths no real route claimed (GW-04). + registerUnknownGatewayRoutes(scope, ctx); }); } diff --git a/src/gateway/logging.ts b/src/gateway/logging.ts index 873bc7f..386e23c 100644 --- a/src/gateway/logging.ts +++ b/src/gateway/logging.ts @@ -1,8 +1,33 @@ import type { AppContext } from '../core/context.js'; +import type { ProviderEvent, RequestEndEvent, RequestStartEvent } from '../core/events.js'; import type { ApiKeyRow, AttemptRow, ProviderRow, RequestLogRow, Surface, Usage } from '../types.js'; import { uuid } from '../util/crypto.js'; import { emptyUsage } from './usage.js'; +/** + * GW-14: dashboard SSE listeners run synchronously inside the request path, so a + * throwing listener must never take the reply (or the log row) down with it. + */ +function guardedEmit(ctx: AppContext, name: string, emit: () => void): void { + try { + emit(); + } catch (error) { + ctx.logger.warn({ err: error, event: name }, 'gateway event listener threw'); + } +} + +export function emitRequestStart(ctx: AppContext, event: RequestStartEvent): void { + guardedEmit(ctx, 'request:start', () => ctx.events.emitRequestStart(event)); +} + +export function emitRequestEnd(ctx: AppContext, event: RequestEndEvent): void { + guardedEmit(ctx, 'request:end', () => ctx.events.emitRequestEnd(event)); +} + +export function emitProvider(ctx: AppContext, event: ProviderEvent): void { + guardedEmit(ctx, 'provider:update', () => ctx.events.emitProvider(event)); +} + export function newAttempt(input: { requestId: string; providerId: string; @@ -85,6 +110,6 @@ export function recordRequestLog(ctx: AppContext, input: RequestLogInput): Reque } catch (error) { ctx.logger.warn({ err: error, requestId: input.requestId }, 'failed to insert gateway request log'); } - ctx.events.emitRequestEnd({ log }); + emitRequestEnd(ctx, { log }); return log; -} \ No newline at end of file +} diff --git a/src/gateway/normalize.ts b/src/gateway/normalize.ts index d8238eb..3fce890 100644 --- a/src/gateway/normalize.ts +++ b/src/gateway/normalize.ts @@ -64,6 +64,11 @@ export function normalizeBody( options: { countTokens?: boolean } = {}, ): NormalizedBody { const next: Json = { ...body }; + // 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(); + } let requestedEffort = requestedEffortFor(surface, body); let appliedEffort: string | null = null; diff --git a/src/gateway/not-found.ts b/src/gateway/not-found.ts new file mode 100644 index 0000000..27d6f0a --- /dev/null +++ b/src/gateway/not-found.ts @@ -0,0 +1,48 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; +import type { AppContext } from '../core/context.js'; +import { ApiError } from '../util/errors.js'; +import { sendApiError, surfaceForUrl } from './errors.js'; +import { recordRequestLog } from './logging.js'; +import { gatewayState } from './preauth.js'; + +/** + * 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 + * access) and no `request_logs` row was written (SPEC §Auth, golden rule 3). + * + * 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. + */ +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 userAgent = request.headers['user-agent']; + state.logged = true; + recordRequestLog(ctx, { + requestId: state.requestId, + startedAt: state.startedAt, + key: state.key, + model: null, + surface, + stream: false, + status: error.status, + ok: false, + errorCode: error.code ?? error.type, + errorMessage: error.message, + ttfbMs: null, + attempts: 0, + clientIp: request.ip ?? null, + userAgent: typeof userAgent === 'string' ? userAgent : null, + }); + sendApiError(reply, surface, error, state.requestId); + }; + + 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 141175b..d22035b 100644 --- a/src/gateway/preauth.ts +++ b/src/gateway/preauth.ts @@ -5,7 +5,7 @@ import { uuid } from '../util/crypto.js'; import { ApiError } from '../util/errors.js'; import { authenticate } from './auth.js'; import { sendApiError, surfaceForUrl } from './errors.js'; -import { recordRequestLog } from './logging.js'; +import { emitRequestStart, recordRequestLog } from './logging.js'; /** Per-request state produced by the pre-body authentication hook. */ export interface GatewayRequestState { @@ -15,8 +15,12 @@ export interface GatewayRequestState { key: ApiKeyRow | null; /** True once the single request_logs row for this request has been written. */ logged: boolean; - /** Raw body text captured by the gateway JSON parser (FIX-09). */ - rawBody: string | null; + /** + * Raw client bytes captured by the gateway JSON parser (FIX-09/GW-08). Kept as a + * Buffer: decoding to a string would rewrite invalid UTF-8 into U+FFFD and break + * the documented byte-for-byte forwarding. + */ + rawBody: Buffer | null; } declare module 'fastify' { @@ -46,7 +50,7 @@ export function createPreAuthHook(ctx: AppContext) { return; } state.key = key; - ctx.events.emitRequestStart({ + emitRequestStart(ctx, { id: state.requestId, ts: state.startedAt, surface: surfaceForUrl(request.url), @@ -84,7 +88,7 @@ function rejectUnauthenticated( // Every log row gets its paired start event, rejections included, so SSE // consumers never see an orphan `request:end`. - ctx.events.emitRequestStart({ + emitRequestStart(ctx, { id: state.requestId, ts: state.startedAt, surface, @@ -127,23 +131,24 @@ export function gatewayState(request: FastifyRequest): GatewayRequestState { /** * Registers the gateway pre-auth hook plus the raw-body JSON parser on the - * encapsulated gateway scope. The parser keeps the verbatim body text so - * unmodified payloads can be forwarded byte-for-byte (FIX-09). + * encapsulated gateway scope. The parser keeps the verbatim bytes (GW-08: + * `parseAs: 'buffer'`) so unmodified payloads are forwarded byte-for-byte, even + * when the client body is not valid UTF-8. */ export function installGatewayHooks(scope: FastifyInstance, ctx: AppContext): void { scope.addHook('onRequest', createPreAuthHook(ctx)); // Encapsulated to this scope: admin keeps its own lenient parser. - scope.addContentTypeParser('application/json', { parseAs: 'string' }, (request, body, done) => { - const text = typeof body === 'string' ? body : String(body ?? ''); - if (request.gateway) request.gateway.rawBody = text; - if (text.trim().length === 0) { + scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (request, body, done) => { + const bytes = Buffer.isBuffer(body) ? body : Buffer.from(String(body ?? ''), 'utf8'); + if (request.gateway) request.gateway.rawBody = bytes; + if (bytes.length === 0) { // The handler reports the missing body with the surface-shaped error. done(null, undefined); return; } try { - const parsed: unknown = JSON.parse(text); + const parsed: unknown = JSON.parse(bytes.toString('utf8')); if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { done( new ApiError('invalid_request_error', 'Request body must be a JSON object.', { diff --git a/src/gateway/proxy.ts b/src/gateway/proxy.ts index d563526..7f29140 100644 --- a/src/gateway/proxy.ts +++ b/src/gateway/proxy.ts @@ -6,7 +6,7 @@ import { SseParser } from '../util/sse.js'; import { upstreamFetch, type UpstreamResponse } from '../util/upstream.js'; import { forwardHeaders } from './forward-headers.js'; import { sendApiError } from './errors.js'; -import { newAttempt, recordRequestLog } from './logging.js'; +import { emitProvider, newAttempt, recordRequestLog } from './logging.js'; import { normalizeBody } from './normalize.js'; import { gatewayState } from './preauth.js'; import { orderProviders, parseRotationStrategy } from './rotation.js'; @@ -19,6 +19,23 @@ export interface ProxyRoute { countTokens?: boolean; } +/** Hard cap on one unterminated SSE frame (GW-05); prevents unbounded buffering. */ +export const SSE_MAX_FRAME_BYTES = 1024 * 1024; +/** `stream_idle_timeout_ms` bounds (SPEC §2.5). */ +const MIN_STREAM_IDLE_MS = 1_000; +const DEFAULT_STREAM_IDLE_MS = 120_000; + +/** Upstream response headers that are meaningful to SDK clients (GW-09). */ +const RESPONSE_HEADER_ALLOWLIST = [ + 'retry-after', + 'request-id', + 'x-request-id', + 'openai-processing-ms', + 'openai-version', + 'anthropic-version', +] as const; +const RESPONSE_HEADER_PREFIXES = ['x-ratelimit-', 'anthropic-ratelimit-', 'x-stainless-'] as const; + const PROXY_ROUTES: ProxyRoute[] = [ { url: '/v1/chat/completions', surface: 'chat', upstreamPath: '/chat/completions' }, { url: '/v1/responses', surface: 'responses', upstreamPath: '/responses' }, @@ -53,6 +70,65 @@ function isTimeoutFailure(error: ApiError | null | undefined): boolean { return error.type === 'timeout_error' || error.code === 'upstream_timeout'; } +/** + * HTTP status for a failure that happened while reading an upstream response body + * (GW-03). A truncated body on a `2xx` upstream response is a gateway-side failure + * and must never be answered with that 2xx status, or SDKs parse the error envelope + * as a completion. An upstream status that is already an error is kept as is. + */ +export function bodyReadFailureStatus(upstreamStatus: number, timedOut: boolean): number { + if (timedOut) return 504; + return upstreamStatus >= 400 ? upstreamStatus : 502; +} + +/** Smallest still-active cooldown across enabled providers, or null (FEAT-06). */ +export function smallestCooldownUntil(providers: ProviderRow[], now = Date.now()): number | null { + let smallest: number | null = null; + for (const provider of providers) { + if (!provider.enabled) continue; + const until = provider.cooldownUntil; + if (until === null || until <= now) continue; + if (smallest === null || until < smallest) smallest = until; + } + return smallest; +} + +/** `Retry-After` is whole seconds and never 0 for a rate-limit answer (FEAT-06). */ +export function retryAfterSeconds(cooldownUntil: number | null, now = Date.now()): number { + if (cooldownUntil === null) return 1; + return Math.max(1, Math.ceil((cooldownUntil - now) / 1000)); +} + +/** + * Drops every character Node refuses in a header value (`ERR_INVALID_CHAR`): control + * characters, CR/LF injection attempts and anything outside Latin-1 (GW-10). + */ +export function sanitizeHeaderValue(value: string): string { + return value.replace(/[^\t\x20-\x7E\x80-\xFF]/g, ''); +} + +/** + * Picks the upstream response headers worth forwarding to the SDK client (GW-09): + * retry/backoff and rate-limit signals plus request ids. `overrides` (router + * headers, content-type/length, SSE framing) always win, and `content-encoding` + * never ships because the gateway already decoded the body. + */ +export function forwardedResponseHeaders( + upstream: Headers, + overrides: Record, +): Record { + const out: Record = {}; + upstream.forEach((value, name) => { + const lower = name.toLowerCase(); + const allowed = + (RESPONSE_HEADER_ALLOWLIST as readonly string[]).includes(lower) || + RESPONSE_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix)); + if (allowed && value.length > 0) out[lower] = value; + }); + for (const [name, value] of Object.entries(overrides)) out[name] = value; + return out; +} + interface SurfaceOutcome { status: number; ok: boolean; @@ -115,10 +191,12 @@ function readBody(request: FastifyRequest): Json { } function routerHeaders(provider: ProviderRow, requestId: string, attempts: number): Record { + // GW-10: provider ids/names are operator supplied; a CR/LF or a non-Latin-1 + // character would make Node throw ERR_INVALID_CHAR for every request. return { - 'x-opencode-router-provider': provider.id, - 'x-opencode-router-name': provider.name, - 'x-opencode-router-request-id': requestId, + 'x-opencode-router-provider': sanitizeHeaderValue(provider.id), + 'x-opencode-router-name': sanitizeHeaderValue(provider.name), + 'x-opencode-router-request-id': sanitizeHeaderValue(requestId), 'x-opencode-router-attempts': String(attempts), }; } @@ -155,8 +233,8 @@ interface AttemptOptions { userAgent: string; signal: AbortSignal; headers: Record; - /** Raw client body; forwarded verbatim so no bytes are rewritten (FIX-09). */ - rawBody: string | null; + /** Raw client bytes; forwarded verbatim so no byte is rewritten (FIX-09/GW-08). */ + rawBody: Buffer | null; body: Json; /** Streaming chat needs an SSE accept header when the client did not send one. */ stream: boolean; @@ -181,6 +259,9 @@ async function runAttempt( timeoutMs: options.timeoutMs, userAgent: options.userAgent, signal: options.signal, + stream: options.stream, + // GW-07: only the Anthropic Messages surface gets an anthropic-version default. + anthropic: route.surface === 'messages', // 3xx never followed: the provider key must not cross origins (FIX-08). redirect: 'manual', }); @@ -201,7 +282,7 @@ async function runAttempt( }), ); ctx.repo.recordProviderSuccess(provider.id, latencyMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'ok', status: upstream.status, @@ -241,7 +322,7 @@ async function runAttempt( // It is fatal for this request (single attempt, logged, cooled down) so the // credentials are never replayed to the redirect target. ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, options.cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'error', status: upstream.status, @@ -257,7 +338,7 @@ async function runAttempt( const retryAfter = retryAfterMs(upstream.headers.get('retry-after')); const cooldownMs = retryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, retryAfter); ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'cooldown', status: upstream.status, @@ -281,17 +362,37 @@ async function runAttempt( }; } if (isTimeoutReason(abortReason)) { - return { - kind: 'abort', - latencyMs, - timedOut: true, - error: - error instanceof ApiError - ? error - : new ApiError('timeout_error', `Upstream provider "${provider.name}" timed out.`, { - code: 'upstream_timeout', - }), - }; + const timeoutError = + error instanceof ApiError + ? error + : new ApiError('timeout_error', `Upstream provider "${provider.name}" timed out.`, { + code: 'upstream_timeout', + }); + // GW-02: a timed-out attempt is an ordinary failed attempt: it gets its + // `request_attempts` row, a provider cooldown and a provider event, so the + // provider is not retried first on the next request. + ctx.repo.insertAttempt( + newAttempt({ + requestId: options.requestId, + providerId: provider.id, + providerName: provider.name, + attempt: options.attempt, + status: null, + ok: false, + errorCode: timeoutError.code ?? timeoutError.type, + errorMessage: timeoutError.message, + latencyMs, + }), + ); + ctx.repo.recordProviderFailure(provider.id, null, timeoutError.message, options.cooldownMs); + emitProvider(ctx, { + providerId: provider.id, + state: 'error', + status: null, + message: timeoutError.message, + ts: Date.now(), + }); + return { kind: 'abort', latencyMs, timedOut: true, error: timeoutError }; } const apiError = error instanceof ApiError @@ -311,7 +412,7 @@ async function runAttempt( }), ); ctx.repo.recordProviderFailure(provider.id, null, apiError.message, options.cooldownMs); - ctx.events.emitProvider({ + emitProvider(ctx, { providerId: provider.id, state: 'error', status: null, @@ -462,19 +563,25 @@ async function streamSurface(input: StreamContext): Promise { let ttfbMs: number | null = null; let aborted = false; let timedOut = false; + let frameTooLarge = false; let ok = true; let errorCode: string | null = null; let errorMessage: string | null = null; try { reply.hijack(); - reply.raw.writeHead(upstream.status, { - 'content-type': 'text/event-stream; charset=utf-8', - 'cache-control': 'no-cache', - connection: 'keep-alive', - 'x-accel-buffering': 'no', - ...routerHeaders(provider, requestId, attempts), - }); + // GW-09: forward the upstream retry/rate-limit/request-id headers alongside the + // SSE framing; content-length is intentionally absent (chunked stream). + reply.raw.writeHead( + upstream.status, + forwardedResponseHeaders(upstream.headers, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache', + connection: 'keep-alive', + 'x-accel-buffering': 'no', + ...routerHeaders(provider, requestId, attempts), + }), + ); reply.raw.flushHeaders(); } catch (error) { disposeUpstream(upstream); @@ -568,6 +675,13 @@ async function streamSurface(input: StreamContext): Promise { break; } pending = offset >= merged.length ? Buffer.alloc(0) : merged.subarray(offset); + // GW-05: a provider streaming bytes without `\n\n` would otherwise buffer the + // whole response in memory (the request bodyLimit does not apply here). + if (pending.length > SSE_MAX_FRAME_BYTES) { + frameTooLarge = true; + upstream.abort('upstream_frame_too_large'); + break; + } if (reply.raw.writableNeedDrain) { const result = await waitForDrain(reply, guard, input.idleMs); if (result !== 'drain') { @@ -577,7 +691,13 @@ async function streamSurface(input: StreamContext): Promise { } } - if (!aborted) { + if (frameTooLarge) { + try { + reply.raw.end(); + } catch { + /* already closed */ + } + } else if (!aborted) { if (pending.length > 0) { const text = pending.toString('utf8'); for (const message of sse.push(`${text}\n\n`)) { @@ -624,7 +744,7 @@ async function streamSurface(input: StreamContext): Promise { } finally { clearIdle(); guard.signal.removeEventListener('abort', onClientAbort); - if (aborted) { + if (aborted || frameTooLarge) { try { await reader.cancel(); } catch { @@ -639,6 +759,12 @@ async function streamSurface(input: StreamContext): Promise { disposeUpstream(upstream); } + if (frameTooLarge) { + ok = false; + errorCode = 'upstream_frame_too_large'; + errorMessage = `Upstream SSE frame exceeded ${SSE_MAX_FRAME_BYTES} bytes without a frame delimiter.`; + } + if (aborted) { ok = false; errorCode = 'client_aborted'; @@ -646,7 +772,7 @@ async function streamSurface(input: StreamContext): Promise { } return { - status: aborted ? 499 : timedOut ? 504 : upstream.status, + status: aborted ? 499 : timedOut ? 504 : frameTooLarge ? 502 : upstream.status, ok, aborted, timedOut, @@ -682,7 +808,7 @@ async function jsonSurface( // an error response; a timeout must not surface as the upstream's 2xx status. const timedOut = isTimeoutReason(upstream.abortReason); return { - status: timedOut ? 504 : upstream.status, + status: bodyReadFailureStatus(upstream.status, timedOut), ok: false, aborted: false, timedOut, @@ -695,11 +821,13 @@ async function jsonSurface( disposeUpstream(upstream); } const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); - const headers: Record = { + // 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), ...routerHeaders(provider, requestId, attempts), - }; + }); try { reply.hijack(); reply.raw.writeHead(upstream.status, headers); @@ -789,7 +917,7 @@ async function handleProxyRequest( { code: 'no_provider_configured', status: 503 }, ); } - if (ctx.repo.enabledModelIds().length === 0 && !allowUnknown) { + if (!ctx.repo.hasEnabledModel() && !allowUnknown) { throw new ApiError( 'api_error', 'No models are enabled. Sync or enable models in the dashboard (Models tab).', @@ -815,6 +943,12 @@ async function handleProxyRequest( const cooldownMs = Math.max(0, ctx.repo.getInt('provider_cooldown_ms', 60_000)); const maxRetries = Math.max(1, ctx.repo.getInt('max_retries', 3)); const timeoutMs = Math.max(1_000, ctx.repo.getInt('request_timeout_ms', 600_000)); + // GW-05: the stream idle gap is its own setting (min 1s); `timeoutMs` stays the + // total deadline enforced by upstreamFetch. + const streamIdleMs = Math.max( + MIN_STREAM_IDLE_MS, + ctx.repo.getInt('stream_idle_timeout_ms', DEFAULT_STREAM_IDLE_MS), + ); const upstreamUserAgent = ctx.repo.getSetting('upstream_user_agent') ?? 'opencode-router/1.0'; const strategy = parseRotationStrategy(ctx.repo.getSetting('rotation_strategy')); const requestHeaders = forwardHeaders(request.headers, { acceptJson: !stream || route.countTokens === true }); @@ -825,6 +959,7 @@ async function handleProxyRequest( let lastStatus: number | null = null; let lastError: ApiError | null = null; let fatalError: ApiError | null = null; + let lastAttemptProvider: ProviderRow | null = null; let everyFailureRateLimited = true; let everyFailureTimeout = true; let attemptNo = 0; @@ -846,6 +981,7 @@ async function handleProxyRequest( attempts += 1; attemptNo += 1; + lastAttemptProvider = fresh; const attempt = await runAttempt(ctx, fresh, route, { requestId, attempt: attemptNo, @@ -861,8 +997,13 @@ async function handleProxyRequest( if (attempt.kind === 'abort') { if (attempt.timedOut) { - // A timeout before any headers reached the client becomes a 504. - throw attempt.error ?? new ApiError('timeout_error', 'Upstream provider timed out.', { code: 'upstream_timeout' }); + // GW-01: a timed-out attempt is already logged and cooled down by + // `runAttempt`; fail over to the next candidate and answer the aggregated + // 504 only after every candidate is exhausted. + lastStatus = null; + lastError = attempt.error; + everyFailureRateLimited = false; + continue; } aborted = true; break; @@ -879,7 +1020,7 @@ async function handleProxyRequest( attempts, requestStartedAt: startedAt, guard, - idleMs: timeoutMs, + idleMs: streamIdleMs, }) : await jsonSurface(reply, surface, requestId, fresh, attempt.response, attempts, attempt.latencyMs); usage = outcome.usage; @@ -926,13 +1067,20 @@ async function handleProxyRequest( // Client error: surface the upstream error untouched, no failover. throw fatalError; } else if (attempts > 0 && everyFailureRateLimited && lastStatus === 429) { + // FEAT-06: hand SDK clients a concrete backoff instead of a hot retry loop. + const cooldownUntil = smallestCooldownUntil(ctx.repo.listProviders()); + const retryAfter = retryAfterSeconds(cooldownUntil); + reply.header('retry-after', String(retryAfter)); + reply.header('x-opencode-router-cooldown-until', String(cooldownUntil ?? Date.now() + retryAfter * 1000)); throw new ApiError('rate_limit_error', 'All providers are rate limited (HTTP 429). Try again shortly.', { code: 'all_providers_rate_limited', status: 429, }); } else if (attempts > 0 && everyFailureTimeout) { // Every provider failed on a network/timeout path: the deadline, not the - // provider, is what the client hit (FIX-04). + // provider, is what the client hit (FIX-04). GW-02: attribute the log row to + // the provider that actually timed out. + provider = lastAttemptProvider; throw new ApiError('timeout_error', lastError?.message ?? 'Every provider timed out.', { status: 504, code: 'upstream_timeout', diff --git a/src/util/upstream.ts b/src/util/upstream.ts index 8832dda..1c3e785 100644 --- a/src/util/upstream.ts +++ b/src/util/upstream.ts @@ -15,16 +15,38 @@ export interface UpstreamRequest { /** Structured body: serialized with JSON.stringify unless `rawBody` is set. */ body?: unknown; /** Client body kept byte-for-byte; takes precedence over `body`. */ - rawBody?: string; + rawBody?: Buffer; /** Extra request headers (client beta/trace headers); router auth headers win. */ headers?: Record; timeoutMs?: number; signal?: AbortSignal | null; userAgent?: string; + /** True for a streaming request: `accept` defaults to `text/event-stream`. */ + stream?: boolean; + /** True for the Anthropic Messages surface: `anthropic-version` gets a default. */ + anthropic?: boolean; /** `manual` (default) refuses to follow redirects so credentials never leave the origin. */ redirect?: 'manual' | 'follow'; } +/** + * Removes userinfo and query from a URL before it is embedded in an error message + * that reaches `request_logs.error_message`, `providers.last_error` or the client + * (GW-12: `https://user:pass@host/v1` must never leak the credentials). + */ +export function redactUrl(raw: string): string { + try { + const url = new URL(raw); + url.username = ''; + url.password = ''; + url.search = ''; + url.hash = ''; + return url.toString(); + } catch { + return raw; + } +} + export interface UpstreamResponse { status: number; ok: boolean; @@ -42,6 +64,21 @@ export interface UpstreamResponse { readonly abortReason: string | null; } +/** + * Scrubs credentials a runtime error may quote verbatim. `fetch` itself rejects a + * credentialed URL with the full URL in its message, so redacting only the URL the + * gateway composes is not enough (GW-12). + */ +export function redactMessage(message: string, url: string): string { + let out = message.split(url).join(redactUrl(url)); + out = out.replace(/(\/\/)[^/@\s]+@/g, '$1'); + out = out.replace( + /([?&](?:api[_-]?key|key|token|access[_-]?token|password)=)[^&\s]*/gi, + '$1REDACTED', + ); + return out; +} + /** * Performs a request against an OpenAI/Anthropic compatible provider endpoint. * Network level failures are converted into ApiError instances. @@ -73,11 +110,15 @@ export async function upstreamFetch(req: UpstreamRequest): Promise = { 'content-type': 'application/json', - accept: 'application/json', + // GW-06: a streaming client that sent no `Accept` must still advertise SSE, + // otherwise providers that branch on the header answer with a JSON body. + accept: req.stream === true ? 'text/event-stream' : 'application/json', authorization: `Bearer ${req.apiKey}`, 'x-api-key': req.apiKey, - 'anthropic-version': '2023-06-01', 'user-agent': req.userAgent ?? 'opencode-router/1.0', + // GW-07: the Anthropic API version is only a default for the Messages surface; + // a client-supplied value (forwarded via `headers`) wins over it. + ...(req.anthropic === true ? { 'anthropic-version': '2023-06-01' } : {}), ...(req.headers ?? {}), }; // Router-supplied credentials always win over caller-supplied header echoes. @@ -108,16 +149,20 @@ export async function upstreamFetch(req: UpstreamRequest): Promise { + it('accepts Bearer tokens', () => { + expect(extractApiKey({ authorization: 'Bearer okr-abc' })).toBe('okr-abc'); + expect(extractApiKey({ authorization: 'bearer okr-abc ' })).toBe('okr-abc'); + expect(extractApiKey({ authorization: 'BEARER okr-abc' })).toBe('okr-abc'); + }); + + it('rejects every non-Bearer Authorization scheme', () => { + expect(extractApiKey({ authorization: 'Basic b2tyLWF respons' })).toBeNull(); + expect(extractApiKey({ authorization: 'Digest username="x"' })).toBeNull(); + expect(extractApiKey({ authorization: 'okr-abc' })).toBeNull(); + expect(extractApiKey({ authorization: 'Bearer' })).toBeNull(); + expect(extractApiKey({ authorization: 'Bearer ' })).toBeNull(); + }); + + it('still falls back to x-api-key', () => { + expect(extractApiKey({ 'x-api-key': ' okr-xyz ' })).toBe('okr-xyz'); + expect(extractApiKey({ 'x-api-key': ['okr-first', 'okr-second'] })).toBe('okr-first'); + // A non-Bearer Authorization must not hide a valid x-api-key. + expect(extractApiKey({ authorization: 'Basic b2ty', 'x-api-key': 'okr-xyz' })).toBe('okr-xyz'); + }); + + it('returns null when nothing is present', () => { + expect(extractApiKey({})).toBeNull(); + expect(extractApiKey({ authorization: ' ', 'x-api-key': '' })).toBeNull(); + }); +}); + +describe('forwardHeaders (GW-07)', () => { + it('forwards the Anthropic version and browser-access opt-in', () => { + const out = forwardHeaders({ + 'anthropic-version': '2025-01-01', + 'anthropic-dangerous-direct-browser-access': 'true', + 'anthropic-beta': 'prompt-caching-2024-07-31', + }); + expect(out['anthropic-version']).toBe('2025-01-01'); + expect(out['anthropic-dangerous-direct-browser-access']).toBe('true'); + expect(out['anthropic-beta']).toBe('prompt-caching-2024-07-31'); + }); + + it('never forwards credentials or hop-by-hop headers', () => { + const out = forwardHeaders({ + authorization: 'Bearer okr-secret', + 'x-api-key': 'okr-secret', + cookie: 'session=abc', + host: 'router.example', + 'content-length': '12', + connection: 'keep-alive', + accept: 'text/event-stream', + 'x-stainless-lang': 'js', + }); + expect(out.authorization).toBeUndefined(); + expect(out['x-api-key']).toBeUndefined(); + expect(out.cookie).toBeUndefined(); + expect(out.host).toBeUndefined(); + expect(out['content-length']).toBeUndefined(); + expect(out.connection).toBeUndefined(); + expect(out.accept).toBe('text/event-stream'); + expect(out['x-stainless-lang']).toBe('js'); + }); + + it('only defaults accept for non-streaming calls', () => { + expect(forwardHeaders({}, { acceptJson: true }).accept).toBe('application/json'); + // Streaming leaves `accept` to `upstreamFetch` (GW-06) so the SSE default applies. + expect(forwardHeaders({}, { acceptJson: false }).accept).toBeUndefined(); + expect(forwardHeaders({ accept: 'application/x-custom' }, { acceptJson: true }).accept).toBe( + 'application/x-custom', + ); + }); + + it('does not let a bare wildcard accept shadow the surface default (GW-06)', () => { + expect(forwardHeaders({ accept: '*/*' }, { acceptJson: false }).accept).toBeUndefined(); + expect(forwardHeaders({ accept: '*/*' }, { acceptJson: true }).accept).toBe('application/json'); + expect(forwardHeaders({ accept: 'text/event-stream' }, { acceptJson: true }).accept).toBe( + 'text/event-stream', + ); + }); +}); diff --git a/tests/gateway-normalize.test.ts b/tests/gateway-normalize.test.ts index 862e844..860e29a 100644 --- a/tests/gateway-normalize.test.ts +++ b/tests/gateway-normalize.test.ts @@ -147,3 +147,26 @@ describe('normalizeBody', () => { expect('stream_options' in body).toBe(false); }); }); + +describe('model id normalization (GW-11)', () => { + it('forwards the trimmed model id', () => { + const out = normalizeBody('chat', { model: ' opencode/flint ' }, null); + expect(out.body.model).toBe('opencode/flint'); + }); + + it('leaves an already trimmed id untouched', () => { + const body: Json = { model: 'opencode/flint', stream: false }; + const out = normalizeBody('chat', body, null); + expect(out.body.model).toBe('opencode/flint'); + expect(out.body).not.toBe(body); + }); + + it('does not mutate the caller body and keeps a non-string model alone', () => { + const body: Json = { model: ' x ' }; + normalizeBody('chat', body, null); + expect(body.model).toBe(' x '); + + const numeric: Json = { model: 7 }; + expect(normalizeBody('chat', numeric, null).body.model).toBe(7); + }); +}); diff --git a/tests/gateway-proxy-helpers.test.ts b/tests/gateway-proxy-helpers.test.ts index 7cd4a8e..73394f0 100644 --- a/tests/gateway-proxy-helpers.test.ts +++ b/tests/gateway-proxy-helpers.test.ts @@ -1,5 +1,16 @@ import { describe, expect, it } from 'vitest'; -import { retryAfterMs, rewriteSseFrame, stripTopLevelXOpencode, stripXOpencode } from '../src/gateway/proxy.js'; +import { + bodyReadFailureStatus, + forwardedResponseHeaders, + retryAfterMs, + retryAfterSeconds, + rewriteSseFrame, + sanitizeHeaderValue, + smallestCooldownUntil, + stripTopLevelXOpencode, + stripXOpencode, +} from '../src/gateway/proxy.js'; +import { provider } from './helpers.js'; describe('stripXOpencode', () => { it('removes a top-level x_opencode key into a new object', () => { @@ -97,3 +108,92 @@ describe('retryAfterMs', () => { expect(retryAfterMs('soon')).toBeNull(); }); }); + +describe('bodyReadFailureStatus (GW-03)', () => { + it('maps a failed body read on a 2xx upstream answer to 502', () => { + expect(bodyReadFailureStatus(200, false)).toBe(502); + expect(bodyReadFailureStatus(204, false)).toBe(502); + expect(bodyReadFailureStatus(301, false)).toBe(502); + }); + + it('keeps an upstream error status', () => { + expect(bodyReadFailureStatus(400, false)).toBe(400); + expect(bodyReadFailureStatus(502, false)).toBe(502); + }); + + it('keeps 504 for a timeout', () => { + expect(bodyReadFailureStatus(200, true)).toBe(504); + expect(bodyReadFailureStatus(500, true)).toBe(504); + }); +}); + +describe('sanitizeHeaderValue (GW-10)', () => { + it('strips control characters and CRLF injection', () => { + expect(sanitizeHeaderValue('provider\r\nx-injected: 1')).toBe('providerx-injected: 1'); + expect(sanitizeHeaderValue('a\u0000b\u0007c')).toBe('abc'); + expect(sanitizeHeaderValue('plain name-1')).toBe('plain name-1'); + }); + + it('drops characters Node rejects outside Latin-1', () => { + expect(sanitizeHeaderValue('日本語 provider')).toBe(' provider'); + }); +}); + +describe('forwardedResponseHeaders (GW-09)', () => { + it('forwards backoff / rate-limit / request-id headers', () => { + const upstream = new Headers({ + 'retry-after': '2', + 'x-ratelimit-remaining': '0', + 'anthropic-ratelimit-tokens-remaining': '7', + 'x-request-id': 'req_1', + 'openai-processing-ms': '12', + 'content-type': 'application/json', + 'content-encoding': 'gzip', + 'set-cookie': 'a=b', + }); + const out = forwardedResponseHeaders(upstream, { 'content-type': 'application/json' }); + expect(out['retry-after']).toBe('2'); + expect(out['x-ratelimit-remaining']).toBe('0'); + expect(out['anthropic-ratelimit-tokens-remaining']).toBe('7'); + expect(out['x-request-id']).toBe('req_1'); + expect(out['openai-processing-ms']).toBe('12'); + expect(out['content-encoding']).toBeUndefined(); + expect(out['set-cookie']).toBeUndefined(); + }); + + it('lets router overrides win', () => { + const upstream = new Headers({ 'x-request-id': 'upstream', 'content-type': 'text/plain' }); + const out = forwardedResponseHeaders(upstream, { + 'x-request-id': 'router', + 'content-type': 'application/json', + 'content-length': '5', + }); + expect(out['x-request-id']).toBe('router'); + expect(out['content-type']).toBe('application/json'); + expect(out['content-length']).toBe('5'); + }); +}); + +describe('FEAT-06 cooldown helpers', () => { + it('finds the smallest active cooldown among enabled providers', () => { + const now = 1_000_000; + const providers = [ + provider('a', { cooldownUntil: now + 5_000 }), + provider('b', { cooldownUntil: now + 2_000 }), + provider('c', { cooldownUntil: now - 1_000 }), + provider('d', { cooldownUntil: null }), + provider('e', { cooldownUntil: now + 1_000, enabled: false }), + ]; + expect(smallestCooldownUntil(providers, now)).toBe(now + 2_000); + expect(smallestCooldownUntil(providers.slice(2), now)).toBeNull(); + expect(smallestCooldownUntil([], now)).toBeNull(); + }); + + it('converts a cooldown deadline to whole Retry-After seconds', () => { + const now = 1_000_000; + expect(retryAfterSeconds(now + 2_400, now)).toBe(3); + expect(retryAfterSeconds(now + 1, now)).toBe(1); + expect(retryAfterSeconds(now - 500, now)).toBe(1); + expect(retryAfterSeconds(null, now)).toBe(1); + }); +}); diff --git a/tests/gateway-stream.test.ts b/tests/gateway-stream.test.ts new file mode 100644 index 0000000..45e85cd --- /dev/null +++ b/tests/gateway-stream.test.ts @@ -0,0 +1,476 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import Fastify, { type FastifyInstance } from 'fastify'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { AppContext } from '../src/core/context.js'; +import { EventBus } from '../src/core/events.js'; +import { registerGatewayRoutes } from '../src/gateway/index.js'; +import { SSE_MAX_FRAME_BYTES } from '../src/gateway/proxy.js'; +import type { AppConfig } from '../src/config.js'; +import { createTestDb, testConfig, type TestDb } from './helpers.js'; + +interface MockRequest { + url: string; + headers: IncomingMessage['headers']; + body: Buffer; +} + +interface MockUpstream { + baseUrl: string; + requests: MockRequest[]; + close(): Promise; +} + +const upstreams: MockUpstream[] = []; + +type MockHandler = (req: IncomingMessage, res: ServerResponse, body: Buffer) => void; + +/** 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 }); + 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`, + requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; + upstreams.push(upstream); + return upstream; +} + +export 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)); + } +} + +function logsFor(db: TestDb, requestId: string) { + return db.repo.listLogs({ limit: 50 }).rows.filter((row) => row.id === requestId); +} + +let db: TestDb; +let app: FastifyInstance; +let ctx: AppContext; +let origin: string; +let apiKey: string; + +function config(): AppConfig { + return testConfig(db.dataDir); +} + +async function buildApp(events = new EventBus()): Promise { + app = Fastify({ logger: false }); + ctx = { + config: config(), + db: db.handle, + repo: db.repo, + events, + logger: app.log, + startedAt: Date.now(), + }; + await registerGatewayRoutes(app, ctx); + await app.listen({ port: 0, host: '127.0.0.1' }); + const { port } = app.server.address() as AddressInfo; + origin = `http://127.0.0.1:${port}`; +} + +function addProvider(id: string, baseUrl: string, priority: number): void { + db.repo.createProvider({ id, name: id, baseUrl, apiKey: 'sk-provider', 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 = (model = 'test/model'): string => + JSON.stringify({ model, messages: [{ role: 'user', content: 'ping' }] }); + +const CHAT = '/v1/chat/completions'; + +beforeEach(async () => { + db = createTestDb('okr-gateway-'); + db.repo.upsertModel({ id: 'test/model', name: 'Test Model' }); + apiKey = db.repo.createApiKey('tests').plaintext; + db.repo.setSetting('rotation_strategy', 'priority'); + await buildApp(); +}); + +afterEach(async () => { + await app.close(); + db.cleanup(); + for (const upstream of upstreams.splice(0)) await upstream.close(); +}); + +/* --------------------------------------------------------------- GW-04 auth */ + +describe('unknown /v1/* paths (GW-04)', () => { + it('requires a gateway API key and logs the rejection', async () => { + const response = await fetch(`${origin}/v1/nope`, { method: 'POST' }); + expect(response.status).toBe(401); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('missing_api_key'); + expect(db.repo.listLogs({}).total).toBe(1); + }); + + it('answers an authenticated unknown path with the surface-shaped 404 and exactly one row', async () => { + const response = await gatewayFetch('/v1/nope', { method: 'POST', body: chatBody() }); + expect(response.status).toBe(404); + expect(response.headers.get('x-opencode-router-request-id')).toBeTruthy(); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('unknown_endpoint'); + + const logs = db.repo.listLogs({}); + expect(logs.total).toBe(1); + expect(logs.rows[0]!.errorCode).toBe('unknown_endpoint'); + expect(logs.rows[0]!.status).toBe(404); + expect(logs.rows[0]!.keyId).not.toBeNull(); + }); + + it('shapes the anthropic 404 for unknown /v1/messages paths', async () => { + const response = await gatewayFetch('/v1/messages/nope', { method: 'POST', body: chatBody() }); + expect(response.status).toBe(404); + const body = (await response.json()) as { type?: string }; + expect(body.type).toBe('error'); + expect(db.repo.listLogs({}).total).toBe(1); + }); + + it('rejects a non-Bearer Authorization scheme (GW-13)', async () => { + const response = await fetch(`${origin}/v1/nope`, { + method: 'POST', + headers: { authorization: 'Basic b2tyLXNlY3JldA==' }, + }); + expect(response.status).toBe(401); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('missing_api_key'); + + // x-api-key keeps working. + const ok = await fetch(`${origin}/v1/nope`, { method: 'POST', headers: { 'x-api-key': apiKey } }); + expect(ok.status).toBe(404); + }); + + it('keeps the real routes ahead of the catch-all', async () => { + const response = await gatewayFetch('/v1/models'); + expect(response.status).toBe(200); + const body = (await response.json()) as { object?: string; data?: unknown[] }; + expect(body.object).toBe('list'); + expect(Array.isArray(body.data)).toBe(true); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); + +/* ------------------------------------------------------- GW-01 / GW-02 failover */ + +describe('timeout failover (GW-01/GW-02)', () => { + it('fails over to a healthy provider, logs the attempt and cools the slow one down', async () => { + const slow = await startUpstream(() => { + /* never responds */ + }); + const fast = await startUpstream((_req, res) => jsonResponse(res, 200, { provider: 'fast' })); + addProvider('slow', slow.baseUrl, 1); + addProvider('fast', fast.baseUrl, 2); + db.repo.setSetting('request_timeout_ms', '1000'); + db.repo.setSetting('provider_cooldown_ms', '60000'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(response.headers.get('x-opencode-router-provider')).toBe('fast'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + expect(await response.json()).toEqual({ provider: 'fast' }); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + const attempts = db.repo.listAttempts(requestId); + expect(attempts).toHaveLength(2); + expect(attempts[0]).toMatchObject({ providerId: 'slow', ok: false, status: null, errorCode: 'upstream_timeout' }); + expect(attempts[1]).toMatchObject({ providerId: 'fast', ok: true, status: 200 }); + + const slowRow = db.repo.getProvider('slow')!; + expect(slowRow.cooldownUntil).not.toBeNull(); + expect(slowRow.cooldownUntil!).toBeGreaterThan(Date.now()); + expect(slowRow.failureCount).toBe(1); + + const logs = logsFor(db, requestId); + expect(logs).toHaveLength(1); + expect(logs[0]).toMatchObject({ providerId: 'fast', ok: true, status: 200, attempts: 2 }); + }); + + it('aggregates a 504 with provider attribution when every provider times out', async () => { + const slow = await startUpstream(() => { + /* never responds */ + }); + addProvider('slow', slow.baseUrl, 1); + db.repo.setSetting('request_timeout_ms', '1000'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(504); + expect(response.headers.get('x-opencode-router-provider')).toBe('slow'); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('upstream_timeout'); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + const logs = logsFor(db, requestId); + expect(logs).toHaveLength(1); + expect(logs[0]).toMatchObject({ providerId: 'slow', ok: false, status: 504, errorCode: 'upstream_timeout' }); + }); +}); + +/* ------------------------------------------------------------------- GW-03 */ + +describe('2xx body-read failure (GW-03)', () => { + it('answers 502 instead of echoing the upstream 200', async () => { + const broken = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'application/json', 'content-length': '200' }); + res.write('{"partial":'); + // Destroy only after the headers/partial body reached the gateway, so this + // exercises the body-read path and not a connection-level failure. + setTimeout(() => res.socket?.destroy(), 50); + }); + addProvider('broken', broken.baseUrl, 1); + + 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('upstream_body_failed'); + + const requestId = response.headers.get('x-opencode-router-request-id')!; + expect(logsFor(db, requestId)[0]).toMatchObject({ status: 502, errorCode: 'upstream_body_failed' }); + }); +}); + +/* ----------------------------------------------------------- GW-05 SSE limits */ + +describe('SSE frame cap and idle timeout (GW-05)', () => { + it('aborts and logs upstream_frame_too_large when a partial frame grows past the cap', async () => { + const noisy = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + res.write('x'.repeat(SSE_MAX_FRAME_BYTES + 4_096)); + // never terminates the frame + }); + addProvider('noisy', noisy.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'x' }] }), + }); + expect(response.status).toBe(200); + const requestId = response.headers.get('x-opencode-router-request-id')!; + await response.text(); + + const row = await waitFor(() => logsFor(db, requestId)[0], 'the frame-cap log row'); + expect(row.errorCode).toBe('upstream_frame_too_large'); + expect(row.ok).toBe(false); + expect(row.status).toBe(502); + }); + + it('honours stream_idle_timeout_ms instead of the total request deadline', async () => { + const stalled = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + // never sends anything else and never ends + }); + addProvider('stalled', stalled.baseUrl, 1); + db.repo.setSetting('stream_idle_timeout_ms', '1000'); + db.repo.setSetting('request_timeout_ms', '600000'); + + const started = Date.now(); + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'x' }] }), + }); + const requestId = response.headers.get('x-opencode-router-request-id')!; + await response.text(); + expect(Date.now() - started).toBeLessThan(5_000); + + const row = await waitFor(() => logsFor(db, requestId)[0], 'the idle-timeout log row'); + expect(row.errorCode).toBe('upstream_timeout'); + expect(row.status).toBe(504); + expect(row.ok).toBe(false); + }); +}); + +/* --------------------------------------- GW-06/07/09/11 headers and model id */ + +describe('headers, model id and response headers (GW-06/GW-07/GW-09/GW-11)', () => { + it('forwards accept, anthropic-version and the trimmed model, and relays upstream headers', async () => { + const upstream = await startUpstream((_req, res) => + jsonResponse(res, 200, { ok: true }, { 'x-ratelimit-remaining': '5', 'retry-after': '3' }), + ); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: ' test/model ', messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(response.status).toBe(200); + expect(response.headers.get('x-ratelimit-remaining')).toBe('5'); + expect(response.headers.get('retry-after')).toBe('3'); + expect(response.headers.get('x-opencode-router-provider')).toBe('up'); + + const sent = upstream.requests.at(-1)!; + expect(sent.headers.accept).toBe('application/json'); + expect(sent.headers['anthropic-version']).toBeUndefined(); + expect(JSON.parse(sent.body.toString('utf8'))).toEqual({ + model: 'test/model', + messages: [{ role: 'user', content: 'hi' }], + }); + }); + + it('defaults and forwards anthropic-version on the messages surface only', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + await gatewayFetch('/v1/messages', { + method: 'POST', + body: JSON.stringify({ model: 'test/model', max_tokens: 16, messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(upstream.requests.at(-1)!.headers['anthropic-version']).toBe('2023-06-01'); + + await gatewayFetch('/v1/messages', { + method: 'POST', + headers: { 'anthropic-version': '2025-01-01' }, + body: JSON.stringify({ model: 'test/model', max_tokens: 16, messages: [{ role: 'user', content: 'hi' }] }), + }); + expect(upstream.requests.at(-1)!.headers['anthropic-version']).toBe('2025-01-01'); + }); + + it('defaults accept to text/event-stream for a streaming call with no accept', async () => { + const upstream = await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"a":1}\n\n'); + res.end(); + }); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: JSON.stringify({ model: 'test/model', stream: true, messages: [{ role: 'user', content: 'hi' }] }), + }); + await response.text(); + expect(upstream.requests.at(-1)!.headers.accept).toBe('text/event-stream'); + }); +}); + +/* ------------------------------------------------------------------- GW-08 */ + +describe('byte-faithful request bodies (GW-08)', () => { + it('forwards the client bytes untouched, including invalid UTF-8', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + const raw = Buffer.concat([ + Buffer.from('{\n "model": "test/model", "big": 9007199254740993, "messages": [{"role":"user","content":"'), + Buffer.from([0xff, 0xfe]), + Buffer.from('"}]}'), + ]); + await gatewayFetch(CHAT, { method: 'POST', body: raw }); + + const sent = upstream.requests.at(-1)!; + expect(sent.body.equals(raw)).toBe(true); + }); +}); + +/* ------------------------------------------------------------------ FEAT-06 */ + +describe('client-facing backoff signal (FEAT-06)', () => { + it('adds Retry-After and the cooldown deadline header to all_providers_rate_limited', async () => { + const first = await startUpstream((_req, res) => + jsonResponse(res, 429, { error: { message: 'rate limited' } }, { 'retry-after': '2' }), + ); + const second = await startUpstream((_req, res) => jsonResponse(res, 429, { error: { message: 'rate limited' } })); + addProvider('first', first.baseUrl, 1); + addProvider('second', second.baseUrl, 2); + db.repo.setSetting('provider_cooldown_ms', '4000'); + + const before = Date.now(); + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('all_providers_rate_limited'); + + const retryAfter = Number(response.headers.get('retry-after')); + expect(Number.isInteger(retryAfter)).toBe(true); + expect(retryAfter).toBeGreaterThanOrEqual(1); + expect(retryAfter).toBeLessThanOrEqual(5); + + const until = Number(response.headers.get('x-opencode-router-cooldown-until')); + expect(Number.isFinite(until)).toBe(true); + expect(until).toBeGreaterThan(before); + expect(until).toBeLessThanOrEqual(Date.now() + 5_000); + }); +}); + +/* ------------------------------------------------------------------- GW-10 */ + +describe('router header sanitization (GW-10)', () => { + it('does not 500 when a provider name contains control characters', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + // Bypasses the admin validation on purpose: the proxy must defend itself too. + db.repo.createProvider({ + id: 'evil', + name: 'bad\r\nx-injected: 1', + baseUrl: upstream.baseUrl, + apiKey: 'sk-provider', + priority: 1, + }); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(response.headers.get('x-opencode-router-name')).toBe('badx-injected: 1'); + expect(response.headers.get('x-injected')).toBeNull(); + }); +}); + +/* ------------------------------------------------------------------- GW-14 */ + +describe('guarded event emission (GW-14)', () => { + it('keeps serving when dashboard listeners throw', async () => { + const events = new EventBus(); + events.on('request:start', () => { + throw new Error('start listener boom'); + }); + events.on('request:end', () => { + throw new Error('end listener boom'); + }); + events.on('provider:update', () => { + throw new Error('provider listener boom'); + }); + await app.close(); + await buildApp(events); + apiKey = db.repo.createApiKey('second').plaintext; + + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { ok: true })); + addProvider('up', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); diff --git a/tests/util-upstream.test.ts b/tests/util-upstream.test.ts index 552dc0a..ee18f41 100644 --- a/tests/util-upstream.test.ts +++ b/tests/util-upstream.test.ts @@ -1,7 +1,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; import { afterEach, describe, expect, it } from 'vitest'; import { ApiError } from '../src/util/errors.js'; -import { joinUrl, upstreamFetch } from '../src/util/upstream.js'; +import { joinUrl, redactUrl, upstreamFetch } from '../src/util/upstream.js'; interface TestServer { base: string; @@ -112,7 +112,7 @@ describe('upstreamFetch bodies', () => { res.writeHead(200, { 'content-type': 'application/json' }); res.end('{}'); }); - const raw = '{\n "model": "x", "big": 9007199254740993, "esc": "\\u00e9", "spaced" : [1, 2] }'; + const raw = Buffer.from('{\n "model": "x", "big": 9007199254740993, "esc": "\\u00e9", "spaced" : [1, 2] }'); const response = await upstreamFetch({ baseUrl: server.base, @@ -126,7 +126,35 @@ describe('upstreamFetch bodies', () => { response.dispose(); expect(received).toHaveLength(1); - expect(received[0]!.toString('utf8')).toBe(raw); + expect(received[0]!.equals(raw)).toBe(true); + }); + + it('keeps invalid UTF-8 bytes intact when forwarding a Buffer body (GW-08)', async () => { + const received: Buffer[] = []; + const server = await listen(async (req, res) => { + received.push(await bodyOf(req)); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + // `\xff` is not valid UTF-8: a string round-trip would turn it into U+FFFD. + const raw = Buffer.concat([ + Buffer.from('{"model":"m","messages":[{"role":"user","content":"'), + Buffer.from([0xff, 0xfe]), + Buffer.from('"}]}'), + ]); + + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-secret', + path: '/chat/completions', + rawBody: raw, + timeoutMs: 2_000, + }); + await response.response.text(); + response.dispose(); + + expect(received[0]!.equals(raw)).toBe(true); + expect(received[0]!.includes(0xef)).toBe(false); // no U+FFFD replacement bytes }); it('sends structured bodies as JSON', async () => { @@ -225,4 +253,128 @@ describe('upstreamFetch timeouts', () => { expect((error as ApiError).code).toBe('client_aborted'); expect((error as ApiError).status).toBe(502); }); -}); \ No newline at end of file +}); +describe('upstreamFetch request headers (GW-06/GW-07)', () => { + interface Captured { + base: string; + headers: () => IncomingMessage['headers'] | null; + } + + const headerServers: Array<{ close(): Promise }> = []; + afterEach(async () => { + for (const server of headerServers.splice(0)) await server.close(); + }); + + async function capture(): Promise { + let headers: IncomingMessage['headers'] | null = null; + const server = await listen((req, res) => { + headers = req.headers; + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + headerServers.push(server); + return { base: server.base, headers: () => headers }; + } + + it('defaults accept to application/json for a non-streaming call', async () => { + const server = await capture(); + const response = await upstreamFetch({ baseUrl: server.base, apiKey: 'k', path: '/chat/completions', body: {} }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('application/json'); + }); + + it('defaults accept to text/event-stream for a streaming call', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: { stream: true }, + stream: true, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('text/event-stream'); + }); + + it('keeps a client-supplied accept header', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/chat/completions', + body: {}, + stream: true, + headers: { accept: 'application/x-custom' }, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.accept).toBe('application/x-custom'); + }); + + it('only defaults anthropic-version on the Anthropic surface', async () => { + const openai = await capture(); + const first = await upstreamFetch({ baseUrl: openai.base, apiKey: 'k', path: '/chat/completions', body: {} }); + await first.response.text(); + first.dispose(); + expect(openai.headers()?.['anthropic-version']).toBeUndefined(); + + const anthropic = await capture(); + const second = await upstreamFetch({ + baseUrl: anthropic.base, + apiKey: 'k', + path: '/messages', + body: {}, + anthropic: true, + }); + await second.response.text(); + second.dispose(); + expect(anthropic.headers()?.['anthropic-version']).toBe('2023-06-01'); + }); + + it('lets a client-supplied anthropic-version win over the default', async () => { + const server = await capture(); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'k', + path: '/messages', + body: {}, + anthropic: true, + headers: { 'anthropic-version': '2025-01-01' }, + }); + await response.response.text(); + response.dispose(); + expect(server.headers()?.['anthropic-version']).toBe('2025-01-01'); + }); +}); + +describe('redactUrl (GW-12)', () => { + it('drops userinfo and query string', () => { + expect(redactUrl('https://user:pass@host.example/v1/chat/completions?key=secret')).toBe( + 'https://host.example/v1/chat/completions', + ); + expect(redactUrl('https://user@host.example/v1')).toBe('https://host.example/v1'); + expect(redactUrl('https://host.example/v1?api_key=abc')).toBe('https://host.example/v1'); + }); + + it('returns unparsable input unchanged', () => { + expect(redactUrl('not a url')).toBe('not a url'); + }); + + it('never exposes credentials in the unreachable-provider error message', async () => { + // Port 1 on loopback is refused immediately, so the error composes promptly. + const error = await upstreamFetch({ + baseUrl: 'http://user:pass@127.0.0.1:1/v1?token=secret', + apiKey: 'k', + path: '/chat/completions', + body: {}, + timeoutMs: 1_000, + }).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(ApiError); + const message = (error as ApiError).message; + expect(message).not.toContain('user:pass'); + expect(message).not.toContain('secret'); + expect(message).toContain('127.0.0.1:1'); + }); +}); From dd965aee49a86330dd5da2481d6a1a5a0cb2c844 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 20:19:16 +0700 Subject: [PATCH 2/5] fix(admin): harden ssrf guard, provider lifecycle and sessions --- src/admin/auth.ts | 68 +++- src/admin/index.ts | 39 ++- src/admin/keys.ts | 10 +- src/admin/logs.ts | 8 +- src/admin/models.ts | 41 ++- src/admin/providers.ts | 50 ++- src/admin/session.ts | 21 +- src/admin/settings.ts | 42 ++- src/admin/stats.ts | 60 +++- src/admin/sync.ts | 86 +++-- src/admin/util.ts | 56 ++- src/core/seed.ts | 23 +- src/core/shutdown.ts | 86 +++++ src/db/repos.ts | 440 +++++++++++++++--------- src/db/schema.ts | 11 + src/index.ts | 17 +- src/server.ts | 25 +- tests/admin-auth.test.ts | 656 ++++++++++++++++++++++++++++++++++++ tests/admin-session.test.ts | 52 +++ tests/admin-util.test.ts | 50 ++- tests/db-repos.test.ts | 221 ++++++++++++ tests/unit.test.ts | 146 +++++++- 22 files changed, 1909 insertions(+), 299 deletions(-) create mode 100644 src/core/shutdown.ts create mode 100644 tests/admin-auth.test.ts diff --git a/src/admin/auth.ts b/src/admin/auth.ts index 45a140e..e66491f 100644 --- a/src/admin/auth.ts +++ b/src/admin/auth.ts @@ -8,8 +8,10 @@ import { verifyDashboardPassword } from '../core/seed.js'; import { ADMIN_CREDENTIAL_BODY_LIMIT, ADMIN_VERSION, HttpError, asString, assertPasswordLength, audit, clientIp, jsonBody, userAgent } from './util.js'; import { clearSessionCookie, createSession, resolveSession, setSessionCookie } from './session.js'; -const LOGIN_WINDOW_MS = 5 * 60 * 1000; -const LOGIN_MAX_ATTEMPTS = 10; +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; interface AttemptRecord { count: number; @@ -17,6 +19,7 @@ interface AttemptRecord { } const attempts = new Map(); +let globalAttempts: AttemptRecord = { count: 0, firstAt: 0 }; export const PUBLIC_ADMIN_ROUTES = new Set([ 'POST /admin/api/login', @@ -27,6 +30,7 @@ export const PUBLIC_ADMIN_ROUTES = new Set([ /** Test/ops helper: forget every recorded failed login. */ export function resetLoginAttempts(): void { attempts.clear(); + globalAttempts = { count: 0, firstAt: 0 }; } export function normalizeAdminPath(url: string): string { @@ -40,30 +44,47 @@ export function isPublicAdminRoute(method: string, url: string): boolean { return PUBLIC_ADMIN_ROUTES.has(`${method.toUpperCase()} ${normalizeAdminPath(url)}`); } -interface RateLimitHit { +export interface RateLimitHit { retryAfterMs: number; + /** Which bucket tripped: the caller's IP or the process-wide failure cap. */ + scope: 'ip' | 'global'; } -function checkLoginRateLimit(ip: string): RateLimitHit | null { - const record = attempts.get(ip); - if (!record) return null; +function windowHit(record: AttemptRecord | undefined, now: number, max: number): number | null { + if (!record || record.count < max) return null; + const elapsed = now - record.firstAt; + if (elapsed > LOGIN_WINDOW_MS) return null; + return LOGIN_WINDOW_MS - elapsed; +} + +/** Per-IP guard first (dashboards), then the FEAT-08 global cap (distributed bots). */ +export function checkLoginRateLimit(ip: string): RateLimitHit | null { const now = Date.now(); - if (now - record.firstAt > LOGIN_WINDOW_MS) { + const record = attempts.get(ip); + if (record && now - record.firstAt > LOGIN_WINDOW_MS) { attempts.delete(ip); - return null; + } else { + const retryAfterMs = windowHit(record, now, LOGIN_MAX_ATTEMPTS); + if (retryAfterMs !== null) return { retryAfterMs, scope: 'ip' }; } - if (record.count < LOGIN_MAX_ATTEMPTS) return null; - return { retryAfterMs: LOGIN_WINDOW_MS - (now - record.firstAt) }; + const globalRetry = windowHit(globalAttempts, now, LOGIN_GLOBAL_MAX_ATTEMPTS); + if (globalRetry !== null) return { retryAfterMs: globalRetry, scope: 'global' }; + return null; } -function recordLoginFailure(ip: string): void { +export function recordLoginFailure(ip: string): void { const now = Date.now(); const record = attempts.get(ip); if (!record || now - record.firstAt > LOGIN_WINDOW_MS) { attempts.set(ip, { count: 1, firstAt: now }); - return; + } else { + record.count += 1; + } + if (now - globalAttempts.firstAt > LOGIN_WINDOW_MS) { + globalAttempts = { count: 1, firstAt: now }; + } else { + globalAttempts.count += 1; } - record.count += 1; } function pruneAttempts(): void { @@ -71,6 +92,9 @@ function pruneAttempts(): void { for (const [ip, record] of attempts) { if (now - record.firstAt > LOGIN_WINDOW_MS) attempts.delete(ip); } + if (globalAttempts.count > 0 && now - globalAttempts.firstAt > LOGIN_WINDOW_MS) { + globalAttempts = { count: 0, firstAt: 0 }; + } } /** `onRequest` hook: rejects unauthenticated requests with `401 unauthorized`. */ @@ -98,7 +122,17 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi const limited = checkLoginRateLimit(ip); if (limited) { const seconds = Math.max(1, Math.ceil(limited.retryAfterMs / 1000)); - throw new HttpError(429, 'too_many_attempts', `Too many failed login attempts. Try again in ${seconds}s.`); + // FEAT-08: standard `Retry-After` plus the same value in the JSON envelope, so + // both HTTP clients and the dashboard can back off correctly. + reply.header('retry-after', String(seconds)); + await reply.status(429).send({ + error: { + message: `Too many failed login attempts. Try again in ${seconds}s.`, + code: 'too_many_attempts', + retryAfter: seconds, + }, + }); + return; } const body = jsonBody(request); @@ -108,14 +142,14 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi if (!verifyDashboardPassword(ctx, password)) { recordLoginFailure(ip); - audit(ctx, 'auth.login.failed', ip, `userAgent=${userAgent(request) ?? '-'}`); + audit(ctx, 'auth.login.failed', ip, `userAgent=${userAgent(request) ?? '-'}`, request); throw new HttpError(401, 'invalid_password', 'Invalid password'); } attempts.delete(ip); const session = createSession(ctx, request); setSessionCookie(ctx, request, reply, session.id, session.expiresAt); - audit(ctx, 'auth.login', session.id, `ip=${ip}`); + audit(ctx, 'auth.login', session.id, `ip=${ip}`, request); return { ok: true, expiresAt: session.expiresAt, sessionId: session.id }; }); @@ -123,7 +157,7 @@ export function registerAuthRoutes(scope: FastifyInstance, ctx: AppContext): voi const resolved = resolveSession(ctx, request); if (resolved) { ctx.repo.deleteSession(resolved.session.id); - audit(ctx, 'auth.logout', resolved.session.id, null); + audit(ctx, 'auth.logout', resolved.session.id, null, request); } clearSessionCookie(ctx, request, reply); return { ok: true }; diff --git a/src/admin/index.ts b/src/admin/index.ts index 3add8d4..582a3b0 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -3,7 +3,7 @@ * encapsulated Fastify scope so the session guard applies to every route in * this module except the explicit public allowlist (login/logout/session). */ -import type { FastifyInstance } from 'fastify'; +import type { FastifyInstance, FastifyReply } from 'fastify'; import type { AppContext } from '../core/context.js'; import { createAuthGuard, registerAuthRoutes } from './auth.js'; import { registerProviderRoutes } from './providers.js'; @@ -14,28 +14,37 @@ import { registerSettingsRoutes } from './settings.js'; import { registerStatsRoutes } from './stats.js'; import { HttpError } from './util.js'; +/** + * AD-11: `reply.send()` is thenable and rejects when the socket is already gone; + * an unhandled rejection from an error handler can take the process down. + */ +function sendQuietly(reply: FastifyReply, status: number, payload: unknown): void { + void Promise.resolve(reply.status(status).send(payload)).catch(() => {}); +} + export async function registerAdminRoutes(app: FastifyInstance, ctx: AppContext): Promise { await app.register( async (scope: FastifyInstance): Promise => { scope.setErrorHandler((error, request, reply) => { - const status = - error instanceof HttpError - ? error.statusCode - : typeof (error as { statusCode?: number }).statusCode === 'number' - ? (error as { statusCode: number }).statusCode - : 500; - const code = - error instanceof HttpError - ? error.code - : ((error as { code?: string }).code ?? (status >= 500 ? 'internal_error' : 'invalid_request')); - if (status >= 500) { + const isHttpError = error instanceof HttpError; + const status = isHttpError + ? error.statusCode + : typeof (error as { statusCode?: number }).statusCode === 'number' + ? (error as { statusCode: number }).statusCode + : 500; + if (status >= 500) ctx.logger?.error?.({ err: error, url: request.url }, 'admin request failed'); + if (!isHttpError && status >= 500) { // Driver/stack detail stays server-side; clients get a generic message. - ctx.logger?.error?.({ err: error, url: request.url }, 'admin request failed'); - void reply.status(status).send({ error: { message: 'Internal server error', code: 'internal_error' } }); + sendQuietly(reply, status, { error: { message: 'Internal server error', code: 'internal_error' } }); return; } + // HttpError messages are authored for clients (surface-shaped, FEAT-09), so + // they are returned even for 5xx; only unexpected errors are masked above. + const code = isHttpError + ? error.code + : ((error as { code?: string }).code ?? (status >= 500 ? 'internal_error' : 'invalid_request')); const message = error instanceof Error ? error.message : String(error); - void reply.status(status).send({ error: { message, code } }); + sendQuietly(reply, status, { error: { message, code } }); }); // Empty JSON bodies are legitimate for action routes (test, sync, revoke, diff --git a/src/admin/keys.ts b/src/admin/keys.ts index 2e089b3..c8019a6 100644 --- a/src/admin/keys.ts +++ b/src/admin/keys.ts @@ -47,7 +47,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const body = jsonBody(request); const name = requireString(body.name, 'name'); const { row, plaintext } = ctx.repo.createApiKey(name); - audit(ctx, 'key.create', row.id, `name=${name} prefix=${row.keyPrefix}`); + audit(ctx, 'key.create', row.id, `name=${name} prefix=${row.keyPrefix}`, request); return { key: apiKeyView(row), plaintext }; }); @@ -65,7 +65,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void if (Object.keys(patch).length === 0) fail(400, 'invalid_request', 'No supported fields to update'); const updated = ctx.repo.updateApiKey(id, patch); if (!updated) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.update', id, `fields=${Object.keys(patch).join(',')}`); + audit(ctx, 'key.update', id, `fields=${Object.keys(patch).join(',')}`, request); return { key: apiKeyView(updated) }; }); @@ -74,7 +74,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void loadKey(ctx, id); const revoked = ctx.repo.updateApiKey(id, { revoked: true, enabled: false }); if (!revoked) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.revoke', id, `name=${revoked.name}`); + audit(ctx, 'key.revoke', id, `name=${revoked.name}`, request); return { key: apiKeyView(revoked) }; }); @@ -87,7 +87,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const plaintext = generateApiKey(); const rotated = ctx.repo.rotateApiKey(id, plaintext); if (!rotated) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.rotate', id, `name=${existing.name} prefix=${rotated.keyPrefix}`); + audit(ctx, 'key.rotate', id, `name=${existing.name} prefix=${rotated.keyPrefix}`, request); return { key: apiKeyView(rotated), plaintext }; }); @@ -95,7 +95,7 @@ export function registerKeyRoutes(scope: FastifyInstance, ctx: AppContext): void const id = (request.params as { id: string }).id; const removed = ctx.repo.deleteApiKey(id); if (!removed) throw new HttpError(404, 'key_not_found', `API key "${id}" not found`); - audit(ctx, 'key.delete', id, `removed=${removed}`); + audit(ctx, 'key.delete', id, `removed=${removed}`, request); return { ok: true }; }); } diff --git a/src/admin/logs.ts b/src/admin/logs.ts index 7bf5c05..ccb71ee 100644 --- a/src/admin/logs.ts +++ b/src/admin/logs.ts @@ -71,7 +71,7 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void const { rows, total } = ctx.repo.listLogs(query); const truncated = total > rows.length; const stamp = new Date().toISOString().replace(/[:.]/g, '-'); - audit(ctx, 'log.export', null, `format=${format} rows=${rows.length} total=${total}`); + audit(ctx, 'log.export', null, `format=${format} rows=${rows.length} total=${total}`, request); if (truncated) reply.header('x-export-truncated', 'true'); if (format === 'csv') { reply @@ -94,9 +94,9 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void return { log: row, attempts: ctx.repo.listAttempts(id) }; }); - scope.delete('/logs', async () => { + scope.delete('/logs', async (request) => { const removed = ctx.repo.clearLogs(); - audit(ctx, 'log.clear', null, `removed=${removed}`); + audit(ctx, 'log.clear', null, `removed=${removed}`, request); return { ok: true, removed }; }); @@ -108,7 +108,7 @@ export function registerLogRoutes(scope: FastifyInstance, ctx: AppContext): void } const cutoff = Date.now() - parsed * 24 * 60 * 60 * 1000; const removed = ctx.repo.deleteLogsBefore(cutoff); - audit(ctx, 'log.prune', null, `days=${parsed} removed=${removed}`); + audit(ctx, 'log.prune', null, `days=${parsed} removed=${removed}`, request); return { removed }; }); } diff --git a/src/admin/models.ts b/src/admin/models.ts index 2a89f83..e066fef 100644 --- a/src/admin/models.ts +++ b/src/admin/models.ts @@ -18,7 +18,15 @@ import { stringList, requireString, } from './util.js'; -import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT, syncProviderModels } from './sync.js'; +import { + SETTING_MODELS_SYNC_PROVIDER_ID, + SETTING_MODELS_SYNCED_AT, + syncFailureMessage, + syncProviderModels, +} from './sync.js'; + +/** AD-05: the global body limit is 128 MB, so the id list needs its own cap. */ +export const MAX_BULK_MODEL_IDS = 1_000; function loadModel(ctx: AppContext, id: string): ModelRow { const model = ctx.repo.getModel(id); @@ -57,7 +65,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo enabled, source: 'manual', }); - audit(ctx, 'model.create', id, `source=manual name=${name}`); + audit(ctx, 'model.create', id, `source=manual name=${name}`, request); return { model: created.row }; }); @@ -98,7 +106,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo if (changed.length === 0) fail(400, 'invalid_request', 'No supported fields to update'); const updated = ctx.repo.updateModel(id, patch); if (!updated) throw new HttpError(404, 'model_not_found', `Model "${id}" not found`); - audit(ctx, 'model.update', id, `fields=${changed.join(',')}`); + audit(ctx, 'model.update', id, `fields=${changed.join(',')}`, request); return { model: updated }; }); @@ -106,7 +114,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo const id = (request.params as { '*': string })['*']; loadModel(ctx, id); ctx.repo.deleteModel(id); - audit(ctx, 'model.delete', id, null); + audit(ctx, 'model.delete', id, null, request); return { ok: true }; }); @@ -118,15 +126,14 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo } const ids = stringList(body.ids); if (!ids || ids.length === 0) fail(400, 'invalid_request', 'ids must be a non-empty array of model ids'); - let updated = 0; - for (const id of ids) { - if (action === 'delete') { - if (ctx.repo.deleteModel(id)) updated += 1; - } else if (ctx.repo.updateModel(id, { enabled: action === 'enable' })) { - updated += 1; - } + if (ids.length > MAX_BULK_MODEL_IDS) { + fail(400, 'invalid_request', `ids must contain at most ${MAX_BULK_MODEL_IDS} entries`); } - audit(ctx, `model.bulk.${action}`, null, `requested=${ids.length} updated=${updated}`); + // AD-05: one set-based statement in a transaction — no per-id event-loop work + // and no partial application if the write fails. + const updated = + action === 'delete' ? ctx.repo.deleteModels(ids) : ctx.repo.setModelsEnabled(ids, action === 'enable'); + audit(ctx, `model.bulk.${action}`, null, `requested=${ids.length} updated=${updated}`, request); return { updated }; }); @@ -144,7 +151,14 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo try { result = await syncProviderModels(ctx, provider); } catch (error) { - throw new HttpError(502, 'sync_failed', error instanceof Error ? error.message : String(error)); + if (error instanceof HttpError) throw error; + // FEAT-09: parity with the provider sync route — log the detail, return the + // client-safe message; never echo driver/upstream internals. + ctx.logger?.warn?.( + { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, + 'model sync failed', + ); + throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); ctx.events.emitProvider({ @@ -159,6 +173,7 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo 'model.sync', provider.id, `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 35346d0..1ecb6ff 100644 --- a/src/admin/providers.ts +++ b/src/admin/providers.ts @@ -10,6 +10,7 @@ import { asBool, asInt, asString, + assertNoControlChars, assertPublicProviderUrl, audit, fail, @@ -60,6 +61,15 @@ export function providerView(provider: ProviderRow): ProviderView { }; } +/** Origin of a provider base URL, or null when it does not parse. */ +function originOf(baseUrl: string): string | null { + try { + return new URL(baseUrl).origin; + } catch { + return null; + } +} + function priorityFrom(value: unknown): number { const parsed = asInt(value); if (parsed === null) fail(400, 'invalid_request', 'priority must be an integer'); @@ -92,6 +102,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): scope.post('/providers', async (request) => { const body = jsonBody(request); const name = requireString(body.name, 'name'); + assertNoControlChars(name, 'name'); const baseUrl = httpBaseUrl(body.baseUrl); assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); const apiKey = asString(body.apiKey); @@ -100,11 +111,12 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (enabled === null) fail(400, 'invalid_request', 'enabled must be true or false'); const priority = body.priority === undefined ? 100 : priorityFrom(body.priority); const id = asString(body.id) ?? undefined; + if (id) assertNoControlChars(id, 'id'); if (id && ctx.repo.getProvider(id)) { throw new HttpError(409, 'provider_exists', `Provider "${id}" already exists`); } const provider = ctx.repo.createProvider({ id, name, baseUrl, apiKey, enabled, priority }); - audit(ctx, 'provider.create', provider.id, `${provider.name} ${provider.baseUrl}`); + audit(ctx, 'provider.create', provider.id, `${provider.name} ${provider.baseUrl}`, request); return { provider: providerView(provider) }; }); @@ -117,6 +129,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (body.name !== undefined) { patch.name = requireString(body.name, 'name'); + assertNoControlChars(patch.name, 'name'); changed.push('name'); } if (body.baseUrl !== undefined) { @@ -141,18 +154,25 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): changed.push('priority'); } if (changed.length === 0) fail(400, 'invalid_request', 'No supported fields to update'); + // AD-07: a replaced URL/key or a re-enabled provider must not stay skipped by + // rotation because of a cooldown recorded against the old configuration. + if (changed.some((field) => field === 'baseUrl' || field === 'apiKey' || field === 'enabled')) { + patch.status = 'unknown'; + patch.cooldownUntil = null; + } const updated = ctx.repo.updateProvider(id, patch); if (!updated) throw new HttpError(404, 'provider_not_found', `Provider "${id}" not found`); - audit(ctx, 'provider.update', id, `fields=${changed.join(',')} previous=${current.name}`); + audit(ctx, 'provider.update', id, `fields=${changed.join(',')} previous=${current.name}`, request); return { provider: providerView(updated) }; }); scope.delete('/providers/:id', async (request) => { const id = (request.params as { id: string }).id; const current = loadProvider(ctx, id); - ctx.repo.deleteProvider(id); - audit(ctx, 'provider.delete', id, current.name); - return { ok: true }; + // AD-02: the provider's synced models go with it (no FK constraints exist). + const { modelsRemoved } = ctx.repo.deleteProviderWithModels(id); + audit(ctx, 'provider.delete', id, `${current.name} modelsRemoved=${modelsRemoved}`, request); + return { ok: true, modelsRemoved }; }); // Test before save — no persisted state required. `id` lets the dashboard probe @@ -167,6 +187,16 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (!id) fail(400, 'invalid_request', 'apiKey is required'); const stored = ctx.repo.getProvider(id); if (!stored) throw new HttpError(404, 'provider_not_found', `Provider "${id}" not found`); + // AD-04: reusing the stored key is only safe for the origin it was saved for; + // otherwise this endpoint would exfiltrate a provider credential to any host. + const draftOrigin = originOf(baseUrl); + if (draftOrigin === null || draftOrigin !== originOf(stored.baseUrl)) { + fail( + 400, + 'api_key_required', + 'apiKey is required when the baseUrl origin differs from the stored provider', + ); + } apiKey = asString(stored.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); } @@ -198,6 +228,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): probe.ok ? `ok models=${probe.models.length} latencyMs=${probe.latencyMs}` : `failed status=${probe.status} error=${probe.error ?? ''}`, + request, ); return { ok: probe.ok, @@ -215,15 +246,13 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): try { result = await syncProviderModels(ctx, provider); } catch (error) { + // The SSRF guard fails with a 400; only upstream failures become a 502. + if (error instanceof HttpError) throw error; ctx.logger?.warn?.( { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, 'provider model sync failed', ); - throw new HttpError( - 502, - 'sync_failed', - syncFailureMessage(provider.name), - ); + throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); ctx.events.emitProvider({ @@ -238,6 +267,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): 'provider.sync', provider.id, `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + request, ); return result; }); diff --git a/src/admin/session.ts b/src/admin/session.ts index 2def50f..0bf60d1 100644 --- a/src/admin/session.ts +++ b/src/admin/session.ts @@ -58,11 +58,26 @@ export function parseSessionCookie(value: string | undefined | null): SessionCoo return { sid, expiresAt, signature }; } +/** + * AD-09: `x-forwarded-proto` is attacker controlled unless `TRUST_PROXY` says a + * proxy sits in front (and strips/sets it). Without that opt-in the header must + * not influence the `Secure` cookie attribute. + */ +export function trustProxyEnabled(ctx?: AppContext): boolean { + const trust = ctx?.config.trustProxy; + if (trust === true) return true; + if (typeof trust === 'string') return trust.trim().length > 0; + if (Array.isArray(trust)) return trust.length > 0; + return false; +} + export function isSecureRequest(request: FastifyRequest, ctx?: AppContext): boolean { if (request.protocol === 'https') return true; - const forwarded = request.headers['x-forwarded-proto']; - const value = Array.isArray(forwarded) ? forwarded[0] : forwarded; - if (typeof value === 'string' && value.split(',')[0]?.trim().toLowerCase() === 'https') return true; + if (trustProxyEnabled(ctx)) { + const forwarded = request.headers['x-forwarded-proto']; + const value = Array.isArray(forwarded) ? forwarded[0] : forwarded; + if (typeof value === 'string' && value.split(',')[0]?.trim().toLowerCase() === 'https') return true; + } // A deployment that advertises an https PUBLIC_URL is served over TLS even when // the socket is plain http (TLS terminated in front), so never drop `Secure`. return ctx?.config.publicUrl?.startsWith('https://') ?? false; diff --git a/src/admin/settings.ts b/src/admin/settings.ts index 2d1d28d..5347f4e 100644 --- a/src/admin/settings.ts +++ b/src/admin/settings.ts @@ -16,6 +16,7 @@ import { asBool, asInt, asString, + assertNoControlChars, assertPasswordLength, audit, fail, @@ -33,6 +34,9 @@ const INT_SETTINGS: Record = { request_timeout_ms: { min: 1_000, max: 3_600_000 }, model_sync_interval_ms: { min: 30_000, max: 86_400_000 }, log_retention_days: { min: 1, max: 3_650 }, + 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 }, }; const ROTATION_STRATEGIES = new Set(['round-robin', 'priority', 'random']); @@ -41,11 +45,15 @@ function settingsView(ctx: AppContext): { settings: Record range.max) { fail(400, 'invalid_request', `${key} must be between ${range.min} and ${range.max}`); } - ctx.repo.setSetting(key, String(parsed)); return String(parsed); } if (key === 'rotation_strategy') { @@ -65,7 +72,6 @@ function applySetting(ctx: AppContext, key: string, value: unknown): string | nu if (!parsed || !ROTATION_STRATEGIES.has(parsed)) { fail(400, 'invalid_request', `rotation_strategy must be one of ${[...ROTATION_STRATEGIES].join(', ')}`); } - ctx.repo.setSetting(key, parsed); return parsed; } if (key === 'upstream_user_agent') { @@ -73,7 +79,8 @@ function applySetting(ctx: AppContext, key: string, value: unknown): string | nu if (!parsed || parsed.length > 200) { fail(400, 'invalid_request', 'upstream_user_agent must be a string of at most 200 characters'); } - ctx.repo.setSetting(key, parsed); + // GW-10: CR/LF would make every upstream `fetch` throw ERR_INVALID_CHAR. + assertNoControlChars(parsed, 'upstream_user_agent'); return parsed; } return null; @@ -116,12 +123,21 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): const body = jsonBody(request); const changed: string[] = []; const ignored: string[] = []; + const updates: Array<[string, string]> = []; for (const [key, value] of Object.entries(body)) { - const applied = applySetting(ctx, key, value); - if (applied === null) ignored.push(key); - else changed.push(key); + const validated = validateSetting(key, value); + if (validated === null) ignored.push(key); + else { + changed.push(key); + updates.push([key, validated]); + } + } + if (updates.length > 0) { + ctx.repo.transaction(() => { + for (const [key, value] of updates) ctx.repo.setSetting(key, value); + }); + audit(ctx, 'settings.update', null, `changed=${changed.join(',')}`, request); } - if (changed.length > 0) audit(ctx, 'settings.update', null, `changed=${changed.join(',')}`); return { ...settingsView(ctx), changed, ignored }; }); @@ -143,14 +159,14 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): setDashboardPassword(ctx, newPassword); const currentId = request.adminSession?.id ?? null; const revoked = ctx.repo.deleteOtherSessions(currentId); - audit(ctx, 'settings.password.change', null, `revokedSessions=${revoked}`); + audit(ctx, 'settings.password.change', null, `revokedSessions=${revoked}`, request); return { ok: true, revoked }; }); scope.delete('/settings/sessions', async (request) => { const currentId = request.adminSession?.id ?? null; const revoked = ctx.repo.deleteOtherSessions(currentId); - audit(ctx, 'settings.sessions.revoke', null, `revoked=${revoked}`); + audit(ctx, 'settings.sessions.revoke', null, `revoked=${revoked}`, request); return { ok: true, revoked }; }); @@ -166,7 +182,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): throw new HttpError(404, 'session_not_found', `Session "${id}" not found`); } ctx.repo.deleteSession(id); - audit(ctx, 'settings.session.revoke', id, null); + audit(ctx, 'settings.session.revoke', id, null, request); return { ok: true, revoked: 1 }; }); @@ -194,7 +210,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): // Every dashboard cookie is now invalid; gateway keys are sha256(plaintext) and keep working. ctx.repo.deleteAllSessions(); reply.header('cache-control', 'no-store'); - audit(ctx, 'settings.secret.rotate', null, 'dashboard sessions invalidated; gateway key hashes unchanged'); + audit(ctx, 'settings.secret.rotate', null, 'dashboard sessions invalidated; gateway key hashes unchanged', request); return { ok: true, secret, sessionsRevoked: true, notes: 'Gateway API keys are unaffected (sha256 of plaintext).' }; }); diff --git a/src/admin/stats.ts b/src/admin/stats.ts index c2d5bd0..205c708 100644 --- a/src/admin/stats.ts +++ b/src/admin/stats.ts @@ -6,6 +6,7 @@ import type { FastifyInstance, FastifyRequest } from 'fastify'; import type { AppContext } from '../core/context.js'; import { getActiveRequests } from '../core/context.js'; import type { StatsOverview } from '../db/repos.js'; +import type { SessionRow } from '../types.js'; import { formatSseJson } from '../util/sse.js'; import { ADMIN_VERSION, @@ -47,6 +48,43 @@ export function clearStatsCache(): void { /** How long to wait for a `drain` before treating the SSE client as stuck. */ const DRAIN_TIMEOUT_MS = 15_000; +/** AD-10: concurrent `/events` streams one process serves before answering 503. */ +export const MAX_EVENTS_STREAMS = 32; +/** AD-10: heartbeat cadence; also the session revalidation cadence. */ +export const EVENTS_HEARTBEAT_MS = 5_000; + +let openEventStreams = 0; + +/** Test/ops helper: forget the concurrent-stream counter. */ +export function resetEventStreams(): void { + openEventStreams = 0; +} + +export function activeEventStreamCount(): number { + return openEventStreams; +} + +/** AD-10: reserve one of the bounded SSE slots; false means the cap is reached. */ +export function acquireEventStream(): boolean { + if (openEventStreams >= MAX_EVENTS_STREAMS) return false; + openEventStreams += 1; + return true; +} + +export function releaseEventStream(): void { + openEventStreams = Math.max(0, openEventStreams - 1); +} + +/** + * AD-10: a stream is authorized at connect time only, so a revoked session or a + * `rotate-secret` (which deletes every session) used to keep streaming. Re-check + * the row + expiry on every heartbeat. + */ +export function eventStreamAuthorized(ctx: AppContext, session: SessionRow | null | undefined): boolean { + if (!session) return false; + if (session.expiresAt <= Date.now()) return false; + return ctx.repo.getSession(session.id) !== null; +} /** Per-client cap on frames buffered while `drain` is pending. */ const EVENTS_QUEUE_LIMIT = 256; @@ -181,8 +219,17 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo }); scope.get('/events', async (request, reply) => { + // AD-10: bound the number of concurrent streams before hijacking the reply. + if (!acquireEventStream()) { + await reply.status(503).send({ + error: { message: `Too many concurrent event streams (max ${MAX_EVENTS_STREAMS})`, code: 'too_many_streams' }, + }); + return; + } + reply.hijack(); const raw = reply.raw; + const session = request.adminSession ?? null; raw.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', @@ -199,7 +246,9 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo let drainTimer: ReturnType | null = null; let failures = 0; let closed = false; - let cleanup: () => void; + // Declared before the first `send()`: a throwing `raw.write` calls `cleanup`, + // and a `const`/unassigned binding there used to be a TDZ TypeError. + let cleanup: () => void = () => {}; const flushQueue = (): void => { draining = false; @@ -261,7 +310,13 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo const offStart = ctx.events.onRequestStart((event) => send('request:start', event)); const offEnd = ctx.events.onRequestEnd((event) => send('request:end', event)); const offProvider = ctx.events.onProvider((event) => send('provider:update', event)); - const heartbeat = setInterval(() => send('stats', statsHeartbeat(ctx)), 5_000); + const heartbeat = setInterval(() => { + if (!eventStreamAuthorized(ctx, session)) { + cleanup(); + return; + } + send('stats', statsHeartbeat(ctx)); + }, EVENTS_HEARTBEAT_MS); heartbeat.unref(); cleanup = (): void => { @@ -273,6 +328,7 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo offStart(); offEnd(); offProvider(); + releaseEventStream(); try { raw.end(); } catch { diff --git a/src/admin/sync.ts b/src/admin/sync.ts index d40fac3..214b73d 100644 --- a/src/admin/sync.ts +++ b/src/admin/sync.ts @@ -7,6 +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'; export const SYNC_TIMEOUT_MS = 20_000; @@ -175,6 +176,10 @@ export async function probeAndRecord( * cannot steal it from each other (see SPEC §3 sync semantics). */ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow): Promise { + // AD-03: sync reaches the network exactly like a probe, so the SSRF guard applies + // here too (a legacy row may predate the guard, the scheduler calls this directly). + assertPublicProviderUrl(provider.baseUrl, ctx.config.providerAllowPrivateHosts); + const probe = await probeProvider({ baseUrl: provider.baseUrl, apiKey: provider.apiKey }); if (!probe.ok) { ctx.logger?.warn?.( @@ -187,47 +192,54 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) throw new Error(syncFailureMessage(provider.name)); } - const existing = ctx.repo.listModels(); - const byId = new Map(existing.map((model) => [model.id, model])); - const upstreamIds = new Set(); - let added = 0; - let updated = 0; - - for (const model of probe.models) { - upstreamIds.add(model.id); - const current = byId.get(model.id); - if (current && current.source === 'manual') continue; - if (current && current.providerId !== null && current.providerId !== provider.id) continue; - const result = ctx.repo.upsertModel({ - id: model.id, - name: model.name, - providerId: provider.id, - contextLength: model.contextLength, - maxOutputTokens: model.maxOutputTokens, - capabilities: model.capabilities, - reasoning: model.reasoning, - source: 'sync', - }); - if (result.created) added += 1; - else updated += 1; - } + 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). + const counts = ctx.repo.transaction(() => { + const existing = ctx.repo.listModels(); + const byId = new Map(existing.map((model) => [model.id, model])); + const upstreamIds = new Set(); + let added = 0; + let updated = 0; + let removed = 0; + + for (const model of probe.models) { + upstreamIds.add(model.id); + const current = byId.get(model.id) ?? null; + if (current && current.source === 'manual') continue; + if (current && current.providerId !== null && current.providerId !== provider.id) continue; + const result = ctx.repo.upsertModel( + { + id: model.id, + name: model.name, + providerId: provider.id, + contextLength: model.contextLength, + maxOutputTokens: model.maxOutputTokens, + capabilities: model.capabilities, + reasoning: model.reasoning, + source: 'sync', + }, + current, + ); + byId.set(model.id, result.row); + if (result.created) added += 1; + else updated += 1; + } - let removed = 0; - for (const row of existing) { - if (row.source !== 'sync') continue; - if (row.providerId !== provider.id) continue; - if (upstreamIds.has(row.id)) continue; - if (ctx.repo.deleteModel(row.id)) removed += 1; - } + for (const row of existing) { + if (row.source !== 'sync') continue; + if (row.providerId !== provider.id) continue; + if (upstreamIds.has(row.id)) continue; + if (ctx.repo.deleteModel(row.id)) removed += 1; + } - const syncedAt = Date.now(); - ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); - ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, provider.id); + ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, provider.id); + return { added, updated, removed }; + }); return { - added, - updated, - removed, + ...counts, total: probe.models.length, providerId: provider.id, syncedAt, diff --git a/src/admin/util.ts b/src/admin/util.ts index 6b121fa..24382b2 100644 --- a/src/admin/util.ts +++ b/src/admin/util.ts @@ -243,7 +243,9 @@ export function assertPublicProviderUrl(rawUrl: string, allowPrivate: boolean): return; } if (allowPrivate) return; - const normalized = host.toLowerCase(); + // AD-01: `new URL('http://localhost./').hostname` keeps the trailing dot, which + // defeated every literal check (`localhost.`, `127.0.0.1.`, `10.0.0.5.`). + const normalized = host.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.+$/, ''); if (PRIVATE_HOSTS.has(normalized) || normalized.endsWith('.localhost') || isBlockedAddress(normalized)) { fail( 400, @@ -253,8 +255,19 @@ export function assertPublicProviderUrl(rawUrl: string, allowPrivate: boolean): } } +/** + * GW-10: control characters (CR/LF especially) in a header-bound value make Node + * throw `ERR_INVALID_CHAR` at write time, turning every proxied request into a 5xx. + */ +export function assertNoControlChars(value: string, field: string): void { + if (/[\u0000-\u001f\u007f]/.test(value)) { + fail(400, 'invalid_request', `${field} must not contain control characters`); + } +} + export function httpBaseUrl(value: unknown): string { const url = requireString(value, 'baseUrl'); + assertNoControlChars(url, 'baseUrl'); let parsed: URL; try { parsed = new URL(url); @@ -266,14 +279,23 @@ export function httpBaseUrl(value: unknown): string { fail(400, 'invalid_request', 'baseUrl must start with http:// or https://'); } if (!parsed.hostname) fail(400, 'invalid_request', 'baseUrl must include a host'); + // GW-12: credentials in the URL would be echoed back in upstream error messages. + if (parsed.username.length > 0 || parsed.password.length > 0) { + fail(400, 'invalid_request', 'baseUrl must not contain credentials'); + } return url.replace(/\/+$/, ''); } -/** Never expose the stored provider key: prefix + suffix only. */ +/** + * AD-08: never expose the stored provider key. Short keys are fully masked and + * long keys reveal at most 4 characters in total (`sk-123456` used to leak 8 of 9). + */ +export const MASKED_KEY_MIN_LENGTH = 12; + export function maskApiKey(key: string | null | undefined): string { if (!key) return ''; - if (key.length <= 8) return '****'; - return `${key.slice(0, 4)}...${key.slice(-4)}`; + if (key.length < MASKED_KEY_MIN_LENGTH) return '****'; + return `${key.slice(0, 2)}...${key.slice(-2)}`; } export function capabilitiesFrom(value: unknown): ModelCapabilities | undefined { @@ -327,9 +349,28 @@ export function sanitizeSettings(settings: Record): { return { settings: { ...rest, passwordSet }, passwordSet }; } -export function audit(ctx: AppContext, action: string, target: string | null = null, detail: string | null = null): void { +/** + * FEAT-05: the audit trail must say *who* acted. The session id goes into the + * actor column and the client IP is appended to the detail; both stay absent + * (actor `dashboard`) for callers without a request. + */ +export function auditActor(request: FastifyRequest | null | undefined): string { + const sessionId = request?.adminSession?.id; + if (sessionId) return `session:${sessionId}`; + return 'dashboard'; +} + +export function audit( + ctx: AppContext, + action: string, + target: string | null = null, + detail: string | null = null, + request?: FastifyRequest | null, +): void { + const ip = request ? clientIp(request) : null; + const withIp = ip ? (detail ? `${detail} ip=${ip}` : `ip=${ip}`) : detail; try { - ctx.repo.audit('dashboard', action, target, detail); + ctx.repo.audit(auditActor(request), action, target, withIp); } catch (error) { ctx.logger?.warn?.({ err: error, action }, 'failed to write audit entry'); } @@ -357,7 +398,8 @@ export interface HealthSnapshot { } export function activeKeyCount(ctx: AppContext): number { - return ctx.repo.listApiKeys().filter((key) => key.enabled && key.revokedAt === null).length; + // OPT-04: COUNT in SQLite instead of materializing every key row. + return ctx.repo.countActiveApiKeys(); } export function buildHealth(ctx: AppContext): HealthSnapshot { diff --git a/src/core/seed.ts b/src/core/seed.ts index 672968b..11bef9b 100644 --- a/src/core/seed.ts +++ b/src/core/seed.ts @@ -27,12 +27,25 @@ export function seedDefaults(ctx: AppContext): void { repo.purgeExpiredSessions(); } -/** Removes old request logs and audit entries according to the retention setting. */ +const DAY_MS = 24 * 60 * 60 * 1000; + +function retentionDays(ctx: AppContext, key: string, fallback: number): number { + const configured = ctx.repo.getInt(key, fallback); + if (!Number.isFinite(configured)) return fallback; + return Math.min(Math.max(configured, 1), 3_650); +} + +/** + * Removes old request logs and audit entries according to their retention settings. + * FEAT-05: the security trail is pruned by `audit_retention_days` (default 90), so a + * 1-day log retention can no longer wipe the audit history. + */ export function pruneLogs(ctx: AppContext): number { - const days = Math.max(1, ctx.repo.getInt('log_retention_days', 30)); - const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; - ctx.repo.deleteAuditBefore(cutoff); - return ctx.repo.deleteLogsBefore(cutoff); + const now = Date.now(); + const auditDays = retentionDays(ctx, 'audit_retention_days', 90); + const logDays = retentionDays(ctx, 'log_retention_days', 30); + ctx.repo.deleteAuditBefore(now - auditDays * DAY_MS); + return ctx.repo.deleteLogsBefore(now - logDays * DAY_MS); } export function verifyDashboardPassword(ctx: AppContext, password: string): boolean { diff --git a/src/core/shutdown.ts b/src/core/shutdown.ts new file mode 100644 index 0000000..23f730f --- /dev/null +++ b/src/core/shutdown.ts @@ -0,0 +1,86 @@ +/** + * FEAT-07: bounded graceful shutdown. + * + * `app.close()` waits for in-flight requests (a long SSE stream can hold it for + * minutes) while `onClose` hooks flush pending writes (scheduler stop, `db.close()` + * which checkpoints WAL). After `timeoutMs` the remaining sockets are force-closed + * so a stuck client cannot hang the process forever. + */ +import type { FastifyBaseLogger } from 'fastify'; + +export interface ShutdownHost { + close(): Promise; + server?: { closeAllConnections?: () => void }; + log: FastifyBaseLogger; +} + +/** How long to let in-flight requests finish before force-closing their sockets. */ +export const SHUTDOWN_DRAIN_MS = 10_000; + +export interface ShutdownOptions { + timeoutMs?: number; + /** Called once when a shutdown starts (clear intervals, stop schedulers). */ + onShutdownStart?: () => void; + /** Signal source; defaults to `process` (injectable for tests). */ + signals?: Pick; + /** Defaults to `process.exit`; injectable for tests. */ + exit?: (code: number) => void; +} + +export interface ShutdownController { + shutdown(signal: string): Promise; + readonly started: boolean; +} + +export function registerGracefulShutdown(host: ShutdownHost, options: ShutdownOptions = {}): ShutdownController { + const timeoutMs = options.timeoutMs ?? SHUTDOWN_DRAIN_MS; + const signals = options.signals ?? process; + const exit = options.exit ?? ((code: number): void => process.exit(code)); + let started = false; + + const shutdown = async (signal: string): Promise => { + // A second SIGTERM during the drain must not start a competing shutdown. + if (started) return; + started = true; + host.log.info({ signal, timeoutMs }, 'shutting down; draining in-flight requests'); + try { + options.onShutdownStart?.(); + } catch (error) { + host.log.warn({ err: error }, 'shutdown start hook failed'); + } + + const force = setTimeout(() => { + host.log.warn({ timeoutMs }, 'shutdown drain timed out; force-closing connections'); + try { + host.server?.closeAllConnections?.(); + } catch (error) { + host.log.warn({ err: error }, 'force-closing connections failed'); + } + }, timeoutMs); + force.unref?.(); + + let code = 0; + try { + await host.close(); + host.log.info({ signal }, 'shutdown complete'); + } catch (error) { + code = 1; + host.log.error({ err: error, signal }, 'shutdown failed'); + } finally { + clearTimeout(force); + } + exit(code); + }; + + for (const signal of ['SIGINT', 'SIGTERM'] as const) { + signals.on(signal, () => { + void shutdown(signal); + }); + } + return { + shutdown, + get started(): boolean { + return started; + }, + }; +} diff --git a/src/db/repos.ts b/src/db/repos.ts index 8c0346d..6695582 100644 --- a/src/db/repos.ts +++ b/src/db/repos.ts @@ -1,4 +1,4 @@ -import type { DatabaseSync } from 'node:sqlite'; +import type { DatabaseSync, StatementSync } from 'node:sqlite'; import { hashApiKey, generateApiKey, uuid } from '../util/crypto.js'; import type { ApiKeyRow, @@ -39,8 +39,10 @@ export const DEFAULT_SETTINGS: Record = { auto_sync_models: 'true', model_sync_interval_ms: '300000', log_retention_days: '30', + audit_retention_days: '90', model_allow_unknown: 'false', upstream_user_agent: 'opencode-router/1.0', + stream_idle_timeout_ms: '120000', }; export interface LogQuery { @@ -88,13 +90,59 @@ export interface StatsOverview { recentErrors: Array<{ ts: number; model: string | null; providerName: string | null; status: number; errorCode: string | null; errorMessage: string | null }>; } +/** Fallbacks used when a model row is written without explicit capabilities. */ +const DEFAULT_MODEL_CAPABILITIES: ModelCapabilities = { tools: true, input: ['text'], output: ['text'], temperature: true }; +const DEFAULT_MODEL_REASONING: ModelReasoning = { supported: false, efforts: [], defaultEffort: null }; + export class Repo { + /** OPT-01: `node:sqlite` re-prepares on every `prepare()`; the gateway hot path prepares the same SQL per request. */ + private readonly statements = new Map(); + private txDepth = 0; + constructor(private readonly db: DatabaseSync) {} + /** Cached `prepare` — one `StatementSync` per distinct SQL string. */ + private stmt(sql: string): StatementSync { + let statement = this.statements.get(sql); + if (!statement) { + // Filters build SQL dynamically (log queries), so bound the cache: clearing it + // is cheap and keeps a pathological caller from growing it without limit. + if (this.statements.size >= 256) this.statements.clear(); + statement = this.db.prepare(sql); + this.statements.set(sql, statement); + } + return statement; + } + + /** + * Runs `fn` inside one transaction so multi-statement writes are all-or-nothing + * (AD-02/AD-05/AD-06). Re-entrant calls join the outer transaction instead of + * opening a nested `BEGIN` (SQLite rejects that). + */ + transaction(fn: () => T): T { + if (this.txDepth > 0) return fn(); + this.db.exec('BEGIN IMMEDIATE'); + this.txDepth += 1; + try { + const result = fn(); + this.db.exec('COMMIT'); + return result; + } catch (error) { + try { + this.db.exec('ROLLBACK'); + } catch { + /* the transaction was already rolled back by SQLite */ + } + throw error; + } finally { + this.txDepth -= 1; + } + } + /* ------------------------------------------------------------------ settings */ getSetting(key: string): string | null { - const row = this.db.prepare('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined; + const row = this.stmt('SELECT value FROM settings WHERE key = ?').get(key) as Row | undefined; if (!row) return DEFAULT_SETTINGS[key] ?? null; return String(row.value); } @@ -110,8 +158,7 @@ export class Repo { } setSetting(key: string, value: string): void { - this.db - .prepare( + this.stmt( `INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, ) @@ -120,7 +167,7 @@ export class Repo { allSettings(): Record { const out: Record = { ...DEFAULT_SETTINGS }; - for (const row of this.db.prepare('SELECT key, value FROM settings').all() as Row[]) { + for (const row of this.stmt('SELECT key, value FROM settings').all() as Row[]) { out[String(row.key)] = String(row.value); } return out; @@ -149,14 +196,14 @@ export class Repo { } listProviders(): ProviderRow[] { - const rows = this.db - .prepare('SELECT * FROM providers ORDER BY priority ASC, created_at ASC') + const rows = this.stmt( + 'SELECT * FROM providers ORDER BY priority ASC, created_at ASC') .all() as Row[]; return rows.map((r) => this.mapProvider(r)); } getProvider(id: string): ProviderRow | null { - const row = this.db.prepare('SELECT * FROM providers WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM providers WHERE id = ?').get(id) as Row | undefined; return row ? this.mapProvider(row) : null; } @@ -170,8 +217,7 @@ export class Repo { }): ProviderRow { const now = Date.now(); const id = input.id?.trim() || uuid(); - this.db - .prepare( + this.stmt( `INSERT INTO providers (id, name, base_url, api_key, enabled, priority, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'unknown', ?, ?)`, ) @@ -214,8 +260,7 @@ export class Repo { lastError: patch.lastError === undefined ? current.lastError : patch.lastError, updatedAt: Date.now(), }; - this.db - .prepare( + this.stmt( `UPDATE providers SET name=?, base_url=?, api_key=?, enabled=?, priority=?, status=?, cooldown_until=?, last_error=?, updated_at=? WHERE id=?`, ) @@ -235,13 +280,24 @@ export class Repo { } deleteProvider(id: string): boolean { - const res = this.db.prepare('DELETE FROM providers WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM providers WHERE id = ?').run(id); return Number(res.changes) > 0; } + /** + * AD-02: `PRAGMA foreign_keys=ON` has no FK constraints, so deleting a provider + * used to leave its synced models with a dangling `provider_id` forever. + */ + deleteProviderWithModels(id: string): { deleted: boolean; modelsRemoved: number } { + return this.transaction(() => { + const modelsRemoved = this.deleteModelsByProvider(id); + const res = this.stmt('DELETE FROM providers WHERE id = ?').run(id); + return { deleted: Number(res.changes) > 0, modelsRemoved }; + }); + } + recordProviderSuccess(id: string, latencyMs: number): void { - this.db - .prepare( + this.stmt( `UPDATE providers SET status='ok', cooldown_until=NULL, last_error=NULL, last_checked_at=?, last_latency_ms=?, success_count=success_count+1, updated_at=? WHERE id=?`, ) @@ -251,19 +307,23 @@ export class Repo { recordProviderFailure(id: string, status: number | null, error: string, cooldownMs: number): void { const now = Date.now(); const rateLimited = status === 429 || status === 503 || status === 529 || (status !== null && status >= 500); - this.db - .prepare( - `UPDATE providers SET status=?, cooldown_until=?, last_error=?, last_checked_at=?, + // GW-15: a network failure (`status === null`), 408/409/425 or a 3xx is retryable + // too, so the provider backs off instead of being re-hit on the next request. + // The `status` column keeps its previous rate-limit-only semantics. + const coolDown = + status === null || + status === 408 || + status === 409 || + status === 425 || + status === 429 || + status === 503 || + status === 529 || + status >= 500 || + (status >= 300 && status < 400); + 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', - rateLimited ? now + cooldownMs : null, - error.slice(0, 500), - now, - now, - id, - ); + ).run(rateLimited ? 'cooldown' : 'error', coolDown ? now + cooldownMs : null, error.slice(0, 500), now, now, id); } /* -------------------------------------------------------------------- models */ @@ -290,67 +350,98 @@ export class Repo { } listModels(): ModelRow[] { - const rows = this.db.prepare('SELECT * FROM models ORDER BY id ASC').all() as Row[]; + const rows = this.stmt('SELECT * FROM models ORDER BY id ASC').all() as Row[]; return rows.map((r) => this.mapModel(r)); } getModel(id: string): ModelRow | null { - const row = this.db.prepare('SELECT * FROM models WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM models WHERE id = ?').get(id) as Row | undefined; return row ? this.mapModel(row) : null; } - upsertModel(input: { - id: string; - name?: string; - providerId?: string | null; - contextLength?: number | null; - maxOutputTokens?: number | null; - capabilities?: ModelCapabilities; - reasoning?: ModelReasoning; - enabled?: boolean; - source?: 'sync' | 'manual'; - }): { row: ModelRow; created: boolean } { - const existing = this.getModel(input.id); + /** + * OPT-10: `known` lets a bulk caller (provider sync) pass the row it already + * loaded, so the upsert does not re-read every model. The returned row is built + * from the inputs — no trailing `getModel` round-trip either. + */ + upsertModel( + input: { + id: string; + name?: string; + providerId?: string | null; + contextLength?: number | null; + maxOutputTokens?: number | null; + capabilities?: ModelCapabilities; + reasoning?: ModelReasoning; + enabled?: boolean; + source?: 'sync' | 'manual'; + }, + known?: ModelRow | null, + ): { row: ModelRow; created: boolean } { + const existing = known === undefined ? this.getModel(input.id) : known; const now = Date.now(); if (!existing) { - this.db - .prepare( - `INSERT INTO models (id, name, provider_id, context_length, max_output_tokens, capabilities, reasoning, enabled, source, created_at, updated_at) + const capabilities = input.capabilities ?? DEFAULT_MODEL_CAPABILITIES; + const reasoning = input.reasoning ?? DEFAULT_MODEL_REASONING; + const row: ModelRow = { + id: input.id, + name: input.name ?? input.id, + providerId: input.providerId ?? null, + contextLength: input.contextLength ?? null, + maxOutputTokens: input.maxOutputTokens ?? null, + capabilities, + reasoning, + enabled: input.enabled !== false, + source: input.source ?? 'manual', + createdAt: now, + updatedAt: now, + }; + this.stmt( + `INSERT INTO models (id, name, provider_id, context_length, max_output_tokens, capabilities, reasoning, enabled, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ) - .run( - input.id, - input.name ?? input.id, - input.providerId ?? null, - input.contextLength ?? null, - input.maxOutputTokens ?? null, - JSON.stringify(input.capabilities ?? { tools: true, input: ['text'], output: ['text'], temperature: true }), - JSON.stringify(input.reasoning ?? { supported: false, efforts: [], defaultEffort: null }), - input.enabled === false ? 0 : 1, - input.source ?? 'manual', - now, - now, - ); - return { row: this.getModel(input.id)!, created: true }; + ).run( + row.id, + row.name, + row.providerId, + row.contextLength, + row.maxOutputTokens, + JSON.stringify(capabilities), + JSON.stringify(reasoning), + row.enabled ? 1 : 0, + row.source, + row.createdAt, + row.updatedAt, + ); + return { row, created: true }; } - this.db - .prepare( - `UPDATE models SET name=?, provider_id=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, + const row: ModelRow = { + ...existing, + name: input.name ?? existing.name, + providerId: input.providerId === undefined ? existing.providerId : input.providerId, + contextLength: input.contextLength === undefined ? existing.contextLength : input.contextLength, + maxOutputTokens: input.maxOutputTokens === undefined ? existing.maxOutputTokens : input.maxOutputTokens, + capabilities: input.capabilities ?? existing.capabilities, + reasoning: input.reasoning ?? existing.reasoning, + enabled: input.enabled ?? existing.enabled, + source: input.source ?? existing.source, + updatedAt: now, + }; + this.stmt( + `UPDATE models SET name=?, provider_id=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, enabled=?, source=?, updated_at=? WHERE id=?`, - ) - .run( - input.name ?? existing.name, - input.providerId === undefined ? existing.providerId : input.providerId, - input.contextLength === undefined ? existing.contextLength : input.contextLength, - input.maxOutputTokens === undefined ? existing.maxOutputTokens : input.maxOutputTokens, - JSON.stringify(input.capabilities ?? existing.capabilities), - JSON.stringify(input.reasoning ?? existing.reasoning), - (input.enabled ?? existing.enabled) ? 1 : 0, - input.source ?? existing.source, - now, - input.id, - ); - return { row: this.getModel(input.id)!, created: false }; + ).run( + row.name, + row.providerId, + row.contextLength, + row.maxOutputTokens, + JSON.stringify(row.capabilities), + JSON.stringify(row.reasoning), + row.enabled ? 1 : 0, + row.source, + row.updatedAt, + row.id, + ); + return { row, created: false }; } updateModel( @@ -366,8 +457,7 @@ export class Repo { ): ModelRow | null { const existing = this.getModel(id); if (!existing) return null; - this.db - .prepare( + this.stmt( `UPDATE models SET name=?, enabled=?, context_length=?, max_output_tokens=?, capabilities=?, reasoning=?, updated_at=? WHERE id=?`, ) @@ -385,20 +475,54 @@ export class Repo { } deleteModel(id: string): boolean { - const res = this.db.prepare('DELETE FROM models WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM models WHERE id = ?').run(id); return Number(res.changes) > 0; } deleteAllModels(): number { - const res = this.db.prepare('DELETE FROM models').run(); + const res = this.stmt('DELETE FROM models').run(); return Number(res.changes); } enabledModelIds(): string[] { - const rows = this.db.prepare('SELECT id FROM models WHERE enabled = 1').all() as Row[]; + const rows = this.stmt('SELECT id FROM models WHERE enabled = 1').all() as Row[]; return rows.map((r) => String(r.id)); } + /** + * Existence check for the gateway hot path: `enabledModelIds().length === 0` + * materialized every id just to answer a boolean question. + */ + hasEnabledModel(): boolean { + const row = this.stmt('SELECT EXISTS(SELECT 1 FROM models WHERE enabled = 1) AS c').get() as Row; + return num(row.c) > 0; + } + + /** + * AD-05: one set-based statement inside a transaction instead of a + * `getModel` + `UPDATE` per id. Returns the number of existing rows matched. + */ + setModelsEnabled(ids: string[], enabled: boolean): number { + if (ids.length === 0) return 0; + const placeholders = ids.map(() => '?').join(','); + return this.transaction(() => { + const result = this.stmt( + `UPDATE models SET enabled = ?, updated_at = ? WHERE id IN (${placeholders})`, + ).run(enabled ? 1 : 0, Date.now(), ...ids); + return Number(result.changes); + }); + } + + /** AD-05: bulk delete counterpart of `setModelsEnabled`. */ + deleteModels(ids: string[]): number { + if (ids.length === 0) return 0; + const placeholders = ids.map(() => '?').join(','); + return this.transaction(() => { + const result = this.stmt(`DELETE FROM models WHERE id IN (${placeholders})`).run(...ids); + return Number(result.changes); + }); + } + /* ------------------------------------------------------------------ api keys */ private mapApiKey(row: Row): ApiKeyRow { @@ -417,23 +541,33 @@ export class Repo { } listApiKeys(): ApiKeyRow[] { - const rows = this.db.prepare('SELECT * FROM api_keys ORDER BY created_at DESC').all() as Row[]; + const rows = this.stmt('SELECT * FROM api_keys ORDER BY created_at DESC').all() as Row[]; return rows.map((r) => this.mapApiKey(r)); } hasActiveApiKey(): boolean { - const row = this.db - .prepare('SELECT COUNT(*) AS c FROM api_keys WHERE enabled = 1 AND revoked_at IS NULL') + return this.countActiveApiKeys() > 0; + } + + /** Cheaper than `listApiKeys().length` for the gateway hot path. */ + countActiveApiKeys(): number { + const row = this.stmt( + 'SELECT COUNT(*) AS c FROM api_keys WHERE enabled = 1 AND revoked_at IS NULL') .get() as Row; - return num(row.c) > 0; + return num(row.c); + } + + /** Removes a provider's synced models when the provider itself is deleted. */ + deleteModelsByProvider(providerId: string): number { + const res = this.stmt('DELETE FROM models WHERE provider_id = ?').run(providerId); + return Number(res.changes); } createApiKey(name: string): { row: ApiKeyRow; plaintext: string } { const plaintext = generateApiKey(); const id = uuid(); const now = Date.now(); - this.db - .prepare( + this.stmt( `INSERT INTO api_keys (id, name, key_hash, key_prefix, key_suffix, enabled, request_count, created_at) VALUES (?, ?, ?, ?, ?, 1, 0, ?)`, ) @@ -442,12 +576,12 @@ export class Repo { } getApiKey(id: string): ApiKeyRow | null { - const row = this.db.prepare('SELECT * FROM api_keys WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM api_keys WHERE id = ?').get(id) as Row | undefined; return row ? this.mapApiKey(row) : null; } findApiKeyByPlaintext(plaintext: string): ApiKeyRow | null { - const row = this.db.prepare('SELECT * FROM api_keys WHERE key_hash = ?').get(hashApiKey(plaintext)) as + const row = this.stmt('SELECT * FROM api_keys WHERE key_hash = ?').get(hashApiKey(plaintext)) as | Row | undefined; return row ? this.mapApiKey(row) : null; @@ -456,8 +590,8 @@ export class Repo { updateApiKey(id: string, patch: { name?: string; enabled?: boolean; revoked?: boolean }): ApiKeyRow | null { const existing = this.getApiKey(id); if (!existing) return null; - this.db - .prepare('UPDATE api_keys SET name = ?, enabled = ?, revoked_at = ? WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET name = ?, enabled = ?, revoked_at = ? WHERE id = ?') .run( patch.name ?? existing.name, (patch.enabled ?? existing.enabled) ? 1 : 0, @@ -474,20 +608,20 @@ export class Repo { rotateApiKey(id: string, plaintext: string): ApiKeyRow | null { const existing = this.getApiKey(id); if (!existing) return null; - this.db - .prepare('UPDATE api_keys SET key_hash = ?, key_prefix = ?, key_suffix = ? WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET key_hash = ?, key_prefix = ?, key_suffix = ? WHERE id = ?') .run(hashApiKey(plaintext), plaintext.slice(0, 8), plaintext.slice(-4), id); return this.getApiKey(id); } deleteApiKey(id: string): boolean { - const res = this.db.prepare('DELETE FROM api_keys WHERE id = ?').run(id); + const res = this.stmt('DELETE FROM api_keys WHERE id = ?').run(id); return Number(res.changes) > 0; } touchApiKey(id: string): void { - this.db - .prepare('UPDATE api_keys SET last_used_at = ?, request_count = request_count + 1 WHERE id = ?') + this.stmt( + 'UPDATE api_keys SET last_used_at = ?, request_count = request_count + 1 WHERE id = ?') .run(Date.now(), id); } @@ -522,8 +656,7 @@ export class Repo { } insertLog(entry: RequestLogRow): void { - this.db - .prepare( + this.stmt( `INSERT INTO request_logs (id, ts, key_id, key_name, provider_id, provider_name, model, surface, stream, status, ok, error_code, error_message, latency_ms, ttfb_ms, input_tokens, output_tokens, total_tokens, reasoning_tokens, cached_tokens, attempts, client_ip, user_agent) @@ -557,8 +690,7 @@ export class Repo { } insertAttempt(entry: AttemptRow): void { - this.db - .prepare( + this.stmt( `INSERT INTO request_attempts (id, request_id, ts, provider_id, provider_name, attempt, status, ok, error_code, error_message, latency_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) @@ -578,8 +710,8 @@ export class Repo { } listAttempts(requestId: string): AttemptRow[] { - const rows = this.db - .prepare('SELECT * FROM request_attempts WHERE request_id = ? ORDER BY attempt ASC') + const rows = this.stmt( + 'SELECT * FROM request_attempts WHERE request_id = ? ORDER BY attempt ASC') .all(requestId) as Row[]; return rows.map((r) => ({ id: String(r.id), @@ -640,38 +772,51 @@ export class Repo { params.push(like, like, like, like); } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; - const totalRow = this.db.prepare(`SELECT COUNT(*) AS c FROM request_logs ${clause}`).get(...params) as Row; + const totalRow = this.stmt(`SELECT COUNT(*) AS c FROM request_logs ${clause}`).get(...params) as Row; const limit = Math.min(Math.max(query.limit ?? 50, 1), 500); const offset = Math.max(query.offset ?? 0, 0); - const rows = this.db - .prepare(`SELECT * FROM request_logs ${clause} ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`) + const rows = this.stmt( + `SELECT * FROM request_logs ${clause} ORDER BY ts DESC, rowid DESC LIMIT ? OFFSET ?`) .all(...params, limit, offset) as Row[]; return { rows: rows.map((r) => this.mapLog(r)), total: num(totalRow.c) }; } getLog(id: string): RequestLogRow | null { - const row = this.db.prepare('SELECT * FROM request_logs WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM request_logs WHERE id = ?').get(id) as Row | undefined; return row ? this.mapLog(row) : null; } deleteLogsBefore(ts: number): number { - const res = this.db.prepare('DELETE FROM request_logs WHERE ts < ?').run(ts); - this.db.prepare('DELETE FROM request_attempts WHERE ts < ?').run(ts); + 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); } clearLogs(): number { - const res = this.db.prepare('DELETE FROM request_logs').run(); - this.db.prepare('DELETE FROM request_attempts').run(); + 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.db - .prepare( + const totalsRow = this.stmt( `SELECT COUNT(*) AS requests, COALESCE(SUM(ok), 0) AS ok, COALESCE(SUM(CASE WHEN stream = 1 THEN 1 ELSE 0 END), 0) AS streaming, @@ -686,19 +831,13 @@ export class Repo { ) .get(since) as Row; - const latencies = ( - this.db - .prepare('SELECT latency_ms FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL ORDER BY latency_ms ASC') - .all(since) as Row[] - ).map((r) => num(r.latency_ms)); - const percentile = (p: number): number => { - if (latencies.length === 0) return 0; - const idx = Math.min(latencies.length - 1, Math.floor((p / 100) * latencies.length)); - return latencies[idx] ?? 0; - }; + 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); - const seriesRows = this.db - .prepare( + const seriesRows = this.stmt( `SELECT CAST(ts / ? AS INTEGER) * ? AS bucket, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END), 0) AS errors, @@ -708,8 +847,7 @@ export class Repo { .all(bucketMs, bucketMs, since) as Row[]; const byModel = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(model, 'unknown') AS model, COUNT(*) AS requests, COALESCE(SUM(total_tokens),0) AS tokens, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors, COALESCE(AVG(latency_ms),0) AS avg_latency FROM request_logs WHERE ts >= ? GROUP BY model ORDER BY requests DESC LIMIT 12`, @@ -724,8 +862,7 @@ export class Repo { })); const byProvider = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(provider_id, '') AS provider_id, COALESCE(provider_name, 'unknown') AS provider_name, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors, COALESCE(AVG(latency_ms),0) AS avg_latency @@ -741,8 +878,7 @@ export class Repo { })); const bySurface = ( - this.db - .prepare( + this.stmt( `SELECT surface, COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors FROM request_logs WHERE ts >= ? GROUP BY surface`, ) @@ -750,8 +886,7 @@ export class Repo { ).map((r) => ({ surface: String(r.surface), requests: num(r.requests), errors: num(r.errors) })); const byKey = ( - this.db - .prepare( + this.stmt( `SELECT COALESCE(key_id, '') AS key_id, COALESCE(key_name, 'unknown') AS key_name, COUNT(*) AS requests, COALESCE(SUM(total_tokens),0) AS tokens FROM request_logs WHERE ts >= ? GROUP BY key_id ORDER BY requests DESC LIMIT 12`, @@ -765,14 +900,13 @@ export class Repo { })); const byStatus = ( - this.db - .prepare('SELECT status, COUNT(*) AS requests FROM request_logs WHERE ts >= ? GROUP BY status ORDER BY requests DESC LIMIT 12') + this.stmt( + 'SELECT status, COUNT(*) AS requests FROM request_logs WHERE ts >= ? GROUP BY status ORDER BY requests DESC LIMIT 12') .all(since) as Row[] ).map((r) => ({ status: num(r.status), requests: num(r.requests) })); const recentErrors = ( - this.db - .prepare( + this.stmt( `SELECT ts, model, provider_name, status, error_code, error_message FROM request_logs WHERE ts >= ? AND ok = 0 ORDER BY ts DESC LIMIT 10`, ) @@ -786,8 +920,7 @@ export class Repo { errorMessage: strOrNull(r.error_message), })); - const last60 = this.db - .prepare( + const last60 = this.stmt( `SELECT COUNT(*) AS requests, COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END),0) AS errors FROM request_logs WHERE ts >= ?`, ) @@ -840,8 +973,7 @@ export class Repo { }): SessionRow { const now = Date.now(); const expiresAt = now + input.ttlMs; - this.db - .prepare( + this.stmt( `INSERT INTO sessions (id, created_at, expires_at, last_seen_at, client_ip, user_agent) VALUES (?, ?, ?, ?, ?, ?)`, ) .run(input.id, now, expiresAt, now, input.clientIp, input.userAgent); @@ -849,7 +981,7 @@ export class Repo { } getSession(id: string): SessionRow | null { - const row = this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as Row | undefined; + const row = this.stmt('SELECT * FROM sessions WHERE id = ?').get(id) as Row | undefined; if (!row) return null; return { id: String(row.id), @@ -862,32 +994,32 @@ export class Repo { } touchSession(id: string): void { - this.db.prepare('UPDATE sessions SET last_seen_at = ? WHERE id = ?').run(Date.now(), id); + this.stmt('UPDATE sessions SET last_seen_at = ? WHERE id = ?').run(Date.now(), id); } deleteSession(id: string): void { - this.db.prepare('DELETE FROM sessions WHERE id = ?').run(id); + this.stmt('DELETE FROM sessions WHERE id = ?').run(id); } deleteAllSessions(): void { - this.db.prepare('DELETE FROM sessions').run(); + this.stmt('DELETE FROM sessions').run(); } /** Deletes every session except `keepId` in one statement (no LIMIT 50 pitfall). */ deleteOtherSessions(keepId: string | null): number { const result = keepId === null - ? this.db.prepare('DELETE FROM sessions').run() - : this.db.prepare('DELETE FROM sessions WHERE id <> ?').run(keepId); + ? this.stmt('DELETE FROM sessions').run() + : this.stmt('DELETE FROM sessions WHERE id <> ?').run(keepId); return Number(result.changes); } purgeExpiredSessions(): void { - this.db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(Date.now()); + this.stmt('DELETE FROM sessions WHERE expires_at < ?').run(Date.now()); } listSessions(): SessionRow[] { - const rows = this.db.prepare('SELECT * FROM sessions ORDER BY last_seen_at DESC LIMIT 50').all() as Row[]; + const rows = this.stmt('SELECT * FROM sessions ORDER BY last_seen_at DESC LIMIT 50').all() as Row[]; return rows.map((r) => ({ id: String(r.id), createdAt: num(r.created_at), @@ -901,19 +1033,19 @@ export class Repo { /* --------------------------------------------------------------------- audit */ deleteAuditBefore(ts: number): number { - const result = this.db.prepare('DELETE FROM audit_logs WHERE ts < ?').run(ts); + const result = this.stmt('DELETE FROM audit_logs WHERE ts < ?').run(ts); return Number(result.changes); } audit(actor: string, action: string, target: string | null, detail: string | null): void { - this.db - .prepare('INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)') + this.stmt( + 'INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)') .run(uuid(), Date.now(), actor, action, target, detail); } listAudit(limit = 100): AuditRow[] { - const rows = this.db - .prepare('SELECT * FROM audit_logs ORDER BY ts DESC LIMIT ?') + const rows = this.stmt( + 'SELECT * FROM audit_logs ORDER BY ts DESC LIMIT ?') .all(Math.min(Math.max(limit, 1), 500)) as Row[]; return rows.map((r) => ({ id: String(r.id), @@ -929,7 +1061,7 @@ export class Repo { const tables = ['providers', 'models', 'api_keys', 'request_logs', 'sessions']; const out: Record = {}; for (const table of tables) { - const row = this.db.prepare(`SELECT COUNT(*) AS c FROM ${table}`).get() as Row; + const row = this.stmt(`SELECT COUNT(*) AS c FROM ${table}`).get() as Row; out[table] = num(row.c); } return out; diff --git a/src/db/schema.ts b/src/db/schema.ts index 563e32e..694a271 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -34,6 +34,8 @@ CREATE TABLE IF NOT EXISTS providers ( updated_at INTEGER NOT NULL ); +CREATE INDEX IF NOT EXISTS idx_providers_enabled ON providers (enabled, priority); + CREATE TABLE IF NOT EXISTS models ( id TEXT PRIMARY KEY, name TEXT NOT NULL, @@ -61,6 +63,8 @@ CREATE TABLE IF NOT EXISTS api_keys ( revoked_at INTEGER ); +CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys (enabled, revoked_at); + CREATE TABLE IF NOT EXISTS request_logs ( id TEXT PRIMARY KEY, ts INTEGER NOT NULL, @@ -92,6 +96,11 @@ CREATE INDEX IF NOT EXISTS idx_request_logs_key ON request_logs (key_id, ts DESC CREATE INDEX IF NOT EXISTS idx_request_logs_model ON request_logs (model, ts DESC); CREATE INDEX IF NOT EXISTS idx_request_logs_provider ON request_logs (provider_id, ts DESC); CREATE INDEX IF NOT EXISTS idx_request_logs_latency ON request_logs (ts, latency_ms); +-- OPT-02: indexes for real predicates (idempotent on existing databases). +CREATE INDEX IF NOT EXISTS idx_request_logs_ts_ok ON request_logs (ts, ok); + +CREATE INDEX IF NOT EXISTS idx_models_enabled ON models (enabled); +CREATE INDEX IF NOT EXISTS idx_models_provider ON models (provider_id); CREATE TABLE IF NOT EXISTS request_attempts ( id TEXT PRIMARY KEY, @@ -119,6 +128,8 @@ CREATE TABLE IF NOT EXISTS sessions ( user_agent TEXT ); +CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions (expires_at); + CREATE TABLE IF NOT EXISTS audit_logs ( id TEXT PRIMARY KEY, ts INTEGER NOT NULL, diff --git a/src/index.ts b/src/index.ts index 791c872..1c0ed63 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ 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 { registerGracefulShutdown } from './core/shutdown.js'; import { buildServer } from './server.js'; import { startScheduler } from './admin/scheduler.js'; @@ -55,14 +56,12 @@ async function main(): Promise { }, 6 * 60 * 60 * 1000); pruneTimer.unref(); - const shutdown = async (signal: string): Promise => { - app.log.info({ signal }, 'shutting down'); - clearInterval(pruneTimer); - await app.close(); - process.exit(0); - }; - process.on('SIGINT', () => void shutdown('SIGINT')); - process.on('SIGTERM', () => void shutdown('SIGTERM')); + // FEAT-07: bound the drain; `app.close()` also runs the `onClose` hook that stops + // the scheduler and closes the database (flushing the WAL). + registerGracefulShutdown(app, { + timeoutMs: 10_000, + onShutdownStart: () => clearInterval(pruneTimer), + }); } -void main(); \ No newline at end of file +void main(); diff --git a/src/server.ts b/src/server.ts index c06d9cd..8a3ec8d 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,7 +1,7 @@ import Fastify, { type FastifyInstance } from 'fastify'; import fastifyCookie from '@fastify/cookie'; import fastifyStatic from '@fastify/static'; -import { existsSync, mkdirSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'; import { isAbsolute, join, relative, resolve } from 'node:path'; import type { AppContext } from './core/context.js'; import { ApiError } from './util/errors.js'; @@ -42,6 +42,11 @@ export async function buildServer(ctx: AppContext): Promise { wildcard: false, decorateReply: true, index: false, + // The dashboard shell is gated server-side for every path that serves it, so + // `/index.html` must never be answered by the static handler (which has no + // session check). Unknown shell paths fall through to the gated not-found + // handler; `sendSpa` below reads the file after the gate instead. + allowedPath: (pathname: string): boolean => pathname !== '/index.html' && pathname !== '/', }); app.get('/health', async () => ({ @@ -59,9 +64,23 @@ export async function buildServer(ctx: AppContext): Promise { await registerAdminRoutes(app, ctx); const indexHtml = join(webDist, 'index.html'); + // Shell content cache: read once, re-read only when the build changes on disk. + let shellCache: { mtimeMs: number; html: string } | null = null; + const readShell = (): string | null => { + try { + const { mtimeMs } = statSync(indexHtml); + if (!shellCache || shellCache.mtimeMs !== mtimeMs) { + shellCache = { mtimeMs, html: readFileSync(indexHtml, 'utf8') }; + } + return shellCache.html; + } catch { + return null; + } + }; const sendSpa = async (_request: unknown, reply: import('fastify').FastifyReply): Promise => { - if (existsSync(indexHtml)) { - await reply.sendFile('index.html'); + const html = existsSync(indexHtml) ? readShell() : null; + if (html !== null) { + await reply.status(200).type('text/html; charset=utf-8').send(html); return; } await reply diff --git a/tests/admin-auth.test.ts b/tests/admin-auth.test.ts new file mode 100644 index 0000000..6ec62c0 --- /dev/null +++ b/tests/admin-auth.test.ts @@ -0,0 +1,656 @@ +/** + * Route-level coverage for the admin API changes: login brute-force guard + * (FEAT-08), settings validate-then-apply (AD-06), provider SSRF/origin/cooldown + * (AD-01/AD-04/AD-07/GW-15), bulk model writes (AD-05), audit attribution + * (FEAT-05), the SSE stream guards (AD-10), the sync guards (AD-03/FEAT-09) and + * the server-side `/index.html` shell gate. + */ +import { randomUUID } from 'node:crypto'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import http from 'node:http'; +import { once } from 'node:events'; +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'; +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 { registerStatsRoutes } from '../src/admin/stats.js'; +import { + MAX_EVENTS_STREAMS, + acquireEventStream, + activeEventStreamCount, + eventStreamAuthorized, + releaseEventStream, + resetEventStreams, +} from '../src/admin/stats.js'; +import type { AppConfig } from '../src/config.js'; +import 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 { buildServer } from '../src/server.js'; +import type { SessionRow } from '../src/types.js'; +import { testConfig } from './helpers.js'; + +/* ------------------------------------------------------------------ upstream mock */ + +const upstream = vi.hoisted(() => ({ + status: 200, + payload: { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] } as unknown, + calls: [] as Array<{ baseUrl: string; apiKey: string; path: string }>, +})); + +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 body = typeof upstream.payload === 'string' ? upstream.payload : JSON.stringify(upstream.payload); + return { + status: upstream.status, + ok: upstream.status >= 200 && upstream.status < 300, + headers: new Headers({ 'content-type': 'application/json' }), + response: new Response(body, { status: upstream.status, headers: { 'content-type': 'application/json' } }), + dispose: () => {}, + abort: () => {}, + abortReason: null, + }; + }, + }; +}); + +/* ----------------------------------------------------------------------- harness */ + +interface TestApp { + app: FastifyInstance; + ctx: AppContext; + repo: Repo; + handle: DbHandle; + dataDir: string; + /** A valid signed session cookie for direct route calls. */ + cookie(): string; + /** Real `/login` round-trip; returns the cookie header value. */ + login(password?: string): Promise; + request(method: string, url: string, payload?: unknown, cookie?: string): Promise; + json(method: string, url: string, payload?: unknown, cookie?: string): Promise; + close(): Promise; +} + +async function buildAdminApp(configOverrides: Partial = {}): Promise { + const dataDir = mkdtempSync(join(tmpdir(), 'okr-admin-')); + const config: AppConfig = { ...testConfig(dataDir), ...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, + ): Promise => + app.inject({ + method: method as 'GET', + url, + ...(payload === undefined ? {} : { payload: payload as object }), + ...(cookie === undefined ? {} : { headers: { cookie } }), + }); + + 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): Promise { + const response = await request(method, url, payload, cookie); + 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(); + resetEventStreams(); + upstream.status = 200; + upstream.payload = { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] }; + upstream.calls = []; + app = await buildAdminApp(); +}); + +afterEach(async () => { + await app.close(); +}); + +/* ------------------------------------------------------------------------ login */ + +describe('login brute-force guard (FEAT-08)', () => { + it('limits per IP after LOGIN_MAX_ATTEMPTS failures', () => { + for (let index = 0; index < LOGIN_MAX_ATTEMPTS; index += 1) recordLoginFailure('10.0.0.1'); + const hit = checkLoginRateLimit('10.0.0.1'); + expect(hit?.scope).toBe('ip'); + expect(hit?.retryAfterMs).toBeGreaterThan(0); + expect(checkLoginRateLimit('10.0.0.2')).toBeNull(); + }); + + it('limits globally across many IPs', () => { + for (let index = 0; index < LOGIN_GLOBAL_MAX_ATTEMPTS; index += 1) { + recordLoginFailure(`10.0.${Math.floor(index / 250)}.${index % 250}`); + } + const hit = checkLoginRateLimit('198.51.100.7'); + expect(hit?.scope).toBe('global'); + expect(hit?.retryAfterMs).toBeGreaterThan(0); + }); + + it('returns 429 + retry-after from the route and blocks even a correct password', 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); + } + const limited = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(limited.statusCode).toBe(429); + expect(limited.headers['retry-after']).toBeDefined(); + const body = JSON.parse(limited.body) as { error: { code: string; retryAfter: number } }; + expect(body.error.code).toBe('too_many_attempts'); + expect(body.error.retryAfter).toBeGreaterThanOrEqual(1); + expect(Number(limited.headers['retry-after'])).toBe(body.error.retryAfter); + }); + + it('clears the per-IP counter after a successful login', async () => { + for (let index = 0; index < 3; index += 1) { + await app.request('POST', '/admin/api/login', { password: 'wrong' }); + } + expect(checkLoginRateLimit('127.0.0.1')).toBeNull(); + const ok = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(ok.statusCode).toBe(200); + expect(checkLoginRateLimit('127.0.0.1')).toBeNull(); + }); +}); + +/* --------------------------------------------------------------------- settings */ + +describe('PATCH /settings (AD-06, audit_retention_days, stream_idle_timeout_ms)', () => { + it('rejects the whole patch when one value is invalid', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '5', request_timeout_ms: 999 }, cookie); + expect(response.statusCode).toBe(400); + expect(app.repo.getSetting('max_retries')).toBe('3'); + expect(app.repo.getSetting('request_timeout_ms')).toBe('600000'); + }); + + it('applies every valid entry in one transaction and reports ignored keys', async () => { + const cookie = app.cookie(); + const body = await app.json<{ changed: string[]; ignored: string[]; settings: Record }>( + 'PATCH', + '/admin/api/settings', + { max_retries: '5', audit_retention_days: '30', stream_idle_timeout_ms: '60000', nope: '1' }, + cookie, + ); + expect(body.changed.sort()).toEqual(['audit_retention_days', 'max_retries', 'stream_idle_timeout_ms']); + expect(body.ignored).toEqual(['nope']); + expect(app.repo.getSetting('max_retries')).toBe('5'); + expect(app.repo.getSetting('audit_retention_days')).toBe('30'); + expect(app.repo.getSetting('stream_idle_timeout_ms')).toBe('60000'); + expect(body.settings.stream_idle_timeout_ms).toBe('60000'); + }); + + it('validates both new ranges', async () => { + const cookie = app.cookie(); + for (const payload of [ + { audit_retention_days: '0' }, + { audit_retention_days: '3651' }, + { stream_idle_timeout_ms: '999' }, + { stream_idle_timeout_ms: '3600001' }, + ]) { + const response = await app.request('PATCH', '/admin/api/settings', payload, cookie); + expect(response.statusCode, JSON.stringify(payload)).toBe(400); + } + const ok = await app.request('PATCH', '/admin/api/settings', { stream_idle_timeout_ms: '1000' }, cookie); + expect(ok.statusCode).toBe(200); + expect(app.repo.getSetting('stream_idle_timeout_ms')).toBe('1000'); + expect(app.repo.getSetting('audit_retention_days')).toBe('90'); + }); + + it('rejects control characters in upstream_user_agent', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { upstream_user_agent: 'ok\r\nX-Evil: 1' }, cookie); + expect(response.statusCode).toBe(400); + expect(app.repo.getSetting('upstream_user_agent')).toBe('opencode-router/1.0'); + }); +}); + +describe('audit attribution (FEAT-05)', () => { + it('records the session id as actor and the client IP in the detail', async () => { + const cookie = await app.login(); + const patched = await app.request('PATCH', '/admin/api/settings', { max_retries: '4' }, cookie); + expect(patched.statusCode).toBe(200); + const body = await app.json<{ items: Array<{ action: string; actor: string; detail: string | null }> }>( + 'GET', + '/admin/api/audit?limit=20', + undefined, + cookie, + ); + const entry = body.items.find((item) => item.action === 'settings.update'); + expect(entry, 'settings.update audit entry missing').toBeDefined(); + expect(entry!.actor).toMatch(/^session:/); + expect(entry!.detail).toContain('ip=127.0.0.1'); + expect(entry!.detail).toContain('changed=max_retries'); + const login = body.items.find((item) => item.action === 'auth.login'); + expect(login?.actor).toBe('dashboard'); + }); +}); + +/* -------------------------------------------------------------------- providers */ + +describe('providers', () => { + function seedProvider(id = 'p1', baseUrl = 'https://api.example.com/v1'): void { + app.repo.createProvider({ id, name: 'Primary', baseUrl, apiKey: 'stored-secret-key' }); + } + + it('resets a stale cooldown when baseUrl, apiKey or enabled changes (AD-07)', async () => { + seedProvider(); + const cookie = app.cookie(); + + app.repo.recordProviderFailure('p1', 429, 'rate limited', 60_000); + expect(app.repo.getProvider('p1')?.status).toBe('cooldown'); + const patched = await app.request('PATCH', '/admin/api/providers/p1', { apiKey: 'rotated-key' }, cookie); + expect(patched.statusCode).toBe(200); + expect(app.repo.getProvider('p1')?.status).toBe('unknown'); + expect(app.repo.getProvider('p1')?.cooldownUntil).toBeNull(); + + app.repo.recordProviderFailure('p1', 429, 'rate limited', 60_000); + const priority = await app.request('PATCH', '/admin/api/providers/p1', { priority: 5 }, cookie); + expect(priority.statusCode).toBe(200); + expect(app.repo.getProvider('p1')?.status).toBe('cooldown'); + expect(app.repo.getProvider('p1')?.cooldownUntil).toBeGreaterThan(Date.now()); + }); + + it('rejects control characters in name and id (GW-10)', async () => { + const cookie = app.cookie(); + for (const payload of [ + { name: 'bad\r\nname', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, + { name: 'ok', id: 'bad\nid', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }, + ]) { + const response = await app.request('POST', '/admin/api/providers', payload, cookie); + expect(response.statusCode, JSON.stringify(payload)).toBe(400); + } + seedProvider(); + const patch = await app.request('PATCH', '/admin/api/providers/p1', { name: 'x\ry' }, cookie); + expect(patch.statusCode).toBe(400); + }); + + it('never returns the raw provider key (AD-08)', async () => { + seedProvider(); + const body = await app.json<{ providers: Array<{ apiKeyMasked: string }> }>('GET', '/admin/api/providers', undefined, app.cookie()); + expect(JSON.stringify(body)).not.toContain('stored-secret-key'); + expect(body.providers[0]?.apiKeyMasked).toBe('st...ey'); + }); + + it('deletes a provider together with its synced models (AD-02)', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'sync-2', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual' }); + const body = await app.json<{ ok: boolean; modelsRemoved: number }>('DELETE', '/admin/api/providers/p1', undefined, app.cookie()); + expect(body).toEqual({ ok: true, modelsRemoved: 2 }); + expect(app.repo.getProvider('p1')).toBeNull(); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['manual']); + }); + + it('reuses a stored key only for the stored origin (AD-04)', async () => { + seedProvider(); + const cookie = app.cookie(); + + const sameOrigin = await app.json<{ ok: boolean; models: number }>( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://api.example.com/v2' }, + cookie, + ); + expect(sameOrigin.ok).toBe(true); + expect(upstream.calls[0]?.apiKey).toBe('stored-secret-key'); + + upstream.calls = []; + const crossOrigin = await app.request( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://evil.example.com/v1' }, + cookie, + ); + expect(crossOrigin.statusCode).toBe(400); + expect((JSON.parse(crossOrigin.body) as { error: { code: string } }).error.code).toBe('api_key_required'); + expect(upstream.calls).toHaveLength(0); + + const explicit = await app.request( + 'POST', + '/admin/api/providers/test', + { id: 'p1', baseUrl: 'https://evil.example.com/v1', apiKey: 'explicit' }, + cookie, + ); + expect(explicit.statusCode).toBe(200); + expect(upstream.calls[0]?.apiKey).toBe('explicit'); + }); + + it('rejects a stored provider whose URL points at a private host (AD-01/GW-12)', async () => { + app.repo.createProvider({ id: 'legacy', name: 'Legacy', baseUrl: 'http://127.0.0.1:9/v1', apiKey: 'k' }); + const cookie = app.cookie(); + const test = await app.request('POST', '/admin/api/providers/legacy/test', undefined, cookie); + expect(test.statusCode).toBe(400); + const res = await app.request('POST', '/admin/api/providers', { name: 'x', baseUrl: 'https://user:pass@api.example.com/v1', apiKey: 'k' }, cookie); + expect(res.statusCode).toBe(400); + }); +}); + +/* ----------------------------------------------------------------------- models */ + +describe('models', () => { + function seedModels(count: number): string[] { + const ids = Array.from({ length: count }, (_, index) => `m-${index}`); + for (const id of ids) app.repo.upsertModel({ id }); + return ids; + } + + it('applies a bulk action atomically with one statement (AD-05)', async () => { + seedModels(3); + const cookie = app.cookie(); + const disabled = await app.json<{ updated: number }>( + 'POST', + '/admin/api/models/bulk', + { action: 'disable', ids: ['m-0', 'm-1', 'missing'] }, + cookie, + ); + expect(disabled.updated).toBe(2); + expect(app.repo.enabledModelIds()).toEqual(['m-2']); + + const deleted = await app.json<{ updated: number }>( + 'POST', + '/admin/api/models/bulk', + { action: 'delete', ids: ['m-0', 'm-2'] }, + cookie, + ); + expect(deleted.updated).toBe(2); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['m-1']); + }); + + it('rejects more than MAX ids without touching the database', async () => { + // The shared fixture uses a tiny bodyLimit; the cap test needs a realistic one. + const large = await buildAdminApp({ bodyLimit: 4 * 1024 * 1024 }); + try { + for (const id of ['m-0', 'm-1']) large.repo.upsertModel({ id }); + const ids = Array.from({ length: 1_001 }, (_, index) => `m-${index}`); + const response = await large.request('POST', '/admin/api/models/bulk', { action: 'delete', ids }, large.cookie()); + expect(response.statusCode).toBe(400); + expect((JSON.parse(response.body) as { error: { message: string } }).error.message).toContain('at most 1000'); + expect(large.repo.listModels()).toHaveLength(2); + } finally { + await large.close(); + } + }); +}); + +/* ------------------------------------------------------------------ sync guards */ + +describe('model sync (AD-03, FEAT-09)', () => { + it('refuses a private provider URL from both sync entry points', async () => { + app.repo.createProvider({ id: 'private', name: 'Private', baseUrl: 'http://10.0.0.5/v1', apiKey: 'k' }); + const cookie = app.cookie(); + const direct = await app.request('POST', '/admin/api/providers/private/sync-models', undefined, cookie); + expect(direct.statusCode).toBe(400); + expect((JSON.parse(direct.body) as { error: { code: string } }).error.code).toBe('invalid_request'); + const global = await app.request('POST', '/admin/api/models/sync', { providerId: 'private' }, cookie); + expect(global.statusCode).toBe(400); + expect(upstream.calls).toHaveLength(0); + }); + + it('returns a client-safe 502 message instead of upstream internals (FEAT-09)', async () => { + app.repo.createProvider({ id: 'p1', name: 'Primary', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + const cookie = app.cookie(); + upstream.status = 500; + upstream.payload = 'boom: sqlite detail'; + const response = await app.request('POST', '/admin/api/models/sync', { providerId: 'p1' }, cookie); + expect(response.statusCode).toBe(502); + const body = JSON.parse(response.body) as { error: { code: string; message: string } }; + expect(body.error.code).toBe('sync_failed'); + expect(body.error.message).toBe('Upstream request failed while syncing models for provider "Primary"'); + expect(body.error.message).not.toContain('boom'); + expect(body.error.message).not.toContain('api.example.com'); + }); + + it('syncs upstream models and stores the sync timestamp', async () => { + app.repo.createProvider({ id: 'p1', name: 'Primary', baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + const body = await app.json<{ added: number; updated: number; removed: number; total: number }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body).toEqual({ added: 2, updated: 0, removed: 0, total: 2, providerId: 'p1', syncedAt: expect.any(Number), latencyMs: expect.any(Number) }); + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['m1', 'm2']); + }); +}); + +/* ------------------------------------------------------------------------- SSE */ + +describe('SSE stream guards (AD-10)', () => { + it('bounds concurrent streams and releases the slot', () => { + resetEventStreams(); + for (let index = 0; index < MAX_EVENTS_STREAMS; index += 1) { + expect(acquireEventStream()).toBe(true); + } + expect(acquireEventStream()).toBe(false); + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS); + releaseEventStream(); + expect(acquireEventStream()).toBe(true); + resetEventStreams(); + expect(activeEventStreamCount()).toBe(0); + }); + + it('survives a throwing socket write before cleanup is assigned (AD-10 TDZ guard)', async () => { + const handlers = new Map Promise>(); + const scope = { + get: (path: string, handler: (request: unknown, reply: unknown) => Promise) => handlers.set(path, handler), + } as unknown as FastifyInstance; + const noop = (): void => {}; + const ctx = { + repo: { listLogs: () => ({ total: 0, rows: [] }) }, + events: { onRequestStart: () => noop, onRequestEnd: () => noop, onProvider: () => noop }, + } as unknown as AppContext; + registerStatsRoutes(scope, ctx); + const handler = handlers.get('/events'); + expect(handler).toBeDefined(); + + let onClose: (() => void) | undefined; + const raw = { + writeHead: () => {}, + flushHeaders: () => {}, + write: () => { + throw new Error('socket gone'); + }, + once: () => {}, + off: () => {}, + end: () => {}, + }; + const request = { + adminSession: null, + raw: { + on: (event: string, listener: () => void) => { + if (event === 'close') onClose = listener; + }, + }, + }; + const reply = { hijack: () => {}, raw }; + + resetEventStreams(); + // Before the fix this rejected with `TypeError: cleanup is not a function`. + await expect(handler!(request, reply)).resolves.toBeUndefined(); + expect(activeEventStreamCount()).toBe(1); + onClose?.(); + expect(activeEventStreamCount()).toBe(0); + }); + + it('drops authorization when the session row disappears or expires', () => { + const now = Date.now(); + const session: SessionRow = { + id: 's1', + createdAt: now, + expiresAt: now + 60_000, + lastSeenAt: now, + clientIp: null, + userAgent: null, + }; + const live = { repo: { getSession: (id: string) => (id === 's1' ? session : null) } } as unknown as AppContext; + expect(eventStreamAuthorized(live, session)).toBe(true); + expect(eventStreamAuthorized(live, null)).toBe(false); + expect(eventStreamAuthorized(live, { ...session, expiresAt: now - 1 })).toBe(false); + + const revoked = { repo: { getSession: () => null } } as unknown as AppContext; + expect(eventStreamAuthorized(revoked, session)).toBe(false); + }); + + it('answers 503 past the cap and frees the slot on disconnect', async () => { + await app.app.listen({ host: '127.0.0.1', port: 0 }); + const address = app.app.server.address(); + const port = typeof address === 'object' && address ? address.port : 0; + const cookie = app.cookie(); + resetEventStreams(); + for (let index = 0; index < MAX_EVENTS_STREAMS - 1; index += 1) acquireEventStream(); + + const first = http.get({ host: '127.0.0.1', port, path: '/admin/api/events', headers: { cookie } }); + const [firstResponse] = (await once(first, 'response')) as [http.IncomingMessage]; + expect(firstResponse.statusCode).toBe(200); + firstResponse.resume(); + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS); + + const second = await new Promise<{ status: number; body: string }>((resolve, reject) => { + const request = http.get({ host: '127.0.0.1', port, path: '/admin/api/events', headers: { cookie } }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk: string) => { + body += chunk; + }); + response.on('end', () => resolve({ status: response.statusCode ?? 0, body })); + }); + request.on('error', reject); + }); + expect(second.status).toBe(503); + expect((JSON.parse(second.body) as { error: { code: string } }).error.code).toBe('too_many_streams'); + + first.destroy(); + const deadline = Date.now() + 2_000; + while (activeEventStreamCount() > MAX_EVENTS_STREAMS - 1 && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(activeEventStreamCount()).toBe(MAX_EVENTS_STREAMS - 1); + resetEventStreams(); + }); +}); + +/* ------------------------------------------------------------- server shell gate */ + +describe('server dashboard shell gate', () => { + let dataDir: string; + let ctx: AppContext; + let server: FastifyInstance; + + beforeEach(async () => { + dataDir = mkdtempSync(join(tmpdir(), 'okr-shell-')); + const webDist = join(dataDir, 'web'); + mkdirSync(join(webDist, 'assets'), { recursive: true }); + writeFileSync(join(webDist, 'index.html'), 'shell'); + writeFileSync(join(webDist, 'assets', 'app.js'), 'console.log("app")'); + const config = { ...testConfig(dataDir), webDistDir: webDist }; + const handle = openDatabase(config); + ctx = { + config, + db: handle, + repo: new Repo(handle.db), + events: new EventBus(), + logger: null as never, + startedAt: Date.now(), + }; + server = await buildServer(ctx); + }); + + afterEach(async () => { + await server.close(); + ctx.db.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }); + + it('never serves the shell without a session', async () => { + const direct = await server.inject({ method: 'GET', url: '/index.html' }); + expect(direct.statusCode).toBe(302); + expect(direct.headers.location).toBe('/login'); + + const dashboard = await server.inject({ method: 'GET', url: '/dashboard' }); + expect(dashboard.statusCode).toBe(302); + expect(dashboard.headers.location).toBe('/login'); + + const root = await server.inject({ method: 'GET', url: '/' }); + expect(root.statusCode).toBe(302); + expect(root.headers.location).toBe('/dashboard'); + + // The login shell and its assets stay reachable without a session. + const login = await server.inject({ method: 'GET', url: '/login' }); + expect(login.statusCode).toBe(200); + expect(login.body).toContain('id="shell"'); + expect(login.headers['content-type']).toContain('text/html'); + const asset = await server.inject({ method: 'GET', url: '/assets/app.js' }); + expect(asset.statusCode).toBe(200); + }); + + it('serves the shell for a valid session', async () => { + const session = ctx.repo.createSession({ id: randomUUID(), ttlMs: 60_000, clientIp: null, userAgent: null }); + const cookie = `${SESSION_COOKIE}=${buildSessionCookie(ctx.db.secret, session.id, session.expiresAt)}`; + const index = await server.inject({ method: 'GET', url: '/index.html', headers: { cookie } }); + expect(index.statusCode).toBe(200); + expect(index.body).toContain('id="shell"'); + const dashboard = await server.inject({ method: 'GET', url: '/dashboard/overview', headers: { cookie } }); + expect(dashboard.statusCode).toBe(200); + expect(dashboard.body).toContain('id="shell"'); + }); +}); diff --git a/tests/admin-session.test.ts b/tests/admin-session.test.ts index 8fe6dbc..1e530ea 100644 --- a/tests/admin-session.test.ts +++ b/tests/admin-session.test.ts @@ -3,9 +3,12 @@ import { describe, expect, it } from 'vitest'; import { SESSION_COOKIE, buildSessionCookie, + isSecureRequest, parseSessionCookie, resolveSession, + sessionCookieOptions, signSession, + trustProxyEnabled, } from '../src/admin/session.js'; import type { AppContext } from '../src/core/context.js'; import type { SessionRow } from '../src/types.js'; @@ -110,3 +113,52 @@ describe('resolveSession', () => { expect(resolveSession(ctx, requestWith())).toBeNull(); }); }); + +describe('isSecureRequest (AD-09) and trustProxy', () => { + function request(protocol: string, headers: Record = {}): FastifyRequest { + return { protocol, headers } as unknown as FastifyRequest; + } + + function ctxWith(patch: { trustProxy?: boolean | string | string[]; publicUrl?: string | null }): AppContext { + return { config: { ...testConfig('/tmp/okr-session-secure'), ...patch } } as unknown as AppContext; + } + + it('trusts the socket protocol unconditionally', () => { + expect(isSecureRequest(request('https'))).toBe(true); + expect(isSecureRequest(request('http'))).toBe(false); + }); + + it('ignores x-forwarded-proto unless TRUST_PROXY is enabled', () => { + const untrusted = ctxWith({ trustProxy: false }); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }), untrusted)).toBe(false); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }))).toBe(false); + + const trusted = ctxWith({ trustProxy: true }); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https' }), trusted)).toBe(true); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'https, http' }), trusted)).toBe(true); + expect(isSecureRequest(request('http', { 'x-forwarded-proto': 'http' }), trusted)).toBe(false); + }); + + it('honours an https PUBLIC_URL as a TLS-terminating deployment', () => { + expect(isSecureRequest(request('http'), ctxWith({ publicUrl: 'https://router.example.com' }))).toBe(true); + expect(isSecureRequest(request('http'), ctxWith({ publicUrl: 'http://router.example.com' }))).toBe(false); + }); + + it('treats only a configured trustProxy value as enabled', () => { + expect(trustProxyEnabled(undefined)).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: false }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: true }))).toBe(true); + expect(trustProxyEnabled(ctxWith({ trustProxy: '1' }))).toBe(true); + expect(trustProxyEnabled(ctxWith({ trustProxy: '' }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: [] }))).toBe(false); + expect(trustProxyEnabled(ctxWith({ trustProxy: ['10.0.0.1'] }))).toBe(true); + }); + + it('sets the Secure cookie attribute from the same check', () => { + const trusted = ctxWith({ trustProxy: true }); + expect(sessionCookieOptions(trusted, request('http', { 'x-forwarded-proto': 'https' })).secure).toBe(true); + const untrusted = ctxWith({ trustProxy: false }); + expect(sessionCookieOptions(untrusted, request('http', { 'x-forwarded-proto': 'https' })).secure).toBe(false); + expect(sessionCookieOptions(untrusted, request('https')).secure).toBe(true); + }); +}); diff --git a/tests/admin-util.test.ts b/tests/admin-util.test.ts index a52a1f7..0b1ab49 100644 --- a/tests/admin-util.test.ts +++ b/tests/admin-util.test.ts @@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest'; import { HttpError, asTimestamp, + assertNoControlChars, assertPublicProviderUrl, csvEscape, + httpBaseUrl, maskApiKey, queryInt, queryTimestamp, @@ -108,6 +110,13 @@ describe('assertPublicProviderUrl', () => { 'http://169.254.169.254/latest/meta-data', 'http://localhost:20125/v1', 'http://api.localhost/v1', + // AD-01: a trailing dot used to defeat every literal check. + 'http://localhost./v1', + 'http://api.localhost./v1', + 'http://127.0.0.1./v1', + 'http://10.0.0.5./v1', + 'http://192.168.1.1./v1', + 'http://169.254.169.254./latest/meta-data', 'http://[::ffff:127.0.0.1]/v1', 'http://[::ffff:7f00:1]/v1', 'http://[fc00::1]/v1', @@ -148,7 +157,46 @@ describe('maskApiKey', () => { expect(maskApiKey('')).toBe(''); expect(maskApiKey('short')).toBe('****'); expect(maskApiKey('12345678')).toBe('****'); - expect(maskApiKey('sk-abcdefghijkl')).toBe('sk-a...ijkl'); + expect(maskApiKey('sk-abcdefghijkl')).toBe('sk...kl'); expect(maskApiKey('sk-abcdefghijkl')).not.toContain('bcdefgh'); }); + + // AD-08: `sk-123456` (9 chars) used to reveal 8 of its 9 characters. + it('reveals at most 4 characters and fully masks anything below 12', () => { + expect(maskApiKey('sk-123456')).toBe('****'); + expect(maskApiKey('a'.repeat(11))).toBe('****'); + expect(maskApiKey('a'.repeat(12))).toBe('aa...aa'); + const masked = maskApiKey('sk-abcdefghijkl'); + expect(masked.replace(/[^a-z0-9]/gi, '')).toHaveLength(4); + expect(masked).toBe('sk...kl'); + }); +}); + +describe('httpBaseUrl', () => { + it('accepts http(s) URLs without credentials and strips trailing slashes', () => { + expect(httpBaseUrl('https://api.openai.com/v1/')).toBe('https://api.openai.com/v1'); + expect(httpBaseUrl('http://8.8.8.8:8080/v1')).toBe('http://8.8.8.8:8080/v1'); + }); + + it('rejects non-http schemes, junk and control characters', () => { + expect(() => httpBaseUrl('ftp://api.openai.com/v1')).toThrow(HttpError); + expect(() => httpBaseUrl('not a url')).toThrow(HttpError); + expect(() => httpBaseUrl('https://api.openai.com/v1\r\nX-Evil: 1')).toThrow(HttpError); + expect(() => httpBaseUrl(123)).toThrow(HttpError); + }); + + // GW-12: credentials in the URL would be echoed back in upstream error messages. + it('rejects userinfo in the URL', () => { + expect(() => httpBaseUrl('https://user:pass@api.openai.com/v1')).toThrow(HttpError); + expect(() => httpBaseUrl('https://user@api.openai.com/v1')).toThrow(HttpError); + }); +}); + +describe('assertNoControlChars', () => { + it('accepts printable values and rejects CR/LF and NUL', () => { + expect(() => assertNoControlChars('openrouter/1.0 (linux)', 'upstream_user_agent')).not.toThrow(); + for (const value of ['a\r', 'a\n', 'a\r\nb', 'a\u0000b', 'a\u007fb']) { + expect(() => assertNoControlChars(value, 'name'), JSON.stringify(value)).toThrow(HttpError); + } + }); }); \ No newline at end of file diff --git a/tests/db-repos.test.ts b/tests/db-repos.test.ts index d389fc2..1e02eae 100644 --- a/tests/db-repos.test.ts +++ b/tests/db-repos.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import type { AttemptRow, RequestLogRow } from '../src/types.js'; +import { Repo } from '../src/db/repos.js'; import { createTestDb, type TestDb } from './helpers.js'; let db: TestDb; @@ -149,3 +150,223 @@ describe('repo: api key rotation', () => { expect(db.repo.rotateApiKey('missing', replacement)).toBeNull(); }); }); + +describe('repo: prepared-statement cache (OPT-01)', () => { + it('prepares each distinct SQL string once', () => { + const db2 = createTestDb('okr-cache-'); + try { + const original = db2.handle.db.prepare.bind(db2.handle.db); + let prepares = 0; + (db2.handle.db as unknown as { prepare: (sql: string) => unknown }).prepare = (sql: string) => { + prepares += 1; + return original(sql); + }; + const repo = new Repo(db2.handle.db); + repo.insertLog(makeLog({ id: 'c1' })); + repo.insertLog(makeLog({ id: 'c2' })); + expect(prepares).toBe(1); + repo.insertLog(makeLog({ id: 'c3' })); + expect(prepares).toBe(1); + // A different statement still gets prepared (and cached) on first use. + repo.getLog('c1'); + expect(prepares).toBe(2); + repo.getLog('c2'); + expect(prepares).toBe(2); + } finally { + db2.cleanup(); + } + }); +}); + +describe('repo: transactions', () => { + it('rolls back every statement when the body throws', () => { + expect(() => + db.repo.transaction(() => { + db.repo.createProvider({ id: 'p1', name: 'P1', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.upsertModel({ id: 'm1' }); + throw new Error('boom'); + }), + ).toThrow('boom'); + expect(db.repo.listProviders()).toHaveLength(0); + expect(db.repo.listModels()).toHaveLength(0); + }); + + it('joins an outer transaction instead of opening a nested one', () => { + const result = db.repo.transaction(() => { + db.repo.upsertModel({ id: 'outer' }); + return db.repo.transaction(() => { + db.repo.upsertModel({ id: 'inner' }); + return 'done'; + }); + }); + expect(result).toBe('done'); + expect(db.repo.listModels().map((model) => model.id).sort()).toEqual(['inner', 'outer']); + }); +}); + +describe('repo: bulk model writes (AD-05)', () => { + it('updates and deletes in one set-based statement', () => { + db.repo.upsertModel({ id: 'a' }); + db.repo.upsertModel({ id: 'b' }); + db.repo.upsertModel({ id: 'c' }); + + expect(db.repo.setModelsEnabled(['a', 'b', 'missing'], false)).toBe(2); + expect(db.repo.enabledModelIds()).toEqual(['c']); + expect(db.repo.setModelsEnabled(['a', 'c'], true)).toBe(2); + expect(db.repo.enabledModelIds().sort()).toEqual(['a', 'c']); + + expect(db.repo.deleteModels(['a', 'nope'])).toBe(1); + expect(db.repo.setModelsEnabled([], false)).toBe(0); + expect(db.repo.deleteModels([])).toBe(0); + }); +}); + +describe('repo: provider delete cascade (AD-02)', () => { + it('removes the provider and its models together', () => { + db.repo.createProvider({ id: 'p1', name: 'P1', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.createProvider({ id: 'p2', name: 'P2', baseUrl: 'http://y/v1', apiKey: 'k' }); + db.repo.upsertModel({ id: 'owned-1', providerId: 'p1', source: 'sync' }); + db.repo.upsertModel({ id: 'owned-2', providerId: 'p1', source: 'sync' }); + db.repo.upsertModel({ id: 'other', providerId: 'p2', source: 'sync' }); + db.repo.upsertModel({ id: 'manual' }); + + expect(db.repo.deleteProviderWithModels('p1')).toEqual({ deleted: true, modelsRemoved: 2 }); + expect(db.repo.getProvider('p1')).toBeNull(); + expect(db.repo.listModels().map((model) => model.id).sort()).toEqual(['manual', 'other']); + expect(db.repo.deleteModelsByProvider('p1')).toBe(0); + }); +}); + +describe('repo: provider failure cooldown (GW-15)', () => { + const cooled = [null, 302, 408, 409, 425, 429, 500, 503, 529]; + const notCooled = [400, 401, 403, 404, 422]; + + it('cools down retryable failures, including network errors and redirects', () => { + for (const [index, status] of cooled.entries()) { + const id = `cool-${index}`; + db.repo.createProvider({ id, name: id, baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure(id, status, 'nope', 60_000); + const row = db.repo.getProvider(id)!; + expect(row.cooldownUntil, `status=${status}`).toBeGreaterThan(Date.now()); + expect(row.failureCount).toBe(1); + } + }); + + it('leaves client errors without a cooldown', () => { + for (const [index, status] of notCooled.entries()) { + const id = `hard-${index}`; + db.repo.createProvider({ id, name: id, baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure(id, status, 'nope', 60_000); + const row = db.repo.getProvider(id)!; + expect(row.cooldownUntil, `status=${status}`).toBeNull(); + expect(row.status).toBe('error'); + } + }); + + it('keeps the cooldown status only for rate-limit style failures', () => { + db.repo.createProvider({ id: 'rl', name: 'rl', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('rl', 429, 'slow down', 60_000); + expect(db.repo.getProvider('rl')?.status).toBe('cooldown'); + + db.repo.createProvider({ id: 'net', name: 'net', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('net', null, 'unreachable', 60_000); + expect(db.repo.getProvider('net')?.status).toBe('error'); + expect(db.repo.getProvider('net')?.cooldownUntil).toBeGreaterThan(Date.now()); + }); +}); + +describe('repo: upsert with a known row (OPT-10)', () => { + it('does not re-read the row and reports the same shape as before', () => { + const created = db.repo.upsertModel({ id: 'a/model', name: 'A', capabilities: undefined }); + expect(created.created).toBe(true); + expect(created.row.name).toBe('A'); + expect(created.row.enabled).toBe(true); + expect(db.repo.getModel('a/model')).toEqual(created.row); + + const known = db.repo.getModel('a/model'); + const updated = db.repo.upsertModel({ id: 'a/model', name: 'A v2', enabled: false }, known); + expect(updated.created).toBe(false); + expect(updated.row.name).toBe('A v2'); + expect(updated.row.enabled).toBe(false); + expect(db.repo.getModel('a/model')).toEqual(updated.row); + + // `known: null` claims "does not exist yet" and must not fall back to a read. + const missing = db.repo.upsertModel({ id: 'b/model', name: 'B' }, null); + expect(missing.created).toBe(true); + expect(db.repo.getModel('b/model')?.name).toBe('B'); + }); +}); + +describe('repo: stats percentiles (OPT-03)', () => { + const reference = (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) * sorted.length))] ?? 0; + }; + + it('matches the nearest-rank definition and ignores null latencies', () => { + const empty = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(empty.totals.p50LatencyMs).toBe(0); + expect(empty.totals.p95LatencyMs).toBe(0); + + const latencies: Array = [1, 7, 3, null, 99, 42, 5, 13, 8, 21]; + latencies.forEach((latency, index) => { + db.repo.insertLog(makeLog({ id: `p${index}`, latencyMs: latency, ts: Date.now() - 1_000 })); + }); + const present = latencies.filter((value): value is number => value !== null); + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(reference(present, 50)); + expect(stats.totals.p95LatencyMs).toBe(reference(present, 95)); + expect(stats.totals.p50LatencyMs).toBe(8); + expect(stats.totals.p95LatencyMs).toBe(99); + }); + + it('is stable for single-row and off-window data', () => { + db.repo.insertLog(makeLog({ id: 'only', latencyMs: 250, ts: Date.now() - 1_000 })); + db.repo.insertLog(makeLog({ id: 'old', latencyMs: 9_000, ts: Date.now() - 90 * 24 * 60 * 60 * 1000 })); + const stats = db.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(250); + expect(stats.totals.p95LatencyMs).toBe(250); + expect(stats.totals.requests).toBe(1); + }); +}); + +describe('repo: schema indexes (OPT-02)', () => { + it('creates an index for every hot predicate', () => { + const names = new Set( + (db.handle.db.prepare("SELECT name FROM sqlite_master WHERE type = 'index'").all() as Array<{ name: string }>).map( + (row) => row.name, + ), + ); + for (const index of [ + 'idx_sessions_expires', + 'idx_models_enabled', + 'idx_models_provider', + 'idx_api_keys_active', + 'idx_providers_enabled', + 'idx_request_logs_ts_ok', + ]) { + expect(names.has(index), index).toBe(true); + } + }); +}); + +describe('repo: hot-path existence helpers (OPT-04)', () => { + it('keeps hasEnabledModel/countActiveApiKeys consistent with the row lists', () => { + expect(db.repo.hasEnabledModel()).toBe(false); + expect(db.repo.countActiveApiKeys()).toBe(0); + db.repo.upsertModel({ id: 'm1' }); + const { row } = db.repo.createApiKey('laptop'); + expect(db.repo.hasEnabledModel()).toBe(true); + expect(db.repo.hasEnabledModel()).toBe(db.repo.enabledModelIds().length > 0); + expect(db.repo.countActiveApiKeys()).toBe(1); + expect(db.repo.hasActiveApiKey()).toBe(true); + + db.repo.updateApiKey(row.id, { revoked: true, enabled: false }); + expect(db.repo.countActiveApiKeys()).toBe(0); + expect(db.repo.hasActiveApiKey()).toBe(false); + + db.repo.updateModel('m1', { enabled: false }); + expect(db.repo.hasEnabledModel()).toBe(false); + }); +}); diff --git a/tests/unit.test.ts b/tests/unit.test.ts index 38ea6f6..0350890 100644 --- a/tests/unit.test.ts +++ b/tests/unit.test.ts @@ -1,7 +1,11 @@ +import { EventEmitter } from 'node:events'; import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { pruneLogs } from '../src/core/seed.js'; +import { registerGracefulShutdown, type ShutdownHost } from '../src/core/shutdown.js'; +import type { AppContext } from '../src/core/context.js'; import { openDatabase, type DbHandle } from '../src/db/index.js'; import { Repo } from '../src/db/repos.js'; import { generateApiKey, hashApiKey, hashPassword, hmacSign, verifyPassword } from '../src/util/crypto.js'; @@ -334,3 +338,143 @@ describe('errors', () => { expect(error.toJSON('messages')).toMatchObject({ type: 'error', error: { type: 'invalid_request_error', message: 'bad' } }); }); }); + +describe('pruneLogs retention (FEAT-05)', () => { + const DAY = 24 * 60 * 60 * 1000; + + function auditRow(id: string, ts: number): void { + handle.db.prepare('INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES (?, ?, ?, ?, ?, ?)').run( + id, + ts, + 'dashboard', + 'test.action', + null, + null, + ); + } + + function ctx(): AppContext { + return { repo } as unknown as AppContext; + } + + it('keeps audit rows on their own retention window', () => { + repo.setSetting('log_retention_days', '1'); + auditRow('old-2d', Date.now() - 2 * DAY); + auditRow('fresh', Date.now()); + const removed = pruneLogs(ctx()); + expect(removed).toBe(0); + expect(repo.listAudit(10).map((item) => item.id).sort()).toEqual(['fresh', 'old-2d']); + }); + + it('prunes audit rows past audit_retention_days and request logs past log_retention_days', () => { + repo.setSetting('log_retention_days', '1'); + repo.setSetting('audit_retention_days', '1'); + auditRow('stale-audit', Date.now() - 2 * DAY); + auditRow('fresh-audit', Date.now()); + repo.insertLog({ + id: 'stale-log', + ts: Date.now() - 2 * DAY, + keyId: null, + keyName: null, + providerId: null, + providerName: null, + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 1, + ttfbMs: 1, + inputTokens: 0, + outputTokens: 0, + totalTokens: 0, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: null, + userAgent: null, + }); + + expect(pruneLogs(ctx())).toBe(1); + expect(repo.listAudit(10).map((item) => item.id)).toEqual(['fresh-audit']); + expect(repo.listLogs({ limit: 10 }).total).toBe(0); + }); +}); + +describe('graceful shutdown (FEAT-07)', () => { + function makeHost(close: () => Promise): { host: ShutdownHost; forced: number[] } { + const forced: number[] = []; + const host = { + close, + server: { closeAllConnections: () => forced.push(Date.now()) }, + log: { info: () => {}, warn: () => {}, error: () => {} }, + } as unknown as ShutdownHost; + return { host, forced }; + } + + it('drains in-flight requests and exits 0', async () => { + let closed = 0; + const { host } = makeHost(async () => { + closed += 1; + }); + const exits: number[] = []; + const started: string[] = []; + const controller = registerGracefulShutdown(host, { + signals: new EventEmitter(), + exit: (code) => exits.push(code), + onShutdownStart: () => started.push('start'), + }); + await controller.shutdown('SIGTERM'); + expect(closed).toBe(1); + expect(started).toEqual(['start']); + expect(exits).toEqual([0]); + expect(controller.started).toBe(true); + }); + + it('force-closes connections after the drain timeout, then closes', async () => { + vi.useFakeTimers(); + try { + let release!: () => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const { host, forced } = makeHost(() => pending); + const exits: number[] = []; + const controller = registerGracefulShutdown(host, { + timeoutMs: 1_000, + signals: new EventEmitter(), + exit: (code) => exits.push(code), + }); + + const running = controller.shutdown('SIGINT'); + await vi.advanceTimersByTimeAsync(1_000); + expect(forced).toHaveLength(1); + expect(exits).toEqual([]); + + release(); + await running; + expect(exits).toEqual([0]); + } finally { + vi.useRealTimers(); + } + }); + + it('reports a failed close and runs only once per process', async () => { + const signals = new EventEmitter(); + let closes = 0; + const { host } = makeHost(async () => { + closes += 1; + throw new Error('close failed'); + }); + const exits: number[] = []; + registerGracefulShutdown(host, { signals, exit: (code) => exits.push(code) }); + + signals.emit('SIGINT'); + signals.emit('SIGTERM'); + await new Promise((resolve) => setImmediate(resolve)); + expect(closes).toBe(1); + expect(exits).toEqual([1]); + }); +}); From 14dba6827a526a5b3ed4abf4e3454310e23cac8d 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 20:19:16 +0700 Subject: [PATCH 3/5] feat(web): add key rotation, log filters and safer dashboard state --- web/index.html | 16 +- web/src/components/SetupBanner.tsx | 7 +- web/src/components/layout/Sidebar.tsx | 8 +- web/src/components/layout/Topbar.tsx | 27 ++- web/src/components/ui/Button.tsx | 5 +- web/src/components/ui/Input.tsx | 28 ++- web/src/components/ui/misc.tsx | 10 +- web/src/lib/api.ts | 95 +++++++++- web/src/lib/format.ts | 19 +- web/src/lib/hooks.ts | 51 +++++- web/src/lib/readiness.tsx | 42 +++-- web/src/lib/realtime.ts | 42 ++++- web/src/lib/theme.ts | 47 +++-- web/src/lib/types.ts | 62 +++++-- web/src/lib/useDialogFocus.ts | 31 ++++ web/src/pages/Keys.tsx | 45 ++++- web/src/pages/Logs.tsx | 120 +++++++++++-- web/src/pages/Models.tsx | 58 +++++- web/src/pages/Overview.tsx | 80 +++++++-- web/src/pages/Settings.tsx | 246 +++++++++++++++++++++++--- web/src/styles.css | 7 + 21 files changed, 877 insertions(+), 169 deletions(-) diff --git a/web/index.html b/web/index.html index 78e93cd..ecc0b72 100644 --- a/web/index.html +++ b/web/index.html @@ -9,14 +9,22 @@ OpenCode Router diff --git a/web/src/components/SetupBanner.tsx b/web/src/components/SetupBanner.tsx index 2a9775b..80b5ae3 100644 --- a/web/src/components/SetupBanner.tsx +++ b/web/src/components/SetupBanner.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { Link } from 'react-router-dom'; import { ArrowUpRight, Check, ShieldCheck, Sparkles, TriangleAlert } from 'lucide-react'; import { setupSteps, useReadiness, type SetupStep } from '../lib/readiness'; @@ -83,7 +83,7 @@ export function ReadinessChecklist({ } /** Prominent "Setup needed" banner shown on every dashboard page until the gateway is ready. */ -export function SetupBanner({ onNavigate }: { onNavigate?: () => void }): ReactNode { +function SetupBannerBase({ onNavigate }: { onNavigate?: () => void }): ReactNode { const { bootstrap, loading } = useReadiness(); if (loading || !bootstrap || bootstrap.gatewayReady) return null; @@ -124,6 +124,9 @@ export function SetupBanner({ onNavigate }: { onNavigate?: () => void }): ReactN ); } +/** Renders on every page: memo so it only re-renders when readiness actually changes. */ +export const SetupBanner = memo(SetupBannerBase); + /** Small ready-state counterpart used at the top of the Overview page. */ export function ReadyBanner(): ReactNode { const { bootstrap } = useReadiness(); diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 0ce60b4..81b15fb 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -1,4 +1,4 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { NavLink, Link } from 'react-router-dom'; import { X, Zap } from 'lucide-react'; import { NAV_ITEMS } from './nav'; @@ -28,7 +28,7 @@ function BrandMark(): ReactNode { ); } -export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }): ReactNode { +function SidebarBase({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }): ReactNode { const { bootstrap } = useReadiness(); const steps = setupSteps(bootstrap); const ready = Boolean(bootstrap?.gatewayReady); @@ -114,4 +114,6 @@ export function Sidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: ) : null} ); -} \ No newline at end of file +} +/** Always-mounted navigation: memo keeps it out of page-level re-render cascades. */ +export const Sidebar = memo(SidebarBase); diff --git a/web/src/components/layout/Topbar.tsx b/web/src/components/layout/Topbar.tsx index 5d286c3..07fc7ff 100644 --- a/web/src/components/layout/Topbar.tsx +++ b/web/src/components/layout/Topbar.tsx @@ -1,20 +1,22 @@ -import type { ReactNode } from 'react'; +import { memo, type ReactNode } from 'react'; import { Link, useLocation, useNavigate } from 'react-router-dom'; import { LogOut, Menu, ShieldCheck } from 'lucide-react'; import { navItemForPath } from './nav'; import { ThemeToggle } from './ThemeToggle'; import { LiveIndicator } from './LiveIndicator'; import { IconButton } from '../ui/Button'; -import { useReadiness } from '../../lib/readiness'; +import { useReadiness, useRealtimeState } from '../../lib/readiness'; import { useAuth } from '../../lib/auth'; import { useToast } from '../ui/Toast'; +import { extractErrorMessage } from '../../lib/api'; -export function Topbar({ onOpenMobile }: { onOpenMobile: () => void }): ReactNode { +function TopbarBase({ onOpenMobile }: { onOpenMobile: () => void }): ReactNode { const location = useLocation(); const navigate = useNavigate(); const toast = useToast(); const { logout } = useAuth(); - const { bootstrap, realtime } = useReadiness(); + const { bootstrap } = useReadiness(); + const realtime = useRealtimeState(); const item = navItemForPath(location.pathname); const ready = Boolean(bootstrap?.gatewayReady); @@ -65,13 +67,20 @@ export function Topbar({ onOpenMobile }: { onOpenMobile: () => void }): ReactNod label="Sign out" icon={} onClick={() => { - void logout().then(() => { - toast.info('Signed out', 'Your dashboard session was cleared.'); - navigate('/login', { replace: true }); - }); + // A failed /logout must not trap the operator in the dashboard: the local + // session state is cleared in the auth layer regardless, so navigate anyway. + void logout() + .then(() => toast.info('Signed out', 'Your dashboard session was cleared.')) + .catch((cause: unknown) => { + toast.error('Sign out failed', extractErrorMessage(cause)); + }) + .finally(() => navigate('/login', { replace: true })); }} /> ); -} \ No newline at end of file +} + +/** Always-mounted shell chrome: memo keeps it out of page-level re-render cascades. */ +export const Topbar = memo(TopbarBase); \ No newline at end of file diff --git a/web/src/components/ui/Button.tsx b/web/src/components/ui/Button.tsx index 8fbf27a..e8679a5 100644 --- a/web/src/components/ui/Button.tsx +++ b/web/src/components/ui/Button.tsx @@ -35,7 +35,7 @@ export function Button({ -