diff --git a/.dockerignore b/.dockerignore index e3f3aeb..c01eae0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,3 +13,15 @@ test .env .env.* !.env.example + +# Local credential and tooling files. A remote/cloud build uploads the whole +# context before the Dockerfile is evaluated, so these must never be sent even +# though the current Dockerfile copies explicit paths only. +.npmrc +*.pem +*.key +*.p12 +.netrc +.git-credentials +coverage +.vscode diff --git a/.env.example b/.env.example index d4cb301..5e66783 100644 --- a/.env.example +++ b/.env.example @@ -9,20 +9,24 @@ # cp .env.example .env # # The gateway loads `.env` from the project root (and from the working directory) -# automatically at startup. Every variable below is read by `src/config.ts`; -# the values shown are the built-in defaults. +# automatically at startup. Every variable below is read by `src/config.ts`; the +# uncommented values are the built-in defaults and the commented lines are +# examples or optional settings. # --------------------------------------------------------------------------- # Authentication # --------------------------------------------------------------------------- # API keys callers must present. The gateway accepts them from # `Authorization: Bearer `, `x-api-key: ` or -# `Authorization: Basic `. +# `Authorization: Basic `. A bare value in `Authorization` with no +# scheme is not accepted. # # Default: sk-dummy-123. When neither OPENCODE_API_KEYS nor OPENCODE_API_KEY is # set, the gateway uses that built-in development key and logs a warning, so it # starts out of the box. It is public knowledge — anyone who can reach the port -# can use it. Replace it before exposing the gateway beyond localhost. +# can use it. Replace it before exposing the gateway beyond localhost: the +# gateway refuses to start when the built-in key is still in use on a +# non-loopback HOST. # # Comma-separated list. Generate a strong key with: # node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))" @@ -35,6 +39,11 @@ OPENCODE_API_KEYS=sk-dummy-123 # Set to true to disable authentication entirely. Only for a trusted loopback host. # OPENCODE_ALLOW_NO_AUTH=false +# Optional operator credential tier: when this list is non-empty, `/admin/*` +# requires one of these keys and no longer accepts a general API key. Unset keeps +# today's behaviour (any configured API key can call the admin routes). +# OPENCODE_ADMIN_API_KEYS= + # --------------------------------------------------------------------------- # HTTP listener # --------------------------------------------------------------------------- @@ -46,9 +55,17 @@ PORT=20123 # inflates the body by ~33%, so keep this above OPENCODE_MAX_ATTACHMENT_BYTES. # OPENCODE_MAX_BODY_BYTES=67108864 -# Trust `x-forwarded-*` headers from a reverse proxy. Enable only behind one. +# Trust `x-forwarded-*` headers from a reverse proxy. Accepts `true` (every hop), +# a positive hop count (`1` = the immediate peer only), or a comma-separated list +# of trusted IPs/CIDRs. Enable only behind a proxy you control that overwrites the +# forwarded headers: with a plain `true` the client address, and therefore the +# per-address rate-limit bucket, is caller-controlled. # OPENCODE_TRUST_PROXY=false +# Wall-clock budget for receiving one request body. A caller that never finishes +# sending is disconnected once it expires. Streamed responses are unaffected. +# OPENCODE_BODY_TIMEOUT_MS=300000 + # Comma-separated CORS allow-list. `*` allows every origin. # OPENCODE_CORS_ORIGINS= @@ -63,7 +80,8 @@ PORT=20123 # In-process rate limit per authenticated API key. RPM is requests per minute; # BURST is the bucket capacity (0 derives max(1, ceil(rpm / 6))). RPM=0 disables # the limiter. /admin/* uses a separate bucket. Rejections answer 429 with a -# retry-after header. +# retry-after header. Failed authentication is throttled separately (at least 60 +# attempts per minute per client address) even when the limiter is disabled here. # OPENCODE_RATE_LIMIT_RPM=0 # OPENCODE_RATE_LIMIT_BURST=0 diff --git a/README.md b/README.md index cd98d54..b73a8ef 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ When nothing is found the request fails with: | `GET` | `/health` | Liveness plus upstream readiness snapshot (public). | | `GET` | `/ready` | Readiness from cached state: `200` only when an upstream server is resolved and a model catalog is already cached (public, never calls upstream). | | `GET` | `/healthz` | Minimal liveness alias (public). | -| `GET` | `/metrics` | Prometheus exposition (requires a key unless `OPENCODE_METRICS_PUBLIC=true`). | +| `GET` | `/metrics` | Prometheus exposition (requires a key unless `OPENCODE_METRICS_PUBLIC=true` is set **and** no `OPENCODE_METRICS_TOKEN` is configured). | | `GET` | `/admin/status` | Config, upstream, catalog and session-cache snapshot. | | `GET` | `/admin/config` | The effective configuration, with secrets redacted. | | `POST` | `/admin/models/refresh` | Force a model catalog reload. | @@ -219,7 +219,7 @@ curl -N http://127.0.0.1:20123/v1/chat/completions \ ``` ``` -data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]} +data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]} data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"content":"One"},"finish_reason":null}]} @@ -472,9 +472,11 @@ model_disabled`. Query `GET /v1/models` instead of guessing. | `HOST` / `PORT` | `127.0.0.1` / `20123` | Listen address. | | `OPENCODE_API_KEYS` | `sk-dummy-123` | Accepted caller keys (comma separated). Replace the built-in default before exposing the port. | | `OPENCODE_ALLOW_NO_AUTH` | `false` | Start without keys (dangerous). | +| `OPENCODE_ADMIN_API_KEYS` | *(unset)* | Operator keys accepted on `/admin/*`; when set, general API keys are rejected there. | | `OPENCODE_METRICS_TOKEN` | *(unset)* | Dedicated scrape token for `GET /metrics`; configuring it keeps that endpoint authenticated even with `OPENCODE_METRICS_PUBLIC=true`. | +| `OPENCODE_BODY_TIMEOUT_MS` | `300000` | Wall-clock budget for receiving one request body; a streaming response is never cut short by it. | | `OPENCODE_RATE_LIMIT_RPM` | `0` (disabled) | Per-minute request budget per API key; `0` turns rate limiting off. | -| `OPENCODE_RATE_LIMIT_BURST` | `0` (disabled) | Burst capacity allowed on top of the per-minute budget. | +| `OPENCODE_RATE_LIMIT_BURST` | `0` | Burst capacity allowed on top of the per-minute budget; `0` derives `max(1, ceil(rpm/6))`. The limiter is off only when `OPENCODE_RATE_LIMIT_RPM=0`. | | `OPENCODE_CORS_ORIGINS` | *(empty)* | Browser origins allowed to call the gateway; `*` allows every origin. | | `OPENCODE_SERVER_URL` / `OPENCODE_SERVER_PASSWORD` | *(unset)* | Explicit upstream server. | | `OPENCODE_AUTOSTART` | `true` | Spawn a private `opencode serve`. | @@ -517,7 +519,10 @@ Every variable, with types, defaults and security notes: `tokens_total`, `completions_total`, `active_streams`, `upstream_restarts_total`, `session_cache_entries`, `event_stream_connected`, `event_stream_reconnects_total`, `event_frames_dropped_total`, `rate_limit_rejections_total`, plus process - defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true`. `/metrics` is + 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. * **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog counts, session count), `/admin/config` (effective configuration with API keys @@ -558,8 +563,9 @@ Every variable, with types, defaults and security notes: read-only agent, and constrain tools with `OPENCODE_AGENT_PERMISSIONS`. * **The default API key is public.** With no `OPENCODE_API_KEYS` configured the gateway accepts `sk-dummy-123`, which anyone reading this repository knows. - Set your own key before exposing the port; never enable - `OPENCODE_ALLOW_NO_AUTH=true` on a reachable host. + The gateway therefore refuses to start when that key is still accepted on a + non-loopback `HOST`; set your own key before exposing the port, and never + enable `OPENCODE_ALLOW_NO_AUTH=true` on a reachable host. * **Bridged tools do not remove the agent's own tool set.** A session whose client tools are bridged still carries native tool *definitions*; the gateway merely denies their actions, and only when @@ -583,7 +589,14 @@ Every variable, with types, defaults and security notes: traffic without authentication; prefer `OPENCODE_METRICS_TOKEN` and keep the endpoint closed. * Put the gateway behind TLS, keep CORS origins explicit, and do not enable - `OPENCODE_TRUST_PROXY` unless a proxy you control sets the forwarded headers. + `OPENCODE_TRUST_PROXY` unless a proxy you control overwrites the forwarded + headers: with a bare `true` the client address is caller-controlled, which also + makes the per-address rate-limit bucket spoofable. Prefer a hop count + (`OPENCODE_TRUST_PROXY=1`) or a CIDR list. +* **Admin routes restart the world.** `/admin/upstream/restart` kills the shared + upstream (every in-flight turn fails) and `DELETE /admin/sessions` drops the + sticky cache for all callers. Set `OPENCODE_ADMIN_API_KEYS` to keep those routes + away from tenant keys, or restrict them at the proxy. ## Docker usage @@ -607,7 +620,11 @@ docker run --rm -p 20123:20123 \ [docker-compose.yml](docker-compose.yml): ```bash -cp .env.example .env # defaults to OPENCODE_API_KEYS=sk-dummy-123 +cp .env.example .env +# Replace the published default before the container can start: HOST=0.0.0.0 is +# not a loopback address, so the gateway refuses to start while +# OPENCODE_API_KEYS is still sk-dummy-123. +pnpm setup -- --random docker compose up --build ``` diff --git a/docs/API.md b/docs/API.md index d6d5644..7c8269c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -21,7 +21,7 @@ operational; it is summarised at the end of this document and in the README. | Name | Kind | Meaning | | --- | --- | --- | -| `x_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.in_progress`, `response.completed`, `response.failed`): `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on `/v1/chat/completions`. `unapplied` (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order `temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens`; the key is omitted when none were supplied. The `/v1/chat/completions`, `/v1/completions` and Anthropic **streamed** sequences do not carry `x_opencode` (their event schemas have no place for extra message fields); use `stream: false`, or the Responses stream, when you need it. | +| `x_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.in_progress`, `response.completed`, `response.failed`): `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on the two OpenAI completion surfaces (`/v1/chat/completions`, `/v1/completions`). `unapplied` (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order `temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens`; the key is omitted when none were supplied. The Anthropic streamed sequence and the two OpenAI streamed sequences do not carry `x_opencode`; one exception: the Anthropic `message_delta` of a cancelled turn carries `x_opencode: {"interrupted": true}`, because the stop reason alone cannot express the interruption. | | `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session only while the model, agent, variant, tool set, permission profile and message prefix all still match. | | `x-opencode-agent` | request header | Run this request with a specific OpenCode agent instead of `OPENCODE_AGENT`. | | `x-request-id` | request/response header | Caller-supplied correlation id, echoed on every response (JSON and SSE). Accepted when it matches `[A-Za-z0-9._:-]{1,128}`; anything else is replaced by a generated id. The same value is used as the request id in the gateway logs. | @@ -30,13 +30,20 @@ operational; it is summarised at the end of this document and in the README. Authentication is required on every endpoint in the table above. Send one of `Authorization: Bearer `, `x-api-key: `, -`Authorization: Basic `. The default key is **`sk-dummy-123`** when -`OPENCODE_API_KEYS` is not configured; set your own before exposing the gateway. +`Authorization: Basic `. A bare value with no scheme +(`Authorization: `) is rejected. The default key is **`sk-dummy-123`** when +`OPENCODE_API_KEYS` is not configured; set your own before exposing the gateway +(a non-loopback bind refuses to start with that published key). Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs are logged. `/`, `/health`, `/ready` and `/healthz` are exempt (and `/metrics` when `OPENCODE_METRICS_PUBLIC=true` and no `OPENCODE_METRICS_TOKEN` is set, which re-authenticates the endpoint in constant time). +When `OPENCODE_ADMIN_API_KEYS` is configured, `/admin` and `/admin/*` accept only +those keys; a general API key answers `401` there. Failed authentication is +throttled per client address (at least 60 attempts per minute) and answers `429` +with a `retry-after` header once that budget is spent. + > **Reading this reference.** Request fields are validated with `zod`; unknown > JSON fields are ignored, matching the permissive behaviour of the OpenAI and > Anthropic servers. Every field listed below is one the adapters accept and @@ -92,6 +99,7 @@ re-authenticates the endpoint in constant time). | `parallel_tool_calls` | boolean | `true` | `false` makes the tool bridge ask the model for at most one bridged tool call per turn; `true`/absent allows several. | | `response_format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema","json_schema":{name,schema}}`. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. | | `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | `seed`, `logit_bias`, `presence_penalty` and `frequency_penalty` are accepted and recorded, and named in `x_opencode.unapplied` when supplied. `logprobs`/`top_logprobs` are **rejected** with `400 unsupported_parameter` unless they are disabled (`logprobs: false`), because the gateway cannot produce token-level scores. | +| `best_of`, `suffix` | — | — | Rejected with `400 unsupported_parameter` naming the field, like `/v1/completions`: the gateway produces exactly one candidate and does not echo a suffix. An explicit `null` is treated as unset. | | `messages[].content[].image_url.detail` | string | `auto` | Only `"auto"` is accepted; the gateway cannot downscale media, so any other value is `400 unsupported_parameter` with `param: "messages"`. | | `top_logprobs`, `modalities`, `audio`, `prediction`, `store`, `web_search_options`, `functions`, `function_call` | — | — | Rejected with `400 unsupported_parameter` naming the field, because the gateway cannot produce the response shape they ask for. `store: false` and `function_call: "none"` are accepted as no-ops, and `modalities: ["text"]` is accepted. | @@ -229,8 +237,8 @@ data: {"error":{"message":"The upstream completion ended with an error.","type": | `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 | | `501` | `invalid_request_error` | `not_implemented_error` | -| `502` | `api_error` | `upstream_error`, `upstream_unauthorized`, `upstream_invalid_json` | -| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `event_stream_unavailable`, `event_stream_lost` (a mid-turn event-stream reconnect; the answer would have been incomplete) | +| `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) | | `504` | `api_error` | `timeout_error`, `upstream_timeout` | | `500` | `api_error` | `internal_error` — an unexpected gateway failure; the message never contains credentials | @@ -267,12 +275,12 @@ reasoning mapping and tool bridging with the chat endpoint. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `model` | string | — | Required. Same naming rules as chat. | -| `input` | string \| array | — | Required. A plain string, or items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `reasoning`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. | +| `input` | string \| array | — | Required, and a non-empty string or array: `input: []` is `400 invalid_request` with `param: "input"` rather than an empty prompt. Items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `reasoning`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. | | `input[].content` parts | — | — | `input_text`, `output_text`, `summary_text` (text is used), `refusal` (the refusal text is used), `input_image`, `input_file`, `input_audio`, `video_url`. | | `instructions` | string | *(unset)* | Prepended as a `system` turn **and echoed** on the response object. | | `stream` | boolean | `false` | Emit the typed SSE sequence. | | `tools` | array | *(none)* | Flat function tools `{type:"function",name,description,parameters}`. | -| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",name}` | `auto` | Bridged into the prompt; echoed back as `auto`, `none`, `required` or `function:`. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when it names a function the request never declared. | +| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",name}` | `auto` | Bridged into the prompt; echoed back as `auto`, `none`, `required` or `function:`. Anything else (for example `"bogus"` or the `allowed_tools` form) is `400 unsupported_parameter` with `param: "tool_choice"` instead of being silently ignored, and the echo always reflects the validated value. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when it names a function the request never declared. | | `reasoning.effort` | string | *(unset)* | Same ladder as `reasoning_effort`. `reasoning.summary` is echoed only. | | `max_output_tokens`, `temperature`, `top_p`, `metadata`, `truncation` | — | — | Accepted and echoed back; `truncation` defaults to `"disabled"` and is **not applied** (the gateway never trims history), and the other four are echoed but not forwarded to the provider. `metadata` is not logged. `max_output_tokens`, `temperature` and `top_p` are named in `x_opencode.unapplied` when supplied. | | `parallel_tool_calls` | boolean | `true` | Echoed; `false` makes the tool bridge ask for at most one bridged tool call per turn. | @@ -290,6 +298,11 @@ replayed (same policy as `thinking`/`redacted_thinking` on `/v1/messages`). `function_call_output` items become `role: "tool"` turns. An `input_file` part accepts `file_data`/`file_url`; a reference carrying only `file_id` is rejected with `400 unsupported_file_reference` instead of being silently dropped. +A `function_call_output.output` may itself be an array of content parts: the text +parts become the tool turn, and `input_image`/`input_file`/`input_audio` parts +are resolved like any other media and attached to the enclosing user turn, +leaving a `[image: ]` / `[document: ]` marker in the tool text +(the same rule as an Anthropic `tool_result`). ### Response (`stream: false`) @@ -415,8 +428,12 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_.. `output_index: 0` and status `completed`. * The message item occupies `output_index: 1` when a reasoning item precedes it. Text that arrives only in the consolidated `text_end` event still gets its - `output_item.added`/`content_part.added` pair, so `output[0]` always matches - `output_text`. + `output_item.added`/`content_part.added` pair **and** is delivered through the + normal delta channel: the suffix the stream has not seen yet is emitted as + `response.output_text.delta` before `response.output_text.done`, so a client + that accumulates deltas and a client that reads `output_text` always agree. + The same rule applies to `reasoning_end` with + `response.reasoning_summary_text.delta`. * Tool calls are emitted at the end of the stream as `response.output_item.added` (status `in_progress`), one `response.function_call_arguments.delta` carrying the whole argument string, @@ -548,7 +565,7 @@ Anthropic Messages API. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `model` | string | — | Required. Resolved before the response starts (unknown models → `404 not_found_error`). | -| `messages` | array | — | Required, at least one. Roles `user` and `assistant` only. | +| `messages` | array | — | Required, at least one. Roles `user` and `assistant` only. A message whose content is an empty string or whose blocks carry no text, media or tool result is dropped, and a request whose messages all drop that way is `400 invalid_request` with `param: "messages"` rather than an empty prompt. | | `messages[].content` | string \| array | — | Blocks: `text`, `image`, `document`, `audio`, `video`, `tool_use`, `tool_result`, `thinking`, `redacted_thinking`. | | `image` block | `{source}` | — | `{type:"base64",media_type,data}` or `{type:"url",url}`. | | `document` block | `{source, title?, context?}` | — | base64, url, or `{type:"text",data}` for inline plain text (which is folded into the prompt text instead of being fetched). | @@ -561,7 +578,7 @@ Anthropic Messages API. | `stop_sequences` | array of string | *(none)* | Honoured on this surface, on both paths: the visible text is truncated at the first match, `stop_reason` becomes `stop_sequence` and `stop_sequence` names the matched entry. Empty strings are dropped. Only assistant text is matched — never `thinking` output or tool arguments. Generation upstream is **not** interrupted, so `usage.output_tokens` still counts the whole turn and the sticky session is not disturbed. | | `system` | string \| array | *(unset)* | Array form accepts `{type:"text",text}` blocks. Joined with blank lines. | | `stream` | boolean | `false` | Emit the Anthropic SSE sequence. | -| `thinking` | object | *(unset)* | `{type:"enabled",budget_tokens}` or `{type:"disabled"}`. (The adapter validates `budget_tokens`; the non-standard `effort` key is accepted and mapped exactly like the top-level `reasoning_effort`.) | +| `thinking` | object | *(unset)* | `{type:"enabled",budget_tokens}` or `{type:"disabled"}`. `budget_tokens` must be an **integer ≥ 1**, and `type:"enabled"` without it is `400 invalid_request` with `param: "thinking.budget_tokens"`, matching the Anthropic contract. (The non-standard `effort` key is accepted and mapped exactly like the top-level `reasoning_effort`; a request using only `effort` does not need a budget.) | | `reasoning_effort` | string | *(unset)* | Extension: OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | | `tools` | array | *(none)* | `{name,description,input_schema}`. Bridged through the prompt. | | `tool_choice` | `{type:"auto"}` \| `{type:"any"}` \| `{type:"none"}` \| `{type:"tool",name}` | auto | `any` maps to a required call, `tool` to a named call. Any of `auto`, `any` and `tool` additionally accepts `disable_parallel_tool_use: true`, which caps the turn at one tool call. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when a named tool was never declared. | @@ -628,7 +645,7 @@ Anthropic Messages API. ``` event: message_start -data: {"type":"message_start","message":{"id":"msg_...","type":"message","role":"assistant","model":"opencode/deepseek-v4.1-flash-free","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}} +data: {"type":"message_start","message":{"id":"msg_...","type":"message","role":"assistant","model":"opencode/deepseek-v4.1-flash-free","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}} event: content_block_start data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}} @@ -748,8 +765,9 @@ is still resolved, so an unknown model returns `404`. The number is an **approximation**: OpenCode exposes no tokenizer endpoint, so the gateway estimates one token per CJK character and `characters / 4` for the -rest over every message, the system prompt, the -tool-bridge instructions that will be prepended to the real prompt, and the tool +rest over every message, the system prompt, and — only when the tool bridge is +active, so a `tool_choice` that disables tool use charges neither — the +tool-bridge instructions that will be prepended to the real prompt and the tool JSON schemas, plus a small per-message overhead, and never reports less than `1`. Media blocks are not downloaded for this endpoint: an inline `base64` block is charged `ceil(decodedBytes / 750)` bytes-per-token, while a `url` block @@ -896,7 +914,6 @@ Unknown ids return `404`: "service": "opencode-api", "version": "1.0.0", "endpoints": [ - "GET /", "POST /v1/chat/completions", "POST /v1/responses", "POST /v1/completions", @@ -930,19 +947,25 @@ These are not model surfaces; they report or control gateway state. | `GET` | `/ready` | public | `200 {status:"ready", ..., upstream:{ready,source,url,models}}` only when an upstream endpoint is resolved **and** a model catalogue is already cached; otherwise `503 {status:"unavailable", ..., upstream:{ready:false,...,error}}`. Reads cached state only, so an anonymous probe cannot trigger upstream work. Force a refresh with `POST /admin/models/refresh`. | | `GET` | `/healthz` | public | Minimal liveness alias `{status:"ok", service, version}`. | | `GET` | `/metrics` | key or `OPENCODE_METRICS_TOKEN`, unless `OPENCODE_METRICS_PUBLIC=true` **and** no token is configured | Prometheus text exposition (`opencode_api_*`). `404 metrics_disabled` when `OPENCODE_METRICS_ENABLED=false`. | -| `GET` | `/admin/status` | key | Service version, uptime, a config subset, upstream status (URL/pid/last error/`stderrTail` — the last 50 stderr lines of the supervised server), catalogue counts and session-cache counts. | -| `GET` | `/admin/config` | key | The effective configuration, with `auth.apiKeyCount`, `auth.usingDefaultApiKey` and `upstream.passwordConfigured` instead of the secrets themselves. `upstream.url`, timeouts, media limits, session settings and reasoning defaults are included. | -| `POST` | `/admin/models/refresh` | key | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | -| `GET` | `/admin/sessions` | key | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | -| `DELETE` | `/admin/sessions` | key | Drops every cached session; returns `{cleared}`. | -| `POST` | `/admin/upstream/restart` | key | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | +| `GET` | `/admin/status` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Service version, uptime, a config subset, upstream status (URL/pid/last error/`stderrTail` — the last 50 stderr lines of the supervised server, with any `server password` value redacted), catalogue counts and session-cache counts. | +| `GET` | `/admin/config` | admin key | The effective configuration, with `auth.apiKeyCount`, `auth.usingDefaultApiKey` and `upstream.passwordConfigured` instead of the secrets themselves. `upstream.url`, timeouts, media limits, session settings and reasoning defaults are included. | +| `POST` | `/admin/models/refresh` | admin key | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | +| `GET` | `/admin/sessions` | admin key | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | +| `DELETE` | `/admin/sessions` | admin key | Drops every cached session; returns `{cleared}`. | +| `POST` | `/admin/upstream/restart` | admin key | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charged 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. `/health`, `/ready`, `/healthz`, `/metrics` and `/` +`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. +`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 +`stream: true` response, whose socket stays open for the whole turn. + ### Metrics `GET /metrics` exposes the `opencode_api_` series below (Prometheus text format; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7c92bb4..692bd63 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -14,11 +14,11 @@ reach through industry-standard HTTP surfaces: | OpenAI chat | `POST /v1/chat/completions` | | OpenAI responses | `POST /v1/responses` | | OpenAI completions | `POST /v1/completions` (legacy prompt completions) | -| OpenAI models | `GET /v1/models`, `GET /v1/models/{id}` | +| OpenAI models | `GET /v1/models`, `GET /v1/models/{id}`, `GET /v1/models/*` | | OpenAI embeddings | `POST /v1/embeddings` (explicitly unsupported → 501) | | Anthropic messages | `POST /v1/messages` | | Anthropic tokens | `POST /v1/messages/count_tokens` | -| Operations | `GET /health`, `GET /ready`, `GET /metrics`, `/admin/*` | +| Operations | `GET /`, `GET /health`, `GET /ready`, `GET /healthz`, `GET /metrics`, `/admin/*` | Default listen address: `http://127.0.0.1:20123`. @@ -70,7 +70,12 @@ opencode serve --hostname 127.0.0.1 --port * A freshly spawned `opencode serve` answers `/api/model` (and `/api/agent`) with an empty list for a moment after reporting readiness. `ModelRegistry` retries both lists briefly and never caches a catalogue without models, so a cold - gateway cannot serve `model_not_found` for a model that exists. + gateway cannot serve `model_not_found` for a model that exists. A single empty + answer keeps the previous catalogue and rewrites its timestamp so the retry is + not paid on every request, but that retention is **bounded**: once + `OPENCODE_MODEL_CACHE_TTL_MS` has elapsed since the *first* empty answer, the + retained catalogue is dropped and the real (empty) answer is served, so `/ready` + and `/v1/models` cannot report models the upstream no longer offers forever. * Re-verified against **opencode 2.4.3** (2026-12-02): spawn/readiness output, `/api/model`, `/api/provider`, `/api/agent` and the model ids are unchanged from 2.3.2; only the cold-start timing above differs in practice. @@ -246,7 +251,7 @@ must recognise a vanished session and retry on a fresh one; every other upstream ### 4.3 `src/upstream/*` (frozen) ```ts -class UpstreamProcess { resolve(): Promise; status(): UpstreamStatus; invalidate(reason); stop(); shutdown(); markStale(reason) } +class UpstreamProcess { resolve(): Promise; status(): UpstreamStatus; invalidate(reason); reprobe(reason); stop(); shutdown(); markStale(reason) } class OpencodeClient { request(path, options): Promise; listModels(); listProviders(); listAgents(); createSession(payload, options?: { signal?: AbortSignal }); getSession(id); getMessages(id); prompt(id, text, files?, options?: { signal?: AbortSignal }); @@ -275,6 +280,23 @@ replacement instead of retrying a dead URL. A failed start is remembered: after spawn or readiness failure `resolve()` fails fast with `503 upstream_unavailable` for a bounded, exponentially growing window (at most 30 s) instead of respawning once per incoming request, and the window resets after a successful start. +`reprobe(reason)` is the non-destructive variant: it drops the published endpoint +but keeps the child and the URL/password it reported, so the next `resolve()` +re-probes that remembered endpoint (bounded by `#probe`'s own 5 s timeout) and +republishes it when it answers — only a failing re-probe escalates to +`markStale()` and a replacement. `OpencodeClient` uses exactly that split: a +**request timeout** calls `reprobe()`, because a server that is merely slow must +not have the shared child SIGKILLed under every other in-flight turn, while a +**network error** and a `401` still call `markStale()`. `stop()` and `shutdown()` +clear a pending re-probe. + +Endpoint probing classifies the answer as `ok`, `unauthorized` or `absent`: +`200` and `400` count as `ok` (an OpenCode build that rejects an unauthenticated +`/api/model` is still reachable), `401`/`403` are `unauthorized` and produce +`503 upstream_unauthorized` naming `OPENCODE_SERVER_PASSWORD` instead of the +misleading "not reachable", and anything else is `absent`. Discovery accepts only +`ok`, so an unrelated service that happens to answer `401` is never published as +the upstream. Catalogue calls (`listModels`, `listProviders`, `listAgents`) use a short dedicated timeout (`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than the 600 s turn budget. `SessionStore.acquire({ fresh: true })` skips cached @@ -292,17 +314,37 @@ deleted by the session-store eviction hook. `stop()` is deliberately **non-terminal**: `POST /admin/upstream/restart` and the retry paths call `stop()`/`invalidate()` and then `resolve()` again, and -`test/process.test.ts` pins that. `shutdown()` is the terminal variant, used only +`test/process.test.ts` pins that. It also terminates a child that has been spawned +but not yet adopted (a start still inside its readiness window lives only in +`#liveChildren`) and awaits the in-flight start, so an admin restart during a cold +start no longer adopts the very server it was asked to replace. `shutdown()` is +the terminal variant, used only by the process-exit path (`src/http/shutdown.ts`): it awaits an in-flight start, SIGKILLs every child that never reached `#child`, and makes any later `resolve()` reject with `503 upstream_unavailable`. +The entry point registers its SIGINT/SIGTERM/SIGHUP handlers **before** the +upstream warm-up, so a signal during a cold start still runs the bounded shutdown +and kills the child the warm-up already spawned. `process.on("exit")` cannot cover +a signal-terminated process, so it stays a last-chance hook only. + `UpstreamStatus` carries the usual endpoint/binary/last-error fields plus `stderrTail?: string[]` (the last ≤ 50 stderr lines of the supervised child, -cleared on every spawn), which `GET /admin/status` returns unchanged. The child's -stdout/stderr are otherwise inspected through a bounded tail only: once readiness -has been published the pattern scan stops entirely, so a chatty long-lived server -cannot grow the buffer or the per-chunk cost. +cleared on every spawn), which `GET /admin/status` returns with the credential +redacted. The child's stdout/stderr are otherwise inspected through a bounded tail +only: once readiness has been published the pattern scan stops entirely, so a +chatty long-lived server cannot grow the buffer or the per-chunk cost. + +The spawned server's credential must never reach disk or a caller. +`redactUpstreamSecret()` masks `server password ` (and a leaked +`Authorization: Basic `) and is applied to every copy written to +`/logs/opencode-.log`, to the stderr excerpts embedded in a spawn +failure message, to the ring-buffer push and, authoritatively, to +`status().stderrTail` on read. The readiness scan keeps the raw chunk — the +password has to be parsed out of it — and the log stream carries an `'error'` +handler, so a full disk or an unwritable log directory degrades to one warning and +a disabled log file instead of an uncaught exception that kills every in-flight +turn. `/sessions.json` is an envelope `{ version, fingerprint, records }` where `fingerprint` is `Config.instanceId`. A `ses_*` id only exists inside the upstream @@ -315,7 +357,18 @@ means a restart starts with an empty persisted cache. only when it is **longer** than the text accumulated from deltas, so a provider that reports the whole answer in the terminal event (and sends no deltas) is not lost, while a step-level event that repeats a shorter fragment never truncates the -answer. The streamed surfaces apply the same rule independently. +answer. The streamed surfaces apply the same rule independently and emit the +unseen suffix on their own delta channel (`response.output_text.delta` / +`response.reasoning_summary_text.delta`), so a client that accumulates deltas and +one that reads the final payload always agree. + +The per-turn bridge between the shared event hub and a completion is a bounded +queue: `EventQueue` appends in O(1) and drains through a head cursor, and it holds +at most `MAX_QUEUED_EVENTS` (10 000) frames. Past that the frame is dropped and the +turn fails through the existing `event_stream_lost` path — a dropped frame leaves a +gap, so failing is the only honest outcome — and the sticky slot is released in +`finally`. A consumer parked on a slow reader can therefore not grow the heap +without bound. `completions_total` records an outcome for every exit, including failures: `finish_reason` stays within the documented `FinishReason` values and a failure @@ -344,13 +397,23 @@ reasoningFromEffort(v), reasoningFromThinking(obj) // tools.ts TOOL_CALL_OPEN, TOOL_CALL_CLOSE, createToolBridge(tools, choice?, options?: { parallelToolCalls?: boolean }): ToolBridge, -parseAssistantText(text): {text, calls}, parseToolCallBody(body): ToolCall[], +parseAssistantText(text, allowedNames?: Iterable): {text, calls}, +parseToolCallBody(body, allowedNames?: Iterable): ToolCall[], normaliseArguments(args): string, renderTranscript(messages): string, -renderToolResult(message): string, class ToolCallFilter +renderToolResult(message): string, class ToolCallFilter(allowedNames?: Iterable) // `class ToolCallFilter` exposes `get scannedCharacters()`, a diagnostic counter // that pins the linear scan of a bridged tool-call envelope. +// The optional `allowedNames` set is the declared tool list. A bridged call whose +// name is not in it is treated exactly like an unparsable body: it produces no +// call and its text stays visible to the caller. OpenAI and Anthropic can never +// name a function the request did not declare, and the orchestrator forces +// `finish_reason: "tool_calls"` whenever a call was bridged, so without the +// allow-list a hallucinated — or injected — name reached the client as a +// legitimate call. `createToolBridge()` binds the declared names into both +// `createFilter()` and `parse()`. + // `createToolBridge` throws `ApiError.badRequest(..., { code: "invalid_request", // param: "tool_choice" })` when the choice requires a tool call but `tools` is // absent or empty, and when `tool_choice` names a function the request never @@ -383,9 +446,20 @@ export function buildDataUri(attachment: Pick): str export function isPrivateHost(host: string): boolean; export function isWithinRoots(candidate: string, roots: readonly string[]): boolean; +/** + * Diagnostics hook. Media failures are reported to the caller with a fixed + * message class (never the errno, never a URL with userinfo, so a download + * cannot be used as a port-scan oracle); the transport detail goes here. + * `setMediaLogger()` is wired once in `src/index.ts`. + */ +export interface MediaLogger { debug(obj: Record, message: string): void } +export function setMediaLogger(logger: MediaLogger | undefined): void; + // mime.ts export function kindFromMime(mime: string): AttachmentKind; export function sniffMime(buffer: Buffer, fallback?: string): string; +export function isValidMimeType(value: string): boolean; +export function normaliseMimeType(value: string): string | undefined; export function isImage(mime: string): boolean; export function isAudio(mime: string): boolean; export function isVideo(mime: string): boolean; @@ -399,16 +473,27 @@ private/loopback hosts when `config.allowPrivateMediaUrls` is false (the shipped default, so the guard is active out of the box); reject local paths when `config.allowLocalFiles` is false and when the resolved real path is outside `config.allowedFileRoots`; enforce `config.maxAttachmentBytes` while streaming the -download (do not buffer unbounded) and again after reading a local file (the -`stat` size can be stale). When private URLs are blocked the remote download is +download and while reading a local file through the same bounded chunk loop (do +not buffer unbounded; the `stat` size can be stale). When private URLs are blocked +the remote download is dialled with `node:http`/`node:https` and a `lookup` callback pinned to the validated address, so the guard and the connection cannot disagree (DNS -rebinding); redirects are followed manually with per-hop re-validation. The +rebinding); redirects are followed manually with per-hop re-validation, and every +hop body is destroyed before the next hop is validated, so a redirect the scheme +allow-list rejects cannot park a keep-alive socket. Name resolution counts against +`config.mediaFetchTimeoutMs` and the caller's disconnect signal, so a stalled +resolver cannot hold a request past its budget. The download requests `accept-encoding: identity` and rejects any other `content-encoding` with `400 attachment_download_failed`, because the byte caps bound the bytes as received and a compressed body would otherwise be inlined and labelled as media. +A declared MIME value (`media_type`, `mime_type`, or a remote `Content-Type`) is +embedded in the upstream `data:` URI only when it matches the RFC 6838 +`type/subtype` grammar; otherwise the bytes are sniffed and, failing that, labelled +`application/octet-stream`. A value carrying a comma would otherwise turn the +payload into a non-base64 body the receiver never decodes. + `isPrivateHost()` normalises the address itself before classifying it: any IPv6 spelling (full, compressed, IPv4-mapped, IPv4-compatible, dotted tail) is expanded first, then IPv4 is canonicalised, then loopback, RFC1918, link-local, unique-local, @@ -443,7 +528,10 @@ Tool-result media: `tool_result.content` `image`/`document` blocks are resolved through the same `resolveMediaBlock` path and attached to the enclosing **user** turn, because `collectAttachments` forwards user-turn attachments only. The tool message keeps a `[: ]` marker; `is_error: true` adds a `[tool error]` -prefix. +prefix. `/v1/responses` applies the same rule to media inside +`function_call_output.output`: its `input_image`/`input_file`/`input_audio`/ +`video_url` parts go through the shared pool and are attached to a synthetic +**user** turn, while the tool turn keeps the `[: ]` marker. ### 4.6 Surface adapters @@ -520,9 +608,15 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * `await writer.drain()` after the frames of a turn so a slow reader applies backpressure instead of growing an unbounded queue; `drain()` resolves on the socket `drain` event or after `SseWriterOptions.drainTimeoutMs` (default - 5000 ms) when the socket is not backed up, and `writer.closedSignal` is - aborted when the connection dies, so a dead reader stops the producer even - without `createDisconnectSignal()`, + 5000 ms) when the socket is not backed up. When that deadline expires the + reader is gone: the writer sets `stalled`, closes itself, aborts + `closedSignal`, drops every later frame and destroys the socket, so the + producer stops and the connection is released instead of parking frames the + reader will never take. `writer.closedSignal` is aborted when the connection + dies, so a dead reader stops the producer even without + `createDisconnectSignal()`; destroying the socket also fires the + client-disconnect signal every surface watches, so the upstream turn is + interrupted rather than left running. * always `close()` the writer, * increment `ctx.metrics.activeStreams` and decrement it in `finally`. * Tests live in `test/**/*.test.ts` and run with `vitest`. Unit tests must not diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 75080de..33a33e3 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -24,9 +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` | boolean | `false` | Trust `x-forwarded-*` headers for the client address. | Enable only when a proxy you control terminates the connection; otherwise clients can spoof their address in logs and metrics. | +| `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_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 the limiter. `/admin/*` uses its own separate bucket. | 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. 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_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 @@ -36,16 +37,21 @@ variable. (Discovery and the spawned CLI read the variables listed in | `OPENCODE_API_KEYS` | CSV list | `sk-dummy-123` | Keys accepted from callers. When unset, the built-in development key `sk-dummy-123` is used. When the published key is among the accepted keys — either because nothing was configured or because it is listed explicitly, as `.env.example` ships it — a warning is logged at startup and `GET /admin/config` reports `auth.usingDefaultApiKey: true`. When set but empty (`OPENCODE_API_KEYS=","`) the gateway refuses to start instead of silently accepting the public default. | The default key is public knowledge (it ships in `.env.example` and the README). Set your own secret before exposing the port; rotate by listing old and new keys together. | | `OPENCODE_API_KEY` | string | *(unset)* | Single-key alias appended to `OPENCODE_API_KEYS`. | Same as above; convenient for local use only. | | `OPENCODE_ALLOW_NO_AUTH` | boolean | `false` | Accept every caller, ignoring keys. | Full unauthenticated access to every model and to the OpenCode agent. Use only on a trusted loopback host. | +| `OPENCODE_ADMIN_API_KEYS` | CSV list | *(unset)* | Optional operator credential tier. When non-empty, `/admin` and `/admin/*` accept only these keys; a general `OPENCODE_API_KEYS` value is rejected there with `401`. Unset keeps the default behaviour (any accepted API key may call the admin routes). When set but empty (`OPENCODE_ADMIN_API_KEYS=","`) the gateway refuses to start, exactly like `OPENCODE_API_KEYS`. | The admin routes can restart the shared upstream (failing every in-flight turn) and drop the sticky-session cache. Give them a separate secret so a tenant key cannot. | | `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes, so this is only safe when `HOST` is a loopback address; otherwise set `OPENCODE_METRICS_TOKEN` instead of exposing the endpoint anonymously. | | `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). Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs end up in access logs. +`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. +Failed authentication is throttled per client address (at least 60 attempts per +minute) and logged at `warn` without the presented value. `GET /`, `GET /health`, `GET /ready` and `GET /healthz` are always public. `pnpm setup` writes `.env` (keeping `sk-dummy-123`); `pnpm setup -- --random` writes a freshly generated 32-byte secret instead, and `--random --force` replaces an -existing custom key. +existing custom key. The file is created with mode `0600` on POSIX (Windows +ignores the mode). ## Upstream OpenCode server @@ -75,7 +81,7 @@ existing custom key. | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_DATA_DIR` | path | `./.opencode-api` | Gateway state directory: upstream logs, optional session file. | May contain upstream log output; treat as sensitive. | +| `OPENCODE_DATA_DIR` | path | `./.opencode-api` | Gateway state directory: upstream logs, optional session file. | Contains upstream log output and is treated as sensitive; the supervised server's password is redacted before it is written to `/logs/opencode-.log` and before it can appear in an error message or in `GET /admin/status`. Keep the directory private anyway. | | `OPENCODE_SESSION_CACHE` | boolean | `true` | Reuse the OpenCode session that already holds the conversation prefix. | Reuse is strictly prefix-checked; a mismatch replays the conversation on a fresh session. Disable for fully stateless routing. | | `OPENCODE_SESSION_TTL_MS` | integer ≥ 1000 | `1800000` (30 min) | Idle lifetime of a cached session. | Longer lifetimes keep session state in memory longer. | | `OPENCODE_SESSION_MAX` | integer ≥ 1 | `500` | Maximum cached sessions (least recently used are evicted). | — | @@ -111,7 +117,7 @@ section "Vision and media input". | `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` may log prompts and upstream payloads. | +| `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_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. | @@ -141,13 +147,19 @@ The gateway exits with code 1 (before it listens) when: 2. `OPENCODE_MODEL_ALIASES` is set but is not a JSON object of string values; 3. `OPENCODE_API_KEYS` / `OPENCODE_API_KEY` is set but yields no usable key (`OPENCODE_API_KEYS=","`), because silently falling back to the published - default key would leave the operator believing a secret is configured. - -A missing key is **not** fatal: with neither `OPENCODE_API_KEYS` nor -`OPENCODE_API_KEY` set, the gateway starts with the built-in development key -`sk-dummy-123` and logs a warning. The same warning is 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. + default key would leave the operator believing a secret is configured; +4. the published built-in key `sk-dummy-123` is still among the accepted keys + while `HOST` is **not** a loopback address. A gateway reachable from the + network and accepting a key printed in this repository is the one combination + that must never start silently; set a real key (or, for a throwaway trusted + network, `OPENCODE_ALLOW_NO_AUTH=true`). + +A missing key on a loopback host is **not** fatal: with neither +`OPENCODE_API_KEYS` nor `OPENCODE_API_KEY` set, the gateway starts with the +built-in development key `sk-dummy-123` and logs a warning. The same warning is +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. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 161be8f..9799816 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -274,9 +274,10 @@ What changed in the numbers this document quotes: and the Fastify cast at `src/server.ts:65` (both refreshed above). * `test/docs-consistency.test.ts` now enforces three lists that had already drifted once: the environment variables (unchanged), the `GET /` endpoint index - in `docs/API.md` against the routes `src/` registers (19 entries, including - `GET /`, `GET /healthz`, `GET /v1/models/*` and the four `/admin/*` routes the - index had omitted), and every metric series declared in + in `docs/API.md` against the routes `src/` registers (20 entries including + `GET /`, `GET /healthz` and `GET /v1/models/*`, of which `GET /` is served by + the route itself and therefore absent from the index body; the six `/admin/*` + routes the index had once omitted), and every metric series declared in `src/metrics/registry.ts` against `docs/API.md` and `README.md`. What the pass changed, beyond the pre-remediation findings above: @@ -311,7 +312,7 @@ What was re-verified for the pass: | --- | --- | | `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | | `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0 | -| `pnpm test` | **PASS** — 24 files, **542 passed**, 4 skipped | +| `pnpm test` | **PASS** — 25 files, **657 passed**, 5 skipped | | `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0` | | `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — `Test Files 1 passed (1)`, `Tests 11 passed (11)` | | `docker build --tag opencode-api:ci .` | **PASS** — image built from the current tree | diff --git a/scripts/init-env.mjs b/scripts/init-env.mjs index aad3829..bc26d47 100644 --- a/scripts/init-env.mjs +++ b/scripts/init-env.mjs @@ -50,14 +50,22 @@ if (existing !== undefined && !isDefault && !force) { const key = useRandom ? randomBytes(32).toString("base64url") : DEFAULT_API_KEY; const template = existing ?? fs.readFileSync(examplePath, "utf8"); +// `.env` holds the gateway's only credential, so it is written owner-only +// (0600). `mode` is ignored on Windows, which is expected; the explicit chmod +// covers a file that already existed with wider permissions, since `mode` only +// applies at creation time. +const PRIVATE_MODE = 0o600; + if (!KEY_PATTERN.test(template)) { // The file exists but has no OPENCODE_API_KEYS line (empty file, or a .env // written by hand): append it rather than failing. const separator = template.length === 0 || template.endsWith("\n") ? "" : "\n"; - fs.writeFileSync(envPath, `${template}${separator}OPENCODE_API_KEYS=${key}\n`, "utf8"); + fs.writeFileSync(envPath, `${template}${separator}OPENCODE_API_KEYS=${key}\n`, { encoding: "utf8", mode: PRIVATE_MODE }); + fs.chmodSync(envPath, PRIVATE_MODE); console.log(`Wrote ${envPath} (appended OPENCODE_API_KEYS).`); } else { - fs.writeFileSync(envPath, template.replace(KEY_PATTERN, `$1${key}`), "utf8"); + fs.writeFileSync(envPath, template.replace(KEY_PATTERN, `$1${key}`), { encoding: "utf8", mode: PRIVATE_MODE }); + fs.chmodSync(envPath, PRIVATE_MODE); console.log(`Wrote ${envPath}`); } console.log(""); diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 93745fd..5417364 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -12,7 +12,8 @@ * * Environment: * OPENCODE_API_URL base URL of the gateway (default http://127.0.0.1:20123) - * OPENCODE_API_KEY required API key; the script exits 1 when it is missing + * OPENCODE_API_KEY API key to send; defaults to the gateway's built-in + * development key `sk-dummy-123` (a warning is printed) * * Exit code: 0 when every check passes, 1 otherwise. */ @@ -348,7 +349,7 @@ function parseArgs(argv) { "Usage: node scripts/smoke.mjs [--model ] [--embedding-501]\n\n" + " --model model to exercise (default: first entry of GET /v1/models)\n" + " --embedding-501 also assert that POST /v1/embeddings returns 501\n\n" + - "Environment: OPENCODE_API_URL (default http://127.0.0.1:20123), OPENCODE_API_KEY (required)\n", + "Environment: OPENCODE_API_URL (default http://127.0.0.1:20123), OPENCODE_API_KEY (default sk-dummy-123)\n", ); process.exit(0); } else { diff --git a/src/adapter/anthropic/countTokens.ts b/src/adapter/anthropic/countTokens.ts index 9dfb019..5872750 100644 --- a/src/adapter/anthropic/countTokens.ts +++ b/src/adapter/anthropic/countTokens.ts @@ -50,13 +50,21 @@ export function estimateRequestTokens(request: InternalRequest): number { } const conversationTokens = estimateConversationTokens(parts); - const toolTokens = request.tools.reduce( - (total, tool) => - total + estimateTokens(`${tool.name}\n${tool.description ?? ""}\n${JSON.stringify(tool.parameters)}`) + - TOOL_OVERHEAD_TOKENS, - 0, - ); - const bridgeTokens = estimateTokens(createToolBridge(request.tools, request.toolChoice).instructions); + // The bridge decides what `buildPrompt` actually prepends: with + // `tool_choice: "none"` it is inactive, so neither the instructions nor the + // `## Available tools` schema block reach the prompt. Charging the schemas + // regardless made a tool-less turn look 11 tokens more expensive than the + // identical request without `tools`. + const bridge = createToolBridge(request.tools, request.toolChoice); + const toolTokens = bridge.active + ? request.tools.reduce( + (total, tool) => + total + estimateTokens(`${tool.name}\n${tool.description ?? ""}\n${JSON.stringify(tool.parameters)}`) + + TOOL_OVERHEAD_TOKENS, + 0, + ) + : 0; + const bridgeTokens = estimateTokens(bridge.instructions); // Counts are documented as "at least one token", never zero. return Math.max(1, conversationTokens + toolTokens + bridgeTokens); diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 2135733..2b71a11 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -177,7 +177,9 @@ const toolChoiceSchema = z.discriminatedUnion("type", [ const thinkingSchema = z.object({ type: z.enum(["enabled", "disabled"]), - budget_tokens: z.number().optional(), + // The real API requires an integer budget; a negative or fractional value used + // to reach the orchestrator unchanged. + budget_tokens: z.number().int().min(1).optional(), /** Non-standard convenience alias mapped by `reasoningFromThinking()`. */ effort: z.string().optional(), }); @@ -352,6 +354,23 @@ function argumentsFromInput(input: unknown): string { } } +/** + * Reject a `thinking` block the real API would reject. + * + * `type: "enabled"` requires an integer `budget_tokens`; the non-standard + * `effort` alias stays exempt because it is the gateway's own convenience + * spelling. `docs/API.md` §4 documents this rule. + */ +function assertThinkingBudget(thinking: AnthropicRequestInput["thinking"]): void { + if (thinking === undefined || thinking.type !== "enabled") return; + if (thinking.budget_tokens === undefined && thinking.effort === undefined) { + throw ApiError.badRequest( + "`thinking.type: \"enabled\"` requires an integer `budget_tokens` (or the non-standard `effort` alias).", + { code: "invalid_request", param: "thinking.budget_tokens" }, + ); + } +} + /** Image and document blocks carried by a `tool_result` content array. */ function toolResultMediaBlocks(content: ToolResultContent | undefined): ToolResultMediaBlock[] { if (content === undefined || typeof content === "string") return []; @@ -466,6 +485,7 @@ export async function toInternalRequest( body: AnthropicRequestInput, options: ToInternalOptions, ): Promise { + assertThinkingBudget(body.thinking); const messages: InternalMessage[] = []; const systemText = systemToText(body.system); if (systemText.length > 0) messages.push({ role: "system", text: systemText }); @@ -484,6 +504,10 @@ export async function toInternalRequest( for (const message of body.messages) { if (typeof message.content === "string") { + // An empty literal carries nothing, exactly like an empty block array: it + // must not become an empty prompt. Dropping it here lets the check below + // reject a request whose messages are all empty. + if (message.content.trim().length === 0) continue; messages.push({ role: message.role, text: message.content }); continue; } @@ -596,6 +620,17 @@ export async function toInternalRequest( messages.push(...toolResults); } + // Every declared message may be empty (no text, no media, no tool result), and + // the normaliser silently deletes such a turn. That used to prompt the upstream + // with an empty string and answer 200; the documented contract is + // `400 invalid_request` (`docs/API.md` §4). + if (messages.length === 0) { + throw ApiError.badRequest("At least one message must carry text, media or a tool result.", { + code: "invalid_request", + param: "messages", + }); + } + const tools: ToolDefinition[] = (body.tools ?? []).map((tool) => { const definition: ToolDefinition = { name: tool.name, parameters: tool.input_schema }; if (tool.description !== undefined) definition.description = tool.description; @@ -1101,8 +1136,15 @@ async function streamAnthropicMessage( stop_sequence: null, // Kept at zero on purpose: usage is only known once the turn // ends, and the authoritative numbers travel in `message_delta`. - // This is documented in docs/API.md §4. - usage: { input_tokens: 0, output_tokens: 0 }, + // All four fields are present because the official SDK types + // them as non-optional on `message_start` too; this is + // documented in docs/API.md §4. + usage: { + input_tokens: 0, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, }, }, "message_start", diff --git a/src/adapter/common/reasoning.ts b/src/adapter/common/reasoning.ts index bef6c32..68cb643 100644 --- a/src/adapter/common/reasoning.ts +++ b/src/adapter/common/reasoning.ts @@ -33,33 +33,42 @@ export interface ResolveVariantInput { mode: "off" | "on-request" | "always"; } +/** + * Every spelling clients use for a thinking effort, mapped to the ladder. + * + * Hoisted to module scope: `normaliseEffort()` runs for every variant of every + * catalogue entry on `GET /v1/models` and several times per completion, and the + * object literal used to be allocated on every one of those calls. Frozen so a + * stray write cannot corrupt the mapping for the whole process. + */ +const EFFORT_ALIASES: Readonly> = Object.freeze({ + none: "none", + off: "none", + disabled: "none", + false: "none", + minimal: "minimal", + min: "minimal", + lowest: "minimal", + low: "low", + medium: "medium", + mid: "medium", + default: "medium", + normal: "medium", + high: "high", + xhigh: "xhigh", + extrahigh: "xhigh", + veryhigh: "xhigh", + max: "max", + maximum: "max", + highest: "max", +}); + /** Normalise the many spellings clients use for thinking effort. */ export function normaliseEffort(value: string | undefined): Effort | undefined { if (!value) return undefined; const token = value.trim().toLowerCase().replace(/[\s_-]/g, ""); if (token === "") return undefined; - const aliases: Record = { - none: "none", - off: "none", - disabled: "none", - false: "none", - minimal: "minimal", - min: "minimal", - lowest: "minimal", - low: "low", - medium: "medium", - mid: "medium", - default: "medium", - normal: "medium", - high: "high", - xhigh: "xhigh", - extrahigh: "xhigh", - veryhigh: "xhigh", - max: "max", - maximum: "max", - highest: "max", - }; - return aliases[token]; + return EFFORT_ALIASES[token]; } /** Bucket an Anthropic thinking budget into an effort label. */ diff --git a/src/adapter/common/tools.ts b/src/adapter/common/tools.ts index 27e3901..2b7bf53 100644 --- a/src/adapter/common/tools.ts +++ b/src/adapter/common/tools.ts @@ -145,11 +145,15 @@ export function createToolBridge( ].join("\n") : ""; + // The declared names are the only tool-call surface this turn has, so every + // parser the bridge hands out rejects an envelope naming anything else. + const declaredNames = new Set(tools.map((tool) => tool.name)); + return { instructions, active, - createFilter: () => new ToolCallFilter(), - parse: (text: string) => parseAssistantText(text), + createFilter: () => new ToolCallFilter(declaredNames), + parse: (text: string) => parseAssistantText(text, declaredNames), }; } @@ -164,6 +168,19 @@ export class ToolCallFilter { #inCall = false; #scanned = 0; readonly #calls: ToolCall[] = []; + /** + * Names the request declared, or `undefined` when the caller did not say. + * + * A call for a function the request never declared is not a tool call: OpenAI + * and Anthropic can never return one, and forwarding it makes SDK agent loops + * fail with "unknown function". The body is then surfaced as text instead of + * being dropped, which is what the "unparsable body" branch already does. + */ + readonly #allowedNames: ReadonlySet | undefined; + + constructor(allowedNames?: Iterable) { + this.#allowedNames = allowedNames === undefined ? undefined : new Set(allowedNames); + } /** * Characters examined while looking for an envelope marker. @@ -200,7 +217,7 @@ export class ToolCallFilter { this.#bodyTail = ""; this.#inCall = false; input = combined.slice(end + TOOL_CALL_CLOSE.length); - const calls = parseToolCallBody(body); + const calls = parseToolCallBody(body, this.#allowedNames); if (calls.length > 0) { this.#calls.push(...calls); // Drop a trailing code fence the model may have added around the block. @@ -268,8 +285,8 @@ export class ToolCallFilter { } /** Parse an assistant message, extracting any tool-call envelopes. */ -export function parseAssistantText(text: string): ParsedAssistantText { - const filter = new ToolCallFilter(); +export function parseAssistantText(text: string, allowedNames?: Iterable): ParsedAssistantText { + const filter = new ToolCallFilter(allowedNames); const forwarded = filter.push(text); const tail = filter.finish(); return { text: forwarded + tail.text, calls: tail.calls }; @@ -324,15 +341,28 @@ function stripTrailingFence(text: string): string { return withoutTrailingSpace.slice(0, after); } -/** Parse the JSON payload found between the envelope markers. */ -export function parseToolCallBody(body: string): ToolCall[] { +/** + * Parse the JSON payload found between the envelope markers. + * + * When `allowedNames` is given, a call whose name is not in it is discarded, so + * the caller can treat the whole body as unparsable and keep it as visible text. + * The parameter is optional: without it any non-empty name is accepted. + */ +export function parseToolCallBody(body: string, allowedNames?: Iterable): ToolCall[] { const cleaned = stripTrailingFence(stripOpeningFence(body)).trim(); if (cleaned === "") return []; + const allowed: ReadonlySet | undefined = allowedNames === undefined ? undefined : new Set(allowedNames); const results: ToolCall[] = []; const pushCall = (name: unknown, args: unknown): void => { if (typeof name !== "string" || name.trim() === "") return; - results.push({ id: `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`, name: name.trim(), arguments: normaliseArguments(args) }); + const trimmed = name.trim(); + if (allowed !== undefined && !allowed.has(trimmed)) return; + results.push({ + id: `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`, + name: trimmed, + arguments: normaliseArguments(args), + }); }; const collectParsed = (parsed: unknown): void => { @@ -418,7 +448,11 @@ function repairTrailingCommas(text: string): string { } if (char === ",") { let next = index + 1; - while (next < text.length && /\s/.test(text.charAt(next))) next += 1; + // `/\s/.test(text.charAt(next))` allocated a fresh `RegExp` for every + // skipped character, so a long whitespace run before `}` allocated one + // object per character. `isFenceSpace` is the allocation-free predicate + // the fence walkers already use. + while (next < text.length && isFenceSpace(text.charAt(next))) next += 1; const following = text.charAt(next); // Only a comma directly before a closing bracket is a trailing comma. if (following === "}" || following === "]") continue; diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index ecf7eba..caea08a 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -175,6 +175,11 @@ const chatRequestSchema = z.object({ functions: z.array(z.unknown()).optional(), function_call: z.union([z.string(), z.object({ name: z.string().min(1) }).passthrough()]).optional(), response_format: responseFormatSchema.optional(), + // Declared even though they are rejected: without a schema entry zod stripped + // the values, so a caller asking for `best_of: 3` received a 200 carrying a + // single completion and had no way to detect the difference. + best_of: z.number().optional(), + suffix: z.string().optional(), }); type ChatRequest = z.infer; @@ -318,6 +323,8 @@ export function unappliedParameters(body: object): string[] { * - `store: true` would promise a response store the gateway does not have, and * the legacy `functions` / `function_call` pair is superseded by `tools` / * `tool_choice`. + * - `best_of` and `suffix` cannot be emulated: the gateway produces exactly one + * completion and cannot insert a suffix in the prompt. * * `stop` is deliberately absent: it is honoured by `truncateAtStopSequences`. * The generation knobs are absent too: they are recorded and listed in @@ -333,6 +340,8 @@ export function assertHonouredParameters(body: { web_search_options?: unknown; functions?: unknown; function_call?: unknown; + best_of?: unknown; + suffix?: unknown; }): void { if (body.top_logprobs !== undefined) { rejectUnsupported("top_logprobs", "the gateway cannot return token log probabilities"); @@ -358,6 +367,15 @@ export function assertHonouredParameters(body: { if (body.function_call !== undefined && body.function_call !== "none") { rejectUnsupported("function_call", "legacy `function_call` is not supported; use `tool_choice` instead"); } + // `best_of` and `suffix` change the shape of the response and cannot be + // emulated; the legacy completions surface already rejects both, so all three + // OpenAI surfaces answer the same way. + 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"); + } } /** `image_url.detail` values the gateway can honour: it always sends full media. */ diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index 9aa561b..b4bb61b 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -209,21 +209,31 @@ const responseTool = z }) .passthrough(); +/** + * Accepted `tool_choice` forms. + * + * The Responses API vocabulary this gateway can honour is the three keywords + * plus the two spellings of a named function (`{type:"function",name}` and the + * `{type:"function",function:{name}}` variant SDKs send). Anything else — + * `allowed_tools`, an unknown string, the legacy `{type:"function"}` with no + * name — used to be silently ignored while the response echoed the raw caller + * value, so a 200 claimed a choice that was never applied. It is rejected with + * `400 unsupported_parameter` instead, like the chat surface. + */ const toolChoice = z.union([ - z.string(), + z.enum(["auto", "none", "required"]), + z.object({ type: z.literal("function"), name: z.string().min(1) }).passthrough(), z - .object({ - type: z.string().optional(), - name: z.string().optional(), - function: z.object({ name: z.string() }).passthrough().optional(), - }) + .object({ type: z.literal("function"), function: z.object({ name: z.string().min(1) }).passthrough() }) .passthrough(), ]); const responsesRequest = z .object({ model: z.string(), - input: z.union([z.string(), z.array(inputItem)]), + // The real API requires at least one input item: an empty array used to run + // the upstream turn with an empty prompt and answer 200. + input: z.union([z.string().trim().min(1), z.array(inputItem).min(1)]), instructions: z.string().optional(), stream: z.boolean().optional(), max_output_tokens: z.number().optional(), @@ -479,6 +489,16 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont app.post("/v1/responses", async (request: FastifyRequest, reply: FastifyReply) => { const parsed = responsesRequest.safeParse(normaliseNullOptionals(request.body ?? {})); if (!parsed.success) { + const invalidChoice = parsed.error.issues.find((issue) => issue.path[0] === "tool_choice"); + if (invalidChoice !== undefined) { + // A `tool_choice` value outside the accepted vocabulary is an + // unsupported parameter, not a malformed body: the chat surface answers + // the same way for the same field. + throw ApiError.badRequest( + "`tool_choice` must be `auto`, `none`, `required`, or a named `function`.", + { code: "unsupported_parameter", param: "tool_choice" }, + ); + } const issue = parsed.error.issues[0]; const param = issue !== undefined && issue.path.length > 0 ? issue.path.join(".") : undefined; throw ApiError.badRequest(issue?.message ?? "Invalid request body.", { @@ -647,7 +667,33 @@ async function mapInputItems( continue; } if (item.type === "function_call_output") { - messages.push({ role: "tool", text: contentToText(item.output), toolCallId: item.call_id }); + // Media inside an `output` array takes the same path as an Anthropic + // `tool_result`: the bytes are resolved and attached to a synthetic user + // turn (the only turn upstream forwards attachments for) while the tool + // message keeps the `[: ]` placeholder. Reducing the item with + // `contentToText()` alone silently dropped an image the model never saw. + const output = item.output; + const media = Array.isArray(output) ? output.filter(isMediaPart) : []; + if (media.length > 0) { + // Reuse `messageDraft()` for the sources (so the bytes take exactly the + // message-item path) and render the `[: ]` markers the + // Anthropic `tool_result` text carries, since a `role: "tool"` message + // has no attachment slot of its own. + const draft = messageDraft("user", media); + drafts.push(draft); + messages.push({ + role: "tool", + text: [contentToText(output), ...media.map(mediaPlaceholder)] + .filter((part) => part.length > 0) + .join("\n"), + toolCallId: item.call_id, + }); + // The synthetic turn the resolved media rides on. `resolveMessageMedia` + // fills this same object in place, so the declaration order is kept. + messages.push(draft.message); + continue; + } + messages.push({ role: "tool", text: contentToText(output), toolCallId: item.call_id }); continue; } if (item.type === "item_reference") { @@ -742,6 +788,49 @@ function messageDraft( return { message: { role, text: text.join("\n") }, sources: media }; } +/** A content part that carries media rather than text. */ +type MediaContentPart = Extract; + +/** Narrow a `function_call_output.output` entry to the parts the media pool can resolve. */ +function isMediaPart(part: ContentPart): part is MediaContentPart { + return ( + part.type === "input_image" || part.type === "input_file" || part.type === "input_audio" || part.type === "video_url" + ); +} + +/** `data:;base64,...` → ``, when the payload carries one. */ +function mimeOfDataUri(value: string | undefined): string | undefined { + if (value === undefined || !isDataUri(value)) return undefined; + const comma = value.indexOf(","); + const header = comma === -1 ? value.slice(5) : value.slice(5, comma); + const mime = header.split(";")[0]; + return mime !== undefined && mime.includes("/") ? mime : undefined; +} + +/** + * Prompt marker for one media part of a `function_call_output`. + * + * `role: "tool"` has no attachment slot, so the text names what was attached; + * the bytes themselves travel on the synthetic user turn. The shape matches the + * Anthropic surface's `mediaPlaceholder()`. + */ +function mediaPlaceholder(part: MediaContentPart): string { + const marker = (kind: string, hint: string | undefined): string => + hint === undefined ? `[${kind}]` : `[${kind}: ${hint}]`; + switch (part.type) { + case "input_image": + return marker("image", mimeOfDataUri(urlOf(part.image_url))); + case "input_file": + return marker("document", mimeOfDataUri(part.file_data)); + case "input_audio": { + const format = part.input_audio.format; + return marker("audio", format.includes("/") ? format : `audio/${format.toLowerCase()}`); + } + case "video_url": + return marker("video", mimeOfDataUri(urlOf(part.video_url))); + } +} + /** `input_image.detail` values the gateway can honour: it always sends full media. */ function assertImageDetail(detail: string | undefined): void { if (detail === undefined || detail === "auto") return; @@ -801,24 +890,30 @@ function mapResponseFormat(format: z.infer | undefined): Resp }; } -function mapToolChoice(value: unknown): InternalRequest["toolChoice"] | undefined { - if (typeof value === "string") { - if (value === "auto" || value === "none" || value === "required") return value; - return undefined; +/** The name of a named-function `tool_choice`, whichever SDK spelling it used. */ +function namedToolChoice(value: ResponsesRequest["tool_choice"]): string { + if (value !== undefined && typeof value !== "string") { + if ("name" in value && typeof value.name === "string") return value.name; + if ("function" in value && typeof value.function === "object" && value.function !== null) { + const nested = (value.function as { name?: unknown }).name; + if (typeof nested === "string") return nested; + } } - if (typeof value !== "object" || value === null) return undefined; - const record = value as { name?: unknown; function?: { name?: unknown } }; - const name = typeof record.name === "string" ? record.name : record.function?.name; - return typeof name === "string" && name.length > 0 ? { name } : undefined; + // Unreachable for a validated request: every named form carries a name. + return ""; } -/** Render `tool_choice` back into the vocabulary of the Responses API. */ -function echoToolChoice(value: unknown): string { +function mapToolChoice(value: ResponsesRequest["tool_choice"]): InternalRequest["toolChoice"] | undefined { + if (value === undefined) return undefined; if (typeof value === "string") return value; - const choice = mapToolChoice(value); - if (choice === undefined) return "auto"; - if (typeof choice === "string") return choice; - return `function:${choice.name}`; + return { name: namedToolChoice(value) }; +} + +/** Render the validated `tool_choice` back into the vocabulary of the Responses API. */ +function echoToolChoice(value: ResponsesRequest["tool_choice"]): string { + if (value === undefined) return "auto"; + if (typeof value === "string") return value; + return `function:${namedToolChoice(value)}`; } function headerValue(request: FastifyRequest, name: string): string | undefined { @@ -1179,16 +1274,20 @@ function failedStreamResponse( } /** - * Emit the legacy flat `event: error` frame followed by the spec-shaped - * terminal `response.failed` event, both consuming the live counter. + * Emit the spec-shaped terminal `response.failed` event first, then the legacy + * flat `event: error` frame, both consuming the live counter. + * + * The order matches `docs/API.md` §2: a client that treats the first `error` + * frame as terminal used to see it before `response.failed` and never received + * the terminal response object carrying the final `output` and `error`. */ function sendFailure(writer: SseWriter, prepared: Prepared, state: StreamState, error: ApiError): void { - emitFrame(writer, state, "error", (sequence) => errorFrame(error, sequence)); emitFrame(writer, state, "response.failed", (sequence) => ({ type: "response.failed", sequence_number: sequence, response: failedStreamResponse(prepared, state, { code: error.code, message: error.message }), })); + emitFrame(writer, state, "error", (sequence) => errorFrame(error, sequence)); } async function pipeEvents( @@ -1287,36 +1386,51 @@ async function pipeEvents( } case "reasoning_end": { - // Adopt the consolidated summary only when it is longer than what the - // deltas already produced, mirroring `text_end` and - // `collectCompletion()`. Upstream emits one `reasoning.ended` per step - // carrying that step's snapshot, so adopting unconditionally truncated - // the streamed reasoning to the last (shorter) step. + // A turn that does not surface reasoning is unaffected: the event is + // ignored before anything is adopted (the same gate the delta branch + // applies, and the same one `messagePayload()` uses). + if (!state.reasoningEnabled && !state.reasoningRequested) break; + if (event.text.length === 0) break; if (event.text.length > state.reasoningLength) { + // Adopt the consolidated summary only when it is longer than what the + // deltas already produced, mirroring `text_end` and + // `collectCompletion()`. Upstream emits one `reasoning.ended` per step + // carrying that step's snapshot, so adopting unconditionally truncated + // the streamed reasoning to the last (shorter) step. The unseen suffix + // still has to reach the delta channel, or a client accumulating + // `response.reasoning_summary_text.delta` renders a truncated summary + // while `response.reasoning_summary_text.done` carries the full text. + const delta = event.text.slice(state.reasoningLength); + if (!state.reasoningStarted) { + // The provider sent the consolidated summary without deltas. + state.reasoningStarted = true; + state.reasoningVisible = true; + const index = state.messageIndex === undefined ? 0 : state.messageIndex + 1; + state.reasoningIndex = index; + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: index, + item: reasoningItem(state.reasoningId, "", "in_progress"), + })); + emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ + type: "response.reasoning_summary_part.added", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: index, + summary_index: 0, + part: { type: "summary_text", text: "" }, + })); + } state.reasoningParts = [event.text]; state.reasoningLength = event.text.length; - } - if (!state.reasoningStarted) { - // The provider sent the consolidated summary without deltas. - if (!state.reasoningEnabled && !state.reasoningRequested) break; - if (state.reasoningLength === 0) break; - state.reasoningStarted = true; - state.reasoningVisible = true; - const index = state.messageIndex === undefined ? 0 : state.messageIndex + 1; - state.reasoningIndex = index; - emitFrame(writer, state, "response.output_item.added", (sequence) => ({ - type: "response.output_item.added", - sequence_number: sequence, - output_index: index, - item: reasoningItem(state.reasoningId, "", "in_progress"), - })); - emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ - type: "response.reasoning_summary_part.added", + emitFrame(writer, state, "response.reasoning_summary_text.delta", (sequence) => ({ + type: "response.reasoning_summary_text.delta", sequence_number: sequence, item_id: state.reasoningId, - output_index: index, + output_index: state.reasoningIndex ?? 0, summary_index: 0, - part: { type: "summary_text", text: "" }, + delta, })); } // The summary is closed once, by `finaliseStream`, when the turn is @@ -1363,9 +1477,10 @@ async function pipeEvents( case "text_end": { if (event.text.length <= state.textLength) break; - // The provider delivered the consolidated text instead of deltas: the - // message item and its content part still have to be announced, or the - // final payload would carry `output_text` with an empty `output`. + // The provider delivered the consolidated text instead of (or in + // addition to) deltas: the message item and its content part still have + // to be announced, or the final payload would carry `output_text` with + // an empty `output`. if (!state.messageStarted) { state.messageStarted = true; const index = state.reasoningIndex === undefined ? 0 : state.reasoningIndex + 1; @@ -1385,8 +1500,22 @@ async function pipeEvents( part: { type: "output_text", text: "", annotations: [] }, })); } + // Only the suffix the deltas have not produced yet is emitted, so a + // step-level snapshot can neither truncate the answer nor duplicate it. + // Without this frame a client accumulating `response.output_text.delta` + // renders a truncated (or, for a `text_end`-only turn, entirely empty) + // answer while `response.output_text.done` carries the full text. + const delta = event.text.slice(state.textLength); state.textParts = [event.text]; state.textLength = event.text.length; + emitFrame(writer, state, "response.output_text.delta", (sequence) => ({ + type: "response.output_text.delta", + sequence_number: sequence, + item_id: state.messageId, + output_index: state.messageIndex ?? 0, + content_index: 0, + delta, + })); break; } @@ -1561,12 +1690,13 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat error: failed ? FAILED_TURN : null, }); + const type = failed ? "response.failed" : incomplete ? "response.incomplete" : "response.completed"; + emitFrame(writer, state, type, (sequence) => ({ type, sequence_number: sequence, response: final })); + if (failed) { // The flat error frame is kept for clients written against the previous - // behaviour; `response.failed` below is the spec-shaped terminal event. + // behaviour, but it follows the spec-shaped terminal event: a client that + // stops at the first `error` frame must still have seen `response.failed`. emitFrame(writer, state, "error", (sequence) => errorFrame(FAILED_TURN, sequence)); } - - const type = failed ? "response.failed" : incomplete ? "response.incomplete" : "response.completed"; - emitFrame(writer, state, type, (sequence) => ({ type, sequence_number: sequence, response: final })); } diff --git a/src/auth.ts b/src/auth.ts index 9fe6e57..44a853c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -11,12 +11,21 @@ * - `x-api-key: ` * - `Authorization: Basic ` (key as the username) * - * Query-string keys are deliberately not supported: request URLs are logged. + * 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 + * credential. Query-string keys are deliberately not supported either: request + * URLs are logged. + * + * When `OPENCODE_ADMIN_API_KEYS` is non-empty, `/admin` and `/admin/*` accept + * only one of those keys; every other route keeps accepting a general key. + * 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 type { FastifyReply, FastifyRequest } from "fastify"; import type { Config } from "./config.js"; import { ApiError } from "./errors.js"; +import { chargeFailedAuth, type RateLimiters } from "./http/rateLimit.js"; const PUBLIC_PATHS = new Set(["/", "/health", "/ready", "/healthz"]); @@ -49,7 +58,9 @@ export function isPublicPath(path: string): boolean { * API key extraction. * * Keys are accepted as `Authorization: Bearer `, `x-api-key: ` or - * `Authorization: Basic base64(:)`. Query-string keys are deliberately not + * `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. */ export function extractApiKey(request: FastifyRequest): string | undefined { @@ -69,10 +80,6 @@ export function extractApiKey(request: FastifyRequest): string | undefined { return undefined; } } - // Bare key in the Authorization header. - if (!normalised?.includes("bearer") && authorization.length > 0 && !authorization.includes(" ")) { - return authorization; - } } const headerKey = request.headers["x-api-key"]; @@ -100,6 +107,26 @@ export function isAuthorized(config: Config, presented: string | undefined): boo return config.apiKeys.some((key) => safeEqual(key, presented)); } +/** True for `/admin` and every route below it. */ +export function isAdminPath(path: string): boolean { + return path === "/admin" || path.startsWith("/admin/"); +} + +/** + * True when the presented credential may use `/admin` and `/admin/*`. + * + * With `OPENCODE_ADMIN_API_KEYS` unset the general key list applies, so the + * tier is opt-in and nothing changes. When it is set, only a key from that list + * is accepted. `OPENCODE_ALLOW_NO_AUTH` still applies: turning authentication + * off deliberately turns the tier off with it. + */ +export function isAdminAuthorized(config: Config, presented: string | undefined): boolean { + 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)); +} + /** * True when the presented credential is the dedicated metrics scrape token. * @@ -112,25 +139,52 @@ export function isMetricsToken(config: Config, presented: string | undefined): b return safeEqual(config.metricsToken, presented); } -function unauthorized(): ApiError { +function unauthorized(message?: string): ApiError { return ApiError.unauthorized( - "Missing or invalid API key. Send it as `Authorization: Bearer `, `x-api-key: `, " + - "or `Authorization: Basic `.", + message ?? + "Missing or invalid API key. Send it as `Authorization: Bearer `, `x-api-key: `, " + + "or `Authorization: Basic `.", ); } +/** + * Reject an attempt: charge the failed-auth limiter first, then hand back the + * 401 to throw. The caller throws, so the type checker sees a rejecting path. + */ +function authRejection(limiters: RateLimiters, request: FastifyRequest, message?: string): ApiError { + // Charged only on the failure path, so a valid credential never spends this + // budget; a drained bucket answers 429 instead of another 401. + chargeFailedAuth(limiters, request); + return unauthorized(message); +} + /** * Fastify `onRequest` hook enforcing authentication. * * It is registered as `onRequest` so an anonymous caller is rejected before * Fastify buffers and parses the body (up to `bodyLimitBytes` per connection). + * + * When `OPENCODE_ADMIN_API_KEYS` is configured, `/admin` and `/admin/*` require + * one of those keys and reject a general key. Every failed attempt is charged to + * the always-on failed-auth limiter, which answers 429 once the caller has spent + * its burst — so guessing costs something even when `OPENCODE_RATE_LIMIT_RPM=0`. */ -export function requireApiKey(config: Config) { +export function requireApiKey(config: Config, limiters: RateLimiters) { return async function authenticate(request: FastifyRequest, _reply: FastifyReply): Promise { const path = requestPath(request); if (isPublicPath(path)) return; const presented = extractApiKey(request); + const adminPath = isAdminPath(path); + + if (adminPath) { + if (isAdminAuthorized(config, presented)) return; + throw authRejection( + limiters, + request, + "Missing or invalid admin API key. /admin/* requires a key from OPENCODE_ADMIN_API_KEYS.", + ); + } if (path === "/metrics") { // A configured scrape token is checked first, so it works even when the @@ -139,14 +193,14 @@ export function requireApiKey(config: Config) { if (config.metricsToken !== undefined) { // With a token configured the endpoint is never anonymous; a general // API key is still accepted. - if (!isAuthorized(config, presented)) throw unauthorized(); + if (!isAuthorized(config, presented)) throw authRejection(limiters, request); return; } if (config.metricsPublic) return; - if (!isAuthorized(config, presented)) throw unauthorized(); + if (!isAuthorized(config, presented)) throw authRejection(limiters, request); return; } - if (!isAuthorized(config, presented)) throw unauthorized(); + if (!isAuthorized(config, presented)) throw authRejection(limiters, request); }; } \ No newline at end of file diff --git a/src/config.ts b/src/config.ts index 4c501df..f41e908 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,6 +5,7 @@ * but an API key configured. */ import fs from "node:fs"; +import { isIP } from "node:net"; import os from "node:os"; import path from "node:path"; @@ -12,10 +13,27 @@ export interface Config { readonly host: string; readonly port: number; readonly bodyLimitBytes: number; - readonly trustProxy: boolean; + /** Wall-clock bound, in milliseconds, on receiving one request body. */ + readonly bodyTimeoutMs: number; + /** + * Fastify's `trustProxy` value: `false` (never trust `x-forwarded-*`), + * `true` (trust every hop), a non-negative hop count, or a list of trusted + * IPs/CIDRs. `true` and a hop count let the caller influence `request.ip`, + * which is the identity the credential-less rate-limit bucket uses, so the + * documented option for a real deployment is the CIDR list. + */ + readonly trustProxy: boolean | number | readonly string[]; /** API keys accepted from callers. Never empty: the built-in default applies. */ readonly apiKeys: readonly string[]; + /** + * Optional dedicated operator credential for `/admin` and `/admin/*`. + * + * Empty by default, in which case a general API key keeps working. When + * non-empty, those routes accept only one of these keys, so a tenant key + * cannot restart the shared upstream or wipe the session cache. + */ + readonly adminApiKeys: readonly string[]; /** * True when the published built-in development key is among the accepted keys * — either because nothing was configured (so the default was installed) or @@ -175,6 +193,76 @@ function envList(name: string): string[] { .filter((part) => part.length > 0); } +/** + * True for one trusted-proxy entry that Fastify's `proxy-addr` can compile. + * + * `proxy-addr` throws on an address it cannot parse (`999.999.999.999`, a prefix + * range past the family's width), and that exception happens inside the + * `Fastify(...)` constructor — a raw stack trace at startup instead of the + * 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. + */ +function isTrustedProxyEntry(entry: string): boolean { + if (entry.includes("%")) return false; + const parts = entry.split("/"); + const address = parts[0]; + if (address === undefined || parts.length > 2) return false; + const family = isIP(address); + if (family === 0) return false; + const prefix = parts[1]; + if (prefix === undefined) return true; + if (!/^\d{1,3}$/.test(prefix)) return false; + return Number(prefix) <= (family === 4 ? 32 : 128); +} + +/** + * Parse `OPENCODE_TRUST_PROXY` into the value Fastify takes. + * + * The grammar extends the boolean spellings the gateway always supported with + * the two forms a bare `true` cannot express: a hop count and a comma-separated + * IP/CIDR allow-list. A positive integer is always a hop count — including `1`, + * which trusts the immediate peer only and is therefore strictly safer than + * `true` (an untrusted client cannot prepend a forged `x-forwarded-for` entry). + * The boolean words keep their old meaning. + * + * The hop count is kept as a number here for `GET /admin/config`; `src/server.ts` + * compiles it into the function form Fastify actually honours (its option parser + * only handles boolean/string/string[]/function, so a numeric option would be + * silently ignored and trust nothing). + * + * An unparseable value warns (without echoing it: an operator can paste a + * secret into the wrong variable) and falls back to `false`, the conservative + * choice — trusting a proxy is what lets a caller steer `request.ip`, and with + * it the credential-less rate-limit bucket. + */ +function parseTrustProxy(): Config["trustProxy"] { + const raw = env("OPENCODE_TRUST_PROXY")?.toLowerCase(); + if (raw === undefined) return false; + if (["true", "yes", "on", "enabled"].includes(raw)) return true; + if (["false", "no", "off", "disabled"].includes(raw)) return false; + + const parsed = parseStrictInt(raw); + if (parsed !== undefined) { + if (parsed === 0) return false; + if (parsed > 0) return parsed; + warnInvalidEnv("OPENCODE_TRUST_PROXY", 0); + return false; + } + + // Every remaining value is read as a comma-separated IP/CIDR list. A single + // entry is the common case (one trusted proxy), so the list parse must not be + // gated on a comma being present. + const entries = raw + .split(",") + .map((part) => part.trim()) + .filter((part) => part.length > 0); + if (entries.length > 0 && entries.every(isTrustedProxyEntry)) return Object.freeze(entries); + + warnInvalidEnv("OPENCODE_TRUST_PROXY", 0); + return false; +} + /** 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; @@ -296,13 +384,28 @@ export function loadConfig(overrides: Partial = {}): Config { // key that ships with the project. const usingDefaultApiKey = apiKeys.includes(DEFAULT_API_KEY); + // A dedicated operator credential is opt-in and separate from `apiKeys`: + // when it is empty every general key still reaches `/admin/*`. + const adminApiKeys = envList("OPENCODE_ADMIN_API_KEYS"); + if (env("OPENCODE_ADMIN_API_KEYS") !== undefined && adminApiKeys.length === 0) { + throw new Error( + "OPENCODE_ADMIN_API_KEYS is set but contains no usable key. " + + "Provide at least one non-empty key, or unset the variable to keep accepting general API keys on /admin/*.", + ); + } + const config: Config = { host: envStr("HOST", "127.0.0.1"), port: envInt("PORT", 20123, 1, 65_535), bodyLimitBytes: envInt("OPENCODE_MAX_BODY_BYTES", 64 * 1024 * 1024, 1024), - trustProxy: envBool("OPENCODE_TRUST_PROXY", false), + // Bounds receiving the body itself, which the preHandler socket timeout + // cannot: that timer only starts once the body has been parsed. 5 minutes + // is generous for a 64 MiB upload and short enough to bound a slow drip. + bodyTimeoutMs: envInt("OPENCODE_BODY_TIMEOUT_MS", 300_000, 1000), + trustProxy: parseTrustProxy(), apiKeys: Object.freeze(apiKeys), + adminApiKeys: Object.freeze(adminApiKeys), usingDefaultApiKey, allowNoAuth: envBool("OPENCODE_ALLOW_NO_AUTH", false), metricsPublic: envBool("OPENCODE_METRICS_PUBLIC", false), diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts index bd87fd8..a72fe38 100644 --- a/src/http/rateLimit.ts +++ b/src/http/rateLimit.ts @@ -4,9 +4,9 @@ * One bucket per authenticated API key (never the raw key: only a SHA-256 hash * 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`, so an unauthenticated caller is rejected before any bucket is - * touched, and `/admin/*` gets its own bucket so operator traffic cannot be - * starved by completion traffic. + * `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. * * The bucket map is bounded: an anonymous deployment cannot let a spoofed or * rotating client address grow it without limit. @@ -126,14 +126,32 @@ function bucketKey(scope: string, identity: string): string { return createHash("sha256").update(`${scope}\u0000${identity}`).digest("hex"); } +/** + * Bucket identity for the failed-authentication limiter: the client address, + * hashed and never the presented credential, which must not reach any state. + */ +function authBucketKey(request: FastifyRequest): string { + const address = request.ip.length > 0 ? request.ip : "unknown"; + return bucketKey("auth", `ip:${address}`); +} + +/** Failed-authentication floor: never below 60 requests/minute, burst 10. */ +const AUTH_RATE_LIMIT_MIN_RPM = 60; +const AUTH_RATE_LIMIT_MIN_BURST = 10; + /** * Identity a request is bucketed on. * * A configured API key gets its own bucket. Every other caller — that is, any * caller in a deployment with `OPENCODE_ALLOW_NO_AUTH=true` — is bucketed by - * `request.ip`, which is proxy-aware when `trustProxy` is enabled, so one client - * cannot spend another client's budget. Caller-supplied headers are never used, - * because an arbitrary value would grow the bucket map without bound. + * `request.ip`, which follows `x-forwarded-for`. + * + * That makes the bucket only as trustworthy as `OPENCODE_TRUST_PROXY`: + * `true` (or a hop count) trusts headers the caller can forge, so a spoofed + * value mints a fresh bucket per request and the limit stops applying. Use the + * documented IP/CIDR list, which only resolves the client address through a + * 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 { const presented = extractApiKey(request); @@ -141,15 +159,51 @@ function bucketIdentity(config: Config, request: FastifyRequest): string { return `ip:${request.ip.length > 0 ? request.ip : "unknown"}`; } -/** Limiter pair wired into the request lifecycle. */ +/** Limiter triple wired into the request lifecycle. */ export interface RateLimiters { readonly api: TokenBucketLimiter; readonly admin: TokenBucketLimiter; + /** + * Always-on limiter for failed authentication. + * + * Unrelated to `OPENCODE_RATE_LIMIT_RPM=0` (which keeps meaning "no request + * limiter"): credential guessing must cost something even in a deployment + * that throttles nothing else. + */ + readonly auth: TokenBucketLimiter; } export function createRateLimiters(config: Config, now?: () => number): RateLimiters { - const options = { rpm: config.rateLimitRpm, burst: config.rateLimitBurst, ...(now ? { now } : {}) }; - return { api: new TokenBucketLimiter(options), admin: new TokenBucketLimiter(options) }; + const clock = now ? { now } : {}; + const options = { rpm: config.rateLimitRpm, burst: config.rateLimitBurst, ...clock }; + const authRpm = Math.max(config.rateLimitRpm, AUTH_RATE_LIMIT_MIN_RPM); + return { + api: new TokenBucketLimiter(options), + admin: new TokenBucketLimiter(options), + auth: new TokenBucketLimiter({ + rpm: authRpm, + burst: Math.max(derivedBurst(authRpm), AUTH_RATE_LIMIT_MIN_BURST), + ...clock, + }), + }; +} + +/** + * Charge the failed-authentication bucket, 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. + */ +export function chargeFailedAuth(limiters: RateLimiters, request: FastifyRequest): void { + const retryAfterMs = limiters.auth.take(authBucketKey(request)); + if (retryAfterMs === undefined) return; + throw new ApiError( + 429, + "rate_limit_error", + `Too many rejected authentication attempts from this address. Retry in ${Math.ceil(retryAfterMs / 1000)}s.`, + { code: "rate_limit_exceeded", retryAfterMs }, + ); } /** @@ -159,7 +213,9 @@ export function createRateLimiters(config: Config, now?: () => number): RateLimi * 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`). + * (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) { return async function rateLimit(request: FastifyRequest, _reply: FastifyReply): Promise { diff --git a/src/http/sse.ts b/src/http/sse.ts index 4c3781d..13b89f2 100644 --- a/src/http/sse.ts +++ b/src/http/sse.ts @@ -8,9 +8,12 @@ * Backpressure: `raw.write()` returns `false` once the socket's buffer is full. * That result used to be discarded, so a slow reader could not throttle the * producer and the queue behind it grew without bound. `drain()` now resolves - * when the socket has caught up (or after a bounded wait), and `closedSignal` - * is aborted as soon as the connection dies, so a producer can stop even if it - * never calls `createDisconnectSignal()`. + * when the socket has caught up (or after a bounded wait); when that wait + * expires the writer is marked `stalled`, closed and its socket destroyed, so the + * producer stops instead of queueing into a socket that is still full. + * `closedSignal` is aborted as soon as the connection dies **or** a drain + * deadline expires, so a producer can stop even if it never calls + * `createDisconnectSignal()`. */ import type { FastifyReply } from "fastify"; @@ -22,7 +25,8 @@ export interface SseWriterOptions { onClose?: () => void; /** * Longest a `drain()` call waits for a backed-up socket before releasing the - * producer. Default 5000; `0` makes `drain()` resolve immediately. + * producer. Default 5000; `0` makes `drain()` resolve immediately. Expiry + * marks the writer `stalled` and closes it (see `stalled`). */ drainTimeoutMs?: number; } @@ -38,6 +42,7 @@ export class SseWriter { #closed = false; #pendingDrain: Promise | undefined; #resolveDrain: (() => void) | undefined; + #drainTimedOut = false; constructor(reply: FastifyReply, options: SseWriterOptions = {}) { this.#reply = reply; @@ -48,6 +53,17 @@ export class SseWriter { return this.#closed; } + /** + * True once a `drain()` wait expired with the socket still backed up. + * + * A stalled writer is also closed: the consumer stopped reading, so the + * producer is told to stop (through `closedSignal`) instead of queueing + * frames the reader will never take. + */ + get stalled(): boolean { + return this.#drainTimedOut; + } + /** Aborted when the connection closes, whether via `close()` or a dead socket. */ get closedSignal(): AbortSignal { return this.#closedController.signal; @@ -93,7 +109,9 @@ export class SseWriter { /** Write a comment frame (used for keep-alives). */ comment(text: string): void { - if (this.#closed) return; + // A heartbeat is only useful while the socket is accepting frames: writing + // one into a backed-up socket adds a frame the reader will never take. + if (this.#closed || this.#pendingDrain !== undefined) return; this.#write(`: ${text}\n\n`); } @@ -124,6 +142,11 @@ export class SseWriter { } #write(chunk: string): void { + // Never queue into a socket whose drain deadline already expired: the reader + // is gone, and `#handleClose()` below has aborted `closedSignal` so the + // producer stops. Dropping the frame while the producer still believes it + // was delivered is not an option — the abort is what ends the turn. + if (this.#closed || this.#drainTimedOut) return; try { if (this.#reply.raw.write(chunk) === false) this.#awaitDrain(); } catch { @@ -135,8 +158,10 @@ export class SseWriter { * Bound the wait for a full socket buffer. * * The producer blocks on `drain()` instead of the writer queueing frames: a - * reader that never catches up releases the producer after - * `drainTimeoutMs`, so a stuck connection cannot grow the process heap. + * reader that never catches up releases the producer after `drainTimeoutMs`, + * and the expiry is recorded as a stall. The writer then closes itself, which + * aborts `closedSignal` so the producer's abort path ends the turn, and drops + * every later frame instead of appending it to a socket that is still full. */ #awaitDrain(): void { if (this.#pendingDrain !== undefined || this.#closed) return; @@ -146,6 +171,7 @@ export class SseWriter { this.#pendingDrain = new Promise((resolve) => { let timer: NodeJS.Timeout | undefined; + let timedOut = false; const done = (): void => { if (timer !== undefined) clearTimeout(timer); raw.off("drain", done); @@ -153,13 +179,34 @@ export class SseWriter { raw.off("error", done); this.#pendingDrain = undefined; this.#resolveDrain = undefined; + if (timedOut) { + // The socket never drained inside the deadline, so the consumer is not + // reading. Record the stall and terminate the stream: mark the writer + // closed (drops further frames, stops the heartbeat) and abort + // `closedSignal` so the producer's abort path stops the upstream turn. + this.#drainTimedOut = true; + this.#handleClose(); + // A socket that has not drained within the deadline is not coming back. + // Destroy it instead of parking the connection (and its buffers) until + // the process exits; the "close" event also feeds the client-disconnect + // signal every surface watches, so the upstream turn is interrupted + // rather than left to run after the reader is gone. + try { + raw.destroy(); + } catch { + /* already gone */ + } + } resolve(); }; this.#resolveDrain = done; raw.once("drain", done); raw.once("close", done); raw.once("error", done); - timer = setTimeout(done, timeoutMs); + timer = setTimeout(() => { + timedOut = true; + done(); + }, timeoutMs); timer.unref?.(); }); } diff --git a/src/http/timeout.ts b/src/http/timeout.ts index f6365f1..e844c12 100644 --- a/src/http/timeout.ts +++ b/src/http/timeout.ts @@ -1,11 +1,19 @@ /** - * Per-request socket timeout. + * Per-request socket timeouts. * - * Fastify has no route-level `requestTimeout`, so the server-level option stays - * `0` and the bound is applied per request once the body is known: a buffered - * completion may not hold a connection (and an upstream turn) forever, while an - * SSE response must never be cut off by it. + * Two separate bounds exist, because they cover different phases: + * + * 1. `armBodyDeadline` — armed in `preParsing`, i.e. before Fastify reads the + * request body, and cleared as soon as the body has been parsed. It bounds + * *body receipt*: without it a caller can open a connection and dribble a + * body forever (an idle socket timer never fires while bytes keep arriving) + * while the gateway buffers up to `bodyLimitBytes` per connection. + * 2. `applyRequestTimeout` — applied in `preHandler`, i.e. after the body is + * known, and only for buffered requests. A buffered completion may not hold + * a connection (and an upstream turn) forever, while an SSE response must + * never be cut off by it. */ +import { setTimeout as setTimer } from "node:timers"; import type { FastifyReply, FastifyRequest } from "fastify"; import type { Config } from "../config.js"; @@ -25,13 +33,66 @@ export function isStreamingBody(body: unknown): boolean { * * Streamed requests are unbounded (the upstream turn has its own * `OPENCODE_REQUEST_TIMEOUT_MS` budget and the SSE stream must survive long - * answers). Buffered requests share that same upstream budget, so a caller - * cannot park a connection indefinitely. + * answers). Buffered requests share that same upstream budget, so once the body + * has been received a caller cannot park a connection indefinitely. Receiving + * the body itself is bounded separately by `OPENCODE_BODY_TIMEOUT_MS`; see + * `armBodyDeadline`. */ export function requestTimeoutFor(config: Pick, body: unknown): number { return isStreamingBody(body) ? 0 : config.upstreamRequestTimeoutMs; } +/** Live body-receipt deadlines, keyed by request so nothing else can be cancelled. */ +const bodyDeadlines = new WeakMap>(); + +/** Cancel the body-receipt deadline armed for `request`, if any. */ +export function clearBodyDeadline(request: FastifyRequest): void { + const timer = bodyDeadlines.get(request); + if (timer === undefined) return; + bodyDeadlines.delete(request); + clearTimeout(timer); +} + +/** + * Bound how long one client may take to deliver its request body. + * + * The deadline is wall-clock, not idle: a caller that keeps sending bytes is + * still cut off once the budget is spent, which is exactly the dribble case an + * idle socket timer cannot catch. On expiry the raw socket is destroyed, so the + * buffered body is released with it. + * + * It must never outlive body receipt: `clearBodyDeadline` is called at the start + * of the `preHandler` hook (the body is complete by then) and again when + * `reply.raw` closes, so a long `stream: true` completion — whose body was + * received in milliseconds — is never destroyed by this deadline. + * + * The timer is `unref`'d, so a pending deadline never keeps the process alive. + */ +export function armBodyDeadline( + request: FastifyRequest, + reply: FastifyReply, + config: Pick, +): void { + if (config.bodyTimeoutMs <= 0) return; + + const previous = bodyDeadlines.get(request); + if (previous !== undefined) clearTimeout(previous); + + const timer = setTimer(() => { + bodyDeadlines.delete(request); + const socket = request.raw.socket; + // A stalled body is a protocol violation; the client gets a reset socket + // rather than a response, exactly as with `requestTimeout`. + socket?.destroy(); + }, config.bodyTimeoutMs); + timer.unref(); + bodyDeadlines.set(request, timer); + + reply.raw.once("close", () => { + clearBodyDeadline(request); + }); +} + /** * Apply the per-request timeout to the underlying socket. * diff --git a/src/index.ts b/src/index.ts index a4bac73..3147b0d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,13 +15,14 @@ import { createMetrics } from "./metrics/registry.js"; import type { AppContext } from "./context.js"; import { defaultCompletionRunner } from "./context.js"; import { DEFAULT_DRAIN_MS, shutdown as performShutdown } from "./http/shutdown.js"; +import { setMediaLogger } from "./media/resolve.js"; import { OpencodeClient } from "./upstream/client.js"; import { EventHub } from "./upstream/events.js"; import { ModelRegistry } from "./upstream/models.js"; import { UpstreamProcess } from "./upstream/process.js"; import { SessionStore } from "./upstream/sessions.js"; import { SERVICE_NAME, VERSION } from "./version.js"; -import { defaultApiKeyNote, privateMediaUrlWarning } from "./startup.js"; +import { defaultApiKeyNote, defaultKeyExposureError, privateMediaUrlWarning } from "./startup.js"; /** Directory holding this file: `/dist` when built, `/src` under tsx. */ const moduleDir = path.dirname(fileURLToPath(import.meta.url)); @@ -44,6 +45,18 @@ async function main(): Promise { ensureDataDirs(config); const log = createLogger(config); + // Media failures report a fixed message class to the caller; the transport + // detail (errno, URL, status) is logged through this hook instead. + setMediaLogger(log); + + // Fail closed on the quickstart that would otherwise be reachable from the + // network with a credential published in the repository. + const defaultKeyExposure = defaultKeyExposureError(config); + if (defaultKeyExposure !== undefined) { + log.error({ host: config.host, usingDefaultApiKey: true }, "refusing to start with the published default API key"); + process.stderr.write(`\n${defaultKeyExposure}\n\n`); + process.exit(1); + } if (config.usingDefaultApiKey) { // Readable on the terminal as well as in the structured log: a published @@ -94,36 +107,6 @@ async function main(): Promise { }; const app = await buildServer(ctx); - // Warm the upstream connection and model catalog without blocking startup. - void (async () => { - try { - events.start(); - const catalog = await models.catalog(); - log.info( - { models: catalog.models.length, agents: catalog.agents.map((agent) => agent.id) }, - "OpenCode upstream ready", - ); - } catch (error) { - log.warn( - { err: error instanceof Error ? error.message : String(error) }, - "OpenCode upstream is not available yet; the gateway will retry on demand", - ); - } - })(); - - await app.listen({ host: config.host, port: config.port }); - log.info( - { - service: SERVICE_NAME, - version: VERSION, - url: `http://${config.host}:${config.port}`, - workdir: config.workdir, - agent: config.agent, - authRequired: authRequired(config) && config.apiKeys.length > 0, - }, - "opencode-api listening", - ); - let shuttingDown = false; const shutdown = async (signal: string): Promise => { if (shuttingDown) return; @@ -133,7 +116,16 @@ async function main(): Promise { process.exit(0); }; - for (const signal of ["SIGINT", "SIGTERM"] as const) { + /** + * Signals handled on every path, registered *before* the upstream warm-up. + * + * The warm-up below spawns the child before `app.listen` runs, so a signal + * received during a slow cold start used to terminate the process with the + * child alive (and nothing ever reclaims the internal port). SIGHUP is + * included for the same reason. `performShutdown()` wraps every hook in its own + * try/catch and its drain tolerates an app that never listened. + */ + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { process.on(signal, () => { // A failed shutdown has already closed the HTTP server and set // `shuttingDown`, so any later signal is ignored: without an exit code the @@ -158,6 +150,38 @@ async function main(): Promise { log.error({ err: error.message, stack: error.stack }, "uncaught exception"); process.exit(1); }); + + // Warm the upstream connection and model catalog without blocking startup. + // Runs after the signal handlers so a signal during a slow cold start stops + // the child it spawns instead of orphaning it. + void (async () => { + try { + events.start(); + const catalog = await models.catalog(); + log.info( + { models: catalog.models.length, agents: catalog.agents.map((agent) => agent.id) }, + "OpenCode upstream ready", + ); + } catch (error) { + log.warn( + { err: error instanceof Error ? error.message : String(error) }, + "OpenCode upstream is not available yet; the gateway will retry on demand", + ); + } + })(); + + await app.listen({ host: config.host, port: config.port }); + log.info( + { + service: SERVICE_NAME, + version: VERSION, + url: `http://${config.host}:${config.port}`, + workdir: config.workdir, + agent: config.agent, + authRequired: authRequired(config) && config.apiKeys.length > 0, + }, + "opencode-api listening", + ); } main().catch((error: unknown) => { diff --git a/src/media/mime.ts b/src/media/mime.ts index cf40193..8137824 100644 --- a/src/media/mime.ts +++ b/src/media/mime.ts @@ -93,6 +93,37 @@ export function normalise(mime: string): string { return (mime.split(";")[0] ?? mime).trim().toLowerCase(); } +/** + * RFC 6838 `type/subtype` grammar for a MIME value without parameters. + * + * The media type reaches an upstream `data:;base64,...` URI, where a comma + * would end the media type early and turn the rest of the header into data that + * is no longer base64. Control characters would reach the upstream JSON and the + * `[: ]` prompt marker. Both the caller-declared value and a remote + * `Content-Type` header are rejected here rather than embedded. + */ +const MIME_TYPE_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/; + +/** True when `mime` is a parameter-free `type/subtype` value that may be embedded. */ +export function isValidMimeType(mime: string): boolean { + return MIME_TYPE_PATTERN.test(mime); +} + +/** + * Normalise a declared MIME value, or `undefined` when it would be unsafe to + * embed. + * + * This is the single choke point for both the caller declaration and a remote + * `Content-Type` header: a value that does not match the `type/subtype` grammar + * (a comma, a control character, free-form text) must not survive into the + * upstream `data:` URI, the transcript marker or the response body. Callers fall + * back to sniffing, and then to `application/octet-stream`. + */ +export function normaliseMimeType(mime: string): string | undefined { + const value = normalise(mime); + return isValidMimeType(value) ? value : undefined; +} + /** * Sniff a MIME type from magic bytes. * diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 2d5b12d..188e6bf 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -37,8 +37,83 @@ import net from "node:net"; import path from "node:path"; import type { Config } from "../config.js"; import { ApiError } from "../errors.js"; +import { createLogger } from "../logger.js"; import type { Attachment } from "../types/internal.js"; -import { kindFromMime, mimeFromFileName, normalise, sniffMime } from "./mime.js"; +import { kindFromMime, mimeFromFileName, normalise, normaliseMimeType, sniffMime } from "./mime.js"; + +/** + * Minimal logging surface used for media diagnostics. + * + * The caller-visible error must not carry transport detail (SEC-02), so the + * errno, the URL and the HTTP status are written to the server-side log at + * `debug` instead. The shape is a structural subset of the process logger, so a + * host (or a test) can install any compatible sink with `setMediaLogger()` + * without this module depending on its type. + */ +export interface MediaLogger { + debug(obj: Record, message: string): void; +} + +let mediaLogger: MediaLogger | undefined; + +/** + * Install the logger used for media diagnostics. + * + * The media module is resolved before the process logger exists, so the host + * wires this once at startup (`setMediaLogger(ctx.log)`); with nothing injected, + * the first failure lazily builds an equivalent logger from the running `Config` + * (see `logMediaDebug`). The diagnostics are debug detail, never a contract. + */ +export function setMediaLogger(logger: MediaLogger | undefined): void { + mediaLogger = logger; +} + +/** One lazily built fallback logger per configuration object. */ +const fallbackLoggers = new WeakMap(); + +/** Server-side diagnostics for a media failure; never caller-visible. */ +function logMediaDebug(config: Config, details: Record, message: string): void { + let logger = mediaLogger; + if (logger === undefined) { + logger = fallbackLoggers.get(config); + if (logger === undefined) { + // Plain JSON on purpose: the pretty transport starts a worker thread, and + // this logger is only ever built on a failure path. + const built = createLogger({ ...config, logPretty: false }); + logger = { debug: (obj, text) => built.debug(obj, text) }; + fallbackLoggers.set(config, logger); + } + } + logger.debug(details, message); +} + +/** + * A URL without its credentials, for a message or a log line. + * + * `URL.toString()` keeps a `user:password@` userinfo component, which the + * request itself never sends (`requestMedia()` sets `host` from `url.host` and + * no `auth`), so interpolating it would leak a secret the download never used. + */ +function describeUrl(url: URL): string { + return `${url.host}${url.pathname}`; +} + +/** + * Short, non-reflective description of a transport failure for the server log. + * + * `error.message` is deliberately not used: it embeds the remote body of a + * non-HTTP port ("Parse Error: Expected HTTP/, RTSP/ or ICE/"), which is exactly + * the transport detail the caller-visible message must not carry. + */ +function transportErrorReason(error: unknown): string { + if (error instanceof Error && error.name === "AbortError") return "aborted"; + if (typeof error === "object" && error !== null) { + const code = (error as NodeJS.ErrnoException).code; + if (typeof code === "string" && code !== "") return code; + } + if (error instanceof Error) return error.name; + return "unknown error"; +} export interface MediaSource { /** Full `data:;base64,` URI. */ @@ -464,10 +539,13 @@ function resolveDataUri(source: MediaSource, config: Config, field: string, limi const meta = match[1] ?? ""; const payload = match[2] ?? ""; const isBase64 = /;base64/i.test(meta); - const declaredMime = normalise(meta.split(";")[0] ?? "") || undefined; + const declaredMime = normaliseMimeType(meta.split(";")[0] ?? ""); 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); } else { try { @@ -487,7 +565,11 @@ function resolveDataUri(source: MediaSource, config: Config, field: string, limi } function resolveBase64(source: MediaSource, config: Config, field: string, limitBytes: number): Attachment { - const buffer = decodeBase64(source.base64 ?? "", field); + const payload = source.base64 ?? ""; + // Refuse an obviously oversized payload on its encoded length, before the + // decoded copy (and the whitespace-stripped copy) is allocated. + assertEncodedWithinLimit(payload, field, limitBytes); + const buffer = decodeBase64(payload, field); assertWithinBudget(buffer.byteLength, config, field, source.name, limitBytes); const mime = sniffOrDeclare(buffer, source.mime, source.name); return toAttachment(buffer, mime, source.name, field, "base64"); @@ -510,7 +592,11 @@ async function resolveUrl( let current = parseHttpUrl(source.url, field); const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(new Error("media fetch timeout")), config.mediaFetchTimeoutMs); + const deadline = Date.now() + config.mediaFetchTimeoutMs; + const timer = setTimeout( + () => controller.abort(new MediaFetchTimeoutError(config.mediaFetchTimeoutMs)), + config.mediaFetchTimeoutMs, + ); const onAbort = (): void => controller.abort(signal?.reason); // `AbortSignal.abort()` is already aborted, and an already-aborted signal never // fires its listeners: without this branch an aborted caller still downloaded @@ -518,19 +604,50 @@ async function resolveUrl( if (signal?.aborted) controller.abort(signal.reason); else signal?.addEventListener("abort", onAbort, { once: true }); + /** + * The response body of the hop being handled, destroyed by `finally` unless a + * branch already consumed it. + * + * A redirect whose next hop fails re-validation used to `throw` between the + * `Location` parse and the `destroy()` call, leaving a live `IncomingMessage` + * and its keep-alive socket behind for the agent idle timeout. One per + * attachment, attacker-paced. Every other exit destroyed it; this makes the + * cleanup structural instead of one `destroy()` per branch. + */ + let hopBody: http.IncomingMessage | undefined; + const releaseHopBody = (): void => { + if (hopBody === undefined) return; + if (!hopBody.destroyed) hopBody.destroy(); + hopBody = undefined; + }; + try { // Redirects are followed manually so every hop is re-validated: letting the // HTTP client follow them would let an allowed public URL bounce the request // to loopback or a cloud metadata endpoint. for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) { - const pinned = await resolvePinnedAddress(current, config, field); + // DNS resolution counts against the fetch budget: `dns.lookup()` is + // `getaddrinfo`-based, takes no timeout and cannot be cancelled, so a + // stalled resolver would otherwise hold the request (and a pool worker) + // for the OS resolver budget, per hop, with the client-disconnect signal + // unable to interrupt it (SEC-04). + const pinned = await resolvePinnedAddress(current, config, field, { + signal: controller.signal, + timeoutMs: Math.max(0, deadline - Date.now()), + }); + if (controller.signal.aborted) throw controller.signal.reason ?? new Error("media fetch aborted"); const response = await requestMedia(current, controller.signal, pinned); + hopBody = response.body; const location = headerValue(response.headers["location"]); if (!isRedirect(response.status) || !location) { if (response.status < 200 || response.status >= 300) { - response.body.destroy(); - throw ApiError.badRequest(`Attachment download failed with HTTP ${response.status}: ${current.toString()}`, { + logMediaDebug( + config, + { field, url: describeUrl(current), status: response.status }, + "attachment download failed with an HTTP error status", + ); + throw ApiError.badRequest(`Attachment download failed with HTTP ${response.status}.`, { code: "attachment_download_failed", param: field, }); @@ -538,7 +655,6 @@ async function resolveUrl( const declaredLength = Number(headerValue(response.headers["content-length"]) ?? "0"); if (Number.isFinite(declaredLength) && declaredLength > limitBytes) { - response.body.destroy(); throw ApiError.badRequest( `Attachment is larger than the ${limitBytes}-byte limit (content-length: ${declaredLength}).`, { code: "attachment_too_large", param: field }, @@ -551,23 +667,29 @@ async function resolveUrl( // for `identity`, so any other encoding is a protocol mismatch. const encoding = normalise(headerValue(response.headers["content-encoding"]) ?? ""); if (encoding !== "" && encoding !== "identity") { - response.body.destroy(); throw ApiError.badRequest( `Attachment download used an unsupported content-encoding: ${encoding}.`, { code: "attachment_download_failed", param: field }, ); } + // The stream is consumed by `readBounded()`; the `finally` below finds + // the body already destroyed and does nothing. const buffer = await readBounded(response.body, limitBytes, field); - const headerMime = normalise(headerValue(response.headers["content-type"]) ?? "") || undefined; + hopBody = undefined; + const headerMime = normaliseMimeType(headerValue(response.headers["content-type"]) ?? ""); const name = source.name ?? deriveName(current, headerMime); const mime = sniffOrDeclare(buffer, headerMime ?? source.mime, name); return toAttachment(buffer, mime, name, field, current.toString()); } if (hop === MAX_REDIRECTS) { - response.body.destroy(); - throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects: ${source.url}`, { + logMediaDebug( + config, + { field, url: describeUrl(current), hops: MAX_REDIRECTS }, + "attachment URL exceeded the redirect limit", + ); + throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects.`, { code: "attachment_download_failed", param: field, }); @@ -577,30 +699,57 @@ async function resolveUrl( try { next = new URL(location, current); } catch { - response.body.destroy(); - throw ApiError.badRequest(`Attachment redirect returned an invalid location: ${location}`, { + logMediaDebug( + config, + { field, url: describeUrl(current), location }, + "attachment redirect returned an invalid location", + ); + throw ApiError.badRequest("Attachment redirect returned an invalid location.", { code: "attachment_download_failed", param: field, }); } + + // The body is released *before* the next-hop validation, so a redirect to + // a scheme outside the allow-list cannot leak the connection even if the + // validation grows another throw. + releaseHopBody(); // Scheme allow-list before the next hop; the address guard runs per hop. - parseHttpUrl(next.toString(), field); - response.body.destroy(); + try { + parseHttpUrl(next.toString(), field); + } catch (error) { + logMediaDebug( + config, + { field, url: describeUrl(current), next: describeUrl(next), protocol: next.protocol }, + "attachment redirect rejected by the scheme allow-list", + ); + throw error; + } current = next; } - throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects: ${source.url}`, { + throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects.`, { code: "attachment_download_failed", param: field, }); } catch (error) { if (error instanceof ApiError) throw error; - const reason = error instanceof Error ? error.message : String(error); - throw ApiError.badRequest(`Could not download attachment from ${current.toString()}: ${reason}`, { - code: "attachment_download_failed", - param: field, - }); + // Transport detail (errno, TLS error, a non-HTTP port's parse error) is a + // connect oracle for an authenticated caller, and `error.message` for a + // non-HTTP port quotes the remote protocol. Keep it server-side only. + logMediaDebug( + config, + { + field, + url: describeUrl(current), + reason: transportErrorReason(error), + aborted: controller.signal.aborted, + }, + "attachment download failed", + ); + throw ApiError.badRequest("Attachment download failed.", { code: "attachment_download_failed", param: field }); } finally { + releaseHopBody(); clearTimeout(timer); signal?.removeEventListener("abort", onAbort); } @@ -619,6 +768,20 @@ function headerValue(value: string | string[] | undefined): string | undefined { return value; } +/** + * Raised when name resolution blows the remaining fetch budget. + * + * A sentinel rather than a bare `AbortError` so the transport-error log can say + * "dns timeout" instead of an opaque abort, while the caller still receives the + * standard 400. + */ +class MediaFetchTimeoutError extends Error { + constructor(timeoutMs: number) { + super(`media fetch timed out after ${timeoutMs} ms`); + this.name = "MediaFetchTimeoutError"; + } +} + /** * Resolve the host of a URL and return the address the connection must use. * @@ -627,8 +790,18 @@ function headerValue(value: string | string[] | undefined): string | undefined { * the guard on, the address is pinned and handed to the request through a * `lookup` callback, so the socket connects to exactly the address that was * validated instead of resolving the hostname a second time (DNS rebinding). + * + * The lookup is bounded by the caller's `signal` and the remaining fetch budget + * (SEC-04): `dns.lookup()` itself can be neither timed out nor cancelled, so the + * race in `lookupAddressesWithin()` is what keeps a stalled resolver from holding + * the request for the OS resolver budget on every hop. */ -async function resolvePinnedAddress(url: URL, config: Config, field: string): Promise { +async function resolvePinnedAddress( + url: URL, + config: Config, + field: string, + budget: { signal: AbortSignal; timeoutMs: number }, +): Promise { if (config.allowPrivateMediaUrls) return undefined; const hostname = url.hostname.replace(/^\[|\]$/g, ""); @@ -642,14 +815,14 @@ async function resolvePinnedAddress(url: URL, config: Config, field: string): Pr const literal = net.isIP(hostname); if (literal !== 0) return { address: hostname, family: literal }; - const validated = await lookupAddresses(hostname); + const validated = await lookupAddressesWithin(hostname, budget); assertAddressesPublic(validated, hostname, field); // Resolve once more immediately before dialling: the first answer validated // above, the second is what the socket will use. Both must be public, so a // hostname that flips to a private address between the check and the connect // is rejected instead of reached. - const pinned = await lookupAddresses(hostname); + const pinned = await lookupAddressesWithin(hostname, budget); assertAddressesPublic(pinned, hostname, field); const first = pinned[0]; if (first === undefined) { @@ -661,6 +834,50 @@ async function resolvePinnedAddress(url: URL, config: Config, field: string): Pr return { address: first.address, family: first.family }; } +/** + * Look a hostname up under the caller's abort signal and the remaining fetch + * budget. + * + * `dns.lookup()` accepts neither a timeout nor an abort, so it is raced against + * both here. The underlying `getaddrinfo` call keeps running after the race is + * lost — Node exposes no way to cancel it — but the request stops waiting and the + * caller gets the standard 400 instead of being held for the OS resolver budget. + */ +async function lookupAddressesWithin( + hostname: string, + budget: { signal: AbortSignal; timeoutMs: number }, +): Promise { + const { signal, timeoutMs } = budget; + if (signal.aborted) throw signal.reason ?? new Error("media fetch aborted"); + if (timeoutMs <= 0) throw new MediaFetchTimeoutError(timeoutMs); + + let timer: NodeJS.Timeout | undefined; + const deadline = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new MediaFetchTimeoutError(timeoutMs)), timeoutMs); + }); + let onAbort: (() => void) | undefined; + const aborted = new Promise((_resolve, reject) => { + onAbort = (): void => { + signal.removeEventListener("abort", onAbort as () => void); + reject(signal.reason ?? new MediaFetchTimeoutError(timeoutMs)); + }; + if (signal.aborted) onAbort(); + else signal.addEventListener("abort", onAbort, { once: true }); + }); + + try { + const lookup = lookupAddresses(hostname); + // A rejection of the losing promise must not surface as an unhandled + // rejection once the race has settled. + lookup.catch(() => undefined); + aborted.catch(() => undefined); + return await Promise.race([lookup, deadline, aborted]); + } finally { + if (timer !== undefined) clearTimeout(timer); + if (onAbort !== undefined) signal.removeEventListener("abort", onAbort); + } +} + async function lookupAddresses(hostname: string): Promise { return dns.lookup(hostname, { all: true, verbatim: true }); } @@ -746,7 +963,12 @@ function parseHttpUrl(value: string | undefined, field: string): URL { try { parsed = new URL(value ?? ""); } catch { - throw ApiError.badRequest(`Invalid attachment URL: ${value}`, { code: "invalid_attachment", param: field }); + // The raw input is never echoed: it can carry a credential in the userinfo + // or a token in the query string, and the caller already knows what it sent. + throw ApiError.badRequest(`Invalid attachment URL (${field}).`, { + code: "invalid_attachment", + param: field, + }); } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { throw ApiError.badRequest(`Unsupported attachment URL protocol: ${parsed.protocol}`, { @@ -848,7 +1070,17 @@ async function resolveLocalFile( { code: "attachment_too_large", param: field }, ); } - buffer = await handle.readFile(); + // Bounded chunked read through the same handle the `stat` came from: the + // pre-read `stat` can be stale (a file that grows between the two calls) or + // meaningless (procfs reports size 0 for a regular file), and `readFile()` + // used to materialise the whole file before the cap was re-applied. The + // shared collector enforces the same bound as the remote path. + buffer = await collectBounded(readHandleChunks(handle, limitBytes), limitBytes, () => + ApiError.badRequest(`Attachment is larger than the ${limitBytes}-byte limit.`, { + code: "attachment_too_large", + param: field, + }), + ); } catch (error) { throw localFileError(error, requested, field); } finally { @@ -856,10 +1088,6 @@ async function resolveLocalFile( } const name = source.name ?? path.basename(realPath); - // The pre-read `stat` can be stale (a file that grows between the two calls) - // or meaningless (procfs reports size 0 for a regular file), so the bytes that - // were actually read are checked against the same budget as well. - assertWithinBudget(buffer.byteLength, config, field, name, limitBytes); const mime = sniffOrDeclare(buffer, source.mime, name); return toAttachment(buffer, mime, name, field, realPath); } @@ -893,18 +1121,46 @@ function localFileError(error: unknown, requested: string, field: string): ApiEr throw error; } +/** + * 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. + */ +function assertEncodedWithinLimit(payload: string, field: string, limitBytes: number): void { + const maxEncoded = Math.ceil((limitBytes * 4) / 3) + 4; + if (payload.length > maxEncoded) { + throw ApiError.badRequest(`Attachment payload is larger than the ${limitBytes}-byte limit.`, { + code: "attachment_too_large", + param: field, + }); + } +} + +const BASE64_ALPHABET = /^[A-Za-z0-9+/=_\-\s]*$/; +/** A base64 payload may only end in at most two `=` padding characters. */ +const BASE64_PADDING = /^[A-Za-z0-9+/_\-\s]*={0,2}\s*$/; + function decodeBase64(payload: string, field: string): Buffer { - const cleaned = payload.replace(/\s+/g, ""); - if (cleaned.length === 0) { + if (payload.trim().length === 0) { throw ApiError.badRequest("Attachment payload is empty.", { code: "invalid_attachment", param: field }); } - if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(cleaned)) { + // 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. + if (!BASE64_ALPHABET.test(payload) || !BASE64_PADDING.test(payload)) { throw ApiError.badRequest("Attachment payload is not valid base64.", { code: "invalid_attachment", param: field, }); } - const normalised = cleaned.replace(/-/g, "+").replace(/_/g, "/"); + // `Buffer` ignores whitespace; only base64url alphabets need a swap. + const normalised = payload.includes("-") || payload.includes("_") ? payload.replace(/-/g, "+").replace(/_/g, "/") : payload; const buffer = Buffer.from(normalised, "base64"); if (buffer.byteLength === 0) { throw ApiError.badRequest("Attachment payload decoded to zero bytes.", { @@ -917,7 +1173,11 @@ function decodeBase64(payload: string, field: string): Buffer { function sniffOrDeclare(buffer: Buffer, declaredMime: string | undefined, name: string | undefined): string { const fromName = name ? mimeFromFileName(name) : undefined; - const fallback = declaredMime ? normalise(declaredMime) : fromName; + // A declared type (`media_type`, `mime_type`, a remote `Content-Type`) or a + // name-derived one reaches the upstream `data:` URI verbatim, so anything that + // is not a `type/subtype` token is dropped here instead of embedded. The order + // matches the historical precedence: declaration, then the file name. + const fallback = normaliseMimeType(declaredMime ?? "") ?? normaliseMimeType(fromName ?? ""); const sniffed = sniffMime(buffer, fallback); // Sniffing wins for well-known binary signatures; otherwise keep the declared type. if (sniffed !== "application/octet-stream") return sniffed; @@ -970,19 +1230,33 @@ function assertWithinBudget( } } -async function readBounded(body: http.IncomingMessage, maxBytes: number, field: string): Promise { +/** Per-read allocation ceiling for a bounded read (remote or local). */ +const MEDIA_READ_CHUNK_BYTES = 64 * 1024; + +/** + * Concatenate a chunk source, refusing to retain more than `maxBytes`. + * + * The bound is checked before each chunk is pushed, so the worst case retention is + * one chunk past the limit. Shared by the remote (`readBounded`) and local + * (`readHandleChunks`) paths so a single check covers both — `FileHandle.readFile()` + * used to grow its buffer to whatever the file contained and only then have the + * cap re-applied. + */ +async function collectBounded( + source: AsyncIterable, + maxBytes: number, + tooLarge: () => ApiError, + onOverflow?: () => void, +): Promise { const chunks: Buffer[] = []; let total = 0; - for await (const chunk of body as AsyncIterable) { + for await (const chunk of source) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); total += buffer.byteLength; if (total > maxBytes) { - body.destroy(); - throw ApiError.badRequest(`Attachment download exceeded the ${maxBytes}-byte limit.`, { - code: "attachment_too_large", - param: field, - }); + onOverflow?.(); + throw tooLarge(); } chunks.push(buffer); } @@ -990,6 +1264,42 @@ async function readBounded(body: http.IncomingMessage, maxBytes: number, field: return Buffer.concat(chunks, total); } +/** + * Yield a file's bytes in bounded chunks. + * + * Each iteration allocates at most `min(64 KiB, limitBytes + 1 - offset)`, so a + * file that grows between the `stat` and EOF cannot be fully materialised before + * the cap rejects it: the collector throws on the first chunk that pushes the + * total past `limitBytes`. + */ +async function* readHandleChunks(handle: FileHandle, limitBytes: number): AsyncGenerator { + let offset = 0; + + for (;;) { + const remaining = limitBytes + 1 - offset; + if (remaining <= 0) return; + const size = Math.min(MEDIA_READ_CHUNK_BYTES, remaining); + const chunk = Buffer.allocUnsafe(size); + const { bytesRead } = await handle.read(chunk, 0, size, offset); + if (bytesRead === 0) return; + offset += bytesRead; + yield bytesRead === size ? chunk : chunk.subarray(0, bytesRead); + } +} + +async function readBounded(body: http.IncomingMessage, maxBytes: number, field: string): Promise { + return collectBounded( + body as AsyncIterable, + maxBytes, + () => + ApiError.badRequest(`Attachment download exceeded the ${maxBytes}-byte limit.`, { + code: "attachment_too_large", + param: field, + }), + () => body.destroy(), + ); +} + function deriveName(url: URL, mime: string | undefined): string | undefined { const base = path.basename(url.pathname); if (base && base !== "/" && base !== ".") return base; @@ -1141,7 +1451,11 @@ export function isWithinRoots(candidate: string, roots: readonly string[]): bool const rootPath = path.resolve(root); if (resolved === rootPath) return true; const relative = path.relative(rootPath, resolved); - if (relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative)) return true; + // Separator-aware traversal test: `..foo` is a legal child directory name, + // while `..` and `../evil` (or `..\evil`) escape the root. + if (relative !== "" && !path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)) { + return true; + } } return false; } \ No newline at end of file diff --git a/src/server.ts b/src/server.ts index 0261c85..c08f5fc 100644 --- a/src/server.ts +++ b/src/server.ts @@ -13,9 +13,10 @@ import { registerAnthropicCountTokenRoutes } from "./adapter/anthropic/countToke import { registerAnthropicMessageRoutes } from "./adapter/anthropic/messages.js"; import { requireApiKey } from "./auth.js"; import type { AppContext } from "./context.js"; +import type { Config } from "./config.js"; import { ApiError, toAnthropicError, toApiError, toOpenAiError } from "./errors.js"; import { createRateLimiters, requireRateLimit } from "./http/rateLimit.js"; -import { applyRequestTimeout } from "./http/timeout.js"; +import { applyRequestTimeout, armBodyDeadline, clearBodyDeadline } from "./http/timeout.js"; import { registerAdminRoutes } from "./routes/admin.js"; import { registerHealthRoutes } from "./routes/health.js"; import { registerMetricsRoutes } from "./routes/metrics.js"; @@ -41,6 +42,28 @@ function resolveRequestId(headers: IncomingHttpHeaders): string { return typeof value === "string" && REQUEST_ID_PATTERN.test(value) ? value : randomUUID(); } +/** + * `Config.trustProxy` in the shape Fastify actually honours. + * + * Fastify's option parser only understands a boolean, a string (or string + * list) of addresses/CIDRs and a function — a *number* is not one of its cases + * and is silently dropped, which would make `OPENCODE_TRUST_PROXY=2` trust + * nothing at all. A hop count is therefore compiled into the function form, + * where hop `0` is the immediate peer, so `hop < hops` trusts exactly the + * configured number of proxies. + * + * `true` means "trust every hop", and that is precisely the value that lets a + * caller forge the address the rate limiter buckets on. + */ +function fastifyTrustProxy( + value: Config["trustProxy"], +): boolean | string | string[] | ((address: string, hop: number) => boolean) { + if (typeof value === "number") return (_address: string, hop: number): boolean => hop < value; + // A readonly string list needs a copy: Fastify types its option as mutable. + if (typeof value !== "boolean") return [...value]; + return value; +} + export async function buildServer(ctx: AppContext): Promise { // Fastify parameterises `FastifyInstance` by the logger type; casting keeps // every route module on the default `FastifyInstance` type without leaking @@ -48,7 +71,7 @@ export async function buildServer(ctx: AppContext): Promise { const app = Fastify({ loggerInstance: ctx.log, bodyLimit: ctx.config.bodyLimitBytes, - trustProxy: ctx.config.trustProxy, + trustProxy: fastifyTrustProxy(ctx.config.trustProxy), // Correlate gateway logs with the caller's own trace id when it sends one. genReqId: (raw) => resolveRequestId(raw.headers), // Upstream calls are long; never let Fastify cut a streaming response short. @@ -125,17 +148,20 @@ export async function buildServer(ctx: AppContext): Promise { }); // ---------------------------------------------------------------- auth --- + // The limiter pair is built first because the authenticator charges the + // failed-authentication bucket on its rejection path. + const limiters = createRateLimiters(ctx.config); + // `onRequest`, not `preHandler`: Fastify parses the body between `preParsing` // and `preHandler`, so a `preHandler` authenticator lets an anonymous caller // make the gateway buffer and JSON-parse up to `bodyLimitBytes`. Registered // after the CORS hooks above, so a preflight is still answered without a key. - app.addHook("onRequest", requireApiKey(ctx.config)); + app.addHook("onRequest", requireApiKey(ctx.config, limiters)); // --------------------------------------------------------- rate limit --- // Beside `requireApiKey`, and for the same reason an `onRequest` hook: the // limiter charges the caller before any body is read, and `/admin/*` has a // separate bucket. - const limiters = createRateLimiters(ctx.config); app.addHook( "onRequest", requireRateLimit(ctx.config, limiters, (scope) => { @@ -144,10 +170,19 @@ export async function buildServer(ctx: AppContext): Promise { ); // ------------------------------------------------------------- timeout --- + // Body receipt is bounded before Fastify reads a single byte: the deadline is + // armed in `preParsing` and cancelled as soon as the body is complete, so a + // caller cannot dribble a body forever while the gateway buffers it. + app.addHook("preParsing", async (request, reply) => { + armBodyDeadline(request, reply, ctx.config); + }); + // Buffered routes get a bounded socket timeout; streaming routes stay // unbounded so a long SSE answer is never cut off. This must stay a - // `preHandler` because the bound depends on the parsed request body. + // `preHandler` because the bound depends on the parsed request body. Clearing + // the body deadline here is what keeps it off a long `stream: true` response. app.addHook("preHandler", async (request, reply) => { + clearBodyDeadline(request); applyRequestTimeout(request, reply, ctx.config); }); @@ -183,6 +218,14 @@ export async function buildServer(ctx: AppContext): Promise { if (apiError.status >= 500) { request.log.error({ err: error, code: apiError.code }, "request failed"); + } else if (apiError.status === 401) { + // An authentication rejection is an audit event, not debug noise: it must + // be visible at the default `info` level. Neither the presented credential + // nor any header is logged — only the request id and the route. + request.log.warn( + { requestId: request.id, method: request.method, route: request.routeOptions?.url ?? "unmatched" }, + "request rejected: authentication failed", + ); } else { request.log.debug({ code: apiError.code, message: apiError.message }, "request rejected"); } diff --git a/src/startup.ts b/src/startup.ts index b809de2..b4102ce 100644 --- a/src/startup.ts +++ b/src/startup.ts @@ -39,6 +39,34 @@ export function isLoopbackHost(host: string): boolean { return /^127(?:\.\d{1,3}){3}$/.test(normalised); } +/** + * Fatal-note text for the fail-open quickstart: `HOST=0.0.0.0` plus the API key + * that ships with the repository. + * + * `.env.example` contains `OPENCODE_API_KEYS=sk-dummy-123` and the container + * image hard-codes `HOST=0.0.0.0`, so the documented + * `cp .env.example .env && docker compose up` used to publish a reachable + * gateway whose only credential is printed in the repository. A warning is not + * enough: the caller of this helper refuses to start. + * + * `undefined` means "start normally": the bind host is loopback, authentication + * is disabled on purpose, or a real key is configured. + */ +export function defaultKeyExposureError(config: { + host: string; + usingDefaultApiKey: boolean; + allowNoAuth: boolean; +}): string | undefined { + if (!config.usingDefaultApiKey || config.allowNoAuth) return undefined; + if (isLoopbackHost(config.host)) return undefined; + return ( + `Refusing to start: HOST=${config.host} is reachable from the network and the gateway still accepts the ` + + `built-in default API key "${DEFAULT_API_KEY}", which is published with the project.\n` + + "Set OPENCODE_API_KEYS to a secret value (see .env.example), or bind HOST=127.0.0.1, " + + "or set OPENCODE_ALLOW_NO_AUTH=true on a trusted host." + ); +} + /** * Warning printed when remote media may target private addresses on a host that * is reachable from the network. diff --git a/src/upstream/client.ts b/src/upstream/client.ts index b347e4f..b7cf814 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -172,7 +172,10 @@ export class OpencodeClient { if (timedOut) { // The abort came from this client's own timer, not from the caller, so // this is a gateway timeout (504), not an unreachable upstream (503). - this.#process.markStale(`Upstream request timed out: ${reason}`); + // A timeout only means the endpoint must be re-verified: killing the + // shared child would fail every in-flight turn of every caller, so the + // child survives unless its re-probe stops answering. + this.#process.reprobe(`Upstream request timed out: ${reason}`); throw ApiError.timeout(`OpenCode did not answer within ${timeoutMs} ms.`, { code: "upstream_timeout", cause: error, diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 2aa3333..7507f6b 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -421,6 +421,19 @@ async function prepare( */ const STREAM_GAP_GRACE_MS = 5_000; +/** + * Frames a single completion may hold for a consumer that stopped reading. + * + * The queue exists because the shared event hub pushes frames while the consumer + * is between `next()` calls; a consumer parked on a slow client would otherwise + * let the hub grow the heap at the upstream frame rate. Above this bound the turn + * fails through the existing `event_stream_lost` path, because a frame that is + * not queued leaves a gap in the same way a reconnect does. The bound is far + * above any legitimate burst (a step's deltas are drained between frames), so a + * healthy turn never reaches it. + */ +export const MAX_QUEUED_EVENTS = 10_000; + async function* execute( prepared: Prepared, deps: CompletionDeps, @@ -502,6 +515,14 @@ async function* execute( const collectedText: string[] = []; const collectedReasoning: string[] = []; const nativeTools: NativeToolActivity[] = []; + /** + * Tool id → last known name, filled by `session.tool.input.started` (the only + * event that carries a name). `nativeTools` used to be scanned backwards for + * every `called`/`success`/`failed` frame, which made a turn with k native + * tools cost O(k²) comparisons; the array is still kept for the `x_opencode` + * payload every surface copies out. + */ + const toolNames = new Map(); let usage: Usage = { ...EMPTY_USAGE }; let messageId = ""; let finishReason: FinishReason = "stop"; @@ -550,6 +571,19 @@ async function* execute( const waitBudget = gapDeadline === undefined ? remaining : Math.min(remaining, gapDeadline - Date.now()); const next = await queue.next(Math.min(Math.max(waitBudget, 0), 1_000), options.signal); + if (queue.overflowed) { + // The consumer fell more than `MAX_QUEUED_EVENTS` behind, so frames were + // rejected instead of buffered. That leaves the same kind of hole a + // reconnect does, and reporting a truncated answer as a normal stop is + // not acceptable: fail loudly through the `event_stream_lost` path. + await safeInterrupt(client, sessionId, log); + const error = ApiError.unavailable("OpenCode event queue overflowed; the response may be incomplete.", { + code: "event_stream_lost", + }); + recordError(error); + yield { kind: "error", error }; + return; + } if (next === "aborted") { await safeInterrupt(client, sessionId, log); const error = new ApiError(499, "timeout_error", "Client disconnected."); @@ -639,9 +673,12 @@ async function* execute( } case "session.tool.input.started": { + const id = stringValue(data["id"]); + const name = stringValue(data["name"]); + if (name !== "") toolNames.set(id, name); const activity: NativeToolActivity = { - id: stringValue(data["id"]), - name: stringValue(data["name"]), + id, + name, status: "started", }; nativeTools.push(activity); @@ -650,9 +687,10 @@ async function* execute( } case "session.tool.called": { + const id = stringValue(data["id"]); const activity: NativeToolActivity = { - id: stringValue(data["id"]), - name: lastToolName(nativeTools, stringValue(data["id"])), + id, + name: toolNames.get(id) ?? "", status: "called", input: data["input"], }; @@ -661,9 +699,10 @@ async function* execute( } case "session.tool.success": { + const id = stringValue(data["id"]); const activity: NativeToolActivity = { - id: stringValue(data["id"]), - name: lastToolName(nativeTools, stringValue(data["id"])), + id, + name: toolNames.get(id) ?? "", status: "succeeded", }; yield { kind: "native_tool", activity }; @@ -671,9 +710,10 @@ async function* execute( } case "session.tool.failed": { + const id = stringValue(data["id"]); const activity: NativeToolActivity = { - id: stringValue(data["id"]), - name: lastToolName(nativeTools, stringValue(data["id"])), + id, + name: toolNames.get(id) ?? "", status: "failed", error: structuredErrorMessage(data["error"]), }; @@ -1089,27 +1129,42 @@ function stringValue(value: unknown): string { return typeof value === "string" ? value : ""; } -function lastToolName(activities: NativeToolActivity[], id: string): string { - for (let index = activities.length - 1; index >= 0; index -= 1) { - const activity = activities[index]; - if (activity && activity.id === id && activity.name) return activity.name; - } - return ""; -} - /** Buffered bridge between the shared event hub and a single completion. */ class EventQueue { - readonly #items: OpencodeEvent[] = []; + #items: OpencodeEvent[] = []; + /** + * Read cursor into `#items`. Dequeuing used to call `Array.prototype.shift()`, + * which moves every remaining element, so draining a backlog that grew during a + * backpressure stall cost O(n²) exactly when the process was already under + * pressure. The array is released once it is fully consumed, which keeps the + * retention bounded. + */ + #head = 0; + #overflowed = false; readonly #waiters: Array<(value: OpencodeEvent) => void> = []; + /** True once a frame was rejected because the queue hit `MAX_QUEUED_EVENTS`. */ + get overflowed(): boolean { + return this.#overflowed; + } + push(event: OpencodeEvent): void { const waiter = this.#waiters.shift(); if (waiter) waiter(event); + else if (this.#items.length - this.#head >= MAX_QUEUED_EVENTS) this.#overflowed = true; else this.#items.push(event); } async next(timeoutMs: number, signal?: AbortSignal): Promise { - if (this.#items.length > 0) return this.#items.shift() as OpencodeEvent; + if (this.#head < this.#items.length) { + const event = this.#items[this.#head] as OpencodeEvent; + this.#head += 1; + if (this.#head === this.#items.length) { + this.#items = []; + this.#head = 0; + } + return event; + } if (signal?.aborted) return "aborted"; return await new Promise((resolve) => { diff --git a/src/upstream/models.ts b/src/upstream/models.ts index 7bdd509..4a7cbbc 100644 --- a/src/upstream/models.ts +++ b/src/upstream/models.ts @@ -34,6 +34,18 @@ export class ModelRegistry { #catalog?: ModelCatalog; #inFlight?: Promise; + /** + * When the upstream first answered with no models while a catalogue was being + * retained. + * + * A single empty answer must not discard a good catalogue (the server reports + * readiness before its providers register), but a catalogue retained forever + * would keep `/ready` ready and `/v1/models` listing models the upstream no + * longer serves. The age of this timestamp bounds the retention: once the TTL + * has elapsed since the first empty answer the retained catalogue is dropped + * and the real empty answer is cached. Cleared by any non-empty answer. + */ + #emptySince?: number; constructor(client: OpencodeClient, config: Config, log: Logger) { this.#client = client; @@ -74,25 +86,47 @@ export class ModelRegistry { // cache TTL). A single empty answer — a forced refresh // (`GET /v1/models?refresh=1`, `POST /admin/models/refresh`) or a TTL // expiry, both of which bypass the cache — must not discard a good - // catalogue either: keep the previous one and let the TTL decide when it - // expires, while still returning the real (empty) answer to the caller. - // One transient upstream hiccup otherwise turned every model call into + // catalogue either: keep the previous one for a bounded grace window, + // while still returning the real (empty) answer to the caller. One + // transient upstream hiccup otherwise turned every model call into // `404 model_not_found` until a non-empty answer happened to load. if (catalog.models.length > 0) { this.#catalog = catalog; + this.#emptySince = undefined; this.#log.debug( { models: catalog.models.length, agents: catalog.agents.length }, "refreshed model catalog", ); } else if (this.#catalog) { - // Refresh the retained catalogue's timestamp: every request would - // otherwise see the entry as expired, re-read the empty answer and pay - // `#retryEmpty()` again while the provider is still cold. - this.#catalog = { ...this.#catalog, fetchedAt: catalog.fetchedAt }; - this.#log.warn( - { agents: catalog.agents.length, retained: this.#catalog.models.length }, - "OpenCode reported no models; keeping the previous catalogue", - ); + // Age of the retention window, anchored on the last empty answer. A + // permanently empty upstream is masked for one TTL; a *repeated* empty + // answer inside that window re-anchors it, so two consecutive polls + // never drop the catalogue between them. A cold start with nothing to + // fall back on is not tracked here at all: it keeps retrying on every + // request instead of serving an empty catalogue for a whole TTL. + this.#emptySince ??= catalog.fetchedAt; + if (catalog.fetchedAt - this.#emptySince < this.#config.modelCacheTtlMs) { + // Refresh the retained catalogue's timestamp: every request would + // otherwise see the entry as expired, re-read the empty answer and pay + // `#retryEmpty()` again while the provider is still cold. + this.#catalog = { ...this.#catalog, fetchedAt: catalog.fetchedAt }; + this.#log.warn( + { agents: catalog.agents.length, retained: this.#catalog.models.length }, + "OpenCode reported no models; keeping the previous catalogue", + ); + } else { + // Past the grace window the real answer becomes the catalogue, so + // `/ready`, `/v1/models` and `resolve()` stop reporting models the + // upstream no longer serves. The clock restarts so the retained + // catalogue can still cover the next window if the upstream recovers + // and goes empty again. + this.#catalog = catalog; + this.#emptySince = catalog.fetchedAt; + this.#log.warn( + { agents: catalog.agents.length }, + "OpenCode reported no models; dropping the retained catalogue", + ); + } } else { this.#log.warn( { agents: catalog.agents.length }, diff --git a/src/upstream/process.ts b/src/upstream/process.ts index d48be03..ef72dad 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -22,7 +22,20 @@ export type SpawnedChild = ChildProcessByStdio; /** Starts the OpenCode server; injectable so tests can script the lifecycle. */ export type SpawnChildFn = (command: string, args: string[]) => SpawnedChild; -/** Test seams for `UpstreamProcess`. Production code leaves both unset. */ +/** + * Outcome of the readiness probe. + * + * `"unauthorized"` and `"absent"` used to be collapsed into a boolean, which + * reported a wrong `OPENCODE_SERVER_PASSWORD` (HTTP 401) as "not reachable" and + * hid the real cause behind a generic message. A 400 still counts as reachable: + * an OpenCode build may answer that to an unauthenticated probe. + */ +export type ProbeResult = "ok" | "unauthorized" | "absent"; + +/** Probes one endpoint; injectable so tests do not need a listening server. */ +export type ProbeFn = (endpoint: UpstreamEndpoint, timeoutMs?: number) => Promise; + +/** Test seams for `UpstreamProcess`. Production code leaves all of them unset. */ export interface UpstreamProcessOptions { spawn?: SpawnChildFn; findBinary?: (explicit?: string) => string | undefined; @@ -31,6 +44,12 @@ export interface UpstreamProcessOptions { * whatever `opencode serve` may be running on the machine. */ discover?: () => Promise; + /** + * Override the readiness probe. Tests use it to script `ok` / `unauthorized` / + * `absent` without standing up an HTTP listener; the default implementation + * performs a real `GET /api/model` with its own 5 s bound. + */ + probe?: ProbeFn; } export type EndpointSource = "env" | "spawned" | "discovered"; @@ -177,6 +196,24 @@ function clampTail(value: string, limit: number): string { return value.length > limit ? value.slice(-limit) : value; } +/** + * Mask the upstream server credential inside free-form child output. + * + * The spawned server prints `server password ` on its own stdout (that + * line is how the gateway learns the credential), so a verbatim copy of the + * child stream writes the password to `/logs/opencode-.log` and + * `GET /admin/status` would echo it back to any authenticated caller. The same + * masking is applied to the stderr excerpts embedded in spawn error messages. + * + * Deliberately narrow: only the value that follows the `server password` marker + * and a Basic credential are replaced, so ordinary diagnostics survive verbatim. + */ +export function redactUpstreamSecret(text: string): string { + return text + .replace(/(server password\s+)\S+/gi, "$1[redacted]") + .replace(/(authorization:\s*Basic\s+)[A-Za-z0-9+/=]+/gi, "$1[redacted]"); +} + export class UpstreamProcess { /** * Instances that have spawned at least one child, and the single `process` @@ -195,6 +232,7 @@ export class UpstreamProcess { readonly #spawnChild: SpawnChildFn; readonly #findBinary: (explicit?: string) => string | undefined; readonly #discoverService: () => Promise; + readonly #probeEndpoint: ProbeFn; #endpoint?: UpstreamEndpoint; #child?: SpawnedChild; @@ -230,6 +268,15 @@ export class UpstreamProcess { /** A `markStale()`/`invalidate()` happened since the last resolve. */ #stalePending = false; #invalidatedPending = false; + /** Set by `reprobe()`: the endpoint was dropped but the child may still be + * sound, so `#resolveInternal()` must re-verify the remembered endpoint before + * spawning a replacement. + */ + #reprobe = false; + /** URL the live `#child` last published, for the `reprobe()` re-verification. */ + #childUrl?: string; + /** Credential that goes with `#childUrl`. Never exposed through `status()`. */ + #childPassword?: string; constructor( config: Config, @@ -256,6 +303,7 @@ export class UpstreamProcess { }) as SpawnedChild); this.#binary = this.#findBinary(config.upstreamBin); this.#discoverService = options.discover ?? (() => this.#discover()); + this.#probeEndpoint = options.probe ?? ((endpoint, timeoutMs) => this.#probe(endpoint, timeoutMs)); } get binary(): string | undefined { @@ -271,7 +319,9 @@ export class UpstreamProcess { binary: this.#binary, lastError: this.#lastError, lastStartedAt: this.#lastStartedAt, - stderrTail: this.#stderrTail.lines, + // Redacted on read as the authoritative boundary: a marker split across two + // chunks is only caught here, never at push time. + stderrTail: this.#stderrTail.lines.map(redactUpstreamSecret), }; } @@ -301,10 +351,24 @@ export class UpstreamProcess { async stop(): Promise { this.#stopping = true; this.#stopped = true; + // A `reprobe()` request is about the endpoint that is being dropped here. + this.#reprobe = false; const child = this.#child; this.#child = undefined; this.#endpoint = undefined; - if (!child || child.exitCode !== null) return; + this.#forgetChildEndpoint(); + + // A start that is still inside its readiness window lives in `#liveChildren` + // only, so `#child` alone is not enough: without this, a stop() during a cold + // start was a no-op whose child was later adopted as the "replacement". + this.#killLiveChildren(child); + const starting = this.#starting; + + if (!child || child.exitCode !== null) { + await starting?.catch(() => undefined); + return; + } + await new Promise((resolve) => { const timer = setTimeout(() => { try { @@ -325,6 +389,26 @@ export class UpstreamProcess { resolve(); } }); + // Callers observe a settled state: no start is left racing the stop. + await starting?.catch(() => undefined); + } + + /** + * Drop the cached endpoint without touching the child. + * + * Used when a request timed out: a busy but alive server must not be killed + * under every in-flight turn, which is what `markStale()` does. The next + * `resolve()` re-verifies the remembered child endpoint first (with `#probe`'s + * own 5 s bound) and only spawns a replacement when it no longer answers. + */ + reprobe(reason: string): void { + this.#lastError = reason; + // Only an actually published endpoint is worth re-verifying. The flag is only + // ever raised here, never lowered: a second timeout that arrives before the + // next `resolve()` must not cancel the first one's re-verification, or the + // spawn path would SIGKILL the child the first timeout deliberately spared. + if (this.#endpoint !== undefined) this.#reprobe = true; + this.#endpoint = undefined; } /** @@ -348,6 +432,7 @@ export class UpstreamProcess { async shutdown(): Promise { this.#terminated = true; this.#stopping = true; + this.#reprobe = false; const starting = this.#starting; if (starting) { @@ -407,21 +492,60 @@ export class UpstreamProcess { password: this.#config.upstreamPassword, source: "env", }; - if (await this.#probe(endpoint)) { + const probe = await this.#probeEndpoint(endpoint); + if (probe === "ok") { this.#assertNotTerminated(); this.#endpoint = endpoint; return endpoint; } + if (probe === "unauthorized") { + this.#lastError = unauthorizedMessage(endpoint.url); + throw ApiError.unavailable(this.#lastError, { code: "upstream_unauthorized" }); + } this.#lastError = `Configured OPENCODE_SERVER_URL is not reachable: ${endpoint.url}`; throw ApiError.unavailable(this.#lastError, { code: "upstream_unreachable" }); } const failures: string[] = []; + // A timed-out request marked the endpoint for re-verification, not for + // replacement: probe the server the live child already published before + // walking the spawn path, so one slow `/api/model` does not kill the server + // under every in-flight turn. + const remembered = this.#rememberedEndpoint(); + if (this.#reprobe && remembered) { + this.#reprobe = false; + const probe = await this.#probeEndpoint(remembered); + this.#assertNotTerminated(); + if (probe === "ok") { + this.#endpoint = remembered; + this.#log.info({ url: remembered.url }, "re-verified the OpenCode server after a timed-out request"); + return remembered; + } + // Re-verification failed, or proved an authentication problem: neither + // keeps a child that cannot serve requests. + this.#lastError = + probe === "unauthorized" ? unauthorizedMessage(remembered.url) : `Re-probe failed for ${remembered.url}`; + const child = this.#child; + this.#child = undefined; + this.#forgetChildEndpoint(); + if (child && child.exitCode === null) { + this.#log.warn({ pid: child.pid }, "terminating the OpenCode server that failed its re-probe"); + try { + child.kill("SIGKILL"); + } catch { + /* already gone */ + } + } + } + if (this.#config.upstreamAutostart) { try { const spawned = await this.#spawn(); this.#endpoint = spawned.endpoint; + this.#reprobe = false; + this.#childUrl = spawned.endpoint.url; + this.#childPassword = spawned.endpoint.password; this.#lastStartedAt = Date.now(); this.#startFailures = 0; this.#startBackoffUntil = 0; @@ -454,6 +578,7 @@ export class UpstreamProcess { if (discovered) { this.#assertNotTerminated(); this.#endpoint = discovered; + this.#reprobe = false; // Discovery succeeded, so the failure chain is broken: a later resolve // after this endpoint dies must not be blocked by the spawn backoff. this.#startFailures = 0; @@ -471,6 +596,23 @@ export class UpstreamProcess { ); } + /** + * The endpoint the live child last published, or `undefined` when there is no + * child to re-verify. Used by the `reprobe()` path after the cached endpoint + * was dropped. + */ + #rememberedEndpoint(): UpstreamEndpoint | undefined { + const child = this.#child; + if (!child || child.exitCode !== null || this.#childUrl === undefined) return undefined; + const pid = child.pid; + return { + url: this.#childUrl, + password: this.#childPassword, + source: "spawned", + ...(pid === undefined ? {} : { pid }), + }; + } + async #discover(): Promise { const descriptor = readServiceDescriptor(); if (!descriptor) return undefined; @@ -482,22 +624,33 @@ export class UpstreamProcess { version: descriptor.version, }; if (!descriptor.pid || isProcessAlive(descriptor.pid)) { - if (await this.#probe(endpoint)) return endpoint; + if ((await this.#probeEndpoint(endpoint)) === "ok") return endpoint; } return undefined; } + /** Forget the URL of a child that is no longer supervised. */ + #forgetChildEndpoint(): void { + this.#childUrl = undefined; + this.#childPassword = undefined; + } + /** Check that an endpoint answers an authenticated request. */ - async #probe(endpoint: UpstreamEndpoint, timeoutMs = 5_000): Promise { + async #probe(endpoint: UpstreamEndpoint, timeoutMs = 5_000): Promise { try { const response = await fetch(`${endpoint.url}/api/model`, { headers: authHeaders(endpoint.password), signal: AbortSignal.timeout(timeoutMs), }); - // 401 still proves something is listening, but with the wrong password. - return response.ok || response.status === 400; + 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 + // the gateway presented the wrong or no `OPENCODE_SERVER_PASSWORD`. + if (response.status === 400) return "ok"; + if (response.status === 401 || response.status === 403) return "unauthorized"; + return "absent"; } catch { - return false; + return "absent"; } } @@ -581,7 +734,31 @@ export class UpstreamProcess { this.#liveChildren.delete(child); }); + // Never let a broken log destination escalate: an unhandled `'error'` event + // from `createWriteStream` throws inside the event loop, reaches the + // `uncaughtException` handler and kills every in-flight turn. The stream opens + // asynchronously, so EACCES/EPERM/ENOSPC or a path that is a directory arrives + // here after the spawn already returned. One warning, then the stream is + // destroyed and later writes are skipped; `#stderrTail` keeps feeding so + // diagnostics survive a broken log file. + let logActive = true; const logStream = fs.createWriteStream(path.join(logDir, `opencode-${port}.log`), { flags: "a" }); + logStream.on("error", (error: Error) => { + if (!logActive) return; + logActive = false; + this.#log.warn({ err: error.message, port }, "could not write the OpenCode server log file"); + logStream.destroy(); + }); + + /** + * Outcome of each `finish()` call, oldest first. + * + * The `exit` handler must know whether *this* spawn produced the promise + * result: a child killed because readiness timed out or the spawn was + * abandoned must not run `#onChildExit`, which would report a crash for a + * process the gateway terminated itself. + */ + const outcomes: boolean[] = []; return await new Promise((resolve, reject) => { let settled = false; @@ -591,6 +768,7 @@ export class UpstreamProcess { const finish = (error?: Error, value?: SpawnResult): void => { if (settled) return; settled = true; + outcomes.push(value !== undefined); clearTimeout(timer); if (error) { try { @@ -608,7 +786,7 @@ export class UpstreamProcess { finish( new Error( `OpenCode server did not report readiness within ${this.#config.upstreamStartTimeoutMs} ms. ` + - `stderr: ${stderr.text.trim().slice(-500)}`, + `stderr: ${redactUpstreamSecret(stderr.text.trim().slice(-500))}`, ), ); }, this.#config.upstreamStartTimeoutMs); @@ -637,31 +815,37 @@ export class UpstreamProcess { child.stdout.setEncoding("utf8"); child.stderr.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { - logStream.write(chunk); + // 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)); if (!settled) inspect(chunk, stdout); }); child.stderr.on("data", (chunk: string) => { - logStream.write(chunk); + if (logActive) logStream.write(redactUpstreamSecret(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. - this.#stderrTail.push(chunk); + // Redacted at push time as defence in depth; a marker split across two + // chunks is only caught by the `status()` pass. + this.#stderrTail.push(redactUpstreamSecret(chunk)); if (!settled) inspect(chunk, stderr); }); child.once("error", (error) => finish(error)); child.once("exit", (code, signal) => { logStream.end(); + const wasHandedOff = outcomes.shift() ?? false; if (!settled) { finish( new Error( `OpenCode server exited before becoming ready (code=${code ?? "null"}, signal=${signal ?? "null"}). ` + - `stderr: ${stderr.text.trim().slice(-500)}`, + `stderr: ${redactUpstreamSecret(stderr.text.trim().slice(-500))}`, ), ); return; } - this.#onChildExit(child, code, signal); + if (wasHandedOff) this.#onChildExit(child, code, signal); }); }); } @@ -715,6 +899,7 @@ export class UpstreamProcess { this.#lastError = `OpenCode server exited (code=${code ?? "null"}, signal=${signal ?? "null"})`; this.#endpoint = undefined; this.#child = undefined; + this.#forgetChildEndpoint(); } /** @@ -739,6 +924,7 @@ export class UpstreamProcess { // Clear the handle before killing: the exit of a server we no longer track // must not overwrite `lastError` (see `#onChildExit`). this.#child = undefined; + this.#forgetChildEndpoint(); this.#log.warn({ pid: child.pid, reason }, "terminating the stale OpenCode server"); try { child.kill("SIGKILL"); @@ -781,6 +967,19 @@ function shuttingDownError(): ApiError { return ApiError.unavailable("upstream is shutting down", { code: "upstream_unavailable" }); } +/** + * Message for a server that answers 401/403 (or a 400 challenge). + * + * The old boolean probe reported that as "not reachable", which sent operators + * looking for a network problem instead of the credential mismatch that caused it. + */ +function unauthorizedMessage(url: string): string { + return ( + `The OpenCode server at ${url} rejected the gateway credentials (HTTP 401). ` + + "Set OPENCODE_SERVER_PASSWORD to the password printed by `opencode serve`." + ); +} + export function authHeaders(password: string | undefined): Record { if (!password) return {}; const token = Buffer.from(`opencode:${password}`, "utf8").toString("base64"); diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index f9276b2..dcd6682 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -102,8 +102,27 @@ export class SessionStore { readonly #log: Logger; readonly #metrics: Metrics; readonly #records = new Map(); + /** + * Number of records currently in `#records`. + * + * Maintained by every mutation so `size()` and the eviction pre-check stay + * constant-time: `commit()` runs on the request path of every completed turn, + * and counting the entries by traversal made the pre-check a full scan at the + * default cap. Every path that adds or drops a record updates it — `#load()`, + * `commit()`, `#remove()`, `release()` (only with `keep === false`), + * `invalidate()`, `clear()` and `sweep()`. + */ + #entryCount = 0; #sweepTimer?: NodeJS.Timeout; #saveTimer?: NodeJS.Timeout; + /** + * Guard against a re-entrant save. + * + * `#save()` is synchronous, so two writes can never interleave; the flag makes + * that explicit and stops a schedule raised while a save is running from + * starting a second one. + */ + #saving = false; #onEvict?: (sessionId: string) => void; constructor(config: Config, log: Logger, metrics: Metrics) { @@ -128,14 +147,15 @@ export class SessionStore { if (this.#sweepTimer) clearInterval(this.#sweepTimer); if (this.#saveTimer) clearTimeout(this.#saveTimer); this.#sweepTimer = undefined; + this.#saveTimer = undefined; + // The shutdown path has no async contract: flush synchronously so a pending + // debounced write cannot be lost when the process exits. if (this.#config.sessionPersist) this.#save(); } /** Total number of cached sessions. */ size(): number { - let total = 0; - for (const candidates of this.#records.values()) total += candidates.length; - return total; + return this.#entryCount; } list(): SessionRecord[] { @@ -264,14 +284,21 @@ export class SessionStore { }; const others = candidates.filter((candidate) => candidate.sessionId !== sessionId); + // The replaced record disappears from the bucket and the new one appears, so + // the bucket grows by one at most. + const replaced = candidates.length - others.length; others.unshift(record); // Drop the oldest sessions that share this root. + let trimmed = 0; while (others.length > MAX_CANDIDATES_PER_ROOT) { - const dropped = others.pop(); - if (dropped) this.#notifyEvict(dropped.sessionId); + const removed = others.pop(); + if (!removed) break; + trimmed += 1; + this.#notifyEvict(removed.sessionId); } + this.#entryCount += 1 - replaced - trimmed; this.#records.set(key, others); this.#evictIfNeeded(); this.#publishGauges(); @@ -288,6 +315,7 @@ export class SessionStore { const candidates = this.#records.get(key); if (!candidates) return; + let dropped = 0; const remaining: SessionRecord[] = []; for (const record of candidates) { const targeted = sessionId === undefined || record.sessionId === sessionId; @@ -299,9 +327,13 @@ export class SessionStore { remaining.push({ ...record, busy: false }); } else { this.#notifyEvict(record.sessionId); + dropped += 1; } } + // A release that keeps the record only rewrites it; the failed-turn drop is + // the path that removes entries. + this.#entryCount -= dropped; if (remaining.length === 0) this.#records.delete(key); else this.#records.set(key, remaining); @@ -322,6 +354,7 @@ export class SessionStore { return false; }); + this.#entryCount -= candidates.length - remaining.length; if (remaining.length === 0) this.#records.delete(key); else this.#records.set(key, remaining); @@ -335,6 +368,7 @@ export class SessionStore { for (const record of candidates) this.#notifyEvict(record.sessionId); } this.#records.clear(); + this.#entryCount = 0; this.#publishGauges(); this.#scheduleSave(); return removed; @@ -358,6 +392,7 @@ export class SessionStore { if (remaining.length === 0) this.#records.delete(key); else this.#records.set(key, remaining); } + this.#entryCount -= removed; if (removed > 0) { this.#log.debug({ removed }, "expired sticky sessions"); this.#publishGauges(); @@ -368,24 +403,38 @@ export class SessionStore { #evictIfNeeded(): void { const max = this.#config.sessionMaxEntries; - if (this.size() <= max) return; - - const ordered = this.list() - .filter((record) => !record.busy) - .sort((a, b) => a.lastUsedAt - b.lastUsedAt); - - let overflow = this.size() - max; - for (const record of ordered) { - if (overflow <= 0) break; - this.#remove(record.key, record.sessionId); + if (this.#entryCount <= max) return; + + // Evict the least recently used idle record, without flattening and sorting + // the cache: one pass over the buckets finds it. Ties (records committed in + // the same millisecond) fall back to bucket insertion order, which is what + // the previous ascending stable sort produced. + let overflow = this.#entryCount - max; + while (overflow > 0) { + const victim = this.#oldestEvictable(); + if (victim === undefined) break; + this.#remove(victim.key, victim.sessionId); overflow -= 1; } } + /** Least recently used idle record; `undefined` when every record is busy. */ + #oldestEvictable(): SessionRecord | undefined { + let oldest: SessionRecord | undefined; + for (const candidates of this.#records.values()) { + for (const record of candidates) { + if (record.busy) continue; + if (oldest === undefined || record.lastUsedAt < oldest.lastUsedAt) oldest = record; + } + } + return oldest; + } + #remove(key: string, sessionId: string): void { const candidates = this.#records.get(key); if (!candidates) return; const remaining = candidates.filter((record) => record.sessionId !== sessionId); + this.#entryCount -= candidates.length - remaining.length; if (remaining.length === 0) this.#records.delete(key); else this.#records.set(key, remaining); this.#notifyEvict(sessionId); @@ -400,16 +449,15 @@ export class SessionStore { } #publishGauges(): void { - // Iterated in place: going through `list()` flattened and sorted up to + // The entry count is already maintained by every mutation, so only the busy + // count needs a walk. Going through `list()` flattened and sorted up to // `sessionMaxEntries` records to compute two integers that the order does not // affect, on every commit, release, invalidate, clear and sweep. - let entries = 0; let busy = 0; for (const candidates of this.#records.values()) { - entries += candidates.length; for (const record of candidates) if (record.busy) busy += 1; } - this.#metrics.sessionCache.set({ state: "entries" }, entries); + this.#metrics.sessionCache.set({ state: "entries" }, this.#entryCount); this.#metrics.sessionCache.set({ state: "busy" }, busy); } @@ -463,6 +511,7 @@ export class SessionStore { this.#records.set(record.key, candidates); restored += 1; } + this.#entryCount += restored; if (restored > 0) this.#log.info({ restored }, "restored sticky sessions from disk"); } catch { /* no persisted state yet */ @@ -471,13 +520,26 @@ export class SessionStore { #scheduleSave(): void { if (!this.#config.sessionPersist) return; - if (this.#saveTimer) clearTimeout(this.#saveTimer); - this.#saveTimer = setTimeout(() => this.#save(), 1_000); + // Do not restart an armed timer: `commit`/`release`/`invalidate`/`clear`/ + // `sweep` all call this, so a busy gateway used to push the write out for as + // long as traffic lasted and then flush the whole cache in one synchronous + // burst on the thread that is delivering SSE frames. The window is anchored + // on the first mutation instead, which bounds how long a change can stay + // unpersisted. + if (this.#saveTimer) return; + this.#saveTimer = setTimeout(() => { + this.#saveTimer = undefined; + this.#save(); + }, 1_000); this.#saveTimer.unref?.(); } #save(): void { if (!this.#config.sessionPersist) return; + // The write is synchronous, so it cannot interleave with another save; the + // flag keeps a re-entrant schedule from starting a second one. + if (this.#saving) return; + this.#saving = true; try { fs.mkdirSync(this.#config.dataDir, { recursive: true }); const records: Record = {}; @@ -492,6 +554,8 @@ export class SessionStore { fs.writeFileSync(this.#persistPath(), JSON.stringify(payload), "utf8"); } catch (error) { this.#log.warn({ err: error instanceof Error ? error.message : String(error) }, "could not persist sessions"); + } finally { + this.#saving = false; } } } diff --git a/test/admin.test.ts b/test/admin.test.ts index 661e513..834ce0c 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -5,9 +5,19 @@ * `app.inject()`: each one requires an API key and each answers with the body * shape documented in `docs/API.md` §Operational endpoints. The config view is * also checked for redaction: it must never echo a secret back to the caller. + * + * The last two describes cover the credential tier (`OPENCODE_ADMIN_API_KEYS`), + * the always-on failed-authentication limiter and the paths the request + * limiter must never touch. */ -import { describe, expect, it } from "vitest"; +import { request as httpRequest } from "node:http"; +import type { AddressInfo, Socket } from "node:net"; +import pino, { type DestinationStream } from "pino"; +import { describe, expect, it, vi } from "vitest"; import type { AppContext } from "../src/context.js"; +import type { Config } from "../src/config.js"; +import { armBodyDeadline, clearBodyDeadline } from "../src/http/timeout.js"; +import { loggerOptions } from "../src/logger.js"; import { buildServer } from "../src/server.js"; import type { UpstreamEndpoint, UpstreamStatus } from "../src/upstream/process.js"; import { createTestContext } from "./helpers/context.js"; @@ -15,6 +25,15 @@ import { createTestContext } from "./helpers/context.js"; const AUTH = { authorization: "Bearer test-key" }; const MODEL = "opencode/big-pickle"; +/** A `Config.trustProxy` value narrowed to the allow-list Fastify accepts. */ +function proxyList(config: Config): readonly string[] { + const value = config.trustProxy; + if (typeof value === "boolean" || typeof value === "number") { + throw new Error(`expected a trusted-proxy allow-list, received ${String(value)}`); + } + return value; +} + /** Context whose scripted upstream reports exactly this status payload. */ function contextWithUpstreamStatus(status: UpstreamStatus): AppContext { const base = createTestContext(); @@ -159,6 +178,321 @@ describe("rate limiting", () => { await app.close(); } }); + + 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. + const ctx = createTestContext({ + config: { rateLimitRpm: 1, rateLimitBurst: 1, allowNoAuth: true, metricsEnabled: true, metricsPublic: true }, + }); + const app = await buildServer(ctx); + try { + for (let index = 0; index < 11; index += 1) { + const throttled = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { "x-forwarded-for": "198.51.100.7" }, + }); + if (index === 0) expect(throttled.statusCode).toBe(200); + if (index === 10) expect(throttled.statusCode).toBe(429); + } + + for (const url of ["/", "/health", "/healthz", "/metrics"]) { + const response = await app.inject({ method: "GET", url }); + expect(response.statusCode, `${url} must not be rate limited`).toBe(200); + } + + // `/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" }); + expect(ready.statusCode).not.toBe(429); + expect([200, 503]).toContain(ready.statusCode); + } finally { + await app.close(); + } + }); + + it("does not mint a fresh bucket from a spoofed address when only a declared proxy is trusted", async () => { + // SEC-10 regression: `trustProxy: true` took `request.ip` straight from + // `x-forwarded-for`, so each spoofed value produced a new bucket and the + // limit never applied. A CIDR allow-list that does not cover the peer keeps + // the address the socket reports. + const spoofed = { "x-forwarded-for": "1.1.1.1" }; + const trusted = createTestContext({ + config: { allowNoAuth: true, rateLimitRpm: 1, rateLimitBurst: 1, trustProxy: ["10.0.0.0/8"] }, + }); + const trustedApp = await buildServer(trusted); + try { + expect(proxyList(trusted.config)).toEqual(["10.0.0.0/8"]); + const first = await trustedApp.inject({ + method: "GET", + url: "/v1/models", + headers: spoofed, + remoteAddress: "203.0.113.9", + }); + expect(first.statusCode).toBe(200); + + const second = await trustedApp.inject({ + method: "GET", + url: "/v1/models", + headers: spoofed, + remoteAddress: "203.0.113.9", + }); + expect(second.statusCode).toBe(429); + } finally { + await trustedApp.close(); + } + + // The documented contrast: trusting every hop is what makes the bucket + // caller-controlled, so the header must be ignored when it is not trusted. + const untrusted = createTestContext({ + config: { allowNoAuth: true, rateLimitRpm: 1, rateLimitBurst: 1, trustProxy: true }, + }); + const untrustedApp = await buildServer(untrusted); + try { + const first = await untrustedApp.inject({ + method: "GET", + url: "/v1/models", + headers: { "x-forwarded-for": "1.1.1.1" }, + remoteAddress: "203.0.113.9", + }); + const second = await untrustedApp.inject({ + method: "GET", + url: "/v1/models", + headers: { "x-forwarded-for": "2.2.2.2" }, + remoteAddress: "203.0.113.9", + }); + expect(first.statusCode).toBe(200); + expect(second.statusCode).toBe(200); + } finally { + await untrustedApp.close(); + } + }); +}); + +// ------------------------------------------------- OPENCODE_ADMIN_API_KEYS --- + +describe("OPENCODE_ADMIN_API_KEYS operator tier (SEC-11)", () => { + it("rejects a general key on every /admin/* route once admin keys are configured", async () => { + const ctx = createTestContext({ + config: { apiKeys: ["tenant-key", "operator-key"], adminApiKeys: ["operator-key"] }, + }); + const app = await buildServer(ctx); + try { + const adminKey = { authorization: "Bearer operator-key" }; + const tenantKey = { authorization: "Bearer tenant-key" }; + + const allowed = await app.inject({ method: "GET", url: "/admin/config", headers: adminKey }); + expect(allowed.statusCode).toBe(200); + + for (const route of ADMIN_ROUTES) { + const denied = await app.inject({ ...route, headers: tenantKey }); + expect(denied.statusCode, `${route.method} ${route.url} must reject a tenant key`).toBe(401); + } + + // The tier is scoped to /admin: the tenant key keeps working elsewhere. + const completion = await app.inject({ method: "GET", url: "/v1/models", headers: tenantKey }); + expect(completion.statusCode).toBe(200); + } finally { + await app.close(); + } + }); + + it("keeps accepting a general key when no admin key is configured", async () => { + const ctx = createTestContext({ config: { apiKeys: ["only-key"], adminApiKeys: [] } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ + method: "GET", + url: "/admin/status", + headers: { authorization: "Bearer only-key" }, + }); + expect(response.statusCode).toBe(200); + } finally { + await app.close(); + } + }); +}); + +// --------------------------------------- failed-authentication limiter (SEC-12) --- + +describe("failed authentication is rate limited and audited", () => { + it("answers 429 after the auth burst and never charges a valid key", async () => { + // `OPENCODE_RATE_LIMIT_RPM=0` keeps meaning "no request limiter"; the auth + // bucket is independent of it and floors at 60 rpm with a burst of 10. + const ctx = createTestContext({ config: { rateLimitRpm: 0, rateLimitBurst: 0 } }); + const app = await buildServer(ctx); + try { + const rejections: number[] = []; + for (let index = 0; index < 11; index += 1) { + const response = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + }); + rejections.push(response.statusCode); + } + + expect(rejections.filter((status) => status === 401)).toHaveLength(10); + expect(rejections[10]).toBe(429); + + const drained = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + }); + expect(drained.statusCode).toBe(429); + expect(Number(drained.headers["retry-after"])).toBeGreaterThanOrEqual(1); + + // A valid credential never spends the failed-auth budget. + const valid = await app.inject({ method: "GET", url: "/v1/models", headers: AUTH }); + expect(valid.statusCode).toBe(200); + } finally { + await app.close(); + } + }); + + it("logs a rejected request at warn without the presented credential", async () => { + const lines: string[] = []; + const destination = { + write: (line: string) => { + lines.push(line); + }, + } as unknown as DestinationStream; + // `debug` is dropped at `warn`, so this also pins that the audit line is + // visible at the documented default level. + const log = pino(loggerOptions(createTestContext({ config: { logLevel: "warn" } }).config), destination); + + const ctx = createTestContext(); + const app = await buildServer({ ...ctx, log }); + try { + const rejected = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer guessed-secret-value" }, + }); + expect(rejected.statusCode).toBe(401); + + const audit = lines.join(""); + expect(audit).toContain("authentication failed"); + expect(audit).toContain('"level":40'); + expect(audit).toContain('"route":"/v1/models"'); + expect(audit).not.toContain("guessed-secret-value"); + expect(audit).not.toContain("Bearer"); + } finally { + await app.close(); + } + }); +}); + +// --------------------------------------------------- body receipt (SEC-14) --- + +interface SlowBody { + /** Resolves when the server closed the connection before answering. */ + readonly closed: Promise; + /** Resolves with the client socket, so the test can stop the write loop. */ + readonly socket: Promise; +} + +/** + * Send an authenticated chunked body that never finishes. + * + * The body keeps growing, so the socket is never idle: an idle socket timer + * cannot catch this, which is exactly why the body deadline is wall-clock. + */ +function sendUnterminatedBody(port: number): SlowBody { + let ready: (socket: Socket) => void = () => undefined; + const socket = new Promise((resolve) => { + ready = resolve; + }); + + const closed = new Promise((resolve) => { + let settled = false; + const finish = (): void => { + if (settled) return; + settled = true; + clearInterval(ticker); + resolve(); + }; + + const request = httpRequest( + { + host: "127.0.0.1", + port, + method: "POST", + path: "/v1/chat/completions", + headers: { ...AUTH, "content-type": "application/json", "transfer-encoding": "chunked" }, + }, + (response) => { + // A response means the body was accepted, which this test never expects. + response.resume(); + }, + ); + request.on("error", finish); + request.on("socket", (clientSocket) => { + clientSocket.on("error", finish); + clientSocket.on("close", finish); + ready(clientSocket); + }); + const ticker = setInterval(() => { + request.write('10\r\n{"model":"x"}\r\n'); + }, 10); + }); + + return { closed, socket }; +} + +describe("OPENCODE_BODY_TIMEOUT_MS bounds body receipt (SEC-14)", () => { + it("destroys the socket of a caller that never finishes its request body", async () => { + const ctx = createTestContext({ config: { allowNoAuth: true, bodyTimeoutMs: 150 } }); + const app = await buildServer(ctx); + await app.listen({ host: "127.0.0.1", port: 0 }); + const address = app.server.address() as AddressInfo; + const body = sendUnterminatedBody(address.port); + try { + const outcome = await Promise.race([ + body.closed.then(() => "closed" as const), + new Promise<"still-open">((resolve) => setTimeout(() => resolve("still-open"), 1500)), + ]); + expect(outcome).toBe("closed"); + } finally { + (await body.socket).destroy(); + await app.close(); + } + }); +}); + +describe("the body deadline never outlives body receipt (SEC-14)", () => { + it("destroys the socket once the wall-clock deadline expires", async () => { + const destroy = vi.fn(); + const request = { + raw: { socket: { destroy } }, + } as unknown as Parameters[0]; + const reply = { raw: { once: () => undefined } } as unknown as Parameters[1]; + + // Armed and never cleared: the callback fires and destroys the socket, which + // a wall clock does even though the socket is not idle. + armBodyDeadline(request, reply, { bodyTimeoutMs: 20 }); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect(destroy).toHaveBeenCalledTimes(1); + }); + + it("is inert once cleared, which is what the preHandler hook does", async () => { + const destroy = vi.fn(); + const request = { + raw: { socket: { destroy } }, + } as unknown as Parameters[0]; + const reply = { raw: { once: () => undefined } } as unknown as Parameters[1]; + + armBodyDeadline(request, reply, { bodyTimeoutMs: 20 }); + // The parsed body is complete by `preHandler`; the deadline must not outlive + // that point, or a long `stream: true` response would be destroyed. + clearBodyDeadline(request); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect(destroy).not.toHaveBeenCalled(); + }); }); // ------------------------------------------------------- remaining admin routes --- diff --git a/test/anthropic-count-tokens.test.ts b/test/anthropic-count-tokens.test.ts index 0d3805e..da79bb9 100644 --- a/test/anthropic-count-tokens.test.ts +++ b/test/anthropic-count-tokens.test.ts @@ -70,11 +70,12 @@ describe("POST /v1/messages/count_tokens estimate", () => { expect(withoutTools).toBe(5); }); - it("does not charge the bridge when tool_choice disables tool use", async () => { + it("does not charge the bridge or the tool schemas when tool_choice disables tool use", async () => { const app = await server(); const messages = [{ role: "user", content: "hi" }]; const tools = [{ name: "noop", description: "Do nothing", input_schema: { type: "object", properties: {} } }]; + const plain = await estimateInputTokens(app, { model: MODEL, messages }); const auto = await estimateInputTokens(app, { model: MODEL, messages, tools }); const disabled = await estimateInputTokens(app, { model: MODEL, @@ -84,6 +85,10 @@ describe("POST /v1/messages/count_tokens estimate", () => { }); expect(disabled).toBeLessThan(auto); + // `buildPrompt` prepends neither the bridge instructions nor the schema + // block when the bridge is inactive, so the estimate must not charge the + // schemas either: it is the same prompt as the identical body without tools. + expect(disabled).toBe(plain); expect(createToolBridge([{ name: "noop", description: "Do nothing", parameters: { type: "object" } }], "none").instructions).toBe(""); }); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index bda538a..e8deefc 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -9,7 +9,11 @@ import type { FastifyInstance } from "fastify"; import { afterEach, describe, expect, it } from "vitest"; import { ApiError } from "../src/errors.js"; -import { truncateAtStopSequence } from "../src/adapter/anthropic/messages.js"; +import { + parseAnthropicMessagesBody, + toInternalRequest, + truncateAtStopSequence, +} from "../src/adapter/anthropic/messages.js"; import { buildServer } from "../src/server.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; import { createTestContext, defaultScript, parseSse, type TestContextOptions } from "./helpers/context.js"; @@ -1622,7 +1626,15 @@ describe("streamed usage (A13)", () => { const frames = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); const messageStart = frames.find((frame) => frame.type === "message_start"); - expect(messageStart?.message?.usage).toEqual({ input_tokens: 0, output_tokens: 0 }); + // All four usage fields are present on the opening frame: the official SDK + // types the two cache counters as non-optional, and the closing + // `message_delta` already carries them. + expect(messageStart?.message?.usage).toEqual({ + input_tokens: 0, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }); const messageDelta = frames.find((frame) => frame.type === "message_delta"); const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; @@ -1663,3 +1675,123 @@ describe("rate limiting (A2)", () => { expect(other.statusCode).toBe(200); }); }); + +describe("thinking validation (COR-04)", () => { + const base = { model: MODEL, max_tokens: 8, messages: [{ role: "user", content: "think" }] }; + + it("rejects `type: \"enabled\"` without a budget_tokens", async () => { + const { app } = await serverWith(); + + const response = await post(app, "/v1/messages", { ...base, thinking: { type: "enabled" } }); + + expect(response.statusCode).toBe(400); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.type).toBe("error"); + expect(error.error.type).toBe("invalid_request_error"); + expect(error.error.message).toContain("budget_tokens"); + }); + + it("rejects a negative or fractional budget_tokens", async () => { + const { app } = await serverWith(); + + for (const budget_tokens of [-1, 0.5]) { + const response = await post(app, "/v1/messages", { + ...base, + thinking: { type: "enabled", budget_tokens }, + }); + expect(response.statusCode, `budget_tokens ${budget_tokens} must be rejected`).toBe(400); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.error.type).toBe("invalid_request_error"); + expect(error.error.message).toContain("budget_tokens"); + } + }); + + it("reports the invalid_request code and the thinking.budget_tokens param", async () => { + // The Anthropic wire error body carries no `code`/`param`, so the internal + // contract is pinned through the normaliser itself. + const request = { model: MODEL, max_tokens: 8, messages: [{ role: "user", content: "think" }] }; + for (const thinking of [{ type: "enabled" }, { type: "enabled", budget_tokens: -1 }, { type: "enabled", budget_tokens: 0.5 }]) { + // The schema rejects the budget cases synchronously and the normaliser + // rejects the missing-budget case; the async wrapper covers both. + await expect( + (async () => + toInternalRequest(parseAnthropicMessagesBody({ ...request, thinking }), { + ctx: createTestContext(), + model: MODEL, + }))(), + ).rejects.toMatchObject({ code: "invalid_request", param: "thinking.budget_tokens" }); + } + }); + + it("still accepts an explicit budget, the disabled form and the effort alias", async () => { + const { app } = await serverWith(); + + for (const thinking of [ + { type: "enabled", budget_tokens: 2_048 }, + { type: "disabled" }, + { type: "enabled", effort: "high" }, + ]) { + const response = await post(app, "/v1/messages", { ...base, thinking }); + expect(response.statusCode, `${JSON.stringify(thinking)} must be accepted`).toBe(200); + } + }); +}); + +describe("empty message content (COR-05)", () => { + it("rejects a request whose messages all yield nothing", async () => { + const { app } = await serverWith(); + + for (const messages of [ + [{ role: "user", content: [] }], + [{ role: "user", content: [{ type: "text", text: "" }] }], + [{ role: "assistant", content: [] }], + // The literal string form is the same case: an empty turn must not become + // an empty prompt with a 200. + [{ role: "user", content: "" }], + [{ role: "user", content: " " }], + ]) { + const response = await post(app, "/v1/messages", { model: MODEL, max_tokens: 8, messages }); + expect(response.statusCode, `${JSON.stringify(messages)} must be rejected`).toBe(400); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.error.type).toBe("invalid_request_error"); + expect(error.error.message).toContain("At least one message"); + } + }); + + it("reports the invalid_request code and the messages param", async () => { + const body = parseAnthropicMessagesBody({ + model: MODEL, + max_tokens: 8, + messages: [{ role: "user", content: [] }], + }); + await expect( + toInternalRequest(body, { ctx: createTestContext(), model: MODEL }), + ).rejects.toMatchObject({ + code: "invalid_request", + param: "messages", + }); + }); + + it("still accepts a message carrying only an image or only a tool result", async () => { + const { app } = await serverWith(); + + const image = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + messages: [ + { + role: "user", + content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: PNG_1X1 } }], + }, + ], + }); + expect(image.statusCode).toBe(200); + + const toolResult = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + messages: [{ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "done" }] }], + }); + expect(toolResult.statusCode).toBe(200); + }); +}); diff --git a/test/client.test.ts b/test/client.test.ts index 3238dd7..89d9b67 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -17,6 +17,9 @@ interface FakeUpstream { url: string; client: OpencodeClient; metrics: Metrics; + /** Reason strings passed to `markStale()` / `reprobe()`, in call order. */ + stale: string[]; + reprobe: string[]; close: () => Promise; } @@ -36,9 +39,16 @@ async function hangingUpstream( const config = testConfig({ upstreamRequestTimeoutMs }); const log = createLogger(config); const metrics = createMetrics({ enabled: false }); + const stale: string[] = []; + const reprobe: string[] = []; const upstream = { resolve: async () => ({ url: `http://127.0.0.1:${port}`, password: undefined, source: "env" as const }), - markStale: () => undefined, + markStale: (reason: string) => { + stale.push(reason); + }, + reprobe: (reason: string) => { + reprobe.push(reason); + }, } as unknown as UpstreamProcess; const client = new OpencodeClient(upstream, config, log, metrics, clientOptions); @@ -46,6 +56,8 @@ async function hangingUpstream( url: `http://127.0.0.1:${port}`, client, metrics, + stale, + reprobe, close: async () => { server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); @@ -80,6 +92,56 @@ afterEach(async () => { } }); +/** A client whose resolved endpoint points at a port nothing listens on. */ +async function refusingUpstream(upstreamRequestTimeoutMs: number): Promise { + const probe = http.createServer(); + await new Promise((resolve) => probe.listen(0, "127.0.0.1", resolve)); + const { port } = probe.address() as AddressInfo; + await new Promise((resolve) => probe.close(() => resolve())); + return stubUpstream(`http://127.0.0.1:${port}`, upstreamRequestTimeoutMs); +} + +/** A server that answers every request with `401`. */ +async function rejectingUpstream(): Promise { + const server = http.createServer((_request, response) => { + response.writeHead(401, { "content-type": "application/json" }); + response.end('{"message":"unauthorized"}'); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const item = stubUpstream(`http://127.0.0.1:${port}`, 5_000); + item.close = async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }; + open.push(item); + return item; +} + +/** A client over a scripted `UpstreamProcess` that records lifecycle calls. */ +function stubUpstream(url: string, upstreamRequestTimeoutMs = 5_000): FakeUpstream { + const config = testConfig({ upstreamRequestTimeoutMs }); + const stale: string[] = []; + const reprobe: string[] = []; + const upstream = { + resolve: async () => ({ url, password: undefined, source: "env" as const }), + markStale: (reason: string) => { + stale.push(reason); + }, + reprobe: (reason: string) => { + reprobe.push(reason); + }, + } as unknown as UpstreamProcess; + return { + url, + client: new OpencodeClient(upstream, config, createLogger(config), createMetrics({ enabled: false })), + metrics: createMetrics({ enabled: false }), + stale, + reprobe, + close: async () => undefined, + }; +} + describe("OpencodeClient", () => { it("reports its own request timeout as a 504", async () => { const upstream = await hangingUpstream(150, { catalogueTimeoutMs: 150 }); @@ -145,7 +207,7 @@ describe("OpencodeClient", () => { expect(count?.value).toBe(1); }); - it("cancels createSession and prompt when the caller aborts", async () => { + it("cancels createSession and prompt when the caller aborts", async () => { const upstream = await hangingUpstream(60_000); const createAbort = new AbortController(); @@ -167,4 +229,39 @@ describe("OpencodeClient", () => { expect(requests.map((value) => value.labels?.["outcome"])).toEqual(["aborted", "aborted"]); expect(requests.map((value) => value.labels?.["operation"])).toEqual(["session.create", "session.prompt"]); }); +}); + +// ------------------------------------------------------------------- COR-09 --- + +describe("OpencodeClient endpoint invalidation (COR-09)", () => { + it("re-verifies instead of killing the shared server on a timeout", async () => { + const upstream = await hangingUpstream(150, { catalogueTimeoutMs: 150 }); + + await expect(upstream.client.listModels()).rejects.toMatchObject({ code: "upstream_timeout" }); + + // One slow catalogue call used to SIGKILL the server shared with every + // in-flight turn; now the child survives and the endpoint is re-probed. + expect(upstream.reprobe).toHaveLength(1); + expect(upstream.reprobe[0]).toContain("timed out"); + expect(upstream.stale).toHaveLength(0); + }); + + it("still replaces the process on a network error", async () => { + const upstream = await refusingUpstream(5_000); + + await expect(upstream.client.listModels()).rejects.toMatchObject({ code: "upstream_unreachable" }); + + expect(upstream.stale).toHaveLength(1); + expect(upstream.stale[0]).toContain("failed"); + expect(upstream.reprobe).toHaveLength(0); + }); + + it("still replaces the process when the upstream rejects the credentials", async () => { + const upstream = await rejectingUpstream(); + + await expect(upstream.client.listModels()).rejects.toMatchObject({ code: "upstream_unauthorized" }); + + expect(upstream.stale).toHaveLength(1); + expect(upstream.reprobe).toHaveLength(0); + }); }); \ No newline at end of file diff --git a/test/completion.test.ts b/test/completion.test.ts index 08e9e68..b6f5681 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -28,8 +28,10 @@ interface Harness { promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }>; /** Options every `prompt()` call received. */ promptOptions: Array<{ signal?: AbortSignal }>; - /** Session ids passed to `client.deleteSession()`. */ + /** Session ids passed to `client.deleteSession()`. */ deletedSessions: string[]; + /** Session ids passed to `client.interrupt()`. */ + interruptCalls: string[]; /** A promise that resolves once `prompt()` has been called at least once. */ waitForPrompt: () => Promise; } @@ -77,6 +79,7 @@ function harness( const promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }> = []; const promptOptions: Array<{ signal?: AbortSignal }> = []; const deletedSessions: string[] = []; + const interruptCalls: string[] = []; let markPrompted: () => void = () => undefined; const prompted = new Promise((resolve) => { markPrompted = resolve; @@ -140,7 +143,8 @@ function harness( }); return { id: "msg_user" }; }, - async interrupt() { + async interrupt(sessionId: string) { + interruptCalls.push(sessionId); return undefined; }, async deleteSession(sessionId: string) { @@ -160,6 +164,7 @@ function harness( promptCalls, promptOptions, deletedSessions, + interruptCalls, waitForPrompt: async () => { await prompted; }, @@ -482,6 +487,54 @@ describe("collectCompletion", () => { expect(result.calls).toEqual([]); }); + it("attributes every native tool event to the name announced by its input.started frame", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.tool.input.started", { assistantMessageID: "msg_a1", id: "tool_1", name: "bash" }), + event("session.tool.called", { assistantMessageID: "msg_a1", id: "tool_1", input: { command: "ls" } }), + event("session.tool.success", { assistantMessageID: "msg_a1", id: "tool_1" }), + event("session.tool.input.started", { assistantMessageID: "msg_a1", id: "tool_2", name: "webfetch" }), + event("session.tool.failed", { assistantMessageID: "msg_a1", id: "tool_2", error: { message: "blocked" } }), + event("session.step.ended", { + assistantMessageID: "msg_a1", + finish: "stop", + tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]); + const result = await collectCompletion(request(), deps); + + // The name used to be recovered by scanning `nativeTools` backwards for every + // `called`/`success`/`failed` frame (O(k²) per turn); the id → name map must + // attribute each event identically. + expect(result.nativeTools.map((activity) => `${activity.status}:${activity.name}`)).toEqual([ + "started:bash", + "called:bash", + "succeeded:bash", + "started:webfetch", + "failed:webfetch", + ]); + }); + + it("keeps an empty tool name when the lifecycle frame arrives out of order", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + // `called` before the only event that carries the name: the old backward + // scan also yielded `""` in this case, and the map must not invent one. + event("session.tool.called", { assistantMessageID: "msg_a1", id: "tool_1", input: { command: "ls" } }), + event("session.tool.input.started", { assistantMessageID: "msg_a1", id: "tool_1", name: "bash" }), + event("session.tool.success", { assistantMessageID: "msg_a1", id: "tool_1" }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]); + const result = await collectCompletion(request(), deps); + + expect(result.nativeTools.map((activity) => `${activity.status}:${activity.name}`)).toEqual([ + "called:", + "started:bash", + "succeeded:bash", + ]); + }); + it("fails fast when the event stream is not connected", async () => { const { deps, promptCalls, sessions } = harness(() => simpleTurn("ok"), {}, { ensureConnected: async () => false }); @@ -1264,6 +1317,48 @@ describe("runCompletion streaming", () => { }); expect(next.reason).not.toBe("session-busy"); }); + + it("interrupts the upstream turn once the agent step budget is exhausted", async () => { + // `OPENCODE_AGENT_MAX_STEPS` is documented as an enforced safety valve, so + // the budget must stop the turn *and* release the session slot. + const { deps, sessions, interruptCalls } = harness( + () => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.step.started", { assistantMessageID: "msg_a2" }), + // A third step would only arrive if the orchestrator kept consuming; the + // budget must have ended the turn before this point. + event("session.step.started", { assistantMessageID: "msg_a3" }), + event("session.execution.succeeded", { assistantMessageID: "msg_a3" }), + ], + { agentMaxSteps: 1, upstreamRequestTimeoutMs: 5_000, upstreamFirstTokenTimeoutMs: 5_000 }, + ); + + // Seed the record the turn reuses, so the released slot is observable. + sessions.commit("steps-conv", "ses_test", { + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [], + toolsHash: "none", + permissionProfile: "default", + }); + + const events: CompletionEvent[] = []; + for await (const item of runCompletion( + request({ conversationKey: "steps-conv", messages: [{ role: "user", text: "Hello" }] }), + deps, + )) { + events.push(item); + } + + expect(interruptCalls).toEqual(["ses_test"]); + expect(events.some((item) => item.kind === "text_delta")).toBe(false); + expect(events.some((item) => item.kind === "error")).toBe(false); + expect(events.at(-1)?.kind).toBe("end"); + // The turn ended through `finalise()`, which commits the record instead of + // leaving it `busy`. + expect(sessions.list()).toHaveLength(1); + expect(sessions.list()[0]?.busy).toBe(false); + }); }); describe("session permission profiles", () => { diff --git a/test/config.test.ts b/test/config.test.ts index f22f705..f124630 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -401,6 +401,117 @@ describe("OPENCODE_METRICS_TOKEN and the rate-limit variables (A2, A10)", () => }); }); +describe("OPENCODE_TRUST_PROXY grammar (SEC-10)", () => { + it("keeps every boolean word working exactly as before", () => { + for (const value of ["true", "yes", "on", "enabled", "TRUE"]) { + setEnv("OPENCODE_TRUST_PROXY", value); + expect(config().trustProxy, `${value} must mean true`).toBe(true); + } + for (const value of ["false", "no", "off", "disabled"]) { + setEnv("OPENCODE_TRUST_PROXY", value); + expect(config().trustProxy, `${value} must mean false`).toBe(false); + } + setEnv("OPENCODE_TRUST_PROXY", undefined); + expect(config().trustProxy).toBe(false); + }); + + it("reads a positive integer as a hop count", () => { + // `1` is a hop count, not a synonym for `true`: trusting only the immediate + // peer is strictly safer than trusting every hop, and `true` keeps working. + setEnv("OPENCODE_TRUST_PROXY", "1"); + expect(config().trustProxy).toBe(1); + setEnv("OPENCODE_TRUST_PROXY", "2"); + expect(config().trustProxy).toBe(2); + // `0` means "trust nothing", like the boolean false spellings. + setEnv("OPENCODE_TRUST_PROXY", "0"); + expect(config().trustProxy).toBe(false); + }); + + it("accepts a comma-separated IP/CIDR allow-list", () => { + setEnv("OPENCODE_TRUST_PROXY", "10.0.0.0/8, 192.168.0.0/16,::1"); + expect(config().trustProxy).toEqual(["10.0.0.0/8", "192.168.0.0/16", "::1"]); + }); + + it("accepts a single IP or CIDR entry", () => { + // One trusted proxy is the common case, so the list parse must not require a + // comma: otherwise the value warns and silently trusts nothing. + setEnv("OPENCODE_TRUST_PROXY", "10.0.0.0/8"); + expect(config().trustProxy).toEqual(["10.0.0.0/8"]); + setEnv("OPENCODE_TRUST_PROXY", "::1"); + expect(config().trustProxy).toEqual(["::1"]); + }); + + it("rejects an entry Fastify's proxy-addr cannot compile", () => { + // These used to pass the shape check and then throw inside the `Fastify()` + // constructor, so a typo took the gateway down with a raw stack trace instead + // of warning and falling back to `false`. + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + for (const value of ["999.999.999.999", "10.0.0.0/33", "2001:db8::/129", "abc", ":::", "::1%eth0"]) { + warn.mockClear(); + setEnv("OPENCODE_TRUST_PROXY", value); + expect(config().trustProxy, value).toBe(false); + expect(warn, value).toHaveBeenCalledTimes(1); + } + }); + + it("warns and falls back to false for an unparseable value", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + setEnv("OPENCODE_TRUST_PROXY", "behind-a-proxy"); + expect(config().trustProxy).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_TRUST_PROXY"); + // Never echo the value: an operator can paste a secret into the wrong variable. + expect(String(warn.mock.calls[0]?.[0])).not.toContain("behind-a-proxy"); + + warn.mockClear(); + setEnv("OPENCODE_TRUST_PROXY", "10.0.0.0/8,not-an-address"); + expect(config().trustProxy).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + + warn.mockClear(); + setEnv("OPENCODE_TRUST_PROXY", "-3"); + expect(config().trustProxy).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + }); +}); + +describe("OPENCODE_ADMIN_API_KEYS operator tier (SEC-11)", () => { + it("is empty when unset, so every general key keeps working", () => { + setEnv("OPENCODE_ADMIN_API_KEYS", undefined); + expect(config().adminApiKeys).toEqual([]); + }); + + it("parses the list and keeps an explicit empty value a startup error", () => { + setEnv("OPENCODE_ADMIN_API_KEYS", "operator-a, operator-b"); + expect(config().adminApiKeys).toEqual(["operator-a", "operator-b"]); + + setEnv("OPENCODE_ADMIN_API_KEYS", " , "); + expect(() => config()).toThrow(/OPENCODE_ADMIN_API_KEYS/); + }); +}); + +describe("OPENCODE_BODY_TIMEOUT_MS (SEC-14)", () => { + it("defaults to five minutes and enforces the one-second floor", () => { + setEnv("OPENCODE_BODY_TIMEOUT_MS", undefined); + expect(config().bodyTimeoutMs).toBe(300_000); + + setEnv("OPENCODE_BODY_TIMEOUT_MS", "1500"); + expect(config().bodyTimeoutMs).toBe(1500); + + setEnv("OPENCODE_BODY_TIMEOUT_MS", "10"); + expect(config().bodyTimeoutMs).toBe(1000); + }); + + it("falls back to the default for a non-numeric value", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_BODY_TIMEOUT_MS", "5m"); + expect(config().bodyTimeoutMs).toBe(300_000); + expect(warn).toHaveBeenCalledTimes(1); + }); +}); + describe("logger redaction (A4)", () => { it("redacts every spelling of a secret field, at every nesting level", () => { const lines: string[] = []; diff --git a/test/disconnect.test.ts b/test/disconnect.test.ts index 4501dfe..c3592ba 100644 --- a/test/disconnect.test.ts +++ b/test/disconnect.test.ts @@ -6,7 +6,7 @@ * tests pin that contract down without opening a socket. */ import { EventEmitter } from "node:events"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import type { FastifyReply, FastifyRequest } from "fastify"; import { createDisconnectSignal } from "../src/http/disconnect.js"; import { SseWriter } from "../src/http/sse.js"; @@ -99,6 +99,7 @@ class FakeRawResponse extends EventEmitter { full = false; headWritten = false; ended = false; + destroyed = false; write(chunk: string): boolean { this.written.push(chunk); @@ -116,18 +117,28 @@ class FakeRawResponse extends EventEmitter { end(): void { this.ended = true; } + + destroy(): void { + this.destroyed = true; + } } -function writerWith(raw: FakeRawResponse, drainTimeoutMs = 5_000): SseWriter { +function writerWith(raw: FakeRawResponse, drainTimeoutMs = 5_000, heartbeatMs = 0): SseWriter { const reply = { raw, getHeaders: () => ({}), hijack: () => undefined, } as unknown as FastifyReply; - return new SseWriter(reply, { heartbeatMs: 0, drainTimeoutMs }); + return new SseWriter(reply, { heartbeatMs, drainTimeoutMs }); } describe("SseWriter backpressure and liveness (A3)", () => { + afterEach(() => { + // The stalled-stream cases use fake timers so a 5 s deadline can be reached + // synchronously; never leak a fake clock into the next test. + vi.useRealTimers(); + }); + it("resolves immediately when the socket accepted the frame", async () => { const raw = new FakeRawResponse(); const writer = writerWith(raw); @@ -202,4 +213,101 @@ describe("SseWriter backpressure and liveness (A3)", () => { writer.send("late frame"); expect(raw.written.length).toBe(before); }); + + it("marks the writer stalled once the drain deadline expires", async () => { + vi.useFakeTimers(); + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw, 5_000); + writer.open(); + writer.send("frame"); + + expect(writer.stalled).toBe(false); + await vi.advanceTimersByTimeAsync(5_000); + + // Pre-fix the timeout released the producer without recording the outcome, + // so the next frame started another 5 s deadline on a socket that was still + // full and the write queue grew for the rest of the turn. + expect(writer.stalled).toBe(true); + }); + + it("stops writing and aborts closedSignal when the drain deadline expires", async () => { + vi.useFakeTimers(); + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw, 1_000); + writer.open(); + + writer.send("first"); + // One write was attempted; every later frame must be dropped, because from + // the producer's point of view the reader is gone. + expect(raw.written).toHaveLength(1); + await vi.advanceTimersByTimeAsync(1_000); + expect(writer.stalled).toBe(true); + writer.send("second"); + writer.send("third"); + + expect(raw.written).toHaveLength(1); + expect(writer.closed).toBe(true); + expect(writer.closedSignal.aborted).toBe(true); + }); + + it("destroys the socket when the drain deadline expires", async () => { + vi.useFakeTimers(); + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw, 1_000); + writer.open(); + writer.send("frame"); + + expect(raw.destroyed).toBe(false); + await vi.advanceTimersByTimeAsync(1_000); + + // A socket that has not drained inside the deadline is dead: without the + // destroy it stays parked for the life of the process, and the client + // disconnect signal never fires, so the upstream turn runs on for a reader + // that is gone. + expect(raw.destroyed).toBe(true); + }); + + it("never writes a heartbeat into a socket whose drain deadline expired", async () => { + vi.useFakeTimers(); + const raw = new FakeRawResponse(); + raw.full = true; + // The heartbeat period is longer than the drain deadline, so the first + // heartbeat would land while the socket is still backed up. + const writer = writerWith(raw, 1_000, 2_000); + writer.open(); + writer.send("frame"); + expect(raw.written).toHaveLength(1); + + await vi.advanceTimersByTimeAsync(10_000); + + // Pre-fix each heartbeat went straight to `raw.write()`, adding a frame to a + // queue that only grows. + expect(raw.written.some((chunk) => chunk.startsWith(":"))).toBe(false); + expect(raw.written).toHaveLength(1); + }); + + it("keeps streaming after a backpressured write that drains in time", async () => { + vi.useFakeTimers(); + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw, 5_000); + + writer.open(); + writer.send("one"); + expect(writer.stalled).toBe(false); + + raw.full = false; + raw.emit("drain"); + await vi.advanceTimersByTimeAsync(10_000); + + // A healthy connection must be unaffected: no stall state, and the next + // frames still reach the socket. + expect(writer.stalled).toBe(false); + writer.send("two"); + expect(raw.written).toEqual(expect.arrayContaining([expect.stringContaining("one")])); + expect(raw.written).toHaveLength(2); + }); }); \ No newline at end of file diff --git a/test/docs-consistency.test.ts b/test/docs-consistency.test.ts index fb6c4f5..553feaf 100644 --- a/test/docs-consistency.test.ts +++ b/test/docs-consistency.test.ts @@ -22,6 +22,8 @@ import { readFileSync, readdirSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; +import { buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -117,22 +119,35 @@ describe("environment-variable documentation", () => { // ------------------------------------------------------------------- P-14 --- -/** The `GET /` endpoint index in `docs/API.md`, as `METHOD /path` strings. */ -function documentedIndex(markdown: string): string[] { +/** The JSON block of the `GET /` example in `docs/API.md`, as written. */ +function documentedIndexBlock(markdown: string): string { const heading = markdown.indexOf("## Gateway root"); if (heading < 0) throw new Error("docs/API.md has no '## Gateway root' section"); const fence = markdown.indexOf("```json", heading); const end = markdown.indexOf("```", fence + 7); if (fence < 0 || end < 0) throw new Error("docs/API.md 'Gateway root' has no JSON block"); - const body = markdown.slice(fence + 7, end); + return markdown.slice(fence + 7, end); +} + +/** `METHOD /path` entries of the documented `GET /` example. */ +function documentedIndex(markdown: string): string[] { const entries: string[] = []; - for (const match of body.matchAll(/"((?:GET|POST|DELETE|PUT|PATCH)\s+\/[^"]*)"/g)) { + for (const match of documentedIndexBlock(markdown).matchAll(/"((?:GET|POST|DELETE|PUT|PATCH)\s+\/[^"]*)"/g)) { const value = match[1]; if (value !== undefined) entries.push(value.replace(/\s+/g, " ").trim()); } return entries; } +/** The `endpoints` array of the documented `GET /` example. */ +function documentedEndpoints(markdown: string): string[] { + const parsed = JSON.parse(documentedIndexBlock(markdown)) as { endpoints?: unknown }; + if (!Array.isArray(parsed.endpoints)) { + throw new Error("docs/API.md 'Gateway root' example has no endpoints array"); + } + return parsed.endpoints.map((entry) => String(entry).replace(/\s+/g, " ").trim()); +} + /** Every route `src/` registers, as `METHOD /path` strings. */ function registeredRoutes(): string[] { const files: string[] = []; @@ -165,10 +180,30 @@ describe("the GET / endpoint index (docs/API.md)", () => { it("parses an index out of the documentation", () => { // A broken extraction must not turn the comparison below into a no-op. expect(documentedIndex(read("docs/API.md")).length).toBeGreaterThanOrEqual(18); + expect(documentedEndpoints(read("docs/API.md")).length).toBeGreaterThanOrEqual(18); }); it("lists exactly the routes src/ registers", () => { - expect([...documentedIndex(read("docs/API.md"))].sort()).toEqual(registeredRoutes()); + // `GET /` is served by the route itself and is deliberately absent from the + // body it returns; `test/regressions.test.ts` pins that the live body equals + // the router table, and the case below pins the documented example against + // the live body, so the two cannot cancel each other out. + const routes = registeredRoutes().filter((route) => route !== "GET /"); + expect([...documentedIndex(read("docs/API.md"))].sort()).toEqual(routes); + }); + + it("matches the live GET / response body exactly", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + await app.ready(); + const live = (await app.inject({ method: "GET", url: "/" })).json() as { endpoints: string[] }; + expect(documentedEndpoints(read("docs/API.md"))).toEqual( + live.endpoints.map((entry) => entry.replace(/\s+/g, " ").trim()), + ); + } finally { + await app.close(); + } }); it("spells every entry as 'METHOD /path' with one space", () => { diff --git a/test/media.test.ts b/test/media.test.ts index ff5cc31..8a05dd7 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -4,11 +4,11 @@ import dns from "node:dns/promises"; import { constants as fsConstants } from "node:fs"; import fsp from "node:fs/promises"; import type { FileHandle } from "node:fs/promises"; -import type { AddressInfo } from "node:net"; +import net, { type AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; import zlib from "node:zlib"; -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { ApiError } from "../src/errors.js"; import { @@ -19,9 +19,20 @@ import { isWithinRoots, resolveAttachment, resolveAttachments, + setMediaLogger, type MediaSource, } from "../src/media/resolve.js"; -import { extensionToMime, isAudio, isImage, isPdf, isTextual, isVideo, kindFromMime, sniffMime } from "../src/media/mime.js"; +import { + extensionToMime, + isAudio, + isImage, + isPdf, + isTextual, + isVideo, + kindFromMime, + normaliseMimeType, + sniffMime, +} from "../src/media/mime.js"; /** 1x1 transparent PNG. */ const PNG_BASE64 = @@ -56,8 +67,37 @@ function config(overrides: Partial = {}): Config { } as Partial); } +/** Listen on loopback and return the assigned port. */ +async function listen(server: http.Server | net.Server): Promise { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return (server.address() as AddressInfo).port; +} + +/** Sockets the server currently has open. */ +async function countConnections(server: http.Server): Promise { + return new Promise((resolve, reject) => { + server.getConnections((error, count) => (error ? reject(error) : resolve(count))); + }); +} + +/** Resolve a source and return the `ApiError` it rejected with. */ +async function mediaFailure( + source: MediaSource, + options: Config, + requestOptions: { signal?: AbortSignal } = {}, +): Promise { + try { + await resolveAttachment(source, options, requestOptions); + } catch (error) { + if (error instanceof ApiError) return error; + throw error; + } + throw new Error("expected the media resolution to fail"); +} + afterEach(() => { vi.restoreAllMocks(); + setMediaLogger(undefined); }); describe("mime helpers", () => { @@ -92,6 +132,21 @@ describe("mime helpers", () => { expect(sniffMime(Buffer.from("unknown"), "text/plain")).toBe("text/plain"); expect(sniffMime(Buffer.from("unknown"))).toBe("application/octet-stream"); }); + + it("rejects a MIME value that is not a type/subtype token (SEC-07)", () => { + expect(normaliseMimeType("image/png; charset=binary")).toBe("image/png"); + expect(normaliseMimeType("IMAGE/PNG")).toBe("image/png"); + expect(normaliseMimeType("image/svg+xml")).toBe("image/svg+xml"); + expect( + normaliseMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"), + ).toBe("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + // A comma ends the media type early in `data:;base64,...`, so it must + // not survive; neither must a control character or free-form text. + expect(normaliseMimeType("image/png,text/html")).toBeUndefined(); + expect(normaliseMimeType("image/png\r\nx")).toBeUndefined(); + expect(normaliseMimeType("not a mime")).toBeUndefined(); + expect(normaliseMimeType("")).toBeUndefined(); + }); }); describe("resolveAttachment", () => { @@ -131,6 +186,91 @@ describe("resolveAttachment", () => { await expect(resolveAttachment({}, config())).rejects.toMatchObject({ code: "invalid_attachment" }); }); + it("refuses an oversized base64 payload before decoding it (SEC-06)", async () => { + const limit = 64; + const maxEncoded = Math.ceil((limit * 4) / 3) + 4; + const payload = "A".repeat(maxEncoded + 1); + const fromSpy = vi.spyOn(Buffer, "from"); + + await expect(resolveAttachment({ base64: payload, mime: "text/plain" }, config({ maxAttachmentBytes: limit }))).rejects.toMatchObject({ + code: "attachment_too_large", + status: 400, + }); + + // The encoded-length bound rejected it, so no decoded copy was allocated. + expect( + fromSpy.mock.calls.some((call) => (call as unknown as unknown[])[1] === "base64"), + ).toBe(false); + fromSpy.mockRestore(); + }); + + it("refuses an oversized base64 data URI before decoding it (SEC-06)", async () => { + const limit = 64; + const maxEncoded = Math.ceil((limit * 4) / 3) + 4; + const payload = "A".repeat(maxEncoded + 1); + const fromSpy = vi.spyOn(Buffer, "from"); + + await expect( + resolveAttachment({ dataUri: `data:text/plain;base64,${payload}` }, config({ maxAttachmentBytes: limit })), + ).rejects.toMatchObject({ code: "attachment_too_large", status: 400 }); + + expect( + fromSpy.mock.calls.some((call) => (call as unknown as unknown[])[1] === "base64"), + ).toBe(false); + fromSpy.mockRestore(); + }); + + it("accepts a payload that decodes to exactly the cap (SEC-06)", async () => { + // "QUJD" decodes to the three ASCII bytes "ABC": the encoded-length bound + // must round up, not truncate, or a payload at the limit is refused. + const attachment = await resolveAttachment( + { base64: "QUJD", mime: "text/plain" }, + config({ maxAttachmentBytes: 3 }), + ); + + expect(attachment.size).toBe(3); + expect(attachment.mime).toBe("text/plain"); + }); + + it("still accepts whitespace inside a base64 payload (SEC-06)", async () => { + const split = `${PNG_BASE64.slice(0, 20)}\n ${PNG_BASE64.slice(20)}`; + + const attachment = await resolveAttachment({ base64: split }, config()); + + expect(attachment.data).toBe(PNG_BASE64); + expect(attachment.mime).toBe("image/png"); + }); + + it("never embeds a declared MIME value that is not a type/subtype token (SEC-07)", async () => { + const payload = Buffer.from("plain text, no magic bytes").toString("base64"); + + for (const mime of ["image/png,text/html", "image/png\r\nx", "not a mime"]) { + const attachment = await resolveAttachment({ base64: payload, mime }, config()); + const uri = buildDataUri(attachment); + + expect(attachment.mime).toBe("application/octet-stream"); + expect(uri.startsWith("data:application/octet-stream;base64,")).toBe(true); + expect(uri).not.toContain("text/html"); + expect(uri).not.toContain("\r"); + expect(uri).not.toContain(mime); + } + }); + + it("keeps a valid exotic MIME declaration unchanged (SEC-07)", async () => { + const payload = Buffer.from("plain text, no magic bytes").toString("base64"); + const exotic = [ + "image/svg+xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ]; + + for (const mime of exotic) { + const attachment = await resolveAttachment({ base64: payload, mime }, config()); + + expect(attachment.mime).toBe(mime); + expect(buildDataUri(attachment)).toBe(`data:${mime};base64,${payload}`); + } + }); + it("rejects multiple sources", async () => { await expect( resolveAttachment({ base64: PNG_BASE64, url: "https://example.com/x.png" }, config()), @@ -350,6 +490,106 @@ describe("resolveAttachment", () => { ).rejects.toMatchObject({ code: "attachment_download_failed" }); }); + it("collapses transport failures instead of exposing a connect oracle (SEC-02)", async () => { + // A port nothing listens on, and a port that answers something that is not + // HTTP: both used to be reported verbatim (`ECONNREFUSED`, + // `Parse Error: Expected HTTP/, RTSP/ or ICE/`), which let an authenticated + // caller probe arbitrary host:port pairs through the gateway. + const closed = http.createServer(); + const closedPort = await listen(closed); + await new Promise((resolve) => closed.close(() => resolve())); + + const rawSockets = new Set(); + const raw = net.createServer((socket) => { + rawSockets.add(socket); + socket.on("close", () => rawSockets.delete(socket)); + socket.write("SMTP 220 ready\r\n"); + }); + const rawPort = await listen(raw); + const reasons: string[] = []; + setMediaLogger({ + debug: (details) => { + const reason = details["reason"]; + if (typeof reason === "string") reasons.push(reason); + }, + }); + + try { + const refused = await mediaFailure( + { url: `http://user:s3cret@127.0.0.1:${closedPort}/x.png` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), + ); + const notHttp = await mediaFailure( + { url: `http://127.0.0.1:${rawPort}/x.png` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), + ); + + expect(refused).toMatchObject({ status: 400, code: "attachment_download_failed" }); + expect(notHttp).toMatchObject({ status: 400, code: "attachment_download_failed" }); + expect(refused.message).toBe("Attachment download failed."); + expect(notHttp.message).toBe(refused.message); + expect(refused.message).not.toContain("ECONNREFUSED"); + expect(notHttp.message).not.toContain("Parse Error"); + // The userinfo is dropped by the request (`host: url.host`, no `auth`), so + // echoing it back would leak a secret the download never used. + expect(refused.message).not.toContain("s3cret"); + expect(refused.message).not.toContain("user:"); + } finally { + for (const socket of rawSockets) socket.destroy(); + await new Promise((resolve) => raw.close(() => resolve())); + } + + // The operator still gets the transport detail, server-side only. + expect(reasons).toContain("ECONNREFUSED"); + expect(reasons.some((reason) => reason.startsWith("HPE_"))).toBe(true); + }); + + it("does not echo the raw URL when it cannot be parsed (SEC-02)", async () => { + const failure = await mediaFailure( + { url: "http://exa mple.test/x.png?token=super-secret" }, + config({ allowRemoteMediaUrls: true }), + ); + + expect(failure).toMatchObject({ status: 400, code: "invalid_attachment" }); + expect(failure.message).not.toContain("super-secret"); + expect(failure.message).not.toContain("exa mple"); + }); + + it("bounds DNS resolution by the fetch budget (SEC-04)", async () => { + // A resolver that never answers: `dns.lookup()` is `getaddrinfo`-based and + // takes no timeout, so only the race in the media module can settle this. + const lookup = vi + .spyOn(dns, "lookup") + .mockReturnValue(new Promise(() => undefined)); + const startedAt = Date.now(); + + await expect( + resolveAttachment( + { url: "http://blackhole.example.test/x.png" }, + config({ allowPrivateMediaUrls: false, mediaFetchTimeoutMs: 150 }), + ), + ).rejects.toMatchObject({ code: "attachment_download_failed", status: 400 }); + + expect(Date.now() - startedAt).toBeLessThan(2_000); + expect(lookup).toHaveBeenCalled(); + }); + + it("returns the standard 400 for an already-aborted signal without resolving or dialling (SEC-04)", async () => { + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "93.184.216.34", family: 4 }] as unknown as LookupAddress); + const dial = vi.spyOn(http, "request"); + + await expect( + resolveAttachment({ url: "http://media.example.test/x.png" }, config({ allowPrivateMediaUrls: false }), { + signal: AbortSignal.abort(), + }), + ).rejects.toMatchObject({ code: "attachment_download_failed", status: 400 }); + + expect(lookup).not.toHaveBeenCalled(); + expect(dial).not.toHaveBeenCalled(); + }); + it("honours a signal that is already aborted", async () => { const startedAt = Date.now(); await expect( @@ -579,6 +819,114 @@ describe("resolveAttachment", () => { await expect(resolveAttachments(sparse, config())).rejects.toMatchObject({ code: "invalid_attachment" }); }); }); + + describe("redirect re-validation (DOC-04)", () => { + /** Answers the redirect chain; reached through the public fixture host. */ + let hop: http.Server; + /** The private target a redirect must never reach. */ + let target: http.Server; + let hopPort = 0; + let targetPort = 0; + let targetHits = 0; + + beforeAll(async () => { + target = http.createServer((_request, response) => { + targetHits += 1; + response.writeHead(200, { "content-type": "image/png" }); + response.end(PNG_BUFFER); + }); + targetPort = await listen(target); + + hop = http.createServer((request, response) => { + const route = request.url?.split("?")[0] ?? ""; + if (route === "/to-private") { + response.writeHead(302, { location: `http://127.0.0.1:${targetPort}/image.png` }); + response.end(); + return; + } + if (route === "/file-scheme") { + response.writeHead(302, { location: "file:///etc/passwd" }); + response.end(); + return; + } + const chain = /^\/chain\/(\d+)$/.exec(route); + if (chain) { + const step = Number(chain[1]); + if (step >= 10) { + response.writeHead(200, { "content-type": "image/png" }); + response.end(PNG_BUFFER); + return; + } + response.writeHead(302, { location: `http://media.example.test:${hopPort}/chain/${step + 1}` }); + response.end(); + return; + } + response.writeHead(404); + response.end(); + }); + hopPort = await listen(hop); + }); + + afterAll(async () => { + hop.closeAllConnections(); + target.closeAllConnections(); + await new Promise((resolve) => hop.close(() => resolve())); + await new Promise((resolve) => target.close(() => resolve())); + }); + + beforeEach(() => { + // The public host is dialled at the local fixture while every URL keeps + // its public name, so the per-hop address guard really runs. + const realRequest = http.request.bind(http); + vi.spyOn(http, "request").mockImplementation((( + options: http.RequestOptions, + callback?: (response: http.IncomingMessage) => void, + ) => realRequest({ ...options, hostname: "127.0.0.1", port: hopPort }, callback)) as typeof http.request); + vi.spyOn(dns, "lookup").mockResolvedValue([ + { address: "93.184.216.34", family: 4 }, + ] as unknown as LookupAddress); + }); + + it("refuses a redirect to a private address and never dials it (DOC-04)", async () => { + const hitsBefore = targetHits; + + await expect( + resolveAttachment( + { url: `http://media.example.test:${hopPort}/to-private` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: false }), + ), + ).rejects.toMatchObject({ code: "private_media_blocked", status: 400 }); + + // The address guard runs on the redirect target *before* a socket is + // opened for that hop. + expect(targetHits).toBe(hitsBefore); + }); + + it("fails a chain longer than five hops (DOC-04)", async () => { + await expect( + resolveAttachment( + { url: `http://media.example.test:${hopPort}/chain/0` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: false }), + ), + ).rejects.toMatchObject({ code: "attachment_download_failed", status: 400 }); + }); + + it("destroys the body of a redirect rejected by the scheme allow-list (SEC-03)", async () => { + for (let attempt = 0; attempt < 8; attempt += 1) { + await expect( + resolveAttachment( + { url: `http://media.example.test:${hopPort}/file-scheme` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), + ), + ).rejects.toMatchObject({ code: "invalid_attachment", status: 400 }); + } + + // The scheme re-validation used to throw before the body was destroyed, so + // each 302 to a `file:` Location leaked one keep-alive socket until the + // agent idle timeout: 8 sequential attachments left 8 sockets open. + expect(await countConnections(hop)).toBeLessThanOrEqual(1); + }); + }); }); describe("local files", () => { @@ -646,14 +994,19 @@ describe("resolveAttachment", () => { } }); - it("re-checks the size after reading, through the open handle", async () => { - // The post-read check must be asserted against the handle the code really - // reads from: spying on `fsp.readFile` no longer intercepts anything once - // the read goes through `fsp.open()`. + it("re-checks the size while reading, through the open handle (SEC-05)", async () => { + // The cap must be enforced against the handle the code really reads from: + // the read goes through `handle.read()` in bounded chunks, so spying on + // `fsp.readFile`/`handle.readFile` intercepts nothing. const cap = PNG_BUFFER.byteLength + 16; const handle = { stat: vi.fn().mockResolvedValue({ isFile: () => true, size: PNG_BUFFER.byteLength, dev: 7, ino: 8 }), - readFile: vi.fn().mockResolvedValue(Buffer.alloc(cap * 2, 7)), + // A file that grew past the cap after the `stat`: the first bounded read + // already exceeds it. + read: vi.fn().mockImplementation((chunk: Buffer, _offset: number, length: number) => + Promise.resolve({ bytesRead: length, buffer: chunk }), + ), + readFile: vi.fn(), close: vi.fn().mockResolvedValue(undefined), }; const openSpy = vi.spyOn(fsp, "open").mockResolvedValue(handle as unknown as FileHandle); @@ -672,7 +1025,8 @@ describe("resolveAttachment", () => { ), ).rejects.toMatchObject({ code: "attachment_too_large" }); - expect(handle.readFile).toHaveBeenCalledTimes(1); + expect(handle.read).toHaveBeenCalledTimes(1); + expect(handle.readFile).not.toHaveBeenCalled(); expect(handle.close).toHaveBeenCalledTimes(1); } finally { openSpy.mockRestore(); @@ -680,6 +1034,45 @@ describe("resolveAttachment", () => { } }); + it("requests no allocation larger than the cap plus one chunk (SEC-05)", async () => { + // A file that keeps growing: the read must never allocate more than + // `min(64 KiB, limit + 1 - offset)` per iteration, so the whole file is not + // materialised before the cap rejects it. + const cap = 200_000; + const requested: number[] = []; + const handle = { + stat: vi.fn().mockResolvedValue({ isFile: () => true, size: 1_000, dev: 7, ino: 8 }), + read: vi.fn().mockImplementation((chunk: Buffer, _offset: number, length: number) => { + requested.push(length); + return Promise.resolve({ bytesRead: length, buffer: chunk }); + }), + close: vi.fn().mockResolvedValue(undefined), + }; + const openSpy = vi.spyOn(fsp, "open").mockResolvedValue(handle as unknown as FileHandle); + const lstatSpy = vi.spyOn(fsp, "lstat").mockResolvedValue({ + isSymbolicLink: () => false, + dev: 7, + ino: 8, + } as unknown as Awaited>); + + try { + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace], maxAttachmentBytes: cap }), + ), + ).rejects.toMatchObject({ code: "attachment_too_large" }); + + // Several bounded chunks were read instead of one unbounded materialisation. + expect(requested.length).toBeGreaterThan(1); + expect(Math.max(...requested)).toBeLessThanOrEqual(64 * 1024); + expect(requested.reduce((total, size) => total + size, 0)).toBeLessThanOrEqual(cap + 64 * 1024); + } finally { + openSpy.mockRestore(); + lstatSpy.mockRestore(); + } + }); + it("refuses files outside the allowed roots", async () => { await expect( resolveAttachment( @@ -896,4 +1289,19 @@ describe("host and path guards", () => { expect(isWithinRoots(path.join(roots[0] as string, "..", "escape.png"), roots)).toBe(false); expect(isWithinRoots(path.join(os.tmpdir(), "other", "x.png"), roots)).toBe(false); }); + + it("accepts a dot-prefixed child directory but not a traversal (SEC-08)", () => { + const roots = [path.join(os.tmpdir(), "root")]; + const root = roots[0] as string; + + // `..foo` is a legal directory name; only `..` (or `../`) escapes the root. + expect(isWithinRoots(path.join(root, "..foo", "x.png"), roots)).toBe(true); + expect(isWithinRoots(path.join(root, "..cache", "nested", "x.png"), roots)).toBe(true); + expect(isWithinRoots("/root/..foo/x.png", ["/root"])).toBe(true); + + expect(isWithinRoots(path.join(root, "..", "evil.png"), roots)).toBe(false); + expect(isWithinRoots(`${root}${path.sep}..${path.sep}evil.png`, roots)).toBe(false); + // A sibling whose name merely starts with the root's name stays outside. + expect(isWithinRoots(path.join(os.tmpdir(), "rootEvil", "x.png"), roots)).toBe(false); + }); }); \ No newline at end of file diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index abe1bd0..e355728 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -221,6 +221,10 @@ describe("POST /v1/chat/completions (non-streaming)", () => { { field: "web_search_options", payload: { web_search_options: {} }, param: "web_search_options" }, { field: "functions", payload: { functions: [{ name: "lookup" }] }, param: "functions" }, { field: "function_call", payload: { function_call: "auto" }, param: "function_call" }, + // Declared-but-unsupported fields used to be stripped by the schema, so + // `best_of: 3` silently produced a single completion with a 200. + { field: "best_of", payload: { best_of: 3 }, param: "best_of" }, + { field: "suffix", payload: { suffix: "XX" }, param: "suffix" }, ]; for (const { field, payload, param } of rejections) { @@ -239,6 +243,26 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); + it("treats an explicit null best_of/suffix as unset", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + best_of: null, + suffix: null, + }, + }); + + // Both fields stay in `NULLABLE_TOP_LEVEL_FIELDS`: no `best_of` was asked + // for, so there is nothing to reject. + expect(response.statusCode).toBe(200); + await app.close(); + }); + it("rejects a non-auto image_url.detail instead of silently sending full media", async () => { const app = await buildServer(createTestContext()); const response = await app.inject({ diff --git a/test/openai-models.test.ts b/test/openai-models.test.ts index 3b719e3..7bfa36a 100644 --- a/test/openai-models.test.ts +++ b/test/openai-models.test.ts @@ -1,7 +1,7 @@ /** * Unit tests for the OpenAI-compatible model listing surface. */ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { createLogger } from "../src/logger.js"; import { buildServer } from "../src/server.js"; import type { OpencodeClient } from "../src/upstream/client.js"; @@ -226,6 +226,112 @@ describe("ModelRegistry catalogue loading", () => { }); }); +describe("ModelRegistry catalogue retention after an empty answer", () => { + const agent: OpencodeAgentInfo = { id: "build", name: "Build", mode: "primary", hidden: false, request: {} }; + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("stops serving a retained catalogue once the TTL elapsed since the first empty answer", async () => { + const models = defaultModels(); + // Only `Date.now()` is controlled: `#retryEmpty()`'s 250/750 ms retries run + // for real, which is why every assertion below happens after its await. + const now = { value: 1_000_000 }; + vi.spyOn(Date, "now").mockImplementation(() => now.value); + + let current: typeof models = models; + const config = testConfig({ modelCacheTtlMs: 1_000 }); + const reg = new ModelRegistry( + { + listModels: async () => current, + listProviders: async () => [], + listAgents: async () => [agent], + } as unknown as OpencodeClient, + config, + createLogger(config), + ); + + // Warm the cache with a good catalogue. `modelCacheTtlMs` is 1 s, so the + // first empty answer below has to land inside that window to be retained. + expect((await reg.catalog()).models).toHaveLength(models.length); + + // The upstream is permanently empty from now on. Each answer inside the + // grace window keeps the retained catalogue and rewrites `fetchedAt`, which + // used to push the expiry out forever: `/ready` stayed ready, `/v1/models` + // kept listing dead models and `resolve()` kept succeeding. + current = []; + now.value = 1_000_500; + expect((await reg.catalog(true)).models).toHaveLength(0); + + // Still inside the TTL window that the first empty answer started. + now.value = 1_000_501; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toHaveLength(models.length); + + // Still inside it one TTL later: the retained catalogue is only masked for + // one window measured from the first empty answer, so it is not dropped just + // because a later empty answer rewrote `fetchedAt`. + now.value = 1_000_999; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toHaveLength(models.length); + + // Once that window elapsed the retained catalogue is gone and `/ready`, + // `/v1/models` and `resolve()` follow. This is what used to never happen: + // each empty answer rewrote `fetchedAt` without any bound, so the stale + // catalogue was renewed forever. + now.value = 1_001_501; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toEqual([]); + expect(reg.cached?.models).toHaveLength(0); + await expect(reg.resolve("opencode/big-pickle")).rejects.toMatchObject({ code: "model_not_found" }); + }); + + it("clears the empty-answer age when a non-empty answer arrives", async () => { + const models = defaultModels(); + const now = { value: 1_000_000 }; + vi.spyOn(Date, "now").mockImplementation(() => now.value); + + let current: typeof models = []; + const config = testConfig({ modelCacheTtlMs: 1_000 }); + const reg = new ModelRegistry( + { + listModels: async () => current, + listProviders: async () => [], + listAgents: async () => [agent], + } as unknown as OpencodeClient, + config, + createLogger(config), + ); + + // First answer is empty: there is nothing to retain and no retention clock. + expect((await reg.catalog()).models).toHaveLength(0); + expect(reg.cached).toBeUndefined(); + + // A recovery must restart every clock, not inherit the previous empty answer. + current = models; + now.value = 3_000; + expect((await reg.catalog()).models).toHaveLength(models.length); + + current = []; + now.value = 4_000; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toHaveLength(models.length); + + // The window restarted with the *second* empty answer (and the recovery in + // between cleared the previous age), so half a TTL later the catalogue is + // still retained. Measuring from the first empty answer would have dropped + // it here. + now.value = 4_500; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toHaveLength(models.length); + + // Past the restarted window it is dropped again. + now.value = 5_501; + expect((await reg.catalog(true)).models).toHaveLength(0); + expect(await reg.list()).toEqual([]); + }); +}); describe("GET /v1/models/:id", () => { it("returns a single entry with the full capability block for a bare id", async () => { const app = await buildServer(createTestContext()); diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index bfcdf1c..0688282 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -10,6 +10,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; import { registerOpenAiResponsesRoutes } from "../src/adapter/openai/responses.js"; import { requireApiKey } from "../src/auth.js"; +import { createRateLimiters } from "../src/http/rateLimit.js"; import type { AppContext, CompletionRunner } from "../src/context.js"; import { ApiError, toApiError, toOpenAiError } from "../src/errors.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; @@ -54,7 +55,7 @@ async function makeApp( const ctx: AppContext = run === undefined ? base : { ...base, completion: { ...base.completion, run } }; const app = Fastify({ requestTimeout: 0, connectionTimeout: 0 }); - app.addHook("preHandler", requireApiKey(ctx.config)); + app.addHook("preHandler", requireApiKey(ctx.config, createRateLimiters(ctx.config))); app.setErrorHandler((error: unknown, _request: FastifyRequest, reply: FastifyReply) => { const apiError = error instanceof ApiError ? error : toApiError(error, "Internal server error."); return reply.status(apiError.status).send(toOpenAiError(apiError)); @@ -404,6 +405,7 @@ describe("POST /v1/responses (non-streaming)", () => { { field: "web_search_options", payload: { web_search_options: {} }, param: "web_search_options" }, { field: "functions", payload: { functions: [{ name: "lookup" }] }, param: "functions" }, { field: "function_call", payload: { function_call: "auto" }, param: "function_call" }, + { field: "tool_choice", payload: { tool_choice: "bogus" }, param: "tool_choice" }, { field: "previous_response_id", payload: { previous_response_id: "resp_x" }, @@ -1129,6 +1131,13 @@ describe("POST /v1/responses (streaming)", () => { expect(errorFrame?.json["code"]).toBe("upstream_error"); expect(errorFrame?.json["param"]).toBeNull(); expect(parsed.some((frame) => frame.json["type"] === "response.completed")).toBe(false); + + // The terminal `response.failed` frame precedes the flat legacy `error` + // frame, matching docs/API.md §2: a client that stops at the first `error` + // frame must still have seen the terminal response object. + const types = parsed.map((frame) => frame.json["type"]); + expect(types).toEqual(["response.created", "response.in_progress", "response.failed", "error"]); + expect(parsed.map((frame) => frame.json["sequence_number"])).toEqual(parsed.map((_, index) => index)); }); it("ends a failed turn with a terminal response.failed event", async () => { @@ -1152,8 +1161,7 @@ describe("POST /v1/responses (streaming)", () => { expect(response.statusCode).toBe(200); const parsed = frames(response.payload); - const terminal = parsed.at(-1); - expect(terminal?.event).toBe("response.failed"); + const terminal = parsed.find((frame) => frame.event === "response.failed"); expect(terminal?.json["type"]).toBe("response.failed"); const body = terminal?.json["response"] as ResponsePayload; expect(body.status).toBe("failed"); @@ -1162,8 +1170,12 @@ describe("POST /v1/responses (streaming)", () => { message: "The upstream completion ended with an error.", }); expect(body.output_text).toBe("partial"); - // The flat `error` frame is kept next to the spec-shaped terminal event. - expect(parsed.some((frame) => frame.event === "error")).toBe(true); + // The flat `error` frame is kept next to the spec-shaped terminal event, but + // it must follow it (`docs/API.md` §2). + const failedAt = parsed.findIndex((frame) => frame.event === "response.failed"); + const errorAt = parsed.findIndex((frame) => frame.event === "error"); + expect(failedAt).toBeGreaterThan(-1); + expect(errorAt).toBeGreaterThan(failedAt); expect(parsed.map((frame) => frame.json.sequence_number)).toEqual(parsed.map((_, index) => index)); }); @@ -1193,7 +1205,9 @@ describe("POST /v1/responses (streaming)", () => { const numbers = parsed.map((frame) => frame.json.sequence_number); expect(numbers).not.toContain(Number.MAX_SAFE_INTEGER); expect(numbers).toEqual(numbers.map((_, index) => index)); - expect(parsed.at(-1)?.event).toBe("response.failed"); + // `response.failed` is the terminal response event; the flat `error` frame + // follows it (`docs/API.md` §2). + expect(parsed.map((frame) => frame.event).slice(-2)).toEqual(["response.failed", "error"]); }); it("keeps the live counter when the stream fails after its first frames", async () => { @@ -1228,7 +1242,7 @@ describe("POST /v1/responses (streaming)", () => { const numbers = parsed.map((frame) => frame.json.sequence_number); expect(numbers).not.toContain(Number.MAX_SAFE_INTEGER); expect(numbers).toEqual(numbers.map((_, index) => index)); - expect(parsed.at(-1)?.event).toBe("response.failed"); + expect(parsed.map((frame) => frame.event).slice(-2)).toEqual(["response.failed", "error"]); }); it("surfaces a consolidated reasoning summary sent without deltas", async () => { @@ -1358,8 +1372,7 @@ describe("POST /v1/responses (streaming)", () => { }); expect(response.statusCode).toBe(200); - const terminal = frames(response.payload).at(-1); - expect(terminal?.event).toBe("response.failed"); + const terminal = frames(response.payload).find((frame) => frame.event === "response.failed"); const body = terminal?.json["response"] as ResponsePayload; expect(body.status).toBe("failed"); // A fabricated all-zero usage asserted a cost for a turn that failed before @@ -1367,7 +1380,7 @@ describe("POST /v1/responses (streaming)", () => { expect(body.usage).toBeNull(); }); - it("announces the message item when the text only arrives in text_end", async () => { + it("delivers a text_end-only turn through the delta channel", async () => { const app = await makeApp({ script: (request): CompletionEvent[] => { const usage = { ...EMPTY_USAGE, inputTokens: 2, outputTokens: 3, totalTokens: 5 }; @@ -1393,7 +1406,11 @@ describe("POST /v1/responses (streaming)", () => { expect(types).toContain("response.output_item.added"); expect(types).toContain("response.content_part.added"); expect(types).toContain("response.output_text.done"); - expect(types).not.toContain("response.output_text.delta"); + // A `text_end`-only turn used to emit no delta at all, so a client that + // accumulates `response.output_text.delta` (the documented path, and what + // `openai-node`'s `ResponseStream` uses) rendered an empty answer. + const deltas = parsed.filter((frame) => frame.json["type"] === "response.output_text.delta"); + expect(deltas.map((frame) => frame.json["delta"])).toEqual(["all at once"]); const final = parsed.at(-1)?.json["response"] as ResponsePayload; expect(final.output_text).toBe("all at once"); @@ -1402,6 +1419,100 @@ describe("POST /v1/responses (streaming)", () => { expect(final.output[0]?.content?.[0]?.text).toBe("all at once"); }); + it("emits the unseen suffix when a consolidated text_end is adopted", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 2, outputTokens: 9, totalTokens: 11 }; + return [ + { kind: "start", sessionId: "ses_suffix", messageId: "msg_suffix", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "Hello", ordinal: 0 }, + // The provider's consolidated snapshot is longer than the deltas. + { kind: "text_end", text: "Hello, the whole answer!", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_suffix" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const deltas = parsed.filter((frame) => frame.json["type"] === "response.output_text.delta"); + expect(deltas.map((frame) => frame.json["delta"])).toEqual(["Hello", ", the whole answer!"]); + // The client-accumulated deltas must equal the terminal payload. + const accumulated = deltas.map((frame) => String(frame.json["delta"])).join(""); + expect(accumulated).toBe("Hello, the whole answer!"); + expect((parsed.at(-1)?.json["response"] as ResponsePayload).output_text).toBe(accumulated); + }); + + it("emits the unseen suffix when a consolidated reasoning_end is adopted", async () => { + const app = await makeApp({ + script: (): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 4, outputTokens: 3, reasoningTokens: 6, totalTokens: 13 }; + return [ + { kind: "start", sessionId: "ses_r_suffix", messageId: "msg_r_suffix", model: "opencode/deepseek-v4.1-flash-free", agent: "build", reusedSession: false, reasoningEnabled: true }, + { kind: "reasoning_delta", text: "first step", ordinal: 0 }, + { kind: "reasoning_end", text: "first step and a second one", ordinal: 0 }, + { kind: "text_delta", text: "Done.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_r_suffix" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Think.", stream: true, reasoning: { effort: "high" } }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const deltas = parsed.filter((frame) => frame.json["type"] === "response.reasoning_summary_text.delta"); + expect(deltas.map((frame) => frame.json["delta"])).toEqual(["first step", " and a second one"]); + const accumulated = deltas.map((frame) => String(frame.json["delta"])).join(""); + expect(accumulated).toBe("first step and a second one"); + + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + expect(final.output.find((item) => item.type === "reasoning")?.summary).toEqual([ + { type: "summary_text", text: accumulated }, + ]); + }); + + it("emits the whole summary when a reasoning summary arrives without deltas", async () => { + const app = await makeApp({ + script: (): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 4, outputTokens: 3, reasoningTokens: 5, totalTokens: 12 }; + return [ + { kind: "start", sessionId: "ses_r2", messageId: "msg_r2", model: "opencode/deepseek-v4.1-flash-free", agent: "build", reusedSession: false, reasoningEnabled: true }, + { kind: "reasoning_end", text: "summary only", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_r2" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Think.", stream: true, reasoning: { effort: "low" } }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const deltas = parsed.filter((frame) => frame.json["type"] === "response.reasoning_summary_text.delta"); + expect(deltas.map((frame) => frame.json["delta"])).toEqual(["summary only"]); + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + expect(final.output.find((item) => item.type === "reasoning")?.summary).toEqual([ + { type: "summary_text", text: "summary only" }, + ]); + }); + it("streams 5000 deltas and joins the text once", async () => { const pieces = Array.from({ length: 5_000 }, (_, index) => `chunk-${index};`); const app = await makeApp({ @@ -1698,3 +1809,176 @@ describe("POST /v1/responses (media concurrency)", () => { expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); }); }); + +describe("POST /v1/responses (function_call_output media)", () => { + it("attaches the media of a function_call_output to a synthetic user turn", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ onRun: (request) => (captured = request) }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { type: "function_call", call_id: "call_1", name: "screenshot", arguments: "{}" }, + { + type: "function_call_output", + call_id: "call_1", + output: [ + { type: "input_text", text: "the screenshot" }, + { type: "input_image", image_url: PNG_DATA_URI }, + { type: "input_file", file_data: "data:application/pdf;base64,JVBERi0=", filename: "report.pdf" }, + ], + }, + { role: "user", content: "What does it show?" }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured?.messages.map((message) => message.role)).toEqual(["assistant", "tool", "user", "user"]); + + const tool = captured?.messages[1]; + expect(tool?.role).toBe("tool"); + // The tool message keeps the placeholder; the bytes ride on the user turn. + expect(tool?.text).toBe("the screenshot\n[image: image/png]\n[document: application/pdf]"); + expect(tool?.toolCallId).toBe("call_1"); + + const mediaTurn = captured?.messages[2]; + expect(mediaTurn?.role).toBe("user"); + expect(mediaTurn?.attachments?.map((attachment) => attachment.kind)).toEqual(["image", "document"]); + expect(mediaTurn?.attachments?.[0]?.data).toBe(PNG_BASE64); + expect(mediaTurn?.attachments?.[1]?.mime).toBe("application/pdf"); + // The caller's own turn keeps its place and its text. + expect(captured?.messages[3]).toEqual({ role: "user", text: "What does it show?" }); + }); + + it("keeps a text-only function_call_output in the tool message", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ onRun: (request) => (captured = request) }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { type: "function_call", call_id: "call_1", name: "lookup", arguments: "{}" }, + { + type: "function_call_output", + call_id: "call_1", + output: [ + { type: "input_text", text: "line one" }, + { type: "output_text", text: "line two" }, + ], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured?.messages).toEqual([ + { role: "assistant", text: "", toolCalls: [{ id: "call_1", name: "lookup", arguments: "{}" }] }, + { role: "tool", text: "line one\nline two", toolCallId: "call_1" }, + ]); + }); +}); + +describe("POST /v1/responses (input validation)", () => { + it("rejects an empty input array with 400", async () => { + const app = await makeApp(); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: [] }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("input"); + }); + + it("rejects an empty input string with 400", async () => { + // The array form was already rejected; the string form used to prompt the + // upstream with an empty turn and answer 200. + const app = await makeApp(); + + for (const input of ["", " "]) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input }, + }); + + expect(response.statusCode, JSON.stringify(input)).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("input"); + } + }); + + it("rejects a tool_choice it cannot honour instead of echoing it", async () => { + const app = await makeApp(); + + for (const tool_choice of ["bogus", { type: "allowed_tools", mode: "auto", tools: [] }]) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "Use the tool.", + tools: [{ type: "function", name: "lookup" }], + tool_choice, + }, + }); + expect(response.statusCode, `${JSON.stringify(tool_choice)} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code).toBe("unsupported_parameter"); + expect(body.error.param).toBe("tool_choice"); + } + }); + + it("accepts and echoes the four tool_choice forms it can honour", async () => { + const captured: InternalRequest[] = []; + const app = await makeApp({ onRun: (request) => captured.push(request) }); + const send = async (tool_choice: unknown): Promise => { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "Use the tool.", + tools: [{ type: "function", name: "lookup" }], + tool_choice, + }, + }); + expect(response.statusCode).toBe(200); + return response.json() as ResponsePayload; + }; + + expect((await send("auto")).tool_choice).toBe("auto"); + expect((await send(undefined)).tool_choice).toBe("auto"); + expect((await send("none")).tool_choice).toBe("none"); + expect((await send("required")).tool_choice).toBe("required"); + expect((await send({ type: "function", name: "lookup" })).tool_choice).toBe("function:lookup"); + expect((await send({ type: "function", function: { name: "lookup" } })).tool_choice).toBe("function:lookup"); + + expect(captured.map((request) => request.toolChoice)).toEqual([ + "auto", + undefined, + "none", + "required", + { name: "lookup" }, + { name: "lookup" }, + ]); + }); +}); diff --git a/test/process.test.ts b/test/process.test.ts index 32ed115..a1c19e9 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -6,17 +6,24 @@ * without launching the CLI. */ 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 { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { ApiError } from "../src/errors.js"; -import { createLogger } from "../src/logger.js"; +import { createLogger, type Logger } from "../src/logger.js"; import { createMetrics, type Metrics } from "../src/metrics/registry.js"; +import { OpencodeClient } from "../src/upstream/client.js"; import { OutputTail, StderrTail, UpstreamProcess, readinessScans, + redactUpstreamSecret, + type ProbeResult, type SpawnedChild, } from "../src/upstream/process.js"; import { testConfig } from "./helpers/context.js"; @@ -55,6 +62,8 @@ interface Harness { process: UpstreamProcess; children: FakeChild[]; metrics: Metrics; + config: ReturnType; + log: Logger; } interface HarnessOptions { @@ -67,7 +76,18 @@ interface HarnessOptions { ready?: boolean; /** Write this text to stderr right before (or instead of) readiness. */ stderr?: string; + /** Write the stderr text in these pieces, as separate chunks. */ + stderrChunks?: string[]; + /** Announce this URL instead of one derived from `--port`. */ + announceUrl?: string; upstreamStartTimeoutMs?: number; + /** Explicit upstream server; bypasses the spawn path. */ + upstreamUrl?: string; + upstreamPassword?: string; + /** Override the readiness probe instead of performing a real request. */ + probe?: (endpoint: { url: string; password?: string }) => Promise; + /** Log directory root; defaults to the OS temp directory. */ + dataDir?: string; /** Keep discovery away from whatever `opencode serve` runs on this machine. */ discover?: () => Promise<{ url: string; password?: string; source: "env" | "spawned" | "discovered" } | undefined>; } @@ -93,10 +113,12 @@ function harness(options: HarnessOptions = {}): Harness { const readyMs = options.readyMs ?? 0; const children: FakeChild[] = []; const config = testConfig({ - dataDir: os.tmpdir(), + dataDir: options.dataDir ?? os.tmpdir(), workdir: os.tmpdir(), upstreamAutostart: true, upstreamStartTimeoutMs: options.upstreamStartTimeoutMs ?? 2_000, + ...(options.upstreamUrl === undefined ? {} : { upstreamUrl: options.upstreamUrl }), + ...(options.upstreamPassword === undefined ? {} : { upstreamPassword: options.upstreamPassword }), }); const log = createLogger(config); const metrics = createMetrics({ enabled: false }); @@ -104,15 +126,20 @@ function harness(options: HarnessOptions = {}): Harness { const process = new UpstreamProcess(config, log, metrics, { findBinary: () => "/fake/opencode", discover: options.discover ?? (async () => undefined), + ...(options.probe === undefined ? {} : { probe: options.probe }), spawn: (_command, args) => { const child = new FakeChild(4_000 + children.length); children.push(child); const port = args[args.indexOf("--port") + 1] ?? "0"; + const url = options.announceUrl ?? `http://127.0.0.1:${port}`; + for (const piece of options.stderrChunks ?? []) { + if (piece.length > 0) child.stderr.write(piece); + } if (options.stderr !== undefined) child.stderr.write(options.stderr); if (options.ready !== false) { const announce = (): void => { if (readyMs !== "never") { - child.stdout.write(`server listening on http://127.0.0.1:${port}\n`); + child.stdout.write(`server listening on ${url}\n`); child.stdout.write("server password fake-password\n"); } }; @@ -126,11 +153,33 @@ function harness(options: HarnessOptions = {}): Harness { }, }); - return { process, children, metrics }; + return { process, children, metrics, config, log }; } const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 10)); +/** + * Resolve and return the rejection reason. + * + * `resolve()` is typed to return an endpoint, so the failure has to be narrowed + * by hand; every caller asserts on the `ApiError` it carries. + */ +async function resolveFailure(target: UpstreamProcess): Promise { + return (await target.resolve().catch((reason: unknown) => reason)) as ApiError; +} + +/** 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 ""; +} + describe("UpstreamProcess", () => { it("terminates the previous server when a respawn replaces it", async () => { const { process, children } = harness(); @@ -373,4 +422,305 @@ describe("UpstreamProcess", () => { for (let index = 0; index < 10; index += 1) stderr.push(`line ${index}\n`); expect(stderr.lines).toEqual(["line 7", "line 8", "line 9"]); }); +}); + +// ------------------------------------------------------------------- SEC-01 --- + +describe("redactUpstreamSecret", () => { + it("masks the password marker and a leaked Basic credential, and nothing else", () => { + expect(redactUpstreamSecret("server password super-secret")).toBe("server password [redacted]"); + expect(redactUpstreamSecret("Server Password hunter2\n")).toBe("Server Password [redacted]\n"); + expect(redactUpstreamSecret("Authorization: Basic b3BlbmNvZGU6aHVudGVyMg==")).toBe( + "Authorization: Basic [redacted]", + ); + // Ordinary diagnostics stay verbatim: masking must be narrow. + expect(redactUpstreamSecret("server listening on http://127.0.0.1:20124")).toBe( + "server listening on http://127.0.0.1:20124", + ); + expect(redactUpstreamSecret("authorization: Bearer abc.def")).toBe("authorization: Bearer abc.def"); + expect(redactUpstreamSecret("warn: slow provider")).toBe("warn: slow provider"); + }); +}); + +describe("UpstreamProcess credential exposure (SEC-01)", () => { + it("redacts the password from the log file, the spawn error and status()", async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-redact-")); + const { process, config } = harness({ + dataDir, + ready: false, + stderr: "server password super-secret\nstartup failed\n", + }); + + const error = await resolveFailure(process); + + // The readiness failure travels into the caller-visible error body. + expect(error.message).toContain("server password [redacted]"); + expect(error.message).not.toContain("super-secret"); + expect(process.status().stderrTail).toEqual(["server password [redacted]", "startup failed"]); + + 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"); + }); + + it("masks a marker split across two chunks on read", async () => { + // Push-time redaction cannot see a marker split across chunks; the + // `status()` pass is the boundary that catches it. + const { process } = harness({ + ready: false, + stderrChunks: ["server pass", "word super-secret\n"], + upstreamStartTimeoutMs: 200, + }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + expect(process.status().stderrTail).toEqual(["server password [redacted]"]); + expect(JSON.stringify(process.status().stderrTail)).not.toContain("super-secret"); + }); +}); + +// ------------------------------------------------------------------- COR-08 --- + +describe("UpstreamProcess log destination failures (COR-08)", () => { + it("survives a child log file that cannot be opened", async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-logfail-")); + const logs = path.join(dataDir, "logs"); + // A directory where the log file belongs: `createWriteStream` emits 'error' + // asynchronously, and with no listener that used to abort the process. + fs.mkdirSync(path.join(logs, `opencode-${testConfig().upstreamPort}.log`), { recursive: true }); + + const { process, children, log } = harness({ dataDir }); + const warn = vi.spyOn(log, "warn"); + + const endpoint = await process.resolve(); + await tick(); + + expect(endpoint.url).toContain("http://127.0.0.1:"); + expect(process.status().ready).toBe(true); + const logged = warn.mock.calls.filter((call) => String(call[1]).includes("could not write the OpenCode server log")); + expect(logged).toHaveLength(1); + + // Later writes are gated on the failure flag and must not throw either. + expect(() => children[0]?.stdout.emit("data", "still alive\n")).not.toThrow(); + expect(() => children[0]?.stderr.emit("data", "warn: after failure\n")).not.toThrow(); + expect(process.status().stderrTail).toContain("warn: after failure"); + await process.stop(); + }); +}); + +// ------------------------------------------------------------------- COR-09 --- + +describe("UpstreamProcess.reprobe (COR-09)", () => { + it("re-publishes the same child when the remembered endpoint answers", async () => { + let probe: ProbeResult = "ok"; + const { process, children } = harness({ probe: async () => probe }); + + const first = await process.resolve(); + process.reprobe("Upstream request timed out: test"); + + const again = await process.resolve(); + + // A timeout must not kill the shared server: every in-flight turn of every + // caller would fail with it. + expect(children).toHaveLength(1); + expect(children[0]?.signals ?? []).not.toContain("SIGKILL"); + expect(again.url).toBe(first.url); + expect(again.pid).toBe(first.pid); + expect(process.status().ready).toBe(true); + }); + + it("keeps the re-probe alive across a second timeout before the next resolve", async () => { + // Two requests can time out before anything calls `resolve()` again. The + // second one must not cancel the first one's re-verification, or the spawn + // path would SIGKILL the child the first timeout deliberately spared. + const { process, children } = harness({ probe: async () => "ok" }); + + const first = await process.resolve(); + process.reprobe("Upstream request timed out: first"); + process.reprobe("Upstream request timed out: second"); + + const again = await process.resolve(); + + expect(children).toHaveLength(1); + expect(children[0]?.signals ?? []).not.toContain("SIGKILL"); + expect(again.pid).toBe(first.pid); + }); + + it("replaces the child when the re-probe no longer answers", async () => { + let probe: ProbeResult = "ok"; + const { process, children } = harness({ probe: async () => probe }); + + const first = await process.resolve(); + expect(children).toHaveLength(1); + + probe = "absent"; + process.reprobe("Upstream request timed out: throw"); + + const second = await process.resolve(); + + expect(children).toHaveLength(2); + expect(children[0]?.signals).toContain("SIGKILL"); + expect(second.pid).not.toBe(first.pid); + expect(process.status().ready).toBe(true); + }); + + it("keeps the spawned server alive across a real client timeout", async () => { + const server = http.createServer(() => { + /* deliberately never answers: the client must time out */ + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const url = `http://127.0.0.1:${port}`; + + try { + const { process, children, config, log, metrics } = harness({ + announceUrl: url, + probe: async (endpoint) => (endpoint.url === url ? "ok" : "absent"), + }); + const client = new OpencodeClient(process, config, log, metrics, { catalogueTimeoutMs: 150 }); + + await expect(client.listModels()).rejects.toMatchObject({ code: "upstream_timeout" }); + // The timeout only marked the endpoint for re-verification. + expect(children[0]?.signals ?? []).not.toContain("SIGKILL"); + expect(process.status().ready).toBe(false); + + const republished = await process.resolve(); + expect(republished.url).toBe(url); + expect(children).toHaveLength(1); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + it("clears the re-probe request on stop()", async () => { + const { process, children } = harness(); + + await process.resolve(); + process.reprobe("Upstream request timed out: stop"); + await process.stop(); + await process.resolve(); + + // `stop()` drops the child, so the remembered endpoint is gone and the next + // resolve must spawn rather than re-verify anything. + expect(children).toHaveLength(2); + expect(process.status().ready).toBe(true); + }); +}); + +// ------------------------------------------------------------------- COR-10 --- + +describe("UpstreamProcess signal-equivalent shutdown during a cold start (COR-10)", () => { + it("kills the child it already spawned when the shared shutdown path runs", async () => { + const { process, children } = harness({ readyMs: 5_000 }); + + const pending = process.resolve(); + expect(children).toHaveLength(1); + + // The signal handlers registered before the warm-up call exactly this. + await process.shutdown(); + + await expect(pending).rejects.toThrow("upstream is shutting down"); + expect(children[0]?.signals).toContain("SIGKILL"); + expect(process.status().ready).toBe(false); + }); +}); + +// ------------------------------------------------------------------- COR-11 --- + +describe("UpstreamProcess.stop during a pending start (COR-11)", () => { + it("interrupts a start that has not been adopted yet and stays non-terminal", async () => { + const { process, children } = harness({ readyMs: 300 }); + + const pending = process.resolve(); + expect(children).toHaveLength(1); + await process.stop(); + + // The child was inside its readiness window; without the fix it was adopted + // afterwards as if it were the replacement server. + expect(children[0]?.signals).toContain("SIGKILL"); + await expect(pending).rejects.toThrow(/readiness|OpenCode server/); + expect(process.status().ready).toBe(false); + + // `stop()` stays non-terminal: the instance is not marked terminal, so the + // next resolve is an ordinary attempt (here bounded by the failed-start + // backoff the interrupted start armed) and never the shutdown error. + const followUp = await resolveFailure(process); + expect(followUp).toBeInstanceOf(ApiError); + expect(followUp.code).toBe("upstream_unavailable"); + expect(followUp.message).not.toContain("shutting down"); + }); +}); + +// ------------------------------------------------------------------- COR-12 --- + +describe("UpstreamProcess readiness probe (COR-12)", () => { + /** Serve exactly one canned response for every `GET /api/model`. */ + async function canned(status: number, body = "{}"): Promise<{ url: string; close: () => Promise }> { + const server = http.createServer((_request, response) => { + response.writeHead(status, { "content-type": "application/json" }); + response.end(body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${port}`, + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; + } + + it("reports 401 as upstream_unauthorized instead of unreachable", async () => { + const target = await canned(401, '{"error":"unauthorized"}'); + try { + const { process } = harness({ upstreamUrl: target.url }); + const error = await resolveFailure(process); + + expect(error).toBeInstanceOf(ApiError); + expect(error.code).toBe("upstream_unauthorized"); + expect(error.status).toBe(503); + expect(error.message).toContain("OPENCODE_SERVER_PASSWORD"); + expect(error.message).not.toContain("not reachable"); + expect(process.status().ready).toBe(false); + } finally { + await target.close(); + } + }); + + it("keeps a 400 challenge reachable", async () => { + const target = await canned(400, '{"error":"bad request"}'); + try { + const { process } = harness({ upstreamUrl: target.url }); + const endpoint = await process.resolve(); + expect(endpoint.url).toBe(target.url); + expect(process.status().ready).toBe(true); + } finally { + await target.close(); + } + }); + + it("publishes any reachable service answering 200, unchanged", async () => { + const target = await canned(200, '{"unrelated":true}'); + try { + const { process } = harness({ upstreamUrl: target.url }); + const endpoint = await process.resolve(); + expect(endpoint.url).toBe(target.url); + } finally { + await target.close(); + } + }); + + it("maps an absent endpoint to upstream_unreachable", async () => { + const target = await canned(500, "boom"); + try { + const { process } = harness({ upstreamUrl: target.url }); + const error = await resolveFailure(process); + expect(error.code).toBe("upstream_unreachable"); + expect(error.message).toContain("is not reachable"); + } finally { + await target.close(); + } + }); }); \ No newline at end of file diff --git a/test/reasoning.test.ts b/test/reasoning.test.ts index 1515859..4f48df0 100644 --- a/test/reasoning.test.ts +++ b/test/reasoning.test.ts @@ -31,6 +31,47 @@ describe("reasoning effort helpers", () => { expect(normaliseEffort(undefined)).toBeUndefined(); }); + it("normalises every accepted spelling without rebuilding the alias table", () => { + // The 21-entry alias object used to be allocated inside `normaliseEffort()`, + // which runs for every model variant on GET /v1/models and several times per + // completion. The table is now module-level, so this pins every spelling it + // answers and bounds the cost of a full pass over it. + const table: Array<[string, string]> = [ + ["none", "none"], + ["off", "none"], + ["disabled", "none"], + ["false", "none"], + ["minimal", "minimal"], + ["min", "minimal"], + ["lowest", "minimal"], + ["low", "low"], + ["medium", "medium"], + ["mid", "medium"], + ["default", "medium"], + ["normal", "medium"], + ["high", "high"], + ["xhigh", "xhigh"], + ["extrahigh", "xhigh"], + ["veryhigh", "xhigh"], + ["max", "max"], + ["maximum", "max"], + ["highest", "max"], + ]; + for (const [spelling, effort] of table) { + expect(normaliseEffort(spelling)).toBe(effort); + // Case, inner whitespace, `_` and `-` are all stripped before the lookup. + expect(normaliseEffort(spelling.toUpperCase())).toBe(effort); + } + expect(normaliseEffort(" extra-high ")).toBe("xhigh"); + expect(normaliseEffort("very_high")).toBe("xhigh"); + + const startedAt = performance.now(); + for (let round = 0; round < 20_000; round += 1) { + for (const [spelling] of table) normaliseEffort(spelling); + } + expect(performance.now() - startedAt).toBeLessThan(500); + }); + it("buckets budgets and back again", () => { expect(effortFromBudget(0)).toBe("minimal"); expect(effortFromBudget(1_500)).toBe("minimal"); diff --git a/test/regressions.test.ts b/test/regressions.test.ts index f4db4e0..8869f43 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -3,8 +3,12 @@ * OpenCode CLI (see docs/ARCHITECTURE.md sections 2 and 6). */ import { describe, expect, it } from "vitest"; +import { spawnSync } from "node:child_process"; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; import http from "node:http"; import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { canonicalPath } from "../src/auth.js"; import { ApiError } from "../src/errors.js"; import { MAX_RATE_LIMIT_BUCKETS, TokenBucketLimiter } from "../src/http/rateLimit.js"; @@ -689,6 +693,40 @@ describe("adversarial input handling", () => { await app.close(); }); + it("accepts only the three documented credential transports", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const documented = [ + { authorization: "Bearer test-key" }, + { authorization: `Basic ${Buffer.from("test-key:").toString("base64")}` }, + { "x-api-key": "test-key" }, + ]; + for (const headers of documented) { + const response = await app.inject({ method: "GET", url: "/v1/models", headers }); + expect(response.statusCode, JSON.stringify(headers)).toBe(200); + } + } finally { + await app.close(); + } + }); + + it("rejects an Authorization header with no scheme", async () => { + // The whole header used to be treated as the key when it contained no space, + // so a completely different scheme (`Negotiate...`) was reinterpreted as a + // credential and `Authorization: ` was an undocumented fourth transport. + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + for (const value of ["test-key", "NegotiateToken", "Bearer"]) { + const response = await app.inject({ method: "GET", url: "/v1/models", headers: { authorization: value } }); + expect(response.statusCode, value).toBe(401); + } + } finally { + await app.close(); + } + }); + it("serves the discovery document without a key", async () => { const ctx = createTestContext(); const app = await buildServer(ctx); @@ -976,4 +1014,60 @@ describe("P-14 GET / route index", () => { await app.close(); } }); +}); + +describe("SEC-10 a numeric trust-proxy hop count really takes effect", () => { + it("derives the client address from x-forwarded-for when one hop is trusted", async () => { + // Fastify's option parser ignores a numeric `trustProxy`, so a hop count has + // to be compiled into the function form. Before that, `trustProxy: 1` trusted + // nothing and every caller shared the socket address. + const ctx = createTestContext({ + config: { allowNoAuth: true, rateLimitRpm: 1, rateLimitBurst: 1, trustProxy: 1 }, + }); + const app = await buildServer(ctx); + try { + const call = (forwarded: string) => + app.inject({ + method: "GET", + url: "/v1/models", + headers: { "x-forwarded-for": forwarded }, + remoteAddress: "203.0.113.9", + }); + + expect((await call("1.1.1.1")).statusCode).toBe(200); + // The same forwarded address is the same bucket, even from another socket. + expect((await call("1.1.1.1")).statusCode).toBe(429); + // A different forwarded address is a different bucket, which proves the + // hop count reached Fastify instead of being dropped. + expect((await call("2.2.2.2")).statusCode).toBe(200); + } finally { + await app.close(); + } + }); +}); + +describe("SEC-15 pnpm setup writes an owner-only .env", () => { + // `mode` is ignored on Windows, where the concept does not apply; the script + // still has to succeed there. + it.skipIf(process.platform === "win32")("creates .env with mode 0600", () => { + const root = mkdtempSync(path.join(tmpdir(), "opencode-api-setup-")); + try { + mkdirSync(path.join(root, "scripts"), { recursive: true }); + cpSync(path.join(process.cwd(), "scripts", "init-env.mjs"), path.join(root, "scripts", "init-env.mjs")); + cpSync(path.join(process.cwd(), ".env.example"), path.join(root, ".env.example")); + + const result = spawnSync(process.execPath, [path.join(root, "scripts", "init-env.mjs"), "--random"], { + cwd: root, + stdio: "ignore", + }); + expect(result.status).toBe(0); + + const envPath = path.join(root, ".env"); + expect(statSync(envPath).mode & 0o777).toBe(0o600); + // A generated key replaced the published default. + expect(readFileSync(envPath, "utf8")).toMatch(/^OPENCODE_API_KEYS=(?!sk-dummy-123)\S+$/m); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); }); \ No newline at end of file diff --git a/test/sessions.test.ts b/test/sessions.test.ts index a112a2c..3db7b7f 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -2,7 +2,7 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; import { SessionStore, deriveKey, hashMessages, hashTools } from "../src/upstream/sessions.js"; @@ -418,6 +418,45 @@ describe("SessionStore", () => { expect(sessions.list().map((record) => record.sessionId)).not.toContain("ses_a"); }); + it("evicts the oldest session, not the one just committed, when timestamps differ", () => { + // With equal timestamps the stable sort happens to hand `pop()` the oldest + // record, which hid an inverted eviction order: the newest session was the + // one dropped. Distinct timestamps make the order explicit. + vi.useFakeTimers(); + try { + const sessions = store({ sessionMaxEntries: 2 }); + for (const [at, id] of [ + [1_000, "a"], + [2_000, "b"], + [3_000, "c"], + ] as const) { + vi.setSystemTime(at); + sessions.commit(`key-${id}`, `ses_${id}`, { ...BASE_INPUT, messages: [{ role: "user", text: id }] }); + } + + const ids = sessions.list().map((record) => record.sessionId); + expect(ids).toContain("ses_c"); + expect(ids).not.toContain("ses_a"); + sessions.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("keeps size() correct when a root drops its oldest candidates", () => { + // `MAX_CANDIDATES_PER_ROOT` trims the bucket inside `commit()`; those drops + // must decrement the same counter as every other removal, or `size()`, + // `clear()` and the eviction pre-check all work from an inflated number. + const sessions = store(); + for (const id of ["1", "2", "3", "4", "5", "6"]) { + sessions.commit("root", `ses_${id}`, { ...BASE_INPUT, messages: [{ role: "user", text: id }] }); + } + + expect(sessions.list()).toHaveLength(4); + expect(sessions.size()).toBe(4); + expect(sessions.clear()).toBe(4); + }); + it("calls the eviction hook", () => { const sessions = store(); const evicted: string[] = []; @@ -427,6 +466,116 @@ describe("SessionStore", () => { expect(evicted).toEqual(["ses_x"]); }); + it("keeps size() correct across commit, release, invalidate, sweep and clear", () => { + // `size()` is now a private counter, so every mutation path that adds or + // drops a record has to update it: a missed path makes the cache grow + // without ever reaching the eviction pre-check. + const sessions = store(); + const message = (text: string): InternalMessage[] => [{ role: "user", text }]; + + sessions.commit("k1", "ses_1", { ...BASE_INPUT, messages: message("one") }); + sessions.commit("k1", "ses_2", { ...BASE_INPUT, messages: message("two") }); + sessions.commit("k2", "ses_3", { ...BASE_INPUT, messages: message("three") }); + expect(sessions.size()).toBe(3); + + // release(keep = true) keeps the record. + sessions.release("k1", "ses_1"); + expect(sessions.size()).toBe(3); + + // release(keep = false) drops it (the failed-turn path). + sessions.release("k1", "ses_2", false); + expect(sessions.size()).toBe(2); + + sessions.invalidate("k2", "test"); + expect(sessions.size()).toBe(1); + + // A sweep that expires nothing must not change the counter either. + expect(sessions.sweep()).toBe(0); + expect(sessions.size()).toBe(1); + + sessions.clear(); + expect(sessions.size()).toBe(0); + }); + + it("keeps size() correct when sweep drops a subset of the candidates", () => { + const sessions = store({ sessionTtlMs: 10 }); + sessions.commit("k", "ses_old", { ...BASE_INPUT, messages: [{ role: "user", text: "old" }] }); + sessions.commit("k", "ses_new", { ...BASE_INPUT, messages: [{ role: "user", text: "new" }] }); + expect(sessions.size()).toBe(2); + + // Only one of the two candidates of the bucket is idle past the TTL, so the + // bucket survives with one record: the counter must follow the bucket rather + // than the whole key. + const older = sessions.list().find((record) => record.sessionId === "ses_old"); + if (!older) throw new Error("expected the old record to be cached"); + older.lastUsedAt = Date.now() - 60_000; + + expect(sessions.sweep()).toBe(1); + expect(sessions.size()).toBe(1); + expect(sessions.list().map((record) => record.sessionId)).toEqual(["ses_new"]); + }); + + it("counts the records restored from disk", () => { + const now = Date.now(); + const sessions = persistedStore({ + "k:ses_1": { + key: "k", + sessionId: "ses_1", + model: "opencode/big-pickle", + agent: "build", + permissionProfile: "default", + prefixHash: hashMessages([USER_1]), + deliveredCount: 1, + createdAt: now, + lastUsedAt: now, + busy: false, + reusedCount: 0, + }, + }); + + try { + expect(sessions.size()).toBe(1); + } finally { + sessions.stop(); + } + }); + + it("does not traverse the cache to answer size() or to pre-check eviction", () => { + const sessions = store({ sessionMaxEntries: 500 }); + sessions.commit("k", "ses_1", { ...BASE_INPUT, messages: [USER_1] }); + + const listSpy = vi.spyOn(sessions, "list"); + expect(sessions.size()).toBe(1); + expect(listSpy).not.toHaveBeenCalled(); + + // Under the cap, `commit()` must not flatten and sort the whole cache. + for (let index = 0; index < 400; index += 1) { + sessions.commit(`key-${index}`, `ses_${index}`, { + ...BASE_INPUT, + messages: [{ role: "user", text: `message ${index}` }], + }); + } + expect(listSpy).not.toHaveBeenCalled(); + listSpy.mockRestore(); + }); + + it("still evicts past the cap and calls the eviction hook once per dropped session", () => { + const sessions = store({ sessionMaxEntries: 3 }); + const evicted: string[] = []; + sessions.onEvict((sessionId) => evicted.push(sessionId)); + + for (const id of ["a", "b", "c", "d", "e"]) { + sessions.commit(`key-${id}`, `ses_${id}`, { + ...BASE_INPUT, + messages: [{ role: "user", text: id }], + }); + } + + expect(sessions.size()).toBe(3); + expect(evicted).toEqual(["ses_a", "ses_b"]); + expect(sessions.list().map((record) => record.sessionId)).not.toContain("ses_a"); + }); + it("can be disabled entirely", () => { const sessions = store({ sessionCacheEnabled: false }); const first = sessions.acquire({ ...BASE_INPUT, messages: [USER_1] }); @@ -500,6 +649,60 @@ describe("hashing helpers", () => { }); }); +describe("session persistence debounce", () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("saves once per window under a sustained burst instead of never", () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); + tempDirs.push(dataDir); + const config = testConfig({ sessionPersist: true, dataDir }); + const sessions = new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); + const target = path.join(dataDir, "sessions.json"); + + try { + // Every commit used to clear and restart the 1 s timer, so a burst that + // keeps mutating the cache meant the write never happened while traffic + // lasted: the whole cache then landed as one synchronous burst. + for (let index = 0; index < 100; index += 1) { + sessions.commit(`key-${index}`, `ses_${index}`, { + ...BASE_INPUT, + messages: [{ role: "user", text: `message ${index}` }], + }); + } + expect(fs.existsSync(target)).toBe(false); + + vi.advanceTimersByTime(1_000); + expect(fs.existsSync(target)).toBe(true); + + const written = JSON.parse(fs.readFileSync(target, "utf8")) as { records: Record }; + expect(Object.keys(written.records)).toHaveLength(100); + } finally { + sessions.stop(); + } + }); + + it("still persists synchronously on stop()", () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); + tempDirs.push(dataDir); + const config = testConfig({ sessionPersist: true, dataDir }); + const sessions = new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); + + sessions.commit("k", "ses_stop", { ...BASE_INPUT, messages: [USER_1] }); + sessions.stop(); + + const written = JSON.parse(fs.readFileSync(path.join(dataDir, "sessions.json"), "utf8")) as { + records: Record; + }; + expect(Object.keys(written.records)).toHaveLength(1); + }); +}); + describe("message serialisation", () => { afterEach(() => { vi.restoreAllMocks(); diff --git a/test/shutdown.test.ts b/test/shutdown.test.ts index 6f7b5d0..fc7fe66 100644 --- a/test/shutdown.test.ts +++ b/test/shutdown.test.ts @@ -7,6 +7,8 @@ */ import { describe, expect, it, vi } from "vitest"; import { DEFAULT_DRAIN_MS, shutdown, type ShutdownApp, type ShutdownDeps } from "../src/http/shutdown.js"; +import { buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; interface Stub { deps: ShutdownDeps; @@ -109,4 +111,22 @@ describe("shutdown", () => { it("keeps a 10 second default drain", () => { expect(DEFAULT_DRAIN_MS).toBe(10_000); }); + + it("resolves for an app that never called listen() and still stops the upstream", async () => { + const s = stub(); + // A signal handled between `buildServer()` and `app.listen()` (the cold-start + // window COR-10 covers) must still reach every stop hook instead of hanging + // on the drain. + const app = await buildServer(createTestContext()); + try { + await expect(shutdown(s.deps, app, 25)).resolves.toBeUndefined(); + + expect(s.events).toHaveBeenCalledTimes(1); + expect(s.sessions).toHaveBeenCalledTimes(1); + expectUpstreamHookCalledOnce(s); + } finally { + // Harmless if `shutdown()` already closed it. + await app.close().catch(() => undefined); + } + }); }); \ No newline at end of file diff --git a/test/startup.test.ts b/test/startup.test.ts new file mode 100644 index 0000000..30cc623 --- /dev/null +++ b/test/startup.test.ts @@ -0,0 +1,101 @@ +/** + * Startup validation notes. + * + * `defaultKeyExposureError()` is the fail-closed guard for the documented + * container quickstart (`HOST=0.0.0.0` plus the API key published in the + * repository); `src/index.ts` writes it to stderr and exits 1. + */ +import fs from "node:fs"; +import { describe, expect, it } from "vitest"; +import { DEFAULT_API_KEY } from "../src/config.js"; +import { + defaultApiKeyNote, + defaultKeyExposureError, + isLoopbackHost, + privateMediaUrlWarning, +} from "../src/startup.js"; + +/** Base configuration for the guard: default key, auth required, exposed host. */ +const EXPOSED = { host: "0.0.0.0", usingDefaultApiKey: true, allowNoAuth: false }; + +describe("defaultKeyExposureError", () => { + it("refuses the exposed host with the published default key", () => { + const message = defaultKeyExposureError(EXPOSED); + + expect(message).toBeDefined(); + expect(message).toContain("OPENCODE_API_KEYS"); + expect(message).toContain(DEFAULT_API_KEY); + expect(message).toContain("HOST=0.0.0.0"); + }); + + it("allows a loopback bind with the default key", () => { + for (const host of ["127.0.0.1", "127.5.5.5", "::1", "localhost", "::ffff:127.0.0.1", "[::1]"]) { + expect(defaultKeyExposureError({ ...EXPOSED, host })).toBeUndefined(); + } + }); + + it("allows an exposed bind with a real key", () => { + expect(defaultKeyExposureError({ ...EXPOSED, usingDefaultApiKey: false })).toBeUndefined(); + }); + + it("allows an exposed bind when authentication is disabled on purpose", () => { + expect(defaultKeyExposureError({ ...EXPOSED, allowNoAuth: true })).toBeUndefined(); + }); + + it("does not refuse a hostname it cannot classify as network-reachable by accident", () => { + // A DNS name is not loopback, so the guard applies. + expect(defaultKeyExposureError({ ...EXPOSED, host: "gateway.example.com" })).toBeDefined(); + }); +}); + +describe("isLoopbackHost", () => { + it("accepts the whole 127.0.0.0/8 block and the literal names only", () => { + expect(isLoopbackHost("127.0.0.1")).toBe(true); + expect(isLoopbackHost("127.255.255.254")).toBe(true); + expect(isLoopbackHost(" LOCALHOST ")).toBe(true); + expect(isLoopbackHost("0.0.0.0")).toBe(false); + expect(isLoopbackHost("192.168.1.10")).toBe(false); + expect(isLoopbackHost("127.0.0.1.evil.example")).toBe(false); + }); +}); + +describe("existing notes stay unchanged in shape", () => { + it("still names the key in the informative note", () => { + expect(defaultApiKeyNote("/srv/app")).toContain(DEFAULT_API_KEY); + }); + + it("still warns only for a non-loopback host with private media URLs", () => { + expect(privateMediaUrlWarning({ host: "127.0.0.1", allowPrivateMediaUrls: true })).toBeUndefined(); + expect(privateMediaUrlWarning({ host: "0.0.0.0", allowPrivateMediaUrls: false })).toBeUndefined(); + expect(privateMediaUrlWarning({ host: "0.0.0.0", allowPrivateMediaUrls: true })).toContain("SSRF"); + }); +}); + +describe("entry point ordering (COR-10)", () => { + it("registers the shutdown signals, including SIGHUP, before the upstream warm-up", () => { + // The entry point cannot be driven in a unit test without starting a real + // listener, so the ordering contract is pinned against its source: a signal + // received during the warm-up must reach the handlers (the warm-up spawns + // the child, and nothing else reclaims its internal port). + const source = fs.readFileSync(new URL("../src/index.ts", import.meta.url), "utf8"); + const registered = source.indexOf('"SIGINT", "SIGTERM", "SIGHUP"'); + const warmUp = source.indexOf("events.start()"); + + expect(registered).toBeGreaterThan(-1); + expect(warmUp).toBeGreaterThan(-1); + expect(registered).toBeLessThan(warmUp); + }); + + it("refuses to start before the informational default-key note", () => { + const source = fs.readFileSync(new URL("../src/index.ts", import.meta.url), "utf8"); + const refusal = source.indexOf("defaultKeyExposureError(config)"); + const listen = source.indexOf("await app.listen("); + + expect(refusal).toBeGreaterThan(-1); + expect(refusal).toBeLessThan(listen); + // The refusal must print to stderr before exiting. + const exit = source.indexOf("process.exit(1);", refusal); + expect(exit).toBeGreaterThan(refusal); + expect(source.slice(refusal, exit)).toContain("process.stderr.write"); + }); +}); diff --git a/test/tools.test.ts b/test/tools.test.ts index a6018c7..2cca8ec 100644 --- a/test/tools.test.ts +++ b/test/tools.test.ts @@ -96,6 +96,42 @@ describe("tool bridge instructions", () => { expect(createToolBridge([WEATHER], "required").active).toBe(true); expect(createToolBridge([WEATHER], { name: "get_weather" }).active).toBe(true); }); + + it("ignores an envelope naming a tool the request never declared", () => { + const bridge = createToolBridge([WEATHER], "auto"); + const text = `${TOOL_CALL_OPEN}{"name":"exfiltrate","arguments":{"cmd":"rm -rf /"}}${TOOL_CALL_CLOSE}`; + const parsed = bridge.parse(text); + + expect(parsed.calls).toEqual([]); + // The body stays visible instead of being silently dropped or reported as a + // call for a function that does not exist. + expect(parsed.text).toContain('"name":"exfiltrate"'); + + const declared = bridge.parse(envelope({ name: "get_weather", arguments: { city: "Hanoi" } })); + expect(declared.calls.map((call) => call.name)).toEqual(["get_weather"]); + }); + + it("hands the declared names to the streaming filter too", () => { + // The orchestrator parses the streamed answer through `createFilter()`, so + // the allow-list has to cover that path and not only `parse()`. + const bridge = createToolBridge([WEATHER], "auto"); + const filter = bridge.createFilter(); + let text = ""; + for (const char of envelope({ name: "exfiltrate", arguments: { cmd: "rm -rf /" } })) text += filter.push(char); + const tail = filter.finish(); + + expect(tail.calls).toEqual([]); + expect(text + tail.text).toContain('"name":"exfiltrate"'); + + const declared = bridge.createFilter(); + let declaredText = ""; + for (const char of envelope({ name: "get_weather", arguments: { city: "Hanoi" } })) { + declaredText += declared.push(char); + } + const declaredTail = declared.finish(); + expect(declaredText + declaredTail.text).toBe(""); + expect(declaredTail.calls.map((call) => call.name)).toEqual(["get_weather"]); + }); }); describe("parseToolCallBody", () => { @@ -218,6 +254,38 @@ describe("parseToolCallBody", () => { expect(parseToolCallBody(body)).toEqual([]); expect(performance.now() - startedAt).toBeLessThan(250); }); + + it("rejects a call whose name the request never declared", () => { + // A hallucinated name — or an envelope injected through untrusted content — + // used to reach the client as a real `tool_calls` block for a function that + // does not exist, and the orchestrator then forced `finish_reason`. + expect(parseToolCallBody('{"name":"exfiltrate","arguments":{"cmd":"rm -rf /"}}', ["get_weather"])).toEqual([]); + expect(parseToolCallBody('{"name":"get_weather","arguments":{"city":"Hanoi"}}', ["get_weather"])[0]?.name).toBe( + "get_weather", + ); + // Without a declared-name set the exported API keeps accepting any name. + expect(parseToolCallBody('{"name":"exfiltrate","arguments":{}}')).toHaveLength(1); + }); + + it("repairs a trailing comma across a long whitespace run", () => { + // The scan used `/\s/.test(...)` per skipped character, which allocated a + // fresh `RegExp` for each one; the shared `isFenceSpace` predicate covers the + // same JSON whitespace and costs no allocation. + const whitespace = " \t\r\n".repeat(10_000); + const calls = parseToolCallBody(`{"name":"a","arguments":{"x":1},${whitespace}}`); + expect(calls).toHaveLength(1); + expect(calls[0]?.arguments).toBe('{"x":1}'); + }); + + it("scans a trailing-comma whitespace run once", () => { + const whitespace = " ".repeat(64 * 1024); + const body = `{"name":"a","arguments":{"x":1},${whitespace}}`; + expect(parseToolCallBody(body)).toHaveLength(1); + + const startedAt = performance.now(); + expect(parseToolCallBody(body)).toHaveLength(1); + expect(performance.now() - startedAt).toBeLessThan(250); + }); }); describe("normaliseArguments", () => { @@ -335,6 +403,37 @@ describe("ToolCallFilter", () => { expect(tail.calls).toEqual([]); }); + it("keeps an envelope naming an undeclared tool visible as text", () => { + const filter = new ToolCallFilter(["get_weather"]); + let text = ""; + for (const char of envelope({ name: "exfiltrate", arguments: { cmd: "rm -rf /" } })) { + text += filter.push(char); + } + const tail = filter.finish(); + + expect(tail.calls).toEqual([]); + expect(text + tail.text).toContain('"name":"exfiltrate"'); + }); + + it("still extracts a declared name through a named filter", () => { + const filter = new ToolCallFilter(["get_weather"]); + let text = ""; + for (const char of envelope({ name: "get_weather", arguments: { city: "Hanoi" } })) { + text += filter.push(char); + } + const tail = filter.finish(); + + expect(text + tail.text).toBe(""); + expect(tail.calls.map((call) => call.name)).toEqual(["get_weather"]); + }); + + it("applies the declared-name allow-list to parseAssistantText", () => { + const parsed = parseAssistantText(envelope({ name: "exfiltrate", arguments: {} }), ["get_weather"]); + expect(parsed.calls).toEqual([]); + expect(parsed.text).toContain("exfiltrate"); + expect(parseAssistantText(envelope({ name: "get_weather", arguments: {} }), ["get_weather"]).calls).toHaveLength(1); + }); + it("preserves comma-bracket text in a streamed envelope", () => { const filter = new ToolCallFilter(); const payload = `${TOOL_CALL_OPEN}{"name":"echo","arguments":{"text":"a,}",}}${TOOL_CALL_CLOSE}`; diff --git a/test/upstream-reconnect.test.ts b/test/upstream-reconnect.test.ts index cc98b91..7abdd85 100644 --- a/test/upstream-reconnect.test.ts +++ b/test/upstream-reconnect.test.ts @@ -13,7 +13,7 @@ import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; import type { OpencodeEvent } from "../src/types/opencode.js"; import type { OpencodeClient } from "../src/upstream/client.js"; -import { collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; +import { collectCompletion, runCompletion, MAX_QUEUED_EVENTS, type CompletionDeps } from "../src/upstream/completion.js"; import type { EventHub, EventListener } from "../src/upstream/events.js"; import { ModelRegistry } from "../src/upstream/models.js"; import { SessionStore } from "../src/upstream/sessions.js"; @@ -181,6 +181,100 @@ describe("runCompletion after an event-stream reconnect", () => { expect(harnessed.interruptCalls).toEqual([SESSION_ID]); }); + it("fails the turn with event_stream_lost when the queued frame budget overflows", async () => { + // The queue between the shared hub and one completion is bounded: a consumer + // parked on a client that stopped reading must not let the hub grow the heap + // at the upstream frame rate. Reaching the cap drops a frame, which is the + // same kind of hole a reconnect leaves, so the turn fails loudly. + const harnessed = harness( + () => [event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" })], + { upstreamRequestTimeoutMs: 30_000, upstreamFirstTokenTimeoutMs: 30_000 }, + ); + + const received: CompletionEvent[] = []; + const iterator = runCompletion(request(), harnessed.deps); + const first = await iterator.next(); + expect(first.done).toBe(false); + if (first.done === true) throw new Error("expected a start event"); + received.push(first.value); + + // Park the consumer on the 1 s wait, then push past the cap while it cannot + // dequeue: the first `MAX_QUEUED_EVENTS` frames are queued, the next one is + // rejected and flips the overflow flag. + const parked = iterator.next(); + for (let index = 0; index <= MAX_QUEUED_EVENTS; index += 1) { + harnessed.emit(event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "x" })); + } + + const next = await parked; + expect(next.done).toBe(false); + if (next.done === true) throw new Error("expected an error event"); + received.push(next.value); + + const failure = received.at(-1); + if (failure?.kind !== "error") throw new Error("expected an error event"); + expect(failure.error.code).toBe("event_stream_lost"); + expect(failure.error.status).toBe(503); + expect(harnessed.interruptCalls).toEqual([SESSION_ID]); + + // The abort path must drop the sticky slot, exactly like a real gap. + await iterator.return(undefined); + expect(harnessed.sessions.list()).toHaveLength(0); + }); + + it("drains a burst below the queue cap in order without failing the turn", async () => { + // The queue is drained with a read cursor instead of `shift()`, and the cap + // must leave a legitimate burst untouched: a healthy turn queued behind one + // slow frame still completes with every delta in order. + const harnessed = harness( + () => [event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" })], + { upstreamRequestTimeoutMs: 30_000, upstreamFirstTokenTimeoutMs: 30_000 }, + ); + + const iterator = runCompletion(request(), harnessed.deps); + const first = await iterator.next(); + if (first.done === true) throw new Error("expected a start event"); + + // Park the consumer on its 1 s wait, then queue a burst well below the cap + // while it cannot dequeue. The parked wait itself consumes the scripted + // frame, so the queue holds exactly `burst` frames when it resumes. + const parked = iterator.next(); + const burst = MAX_QUEUED_EVENTS / 2; + for (let index = 0; index < burst; index += 1) { + harnessed.emit(event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "x" })); + } + const resumed = await parked; + if (resumed.done === true) throw new Error("expected a queued event"); + expect(resumed.value.kind).toBe("text_delta"); + + // Drain the queued burst; the first frame is the one the parked wait took. + let drained = 1; + let failure: CompletionEvent | undefined; + while (drained < burst) { + const step = await iterator.next(); + if (step.done === true) break; + if (step.value.kind === "error") failure = step.value; + if (step.value.kind === "text_delta") drained += 1; + } + expect(failure).toBeUndefined(); + expect(drained).toBe(burst); + + // Terminate the turn cleanly: a bounded queue must not fail a burst that + // stayed under the cap, and the terminal event must still arrive. The + // generator only removes its queue waiter once a `next()` call resolves, so + // the terminal frame is emitted from a timer after the wait is registered. + let terminal: CompletionEvent | undefined; + while (terminal === undefined) { + const pending = iterator.next(); + setTimeout(() => harnessed.emit(event("session.execution.succeeded", { assistantMessageID: "msg_a1" })), 20); + const step = await pending; + if (step.done === true) break; + if (step.value.kind === "end" || step.value.kind === "error") terminal = step.value; + } + expect(terminal?.kind).toBe("end"); + await iterator.return(undefined); + }); + it("reports the same gap as a generic timeout when the reconnect is not observed", async () => { // Pre-fix behaviour, pinned as a contrast: before `execute()` subscribed to // `onReconnect`, the gap was invisible, so the turn waited out the request