diff --git a/.env.example b/.env.example index 5e66783..8279a33 100644 --- a/.env.example +++ b/.env.example @@ -137,7 +137,10 @@ PORT=20123 # Permission ruleset applied to every API session, as a JSON array. Unset means # the OpenCode default (build agent prompts/denies per its own policy). -# OPENCODE_AGENT_PERMISSIONS=[{"action":"*","resource":"*","effect":"allow"}] +# Deny first, then fall back to `ask`: an `allow` catch-all would grant the agent +# unrestricted tool access, so the built-in shell/web tools stay denied and +# everything else asks. +# OPENCODE_AGENT_PERMISSIONS=[{"action":"bash","resource":"*","effect":"deny"},{"action":"webfetch","resource":"*","effect":"deny"},{"action":"websearch","resource":"*","effect":"deny"},{"action":"*","resource":"*","effect":"ask"}] # --------------------------------------------------------------------------- # Gateway state, sticky sessions and model cache diff --git a/README.md b/README.md index b73a8ef..0c5197e 100644 --- a/README.md +++ b/README.md @@ -522,8 +522,9 @@ Every variable, with types, defaults and security notes: defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true` is set **and** no `OPENCODE_METRICS_TOKEN` is configured: a configured token is always required, even when the endpoint is public, so a general API key is never handed to a - scraper. `/metrics` is - never rate limited, so a local scraper cannot be throttled by its own traffic. + scraper. `/metrics` is charged to the same rate-limit bucket as the API routes, + so an anonymous scraper cannot walk every collector without limit; only the + liveness probes and `OPTIONS` stay exempt. * **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog counts, session count), `/admin/config` (effective configuration with API keys and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions` diff --git a/docs/API.md b/docs/API.md index 7c8269c..5e85a67 100644 --- a/docs/API.md +++ b/docs/API.md @@ -235,7 +235,7 @@ data: {"error":{"message":"The upstream completion ended with an error.","type": | `403` | `invalid_request_error` | `permission_error` | | `404` | `invalid_request_error` | `model_not_found` | | `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error`, `rate_limit_exceeded` (the gateway's own limiter; with `retry-after` header, in seconds; mid-stream the hint travels as `retry_after_ms` in the error frame instead) | -| `499` | — | client disconnected before the response started | +| `499` | `api_error` | `timeout_error` — client disconnected before the response started | | `501` | `invalid_request_error` | `not_implemented_error` | | `502` | `api_error` | `upstream_error`, `upstream_invalid_json` | | `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `upstream_unauthorized` (the upstream answered `401`/`403`: check `OPENCODE_SERVER_PASSWORD`), `event_stream_unavailable`, `event_stream_lost` (a mid-turn event-stream reconnect; the answer would have been incomplete) | @@ -958,9 +958,11 @@ When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charge against a per-key token bucket (with a separate bucket for `/admin/*`). A rejected request answers `429` with `error.code: "rate_limit_exceeded"` and a `retry-after` header in seconds. Failed authentication has its own always-on -bucket (at least 60 attempts per minute per client address) and also answers -`429` once it is spent. `/health`, `/ready`, `/healthz`, `/metrics` and `/` -are never rate limited. +bucket (at least 60 attempts per minute per client address) plus a much higher +global ceiling over every address, and also answers `429` once either is spent. +`/health`, `/ready`, `/healthz` and `/` are never rate limited; `/metrics` is +charged to the same bucket as any other route, so an anonymous scrape loop is +throttled too. `OPENCODE_BODY_TIMEOUT_MS` bounds how long a caller may take to send the request body; a request that never finishes is disconnected. It does not apply to a diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 33a33e3..23b496a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -24,10 +24,10 @@ variable. (Discovery and the spawned CLI read the variables listed in | `HOST` | string | `127.0.0.1` | Interface the gateway binds. | Anything other than a loopback address exposes the API (and the OpenCode agent) to the network. Set `0.0.0.0` only inside a container or behind a proxy. | | `PORT` | integer 1–65535 | `20123` | TCP port to listen on. | — | | `OPENCODE_MAX_BODY_BYTES` | integer ≥ 1024 | `67108864` (64 MiB) | Maximum request body size. | Raising it widens the memory-exhaustion surface; base64 media inflates bodies by ~33%. | -| `OPENCODE_TRUST_PROXY` | `true`-like, `false`-like, a positive hop count, or a CSV list of trusted IPs/CIDRs | `false` | Trust `x-forwarded-*` headers for the client address. `true`/`yes`/`on`/`enabled` trusts every hop; `false`/`no`/`off`/`disabled`/`0` trusts nothing; a positive integer is a hop count (`1` trusts the immediate peer only, `2` the last two, …) and is compiled into Fastify's function form; `10.0.0.0/8,127.0.0.1` trusts only those peers. An unrecognised value warns (without echoing it) and falls back to `false`. | Enable only when a proxy you control terminates the connection and overwrites the forwarded headers; otherwise clients can spoof their address in logs, metrics **and the per-address rate-limit bucket**, which makes the anonymous limiter ineffective. Prefer a hop count or a CIDR list over a bare `true`: with `true` the leftmost `x-forwarded-for` entry is trusted even when a client prepended one. | +| `OPENCODE_TRUST_PROXY` | `true`-like, `false`-like, a positive hop count, or a CSV list of trusted IPs/CIDRs | `false` | Trust `x-forwarded-*` headers for the client address. `true`/`yes`/`on`/`enabled` trusts every hop; `false`/`no`/`off`/`disabled`/`0` trusts nothing; a positive integer is a hop count (`1` trusts the immediate peer only, `2` the last two, …) and is compiled into Fastify's function form; `10.0.0.0/8,127.0.0.1` trusts only those peers. An unrecognised value — including a CIDR with a `/0` prefix, which would trust every peer — warns (without echoing it) and falls back to `false`. | Enable only when a proxy you control terminates the connection and overwrites the forwarded headers; otherwise clients can spoof their address in logs, metrics **and the per-address rate-limit bucket**, which makes the anonymous limiter ineffective. Prefer a hop count or a CIDR list over a bare `true`: with `true` the leftmost `x-forwarded-for` entry is trusted even when a client prepended one. | | `OPENCODE_BODY_TIMEOUT_MS` | integer ≥ 1000 | `300000` (5 min) | Wall-clock budget for receiving one request body. A caller that opens a connection and never finishes sending is disconnected when it expires. Only body receipt is bounded; a `stream: true` response is never cut short by it. | Bounds how long a caller can hold a connection and its body buffers (`OPENCODE_MAX_BODY_BYTES` each) without completing a request. Lower it if your clients never upload large media. | | `OPENCODE_CORS_ORIGINS` | CSV list | *(empty)* | Allowed browser origins; `*` allows all. An allowed origin receives `access-control-allow-headers` covering this gateway's headers plus the ones the official OpenAI and Anthropic SDKs send (`openai-organization`, `openai-project`, `x-stainless-*`, `anthropic-dangerous-direct-browser-access`), and `access-control-expose-headers: x-request-id`. | `*` lets any web page call the gateway with a user's key. Prefer an explicit list. | -| `OPENCODE_RATE_LIMIT_RPM` | integer ≥ 0 | `0` | Sustained requests per minute allowed per authenticated API key; `0` disables this limiter. `/admin/*` uses its own separate bucket. Failed authentication is throttled by a third bucket that is always active (at least 60 failed attempts per minute per client address), independently of this variable. | Bounds how many paid upstream turns one key can trigger. A rejected request answers `429 rate_limit_error` (`code: rate_limit_exceeded`) with a `retry-after` header. | +| `OPENCODE_RATE_LIMIT_RPM` | integer ≥ 0 | `0` | Sustained requests per minute allowed per authenticated API key; `0` disables this limiter. `/admin/*` uses its own separate bucket, and `/metrics` is charged to the per-key bucket like any other route. Failed authentication is throttled by a bucket that is always active (at least 60 failed attempts per minute per client address) plus a much higher global ceiling over all addresses, independently of this variable. | Bounds how many paid upstream turns one key can trigger. A rejected request answers `429 rate_limit_error` (`code: rate_limit_exceeded`) with a `retry-after` header. | | `OPENCODE_RATE_LIMIT_BURST` | integer ≥ 0 | `0` | Token-bucket capacity per API key; `0` derives `max(1, ceil(rpm / 6))`. Ignored when `OPENCODE_RATE_LIMIT_RPM=0`. | A large burst allows that many concurrent turns per key before throttling starts. | ## Authentication @@ -42,10 +42,19 @@ variable. (Discovery and the spawned CLI read the variables listed in | `OPENCODE_METRICS_TOKEN` | string | *(unset)* | Dedicated scrape credential for `GET /metrics`, compared in constant time before the `OPENCODE_METRICS_PUBLIC` bypass. When set, `/metrics` requires it even if `OPENCODE_METRICS_PUBLIC=true`; a valid general API key is still accepted. | Lets a Prometheus scraper read metrics without handing it a general-purpose key. Prefer it over making the endpoint public. | Keys are presented as `Authorization: Bearer `, `x-api-key: `, -`Authorization: Basic ` (key as the username). A bare value with no -scheme (`Authorization: `) is **not** accepted. Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs end up in access logs. +`Authorization: Basic ` (key as the username, empty password). A +bare value with no scheme (`Authorization: `) is **not** accepted, and +neither is a Basic value that carries a password or omits the colon. Query-string +keys (`?api_key=`) are deliberately **not** supported because request URLs end up +in access logs. Failed authentication is throttled per client address (at least 60 attempts per -minute) and logged at `warn` without the presented value. +minute) and by a much higher global ceiling over all addresses, and logged at +`warn` without the presented value. Because the per-address bucket is keyed on +`request.ip`, a deployment behind a reverse proxy with the default +`OPENCODE_TRUST_PROXY=false` resolves every caller to the proxy address: set +`OPENCODE_TRUST_PROXY` to a hop count or a CIDR list (see "HTTP server") so the +bucket is per caller rather than shared, and so the global ceiling is not what +answers `429` for legitimate clients. `GET /`, `GET /health`, `GET /ready` and `GET /healthz` are always public. `pnpm setup` writes `.env` (keeping `sk-dummy-123`); `pnpm setup -- --random` writes @@ -112,24 +121,30 @@ section "Vision and media input". | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_REASONING_DEFAULT` | `off` \| `on-request` \| `always` | `on-request` | Server-wide policy for thinking effort. Unrecognised values fall back to `on-request`. | `always` selects a thinking variant even when the caller did not ask, raising cost and latency. | +| `OPENCODE_REASONING_DEFAULT` | `off` \| `on-request` \| `always` | `on-request` | Server-wide policy for thinking effort. Unrecognised values fall back to `on-request` and log a warning naming the variable. | `always` selects a thinking variant even when the caller did not ask, raising cost and latency. | | `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` | boolean | `true` | When a request declares client tools, add `deny` permission rules for OpenCode's built-in actions (`bash`, `webfetch`, `websearch`, `edit`, `write`, `patch`, `task`, `skill`) so the model emits a bridged tool call instead of running its own tools. | **Keep `true`.** Setting it to `false` lets a request that declares any tool also drive the agent's shell, web and file tools. The deny rules are merged on top of `OPENCODE_AGENT_PERMISSIONS` for that session only. | | `OPENCODE_EXPOSE_NATIVE_TOOLS` | boolean | `false` | Stream native OpenCode tool activity as SSE events (see `OPENCODE_NATIVE_TOOL_EVENT`). | Native tool payloads can reveal file paths and command input/output from the agent's workspace. | | `OPENCODE_NATIVE_TOOL_EVENT` | string | `opencode.tool_call` | SSE event name used for native tool activity. | — | | `OPENCODE_REASONING_FIELD` | `reasoning_content` \| `both` | `reasoning_content` | `POST /v1/chat/completions` only: when `both`, the adapter emits an extra `reasoning` alias next to `reasoning_content` on messages and deltas. Read into `Config.reasoningField`. | — | -| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. | +| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. Unrecognised values fall back to `info` and log a warning naming the variable. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. | | `OPENCODE_LOG_PRETTY` | boolean | `true` when stdout is a TTY | Pretty-print logs instead of JSON lines. | Needs `pino-pretty`, which is a dev dependency; without it the gateway falls back to JSON instead of failing. | | `OPENCODE_METRICS_ENABLED` | boolean | `true` | Enable Prometheus collection; when false, `GET /metrics` answers `404`. | — | | `OPENCODE_INSTANCE_ID` | string | `opencode-api-` | Identifier for this gateway instance. Also the fingerprint of the persisted session cache (`OPENCODE_SESSION_PERSIST`). | Changing it invalidates the persisted session cache. | Boolean values accept `1/true/yes/on/enabled` and `0/false/no/off/disabled` -(case-insensitive). Any other value falls back to the default. +(case-insensitive). Any other value is unrecognised: the default is kept and a +warning naming the variable is logged. Integer values must be a whole number: the entire value is parsed, so `OPENCODE_REQUEST_TIMEOUT_MS=10m` is **not** read as 10 seconds — it is treated as unrecognised, the default is kept and a warning naming the variable is logged. Out-of-range integers are clamped to the documented bounds. +`OPENCODE_REASONING_DEFAULT` and `OPENCODE_LOG_LEVEL` are unrecognised in the same +way: the default (`on-request`, `info`) is kept and a warning naming the variable +is logged. The warning never echoes the value, because an operator can paste a +secret into the wrong variable. + ## Environment variables read by other libraries `dotenv` loads `.env` from the project root and then the working directory. The @@ -161,7 +176,8 @@ logged when the published key is configured explicitly — including the `.env.example` default that `pnpm setup` copies — because in that case the port is just as unprotected. Every variable is otherwise clamped to its documented bounds, and an unrecognised -boolean/integer falls back to the default. +boolean, integer, reasoning default or log level falls back to the default with a +warning naming the variable. ## Recommended hardening for a reachable deployment diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 9799816..cc22b2b 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -79,7 +79,7 @@ FAIL POST /v1/chat/completions (non-streaming) | Bad body, chat / responses | `400 invalid_request_error` with `param` | OK | | Bad body, `/v1/messages` | `400 {"type":"error","error":{"type":"invalid_request_error",...}}` | OK | | `POST /v1/messages` without key | `401` **Anthropic** shape | OK | -| Auth transports | Bearer, `x-api-key`, `Basic base64(key:)`, `?api_key=` all `200` | OK | +| Auth transports | Bearer, `x-api-key`, `Basic base64(key:)` all `200`; a query-string key is not a transport and answers `401` | OK | | `POST /v1/chat/completions` (real model) | `429` + `retry-after: 57508`, `code":"provider.free-limit"` | OK (expected quota) | | `POST /v1/messages` (real model) | `429` + `retry-after: 57507` | OK (expected quota) | | `POST /v1/responses` (real model) | `429` + `retry-after: 57507` | OK (expected quota) | diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 2b71a11..75aff73 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -314,8 +314,58 @@ export interface ToInternalOptions { budget?: MediaBudget; } +/** + * Optional top-level fields for which an explicit `null` means "unset". + * + * Anthropic SDKs and the proxies in front of them serialise an untouched option + * as `null`, and the real API accepts that; zod rejects `null` for a plain + * `.optional()`, so without this the same request that `/v1/chat/completions` + * accepts (the OpenAI surfaces strip these too, see `normaliseNullFields` in + * `src/adapter/openai/chat.ts`) was answered `400 invalid_request` here. + * Required fields (`model`, `messages`) and per-message `content` are + * deliberately absent: a `null` there is a genuine defect. + */ +const NULL_MEANS_UNSET_FIELDS: ReadonlySet = new Set([ + "max_tokens", + "system", + "stream", + "temperature", + "top_p", + "top_k", + "stop_sequences", + "metadata", + "tools", + "tool_choice", + "thinking", + "reasoning_effort", + "service_tier", + "container", + "mcp_servers", +]); + +/** + * Drop explicit `null` values for the optional top-level request fields. + * + * Every other key (including unknown ones) is passed through untouched, so + * nothing else about validation changes. The original object is returned when + * there is nothing to strip. + */ +export function normaliseNullOptionals(body: unknown): unknown { + if (typeof body !== "object" || body === null || Array.isArray(body)) return body; + let changed = false; + const normalised: Record = {}; + for (const [key, value] of Object.entries(body)) { + if (value === null && NULL_MEANS_UNSET_FIELDS.has(key)) { + changed = true; + continue; + } + normalised[key] = value; + } + return changed ? normalised : body; +} + function parseOrThrow(schema: S, body: unknown, label: string): z.output { - const parsed = schema.safeParse(body); + const parsed = schema.safeParse(normaliseNullOptionals(body)); if (parsed.success) return parsed.data; const issue = parsed.error.issues[0]; const path = issue ? issue.path.map((segment) => String(segment)).join(".") : ""; diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index caea08a..82c1f2f 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -582,8 +582,13 @@ export async function resolveMessageMedia( const starts: number[] = []; for (const [index, draft] of drafts.entries()) { starts.push(allSources.length); - owners.push(...draft.sources.map(() => index)); - allSources.push(...draft.sources); + // Appended one by one: `push(...array)` throws `RangeError` once the array + // grows past the engine's argument limit (~125 000 elements), which a body + // far below `bodyLimitBytes` can reach with minimal `image_url` parts. + for (const source of draft.sources) { + owners.push(index); + allSources.push(source); + } } const resolved = @@ -958,6 +963,7 @@ async function streamChat( // end events together. It is the streamed twin of `CollectedCompletion.text` // and gates the documented "adopt only when longer" rule below. let textLength = 0; + let reasoningLength = 0; // Headers are sent lazily so that a failure before the first event is still // reported with a proper HTTP status instead of a 200 SSE body. @@ -1014,12 +1020,30 @@ async function streamChat( } case "reasoning_delta": { + reasoningLength += event.text.length; const delta: Record = { reasoning_content: event.text }; if (ctx.config.reasoningField === "both") delta["reasoning"] = event.text; ensure().send({ ...base, choices: [{ index: 0, delta, finish_reason: null }] }); break; } + case "reasoning_end": { + // A provider may deliver the consolidated thinking summary instead of + // (or in addition to) deltas; the buffered route and the other two + // streamed surfaces adopt it only when it is longer than what the + // deltas produced (`docs/ARCHITECTURE.md` §4.3). Only the suffix the + // stream has not seen yet is emitted. Without this case a turn whose + // thinking arrives only through `session.reasoning.ended` streamed an + // empty `reasoning_content` while the buffered body carried it. + if (event.text.length <= reasoningLength) break; + const summary = event.text.slice(reasoningLength); + reasoningLength = event.text.length; + const delta: Record = { reasoning_content: summary }; + if (ctx.config.reasoningField === "both") delta["reasoning"] = summary; + ensure().send({ ...base, choices: [{ index: 0, delta, finish_reason: null }] }); + break; + } + case "tool_calls": { if (event.calls.length === 0) break; const active = ensure(); diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index 2ce5a2f..16df4ba 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -34,7 +34,6 @@ import { normaliseNullFields, openAiUsage, openCodeExtension, - rejectUnsupported, StopSequenceFilter, truncateAtStopSequences, unappliedParameters, @@ -107,13 +106,6 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon }); } - if (body.best_of !== undefined) { - rejectUnsupported("best_of", "the gateway produces exactly one completion per request"); - } - if (body.suffix !== undefined) { - rejectUnsupported("suffix", "the OpenCode runtime cannot insert a suffix"); - } - if (body.n !== undefined && body.n !== 1) { throw ApiError.badRequest("Only `n: 1` is supported by this gateway.", { code: "invalid_request", diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index b4bb61b..0492962 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -261,6 +261,11 @@ const responsesRequest = z web_search_options: z.unknown().optional(), functions: z.array(z.unknown()).optional(), function_call: z.union([z.string(), z.object({ name: z.string().min(1) }).passthrough()]).optional(), + // Accepted for schema compatibility only, and rejected rather than dropped: + // a caller that bounds the tool loop must not silently get an unbounded one. + max_tool_calls: z.number().optional(), + prompt_cache_key: z.string().optional(), + safety_identifier: z.string().optional(), // Generation knobs: accepted and recorded, then reported through // `x_opencode.unapplied` because the OpenCode agent loop owns them. presence_penalty: z.number().optional(), @@ -476,6 +481,20 @@ function assertSupportedRequest(body: ResponsesRequest): void { "the gateway keeps no response state and cannot return encrypted reasoning content", ); } + // Declared so `.strip()` cannot swallow them: a bound the gateway does not + // apply must be reported, not silently ignored. + if (body.max_tool_calls !== undefined) { + rejectUnsupported( + "max_tool_calls", + "the tool loop is bounded by the upstream agent step budget, not by the caller", + ); + } + if (body.prompt_cache_key !== undefined) { + rejectUnsupported("prompt_cache_key", "the gateway keeps no prompt cache of its own"); + } + if (body.safety_identifier !== undefined) { + rejectUnsupported("safety_identifier", "the gateway runs no provider-side safety screening"); + } } /** Unix time in seconds, the unit OpenAI uses for `created_at` / `created`. */ @@ -584,7 +603,12 @@ async function prepare( maxCount: ctx.config.maxAttachments, maxBytes: ctx.config.maxAttachmentBytes, }); - messages.push(...(await mapInputItems(body.input, ctx, signal, budget))); + // Appended one by one: `push(...array)` throws `RangeError` once the array + // grows past the engine's argument limit (~125 000 elements), which a body + // far below `bodyLimitBytes` can reach with minimal input items. + for (const message of await mapInputItems(body.input, ctx, signal, budget)) { + messages.push(message); + } } const tools: ToolDefinition[] = (body.tools ?? []).map((tool) => ({ @@ -1319,7 +1343,12 @@ async function pipeEvents( // report a pre-flight failure as an in-band `response.failed`. const iterator = events[Symbol.asyncIterator](); const first = await iterator.next(); - if (!first.done && first.value.kind === "error") throw first.value.error; + if (!first.done && first.value.kind === "error") { + // The turn never started, so the session slot is still held: close the + // generator so its `finally` releases it before the 4xx/5xx leaves. + await closeIterator(iterator); + throw first.value.error; + } emitFrame(writer, state, "response.created", (sequence) => ({ type: "response.created", @@ -1538,6 +1567,12 @@ async function pipeEvents( case "error": sendFailure(writer, prepared, state, event.error); + // Close the orchestrator generator: its cleanup is a `finally` + // (`unsubscribe()` then `sessions.release(...)`), so returning without + // this leaves the sticky-session record `busy: true` until the + // generator happens to be collected. `for await` does this implicitly; + // the manual iterator below does not. + await closeIterator(iterator); return; default: @@ -1550,12 +1585,27 @@ async function pipeEvents( } } catch (error) { sendFailure(writer, prepared, state, toApiError(error, "OpenCode completion failed.")); + await closeIterator(iterator); return; } finaliseStream(writer, prepared, state); } +/** + * Close the orchestrator generator, ignoring a failure raised by its cleanup. + * + * The turn is already being reported as failed, so an error from `return()` + * must not replace the frame the caller is about to read. + */ +async function closeIterator(iterator: AsyncGenerator): Promise { + try { + await iterator.return(undefined); + } catch { + /* the turn is already failed */ + } +} + /** Emit the closing frames plus `response.completed` / `response.incomplete` / `response.failed`. */ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamState): void { // Items already announced through `response.output_item.done`; the closing diff --git a/src/auth.ts b/src/auth.ts index 44a853c..c9177de 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -9,7 +9,13 @@ * clients all work without configuration: * - `Authorization: Bearer ` * - `x-api-key: ` - * - `Authorization: Basic ` (key as the username) + * - `Authorization: Basic ` (key as the username, empty password) + * + * The Basic form is exactly the documented one: a non-empty username and an + * empty password. `base64()` without the colon and `base64(user:password)` + * are not credentials this gateway accepts, so an intermediary that injects a + * foreign `Authorization: Basic` header cannot have its password compared + * against the gateway key list. * * A scheme-less `Authorization` value is rejected: it is not one of the three * documented transports, and accepting it reinterpreted any foreign scheme as a @@ -21,7 +27,7 @@ * Failed attempts are charged to an always-on limiter and audited at `warn`, * so credential guessing is neither free nor invisible. */ -import { timingSafeEqual } from "node:crypto"; +import { createHash, timingSafeEqual } from "node:crypto"; import type { FastifyReply, FastifyRequest } from "fastify"; import type { Config } from "./config.js"; import { ApiError } from "./errors.js"; @@ -44,9 +50,21 @@ export function canonicalPath(url: string): string { return collapsed === "" ? "/" : collapsed; } -/** Path of a request URL, ignoring the query string and normalising spelling. */ +/** Per-request memo of `requestPath`, keyed by the request object. */ +const requestPaths = new WeakMap(); + +/** + * Path of a request URL, ignoring the query string and normalising spelling. + * + * Memoised per request: both the authenticator and the rate limiter ask for it, + * and canonicalisation runs two regular-expression passes. + */ export function requestPath(request: FastifyRequest): string { - return canonicalPath(request.url); + const memo = requestPaths.get(request); + if (memo !== undefined) return memo; + const path = canonicalPath(request.url); + requestPaths.set(request, path); + return path; } /** True for the routes that never require a credential. */ @@ -58,12 +76,29 @@ export function isPublicPath(path: string): boolean { * API key extraction. * * Keys are accepted as `Authorization: Bearer `, `x-api-key: ` or - * `Authorization: Basic base64(:)`. Any other `Authorization` value — - * including a bare key with no scheme — is rejected, so a foreign scheme is - * never reinterpreted as a credential. Query-string keys are deliberately not - * supported: request URLs are logged and end up in proxy access logs. + * `Authorization: Basic base64(:)` — the key as the username with an empty + * password. Any other `Authorization` value — including a bare key with no + * scheme — is rejected, so a foreign scheme is never reinterpreted as a + * credential. Query-string keys are deliberately not supported: request URLs are + * logged and end up in proxy access logs. + * + * The result is memoised per request (see `presentedKeys`), because both the + * authenticator and the rate limiter need it and decoding Basic base64 twice per + * request is needless work. */ export function extractApiKey(request: FastifyRequest): string | undefined { + const memo = presentedKeys.get(request); + if (memo !== undefined) return memo.value; + + const value = readApiKey(request); + presentedKeys.set(request, { value }); + return value; +} + +/** Per-request memo of `extractApiKey`, keyed by the request object. */ +const presentedKeys = new WeakMap(); + +function readApiKey(request: FastifyRequest): string | undefined { const authorization = request.headers.authorization; if (typeof authorization === "string" && authorization.length > 0) { const [scheme, ...rest] = authorization.split(" "); @@ -71,14 +106,15 @@ export function extractApiKey(request: FastifyRequest): string | undefined { const normalised = scheme?.toLowerCase(); if (normalised === "bearer" && value) return value; if (normalised === "basic" && value) { - try { - const decoded = Buffer.from(value, "base64").toString("utf8"); - const [user, pass] = decoded.split(":"); - if (user && user.length > 0) return user; - if (pass && pass.length > 0) return pass; - } catch { - return undefined; - } + // `Buffer.from(value, "base64")` never throws: it skips what it cannot + // decode, so there is no error path to catch here. + const decoded = Buffer.from(value, "base64").toString("utf8"); + const separator = decoded.indexOf(":"); + // The documented form is `base64(:)`: a non-empty username and an + // empty password. A colon-less value or a password is not a credential. + if (separator <= 0) return undefined; + if (separator !== decoded.length - 1) return undefined; + return decoded.slice(0, separator); } } @@ -89,22 +125,32 @@ export function extractApiKey(request: FastifyRequest): string | undefined { return undefined; } +/** + * Fixed-width digest of a credential. + * + * Comparing digests instead of the raw strings keeps `timingSafeEqual` on equal + * length inputs, so neither the key length nor the position of a matching key is + * observable through the comparison. + */ +function digest(value: string): Buffer { + return createHash("sha256").update(value, "utf8").digest(); +} + function safeEqual(left: string, right: string): boolean { - const a = Buffer.from(left, "utf8"); - const b = Buffer.from(right, "utf8"); - if (a.length !== b.length) { - // Still perform a comparison to keep the timing profile flat. - timingSafeEqual(a, a); - return false; - } - return timingSafeEqual(a, b); + return timingSafeEqual(digest(left), digest(right)); } export function isAuthorized(config: Config, presented: string | undefined): boolean { if (config.allowNoAuth) return true; if (config.apiKeys.length === 0) return false; if (!presented) return false; - return config.apiKeys.some((key) => safeEqual(key, presented)); + // Every configured key is evaluated: `some` stops at the matching key, which + // leaks its position through the timing profile. + let matched = false; + for (const key of config.apiKeys) { + if (safeEqual(key, presented)) matched = true; + } + return matched; } /** True for `/admin` and every route below it. */ @@ -124,7 +170,12 @@ export function isAdminAuthorized(config: Config, presented: string | undefined) if (config.allowNoAuth) return true; if (config.adminApiKeys.length === 0) return isAuthorized(config, presented); if (!presented) return false; - return config.adminApiKeys.some((key) => safeEqual(key, presented)); + // As in `isAuthorized`, every key is evaluated without short-circuiting. + let matched = false; + for (const key of config.adminApiKeys) { + if (safeEqual(key, presented)) matched = true; + } + return matched; } /** diff --git a/src/config.ts b/src/config.ts index f41e908..ed7d468 100644 --- a/src/config.ts +++ b/src/config.ts @@ -146,8 +146,8 @@ function envOptStr(name: string): string | undefined { * the console directly. The variable name is logged; the value is not, because * an operator can put secrets in the wrong variable. */ -function warnInvalidEnv(name: string, fallback?: number): void { - const suffix = fallback === undefined ? "" : `; using the default (${fallback})`; +function warnInvalidEnv(name: string, fallback?: number | string | boolean): void { + const suffix = fallback === undefined ? "" : `; using the default (${String(fallback)})`; console.warn(`opencode-api: ignoring invalid value for ${name}${suffix}`); } @@ -176,11 +176,19 @@ function envInt(name: string, fallback: number, min = Number.NEGATIVE_INFINITY, return Math.min(max, Math.max(min, parsed)); } +/** + * Parse a boolean environment value. + * + * An unrecognised spelling warns (naming the variable, never the value) and + * falls back, so an operator who typo'd `fals` learns the value was ignored + * instead of believing it took effect. + */ function envBool(name: string, fallback: boolean): boolean { const raw = env(name)?.toLowerCase(); if (raw === undefined) return fallback; if (["1", "true", "yes", "on", "enabled"].includes(raw)) return true; if (["0", "false", "no", "off", "disabled"].includes(raw)) return false; + warnInvalidEnv(name, fallback); return fallback; } @@ -202,6 +210,10 @@ function envList(name: string): string[] { * documented "warn and fall back to `false`". The check therefore runs here, with * `node:net`'s own address parser. A zone-qualified IPv6 literal is rejected * because `proxy-addr` does not understand the `%zone` suffix. + * + * A `/0` prefix is rejected as well: it matches every address of that family, so + * the leftmost `x-forwarded-for` entry of any peer becomes the client address and + * both the rate-limit bucket and every access-log line are caller-controlled. */ function isTrustedProxyEntry(entry: string): boolean { if (entry.includes("%")) return false; @@ -213,7 +225,9 @@ function isTrustedProxyEntry(entry: string): boolean { const prefix = parts[1]; if (prefix === undefined) return true; if (!/^\d{1,3}$/.test(prefix)) return false; - return Number(prefix) <= (family === 4 ? 32 : 128); + const length = Number(prefix); + if (length <= 0) return false; + return length <= (family === 4 ? 32 : 128); } /** @@ -263,6 +277,24 @@ function parseTrustProxy(): Config["trustProxy"] { return false; } +/** + * The pino levels `OPENCODE_LOG_LEVEL` accepts. + * + * `src/logger.ts` hands the value straight to pino, which throws on anything + * outside this set — an internals stack trace instead of a configuration + * message. Validating here keeps the failure a warning and a fallback. + */ +const LOG_LEVELS: readonly string[] = ["trace", "debug", "info", "warn", "error", "fatal"]; + +function envLogLevel(name: string, fallback: string): string { + const raw = env(name); + if (raw === undefined) return fallback; + const normalised = raw.toLowerCase(); + if (LOG_LEVELS.includes(normalised)) return normalised; + warnInvalidEnv(name, fallback); + return fallback; +} + /** Resolve a possibly-relative path against the current working directory. */ export function resolvePath(value: string): string { const expanded = value.startsWith("~") ? path.join(os.homedir(), value.slice(1)) : value; @@ -460,15 +492,19 @@ export function loadConfig(overrides: Partial = {}): Config { mediaFetchTimeoutMs: envInt("OPENCODE_MEDIA_FETCH_TIMEOUT_MS", 15_000, 100), reasoningDefault: (() => { - const raw = envStr("OPENCODE_REASONING_DEFAULT", "on-request").toLowerCase(); - return raw === "off" || raw === "always" ? raw : "on-request"; + const raw = env("OPENCODE_REASONING_DEFAULT"); + if (raw === undefined) return "on-request"; + const normalised = raw.toLowerCase(); + if (normalised === "off" || normalised === "on-request" || normalised === "always") return normalised; + warnInvalidEnv("OPENCODE_REASONING_DEFAULT", "on-request"); + return "on-request"; })(), exposeNativeTools: envBool("OPENCODE_EXPOSE_NATIVE_TOOLS", false), toolBridgeDenyNativeTools: envBool("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS", true), nativeToolEventName: envStr("OPENCODE_NATIVE_TOOL_EVENT", "opencode.tool_call"), reasoningField: envStr("OPENCODE_REASONING_FIELD", "reasoning_content").toLowerCase() === "both" ? "both" : "reasoning_content", - logLevel: envStr("OPENCODE_LOG_LEVEL", "info"), + logLevel: envLogLevel("OPENCODE_LOG_LEVEL", "info"), logPretty: envBool("OPENCODE_LOG_PRETTY", process.stdout.isTTY === true), metricsEnabled: envBool("OPENCODE_METRICS_ENABLED", true), instanceId: envStr("OPENCODE_INSTANCE_ID", `opencode-api-${process.pid}`), diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts index a72fe38..4263a24 100644 --- a/src/http/rateLimit.ts +++ b/src/http/rateLimit.ts @@ -5,8 +5,9 @@ * is retained) plus one bucket per client address for credential-less callers * (never the raw address either). The limiter runs as an `onRequest` hook beside * `requireApiKey`, `/admin/*` gets its own bucket so operator traffic cannot be - * starved by completion traffic, and a third always-on bucket charges failed - * authentication so credential guessing is never free. + * starved by completion traffic, and two always-on buckets charge failed + * authentication — one per client address, one global ceiling — so credential + * guessing is neither free nor invisible. * * The bucket map is bounded: an anonymous deployment cannot let a spoofed or * rotating client address grow it without limit. @@ -139,6 +140,22 @@ function authBucketKey(request: FastifyRequest): string { const AUTH_RATE_LIMIT_MIN_RPM = 60; const AUTH_RATE_LIMIT_MIN_BURST = 10; +/** + * Global failed-authentication ceiling. + * + * The per-address bucket is the primary control, but behind a reverse proxy with + * `OPENCODE_TRUST_PROXY=false` (the default) every caller resolves to the proxy + * address, so all callers share one bucket. This second, much higher bucket + * bounds the aggregate failed-auth work an attacker can trigger without letting a + * single address lock the deployment out: it is only reached after the shared + * per-address bucket has been drained many times over. + */ +const AUTH_GLOBAL_RATE_LIMIT_RPM = 6_000; +const AUTH_GLOBAL_RATE_LIMIT_BURST = 600; + +/** Bucket identity of the global failed-authentication ceiling. */ +const AUTH_GLOBAL_BUCKET = bucketKey("auth", "global"); + /** * Identity a request is bucketed on. * @@ -153,13 +170,29 @@ const AUTH_RATE_LIMIT_MIN_BURST = 10; * declared proxy, when this limiter must be a control rather than a courtesy. * Caller-supplied headers are never read directly. */ -function bucketIdentity(config: Config, request: FastifyRequest): string { +function bucketIdentity(request: FastifyRequest, keySet: ReadonlySet): string { const presented = extractApiKey(request); - if (presented !== undefined && config.apiKeys.includes(presented)) return `key:${presented}`; + if (presented !== undefined && keySet.has(presented)) return `key:${presented}`; return `ip:${request.ip.length > 0 ? request.ip : "unknown"}`; } -/** Limiter triple wired into the request lifecycle. */ +/** + * A `Set` view of `Config.apiKeys` for the hot-path membership test. + * + * `Config` objects are immutable in practice and long-lived, so the set is built + * once per configuration instead of scanning the array on every request. + */ +const keySets = new WeakMap>(); + +function configuredKeySet(config: Config): ReadonlySet { + const memo = keySets.get(config); + if (memo !== undefined) return memo; + const set = new Set(config.apiKeys); + keySets.set(config, set); + return set; +} + +/** Limiter set wired into the request lifecycle. */ export interface RateLimiters { readonly api: TokenBucketLimiter; readonly admin: TokenBucketLimiter; @@ -171,6 +204,14 @@ export interface RateLimiters { * that throttles nothing else. */ readonly auth: TokenBucketLimiter; + /** + * Always-on global ceiling for failed authentication. + * + * Bounds the aggregate failed-auth work across every address, so a single + * shared per-address bucket (the reverse-proxy case) cannot be drained into a + * full lockout nor left unbounded. + */ + readonly authGlobal: TokenBucketLimiter; } export function createRateLimiters(config: Config, now?: () => number): RateLimiters { @@ -185,19 +226,41 @@ export function createRateLimiters(config: Config, now?: () => number): RateLimi burst: Math.max(derivedBurst(authRpm), AUTH_RATE_LIMIT_MIN_BURST), ...clock, }), + authGlobal: new TokenBucketLimiter({ + rpm: Math.max(authRpm, AUTH_GLOBAL_RATE_LIMIT_RPM), + burst: Math.max(derivedBurst(AUTH_GLOBAL_RATE_LIMIT_RPM), AUTH_GLOBAL_RATE_LIMIT_BURST), + ...clock, + }), }; } /** - * Charge the failed-authentication bucket, calling it once per rejected request. + * Charge the failed-authentication buckets, calling it once per rejected request. * * Called only on the failure path, so a valid credential never spends this * budget, and it reuses the bounded bucket map (see `MAX_RATE_LIMIT_BUCKETS`) * so an attacker rotating source addresses cannot grow it without limit. + * + * Two buckets are charged: the per-address one, which is the control that keeps + * one noisy host from spending everyone else's budget, and a much higher global + * one, which bounds aggregate failed-auth work when every caller shares a single + * address (the default `OPENCODE_TRUST_PROXY=false` behind a proxy). */ export function chargeFailedAuth(limiters: RateLimiters, request: FastifyRequest): void { const retryAfterMs = limiters.auth.take(authBucketKey(request)); - if (retryAfterMs === undefined) return; + if (retryAfterMs === undefined) { + // The per-address budget is spent by this caller only; the global ceiling is + // what stops aggregate guessing, and it answers 429 for everyone once spent. + const globalRetryAfterMs = limiters.authGlobal.take(AUTH_GLOBAL_BUCKET); + if (globalRetryAfterMs === undefined) return; + const globalSeconds = Math.ceil(globalRetryAfterMs / 1000); + throw new ApiError( + 429, + "rate_limit_error", + `Too many rejected authentication attempts across all addresses. Retry in ${globalSeconds}s.`, + { code: "rate_limit_exceeded", retryAfterMs: globalRetryAfterMs }, + ); + } throw new ApiError( 429, "rate_limit_error", @@ -209,23 +272,25 @@ export function chargeFailedAuth(limiters: RateLimiters, request: FastifyRequest /** * Build the rate-limiting `onRequest` hook. * - * Health/metrics probes and preflight requests are exempt; `/admin/*` uses the - * admin bucket. Authenticated callers are bucketed per configured key, every - * other caller per client address (see `bucketIdentity`). A rejected request - * answers `429 rate_limit_error` with the documented `retry-after` header - * (Fastify's error handler derives it from `retryAfterMs`). A request that - * fails authentication is charged separately, to `RateLimiters.auth`, before - * the 401 is thrown — see `chargeFailedAuth`. + * Liveness probes and preflight requests are exempt; `/admin/*` uses the admin + * bucket, and `/metrics` is charged to the api bucket like any other route so an + * anonymous scrape loop cannot walk the whole registry for free. Authenticated + * callers are bucketed per configured key, every other caller per client address + * (see `bucketIdentity`). A rejected request answers `429 rate_limit_error` with + * the documented `retry-after` header (Fastify's error handler derives it from + * `retryAfterMs`). A request that fails authentication is charged separately, to + * `RateLimiters.auth`, before the 401 is thrown — see `chargeFailedAuth`. */ export function requireRateLimit(config: Config, limiters: RateLimiters, onReject?: (scope: "api" | "admin") => void) { + const keySet = configuredKeySet(config); return async function rateLimit(request: FastifyRequest, _reply: FastifyReply): Promise { if (!limiters.api.enabled) return; const path = requestPath(request); - if (isPublicPath(path) || path === "/metrics" || request.method === "OPTIONS") return; + if (isPublicPath(path) || request.method === "OPTIONS") return; const scope = path === "/admin" || path.startsWith("/admin/") ? "admin" : "api"; const limiter = scope === "admin" ? limiters.admin : limiters.api; - const retryAfterMs = limiter.take(bucketKey(scope, bucketIdentity(config, request))); + const retryAfterMs = limiter.take(bucketKey(scope, bucketIdentity(request, keySet))); if (retryAfterMs === undefined) return; onReject?.(scope); diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 188e6bf..e14e170 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -398,6 +398,9 @@ export async function resolveAttachments( // `drain()` walks indexes in order, so this array stays ordered. attachments.push(decision.attachment); } else { + // The slot claimed for this source is given back: nothing was retained + // for it, so a later source may still use it. + budget.releaseSlot(); recordOmission(nextAdmit, "bytes"); } nextAdmit += 1; @@ -521,7 +524,12 @@ async function resolveSource( } if (source.dataUri) return resolveDataUri(source, config, field, limitBytes); - if (source.base64 !== undefined) return resolveBase64(source, config, field, limitBytes); + // An empty `file_data` (a blank form field a client serialises anyway) must not + // shadow a `file_url` sent beside it: the source list above already dropped the + // empty string, so the base64 branch is taken only for a payload that has bytes. + if (source.base64 !== undefined && source.base64.length > 0) { + return resolveBase64(source, config, field, limitBytes); + } if (source.url) return resolveUrl(source, config, field, limitBytes, signal); return resolveLocalFile(source, config, field, limitBytes); } @@ -544,9 +552,12 @@ function resolveDataUri(source: MediaSource, config: Config, field: string, limi let buffer: Buffer; if (isBase64) { // Only the part after the comma is a base64 payload; the `data:` prefix is - // never counted against the encoded-length bound. - assertEncodedWithinLimit(payload, field, limitBytes); - buffer = decodeBase64(payload, field); + // never counted against the encoded-length bound. The line breaks of a + // MIME-wrapped payload carry no bytes, so they are stripped before the bound + // and the decode: the cap then measures the characters that actually decode. + const encoded = stripBase64Whitespace(payload); + assertEncodedWithinLimit(encoded, field, limitBytes); + buffer = decodeBase64(encoded, field); } else { try { buffer = Buffer.from(decodeURIComponent(payload), "utf8"); @@ -565,9 +576,13 @@ function resolveDataUri(source: MediaSource, config: Config, field: string, limi } function resolveBase64(source: MediaSource, config: Config, field: string, limitBytes: number): Attachment { - const payload = source.base64 ?? ""; + // The whitespace of a MIME-wrapped payload is stripped before the encoded-length + // bound and the decode: a payload wrapped at 76 characters per line decodes to + // the same bytes but is ~2.6 % longer as it arrives, which used to push a + // payload within ~1.4 % of the cap over the bound. + const payload = stripBase64Whitespace(source.base64 ?? ""); // Refuse an obviously oversized payload on its encoded length, before the - // decoded copy (and the whitespace-stripped copy) is allocated. + // decoded copy is allocated. assertEncodedWithinLimit(payload, field, limitBytes); const buffer = decodeBase64(payload, field); assertWithinBudget(buffer.byteLength, config, field, source.name, limitBytes); @@ -1050,6 +1065,22 @@ async function resolveLocalFile( openedIdentity = { dev: linkStats.dev, ino: linkStats.ino }; } + // The type is proven before the open, never after it: `open()` on a FIFO, a + // Unix socket or a device node blocks the libuv threadpool until a writer + // appears, and one never does for a socket or a device — while no timeout + // covers this path (`mediaFetchTimeoutMs` is remote-only), so four requests + // naming one FIFO stall every filesystem operation in the process. + // `realpath()` has already canonicalised the final component, so `stat()` + // reports the file the roots check admitted; a final component swapped for a + // symlink after this point is still refused by `O_NOFOLLOW` in the open below. + const resolvedStats = await fsp.stat(realPath); + if (!resolvedStats.isFile()) { + throw ApiError.badRequest(`Attachment path is not a regular file: ${requested}`, { + code: "invalid_attachment", + param: field, + }); + } + handle = await fsp.open(realPath, fsConstants.O_RDONLY | OPEN_NOFOLLOW); const stats = await handle.stat(); if (openedIdentity !== undefined && (stats.dev !== openedIdentity.dev || stats.ino !== openedIdentity.ino)) { @@ -1097,10 +1128,11 @@ async function resolveLocalFile( * * `ENOENT`/`ENOTDIR` keep the historical `attachment_not_found`; the errno * values a caller can trigger by making a file unreadable (`EACCES`, `EPERM`, - * `ELOOP` from `O_NOFOLLOW`, `EISDIR`, a Windows lock's `EBUSY`) become - * `invalid_attachment`. Anything else stays a 500 on purpose: an unexpected - * errno is an operational problem, not a caller error, and must keep surfacing - * in the logs. + * `ELOOP` from `O_NOFOLLOW`, `EISDIR`, a Windows lock's `EBUSY`) and the ones a + * non-regular final component produces (`ENXIO` for a Unix socket, `ENODEV` for a + * device) become `invalid_attachment`. Anything else stays a 500 on purpose: an + * unexpected errno is an operational problem, not a caller error, and must keep + * surfacing in the logs. */ function localFileError(error: unknown, requested: string, field: string): ApiError { if (error instanceof ApiError) return error; @@ -1112,7 +1144,15 @@ function localFileError(error: unknown, requested: string, field: string): ApiEr param: field, }); } - if (code === "EACCES" || code === "EPERM" || code === "ELOOP" || code === "EISDIR" || code === "EBUSY") { + if ( + code === "EACCES" || + code === "EPERM" || + code === "ELOOP" || + code === "EISDIR" || + code === "EBUSY" || + code === "ENXIO" || + code === "ENODEV" + ) { return ApiError.badRequest(`Attachment file is not readable: ${requested}`, { code: "invalid_attachment", param: field, @@ -1121,15 +1161,26 @@ function localFileError(error: unknown, requested: string, field: string): ApiEr throw error; } +/** + * Remove the whitespace a MIME-wrapped base64 payload carries. + * + * `Buffer.from(value, "base64")` ignores CR/LF, spaces and tabs, so stripping + * them changes nothing about the decoded bytes; it lets the encoded-length bound + * measure the payload instead of its line wrapping. + */ +function stripBase64Whitespace(payload: string): string { + return payload.replace(/\s+/g, ""); +} + /** * Refuse a base64 payload that cannot decode to the byte limit, on its encoded * length alone. * * The bound is the exact 4-chars-per-3-bytes ceiling (`ceil(limit * 4 / 3)`) plus * the padding slack, so a payload that decodes to exactly `limitBytes` still - * passes while a payload that could never fit is refused before any decoded (or - * whitespace-stripped) copy is allocated. `+ 4` covers up to four bytes of - * trailing padding/line ending. + * passes while a payload that could never fit is refused before any decoded copy + * is allocated. `+ 4` covers up to four bytes of trailing padding. The caller + * strips whitespace first, so the length measured here is the encoded payload. */ function assertEncodedWithinLimit(payload: string, field: string, limitBytes: number): void { const maxEncoded = Math.ceil((limitBytes * 4) / 3) + 4; @@ -1149,10 +1200,10 @@ function decodeBase64(payload: string, field: string): Buffer { if (payload.trim().length === 0) { throw ApiError.badRequest("Attachment payload is empty.", { code: "invalid_attachment", param: field }); } - // The alphabet is validated on the payload as it arrived (whitespace is part - // of the grammar here, not stripped first), so no throw-away copy is built just - // to check it. The byte bound was applied to the raw encoded length before this - // function was entered. + // The alphabet is validated on the payload as it arrived (the pattern tolerates + // whitespace, so a caller that did not strip it is still checked as-is), so no + // throw-away copy is built just to check it. The byte bound was applied to the + // whitespace-stripped encoded length before this function was entered. if (!BASE64_ALPHABET.test(payload) || !BASE64_PADDING.test(payload)) { throw ApiError.badRequest("Attachment payload is not valid base64.", { code: "invalid_attachment", diff --git a/src/server.ts b/src/server.ts index c08f5fc..0c5f064 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,7 +11,7 @@ import { registerOpenAiModelRoutes } from "./adapter/openai/models.js"; import { registerOpenAiResponsesRoutes } from "./adapter/openai/responses.js"; import { registerAnthropicCountTokenRoutes } from "./adapter/anthropic/countTokens.js"; import { registerAnthropicMessageRoutes } from "./adapter/anthropic/messages.js"; -import { requireApiKey } from "./auth.js"; +import { canonicalPath, requireApiKey } from "./auth.js"; import type { AppContext } from "./context.js"; import type { Config } from "./config.js"; import { ApiError, toAnthropicError, toApiError, toOpenAiError } from "./errors.js"; @@ -22,8 +22,40 @@ import { registerHealthRoutes } from "./routes/health.js"; import { registerMetricsRoutes } from "./routes/metrics.js"; import { SERVICE_NAME, VERSION } from "./version.js"; +/** + * The two paths the Anthropic surface serves. + * + * Compared exactly, not by prefix: an unmatched `/v1/messagesfoo` must be + * answered with the OpenAI error shape, like every other unmatched route. + */ +const ANTHROPIC_SURFACE_PATHS: ReadonlySet = new Set(["/v1/messages", "/v1/messages/count_tokens"]); + function isAnthropicSurface(request: FastifyRequest): boolean { - return (request.url.split("?")[0] ?? "").startsWith("/v1/messages"); + return ANTHROPIC_SURFACE_PATHS.has(canonicalPath(request.url)); +} + +/** + * Union of an existing `vary` value and `value`. + * + * The CORS hook must not drop a `vary` another hook or route already set: + * overwriting it would let a cache serve a cross-origin response to a caller that + * never sent `Origin`. + */ +export function appendVary(existing: string | number | string[] | undefined, value: string): string { + const current: string[] = []; + const append = (raw: string): void => { + for (const part of raw.split(",")) { + const trimmed = part.trim(); + if (trimmed.length === 0) continue; + if (current.some((entry) => entry.toLowerCase() === trimmed.toLowerCase())) continue; + current.push(trimmed); + } + }; + if (Array.isArray(existing)) for (const entry of existing) append(String(entry)); + else if (typeof existing === "string") append(existing); + else if (typeof existing === "number") append(String(existing)); + append(value); + return current.join(", "); } /** @@ -137,7 +169,8 @@ export async function buildServer(ctx: AppContext): Promise { // `x-request-id` is set on every response; without this a browser cannot // read it, although the reference documents it as the correlation id. reply.header("access-control-expose-headers", "x-request-id"); - reply.header("vary", "origin"); + // Append, never overwrite: another hook may already have set `vary`. + reply.header("vary", appendVary(reply.getHeader("vary"), "origin")); } if (request.method === "OPTIONS") { // A disallowed origin still gets 204 without the CORS headers, so the @@ -234,11 +267,10 @@ export async function buildServer(ctx: AppContext): Promise { reply.header("retry-after", String(Math.ceil(apiError.retryAfterMs / 1000))); } - const status = apiError.status === 499 ? 499 : apiError.status; if (isAnthropicSurface(request)) { - return reply.status(status).send(toAnthropicError(apiError)); + return reply.status(apiError.status).send(toAnthropicError(apiError)); } - return reply.status(status).send(toOpenAiError(apiError)); + return reply.status(apiError.status).send(toOpenAiError(apiError)); }); app.setNotFoundHandler((request, reply) => { diff --git a/src/upstream/client.ts b/src/upstream/client.ts index b7cf814..75c948a 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -124,6 +124,10 @@ export class OpencodeClient { if (response.status === 401) { outcome = "unauthorized"; + // Release the body before throwing: undici keeps the socket until the + // body is consumed or cancelled, so every rejected call leaked one + // unread body and descriptor. + await response.body?.cancel().catch(() => undefined); this.#process.markStale("OpenCode rejected the gateway credentials."); throw ApiError.unavailable( "OpenCode rejected the gateway credentials. Restart the gateway or re-run `opencode serve`.", @@ -140,7 +144,9 @@ export class OpencodeClient { type: parsed?._tag ?? `http_${response.status}`, message: parsed?.message ?? text.slice(0, 500) ?? response.statusText, status: response.status, - response: { body: text }, + // Bounded to the same 500 characters as the message: the whole body + // used to be retained on the error for the rest of the request. + response: { body: text.slice(0, 500) }, retryAfterMs: parsed?.retryAfterMs, }); } diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 7507f6b..31f679e 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -68,6 +68,14 @@ interface Prepared { key: string; /** Permission profile the upstream session was created under. */ permissionProfile: string; + /** + * Fingerprint of the request's tool definitions. + * + * Computed once in `prepare()` for `sessions.acquire()` and carried here so + * `finalise()` does not sort and serialise the whole tool array a second time + * on the SSE-delivery path. + */ + toolsHash: string; } /** Aggregated result of a non-streaming completion. */ @@ -403,6 +411,7 @@ async function prepare( promptFiles: files, key, permissionProfile, + toolsHash, }; } catch (error) { // `acquire()` already reserved the record when it reused a session. Anything @@ -638,11 +647,27 @@ async function* execute( } case "session.text.ended": { - const text = typeof data["text"] === "string" ? data["text"] : ""; + const raw = typeof data["text"] === "string" ? data["text"] : ""; + const ordinal = numberValue(data["ordinal"]); + // The consolidated step text is the *raw* upstream text, so on a + // bridged turn it still contains the `[[OPENCODE_TOOL_CALL]]` envelope + // that the deltas above were filtered for. Yielding it verbatim made + // every consumer's "adopt only when longer" rule fire (raw text = + // filtered text + envelope) and leaked the internal marker into + // `content` next to the parsed `tool_calls`. Filter it through the + // same turn-scoped bridge so both paths compare like with like. + const parsed = bridge.active ? bridge.parse(raw) : undefined; + // A step that delivered its text only through this frame never went + // through the filter, so its calls would be lost with the envelope. + // Deltas already drained theirs, hence the `bridgedToolCalls` guard. + if (parsed !== undefined && bridgedToolCalls === 0 && parsed.calls.length > 0) { + bridgedToolCalls += parsed.calls.length; + yield { kind: "tool_calls", calls: parsed.calls }; + } yield { kind: "text_end", - text, - ordinal: numberValue(data["ordinal"]), + text: parsed === undefined ? raw : parsed.text, + ordinal, ...(messageId !== "" ? { messageId } : {}), }; break; @@ -819,7 +844,7 @@ async function* execute( agent: prepared.agent, variant: prepared.decision.variant, messages: prepared.request.messages, - toolsHash: hashTools(prepared.request.tools), + toolsHash: prepared.toolsHash, permissionProfile: prepared.permissionProfile, }); diff --git a/src/upstream/events.ts b/src/upstream/events.ts index 7f572f5..aff1902 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -124,6 +124,10 @@ export class EventHub { this.#controller?.abort(); this.#controller = undefined; this.#connected = false; + // The next start begins at the documented floor: an accumulated delay from + // a flapping upstream used to survive `stop()`, so the first turn after a + // restart waited it instead of 250 ms. + this.#reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; // The gauge is zeroed here as well: `#loop`'s `finally` only observes the // transition while `#connected` is still true, and `stop()` clears it first, // so after a shutdown the exposition used to keep reporting 1. @@ -190,7 +194,11 @@ export class EventHub { this.#recordDisconnect(); await delay(this.#reconnectDelayMs); if (!this.#isCurrentLoop(generation)) return; - if (this.#reconnectDelayMs < MAX_RECONNECT_DELAY_MS) this.#reconnectDelayMs *= 2; + if (this.#reconnectDelayMs < MAX_RECONNECT_DELAY_MS) { + // Clamped: doubling only below the cap turned 4_000 into 8_000, above + // the documented `MAX_RECONNECT_DELAY_MS`. + this.#reconnectDelayMs = Math.min(this.#reconnectDelayMs * 2, MAX_RECONNECT_DELAY_MS); + } } } @@ -271,6 +279,10 @@ export class EventHub { if (!response.ok || !response.body) { this.#dropReason = "rejected"; + // Undici keeps the socket until the body is consumed or cancelled. An + // upstream that answers 401/500 to `/api/event` is reconnected to + // forever, so an unread body per attempt exhausted the descriptor table. + await response.body?.cancel().catch(() => undefined); throw new Error(`event stream rejected with status ${response.status}`); } diff --git a/src/upstream/process.ts b/src/upstream/process.ts index ef72dad..bdcd389 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -107,6 +107,21 @@ const STDERR_PARTIAL_LIMIT_CHARS = 8_192; /** First failure window; doubles per consecutive failure up to the cap. */ const START_BACKOFF_BASE_MS = 1_000; const START_BACKOFF_MAX_MS = 30_000; +/** + * How much of the previous chunk is carried across the log-file redaction + * boundary. + * + * `redactUpstreamSecret()` is a per-chunk regex, so a `server password` marker + * the child's pipe split across two writes was invisible at push time and the + * plaintext credential reached `/logs/opencode-.log`, which has + * no read-time pass. The tail is carried across the boundary and written with + * the next chunk; `partialMarkerLength()` keeps the boundary from falling + * inside a marker. + */ +const LOG_REDACTION_CARRY_CHARS = 64; + +/** Markers the log redaction masks, lower-cased for the boundary check. */ +const LOG_MARKERS = ["server password", "authorization: basic"]; /** * Number of readiness scans performed, exposed for tests. @@ -196,6 +211,30 @@ function clampTail(value: string, limit: number): string { return value.length > limit ? value.slice(-limit) : value; } +/** + * Length of the longest suffix of `text` that could still grow into a marker. + * + * The log-file copy is written with a carry across chunk boundaries, so the + * write boundary must never fall inside `server password` or + * `authorization: Basic` — otherwise the head of the marker reaches the disk + * and the tail is redacted on its own, which leaves the credential readable. + */ +function partialMarkerLength(text: string): number { + const lower = text.toLowerCase(); + let longest = 0; + for (const marker of LOG_MARKERS) { + const limit = Math.min(marker.length, lower.length); + for (let size = limit; size > longest; size -= 1) { + if (lower.endsWith(marker.slice(0, size))) longest = size; + } + // A marker followed by whitespace is still incomplete: the value the regex + // consumes has not arrived yet. + const spaced = new RegExp(`${marker}\\s+$`).exec(lower); + if (spaced) longest = Math.max(longest, spaced[0].length); + } + return longest; +} + /** * Mask the upstream server credential inside free-form child output. * @@ -351,6 +390,14 @@ export class UpstreamProcess { async stop(): Promise { this.#stopping = true; this.#stopped = true; + // A deliberate stop is not a start failure. The accumulated bookkeeping + // would otherwise make the caller's own next `resolve()` (the admin + // restart path does exactly `stop()` then `resolve()`) fail with + // `retrying in N ms` for up to 30 s, although a configured or discovered + // server may be reachable. Cleared before the in-flight start is awaited: + // a start that this stop interrupts still counts as its own failure. + this.#startFailures = 0; + this.#startBackoffUntil = 0; // A `reprobe()` request is about the endpoint that is being dropped here. this.#reprobe = false; const child = this.#child; @@ -446,6 +493,10 @@ export class UpstreamProcess { // `stop()` only knows `#child`: nothing else this instance started may // survive a terminal shutdown, in-process or at `process.exit()`. this.#killLiveChildren(); + // Terminal means terminal: the instance has nothing left to terminate, so + // the process-exit registry must not retain it (with its config and logger) + // for the lifetime of the process. + UpstreamProcess.#liveInstances.delete(this); } /** @@ -642,6 +693,10 @@ export class UpstreamProcess { headers: authHeaders(endpoint.password), signal: AbortSignal.timeout(timeoutMs), }); + // The body is never read, so it must be cancelled on every path: undici + // keeps the socket until the body is consumed, and every `reprobe()` of a + // failing endpoint used to leak one unread body and descriptor. + await response.body?.cancel().catch(() => undefined); if (response.ok) return "ok"; // OpenCode 2.x answers 400 to an unauthenticated probe, so 400 has always // counted as "something is listening" and must keep doing so. 401/403 mean @@ -750,6 +805,33 @@ export class UpstreamProcess { logStream.destroy(); }); + /** + * Append a chunk to the log file with the credential masked. + * + * The mask is a per-chunk regex, so the tail of the previous chunk is + * carried across the boundary: a `server password` marker the child's pipe + * split across two writes used to be written to disk in plaintext, and the + * file — unlike `status()` — has no read-time pass. + */ + let redactionCarry = ""; + const writeLog = (chunk: string): void => { + if (!logActive) return; + const pending = redactionCarry + chunk; + const boundary = Math.max(0, pending.length - LOG_REDACTION_CARRY_CHARS); + // Never write a partial marker: the boundary moves back over it. + const hold = partialMarkerLength(pending.slice(0, boundary)); + const writeable = pending.slice(0, boundary - hold); + redactionCarry = pending.slice(writeable.length); + if (writeable.length > 0) logStream.write(redactUpstreamSecret(writeable)); + }; + /** Write the carried tail, so the file ends on a complete line. */ + const flushLog = (): void => { + if (!logActive || redactionCarry.length === 0) return; + const tail = redactUpstreamSecret(redactionCarry); + redactionCarry = ""; + logStream.write(tail); + }; + /** * Outcome of each `finish()` call, oldest first. * @@ -818,11 +900,11 @@ export class UpstreamProcess { // The log file is the exposure path: the readiness scan below keeps the // raw chunk (it has to parse the password out of it), the copy on disk // must not contain it. - if (logActive) logStream.write(redactUpstreamSecret(chunk)); + writeLog(chunk); if (!settled) inspect(chunk, stdout); }); child.stderr.on("data", (chunk: string) => { - if (logActive) logStream.write(redactUpstreamSecret(chunk)); + writeLog(chunk); // The stderr ring buffer is fed for the whole lifetime of the child, not // only while waiting for readiness: an operator needs the reason a // long-running server died, not just the reason a start failed. @@ -832,8 +914,18 @@ export class UpstreamProcess { if (!settled) inspect(chunk, stderr); }); - child.once("error", (error) => finish(error)); + // A failed spawn emits `error` and `close`, never `exit`: without this the + // log descriptor stayed open and the dead child stayed in + // `#liveChildren`, where the exit hook would later `kill()` the stale + // handle for the lifetime of the process. + child.once("error", (error) => { + this.#liveChildren.delete(child); + flushLog(); + logStream.end(); + finish(error); + }); child.once("exit", (code, signal) => { + flushLog(); logStream.end(); const wasHandedOff = outcomes.shift() ?? false; if (!settled) { diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index dcd6682..93d6888 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -516,6 +516,10 @@ export class SessionStore { } catch { /* no persisted state yet */ } + // A file written under a higher cap (or a lowered + // `OPENCODE_SESSION_MAX_ENTRIES`) used to stay above the maximum until the + // next successful commit, so `session_entries` over-reported the cap. + this.#evictIfNeeded(); } #scheduleSave(): void { @@ -649,19 +653,20 @@ function restoreRecord(value: unknown, now: number, ttlMs: number): SessionRecor * under the same root but are disambiguated by the prefix check in `acquire`. */ export function deriveKey(input: AcquireInput): string { - return createHash("sha256") - .update( - JSON.stringify({ - model: input.model, - agent: input.agent, - variant: input.variant ?? null, - tools: input.toolsHash, - permissions: input.permissionProfile, - root: input.messages[0] ?? null, - }), - ) - .digest("hex") - .slice(0, 32); + // The root message is embedded as *raw* JSON, exactly where + // `JSON.stringify({ …, root })` would have put it, so keys stay identical to + // the ones written by earlier versions while the message itself is serialised + // at most once (see `messageJson`). + const root = input.messages[0]; + const rootJson = root === undefined ? "null" : serialiseMessage(root); + const head = + `{"model":${JSON.stringify(input.model)},` + + `"agent":${JSON.stringify(input.agent)},` + + `"variant":${JSON.stringify(input.variant ?? null)},` + + `"tools":${JSON.stringify(input.toolsHash)},` + + `"permissions":${JSON.stringify(input.permissionProfile)},` + + `"root":`; + return createHash("sha256").update(head + rootJson + "}").digest("hex").slice(0, 32); } /** @@ -686,14 +691,16 @@ const messageJson = new WeakMap(); * byte-identical to stringifying the array. Persisted prefix hashes and session * keys therefore stay compatible with hashes written by earlier versions. */ +function serialiseMessage(message: InternalMessage): string { + const cached = messageJson.get(message); + if (cached !== undefined) return cached; + const json = JSON.stringify(message); + messageJson.set(message, json); + return json; +} + function serialiseMessages(messages: InternalMessage[]): string { - const parts = messages.map((message) => { - const cached = messageJson.get(message); - if (cached !== undefined) return cached; - const json = JSON.stringify(message); - messageJson.set(message, json); - return json; - }); + const parts = messages.map((message) => serialiseMessage(message)); return `[${parts.join(",")}]`; } diff --git a/test/adapter-proposals.test.ts b/test/adapter-proposals.test.ts new file mode 100644 index 0000000..b852acb --- /dev/null +++ b/test/adapter-proposals.test.ts @@ -0,0 +1,249 @@ +/** + * Regression tests for the adapter and orchestrator findings of the last + * improvement round. Every test here fails without its fix. + */ +import { afterEach, describe, expect, it } from "vitest"; +import { buildServer } from "../src/server.js"; +import type { AppContext } from "../src/context.js"; +import { ApiError } from "../src/errors.js"; +import { EMPTY_USAGE, type CompletionEvent } from "../src/types/internal.js"; +import { createTestContext, parseSseJson, testConfig } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "opencode/deepseek-v4.1-flash-free"; +const PNG = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + +afterEach(() => { + delete process.env["OPENCODE_REASONING_FIELD"]; +}); + +describe("A2: streamed chat adopts a consolidated reasoning summary", () => { + it("emits reasoning_content for a turn that only reports reasoning_end", async () => { + const ctx = createTestContext({ + script: () => [ + { kind: "start", sessionId: "ses_1", messageId: "msg_1", model: MODEL, agent: "build", reasoningEnabled: true, reusedSession: false }, + { kind: "reasoning_end", text: "weighing the options", ordinal: 0 }, + { kind: "text_delta", text: "Answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: { ...EMPTY_USAGE, inputTokens: 1, outputTokens: 1, totalTokens: 2 }, messageId: "msg_1" }, + ], + }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "hi" }], stream: true }, + }); + + const reasoning = parseSseJson<{ choices: Array<{ delta: Record }> }>(response.body) + .flatMap((frame) => frame.json.choices) + .map((choice) => String(choice.delta["reasoning_content"] ?? "")) + .join(""); + expect(reasoning).toBe("weighing the options"); + }); + + it("emits only the unseen suffix when deltas already streamed part of it", async () => { + const ctx = createTestContext({ + script: () => [ + { kind: "start", sessionId: "ses_1", messageId: "msg_1", model: MODEL, agent: "build", reasoningEnabled: true, reusedSession: false }, + { kind: "reasoning_delta", text: "think", ordinal: 0 }, + { kind: "reasoning_end", text: "thinking hard", ordinal: 0 }, + { kind: "text_delta", text: "Answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: { ...EMPTY_USAGE, inputTokens: 1, outputTokens: 1, totalTokens: 2 }, messageId: "msg_1" }, + ], + }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "hi" }], stream: true }, + }); + + const reasoning = parseSseJson<{ choices: Array<{ delta: Record }> }>(response.body) + .flatMap((frame) => frame.json.choices) + .map((choice) => String(choice.delta["reasoning_content"] ?? "")) + .join(""); + expect(reasoning).toBe("thinking hard"); + }); +}); + +describe("A3: the responses stream closes the orchestrator generator", () => { + it("closes the generator when the turn fails before the head is committed", async () => { + const base = createTestContext(); + let closes = 0; + const ctx: AppContext = { + ...base, + completion: { + ...base.completion, + // The orchestrator's cleanup is a `finally`, so an unclosed generator + // means the sticky-session record is never released. + run: async function* (): AsyncGenerator { + try { + yield { kind: "error", error: ApiError.unavailable("the upstream refused the turn") }; + } finally { + closes += 1; + } + }, + }, + }; + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", stream: true }, + }); + + expect(response.statusCode).toBeGreaterThanOrEqual(400); + expect(closes).toBe(1); + }); + + it("closes the generator when the turn fails after the head is committed", async () => { + const base = createTestContext(); + let closes = 0; + const ctx: AppContext = { + ...base, + completion: { + ...base.completion, + run: async function* (): AsyncGenerator { + try { + yield { kind: "start", sessionId: "ses_1", messageId: "msg_1", model: MODEL, agent: "build", reasoningEnabled: false, reusedSession: false }; + yield { kind: "text_delta", text: "partial", ordinal: 0 }; + yield { kind: "error", error: ApiError.unavailable("the stream broke") }; + } finally { + closes += 1; + } + }, + }, + }; + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(200); + expect(closes).toBe(1); + }); +}); + +describe("A5: /v1/responses rejects the fields it cannot honour", () => { + it("rejects max_tool_calls instead of dropping it", async () => { + const ctx = createTestContext({ script: () => [] }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", max_tool_calls: 1 }, + }); + + expect(response.statusCode).toBe(400); + expect(response.json()).toMatchObject({ error: { code: "unsupported_parameter", param: "max_tool_calls" } }); + }); + + it("rejects prompt_cache_key and safety_identifier", async () => { + const ctx = createTestContext({ script: () => [] }); + const app = await buildServer(ctx); + for (const field of ["prompt_cache_key", "safety_identifier"]) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", [field]: "value" }, + }); + expect(response.statusCode).toBe(400); + expect(response.json()).toMatchObject({ error: { param: field } }); + } + }); +}); + +describe("A6: the Anthropic surface treats `null` as unset", () => { + it("accepts null optional fields on /v1/messages", async () => { + const ctx = createTestContext({ + script: () => [ + { kind: "start", sessionId: "ses_1", messageId: "msg_1", model: MODEL, agent: "build", reasoningEnabled: false, reusedSession: false }, + { kind: "text_end", text: "ok", ordinal: 0, messageId: "msg_1" }, + { kind: "end", finishReason: "stop", usage: { ...EMPTY_USAGE, inputTokens: 1, outputTokens: 1, totalTokens: 2 }, messageId: "msg_1" }, + ], + }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/messages", + headers: { ...AUTH, "anthropic-version": "2023-06-01" }, + payload: { + model: MODEL, + max_tokens: 64, + messages: [{ role: "user", content: "hi" }], + system: null, + tools: null, + tool_choice: null, + thinking: null, + metadata: null, + stop_sequences: null, + temperature: null, + }, + }); + + expect(response.statusCode).toBe(200); + }); + + it("still rejects a null required field", async () => { + const ctx = createTestContext({ script: () => [] }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/messages", + headers: { ...AUTH, "anthropic-version": "2023-06-01" }, + payload: { model: MODEL, max_tokens: 64, messages: null }, + }); + + expect(response.statusCode).toBe(400); + }); + + it("accepts null optional fields on /v1/messages/count_tokens", async () => { + const ctx = createTestContext({ script: () => [] }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/messages/count_tokens", + headers: { ...AUTH, "anthropic-version": "2023-06-01" }, + payload: { model: MODEL, messages: [{ role: "user", content: "hi" }], system: null, tools: null, thinking: null }, + }); + + expect(response.statusCode).toBe(200); + }); +}); + +describe("M5: a large legal body is not turned into a 500 by `push(...)`", () => { + it("resolves a message list with more sources than the engine argument limit", async () => { + const { resolveMessageMedia } = await import("../src/adapter/openai/chat.js"); + const { createMediaBudget } = await import("../src/media/resolve.js"); + // One count slot: every source but the first is omitted before it is dialed, + // so the case stays offline and fast while still building the full list. + const config = testConfig({ maxAttachments: 1, maxAttachmentBytes: 1_000_000 }); + // One message carrying more parts than the engine's argument limit: the + // per-message source array is what `push(...)` used to spread. + const drafts = [ + { + message: { role: "user" as const, text: "hi" }, + sources: Array.from({ length: 140_000 }, (_unused, index) => + index === 0 ? { dataUri: `data:image/png;base64,${PNG}` } : { url: "ftp://invalid.invalid/a.png" }, + ), + }, + ]; + + const messages = await resolveMessageMedia(drafts, config, { + signal: new AbortController().signal, + budget: createMediaBudget({ maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }), + field: "messages", + }); + + expect(messages).toHaveLength(1); + }, 30_000); +}); diff --git a/test/admin.test.ts b/test/admin.test.ts index 834ce0c..81bf832 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -180,10 +180,10 @@ describe("rate limiting", () => { }); it("never touches the exempt paths, even with a drained bucket", async () => { - // `docs/API.md` and the README promise that `/`, `/health`, `/ready`, - // `/healthz` and `/metrics` are not rate limited. Drain the credential-less - // bucket first (burst 1, so the eleventh request is certainly over budget), - // then prove the probes still answer. + // `docs/API.md` and the README promise that `/`, `/health`, `/ready` and + // `/healthz` are not rate limited. Drain the credential-less bucket first + // (burst 1, so the eleventh request is certainly over budget), then prove + // the probes still answer. const ctx = createTestContext({ config: { rateLimitRpm: 1, rateLimitBurst: 1, allowNoAuth: true, metricsEnabled: true, metricsPublic: true }, }); @@ -199,11 +199,16 @@ describe("rate limiting", () => { if (index === 10) expect(throttled.statusCode).toBe(429); } - for (const url of ["/", "/health", "/healthz", "/metrics"]) { + for (const url of ["/", "/health", "/healthz"]) { const response = await app.inject({ method: "GET", url }); expect(response.statusCode, `${url} must not be rate limited`).toBe(200); } + // `/metrics` is charged to the same bucket (H1): an anonymous scraper must + // not be able to walk every collector without limit. + const metrics = await app.inject({ method: "GET", url: "/metrics" }); + expect(metrics.statusCode).toBe(429); + // `/ready` may answer 503 when no catalogue is cached; what matters is // that the limiter never answers 429 for it. const ready = await app.inject({ method: "GET", url: "/ready" }); diff --git a/test/completion.test.ts b/test/completion.test.ts index b6f5681..9b22cd3 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -312,6 +312,31 @@ describe("collectCompletion", () => { expect(result.finishReason).toBe("tool_calls"); }); + it("filters the tool envelope out of a consolidated text_end", async () => { + // A bridged turn whose text arrives only through `session.text.ended`: the + // consolidated text is the *raw* step text, so yielding it verbatim made + // every consumer's "adopt only when longer" rule fire and leaked the + // internal marker into `content` next to the parsed `tool_calls`. + const envelope = `${TOOL_CALL_OPEN}{"name":"get_weather","arguments":{"city":"Hanoi"}}${TOOL_CALL_CLOSE}`; + const turn = (): OpencodeEvent[] => [ + event("session.step.started", { assistantMessageID: "msg_a1", agent: "build", model: { providerID: "opencode", id: "seaglass-alpha-free" }, started: 0 }), + event("session.text.ended", { assistantMessageID: "msg_a1", ordinal: 0, text: envelope }), + event("session.step.ended", { assistantMessageID: "msg_a1", finish: "stop", tokens: { input: 100, output: 5, reasoning: 0, cache: { read: 10, write: 0 } } }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]; + const options: Partial = { tools: [WEATHER], toolChoice: "auto" }; + + const collected = await collectCompletion(request(options), harness(() => turn()).deps); + expect(collected.text).toBe(""); + expect(collected.calls).toHaveLength(1); + + const streamed: string[] = []; + for await (const item of runCompletion(request(options), harness(() => turn()).deps)) { + if (item.kind === "text_end") streamed.push(item.text); + } + expect(streamed.join("")).not.toContain(TOOL_CALL_OPEN); + }); + it("forwards the tool protocol in the prompt", async () => { const { deps, promptCalls } = harness(() => simpleTurn("ok")); await collectCompletion( diff --git a/test/docs-consistency.test.ts b/test/docs-consistency.test.ts index 553feaf..a62a403 100644 --- a/test/docs-consistency.test.ts +++ b/test/docs-consistency.test.ts @@ -36,7 +36,7 @@ function read(relativePath: string): string { * suffix is optional so the plain `env()` reads count too, and `\b` plus the * lowercase spelling keeps `warnInvalidEnv("...")` out of the set. */ -const ENV_READ = /\benv(?:Str|OptStr|Int|Bool|List)?\(\s*"([A-Z][A-Z0-9_]*)"/g; +const ENV_READ = /\benv(?:Str|OptStr|Int|Bool|List|LogLevel)?\(\s*"([A-Z][A-Z0-9_]*)"/g; /** A token that reads as an environment-variable name in documentation. */ const DOCUMENTED_NAME = /\b(?:OPENCODE_[A-Z0-9_]+|HOST|PORT)\b/g; @@ -252,3 +252,34 @@ describe("the metric documentation (docs/API.md)", () => { expect(undocumented).toEqual([]); }); }); + +describe("the documented fallbacks and error rows (D1-D3)", () => { + it("names the wire type of the 499 row", () => { + const row = read("docs/API.md") + .split(/\r?\n/) + .find((line) => line.startsWith("| `499`")); + expect(row, "docs/API.md has no 499 row").toBeDefined(); + expect(row).toContain("`api_error`"); + expect(row).toContain("`timeout_error`"); + }); + + it("ships a deny-first OPENCODE_AGENT_PERMISSIONS example", () => { + const line = read(".env.example") + .split(/\r?\n/) + .find((entry) => entry.includes("OPENCODE_AGENT_PERMISSIONS=")); + expect(line, ".env.example has no OPENCODE_AGENT_PERMISSIONS example").toBeDefined(); + expect(line).not.toContain('"effect":"allow"'); + expect(line).toContain('"effect":"deny"'); + }); + + it("documents a warning for every unrecognised value class", () => { + const documentation = read("docs/CONFIGURATION.md"); + for (const pattern of [ + /Boolean values accept[\s\S]{0,400}?warning/, + /Integer values must be[\s\S]{0,400}?warning/, + /OPENCODE_REASONING_DEFAULT` and `OPENCODE_LOG_LEVEL`[\s\S]{0,400}?warning/, + ]) { + expect(documentation, String(pattern)).toMatch(pattern); + } + }); +}); diff --git a/test/http-proposals.test.ts b/test/http-proposals.test.ts new file mode 100644 index 0000000..d12b14d --- /dev/null +++ b/test/http-proposals.test.ts @@ -0,0 +1,404 @@ +/** + * HTTP, auth and configuration findings from `IMPROVEMENT_PROPOSALS.md` + * (H1-H11, D1-D3). + * + * Every test drives the real Fastify app through `buildServer(ctx)` and + * `app.inject()`; no socket is ever bound. The configuration cases resolve a + * fresh `Config` from the environment, and the two cases that observe internal + * call counts (`H4`, `H10`) use a counting request double or the `node:crypto` + * spy, because the property under test is not visible on the wire. + */ +import { readFileSync } from "node:fs"; +import os from "node:os"; +import type { FastifyRequest } from "fastify"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { extractApiKey, isAuthorized, requestPath } from "../src/auth.js"; +import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; +import { chargeFailedAuth, createRateLimiters } from "../src/http/rateLimit.js"; +import { appendVary, buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; + +/** A `node:crypto` spy recording every `timingSafeEqual` call. */ +const cryptoProbe = vi.hoisted(() => ({ calls: [] as Array<{ left: number; right: number }> })); + +vi.mock("node:crypto", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + timingSafeEqual: (left: Buffer, right: Buffer): boolean => { + cryptoProbe.calls.push({ left: left.length, right: right.length }); + return actual.timingSafeEqual(left, right); + }, + }; +}); + +/** Variables a test changed, with their original value, restored after each test. */ +const savedEnv = new Map(); + +function setEnv(name: string, value: string | undefined): void { + if (!savedEnv.has(name)) savedEnv.set(name, process.env[name]); + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + resetConfigCache(); +} + +/** Resolve a configuration without memoising it, so no test can poison the cache. */ +function resolve(overrides: Partial = {}): Config { + return loadConfig({ + dataDir: os.tmpdir(), + workdir: os.tmpdir(), + metricsEnabled: false, + ...overrides, + } as Partial); +} + +function read(relativePath: string): string { + return readFileSync(new URL(relativePath, import.meta.url), "utf8"); +} + +afterEach(() => { + for (const [name, value] of savedEnv) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + savedEnv.clear(); + resetConfigCache(); + vi.restoreAllMocks(); +}); + +// ---------------------------------------------------------------------- H1 --- + +describe("H1 /metrics is charged to the api bucket", () => { + it("throttles an anonymous scrape loop but keeps the liveness probes exempt", async () => { + const ctx = createTestContext({ + config: { metricsEnabled: true, metricsPublic: true, rateLimitRpm: 1, rateLimitBurst: 1 }, + }); + const app = await buildServer(ctx); + try { + const first = await app.inject({ method: "GET", url: "/metrics" }); + expect(first.statusCode).toBe(200); + + const second = await app.inject({ method: "GET", url: "/metrics" }); + expect(second.statusCode).toBe(429); + expect((second.json() as { error: { type: string } }).error.type).toBe("rate_limit_error"); + + for (const url of ["/", "/health", "/healthz"]) { + const probe = await app.inject({ method: "GET", url }); + expect(probe.statusCode, `${url} must stay exempt`).toBe(200); + } + } finally { + await app.close(); + } + }); +}); + +// ---------------------------------------------------------------------- H2 --- + +describe("H2 the failed-auth limiter keeps a per-address bucket and adds a global ceiling", () => { + it("does not let one address spend everyone else's budget", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + for (let index = 0; index < 10; index += 1) { + const attempt = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + remoteAddress: "198.51.100.10", + }); + expect(attempt.statusCode, `attempt ${index}`).toBe(401); + } + + const exhausted = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + remoteAddress: "198.51.100.10", + }); + expect(exhausted.statusCode).toBe(429); + + // Another address still gets its own budget: a single host cannot lock out + // the deployment, which is what a lone shared bucket would do. + const fresh = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + remoteAddress: "198.51.100.20", + }); + expect(fresh.statusCode).toBe(401); + } finally { + await app.close(); + } + }); + + it("bounds aggregate failed-auth work across every address", () => { + const limiters = createRateLimiters(createTestContext().config); + const attempt = (address: string): (() => void) => () => chargeFailedAuth(limiters, { + ip: address, + } as unknown as FastifyRequest); + + // Every attempt comes from a fresh address, so the per-address bucket never + // rejects: only the global ceiling can. The ceiling refills while the loop + // runs, so the bound is `burst` plus a margin rather than exactly `burst`. + let rejection: string | undefined; + for (let index = 0; index < limiters.authGlobal.burst + 50; index += 1) { + const address = `198.51.${Math.floor(index / 250)}.${index % 250}`; + try { + attempt(address)(); + } catch (error) { + rejection = error instanceof Error ? error.message : String(error); + break; + } + } + + expect(rejection, "the global ceiling never rejected an attempt").toMatch(/across all addresses/); + }); +}); + +// ---------------------------------------------------------------------- H3 --- + +describe("H3 extractApiKey accepts only the documented Basic form", () => { + it("rejects a password, a colon-less value and an empty username", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + const basic = (value: string): { authorization: string } => ({ + authorization: `Basic ${Buffer.from(value, "utf8").toString("base64")}`, + }); + try { + const accepted = await app.inject({ method: "GET", url: "/v1/models", headers: basic("test-key:") }); + expect(accepted.statusCode).toBe(200); + + for (const value of ["test-key", ":test-key", "test-key:password", "user:pass"]) { + const rejected = await app.inject({ method: "GET", url: "/v1/models", headers: basic(value) }); + expect(rejected.statusCode, `base64(${value})`).toBe(401); + } + } finally { + await app.close(); + } + }); +}); + +// ---------------------------------------------------------------------- H4 --- + +describe("H4 key comparison uses fixed-width digests and no short-circuit", () => { + it("hashes every configured key and compares 32-byte digests", () => { + const config = createTestContext().config; + const keyed = { ...config, apiKeys: Object.freeze(["test-key", "alpha", "beta"]) } as Config; + + cryptoProbe.calls.length = 0; + expect(isAuthorized(keyed, "test-key")).toBe(true); + // The matching key is first: `Array.prototype.some` would stop here. + expect(cryptoProbe.calls).toHaveLength(3); + for (const call of cryptoProbe.calls) { + expect(call.left, "digests must be fixed width").toBe(32); + expect(call.right, "digests must be fixed width").toBe(32); + } + + cryptoProbe.calls.length = 0; + expect(isAuthorized(keyed, "nope")).toBe(false); + expect(cryptoProbe.calls).toHaveLength(3); + }); +}); + +// ---------------------------------------------------------------------- H5 --- + +describe("H5 OPENCODE_TRUST_PROXY rejects a /0 prefix", () => { + it("warns and falls back to false instead of trusting every peer", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + for (const value of ["10.0.0.0/0", "0.0.0.0/0", "::/0"]) { + warn.mockClear(); + setEnv("OPENCODE_TRUST_PROXY", value); + expect(resolve().trustProxy, value).toBe(false); + expect(warn, value).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0]), value).toContain("OPENCODE_TRUST_PROXY"); + } + + // A real prefix still compiles. + warn.mockClear(); + setEnv("OPENCODE_TRUST_PROXY", "10.0.0.0/8"); + expect(resolve().trustProxy).toEqual(["10.0.0.0/8"]); + expect(warn).not.toHaveBeenCalled(); + }); +}); + +// ---------------------------------------------------------------------- H6 --- + +describe("H6 invalid booleans and reasoning defaults warn", () => { + it("names the variable for an unrecognised boolean", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS", "fals"); + + expect(resolve().toolBridgeDenyNativeTools).toBe(true); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS"); + }); + + it("names the variable for an unrecognised reasoning default", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS", undefined); + setEnv("OPENCODE_REASONING_DEFAULT", "alway"); + + expect(resolve().reasoningDefault).toBe("on-request"); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_REASONING_DEFAULT"); + }); + + it("stays quiet for a valid value", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_REASONING_DEFAULT", undefined); + setEnv("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS", "off"); + + expect(resolve().toolBridgeDenyNativeTools).toBe(false); + expect(warn).not.toHaveBeenCalled(); + }); +}); + +// ---------------------------------------------------------------------- H7 --- + +describe("H7 OPENCODE_LOG_LEVEL is validated", () => { + it("falls back to info with a warning for an unknown level", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_LOG_LEVEL", "verbose"); + + expect(resolve().logLevel).toBe("info"); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_LOG_LEVEL"); + }); + + it("accepts every documented pino level, case-insensitively", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + for (const level of ["trace", "debug", "info", "warn", "error", "fatal"]) { + setEnv("OPENCODE_LOG_LEVEL", level.toUpperCase()); + expect(resolve().logLevel, level).toBe(level); + } + expect(warn).not.toHaveBeenCalled(); + }); +}); + +// ---------------------------------------------------------------------- H8 --- + +describe("H8 isAnthropicSurface compares the path exactly", () => { + it("answers an unmatched /v1/messagesfoo with the OpenAI error shape", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "POST", url: "/v1/messagesfoo", headers: AUTH }); + expect(response.statusCode).toBe(404); + + const body = response.json() as { type?: string; error?: { type?: string; code?: string } }; + expect(body.type, "the Anthropic envelope has a top-level type").toBeUndefined(); + expect(body.error?.code).toBe("not_found_error"); + } finally { + await app.close(); + } + }); + + it("keeps the Anthropic envelope on the real surface", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "POST", url: "/v1/messages/count_tokens", headers: AUTH }); + expect(response.statusCode).not.toBe(404); + } finally { + await app.close(); + } + }); +}); + +// ---------------------------------------------------------------------- H9 --- + +describe("H9 the CORS hook appends to an existing vary header", () => { + it("unions the existing value with origin", () => { + expect(appendVary(undefined, "origin")).toBe("origin"); + expect(appendVary("accept-encoding", "origin")).toBe("accept-encoding, origin"); + expect(appendVary("Accept-Encoding, origin", "origin")).toBe("Accept-Encoding, origin"); + expect(appendVary(["accept-encoding", "origin"], "origin")).toBe("accept-encoding, origin"); + }); + + it("still sets vary on a cross-origin response", async () => { + const ctx = createTestContext({ config: { corsOrigins: ["*"] } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/health", headers: { origin: "https://app.example" } }); + expect(response.headers["vary"]).toBe("origin"); + } finally { + await app.close(); + } + }); +}); + +// --------------------------------------------------------------------- H10 --- + +describe("H10 the path and the presented key are memoised per request", () => { + it("reads the url and the authorization header once each", () => { + const reads = { url: 0, authorization: 0 }; + const request = { + get url(): string { + reads.url += 1; + return "/v1/models?refresh=1"; + }, + get headers(): Record { + return { + get authorization(): string { + reads.authorization += 1; + return "Bearer test-key"; + }, + }; + }, + } as unknown as FastifyRequest; + + expect(requestPath(request)).toBe("/v1/models"); + expect(extractApiKey(request)).toBe("test-key"); + expect(requestPath(request)).toBe("/v1/models"); + expect(extractApiKey(request)).toBe("test-key"); + + expect(reads.url).toBe(1); + expect(reads.authorization).toBe(1); + }); +}); + +// --------------------------------------------------------------------- H11 --- + +describe("H11 the error handler has no identity no-op", () => { + it("uses apiError.status directly", () => { + const source = read("../src/server.ts"); + expect(source).not.toContain("apiError.status === 499"); + expect(source).toContain("reply.status(apiError.status)"); + }); +}); + +// ------------------------------------------------------------------ D1-D3 --- + +describe("D1-D3 the documentation matches the code", () => { + it("names the wire type of the 499 row", () => { + const row = read("../docs/API.md") + .split(/\r?\n/) + .find((line) => line.startsWith("| `499`")); + expect(row, "docs/API.md has no 499 row").toBeDefined(); + expect(row).toContain("`api_error`"); + expect(row).toContain("`timeout_error`"); + }); + + it("ships a deny-first permission example", () => { + const line = read("../.env.example") + .split(/\r?\n/) + .find((entry) => entry.includes("OPENCODE_AGENT_PERMISSIONS=")); + expect(line, ".env.example has no OPENCODE_AGENT_PERMISSIONS example").toBeDefined(); + expect(line).not.toContain('"effect":"allow"'); + expect(line).toContain('"effect":"deny"'); + }); + + it("documents a warning for booleans, integers, the reasoning default and the log level", () => { + const documentation = read("../docs/CONFIGURATION.md"); + for (const pattern of [ + /Boolean values accept[\s\S]{0,400}?warning/, + /Integer values must be[\s\S]{0,400}?warning/, + /OPENCODE_REASONING_DEFAULT` and `OPENCODE_LOG_LEVEL`[\s\S]{0,400}?warning/, + ]) { + expect(documentation, String(pattern)).toMatch(pattern); + } + }); +}); \ No newline at end of file diff --git a/test/media-proposals.test.ts b/test/media-proposals.test.ts new file mode 100644 index 0000000..51cbf5d --- /dev/null +++ b/test/media-proposals.test.ts @@ -0,0 +1,274 @@ +/** + * Regression tests for the accepted media findings (M1, M2, M3, M4, M6). + * + * Every test in this file fails against the unfixed `src/media/resolve.ts`. The + * upstream is fully scripted through `createTestContext`, so no live OpenCode + * server is needed; the only socket is a loopback fixture that serves one PNG. + */ +import { execFileSync } from "node:child_process"; +import fsp from "node:fs/promises"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; +import { ApiError } from "../src/errors.js"; +import { + createMediaBudget, + resolveAttachment, + resolveAttachments, + setMediaLogger, + type MediaSource, +} from "../src/media/resolve.js"; +import { buildServer } from "../src/server.js"; +import type { InternalRequest } from "../src/types/internal.js"; +import { createTestContext } from "./helpers/context.js"; + +/** 1x1 transparent PNG. */ +const PNG_BASE64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; +const PNG_BUFFER = Buffer.from(PNG_BASE64, "base64"); + +const AUTH = { authorization: "Bearer test-key" }; + +/** Loopback fixture servers left open by a test. */ +const servers: http.Server[] = []; + +afterEach(() => { + vi.restoreAllMocks(); + setMediaLogger(undefined); +}); + +afterAll(async () => { + while (servers.length > 0) { + const server = servers.pop(); + if (server) await new Promise((resolve) => server.close(() => resolve())); + } +}); + +function config(overrides: Partial = {}): Config { + resetConfigCache(); + return loadConfig({ + dataDir: os.tmpdir(), + workdir: os.tmpdir(), + logLevel: "silent", + metricsEnabled: false, + ...overrides, + } as Partial); +} + +/** Serve one PNG on loopback and return its base URL. */ +async function servePng(): Promise { + const server = http.createServer((request, response) => { + if (request.url === "/a.png") { + response.writeHead(200, { "content-type": "image/png", "content-length": String(PNG_BUFFER.byteLength) }); + response.end(PNG_BUFFER); + return; + } + response.writeHead(404, { "content-type": "text/plain" }); + response.end("not found"); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +} + +/** Resolve a source and return the `ApiError` it rejected with. */ +async function mediaFailure(source: MediaSource, options: Config): Promise { + try { + await resolveAttachment(source, options); + } catch (error) { + if (error instanceof ApiError) return error; + throw error; + } + throw new Error("expected the media resolution to fail"); +} + +/** A base64 source of exactly `bytes` decoded bytes. */ +function sizedSource(bytes: number): MediaSource { + return { base64: Buffer.alloc(bytes, "A").toString("base64"), mime: "text/plain" }; +} + +describe("M1: a non-regular local file is rejected before open()", () => { + let workspace: string; + + beforeAll(async () => { + workspace = await fsp.mkdtemp(path.join(os.tmpdir(), "opencode-api-media-m1-")); + await fsp.writeFile(path.join(workspace, "image.png"), PNG_BUFFER); + }); + + afterAll(async () => { + await fsp.rm(workspace, { recursive: true, force: true }); + }); + + it.skipIf(process.platform === "win32")("refuses a FIFO without opening it", async () => { + const fifo = path.join(workspace, "pipe"); + execFileSync("mkfifo", [fifo]); + // `open()` on a FIFO blocks the libuv threadpool until a writer appears, so + // the spy refuses the open outright: the assertion is that it is never called. + const openSpy = vi.spyOn(fsp, "open").mockRejectedValue( + Object.assign(new Error("ENXIO: no such device or address"), { code: "ENXIO" }), + ); + + try { + const error = await mediaFailure( + { path: fifo }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ); + + expect(error.code).toBe("invalid_attachment"); + expect(error.status).toBe(400); + expect(openSpy).not.toHaveBeenCalled(); + // The transport detail stays server-side (SEC-02). + expect(error.message).not.toContain("ENXIO"); + } finally { + openSpy.mockRestore(); + await fsp.rm(fifo, { force: true }); + } + }); + + it("still reads a regular file inside the root", async () => { + const attachment = await resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ); + + expect(attachment.mime).toBe("image/png"); + expect(attachment.size).toBe(PNG_BUFFER.byteLength); + }); +}); + +describe("M2: the encoded-length bound ignores whitespace", () => { + it("accepts a MIME-wrapped payload that decodes within the cap", async () => { + const limit = 1024; + const encoded = Buffer.alloc(limit, "A").toString("base64"); + const wrapped = encoded.match(/.{1,76}/g)?.join("\r\n") ?? ""; + const maxEncoded = Math.ceil((limit * 4) / 3) + 4; + + // The raw length is over the bound while the payload itself is not: this is + // the ~1.4 % window the fix reclaims. + expect(wrapped.length).toBeGreaterThan(maxEncoded); + expect(wrapped.replace(/\s+/g, "").length).toBeLessThanOrEqual(maxEncoded); + + const fromBase64 = await resolveAttachment( + { base64: wrapped, mime: "text/plain" }, + config({ maxAttachmentBytes: limit }), + ); + expect(fromBase64.size).toBe(limit); + + const fromDataUri = await resolveAttachment( + { dataUri: `data:text/plain;base64,${wrapped}` }, + config({ maxAttachmentBytes: limit }), + ); + expect(fromDataUri.size).toBe(limit); + }); + + it("still refuses a payload that cannot fit even without whitespace", async () => { + const limit = 64; + const maxEncoded = Math.ceil((limit * 4) / 3) + 4; + const payload = "A".repeat(maxEncoded + 1); + + await expect( + resolveAttachment({ base64: payload, mime: "text/plain" }, config({ maxAttachmentBytes: limit })), + ).rejects.toMatchObject({ code: "attachment_too_large", status: 400 }); + }); +}); + +describe("M3: a count slot is released when byte admission fails", () => { + it("keeps the third source admissible after the second is dropped for bytes", async () => { + const budget = createMediaBudget({ maxCount: 2, maxBytes: 1000 }); + const result = await resolveAttachments( + [sizedSource(900), sizedSource(900), sizedSource(50)], + config({ maxAttachmentBytes: 1000 }), + { budget, concurrency: 1 }, + ); + + expect(result.attachments.map((attachment) => attachment.size)).toEqual([900, 50]); + expect(result.omitted).toEqual([{ index: 1, reason: "bytes" }]); + expect(budget.usedCount).toBe(2); + expect(budget.usedBytes).toBe(950); + }); +}); + +describe("M4: an empty file_data does not shadow a file_url", () => { + it("resolves the URL when the base64 payload is empty", async () => { + const base = await servePng(); + + const attachment = await resolveAttachment( + { base64: "", url: `${base}/a.png` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), + ); + + expect(attachment.mime).toBe("image/png"); + expect(attachment.data).toBe(PNG_BASE64); + }); + + it("accepts an input_file with an empty file_data through /v1/responses", async () => { + const base = await servePng(); + let captured: InternalRequest | undefined; + const ctx = createTestContext({ + config: { allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }, + onRun: (request) => (captured = request), + }); + const app = await buildServer(ctx); + + try { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "what is in this image?" }, + { type: "input_file", file_data: "", file_url: `${base}/a.png` }, + ], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured?.messages[0]?.attachments?.map((attachment) => attachment.mime)).toEqual(["image/png"]); + } finally { + await app.close(); + } + }); +}); + +describe("M6: ENXIO and ENODEV map to the 400 path", () => { + let workspace: string; + + beforeAll(async () => { + workspace = await fsp.mkdtemp(path.join(os.tmpdir(), "opencode-api-media-m6-")); + await fsp.writeFile(path.join(workspace, "image.png"), PNG_BUFFER); + }); + + afterAll(async () => { + await fsp.rm(workspace, { recursive: true, force: true }); + }); + + it.each(["ENXIO", "ENODEV"])("maps %s from a non-regular file to 400 invalid_attachment", async (code) => { + const openSpy = vi + .spyOn(fsp, "open") + .mockRejectedValue(Object.assign(new Error(`${code}: no such device or address`), { code })); + + try { + const error = await mediaFailure( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ); + + expect(error.code).toBe("invalid_attachment"); + expect(error.status).toBe(400); + // The errno is transport detail: it never reaches the caller. + expect(error.message).not.toContain(code); + } finally { + openSpy.mockRestore(); + } + }); +}); \ No newline at end of file diff --git a/test/upstream-proposals.test.ts b/test/upstream-proposals.test.ts new file mode 100644 index 0000000..3806afe --- /dev/null +++ b/test/upstream-proposals.test.ts @@ -0,0 +1,608 @@ +/** + * Regression tests for the accepted upstream findings U1-U5 and U8-U10. + * + * Every test drives the real modules through the documented seams only: + * `UpstreamProcessOptions` (`spawn` / `probe` / `findBinary` / `discover`), + * `EventHubOptions.idleTimeoutMs`, `OpencodeClientOptions.catalogueTimeoutMs` + * and `createTestContext` from `test/helpers/context.ts`. No live OpenCode + * server and no network access is needed. + */ +import { createHash } from "node:crypto"; +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Config } from "../src/config.js"; +import type { InternalMessage } from "../src/types/internal.js"; +import { createLogger } from "../src/logger.js"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; +import { OpencodeClient } from "../src/upstream/client.js"; +import { EventHub } from "../src/upstream/events.js"; +import { UpstreamProcess, type SpawnedChild } from "../src/upstream/process.js"; +import { SessionStore, deriveKey } from "../src/upstream/sessions.js"; +import { createTestContext, testConfig } from "./helpers/context.js"; + +/** Stand-in for a spawned `opencode serve` child. */ +class FakeChild extends EventEmitter { + readonly pid: number; + readonly stdout = new PassThrough(); + readonly stderr = new PassThrough(); + readonly signals: NodeJS.Signals[] = []; + exitCode: number | null = null; + + constructor( + pid: number, + /** A child that survives every signal, so only the exit path reaps it. */ + private readonly stubborn = false, + ) { + super(); + this.pid = pid; + } + + kill(signal: NodeJS.Signals = "SIGTERM"): boolean { + this.signals.push(signal); + if (this.exitCode !== null) return false; + if (this.stubborn) return true; + this.exitCode = signal === "SIGTERM" ? 0 : null; + // A real child reports its exit asynchronously. + setImmediate(() => this.emit("exit", this.exitCode, signal)); + return true; + } + + /** Simulate an unexpected death (no signal from the gateway). */ + crash(): void { + if (this.exitCode !== null) return; + this.exitCode = 1; + this.emit("exit", 1, null); + } +} + +interface HarnessOptions { + /** Write the readiness lines at all (false simulates a failed start). */ + ready?: boolean; + /** How long the scripted child waits before reporting readiness. */ + readyMs?: number; + /** + * Write this text to stderr in these pieces, as separate chunks. + * + * The pieces are written on separate turns of the event loop: a stream with + * no reader coalesces two synchronous writes into one chunk, which would hide + * a marker split across a chunk boundary. + */ + stderrChunks?: string[]; + upstreamStartTimeoutMs?: number; + /** Explicit upstream server; bypasses the spawn path. */ + upstreamUrl?: string; + /** Fail the spawn with this error instead of reporting readiness. */ + spawnError?: string; + /** Keep the child alive through every signal. */ + stubborn?: boolean; +} + +interface Harness { + process: UpstreamProcess; + children: FakeChild[]; + config: Config; + metrics: Metrics; + dataDir: string; +} + +const tempDirs: string[] = []; + +function harness(options: HarnessOptions = {}): Harness { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-proposals-")); + tempDirs.push(dataDir); + const children: FakeChild[] = []; + const config = testConfig({ + dataDir, + workdir: dataDir, + upstreamAutostart: true, + upstreamStartTimeoutMs: options.upstreamStartTimeoutMs ?? 2_000, + ...(options.upstreamUrl === undefined ? {} : { upstreamUrl: options.upstreamUrl }), + }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + const spawnError = options.spawnError; + + const process = new UpstreamProcess(config, log, metrics, { + findBinary: () => path.join(dataDir, "opencode"), + discover: async () => undefined, + spawn: (_command, args) => { + const child = new FakeChild(4_000 + children.length, options.stubborn === true); + children.push(child); + const port = args[args.indexOf("--port") + 1] ?? "0"; + const url = `http://127.0.0.1:${port}`; + const pieces = options.stderrChunks ?? []; + for (const [index, piece] of pieces.entries()) { + if (piece.length === 0) continue; + if (index === 0) child.stderr.write(piece); + else setTimeout(() => child.stderr.write(piece), index * 10); + } + if (spawnError !== undefined) { + setImmediate(() => child.emit("error", new Error(spawnError))); + } else if (options.ready !== false) { + const announce = (): void => { + child.stdout.write(`server listening on ${url}\n`); + child.stdout.write("server password fake-password\n"); + }; + const readyMs = options.readyMs ?? 0; + if (readyMs === 0) setImmediate(announce); + else setTimeout(announce, readyMs); + } else { + // Fail the start: the child exits before reporting readiness. + setImmediate(() => child.crash()); + } + return child as unknown as SpawnedChild; + }, + }); + + return { process, children, config, metrics, dataDir }; +} + +const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 10)); + +/** Read a file once the async write stream behind it has flushed. */ +async function readFileEventually(file: string): Promise { + for (let attempt = 0; attempt < 100; attempt += 1) { + if (fs.existsSync(file)) { + const text = fs.readFileSync(file, "utf8"); + if (text.length > 0) return text; + } + await tick(); + } + return ""; +} + +async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return; + await tick(); + } + throw new Error("timed out waiting for condition"); +} + +/** Resolve and return the rejection reason. */ +async function resolveFailure(target: UpstreamProcess): Promise { + return (await target.resolve().catch((reason: unknown) => reason)) as Error; +} + +/** A client over a scripted `UpstreamProcess` that records lifecycle calls. */ +function clientOver(url: string, catalogueTimeoutMs = 5_000): OpencodeClient { + const ctx = createTestContext({ config: { upstreamRequestTimeoutMs: 5_000 } }); + const upstream = { + resolve: async () => ({ url, password: undefined, source: "env" as const }), + markStale: () => undefined, + reprobe: () => undefined, + } as unknown as UpstreamProcess; + return new OpencodeClient(upstream, ctx.config, ctx.log, ctx.metrics, { catalogueTimeoutMs }); +} + +/** + * A server that answers with `status` and a body it never finishes. + * + * The body stays unread unless the client consumes or cancels it, which is what + * makes an uncancelled early return observable as a connection that never + * closes. + */ +async function stallingServer( + status: number, + body: string, +): Promise<{ url: string; closedCount: () => number; close: () => Promise }> { + let closed = 0; + const server = http.createServer((_request, response) => { + response.on("close", () => { + closed += 1; + }); + response.writeHead(status, { "content-type": "application/json" }); + response.write(body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${address.port}`, + closedCount: () => closed, + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +interface EventFixture { + hub: EventHub; + connectionCount: () => number; + closedCount: () => number; + close: () => Promise; +} + +const eventFixtures: EventFixture[] = []; +const servers: Array<{ close: () => Promise }> = []; + +/** Start a fake `/api/event` server and point an EventHub at it. */ +async function eventFixture( + handle: (response: http.ServerResponse, connection: number) => void, + options: { idleTimeoutMs?: number } = {}, +): Promise { + let connections = 0; + let closed = 0; + const server = http.createServer((request, response) => { + if (!request.url?.startsWith("/api/event")) { + response.writeHead(404); + response.end(); + return; + } + connections += 1; + const connection = connections; + response.on("close", () => { + closed += 1; + }); + handle(response, connection); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + + const config = testConfig(); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + const upstream = { + resolve: async () => ({ url: `http://127.0.0.1:${address.port}`, password: undefined, source: "env" as const }), + } as unknown as UpstreamProcess; + const hub = new EventHub(upstream, config, log, metrics, { + ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }), + }); + + const fixture: EventFixture = { + hub, + connectionCount: () => connections, + closedCount: () => closed, + close: async () => { + await hub.stop(); + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; + eventFixtures.push(fixture); + return fixture; +} + +/** + * The `process` `exit` hook the first spawn of this file installs. + * + * `UpstreamProcess` registers it with `process.once("exit", …)` exactly once per + * process, so the listener is recorded as it is registered instead of being + * picked out of `process.listeners("exit")` (which also holds unrelated + * listeners). + */ +const exitHooks: Array<() => void> = []; +const originalProcessOnce = process.once; +process.once = function (event: string | symbol, listener: (...args: unknown[]) => void) { + if (event === "exit") exitHooks.push(listener as () => void); + return originalProcessOnce.call(process, event, listener); +} as unknown as typeof process.once; + +function exitHook(): (() => void) | undefined { + return exitHooks[exitHooks.length - 1]; +} + +afterEach(async () => { + while (eventFixtures.length > 0) { + const fixture = eventFixtures.pop(); + if (fixture) await fixture.close(); + } + while (servers.length > 0) { + const server = servers.pop(); + if (server) await server.close(); + } + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); + } + vi.restoreAllMocks(); +}); + +// ------------------------------------------------------------------------ U1 --- + +describe("U1 log-file redaction across a chunk boundary", () => { + it("masks a password marker the child's pipe split across two chunks", async () => { + const { process, config, dataDir } = harness({ + readyMs: 100, + stderrChunks: ["server pass", "word super-secret\n"], + }); + + await process.resolve(); + // The child's exit is what flushes and closes the log file. + await process.stop(); + + // Per-chunk redaction missed the split marker, so the plaintext credential + // was appended to the log file, which has no read-time pass. + const logFile = path.join(dataDir, "logs", `opencode-${config.upstreamPort}.log`); + const written = await readFileEventually(logFile); + expect(written).toContain("server password [redacted]"); + expect(written).not.toContain("super-secret"); + }); +}); + +// ------------------------------------------------------------------------ U2 --- + +describe("U2 response bodies are cancelled on early-return paths", () => { + it("cancels the body when /api/event rejects the connection", async () => { + const fixture = await eventFixture((response) => { + response.writeHead(401, { "content-type": "application/json" }); + response.write('{"message":"unauthorized"}'); + }); + + fixture.hub.start(); + // Two attempts: the hub reconnects to a rejecting upstream forever, so an + // unread body per attempt would exhaust the descriptor table. + await waitFor(() => fixture.connectionCount() >= 2); + expect(fixture.closedCount()).toBeGreaterThanOrEqual(1); + }); + + it("cancels the body the readiness probe never reads", async () => { + const target = await stallingServer(500, '{"error":"boom"}'); + servers.push(target); + const { process } = harness({ upstreamUrl: target.url }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unreachable" }); + + // `#probe` classifies on the status alone; without `body.cancel()` the + // socket stayed open with an unread body. + await waitFor(() => target.closedCount() >= 1, 1_500); + }); + + it("cancels the body of a 401 from a client call", async () => { + const target = await stallingServer(401, '{"message":"unauthorized"}'); + servers.push(target); + const client = clientOver(target.url); + + await expect(client.listModels()).rejects.toMatchObject({ code: "upstream_unauthorized" }); + + // The 401 branch threw before `response.text()`, leaving the body unread. + await waitFor(() => target.closedCount() >= 1, 1_500); + }); +}); + +// ------------------------------------------------------------------------ U3 --- + +describe("U3 spawn error releases the log descriptor and the child entry", () => { + it("ends the log stream and drops the child from the live set", async () => { + const create = vi.spyOn(fs, "createWriteStream"); + const { process, children } = harness({ spawnError: "spawn EACCES" }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + + // A failed spawn emits `error` and `close`, never `exit`: the descriptor + // used to stay open for the lifetime of the process. + const stream = create.mock.results[0]?.value as unknown as fs.WriteStream | undefined; + expect(stream?.writableEnded).toBe(true); + + const child = children[0]; + expect(child).toBeDefined(); + const signalsBefore = child?.signals.length ?? 0; + + // The dead child used to stay in `#liveChildren`, so the exit hook called + // `kill()` on the stale handle. + await process.shutdown(); + expect(child?.signals.length).toBe(signalsBefore); + }); +}); + +// ------------------------------------------------------------------------ U4 --- + +describe("U4 a deliberate stop() is not a start failure", () => { + it("clears the failure bookkeeping so the next resolve is not backed off", async () => { + const { process, children } = harness({ ready: false, upstreamStartTimeoutMs: 150 }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + expect(children).toHaveLength(1); + + await process.stop(); + + // The accumulated window used to reject the caller's own next resolve with + // `retrying in N ms` although nothing had been retried yet. + const second = await resolveFailure(process); + expect(second.message).not.toContain("failed to start"); + expect(children).toHaveLength(2); + }); +}); + +// ------------------------------------------------------------------------ U5 --- + +describe("U5 reconnect delay stays inside its documented cap", () => { + it("clamps the doubling at MAX_RECONNECT_DELAY_MS", async () => { + const fixture = await eventFixture((response) => { + response.writeHead(200, { "content-type": "text/event-stream" }); + response.write('data: {"id":"e0","type":"server.connected","data":{}}\n\n'); + // End the body immediately: a flapping upstream. + setImmediate(() => response.end()); + }); + + fixture.hub.start(); + expect(await fixture.hub.ensureConnected(2_000)).toBe(true); + + // 250 + 500 + 1_000 + 2_000 ms of backoff before the value reaches 4_000. + await waitFor(() => fixture.hub.reconnectDelayMs >= 4_000, 15_000); + // One more cycle: doubling 4_000 used to produce 8_000, above the cap. + await waitFor(() => fixture.hub.reconnectDelayMs > 4_000, 15_000); + expect(fixture.hub.reconnectDelayMs).toBe(5_000); + }); + + it("resets the accumulated delay in stop()", async () => { + const fixture = await eventFixture((response) => { + response.writeHead(200, { "content-type": "text/event-stream" }); + response.write('data: {"id":"e0","type":"server.connected","data":{}}\n\n'); + setImmediate(() => response.end()); + }); + + fixture.hub.start(); + expect(await fixture.hub.ensureConnected(2_000)).toBe(true); + await waitFor(() => fixture.hub.reconnectDelayMs >= 500, 5_000); + + await fixture.hub.stop(); + + // The delay used to survive `stop()`, so the first turn after a restart + // waited the accumulated backoff instead of 250 ms. + expect(fixture.hub.reconnectDelayMs).toBe(250); + }); +}); + +// ------------------------------------------------------------------------ U8 --- + +describe("U8 the entry cap is enforced while loading", () => { + it("evicts restored records above sessionMaxEntries", () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-cap-")); + tempDirs.push(dataDir); + const config = testConfig({ sessionPersist: true, dataDir, sessionMaxEntries: 2 }); + const now = Date.now(); + const records: Record = {}; + for (let index = 0; index < 5; index += 1) { + const key = `root-${index}`; + const sessionId = `ses_${index}`; + records[`${key}:${sessionId}`] = { + key, + sessionId, + model: "opencode/big-pickle", + agent: "build", + prefixHash: "abc", + deliveredCount: 1, + createdAt: now, + lastUsedAt: now - index, + permissionProfile: "default", + toolsHash: "none", + busy: false, + reusedCount: 0, + }; + } + fs.writeFileSync( + path.join(dataDir, "sessions.json"), + JSON.stringify({ version: 1, fingerprint: config.instanceId, records }), + "utf8", + ); + + const sessions = new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); + + // `#load()` used to restore every record and only `commit()` evicted, so the + // cache stayed above the cap until the next successful turn. + expect(sessions.size()).toBe(2); + expect(sessions.list()).toHaveLength(2); + }); +}); + +// ------------------------------------------------------------------------ U9 --- + +describe("U9 the process-exit registry is pruned", () => { + it("removes the instance on the terminal shutdown path", async () => { + const { process, children } = harness({ stubborn: true }); + await process.resolve(); + + // Drop the handle but keep the child in `#liveChildren`: only the exit path + // can reap a child that survives every signal. + process.markStale("test stale server"); + const child = children[0]; + expect(child?.exitCode).toBeNull(); + + await process.shutdown(); + const signalsBefore = child?.signals.length ?? 0; + const hook = exitHook(); + expect(hook).toBeTypeOf("function"); + + // The instance used to stay in the static set for the lifetime of the + // process, so the exit hook kept killing its (already dead) children. + hook?.(); + expect(child?.signals.length).toBe(signalsBefore); + }); +}); + +// ----------------------------------------------------------------------- U10 --- + +describe("U10 the retained upstream error body is bounded", () => { + it("truncates the body on ApiError to 500 characters", async () => { + const server = http.createServer((_request, response) => { + response.writeHead(500, { "content-type": "application/json" }); + response.end("x".repeat(4_000)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + const close = async (): Promise => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }; + servers.push({ close }); + const client = clientOver(`http://127.0.0.1:${address.port}`); + + const error = (await client.listModels().catch((reason: unknown) => reason)) as Error & { + upstreamBody?: string; + }; + + expect(error.upstreamBody?.length).toBe(500); + }); +}); + +describe("U7: deriveKey reuses the memoised root message JSON", () => { + it("hashes exactly the JSON the inline object produced", () => { + const root: InternalMessage = { + role: "user", + text: "Hello", + attachments: [{ kind: "image", mime: "image/png", data: "AAAA" }], + }; + const input = { + key: "", + fresh: false, + model: "opencode/seaglass-alpha-free", + agent: "build", + variant: "high", + messages: [root], + toolsHash: "abc123", + permissionProfile: "bridge", + }; + + const expected = createHash("sha256") + .update( + JSON.stringify({ + model: input.model, + agent: input.agent, + variant: input.variant, + tools: input.toolsHash, + permissions: input.permissionProfile, + root, + }), + ) + .digest("hex") + .slice(0, 32); + + expect(deriveKey(input)).toBe(expected); + }); + + it("hashes a missing root message as null", () => { + const input = { + key: "", + fresh: false, + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [], + toolsHash: "none", + permissionProfile: "default", + }; + + const expected = createHash("sha256") + .update( + JSON.stringify({ + model: input.model, + agent: input.agent, + variant: null, + tools: input.toolsHash, + permissions: input.permissionProfile, + root: null, + }), + ) + .digest("hex") + .slice(0, 32); + + expect(deriveKey(input)).toBe(expected); + }); +});