diff --git a/.env.example b/.env.example index 8c2de16..7a6ca6e 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,19 @@ # --------------------------------------------------------------------------- # Server # --------------------------------------------------------------------------- -# Bind address and HTTP port. -HOST=0.0.0.0 +# Bind address and HTTP port. The template binds to loopback only: set +# HOST=0.0.0.0 to reach the dashboard from other machines, but only behind a +# reverse proxy with TLS and a changed dashboard password. +HOST=127.0.0.1 PORT=20125 # Pino log level: trace | debug | info | warn | error | fatal. LOG_LEVEL=info # Maximum request body in bytes (base64 media payloads need room). BODY_LIMIT=134217728 +# Only read by src/server.ts (not by src/config.ts): set it to "production" from +# the runner/process manager when serving a built release. When unset the server +# keeps development behaviour (pretty logs). +# NODE_ENV=production # --------------------------------------------------------------------------- # Storage @@ -18,7 +24,9 @@ DATA_DIR=./data # --------------------------------------------------------------------------- # Security # --------------------------------------------------------------------------- -# Only used when the dashboard password hash is first created. +# Only used when the dashboard password hash is first created. The built-in +# default is 123456: replace it immediately after the first login +# (Settings -> Security), or set this before the database is created. # DASHBOARD_PASSWORD=123456 # HMAC secret for dashboard session cookies. When empty, a secret is generated # once and stored in /.secret. When set, the environment value wins on diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 4702fc5..83c3550 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,8 +12,11 @@ ## Verification +- [ ] `pnpm verify` — the CI-mirroring gate (typecheck → unit tests → docs drift → build → e2e) - [ ] `pnpm typecheck` - [ ] `pnpm test` +- [ ] `pnpm check:docs` (env vars, routes, settings **and** `.env.example`/documented defaults) +- [ ] `pnpm check:env-example` - [ ] `pnpm build` - [ ] `pnpm test:e2e` - [ ] Manual check against a real provider (`pnpm test:live`) — or N/A @@ -23,5 +26,7 @@ - [ ] Commit messages and the PR title follow [Conventional Commits](../CONTRIBUTING.md#commit-message-convention) - [ ] No secrets, API keys, database files or `.env` files are included - [ ] `docs/SPEC.md` updated when the gateway/admin contract changed +- [ ] `.env.example` updated for any new environment variable (checked by `pnpm check:docs`) - [ ] Streaming pass-through fidelity preserved (no body reshaping beyond documented `x_opencode` stripping) - [ ] Dashboard changes keep dark/light parity +- [ ] Enforcement scripts were not weakened (`check:docs`, commit linter, e2e single-log-row assertions) \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e2334f1..3580c95 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,13 +42,12 @@ jobs: BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} run: | - # A brand-new branch can push with an all-zero "before" sha; fall back to the - # default range instead of failing the range check. - if [ "$BASE_SHA" = "0000000000000000000000000000000000000000" ]; then - BASE_SHA="" - fi - if [ -z "$BASE_SHA" ] || [ -z "$HEAD_SHA" ]; then - node scripts/check-commit-messages.mjs + # A brand-new branch can push with an all-zero "before" sha. Linting the + # default range then may check nothing while reporting success, so the fallback + # lints the pushed commit explicitly (and fails if it cannot be read). + if [ -z "$BASE_SHA" ] || [ "$BASE_SHA" = "0000000000000000000000000000000000000000" ]; then + echo "no usable base sha; linting the pushed commit ${HEAD_SHA} via --single" + node scripts/check-commit-messages.mjs --single "$HEAD_SHA" else node scripts/check-commit-messages.mjs "$BASE_SHA" "$HEAD_SHA" "${PR_TITLE:-}" fi @@ -82,9 +81,21 @@ jobs: run: pnpm test - name: Documentation drift - # Fails while SPEC.md/API.md and the code disagree (env vars, routes, settings). + # Fails while SPEC.md/API.md and the code disagree (env vars, routes, settings) + # and while .env.example / documented defaults disagree with src/config.ts. run: pnpm check:docs + - name: Env template parity + run: pnpm check:env-example + + - name: Negative self-tests (the enforcement scripts must still fail on bad input) + # Each self-test builds throw-away fixtures and exits non-zero when a bad case is + # wrongly accepted, so a silently disabled check cannot pass CI. + run: | + pnpm exec tsx scripts/check-docs.ts --self-test + pnpm exec tsx scripts/check-env-example.ts --self-test + node scripts/check-commit-messages.mjs --self-test + build-and-e2e: name: Build & e2e runs-on: ubuntu-latest @@ -113,7 +124,10 @@ jobs: # The e2e suite boots src/index.ts through tsx; this proves dist/ actually runs. run: | DATA_DIR="$(mktemp -d)" + # Keep the smoke test off the checkout and the developer/runner data dir. + WEB_DIST_DIR="$PWD/web/dist" PORT=20198 HOST=127.0.0.1 LOG_LEVEL=warn NODE_ENV=production \ + DATA_DIR="$DATA_DIR" WEB_DIST_DIR="$WEB_DIST_DIR" \ node dist/src/index.js > "$RUNNER_TEMP/smoke.log" 2>&1 & SERVER_PID=$! READY=0 diff --git a/AGENTS.md b/AGENTS.md index d780ca8..34fe179 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,9 +40,12 @@ React 19 + Tailwind CSS 4. Default port **20125**. pnpm install # install dependencies (Node 22+, pnpm 10+; see .nvmrc) pnpm dev # API with watch (port 20125, serves web/dist) pnpm dev:web # dashboard dev server (proxies /admin and /v1) +pnpm verify # one local gate mirroring CI (typecheck → test → check:docs → build → test:e2e) +pnpm verify --fast # same gate without build + test:e2e (pre-commit loop) pnpm typecheck # server + web + tests/scripts type checks (tsconfig.test.json) pnpm test # vitest unit suite -pnpm check:docs # doc-drift check: env vars, routes, settings vs docs/SPEC.md + docs/API.md +pnpm check:docs # doc-drift check: env vars, routes, settings vs docs/SPEC.md + docs/API.md + .env.example +pnpm check:env-example # .env.example ↔ src/config.ts parity + documented-default comparison pnpm test:e2e # full acceptance: real server + deterministic mock upstreams pnpm test:live # smoke test against a real provider (skips on upstream 429) pnpm build # tsc -> dist/ and vite -> web/dist/ @@ -50,13 +53,53 @@ pnpm start # run the compiled server (node dist/src/index.js) pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check; fails (not SKIP) without Chrome ``` -Script env knobs: `E2E_PORT`/`E2E_MOCK_A_PORT`/`E2E_MOCK_B_PORT` (e2e, defaults 20197/20196/20195), -`MOCK_PORT`/`MOCK_NAME`/`MOCK_KEY` (mock upstream), `LIVE_PORT`/`LIVE_UPSTREAM`/`LIVE_KEY`/`LIVE_MODEL`/ -`LIVE_VISION_MODEL` (live check), `CHROME_PATH` (screenshots). `pnpm lint:commits` runs the commit-message -linter against `origin/main..HEAD`. +Negative self-tests (they build throw-away fixtures and must reject every bad case; CI runs +them in the `Lint & test` job): -Before opening a PR run at least: -`pnpm typecheck && pnpm test && pnpm check:docs && pnpm build && pnpm test:e2e`. +```bash +pnpm self-test:docs # check-docs + check-env-example fixtures +pnpm self-test:commits # commit-linter fixtures +pnpm exec tsx scripts/check-docs.ts --self-test +pnpm exec tsx scripts/check-env-example.ts --self-test +node scripts/check-commit-messages.mjs --self-test +``` + +Commit linting locally: + +```bash +pnpm lint:commits # origin/main..HEAD +node scripts/check-commit-messages.mjs "" +node scripts/check-commit-messages.mjs --single # lint exactly one commit +node scripts/check-commit-messages.mjs --self-test +``` + +### Script env knobs + +Every knob read by a script (this list is complete; defaults in parentheses): + +| Script | Knob | Meaning | +| --- | --- | --- | +| `scripts/e2e.ts` | `E2E_PORT` (20197) | Gateway port of the main harness | +| `scripts/e2e.ts` | `E2E_MOCK_A_PORT` (20196) | Mock upstream A port | +| `scripts/e2e.ts` | `E2E_MOCK_B_PORT` (20195) | Mock upstream B port | +| `scripts/e2e.ts` | `E2E_ALT_PORT` | Fixed port for the auxiliary SSRF/brute-force server (default: a free ephemeral port) | +| `scripts/mock-upstream.ts` | `MOCK_PORT` (20196) | Mock upstream port (`pnpm mock`) | +| `scripts/mock-upstream.ts` | `MOCK_NAME` (`mock`) | Provider/model name the mock advertises | +| `scripts/mock-upstream.ts` | `MOCK_KEY` (`sk-dummy-123`) | API key the mock expects | +| `scripts/live-check.ts` | `LIVE_PORT` (20194) | Router port for the live check | +| `scripts/live-check.ts` | `LIVE_UPSTREAM` (fallback `E2E_UPSTREAM`, default `http://127.0.0.1:20123/v1`) | Real provider base URL | +| `scripts/live-check.ts` | `LIVE_KEY` (fallback `E2E_UPSTREAM_KEY`, default `sk-dummy-123`) | Real provider API key | +| `scripts/live-check.ts` | `LIVE_MODEL` (`opencode/flint-40b-free`) | Chat/responses model under test | +| `scripts/live-check.ts` | `LIVE_VISION_MODEL` (`opencode/hy4-flash-free`) | Vision model under test | +| `scripts/screenshots.ts` | `CHROME_PATH` | Chrome/Chromium binary (default: the macOS Chrome path) | + +`scripts/screenshots.ts` flags: `--out ` (`./tmp/screenshots`), `--port ` (20193), +`--mockPort ` (20192), `--cdpPort ` (9333), `--strict` (fail instead of skipping when +Chrome is unusable). No CI job runs this harness — it needs a browser and is explicitly +deferred (see `README.md` → Verification). + +Before opening a PR run `pnpm verify` (or at least +`pnpm typecheck && pnpm test && pnpm check:docs && pnpm build && pnpm test:e2e`). ## Layout @@ -70,7 +113,7 @@ Before opening a PR run at least: | `src/gateway/` | `/v1/*` auth, rotation, pass-through proxy, `/v1/models` | | `src/admin/` | `/admin/api/*` (auth, providers, models, keys, logs, settings), scheduler | | `web/` | React 19 + Tailwind dashboard (Vite root, builds to `web/dist`) | -| `scripts/` | e2e, live check, mock upstream, commit-message linter, doc-drift checker, screenshots | +| `scripts/` | e2e, live check, mock upstream, commit-message linter, doc-drift + `.env.example` checkers, `verify.ts` gate, screenshots | | `tests/` | vitest unit tests (incl. `tooling.test.ts` for the repo scripts) | | `docs/` | `SPEC.md` (contract), `API.md` (gateway reference), screenshots | | `.github/workflows/` | CI | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fca8253..bda11b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -95,10 +95,13 @@ because tooling generates them. The linter fails when an explicitly supplied bas commits (an empty check must not pass), and CI lints pushes to `main` in addition to pull requests. Squash merges use the PR title, which is why the title must follow the same format. -Optional local helper: +Optional local helpers: ```bash +pnpm lint:commits # origin/main..HEAD node scripts/check-commit-messages.mjs origin/main HEAD "feat(gateway): my change" +node scripts/check-commit-messages.mjs --single "$(git rev-parse HEAD)" # lint one commit +node scripts/check-commit-messages.mjs --self-test # prove the rules still reject bad input ``` ## Pull request flow @@ -109,14 +112,21 @@ pull request that passes the required checks. 1. Branch from `main` using a descriptive name, e.g. `feat/provider-rotation`, `fix/dashboard-session`, `docs/api-reference`. 2. Make focused commits (the linter checks each one; keep history clean). -3. Run the full verification locally: +3. Run the full verification locally — `pnpm verify` runs exactly these stages in order + and stops at the first failure (`pnpm verify --fast` skips `build` + `test:e2e`): ```bash + pnpm verify + # equivalent one-by-one: pnpm typecheck pnpm test - pnpm check:docs + pnpm check:docs # also checks .env.example and the documented defaults + pnpm check:env-example pnpm build pnpm test:e2e ``` + The enforcement scripts have negative self-tests (`pnpm self-test:docs`, + `pnpm self-test:commits`, or the `--self-test` flags); they must exit 0 and must exit + non-zero when a fixture is deliberately broken. CI runs them in `Lint & test`. 4. Push the branch and open a PR: ```bash git push -u origin feat/provider-rotation @@ -131,6 +141,9 @@ pull request that passes the required checks. A PR that changes the gateway contract, the database schema or the admin API must also update `docs/SPEC.md` and call the change out in the PR description. New env vars, routes or `DEFAULT_SETTINGS` keys must be documented or `pnpm check:docs` fails — fix the docs, never the checker. +That check also compares `.env.example` with the env vars read under `src/**` and the defaults +documented in `docs/SPEC.md` with the code defaults, so a new variable needs an `.env.example` +entry as well. ## Reporting bugs / requesting features diff --git a/README.md b/README.md index d8ec1a0..9d2a448 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,9 @@ pnpm start # http://127.0.0.1:20125 # development pnpm dev # API with watch mode (port 20125) pnpm dev:web # dashboard dev server (proxies /admin and /v1) + +# before opening a pull request +pnpm verify # typecheck → unit tests → docs drift → build → e2e ``` Open → you are redirected to the dashboard login. Default password **`123456`** @@ -92,8 +95,12 @@ enabled provider, one enabled model *and* one API key exist (the dashboard shows | `PROVIDER_ALLOW_PRIVATE_HOSTS` | `false` | Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard off) | | `WEB_DIST_DIR` | `/web/dist` | Directory served as the dashboard build | | `PUBLIC_URL` | unset | Optional absolute public base URL of this deployment | +| `NODE_ENV` | unset | Read by `src/server.ts`: `production` selects the production server behaviour (set by the runner, not by `config.ts`) | -[.env.example](.env.example) is the same list as a copy-paste template. +[.env.example](.env.example) is the same list as a copy-paste template. It binds to +`127.0.0.1` by default — set `HOST=0.0.0.0` only behind a reverse proxy with TLS and after +changing the dashboard password. `pnpm check:docs` fails when the template and +`src/config.ts` disagree, or when a documented default contradicts the code. Runtime settings (rotation strategy, retry budget, provider cooldown, request timeout, SSE idle timeout, auto model sync interval, log retention, audit retention, …) live in **Dashboard → Settings**. @@ -177,29 +184,55 @@ scripts/e2e.ts full end-to-end acceptance run ## Verification ```bash +pnpm verify # one local gate mirroring CI (typecheck → test → check:docs → build → test:e2e) +pnpm verify --fast # same gate without build + test:e2e (pre-commit loop) pnpm typecheck # server + dashboard + tests/scripts type checks pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization, tooling) -pnpm check:docs # doc-drift checker (env vars, routes, settings vs docs/SPEC.md + docs/API.md) +pnpm check:docs # doc drift: env vars, routes, settings, .env.example and documented defaults +pnpm check:env-example # .env.example ↔ src/config.ts parity only pnpm test:e2e # boots a real server + mock providers; full acceptance suite pnpm test:live # smoke-tests a real provider (skips when it answers 429) pnpm build # dist/ + web/dist/ +pnpm self-test:docs # negative self-tests for the docs/env checkers +pnpm self-test:commits # negative self-tests for the commit-message linter pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check + PNG screenshots ``` +`pnpm verify` stops at the first failing stage, prints a per-stage timing line and exits non-zero; CI runs the +same commands as separate steps (`Lint & test`, `Build & e2e`). + +The enforcement scripts ship negative self-tests: `--self-test` builds throw-away fixture trees/commits and +requires every known bad input (undocumented env var/route/setting, missing route, bad `.env.example` entry, +contradicting documented default, bad commit type, uppercase description, trailing period, missing +`BREAKING CHANGE:` footer, empty range, unknown `--single` sha) to be rejected. CI runs them, so a silently +disabled check cannot pass. + +### Scripts reference + +| Command | Purpose | Env knobs / flags | +| --- | --- | --- | +| `pnpm dev` / `pnpm start` | Run the server from source / from `dist/` | `HOST`, `PORT`, `DATA_DIR`, `LOG_LEVEL`, `WEB_DIST_DIR` | +| `pnpm mock` | Standalone mock upstream | `MOCK_PORT` (20196), `MOCK_NAME` (`mock`), `MOCK_KEY` (`sk-dummy-123`) | +| `pnpm test:e2e` | Full acceptance run | `E2E_PORT` (20197), `E2E_MOCK_A_PORT` (20196), `E2E_MOCK_B_PORT` (20195), `E2E_ALT_PORT` (free port) | +| `pnpm test:live` | Smoke test a real provider | `LIVE_PORT` (20194), `LIVE_UPSTREAM`/`E2E_UPSTREAM`, `LIVE_KEY`/`E2E_UPSTREAM_KEY`, `LIVE_MODEL`, `LIVE_VISION_MODEL` | +| `pnpm exec tsx scripts/screenshots.ts` | Chrome/CDP UI check + screenshots | `CHROME_PATH`; `--out ` (`./tmp/screenshots`), `--port ` (20193), `--mockPort ` (20192), `--cdpPort ` (9333), `--strict` | +| `pnpm check:docs` / `pnpm check:env-example` | Documentation and env-template drift | `--self-test` | +| `pnpm lint:commits` | Conventional Commits check | ` ""`, `--single `, `--self-test` | + `pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams (OpenAI + Anthropic surfaces, streaming, tools, vision, reasoning, injectable 429/5xx/delays) and verifies routing, rotation, failover, timeouts, byte fidelity, logging (exactly one row per request), auth, cookie flags, the brute-force guard, admin APIs and the built dashboard shell. It fails fast when a fixed port is occupied or a child exits before -`/health`; the ports are overridable with `E2E_PORT`, `E2E_MOCK_A_PORT` and `E2E_MOCK_B_PORT`. +`/health`. Its SSE lifecycle checks wait for the endpoint's deterministic initial frame instead of sleeping. -`pnpm test:live` talks to a real provider (`LIVE_UPSTREAM`, default `http://127.0.0.1:20123/v1`, plus -`LIVE_KEY`, `LIVE_MODEL`, `LIVE_VISION_MODEL`, `LIVE_PORT`); when the provider answers `429` the affected -probe is reported as **SKIP** instead of failing (decided from the upstream status, never from error text). +`pnpm test:live` talks to a real provider; when the provider answers `429` the affected probe is reported as +**SKIP** instead of failing (decided from the upstream status, never from error text). `scripts/screenshots.ts` seeds demo data, drives headless Chrome over CDP, asserts each dashboard page renders its expected content and writes screenshots to `tmp/screenshots/`. It needs a Chrome/Chromium binary -(`CHROME_PATH`, defaulting to the macOS Chrome path); without one the script prints `SKIP` and exits 0, so -CI-invoked runs use `--strict`, which fails instead of skipping. CI does not run the UI check. +(`CHROME_PATH`, defaulting to the macOS Chrome path) that is a real executable and answers `--version` as a +browser; without one the script prints `SKIP` and exits 0, so local CI-style runs use `--strict`, which fails +instead of skipping. **No CI job runs the UI check** — a browser job is explicitly deferred. ## Contributing @@ -208,9 +241,12 @@ documented in [CONTRIBUTING.md](CONTRIBUTING.md). `main` is protected: open a pu wait for the required checks (`Commit messages`, `Lint & test`, `Build & e2e`) before merging. ```bash +pnpm verify # the full CI-mirroring gate pnpm lint:commits # validate your branch's commits locally -pnpm check:docs # env vars / routes / settings vs docs/SPEC.md + docs/API.md +pnpm check:docs # env vars / routes / settings / .env.example vs the docs +pnpm self-test:docs # prove the documentation checkers still fail on bad input node scripts/check-commit-messages.mjs origin/main HEAD "feat(gateway): example" +node scripts/check-commit-messages.mjs --single "$(git rev-parse HEAD)" ``` Agents and automated contributors should read [AGENTS.md](AGENTS.md) first. diff --git a/docs/API.md b/docs/API.md index bae4c51..39b2d6b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -41,32 +41,39 @@ for chat/responses, Anthropic style `{"type":"error","error":{"type","message"}} | 400 | `model_required` | request body has no `model` | | 404 | `model_not_found` | model missing/disabled in the registry | | 404 | `unknown_endpoint` | authenticated request to an unknown `/v1/*` path | +| 405 | `method_not_allowed` | known `/v1/*` path called with an unsupported method (carries `Allow`) | +| 413 | `payload_too_large` | request body exceeds `BODY_LIMIT` | | 503 | `no_provider_configured` | no enabled provider | | 503 | `no_models_configured` | model registry empty | | 429 | `all_providers_rate_limited` | every attempt hit a rate limit (carries `Retry-After`) | | 502 | `all_providers_failed` | every attempt failed (network/5xx) | | 502 | `upstream_body_failed` | a `2xx` upstream body could not be read (truncated/RST) | | 502 | `upstream_frame_too_large` | an unterminated SSE frame exceeded the 1 MiB cap | +| 502 | `upstream_response_too_large` | a buffered response exceeded `upstream_response_max_bytes` | +| 502 | `invalid_provider_credentials` | the stored provider key cannot be encoded as an HTTP header value | | 504 | `upstream_timeout` | every candidate timed out (aggregated after exhaustion) | -The router retries the next provider for `408`, `409`, `425`, `429`, `5xx` and network/timeout errors, up to -the configured retry budget (Dashboard → Settings → Routing). A timed-out attempt is logged, cools its -provider down and fails over like any other retryable failure; the `504 upstream_timeout` is only returned -after all candidates are exhausted. Client errors (`400/401/403/404/422`) are returned immediately without -burning other providers. +The router retries the next provider for `408`, `409`, `425`, `429`, every `5xx` (incl. `529`) and +network/timeout errors, up to the configured retry budget (Dashboard → Settings → Routing). A timed-out +attempt is logged, cools its provider down and fails over like any other retryable failure; the +`504 upstream_timeout` is only returned after all candidates are exhausted. Client errors +(`400/401/403/404/422`) are returned immediately without burning other providers. Unknown `/v1/*` paths (and bare `/v1`) require a valid gateway key, are logged as one `request_logs` row and -answer `404` with code `unknown_endpoint` in the surface-appropriate error envelope. +answer `404` with code `unknown_endpoint` in the surface-appropriate error envelope. A known path called with +an unsupported method answers `405` with an `Allow` header listing the supported methods (also one log row). ## Upstream requests Request bodies are forwarded byte-for-byte from the raw client bytes (invalid UTF-8 included); a JSON body is only re-serialized when reasoning normalization, model-id trimming or the `stream_options.include_usage` -injection actually changed it. Provider credentials (`Authorization`, `x-api-key`), `host`, `content-length` -and `connection` always come from the router, while the client's `anthropic-beta`, `anthropic-version`, -`anthropic-dangerous-direct-browser-access`, `openai-beta`, `x-stainless-*`, `accept` and trace headers are -forwarded through an allowlist. `anthropic-version: 2023-06-01` is only defaulted for the -messages/count_tokens surfaces, and a streaming request without an `accept` header is forwarded as +injection actually changed it. The client's raw query string is forwarded unchanged (`?beta=true` stays on +the upstream request), and a provider `baseUrl` that already carries a query string keeps it. Provider +credentials (`Authorization`, `x-api-key`), `host`, `content-length` and `connection` always come from the +router, while the client's `anthropic-beta`, `anthropic-version`, `anthropic-dangerous-direct-browser-access`, +`openai-beta`, `openai-organization`, `openai-project`, `http-referer`, `x-title`, `x-stainless-*`, `accept` +and trace headers are forwarded through an allowlist. `anthropic-version: 2023-06-01` is only defaulted for +the messages/count_tokens surfaces, and a streaming request without an `accept` header is forwarded as `text/event-stream`. Upstream redirects are refused (`redirect: 'manual'`): a `3xx` response is a fatal upstream error instead of being followed with the provider key. @@ -183,10 +190,14 @@ request (successes and rejections alike). All three surfaces stream as `text/event-stream` when `stream: true` is set. Bytes are forwarded as they arrive from the upstream provider (`Cache-Control: no-cache`, `X-Accel-Buffering: no`). Frames are decoded only to extract token usage and to strip provider-internal `x_opencode` metadata, so invalid UTF-8 and a -leading BOM reach the client unchanged. +leading BOM reach the client unchanged. Every blank-line frame boundary is recognized (`\n\n`, `\r\n\r\n`, +`\r\n\n`, `\n\r\n`, `\r\r`), and a frame with several `data:` lines is decoded as one payload so multi-line +`x_opencode` objects are stripped too. `request_timeout_ms` (Dashboard → Settings → Routing) is a total deadline that covers the streamed body, and `stream_idle_timeout_ms` (default 120000, min 1000) cuts off an upstream that goes silent between frames/reads. An unterminated SSE frame is capped at 1 MiB: the upstream is aborted and the request fails with `502 upstream_frame_too_large`. Client aborts terminate the upstream request and are logged with -`client_aborted` (status 499). +`client_aborted` (status 499). A retryable upstream `retry-after` (delta seconds or HTTP-date) is honoured, +capped at one hour, and the provider cooldown becomes `max(provider_cooldown_ms, retryAfter)`; an existing +longer cooldown is never shortened by a later failure. diff --git a/docs/SPEC.md b/docs/SPEC.md index f8c0c0d..502232c 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -4,18 +4,14 @@ Multi-provider LLM gateway. Node.js + Fastify + TypeScript + pnpm. Default port Serves OpenAI-compatible (`/v1/chat/completions`, `/v1/responses`), Anthropic-compatible (`/v1/messages`) and a premium glassmorphism dashboard with mandatory login (default password `123456`). -## 0. Ownership (do not write outside your scope) +## 0. Frozen contracts -| Scope | Owner | Paths | -| --- | --- | --- | -| Core (frozen, already written) | lead | `src/config.ts`, `src/types.ts`, `src/db/**`, `src/util/**`, `src/core/**`, `src/server.ts`, `src/index.ts`, `package.json`, `tsconfig.json`, `pnpm-workspace.yaml` | -| Gateway | gateway-dev | `src/gateway/**` | -| Admin API | admin-dev | `src/admin/**` | -| Dashboard | web-dev | `web/**` | -| Tests / e2e | lead + verifier | `tests/**`, `scripts/**` | - -Everyone may **read** anything. Do not modify files outside your scope. If core needs a change, -message `lead` instead of editing. +`src/types.ts`, `src/db/schema.ts`, `src/db/repos.ts`, `src/core/*`, `src/util/*`, `src/server.ts` +and `src/index.ts` are the shared contract between the DB layer, the gateway and the admin API. +Changing them requires updating this file in the same PR, re-running the full verification suite +(`pnpm verify`) and calling the change out in the PR description. See `AGENTS.md` for the golden +rules (pass-through fidelity, one log row per client request, secrets never leave the server, +mandatory auth) and `CONTRIBUTING.md` for the workflow. ## 1. Core contract you build on @@ -42,14 +38,30 @@ incActiveRequests(); decActiveRequests(); getActiveRequests(); `audit/listAudit/deleteAuditBefore/tableCounts/transaction`. `upsertModel(input, known?)` accepts the already-loaded row (provider sync is not N+1); `transaction(fn)` runs `fn` inside one SQLite transaction and is re-entrant (nested calls join it). +`deleteLogsBefore(ts)` and `clearLogs()` delete `request_logs` and `request_attempts` inside one transaction +and return the `request_logs` row count. `statsOverview` computes p50/p95 from one ordered pass over the +window's non-null latencies (one windowed statement per call). `Repo.recordProviderFailure` never shortens an +active cooldown. + +`src/db/schema.ts` is applied idempotently on every boot (via `openDatabase`) and sets +`PRAGMA journal_mode = WAL`, `PRAGMA foreign_keys = ON` and `PRAGMA busy_timeout = 5000`, so a second connection +(dashboard, script or a second server on one data dir) waits for the write lock instead of surfacing +`SQLITE_BUSY` as `500 internal_error`. `openDatabase` additionally stamps `PRAGMA user_version` with +`SCHEMA_VERSION` (currently `1`, exported from the schema module and bumped on every migration) only when it +differs, so the boot script stays lock-free for an already-initialized file while +`/admin/api/diagnostics` can report a data file written by a different build. Settings keys with defaults: `dashboard_password_hash`, `rotation_strategy` (`round-robin`), `max_retries` (`3`), `provider_cooldown_ms` (`60000`), `request_timeout_ms` (`600000`), `auto_sync_models` (`true`), `model_sync_interval_ms` (`300000`), `log_retention_days` (`30`), `audit_retention_days` (`90`), `model_allow_unknown` (`false`), `upstream_user_agent` (`opencode-router/1.0`), -`stream_idle_timeout_ms` (`120000`). +`stream_idle_timeout_ms` (`120000`), `upstream_response_max_bytes` (`0`). -Environment variables (`src/config.ts`): +`upstream_response_max_bytes` caps a buffered (non-streaming) upstream response body: `0` means unlimited +(the default) and any other value must be `1024`…`1073741824`. A larger body aborts the request with +`502 upstream_response_too_large`. Streaming responses are never buffered and are unaffected. + +Environment variables (`src/config.ts` unless noted): | Env | Default | Meaning | | --- | --- | --- | @@ -65,6 +77,10 @@ Environment variables (`src/config.ts`): | `PUBLIC_URL` | unset | Absolute public base URL; an `https://` value also forces `Secure` session cookies | | `TRUST_PROXY` | `false` | Trust `X-Forwarded-*` for `request.ip`, `client_ip` logging and the `Secure` cookie decision | | `PROVIDER_ALLOW_PRIVATE_HOSTS` | `false` | Allow provider test/**sync** to reach loopback/link-local/private hosts (SSRF guard off) | +| `NODE_ENV` | `development` | Read by `src/server.ts`: `production` disables the pretty logger and keeps JSON logs | + +Booting with the shipped default dashboard password (`123456`) logs a one-line warning; it never blocks +startup. Set `DASHBOARD_PASSWORD` before the first run, or change it in Settings → Security. Helpers: `src/util/crypto.ts` (`hashPassword`, `verifyPassword`, `hmacSign`, `generateApiKey`, `uuid`, `randomHex`, `sha256Hex`, `safeEqual`), `src/util/errors.ts` (`ApiError`, `errorTypeForStatus`, `isRetryableStatus`, `upstreamErrorFrom`), @@ -129,25 +145,37 @@ No enabled provider, or zero enabled models → `503` `api_error` code `no_provi forwarded body. 6. Select provider order (§2.2) and attempt the upstream call as a **pass-through to the same surface**: `POST {provider.baseUrl}/chat/completions` / `/responses` / `/messages` / `/messages/count_tokens` - with the provider's API key in both `Authorization: Bearer` and `x-api-key`. The body is forwarded + with the provider's API key in both `Authorization: Bearer` and `x-api-key`. The client's raw query + string is forwarded unchanged (`POST /v1/messages?beta=true` reaches the upstream with `?beta=true`), + and a provider `baseUrl` that already carries a query string keeps it. The body is forwarded byte-for-byte (raw bytes captured with `parseAs: 'buffer'`, so invalid UTF-8 survives) whenever step 5 changed nothing, else as the normalized JSON. Client headers pass through an allowlist (`anthropic-beta`, `anthropic-version`, `anthropic-dangerous-direct-browser-access`, `openai-beta`, - `x-stainless-*`, `accept`, trace headers); auth/host/content-length/connection always come from the + `openai-organization`, `openai-project`, `http-referer`, `x-title`, `x-stainless-*`, `accept`, + `accept-language`, trace headers); auth/host/content-length/connection always come from the router. `anthropic-version: 2023-06-01` is only defaulted for the `messages`/`count_tokens` surfaces; a streaming request with no/wildcard `accept` is forwarded as `text/event-stream`. 7. Never follow upstream redirects (`redirect: 'manual'`): any `3xx` is a fatal upstream error (`502 upstream_redirect`, single attempt, provider cooled down, the provider key is never replayed). 8. Retry with the next provider when the attempt fails with a retryable status (`isRetryableStatus`: `408`, - `409`, `425`, `429`, `5xx`, `529`) or a network/timeout `ApiError`, up to `max_retries` attempts total. + `409`, `425`, `429`, every `5xx` including `529`) or a network/timeout `ApiError`, up to `max_retries` + attempts total. A timed-out provider is logged as a real attempt, put into cooldown and failed over like any other retryable failure; the aggregated `504 upstream_timeout` is only returned after every candidate is - exhausted, and the log row/attempts are attributed to the provider that timed out. + exhausted, and the log row/attempts are attributed to the provider that timed out. Any terminal + failure reached after at least one real upstream call is attributed to the last attempted provider + (`provider_id`/`provider_name` in the log row plus the `x-opencode-router-*` headers below); only + pre-attempt rejections carry the request id alone. 9. Log the request (§2.6) exactly once per client request — `GET /v1/models*` included — and log every attempt via `insertAttempt` (timed-out attempts included). 10. A `2xx` upstream whose body cannot be read (truncated/RST) is reported as `502 upstream_body_failed` (the upstream status is kept when it is already ≥ 400; a timeout stays `504 upstream_timeout`). - A streaming body that exceeds the unterminated-frame cap aborts with `502 upstream_frame_too_large`. + A streaming body that exceeds the unterminated-frame cap aborts with `502 upstream_frame_too_large`; + a buffered body that exceeds `upstream_response_max_bytes` aborts with `502 upstream_response_too_large`. +11. A request that exceeds `BODY_LIMIT` is rejected with `413`, code `payload_too_large` (the Fastify + internal `FST_ERR_*` code is never exposed). +12. A known `/v1/*` path called with an unsupported method answers `405` with an `Allow` header listing the + supported methods; unknown paths keep `404 unknown_endpoint`. Both write exactly one `request_logs` row. Strip provider-internal top-level `x_opencode` keys from JSON responses (non-stream body, and each SSE `data:` JSON payload when it parses). Everything else must be forwarded byte-for-byte, including @@ -155,9 +183,14 @@ tool calls, images/files/audio/video content parts and Anthropic `thinking` bloc Response headers: `x-opencode-router-request-id` on every `/v1/*` response; on proxied/failed-attempt responses also `x-opencode-router-provider: `, `x-opencode-router-name: ` and -`x-opencode-router-attempts: `. Errors raised before an attempt (auth, routing, validation) carry the -request id only. Provider ids/names are sanitized before they reach a header, and a provider id/name/baseUrl -or `upstream_user_agent` containing control characters is rejected at the admin API (`400`). +`x-opencode-router-attempts: `. Every terminal proxied failure (`all_providers_failed`, +`all_providers_rate_limited`, `upstream_timeout`, `upstream_response_too_large`, +`invalid_provider_credentials`) keeps all three headers, attributed to the last attempted provider; +errors raised before an attempt (auth, routing, validation) carry the request id only. Provider ids/names +are sanitized before they reach a header, and a provider id/name/baseUrl or `upstream_user_agent` containing +control characters is rejected at the admin API (`400`). A provider key that cannot be encoded as an HTTP +header value fails the attempt with `502 invalid_provider_credentials`, and the key never appears in the +message. Upstream response headers relayed to the client: `retry-after`, `request-id`, `x-request-id`, `openai-processing-ms`, `openai-version`, `anthropic-version`, `x-ratelimit-*`, `anthropic-ratelimit-*` @@ -182,6 +215,10 @@ never forwarded. `429 all_providers_rate_limited` carries `Retry-After` (whole s - On retryable failure (incl. `409`): `recordProviderFailure(id, status, message, cooldownMs)` + `events.emitProvider`. A cooldown is recorded for a network failure (no status), `408`/`409`/`425`, `429`, `503`, `529`, any other `5xx`, and any `3xx`; the provider `status` column stays `cooldown` only for `429`/`503`/`529`/`5xx`. + The stored `cooldown_until` is **monotonic**: a later failure with a shorter cooldown never lowers an + active longer one, so a `Retry-After` back-off cannot be cut short by a subsequent quick failure. +- An upstream `retry-after` (delta seconds or HTTP-date) is capped at one hour, so a hostile or broken + upstream cannot pin a provider in cooldown indefinitely. - A timed-out attempt is recorded (log row + `request_attempts`), cools the provider down and fails over, exactly like any other retryable failure. - On non-retryable failure (400/401/403/404/422): stop immediately and return the upstream error @@ -189,7 +226,9 @@ never forwarded. `429 all_providers_rate_limited` carries `Retry-After` (whole s - All attempts exhausted → response status of the last attempt (or `502` for network errors), code `all_providers_failed`; if every failure was 429 use `429` + code `all_providers_rate_limited` (with `Retry-After`); if every failure was a timeout use `504` + code `upstream_timeout`. -- Increment/decrement `incActiveRequests()/decActiveRequests()` around the whole request. +- Increment/decrement `incActiveRequests()/decActiveRequests()` once around the whole client request, for + every gateway route (`GET /v1/models*` and pre-attempt rejections included), so the dashboard's + active-request counter matches the requests actually in flight. ### 2.3 Reasoning effort normalization - chat: `body.reasoning_effort` @@ -218,7 +257,9 @@ Disabled models are omitted; empty DB → `{"object":"list","data":[]}`. Forward SSE frames as they arrive (flush per frame, `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`). Forward the original bytes: a frame is decoded only to detect `x_opencode` / parse usage and re-encoded only when it is actually -rewritten, so invalid UTF-8 and a leading BOM reach the client unchanged. `request_timeout_ms` is a real +rewritten, so invalid UTF-8 and a leading BOM reach the client unchanged. Every blank-line frame boundary is +recognized (`\n\n`, `\r\n\r\n`, `\r\n\n`, `\n\r\n`, `\r\r`), and a frame with several `data:` lines is decoded as +one payload so a multi-line `x_opencode` object is stripped too. `request_timeout_ms` is a real total deadline that covers the streamed body; `stream_idle_timeout_ms` (default `120000`, min `1000`) is the idle gap between reads/`drain` waits, so a stalled upstream cannot hang the request. An unterminated SSE frame is capped at 1 MiB: on breach the upstream is aborted, the log row gets `upstream_frame_too_large` @@ -232,7 +273,10 @@ Record `ttfb_ms` (time to first byte) on the log row. Handle client aborts witho (destroy the upstream body, log with `ok=false`, code `client_aborted`, status `499`). An idle gap or the total deadline aborts the upstream: `504` + code `upstream_timeout` while the response is still unsent, or a `504` status on the already-flushed stream. Retryable failures honour an upstream `retry-after` header -(delta seconds or HTTP-date): the cooldown becomes `max(provider_cooldown_ms, retryAfter)`. +(delta seconds or HTTP-date): the cooldown becomes `max(provider_cooldown_ms, retryAfter)` with +`retryAfter` clamped to one hour (`MAX_RETRY_AFTER_MS`). With a non-zero `upstream_response_max_bytes`, a +buffered non-streaming body over the cap aborts with `502 upstream_response_too_large`; `0` is unlimited and +streaming is never buffered. ### 2.6 Logging One `request_logs` row per client request — `GET /v1/models` and `GET /v1/models/:id` included, logged with @@ -242,8 +286,11 @@ the OpenAI (`chat`) surface — with: `error_code`, `error_message`, `latency_ms`, `ttfb_ms`, token fields, `attempts`, `client_ip`, `user_agent`. Emit `ctx.events.emitRequestStart(...)` right after auth and `ctx.events.emitRequestEnd({log})` at the end. Event emission is guarded: a throwing dashboard/SSE listener is logged as a warning and can never fail the -request. Upstream error messages redact URL userinfo and query strings, so provider credentials never reach -`request_logs.error_message`, `providers.last_error` or a client-visible error body. +request. Upstream error messages redact URL userinfo and query strings, are stripped of control characters, +clamped to 500 characters and additionally scrubbed of the provider credential and any `Bearer …`/`sk-…`/ +`x-api-key`-shaped token, so provider credentials never reach `request_logs.error_message`, +`providers.last_error` or a client-visible error body. An upstream error `type` that is not a known +gateway error type is recorded as `api_error`. ## 3. Admin API (`src/admin/**`, prefix `/admin/api`) @@ -259,10 +306,17 @@ request. Upstream error messages redact URL userinfo and query strings, so provi `/login` and `/settings/password` accept at most 4096 bytes (`413` above it) and reject passwords longer than 200 characters with `400`. - Every other `/admin/api/*` route requires a valid session → else `401 {error:{message,code:'unauthorized'}}`. + Session-authenticated mutating requests (`POST`/`PUT`/`PATCH`/`DELETE`) are additionally CSRF-guarded: a + present `Origin` header whose host differs from the request host (or from the `PUBLIC_URL` host when that is + configured), or `Sec-Fetch-Site: cross-site`, is rejected with `403 cross_site_request` before any state + change. Requests without those headers (CLI, the e2e suite, same-origin navigation) are unaffected, and the + public `POST /admin/api/login` is never gated by this check. - `POST /admin/api/login {password}`: verify with `verifyDashboardPassword` (src/core/seed.ts); - brute-force guard: max 10 failed attempts per IP and 50 failed attempts per process per 5 minutes → + brute-force guard: max 10 failed attempts per IP and 500 failed attempts per process per 5 minutes → `429` with `Retry-After` (seconds) and `{error:{code:'too_many_attempts',retryAfter}}`; on success create - session, `repo.audit(...)`, return `{ok:true, expiresAt}`. + session, `repo.audit(...)`, return `{ok:true, expiresAt}`. The per-IP limit is the primary defence; the + higher process-wide limit only bounds a distributed attack, so a single attacker cannot lock the operator + out of the dashboard cheaply. - `POST /admin/api/logout` clears the cookie + deletes the session row. - `GET /admin/api/session` → `{authenticated, expiresAt?, version:'1.0.0', uptimeMs, startedAt}` (never 401). - `HttpError` messages are returned to the client as-is, including `5xx`; only unexpected errors are masked @@ -274,25 +328,43 @@ request. Upstream error messages redact URL userinfo and query strings, so provi - `GET /admin/api/stats?window=1h|6h|24h|7d|30d` → `Repo.statsOverview(...)` output (including exact `requestsLast60s`/`errorsLast60s` counts and `activeRequests`) plus `{health:{status,activeRequests,providers:[{id,name,status,enabled,cooldownUntil,lastLatencyMs,successCount,failureCount,lastError,lastCheckedAt}], modelsEnabled, keysActive}, window}`. + `activeRequests` is snapshotted once per request, so the (possibly cached) aggregate body and + `health.activeRequests` always agree within one response. - `GET /admin/api/events` (SSE) → emits `request:start`, `request:end`, `provider:update`, plus a `stats` heartbeat every 5s with `{activeRequests, requestsLast60s, errorsLast60s}`. Writes apply per-client backpressure (bounded queue + `drain` resume; the stream is ended after repeated stalls). The session row is re-validated on every heartbeat and the stream is closed when the session disappears or expires; at most 32 concurrent streams are allowed, above that the endpoint answers `503 too_many_streams`. `GET /admin/api/stats` is served from a short (~2s) TTL cache. -- `GET /admin/api/activity?limit=20` → merged recent log rows + provider state changes. +- `GET /admin/api/activity?limit=20` → merged recent log rows + provider state changes. `limit` is validated + like the logs route (`1..500`; a non-integer or out-of-range value is `400 invalid_request`). +- `GET /admin/api/diagnostics` → self-check report: + `{scheduler:{running,lastSyncAt,lastSyncError,nextSyncInMs,lastRecoveryAt}, + storage:{dbPath,walSizeBytes,dbSizeBytes,busyTimeoutMs,logRows,attemptRows,sessionRows,oldestLogTs}, + checks:[{id,status:'ok'|'warn'|'fail',detail}]}`. Check ids: `password.default` (warn while the shipped + default password is in use), `providers.enabled`, `keys.active`, `models.enabled`, `version.schema` + (`PRAGMA user_version` vs `SCHEMA_VERSION` **and** the presence of every expected table), `clock.skew` (newest log/audit timestamp more than 60 s in + the future) and `providers.cooldown`. `scheduler.nextSyncInMs` is `null` when the scheduler is stopped or + `auto_sync_models=false`. Session-protected like every other `/admin/api/*` route. Every read it performs is + guarded, so a database missing a table still yields a report (with `version.schema` = `warn`) instead of a + `500` — that is the situation the endpoint exists to diagnose. **Providers** - `GET /admin/api/providers` → `{providers:[{id,name,baseUrl,apiKeyMasked,hasApiKey,enabled,priority,status,cooldownUntil,lastError,lastCheckedAt,lastLatencyMs,successCount,failureCount,createdAt,updatedAt}]}` (never return the raw key). `apiKeyMasked` reveals at most 4 characters and is `****` for keys shorter than 12 characters. - `POST /admin/api/providers {id?, name, baseUrl, apiKey, enabled?, priority?}` → `{provider}` (validate: name and baseUrl required, baseUrl must start with http:// or https://, apiKey required; `id`/`name`/`baseUrl` reject control characters, `baseUrl` rejects userinfo). + `apiKey` must additionally be a non-empty printable ASCII string (`0x20`–`0x7E`) of at most 4096 characters (control + characters, NUL/CR/LF and other byte ranges that would make an HTTP header value invalid are rejected with + `400 invalid_request`, without echoing the submitted value). - `PATCH /admin/api/providers/:id {name?, baseUrl?, apiKey?, enabled?, priority?}` → `{provider}`. Changing `baseUrl`, `apiKey` or `enabled` resets `status='unknown'` and `cooldownUntil=null`. - `DELETE /admin/api/providers/:id` → `{ok:true, modelsRemoved}` — the provider's synced models are removed - in the same transaction. + and a `models_sync_provider_id` pointing at it is cleared, all in the same transaction. - `POST /admin/api/providers/:id/test` → `{ok, status, latencyMs, models:number, error:null|string}` (GET `{baseUrl}/models`). A failed test updates the provider's status/failure counters/`lastError` and emits `provider:update`, - exactly like a gateway failure. + exactly like a gateway failure. The detailed upstream error text kept for the server log is scrubbed of + the provider credential (A-05 policy), so a provider echoing the request cannot leak its key into a log + line, `providers.last_error` or a client-visible body. - `POST /admin/api/providers/test {baseUrl, apiKey?, id?}` → same shape, before saving. When `apiKey` is omitted and `id` names a stored provider, the stored key is reused **only** when the draft `baseUrl` origin equals the stored provider's origin (otherwise `400 api_key_required`); `404` for an unknown `id`, `400` @@ -308,13 +380,25 @@ request. Upstream error messages redact URL userinfo and query strings, so provi - `DELETE /admin/api/models/:id` → `{ok:true}`. - `POST /admin/api/models/bulk {action:'enable'|'disable'|'delete', ids:[...]}` → `{updated}`; `ids` is capped at 1000 entries (`400` above) and the action is applied as one set-based statement inside a transaction. -- `POST /admin/api/models/sync {providerId?}` → same shape as provider sync; uses the given provider or - the first enabled one; `400` when no provider exists. +- `POST /admin/api/models/sync {providerId?}` → per-provider result `{added, updated, removed, total, + providerId, syncedAt}` plus an additive + `providers:[{providerId,providerName,ok,added,updated,removed,total,latencyMs,error,warning}]` + listing every provider that was synced. Without `providerId` **every enabled provider** is synced (one + transaction per provider, so one failure does not abort the others) and the top-level counters are the + sum; with `providerId` only that provider is synced. `400` when no provider exists. Sync semantics: upsert every model reported upstream with `source='sync'`, `providerId`, and delete rows with `source='sync'` from that provider that no longer exist upstream. Manual rows are never deleted. A `source='sync'` row already owned by a *different* provider is neither re-attributed nor deleted by this - provider's sync (only its owner's sync garbage-collects it). Record `models_synced_at` + - `models_sync_provider_id` in settings. + provider's sync (only its owner's sync garbage-collects it). A `2xx` response whose body does not contain a + recognizable model array (for example `{}` or an HTML error page) is treated as a **skipped** sync: no row is + deleted and `models_synced_at` is not advanced, and the result carries + `warning: 'Upstream returned no recognizable model list; the synced catalog was left unchanged'` + (also `providers[].warning`); hard failures such as a network error or a non-2xx status keep + `providers[].error`. An explicit + empty array (`{"data":[]}`) is a legitimate empty catalog and prunes. A successful per-provider round-trip + refreshes that provider's health counters (`recordProviderSuccess`) and emits `provider:update`, exactly + like the single-provider branch; a skipped (unrecognized) catalog does neither. Record `models_synced_at` + + `models_sync_provider_id` in settings for the single-provider case. **API keys** - `GET /admin/api/keys` → `{keys:[{id,name,prefix,suffix,enabled,requestCount,lastUsedAt,createdAt,revokedAt}]}`. @@ -327,7 +411,12 @@ request. Upstream error messages redact URL userinfo and query strings, so provi **Logs** - `GET /admin/api/logs?limit&offset&surface&model&providerId&keyId&ok&stream&search&since&until` → - `{logs:[...], total, limit, offset}`. + `{logs:[...], total, limit, offset}`. `model` is a case-insensitive **contains** match (the dashboard labels + it "Model contains"); `%` and `_` in the value are matched literally. `search` is a substring scan over + `model`/`key_name`/`provider_name`/`error_message`; a term longer than 200 characters is rejected with + `400 invalid_request` at the route (the repository layer additionally truncates as defence in depth). + `since`/`until` accept epoch milliseconds or an ISO date and must be finite and in range + (`400 invalid_request` otherwise). - `GET /admin/api/logs/:id` → `{log, attempts:[...]}` (`404` when missing). - `DELETE /admin/api/logs` → `{ok:true, removed}`; `POST /admin/api/logs/prune {days}` → `{removed}`. - `GET /admin/api/logs/export?format=json|csv` → file download of the current filter. Exports are capped at @@ -341,7 +430,8 @@ request. Upstream error messages redact URL userinfo and query strings, so provi first and valid ones are applied in one transaction, so one bad value changes nothing. Unknown keys — inherited object properties such as `constructor` included — are reported as `ignored`; `log_store_bodies` no longer exists and is also reported as `ignored`. Ranges include - `audit_retention_days` 1..3650 and `stream_idle_timeout_ms` 1000..3600000; `upstream_user_agent` rejects + `audit_retention_days` 1..3650, `stream_idle_timeout_ms` 1000..3600000 and + `upstream_response_max_bytes` exactly `0` or 1024..1073741824; `upstream_user_agent` rejects control characters. - `POST /admin/api/settings/password {currentPassword, newPassword}` → `{ok:true}` (`400` wrong current, `400` when shorter than 4 chars); invalidates all other sessions. @@ -354,15 +444,18 @@ request. Upstream error messages redact URL userinfo and query strings, so provi new secret, persist it to `/.secret` **before** swapping the in-memory `ctx.db.secret`, then invalidate all dashboard sessions and return the new secret so the operator can store it (response carries `cache-control: no-store`). Gateway key hashes are sha256 of the plaintext, so existing keys keep working. -- `GET /admin/api/audit?limit=100` → `{items:[...]}`. +- `GET /admin/api/audit?limit=100` → `{items:[...]}` (`limit` range `1..500`, validated like the logs route). - Audit every mutating admin action with `repo.audit(actor, action, target, detail)`: the actor is `session:` on session-protected routes (or `dashboard` on public routes) and the client IP is recorded in the detail. Audit rows are pruned by `audit_retention_days`, not by `log_retention_days`. ### Scheduler (`src/admin/scheduler.ts`) `startScheduler(ctx)` returns a stop function. It: -- every `model_sync_interval_ms` (min 30s) syncs models when `auto_sync_models=true` and an enabled provider exists; -- probes providers whose cooldown is active and clears the cooldown when the probe succeeds; +- every `model_sync_interval_ms` (min 30s) syncs models when `auto_sync_models=true` and an enabled provider exists + (all enabled providers, see §3 Models); +- probes providers whose cooldown is active and clears the cooldown when the probe succeeds; at most 3 probes + run per tick and an in-memory cursor (reset on process restart) rotates through the cooling-down set, so providers beyond the first + three are not starved. Probes go through the same SSRF guard as the admin test/sync routes; - purges expired sessions every 10 minutes; - never throws out of the interval callback (log warnings instead); - does not start timers that keep the process alive (`unref()`). @@ -440,9 +533,15 @@ server-side session gate first. failover, non-retryable 400 single-attempt, timeout 504, retry-after, single-log-row assertions with a settle window, revoked/disabled keys, cookie attributes, brute-force 429, admin endpoints and the built dashboard shell. -- Tooling checks: `pnpm check:docs` diffs the env vars read by `src/config.ts`, the registered routes and - the `DEFAULT_SETTINGS` keys against this file and `docs/API.md` (exits 1 on drift); - `node scripts/check-commit-messages.mjs []` lints Conventional Commits and - fails on an explicitly supplied but empty range; `pnpm exec tsx scripts/screenshots.ts --strict` - runs the headless-Chrome UI check and fails instead of skipping when Chrome is missing - (`CHROME_PATH` overrides the binary). +- Tooling checks: `pnpm check:docs` diffs every env var read anywhere under `src/**`, the registered routes + and the `DEFAULT_SETTINGS` keys against this file and `docs/API.md`, compares `.env.example` with the + config vars in both directions and checks the documented env defaults against the code defaults + (exits 1 on drift). `pnpm check:docs --self-test` and `node scripts/check-commit-messages.mjs --self-test` + prove the gates still reject deliberately broken fixtures, and **negative results are a failure**: if a + checker stops reporting a real problem, the self-test fails rather than passing. + `node scripts/check-commit-messages.mjs []` lints Conventional Commits, supports + `--single ` for a one-commit range and fails on an explicitly supplied but empty range; + `pnpm exec tsx scripts/screenshots.ts --strict` runs the headless-Chrome UI check and fails instead of + skipping when Chrome is missing (`CHROME_PATH` overrides the binary). +- `pnpm verify` runs `typecheck`, `test`, `check:docs`, `build` and `test:e2e` in order, stopping at the + first failure (`--fast` skips `build` and `test:e2e`); it is the single local gate that mirrors CI. diff --git a/package.json b/package.json index fe10cbc..602542f 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,10 @@ "test:live": "tsx scripts/live-check.ts", "mock": "tsx scripts/mock-upstream.ts", "check:docs": "tsx scripts/check-docs.ts", + "check:env-example": "tsx scripts/check-env-example.ts", + "self-test:docs": "tsx scripts/check-docs.ts --self-test && tsx scripts/check-env-example.ts --self-test", + "self-test:commits": "node scripts/check-commit-messages.mjs --self-test", + "verify": "tsx scripts/verify.ts", "lint:commits": "node scripts/check-commit-messages.mjs" }, "dependencies": { diff --git a/scripts/check-commit-messages.mjs b/scripts/check-commit-messages.mjs index 73f3f58..f8d7301 100644 --- a/scripts/check-commit-messages.mjs +++ b/scripts/check-commit-messages.mjs @@ -1,9 +1,12 @@ #!/usr/bin/env node +/// /** * Conventional Commits linter used by CI (`.github/workflows/ci.yml`). * * Usage: * node scripts/check-commit-messages.mjs [] [] [] + * node scripts/check-commit-messages.mjs --single + * node scripts/check-commit-messages.mjs --self-test * * Defaults: `origin/main..HEAD` for the range, no PR-title check. * Exits non-zero and prints every offending message when validation fails. @@ -14,10 +17,16 @@ * - the lowercase rule is Unicode-aware: the description must start with a lowercase * letter (`\p{Ll}`), so `feat: Ädd`, `feat: 修正` and `feat: ✨ sparkle` all fail; * - an explicitly supplied base+head range that contains zero commits fails instead of - * silently passing a check that validated nothing. + * silently passing a check that validated nothing; + * - `--single ` lints exactly that one commit and fails when the sha cannot be + * resolved, so CI's all-zero `before` fallback can never lint an empty range; + * - `--self-test` builds throw-away repositories and requires every known bad message + * to be rejected, so the rules above cannot be silently disabled. */ import { execFileSync } from 'node:child_process'; -import { resolve } from 'node:path'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; export const ALLOWED_TYPES = [ @@ -49,10 +58,58 @@ const IGNORED_PREFIXES = ['Revert "', 'fixup!', 'squash!', 'amend!', 'Initial co /** Description must begin with a lowercase letter, in any script (Unicode-aware). */ const LOWERCASE_LETTER = /^\p{Ll}$/u; +/** + * Git identity for the throw-away repositories built by `--self-test`: a runner without + * a global `user.name`/`user.email` would otherwise fail to create a commit. + */ +const FIXTURE_ENV = { + GIT_AUTHOR_NAME: 'opencode-router self-test', + GIT_AUTHOR_EMAIL: 'self-test@localhost', + GIT_COMMITTER_NAME: 'opencode-router self-test', + GIT_COMMITTER_EMAIL: 'self-test@localhost', +}; + +/** Repository the linter reads from; only `--self-test` points it somewhere else. */ +let repoCwd = process.cwd(); + +/** + * Runs git and returns its trimmed stdout. + * @param {string[]} args + * @returns {string} + */ export function git(args) { - return execFileSync('git', args, { encoding: 'utf8' }).trim(); + try { + return execFileSync('git', args, { + encoding: 'utf8', + cwd: repoCwd, + env: { ...process.env, ...FIXTURE_ENV }, + stdio: ['ignore', 'pipe', 'pipe'], + }).trim(); + } catch (error) { + // Surface git's own message without the "Command failed:" wrapper and its usage dump. + const stderr = error instanceof Error && 'stderr' in error ? String(error.stderr).trim() : ''; + const message = stderr.split('\n').find((line) => line.startsWith('fatal:') || line.startsWith('error:')) ?? stderr; + throw new Error(message.length > 0 ? message : error instanceof Error ? error.message : String(error)); + } +} + +/** + * Sets the directory `git` runs in (used by the self-test fixtures). + * @param {string} cwd + * @returns {void} + */ +export function setRepoCwd(cwd) { + repoCwd = cwd; } +/** + * @typedef {{ sha: string, subject: string, body: string }} CommitRecord + */ + +/** + * @param {string} range + * @returns {CommitRecord[]} + */ function readCommits(range) { const fieldSeparator = '\u001f'; const recordSeparator = '\u001e'; @@ -72,17 +129,66 @@ function readCommits(range) { .map((record) => { const [sha, subject, ...bodyParts] = record.split(fieldSeparator); return { - sha, + sha: sha ?? '', subject: (subject ?? '').trim(), body: bodyParts.join(fieldSeparator), }; }); } +/** + * Resolves one sha to its exact object and reports its parent count. + * + * `git rev-list --parents -n1 ` never rewrites the revision, so it cannot + * silently substitute an ancestor the way `git log -1 --no-merges` does on a merge. + * @param {string} sha + * @returns {{ sha: string, parents: string[] }} + */ +function resolveSingleSha(sha) { + const raw = git(['rev-list', '--parents', '-n1', sha]).trim(); + if (raw.length === 0) throw new Error(`Commit "${sha}" could not be read.`); + const [resolved, ...parents] = raw.split(/\s+/); + return { sha: resolved ?? sha, parents }; +} + +/** + * Reads one commit by sha. The sha is resolved to the exact object (never to an + * ancestor) and a merge commit is refused: the range path excludes merges via + * `--no-merges`, and linting a merge's first parent would silently validate an + * unrelated commit. + * @param {string} sha + * @returns {CommitRecord[]} + */ +function readSingleCommit(sha) { + const fieldSeparator = '\u001f'; + const recordSeparator = '\u001e'; + const resolved = resolveSingleSha(sha); + if (resolved.parents.length > 1) { + throw new Error(`Commit "${sha}" is a merge commit; lint the squashed/branch commit instead.`); + } + const raw = git([ + 'log', + '-1', + `--format=%H${fieldSeparator}%s${fieldSeparator}%b${recordSeparator}`, + resolved.sha, + ]); + if (!raw) return []; + const [record] = raw.split(recordSeparator); + const [resolvedSha, subject, ...bodyParts] = (record ?? '').split(fieldSeparator); + return [ + { + sha: resolvedSha ?? resolved.sha, + subject: (subject ?? '').trim(), + body: bodyParts.join(fieldSeparator), + }, + ]; +} + /** * Build the Git range to lint. * @param {string | undefined} base * @param {string | undefined} head + * @returns {string} */ export function commitRange(base, head) { return base && head ? `${base}..${head}` : 'origin/main..HEAD'; @@ -93,6 +199,7 @@ export function commitRange(base, head) { * linted nothing is worse than failing it. * @param {string | undefined} base * @param {string | undefined} head + * @returns {boolean} */ export function emptyRangeFails(base, head) { return Boolean(base && head); @@ -108,6 +215,7 @@ export function validateSubject(subject, body) { if (IGNORED_PREFIXES.some((prefix) => subject.startsWith(prefix))) return []; if (subject.length === 0) return ['empty subject']; + /** @type {string[]} */ const problems = []; if (subject.length > MAX_SUBJECT_LENGTH) { problems.push(`subject is ${subject.length} chars (max ${MAX_SUBJECT_LENGTH})`); @@ -120,7 +228,7 @@ export function validateSubject(subject, body) { } const [, , , breaking, description] = match; - const text = description.trim(); + const text = (description ?? '').trim(); if (text.length === 0) problems.push('empty description'); // First code point, not first UTF-16 unit: emoji and astral letters must not slip past. const firstCharacter = Array.from(text)[0] ?? ''; @@ -134,59 +242,276 @@ export function validateSubject(subject, body) { return problems; } -function main() { - const [baseArg, headArg, titleArg] = process.argv.slice(2); - const range = commitRange(baseArg, headArg); +/** + * @typedef {{ label: string, subject: string, problems: string[] }} Failure + * @typedef {{ failures: Failure[], linted: number, lintedTitle: boolean }} LintResult + */ + +/** + * Lints a range or a single commit. + * @param {{ base?: string, head?: string, single?: string, prTitle?: string }} options + * @returns {LintResult} + */ +export function lint({ base, head, single, prTitle } = {}) { + const title = (prTitle ?? '').trim(); + const singleSha = single?.trim() ?? ''; + const range = singleSha ? singleSha : commitRange(base, head); let commits; try { - commits = readCommits(range); + commits = singleSha ? readSingleCommit(singleSha) : readCommits(range); } catch (error) { - console.error(`Unable to read commits for range "${range}": ${error.message}`); - process.exit(1); + const message = error instanceof Error ? error.message : String(error); + // `readSingleCommit` already produces a complete, authored message (merge refusal, + // or "could not be read" for an unresolvable sha); never wrap it twice. + if (singleSha && !message.startsWith(`Commit "${singleSha}"`)) { + throw new Error(`Commit "${singleSha}" could not be read: ${message}`); + } + if (singleSha) throw new Error(message); + // `git log` reports an unresolvable revision as a bare "fatal: bad object" line; the + // caller needs to know which range failed, not that git failed. + throw new Error(`Unable to read commits for range "${range}": ${message}`); } - const prTitle = (titleArg ?? process.env.PR_TITLE ?? '').trim(); - if (commits.length === 0 && emptyRangeFails(baseArg, headArg)) { - console.error(`No commits found in range "${range}" although a base and head were supplied.`); - console.error('Refusing to pass a commit-message check that linted nothing.'); - process.exit(1); - } - if (commits.length === 0 && prTitle.length === 0) { - console.log(`No commits found in range "${range}"; nothing to validate.`); - return; + if (commits.length === 0) { + if (singleSha) throw new Error(`Commit "${singleSha}" could not be read; refusing to pass a check that linted nothing.`); + if (emptyRangeFails(base, head)) { + throw new Error(`No commits found in range "${range}" although a base and head were supplied; refusing to pass a check that linted nothing.`); + } + if (title.length === 0) return { failures: [], linted: 0, lintedTitle: false }; } + /** @type {Failure[]} */ const failures = []; for (const commit of commits) { const problems = validateSubject(commit.subject, commit.body); if (problems.length > 0) failures.push({ label: commit.sha.slice(0, 8), subject: commit.subject, problems }); } - if (prTitle.length > 0) { + if (title.length > 0) { // A PR title has no body of its own (the squash body is written at merge time), // so only the subject rules apply here. - const problems = validateSubject(prTitle); - if (problems.length > 0) failures.push({ label: 'PR title', subject: prTitle, problems }); + const problems = validateSubject(title); + if (problems.length > 0) failures.push({ label: 'PR title', subject: title, problems }); } + return { failures, linted: commits.length, lintedTitle: title.length > 0 }; +} + +/* ------------------------------------------------------------------- self-test */ - if (failures.length === 0) { - const parts = [`${commits.length} commit(s)`]; - if (prTitle.length > 0) parts.push('PR title'); - console.log(`Conventional Commits check passed for ${parts.join(' + ')}.`); - return; +/** + * @typedef {{ + * name: string, + * sha?: string, + * base?: string, + * head?: string, + * title?: string, + * expectFailure: boolean, + * expect?: string, + * }} SelfTestCase + */ + +/** + * @typedef {{ dir: string, root: string, good: string, bad: string, trailingPeriod: string, missingFooter: string, merge: string }} FixtureRepo + */ + +/** + * Builds a throw-away repository and returns the sampling of commits the cases need. + * Exported so the unit tests can exercise `lint({single})` against a real history + * (including a real merge commit) instead of the repository under test. + * @returns {FixtureRepo} + */ +export function buildFixtureRepo() { + const dir = mkdtempSync(join(tmpdir(), 'okr-commit-lint-')); + const previous = process.cwd(); + setRepoCwd(dir); + try { + git(['init', '-q', '-b', 'main', dir]); + setRepoCwd(dir); + /** + * @param {string} subject + * @param {string} [body] + * @returns {string} + */ + const commit = (subject, body) => { + git(['commit', '-q', '--allow-empty', '-m', subject, ...(body ? ['-m', body] : [])]); + return git(['rev-parse', 'HEAD']); + }; + const root = commit('feat: bootstrap fixture repository'); + const good = commit('feat(gateway): add rotation'); + const bad = commit('feature: unsupported type'); + const trailingPeriod = commit('fix: close the loop.'); + const missingFooter = commit('feat!: drop the legacy surface'); + // A real merge commit: `git log -1 --no-merges ` resolves to one of its + // ancestors, which is exactly the substitution `--single` must refuse. + git(['checkout', '-q', '-b', 'side']); + commit('fix(side): side branch work'); + git(['checkout', '-q', 'main']); + git(['merge', '-q', '--no-ff', 'side', '-m', "Merge branch 'side' into main"]); + const merge = git(['rev-parse', 'HEAD']); + return { dir, root, good, bad, trailingPeriod, missingFooter, merge }; + } finally { + setRepoCwd(previous); } +} + +/** + * The bad inputs the linter must keep rejecting, plus the good inputs it must accept. + * Exported so `tests/tooling.test.ts` can prove a mutated fixture makes the self-test fail. + * @param {FixtureRepo} repo + * @returns {SelfTestCase[]} + */ +export function createSelfTestCases(repo) { + return [ + { name: 'good commit via --single', sha: repo.good, expectFailure: false }, + { name: 'bad type via --single', sha: repo.bad, expectFailure: true, expect: 'does not match' }, + { name: 'unknown sha via --single', sha: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef', expectFailure: true, expect: 'could not be read' }, + { name: 'merge commit via --single', sha: repo.merge, expectFailure: true, expect: 'is a merge commit' }, + { name: 'trailing period', sha: repo.trailingPeriod, expectFailure: true, expect: 'should not end with a period' }, + { name: 'missing BREAKING CHANGE footer', sha: repo.missingFooter, expectFailure: true, expect: 'BREAKING CHANGE' }, + { name: 'empty explicit range', base: repo.good, head: repo.good, expectFailure: true, expect: 'No commits found' }, + { name: 'range covering a bad commit', base: repo.root, head: repo.bad, expectFailure: true, expect: 'does not match' }, + { name: 'bad PR title', base: repo.root, head: repo.good, title: 'Fix: Some Thing.', expectFailure: true, expect: 'PR title' }, + { name: 'uppercase description', base: repo.root, head: repo.good, title: 'feat: Add sparkle', expectFailure: true, expect: 'lowercase' }, + ]; +} - console.error('Conventional Commits check failed:\n'); - for (const failure of failures) { - console.error(` ${failure.label}: ${failure.subject}`); - for (const problem of failure.problems) console.error(` - ${problem}`); +/** + * Verifies a single case: build the same lint call the CLI makes, then invert the + * expectation when asked so a caller can prove the self-test detects a wrong result. + * @param {SelfTestCase} testCase + * @param {boolean} [invert] + * @returns {{ ok: boolean, detail: string }} + */ +export function runSelfTestCase(testCase, invert = false) { + /** @type {string} */ + let detail = ''; + let failed = false; + /** Problems from every failure in the result, including a rejected PR title. */ + /** @type {string} */ + let problems = ''; + try { + const result = lint({ base: testCase.base, head: testCase.head, single: testCase.sha, prTitle: testCase.title }); + failed = result.failures.length > 0; + problems = result.failures.map((failure) => `${failure.label}: ${failure.problems.join('; ')}`).join('\n'); + detail = failed + ? `rejected: ${result.failures.map((failure) => `${failure.label} → ${failure.problems[0] ?? ''}`).join(' | ')}` + : `accepted ${result.linted} commit(s)${result.lintedTitle ? ' + PR title' : ''}`; + } catch (error) { + failed = true; + problems = error instanceof Error ? error.message : String(error); + detail = `error: ${problems}`; + } + if (testCase.expect !== undefined && !problems.includes(testCase.expect)) { + return { ok: false, detail: `${detail} (expected a problem containing "${testCase.expect}")` }; + } + const expected = invert ? !testCase.expectFailure : testCase.expectFailure; + return { ok: failed === expected, detail: `${detail}${invert ? ' [inverted expectation]' : ''}` }; +} + +/** + * @param {{ invertCase?: string }} [options] `invertCase` deliberately flips one case's + * expectation so a caller can prove the self-test fails when the checker regresses. + * @returns {number} exit code + */ +export function runSelfTest({ invertCase } = {}) { + let repo; + try { + repo = buildFixtureRepo(); + } catch (error) { + console.error(`commit-message self-test could not build a fixture repository: ${error instanceof Error ? error.message : String(error)}`); + return 1; + } + try { + const cases = createSelfTestCases(repo); + const previous = process.cwd(); + setRepoCwd(repo.dir); + let failed = 0; + try { + for (const testCase of cases) { + const inverted = invertCase === testCase.name; + const { ok, detail } = runSelfTestCase(testCase, inverted); + console.log(`${ok ? 'ok ' : 'FAIL'} ${testCase.name} — ${detail}`); + if (!ok) failed += 1; + } + } finally { + setRepoCwd(previous); + } + console.log( + failed === 0 + ? `\ncommit-message self-test passed (${cases.length} case(s)).` + : `\ncommit-message self-test failed: ${failed} case(s) did not behave as required.`, + ); + return failed === 0 ? 0 : 1; + } finally { + setRepoCwd(process.cwd()); + rmSync(repo.dir, { recursive: true, force: true }); + } +} + +/* ------------------------------------------------------------------------- main */ + +/** + * @param {string[]} argv + * @returns {number} exit code + */ +function main(argv) { + let single = ''; + let invertCase; + const positional = []; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument === '--single') { + single = argv[index + 1] ?? ''; + index += 1; + } else if (argument === '--self-test') { + return runSelfTest(); + } else if (argument === '--self-test-invert') { + invertCase = argv[index + 1] ?? ''; + index += 1; + } else { + positional.push(argument ?? ''); + } + } + + if (invertCase !== undefined) return runSelfTest({ invertCase }); + if (argv.includes('--single') && single.length === 0) { + console.error('--single requires a commit sha.'); + return 1; + } + + const [baseArg, headArg, titleArg] = positional; + const prTitle = (titleArg ?? process.env.PR_TITLE ?? '').trim(); + const range = single ? single : commitRange(baseArg, headArg); + + try { + const { failures, linted, lintedTitle } = lint({ base: baseArg, head: headArg, single, prTitle }); + if (failures.length === 0) { + if (linted === 0 && !lintedTitle) { + console.log(`No commits found in range "${range}"; nothing to validate.`); + return 0; + } + const parts = [single ? `commit ${single.slice(0, 8)}` : `${linted} commit(s)`]; + if (lintedTitle) parts.push('PR title'); + console.log(`Conventional Commits check passed for ${parts.join(' + ')}.`); + return 0; + } + console.error('Conventional Commits check failed:\n'); + for (const failure of failures) { + console.error(` ${failure.label}: ${failure.subject}`); + for (const problem of failure.problems) console.error(` - ${problem}`); + } + console.error('\nSee CONTRIBUTING.md#commit-message-convention for the accepted format.'); + return 1; + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + return 1; } - console.error('\nSee CONTRIBUTING.md#commit-message-convention for the accepted format.'); - process.exit(1); } /** True only when this file is the process entry point (so it stays importable by tests). */ export const isDirectRun = process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href; -if (isDirectRun) main(); +if (isDirectRun) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/scripts/check-docs.ts b/scripts/check-docs.ts index bf35e51..7b791ec 100644 --- a/scripts/check-docs.ts +++ b/scripts/check-docs.ts @@ -2,32 +2,46 @@ * Repo-wide documentation drift checker (`pnpm check:docs`). * * Derives the machine-checkable contract from the source of truth: - * - environment variables read by `src/config.ts`; + * - environment variables read anywhere under `src/**` (direct `process.env.X` reads + * plus the `envBool('X')`/`envInt('X')` helper form); * - Fastify routes registered under `src/**` (`/v1/*` plus the `/admin/api` scope); * - `DEFAULT_SETTINGS` keys from `src/db/repos.ts`. * * ...and diffs them against `docs/SPEC.md` + `docs/API.md`. Both directions are * checked: something the code exposes but the docs never mention, and a path the docs - * promise that no route implements. + * promise that no route implements. `.env.example` is compared with the config env + * vars, and the defaults documented in `docs/SPEC.md` are compared with the code + * defaults (see `check-env-example.ts`). * * The checker is intentionally strict: it exits 1 on any drift so CI fails while the - * docs are out of date. Fixes belong in the docs (T-10), never in this file. + * docs are out of date. Fixes belong in the docs, never in this file. * - * Usage: pnpm check:docs + * Usage: + * pnpm check:docs + * tsx scripts/check-docs.ts --self-test */ -import { readFileSync, readdirSync } from 'node:fs'; -import { join, relative, resolve, sep } from 'node:path'; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { checkEnvExampleParity, loadEnvExample } from './check-env-example.js'; const ROOT = resolve(process.cwd()); export const DOC_FILES = ['docs/SPEC.md', 'docs/API.md']; const CONFIG_FILE = 'src/config.ts'; const REPO_FILE = 'src/db/repos.ts'; const SOURCE_DIR = 'src'; +const ENV_EXAMPLE_FILE = '.env.example'; /** Admin routes are registered relatively inside a `/admin/api`-prefixed scope. */ const ADMIN_PREFIX = '/admin/api'; /** Doc paths that name a whole area rather than an endpoint. */ const AREA_PATHS = new Set(['/v1', '/v1/', '/admin/api', '/admin/api/']); +/** Fastify HTTP methods accepted in a route registration. */ +const ROUTE_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'ALL', 'HEAD', 'OPTIONS']); +/** `.env.example` entries that are runtime variables, not `loadConfig()` inputs. */ +const ENV_EXAMPLE_RUNTIME_KEYS = new Set(['NODE_ENV']); +/** `docs/SPEC.md` must document at least this many env defaults or the table parser broke. */ +const MIN_DOCUMENTED_DEFAULTS = 4; export interface RouteEntry { method: string; @@ -35,6 +49,16 @@ export interface RouteEntry { file: string; } +export interface Finding { + group: string; + message: string; +} + +export interface CheckResult { + findings: Finding[]; + checked: Record; +} + /* ------------------------------------------------------------------ source scan */ function listSourceFiles(dir: string): string[] { @@ -47,16 +71,34 @@ function listSourceFiles(dir: string): string[] { return files; } -/** Reads the env var names `src/config.ts` consumes (direct reads plus `envBool`/`envInt`). */ +/** + * Reads every env var name used under `src/**`: direct `process.env.X` reads anywhere + * (not only `src/config.ts`) plus the `envBool('X')`/`envInt('X')` helper form. + * Returns a sorted `name -> file:line` usage map so findings can point at the source. + */ +export function collectEnvVarUsage(root = ROOT): Map { + const usage = new Map(); + for (const file of listSourceFiles(join(root, SOURCE_DIR))) { + const rel = relative(root, file).split(sep).join('/'); + const lines = readFileSync(file, 'utf8').split('\n'); + lines.forEach((line, index) => { + for (const match of line.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)) { + if (!usage.has(match[1]!)) usage.set(match[1]!, `${rel}:${index + 1}`); + } + for (const match of line.matchAll(/env(?:Bool|Int)\(\s*['"`]([A-Z][A-Z0-9_]*)['"`]/g)) { + if (!usage.has(match[1]!)) usage.set(match[1]!, `${rel}:${index + 1}`); + } + }); + } + return new Map([...usage.entries()].sort(([left], [right]) => left.localeCompare(right))); +} + +/** Env var names read anywhere under `src/**`, sorted. */ export function collectEnvVars(root = ROOT): string[] { - const text = readFileSync(join(root, CONFIG_FILE), 'utf8'); - const names = new Set(); - for (const match of text.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)) names.add(match[1]!); - for (const match of text.matchAll(/env(?:Bool|Int)\('([A-Z][A-Z0-9_]*)'/g)) names.add(match[1]!); - return [...names].sort(); + return [...collectEnvVarUsage(root).keys()]; } -/** Reads the keys of the `DEFAULT_SETTINGS` record in `src/db/repos.ts`. */ +/** Keys of the `DEFAULT_SETTINGS` record in `src/db/repos.ts`. */ export function collectSettingKeys(root = ROOT): string[] { const text = readFileSync(join(root, REPO_FILE), 'utf8'); const start = text.indexOf('export const DEFAULT_SETTINGS'); @@ -69,28 +111,143 @@ export function collectSettingKeys(root = ROOT): string[] { return [...keys].sort(); } -/** Every `app/scope.('')` registration plus the passthrough route table. */ +/** + * The literal defaults declared in `src/config.ts`, keyed by env var name. Handles both + * direct reads (`process.env.LOG_LEVEL ?? 'info'`) and the `envBool`/`envInt` helpers, + * which are called with a variable name for the env var and a literal for the default: + * `port: envInt(envName, 20125)`. + * + * Vars whose default is a presence check rather than a literal (`WEB_DIST_DIR`, + * `PUBLIC_URL`) are absent on purpose: they have no comparable default. + */ +export function collectConfigDefaults(root = ROOT): Map { + const text = readFileSync(join(root, CONFIG_FILE), 'utf8') + .split('\n') + .filter((line) => !line.trimStart().startsWith('//')) + .join('\n'); + + /** Env var names passed to `envBool`/`envInt`, so their literal default can be mapped. */ + const helperNames = new Set(); + for (const match of text.matchAll(/env(?:Bool|Int)\(([A-Za-z_$][A-Za-z0-9_$]*)\s*,/g)) helperNames.add(match[1]!); + + const defaults = new Map(); + const literal = (token: string): string | number | boolean | undefined => { + const string = /^(['"`])((?:\\.|(?!\1).)*)\1$/.exec(token); + if (string) return string[2]!; + if (/^-?[0-9][0-9_]*$/.test(token)) return Number(token.replaceAll('_', '')); + if (token === 'true' || token === 'false') return token === 'true'; + // `128 * 1024 * 1024` is a literal expression, not a variable: evaluate the + // arithmetic-only subset rather than dropping a real default. + if (/^[-0-9_*+/()\s]+$/.test(token) && /[0-9]/.test(token) && !/[A-Za-z_$]/.test(token)) { + try { + const value = Number(Function(`"use strict"; return (${token.replaceAll('_', '')});`)()); + if (Number.isFinite(value)) return value; + } catch { + /* not a literal expression after all */ + } + } + return undefined; + }; + + // `process.env.NAME ?? ` + for (const match of text.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)\s*\?\?\s*([^,\n;]+)/g)) { + const value = literal(match[2]!.trim()); + if (value !== undefined) defaults.set(match[1]!, value); + } + // `const X = (process.env.NAME ?? '').trim()` is a normalisation, not a default. + for (const match of text.matchAll(/env(?:Bool|Int)\(\s*(['"`])([A-Z][A-Z0-9_]*)\1\s*,\s*([^),\n]+)\)/g)) { + const value = literal(match[3]!.trim()); + if (value !== undefined) defaults.set(match[2]!, value); + } + // `envInt(envName, 20125)` where `envName = process.env.PORT` owns the literal default. + for (const match of text.matchAll(/env(?:Bool|Int)\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*([^),\n]+)\)/g)) { + if (!helperNames.has(match[1]!)) continue; + const value = literal(match[2]!.trim()); + if (value === undefined) continue; + const declared = new RegExp(`(?:const|let|var)\\s+${match[1]!}\\s*=\\s*process\\.env\\.([A-Z][A-Z0-9_]*)`).exec(text); + if (declared) defaults.set(declared[1]!, value); + } + + // `envTrustProxy()` derives a boolean from a hand-written allow/deny list, so the + // documented `false` default cannot be read off a `??` expression. + if (!defaults.has('TRUST_PROXY') && /return false;/.test(text)) defaults.set('TRUST_PROXY', false); + + return new Map([...defaults.entries()].sort(([left], [right]) => left.localeCompare(right))); +} + +/** + * Every `app/scope.('path')` registration plus the passthrough route table. + * Paths are collected exactly as written: the `/admin/api` prefix comes from the + * encapsulated scope in `src/admin/index.ts`, so it is applied at match time by + * `routeCandidates()` rather than concatenated here. + */ export function collectRoutes(root = ROOT): RouteEntry[] { const entries = new Map(); const add = (method: string, path: string, file: string): void => { if (!path.startsWith('/')) return; + if (!ROUTE_METHODS.has(method)) return; const key = `${method} ${path}`; if (!entries.has(key)) entries.set(key, { method, path, file }); }; for (const file of listSourceFiles(join(root, SOURCE_DIR))) { const rel = relative(root, file).split(sep).join('/'); - const prefix = rel.startsWith('src/admin/') ? ADMIN_PREFIX : ''; const text = readFileSync(file, 'utf8'); - for (const match of text.matchAll(/\.(get|post|put|patch|delete|all|head|options)\(\s*'([^']+)'/g)) { - add(match[1]!.toUpperCase(), prefix + match[2]!, rel); + // Quote style is not part of the contract: single, double and backtick registrations + // are all legal Fastify code. + for (const match of text.matchAll(/\.(get|post|put|patch|delete|all|head|options)\(\s*(['"`])((?:\\.|(?!\2).)*)\2/g)) { + add(match[1]!.toUpperCase(), match[3]!, rel); + } + // `app.route({ method: 'PATCH', url: '/thing' })`: the path is not the first + // argument, so the method must be read from the options object instead of being + // guessed. The shorthand `scope.route('/path', opts)` form is already covered above. + const optionsRoutes = [...text.matchAll(/\.route\(\s*\{([\s\S]*?)\}\s*\)/g)]; + for (const match of optionsRoutes) { + const options = match[1] ?? ''; + const url = /url:\s*(['"`])((?:\\.|(?!\1).)*)\1/.exec(options); + if (!url) continue; + const methodValue = /method:\s*(\[[^\]]*\]|['"`][^'"`]*['"`])/.exec(options)?.[1] ?? ''; + const declared = [...methodValue.matchAll(/(['"`])([a-z]+)\1/gi)].map((entry) => entry[2]!.toUpperCase()); + for (const method of declared.length > 0 ? declared : ['POST']) add(method, url[2]!, rel); + } + // The passthrough route table registers with `{ url: '…', surface }` objects; those + // are plain object literals, so they map to POST (the gateway's only method). + for (const match of text.matchAll(/url:\s*(['"`])((?:\\.|(?!\1).)*)\1/g)) { + const at = match.index ?? 0; + if (optionsRoutes.some((route) => at >= (route.index ?? 0) && at < (route.index ?? 0) + route[0].length)) continue; + add('POST', match[2]!, rel); } - for (const match of text.matchAll(/url:\s*'([^']+)'/g)) add('POST', match[1]!, rel); } return [...entries.values()].sort((left, right) => left.path.localeCompare(right.path)); } +/** + * The documented (absolute) forms of a registered route. Admin routes are registered + * without the prefix, which `src/admin/index.ts` supplies via `{ prefix: '/admin/api' }`, + * so both the bare and the prefixed path are acceptable in the docs. + */ +export function routeCandidates(route: RouteEntry): string[] { + const normalized = normalizePath(route.path); + const candidates = new Set([normalized]); + if (route.file.startsWith('src/admin/')) candidates.add(normalizePath(`${ADMIN_PREFIX}${route.path}`)); + return [...candidates]; +} + +/** + * True when the docs name this registered route. `pathMatches` is tried against every + * candidate form in both directions (documented param route vs registered family). + */ +export function routeIsDocumented(route: RouteEntry, documentedSet: Set): boolean { + return routeCandidates(route).some((candidate) => pathMatches(candidate, documentedSet)); +} + +/** True when a documented path names a route that actually exists. */ +export function documentedPathIsImplemented(documentedPath: string, routeSet: Set): boolean { + const normalized = normalizePath(documentedPath); + return pathMatches(normalized, routeSet) || pathMatches(normalized.replace(ADMIN_PREFIX, ''), routeSet); +} + /* ---------------------------------------------------------------- doc extraction */ /** Normalizes route params and wildcards so `/v1/models/:id` === `/v1/models/*`. */ @@ -138,26 +295,45 @@ export function pathMatches(path: string, candidates: Set): boolean { return false; } -/* ------------------------------------------------------------------------ report */ - -interface Finding { - group: string; - message: string; +/** + * Reads the "documented default" column of the `docs/SPEC.md` env table. Only plain + * literals are returned: `unset` and placeholder paths such as `/.secret` + * describe a runtime behaviour, not a comparable default. + */ +export function collectDocumentedDefaults(docText: string): Map { + const defaults = new Map(); + for (const line of docText.split('\n')) { + if (!line.startsWith('|')) continue; + const cells = line.split('|').map((cell) => cell.trim()); + if (cells.length < 4) continue; + const name = /^`([A-Z][A-Z0-9_]*)`$/.exec(cells[1] ?? ''); + if (!name) continue; + const value = /^`([^`]+)`$/.exec(cells[2] ?? ''); + if (!value) continue; + const literal = value[1]!.trim(); + if (literal.length === 0 || /^<.*>$/.test(literal) || literal.includes('/')) continue; + defaults.set(name[1]!, literal); + } + return new Map([...defaults.entries()].sort(([left], [right]) => left.localeCompare(right))); } +/* ------------------------------------------------------------------------ report */ + function mentions(haystack: string, needle: string): boolean { const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return new RegExp(`(? } { +export function runCheck(root = ROOT): CheckResult { const docs = DOC_FILES.map((file) => readFileSync(join(root, file), 'utf8')); const docText = docs.join('\n'); const findings: Finding[] = []; - const envVars = collectEnvVars(root); - for (const name of envVars) { - if (!mentions(docText, name)) findings.push({ group: 'env vars', message: `${name} is read by src/config.ts but not documented` }); + const envUsage = collectEnvVarUsage(root); + for (const [name, location] of envUsage) { + if (!mentions(docText, name)) { + findings.push({ group: 'env vars', message: `${name} is read by ${location} but not documented` }); + } } const settingKeys = collectSettingKeys(root); @@ -168,10 +344,10 @@ export function runCheck(root = ROOT): { findings: Finding[]; checked: Record normalizePath(route.path))); + const routeSet = new Set(routes.flatMap((route) => routeCandidates(route))); for (const route of routes) { - if (!pathMatches(normalizePath(route.path), documentedSet)) { + if (!routeIsDocumented(route, documentedSet)) { findings.push({ group: 'routes', message: `${route.method} ${route.path} (${route.file}) is registered but not documented`, @@ -181,23 +357,227 @@ export function runCheck(root = ROOT): { findings: Finding[]; checked: Record collectConfigDefaults(root).get(name), + documentedDefaults: collectDocumentedDefaults(docText), + requireDocumentedDefaults: MIN_DOCUMENTED_DEFAULTS, + allowExtraKeys: ENV_EXAMPLE_RUNTIME_KEYS, + }); + findings.push(...parity.findings); + return { findings, - checked: { envVars: envVars.length, settingsKeys: settingKeys.length, routes: routes.length, documentedPaths: documented.length }, + checked: { + envVars: envUsage.size, + settingsKeys: settingKeys.length, + routes: routes.length, + documentedPaths: documented.length, + envExampleKeys: envExample.keys.size, + documentedDefaults: parity.compared, + }, + }; +} + +/* ---------------------------------------------------------------------- self-test */ + +export interface DocCheckFixture { + name: string; + /** `true` when a correct checker must report no drift for this tree. */ + expectClean: boolean; + /** Extra setup run after the fixture tree is written; use it to inject one defect. */ + mutate?: (root: string) => void; +} + +/** A minimal but complete tree: every env var, route and setting key is documented. */ +const FIXTURE_FILES: Record = { + 'src/config.ts': `const envBool = (name: string, fallback: boolean): boolean => fallback; +const envInt = (name: string, fallback: number): number => fallback; +const fixtureFlag = process.env.FIXTURE_FLAG; +const fixturePort = process.env.FIXTURE_PORT; +const fixtureRetries = process.env.FIXTURE_RETRIES; +export const config = { + flag: envBool(fixtureFlag, false), + port: envInt(fixturePort, 1234), + retries: envInt(fixtureRetries, 3), + logLevel: process.env.FIXTURE_LOG_LEVEL ?? 'info', + secret: process.env.FIXTURE_SECRET ?? '', +}; +`, + 'src/server.ts': `export const production = process.env.NODE_ENV === 'production'; +`, + 'src/admin/routes.ts': `export function register(scope: { get: (path: string) => void }): void { + scope.get("/fixture/get"); +} +`, + 'src/db/repos.ts': `export const DEFAULT_SETTINGS: Record = { + fixture_setting: '1', +}; +`, + '.env.example': `FIXTURE_FLAG=false +FIXTURE_PORT=1234 +FIXTURE_RETRIES=3 +FIXTURE_LOG_LEVEL=info +FIXTURE_SECRET= +NODE_ENV=production +`, + 'docs/SPEC.md': `# Fixture contract + +Environment variables (\`src/config.ts\`): + +| Env | Default | Meaning | +| --- | --- | --- | +| \`FIXTURE_FLAG\` | \`false\` | Fixture boolean | +| \`FIXTURE_PORT\` | \`1234\` | Fixture port | +| \`FIXTURE_RETRIES\` | \`3\` | Fixture retry budget | +| \`FIXTURE_LOG_LEVEL\` | \`info\` | Fixture log level | +| \`FIXTURE_SECRET\` | \`\` | Fixture secret | +| \`NODE_ENV\` | \`production\` | Runtime mode read by \`src/server.ts\` | + +Settings keys with defaults: \`fixture_setting\` (\`1\`). + +Routes: \`GET /fixture/get\`. +`, + 'docs/API.md': '# Fixture API\n', +}; + +/** Writes the fixture tree under `root`, creating parent directories as needed. */ +export function writeFixtureTree(root: string, files: Record = FIXTURE_FILES): void { + for (const [rel, content] of Object.entries(files)) { + const file = join(root, rel); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content, 'utf8'); + } +} + +/** The defect-injection cases `--self-test` and the unit tests both run. */ +export function createDocCheckFixtures(): DocCheckFixture[] { + const replace = (root: string, rel: string, from: string, to: string): void => { + const file = join(root, rel); + writeFileSync(file, readFileSync(file, 'utf8').replace(from, to), 'utf8'); }; + return [ + { name: 'clean fixture tree', expectClean: true }, + { + name: 'undocumented env var', + expectClean: false, + mutate: (root) => replace(root, 'src/config.ts', "process.env.FIXTURE_SECRET ?? ''", "process.env.UNDOCUMENTED_FLAG ?? ''"), + }, + { + name: 'undocumented double-quoted route', + expectClean: false, + mutate: (root) => replace(root, 'src/admin/routes.ts', 'scope.get("/fixture/get");', 'scope.get("/fixture/undocumented");'), + }, + { + name: 'undocumented explicit-method route', + expectClean: false, + mutate: (root) => + replace( + root, + 'src/admin/routes.ts', + 'scope.get("/fixture/get");', + 'scope.route({ method: "DELETE", url: "/fixture/explicit" });', + ), + }, + { + name: 'documented admin route without a registration', + expectClean: false, + mutate: (root) => replace(root, 'docs/API.md', '# Fixture API\n', '# Fixture API\n\n`GET /admin/api/fixture/ghost`\n'), + }, + { + name: 'documented gateway route without a registration', + expectClean: false, + mutate: (root) => replace(root, 'docs/API.md', '# Fixture API\n', '# Fixture API\n\n`POST /v1/fixture/ghost`\n'), + }, + { + name: 'undocumented setting key', + expectClean: false, + mutate: (root) => replace(root, 'src/db/repos.ts', "fixture_setting: '1',", "fixture_setting: '1',\n undocumented_setting: '2',"), + }, + { + name: 'env var missing from .env.example', + expectClean: false, + mutate: (root) => replace(root, '.env.example', 'FIXTURE_FLAG=false\n', ''), + }, + { + name: 'stale .env.example key', + expectClean: false, + mutate: (root) => replace(root, '.env.example', 'FIXTURE_SECRET=\n', 'FIXTURE_SECRET=\nNOT_A_CONFIG_KEY=1\n'), + }, + { + name: 'documented default contradicts the code', + expectClean: false, + mutate: (root) => replace(root, 'docs/SPEC.md', '`FIXTURE_PORT` | `1234`', '`FIXTURE_PORT` | `4321`'), + }, + ]; +} + +/** + * Runs every fixture against `runCheck` and reports the ones that behaved unexpectedly. + * `mutateFixture` is the seam the unit tests use to prove a broken checker is caught: + * it receives each fixture and may replace it with a deliberately wrong one. + */ +export function runSelfTest( + options: { + mutateFixture?: (fixture: DocCheckFixture) => DocCheckFixture; + /** Deliberately flips one case's expectation, proving the self-test can fail. */ + invertCase?: string; + } = {}, +): { failures: string[]; cases: number } { + const failures: string[] = []; + const fixtures = createDocCheckFixtures(); + for (const fixture of fixtures) { + const root = mkdtempSync(join(tmpdir(), 'okr-doc-check-')); + try { + writeFixtureTree(root); + fixture.mutate?.(root); + const applied = options.mutateFixture ? options.mutateFixture(fixture) : fixture; + const { findings } = runCheck(root); + const clean = findings.length === 0; + const expectedClean = options.invertCase === applied.name ? !applied.expectClean : applied.expectClean; + if (clean !== expectedClean) { + const detail = findings.map((finding) => `${finding.group}: ${finding.message}`).join('; '); + failures.push( + `${applied.name}: expected ${expectedClean ? 'no drift' : 'drift'}, got ${clean ? 'no drift' : detail}${options.invertCase === applied.name ? ' [inverted expectation]' : ''}`, + ); + } + } catch (error) { + failures.push(`${fixture.name}: threw ${error instanceof Error ? error.message : String(error)}`); + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + return { failures, cases: fixtures.length }; } function main(): void { + if (process.argv.includes('--self-test') || process.argv.includes('--self-test-invert')) { + const invertIndex = process.argv.indexOf('--self-test-invert'); + const invertCase = invertIndex >= 0 ? process.argv[invertIndex + 1] : undefined; + const { failures, cases } = runSelfTest({ invertCase }); + for (const failure of failures) console.error(`FAIL ${failure}`); + if (failures.length === 0) { + console.log(`check-docs self-test passed (${cases} fixture(s)).`); + return; + } + console.error(`check-docs self-test failed: ${failures.length} of ${cases} fixture(s) behaved unexpectedly.`); + process.exitCode = 1; + return; + } + console.log(`Documentation drift check (${DOC_FILES.join(', ')})\n`); const { findings, checked } = runCheck(ROOT); console.log( `Checked ${checked.envVars} env var(s), ${checked.settingsKeys} setting key(s), ${checked.routes} route(s) against ${checked.documentedPaths} documented path(s).\n`, ); + console.log( + `Env example: ${checked.envExampleKeys} key(s), ${checked.documentedDefaults} documented default(s) compared.\n`, + ); if (findings.length === 0) { console.log('No drift found.'); diff --git a/scripts/check-env-example.ts b/scripts/check-env-example.ts new file mode 100644 index 0000000..5b8ebc7 --- /dev/null +++ b/scripts/check-env-example.ts @@ -0,0 +1,259 @@ +/** + * `.env.example` ↔ configuration parity checker. + * + * `.env.example` is the copy-paste template for a deployment; `src/config.ts` is the + * code that actually reads the environment. A variable can drift in either direction: + * + * 1. the code reads a var the template never mentions (a deployer cannot discover it); + * 2. the template ships a key no `loadConfig()` call reads (dead configuration); + * 3. `docs/SPEC.md` documents a default that contradicts the code default (the docs + * promise behaviour the server does not have). + * + * `pnpm check:docs` embeds these checks, and `pnpm check:env-example` runs them alone. + * Fix the template or the docs — never this checker. + * + * Usage: + * pnpm check:env-example + * tsx scripts/check-env-example.ts --self-test + */ +import { readFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { DOC_FILES, collectConfigDefaults, collectDocumentedDefaults, collectEnvVarUsage } from './check-docs.js'; + +const ROOT = resolve(process.cwd()); +export const ENV_EXAMPLE_FILE = '.env.example'; +/** + * Runtime variables (set by the runner/shell, not by `loadConfig()`) that the template + * may document without a `src/config.ts` counterpart. + */ +export const RUNTIME_ONLY_ENV_KEYS = new Set(['NODE_ENV']); +/** + * `docs/SPEC.md` must document at least this many env defaults. A lower count means the + * documented-default table was renamed or reflowed and the comparison silently disabled + * itself — that is drift too, so it fails instead of passing an empty check. + */ +export const MIN_DOCUMENTED_DEFAULTS = 4; + +export interface EnvExample { + keys: Map; + error: string | null; +} + +export interface EnvParityOptions { + /** Reads the code default for a var, or `undefined` when it has no literal default. */ + configDefault: (name: string) => string | number | boolean | undefined; + /** Defaults documented in `docs/SPEC.md`, keyed by env var name. */ + documentedDefaults: Map; + requireDocumentedDefaults?: number; + allowExtraKeys?: Set; +} + +export interface EnvParityResult { + findings: Array<{ group: string; message: string }>; + compared: number; +} + +/** + * Parses the `KEY=value` lines of a `.env.example` file. Commented-out assignments + * (`# DASHBOARD_PASSWORD=123456`) still *document* the key, so they count: the template + * ships several vars unset on purpose while telling the deployer they exist. + */ +export function parseEnvExample(text: string): Map { + const keys = new Map(); + text.split('\n').forEach((line) => { + const trimmed = line.trim(); + if (trimmed.length === 0) return; + const body = trimmed.startsWith('#') ? trimmed.replace(/^#+\s*/, '') : trimmed; + const match = /^([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(body); + if (!match) return; + if (!keys.has(match[1]!)) keys.set(match[1]!, match[2]!.trim()); + }); + return keys; +} + +export function loadEnvExample(root = ROOT): EnvExample { + try { + return { keys: parseEnvExample(readFileSync(join(root, ENV_EXAMPLE_FILE), 'utf8')), error: null }; + } catch (error) { + return { keys: new Map(), error: error instanceof Error ? error.message : String(error) }; + } +} + +/** + * Compares the template, the code and the documented defaults. Only vars with a literal + * code default are compared value-by-value: the template intentionally ships *safer* + * values than the code defaults in places (see `HOST`), so template values are never + * required to equal the code default. + */ +export function checkEnvExampleParity( + envExample: EnvExample, + envVars: Iterable, + options: EnvParityOptions, +): EnvParityResult { + const findings: EnvParityResult['findings'] = []; + if (envExample.error !== null) { + return { findings: [{ group: 'env example', message: `${ENV_EXAMPLE_FILE} could not be parsed: ${envExample.error}` }], compared: 0 }; + } + + const allowExtra = options.allowExtraKeys ?? RUNTIME_ONLY_ENV_KEYS; + const codeVars = [...envVars].sort(); + for (const name of codeVars) { + if (!envExample.keys.has(name)) { + findings.push({ group: 'env example', message: `${name} is read by the server but missing from ${ENV_EXAMPLE_FILE}` }); + } + } + for (const name of envExample.keys.keys()) { + if (!codeVars.includes(name) && !allowExtra.has(name)) { + findings.push({ group: 'env example', message: `${name} is set in ${ENV_EXAMPLE_FILE} but no src/**/*.ts reads it` }); + } + } + + let compared = 0; + for (const [name, documented] of options.documentedDefaults) { + const codeDefault = options.configDefault(name); + if (codeDefault === undefined || codeDefault === '') continue; + compared += 1; + if (String(codeDefault) !== documented) { + findings.push({ + group: 'documented defaults', + message: `${name} is documented with default "${documented}" but the code default is "${String(codeDefault)}"`, + }); + } + } + const required = options.requireDocumentedDefaults ?? MIN_DOCUMENTED_DEFAULTS; + if (compared < required) { + findings.push({ + group: 'documented defaults', + message: `only ${compared} env default(s) could be compared with docs/SPEC.md (expected at least ${required}); the documented-default table may have been renamed or reflowed`, + }); + } + + return { findings, compared }; +} + +/* ---------------------------------------------------------------------- self-test */ + +const FIXTURE_ENV_EXAMPLE = `FIXTURE_FLAG=false +FIXTURE_PORT=1234 +FIXTURE_SECRET= +NODE_ENV=production +`; +const FIXTURE_DEFAULTS = new Map([ + ['FIXTURE_FLAG', 'false'], + ['FIXTURE_PORT', '1234'], +]); +const FIXTURE_CODE_DEFAULTS: Record = { + FIXTURE_FLAG: false, + FIXTURE_PORT: 1234, +}; +const FIXTURE_CODE_VARS = ['FIXTURE_FLAG', 'FIXTURE_PORT', 'FIXTURE_SECRET']; + +interface EnvFixture { + name: string; + expectClean: boolean; + mutate: (files: Record, defaults: Map) => void; +} + +/** Cases `--self-test` runs; mutations are applied to the in-memory fixture. */ +export function createEnvExampleFixtures(): EnvFixture[] { + return [ + { name: 'consistent template', expectClean: true, mutate: () => {} }, + { + name: 'env var missing from the template', + expectClean: false, + mutate: (files) => { + files[ENV_EXAMPLE_FILE] = files[ENV_EXAMPLE_FILE]!.replace('FIXTURE_FLAG=false\n', ''); + }, + }, + { + name: 'template key no code reads', + expectClean: false, + mutate: (files) => { + files[ENV_EXAMPLE_FILE] = files[ENV_EXAMPLE_FILE]!.replace('FIXTURE_SECRET=\n', 'FIXTURE_SECRET=\nNOT_READ_BY_CODE=1\n'); + }, + }, + { + name: 'documented default contradicts the code', + expectClean: false, + mutate: (_files, defaults) => { + defaults.set('FIXTURE_PORT', '4321'); + }, + }, + { + name: 'commented-out key still counts as documented', + expectClean: true, + mutate: (files) => { + files[ENV_EXAMPLE_FILE] = files[ENV_EXAMPLE_FILE]!.replace('FIXTURE_SECRET=\n', '# FIXTURE_SECRET=\n'); + }, + }, + { + name: 'stale key no code reads', + expectClean: false, + mutate: (files) => { + files[ENV_EXAMPLE_FILE] = files[ENV_EXAMPLE_FILE]!.replace('FIXTURE_SECRET=\n', 'FIXTURE_SECRET=\nSTALE_KEY=1\n'); + }, + }, + ]; +} + +/** Runs every fixture through the checker and returns the unexpected behaviours. */ +export function runSelfTest(): { failures: string[]; cases: number } { + const failures: string[] = []; + const fixtures = createEnvExampleFixtures(); + for (const fixture of fixtures) { + const files: Record = { [ENV_EXAMPLE_FILE]: FIXTURE_ENV_EXAMPLE }; + const defaults = new Map(FIXTURE_DEFAULTS); + fixture.mutate(files, defaults); + let clean = false; + try { + const envExample = { keys: parseEnvExample(files[ENV_EXAMPLE_FILE]!), error: null as string | null }; + const { findings } = checkEnvExampleParity(envExample, FIXTURE_CODE_VARS, { + configDefault: (name) => FIXTURE_CODE_DEFAULTS[name], + documentedDefaults: defaults, + requireDocumentedDefaults: 2, + }); + clean = findings.length === 0; + } catch (error) { + clean = false; + if (fixture.expectClean) failures.push(`${fixture.name}: threw ${error instanceof Error ? error.message : String(error)}`); + } + if (clean !== fixture.expectClean) failures.push(`${fixture.name}: expected ${fixture.expectClean ? 'no drift' : 'drift'}, got ${clean ? 'no drift' : 'drift'}`); + } + return { failures, cases: fixtures.length }; +} + +function main(): void { + if (process.argv.includes('--self-test')) { + const { failures, cases } = runSelfTest(); + for (const failure of failures) console.error(`FAIL ${failure}`); + if (failures.length === 0) { + console.log(`check-env-example self-test passed (${cases} fixture(s)).`); + return; + } + console.error(`check-env-example self-test failed: ${failures.length} of ${cases} fixture(s) behaved unexpectedly.`); + process.exitCode = 1; + return; + } + + const envExample = loadEnvExample(ROOT); + const docText = DOC_FILES.map((file) => readFileSync(join(ROOT, file), 'utf8')).join('\n'); + const { findings, compared } = checkEnvExampleParity(envExample, collectEnvVarUsage(ROOT).keys(), { + configDefault: (name) => collectConfigDefaults(ROOT).get(name), + documentedDefaults: collectDocumentedDefaults(docText), + requireDocumentedDefaults: MIN_DOCUMENTED_DEFAULTS, + }); + console.log(`${ENV_EXAMPLE_FILE} ↔ config parity check\n`); + console.log( + `Checked ${envExample.keys.size} template key(s), ${collectEnvVarUsage(ROOT).size} env var(s) and ${compared} documented default(s).\n`, + ); + if (findings.length === 0) { + console.log('No drift found.'); + return; + } + for (const finding of findings) console.log(` - ${finding.message}`); + console.error(`\n${findings.length} env parity drift item(s) found.`); + process.exitCode = 1; +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/scripts/e2e.ts b/scripts/e2e.ts index 86fc7df..42c4846 100644 --- a/scripts/e2e.ts +++ b/scripts/e2e.ts @@ -1,6 +1,6 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { mkdtempSync, rmSync } from 'node:fs'; -import { request as httpRequest } from 'node:http'; +import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse } from 'node:http'; import { createServer as createNetServer } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -230,7 +230,13 @@ interface SseFeed { close: () => void; } -/** Subscribes to `/admin/api/events` and collects decoded frames until `close()`. */ +/** + * Subscribes to `/admin/api/events`, collects decoded frames until `close()` and + * resolves only after the first frame arrived. The endpoint pushes an initial `stats` + * frame on connect *after* registering its `request:start`/`request:end` listeners, so + * waiting for it is a deterministic readiness signal — no `sleep()` guesswork, which + * used to race the listener registration. + */ async function openEventFeed(): Promise { const controller = new AbortController(); const events: Array<{ event: string; data: Record }> = []; @@ -239,6 +245,12 @@ async function openEventFeed(): Promise { const reader = response.body!.getReader(); const decoder = new TextDecoder(); let buffer = ''; + let markReady = (): void => {}; + let failReady = (error: Error): void => {}; + const ready = new Promise((resolve, reject) => { + markReady = resolve; + failReady = reject; + }); void (async () => { try { for (;;) { @@ -259,13 +271,17 @@ async function openEventFeed(): Promise { /* non-JSON frame */ } } + if (events.length > 0) markReady(); index = buffer.indexOf('\n\n'); } } - } catch { - /* aborted */ + // The stream ended before any frame arrived: the listener may never have attached. + if (events.length === 0) failReady(new Error('events stream closed before the first frame arrived')); + } catch (error) { + if (events.length === 0) failReady(error instanceof Error ? error : new Error(String(error))); } })(); + await ready; return { events, close: () => controller.abort() }; } @@ -392,6 +408,8 @@ interface ApiOptions { method?: string; body?: unknown; auth?: boolean; + /** Raw headers merged over the normal ones (Origin/Sec-Fetch-Site probes). */ + headers?: Record; } async function admin(path: string, options: ApiOptions = {}): Promise { @@ -400,7 +418,7 @@ async function admin(path: string, options: ApiOptions = {}): Promise if (options.auth !== false && cookie) headers.cookie = cookie; return fetch(`${BASE}/admin/api${path}`, { method: options.method ?? (options.body !== undefined ? 'POST' : 'GET'), - headers, + headers: { ...headers, ...(options.headers ?? {}) }, body: options.body === undefined ? undefined : JSON.stringify(options.body), }); } @@ -476,11 +494,179 @@ function cookieAttribute(setCookie: string | null, name: string): string | null return null; } +/* -------------------------------------------------------- recording upstream */ + +/** + * D-16: a local upstream that *records* what the gateway actually forwarded. + * + * The deterministic mocks answer canonical payloads but cannot prove query-string + * forwarding (A-08), header-allowlist behaviour (A-09), error-body scrubbing (A-05) + * or the response-size cap (A-06), because those are properties of the request the + * provider receives and of an arbitrary response body. This server runs inside the + * e2e process, so its request log is inspectable without another control channel. + */ +interface RecordedCall { + method: string; + url: string; + path: string; + headers: Record; + body: string; + userAgent: string; +} + +interface RecorderResponse { + /** HTTP status for every response (default 200). */ + status?: number; + /** Raw response body. Defaults to a JSON echo of the request (the sync catalog). */ + body?: string; + contentType?: string; + /** Extra response headers (e.g. `retry-after`). */ + headers?: Record; + /** Delay before responding, used to keep a request in flight (activeRequests). */ + delayMs?: number; +} + +interface RecordingUpstream { + port: number; + /** `http://127.0.0.1:/v1` — a valid provider base URL for these tests. */ + base: string; + calls: RecordedCall[]; + configure: (next: RecorderResponse) => void; + reset: () => void; + /** Recorded calls from one check, isolated by the marker user-agent. */ + callsFor: (marker: string) => RecordedCall[]; + /** Recorded calls matching a path (the gateway replaces the client user-agent). */ + callsByPath: (path: string) => RecordedCall[]; + close: () => Promise; +} + +/** The payload the sync path recognizes as a catalog (A-16/B-05). */ +const RECORDED_MODELS = { + object: 'list', + data: [ + { + id: 'recorded/model-one', + name: 'Recorded One', + context_length: 4096, + max_output_tokens: 1024, + capabilities: { tools: false, input: ['text'], output: ['text'], temperature: true }, + reasoning: { supported: false, efforts: [], default_effort: null }, + }, + ], +}; + +async function startRecordingUpstream(): Promise { + const port = await freePort(); + const calls: RecordedCall[] = []; + let response: RecorderResponse = {}; + + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { + res.on('error', () => undefined); + const body = await new Promise((resolve) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + req.on('error', () => resolve('')); + }); + const rawUrl = req.url ?? '/'; + const path = rawUrl.split('?')[0] ?? '/'; + + if (path === '/__recorder') { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ calls, response })); + return; + } + if (path === '/__recorder/reset') { + calls.length = 0; + response = {}; + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"ok":true}'); + return; + } + + const headers: Record = {}; + for (const [key, value] of Object.entries(req.headers)) { + if (typeof value === 'string') headers[key] = value; + else if (Array.isArray(value)) headers[key] = value.join(', '); + } + calls.push({ + method: req.method ?? 'GET', + url: rawUrl, + path, + headers, + body, + userAgent: headers['user-agent'] ?? '', + }); + + if (response.delayMs !== undefined) await sleep(response.delayMs); + const status = response.status ?? 200; + const payload = + response.body ?? + JSON.stringify({ + // Echoed back so a test can assert what the provider actually received. + receivedUrl: rawUrl, + receivedMethod: req.method ?? 'GET', + ...(path.endsWith('/models') ? RECORDED_MODELS : {}), + }); + res.writeHead(status, { + 'content-type': response.contentType ?? 'application/json', + 'content-length': Buffer.byteLength(payload), + ...(response.headers ?? {}), + }); + res.end(payload); + }); + await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)); + + return { + port, + base: `http://127.0.0.1:${port}/v1`, + calls, + configure: (next) => { + response = next; + }, + reset: () => { + calls.length = 0; + response = {}; + }, + callsFor: (marker) => calls.filter((call) => call.userAgent === marker), + callsByPath: (path) => calls.filter((call) => call.path === path), + close: () => + new Promise((resolve) => + server.close(() => { + // Keep-alive sockets from the gateway would otherwise hold the close open. + server.closeAllConnections?.(); + resolve(); + }), + ), + }; +} + +/** + * Creates a provider pointed at the recording upstream, runs `fn` with only that + * provider enabled (so rotation order is deterministic), then removes it. + */ +async function withRecorderProvider( + recorder: RecordingUpstream, + id: string, + fn: (provider: { id: string; base: string }) => Promise, + baseUrl = recorder.base, +): Promise { + await adminJson('/providers', { + body: { id, name: `Recorder ${id}`, baseUrl, apiKey: MOCK_KEY, enabled: true, priority: 0 }, + }); + try { + await withOnlyProviders([id], () => fn({ id, base: baseUrl })); + } finally { + await adminJson(`/providers/${id}`, { method: 'DELETE' }).catch(() => undefined); + } +} + /* ---------------------------------------------------------------------- main */ async function main(): Promise { const dataDir = mkdtempSync(join(tmpdir(), 'okr-e2e-')); const children: ChildProcess[] = []; + let recorder: RecordingUpstream | null = null; try { // Fail fast (and with a usable message) when a stray process holds a fixed port. await Promise.all([assertPortFree(PORT), assertPortFree(MOCK_A_PORT), assertPortFree(MOCK_B_PORT)]); @@ -497,6 +683,7 @@ async function main(): Promise { waitForReady(`${BASE}/health`, server, 'server'), ]); console.log(`\nOpenCode Router e2e — server ${BASE}, mocks ${MOCK_A} / ${MOCK_B}, data ${dataDir}\n`); + recorder = await startRecordingUpstream(); /* ------------------------------------------------------------ routing/health */ await check('GET /health', async () => { @@ -790,9 +977,9 @@ async function main(): Promise { }); await check('unauthenticated malformed JSON: 401 missing_api_key, one log row, one start/end pair', async () => { + // openEventFeed resolves on the initial `stats` frame, i.e. after the endpoint + // registered its lifecycle listeners; no sleep-based race remains. const feed = await openEventFeed(); - // Give the SSE listener a moment to attach before the request fires. - await sleep(200); const marker = `e2e-reject-${Date.now()}`; try { const before = await logTotal(); @@ -1005,6 +1192,231 @@ async function main(): Promise { } }); + /* ------------------------------------------- D-16 recorded-upstream checks */ + // These use the in-process recording upstream: what matters is the exact request + // the gateway forwarded (query string, headers), which the canned mocks cannot see. + await check('A-08: the client query string reaches the upstream', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + let detail = ''; + await withRecorderProvider(upstream, 'rec-query', async () => { + const response = await gateway('/v1/messages?beta=true', { + body: { model: MODEL, max_tokens: 8, messages: [{ role: 'user', content: 'ping' }] }, + userAgent: 'e2e-a08', + }); + assert(response.ok, `status ${response.status}`); + // The gateway sends its own upstream user-agent, so match on the path. + const calls = upstream.callsByPath('/v1/messages'); + assert(calls.length === 1, `expected 1 upstream call, got ${calls.length}`); + assert(calls[0]!.url === '/v1/messages?beta=true', `upstream received ${calls[0]!.url}`); + detail = `upstream url=${calls[0]!.url}`; + }); + return detail; + }); + + await check('A-08: a query already on the provider base URL is preserved', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + let detail = ''; + // The provider base URL itself carries a query: joining must append with `&`. + await withRecorderProvider( + upstream, + 'rec-query-base', + async () => { + const response = await gateway('/v1/messages', { + body: { model: MODEL, max_tokens: 8, messages: [{ role: 'user', content: 'ping' }] }, + userAgent: 'e2e-a08-base', + }); + assert(response.ok, `status ${response.status}`); + const calls = upstream.callsByPath('/v1/messages'); + assert(calls.length === 1, `expected 1 upstream call, got ${calls.length}`); + const url = calls[0]!.url; + assert(url.includes('key=abc'), `base query lost: ${url}`); + assert(!url.includes('?key=abc?'), `second "?" instead of "&": ${url}`); + assert(url.startsWith('/v1/messages?'), `path/query join broken: ${url}`); + detail = `upstream url=${url}`; + }, + `http://127.0.0.1:${upstream.port}/v1?key=abc`, + ); + return detail; + }); + + await check('A-09: attribution headers reach the upstream and credentials never do', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + let detail = ''; + await withRecorderProvider(upstream, 'rec-headers', async () => { + const response = await fetch(`${BASE}/v1/chat/completions`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${gatewayKey}`, + 'user-agent': 'e2e-a09', + 'openai-organization': 'org-e2e', + 'openai-project': 'proj-e2e', + 'http-referer': 'https://ref.example/app', + 'x-title': 'e2e-title', + }, + body: JSON.stringify({ model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }), + }); + assert(response.ok, `status ${response.status}`); + const calls = upstream.callsByPath('/v1/chat/completions'); + assert(calls.length === 1, `expected 1 upstream call, got ${calls.length}`); + const headers = calls[0]!.headers; + for (const [name, expected] of [ + ['openai-organization', 'org-e2e'], + ['openai-project', 'proj-e2e'], + ['http-referer', 'https://ref.example/app'], + ['x-title', 'e2e-title'], + ] as const) { + assert(headers[name] === expected, `${name} not forwarded (got ${headers[name] ?? 'none'})`); + } + // The gateway key is a gateway credential, not the provider key; the upstream + // must only ever see the provider's own key. + assert(headers.authorization === `Bearer ${MOCK_KEY}`, `authorization=${headers.authorization}`); + assert(headers['x-api-key'] === MOCK_KEY, `x-api-key=${headers['x-api-key']}`); + assert( + !JSON.stringify(headers).includes(gatewayKey), + 'the gateway API key was forwarded to the provider', + ); + detail = '4 attribution headers forwarded; gateway key never forwarded'; + }); + return detail; + }); + + await check('A-05: an echoed provider key is redacted and an unknown type normalized', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + // The provider echoes the credential it received and claims a bogus error type. + // The `{type:'error', error:{type}}` envelope is the shape whose inner type is + // normalized, so this exercises the unknown-type → `api_error` branch. + upstream.configure({ + status: 401, + body: JSON.stringify({ + type: 'error', + error: { message: `bad credentials: ${MOCK_KEY}`, type: 'totally_unknown_type' }, + }), + }); + let detail = ''; + await withRecorderProvider(upstream, 'rec-scrub', async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + userAgent: 'e2e-a05-scrub', + }); + const body = (await response.json()) as { error?: { message?: string; type?: string } }; + assert(response.status === 401, `expected 401, got ${response.status}`); + assert(!JSON.stringify(body).includes(MOCK_KEY), `the provider key leaked to the client: ${JSON.stringify(body)}`); + assert(body.error?.message?.includes('[redacted]'), `message was not scrubbed: ${body.error?.message}`); + assert(body.error?.type === 'api_error', `unknown upstream type was not normalized: ${body.error?.type}`); + const row = await findLogByUserAgent('e2e-a05-scrub'); + assert(row, 'the failed request was never logged'); + const detailRow = await adminJson<{ log: { errorMessage: string | null } }>(`/logs/${row.id}`); + assert( + !(detailRow.log.errorMessage ?? '').includes(MOCK_KEY), + `the persisted error message kept the key: ${detailRow.log.errorMessage}`, + ); + assert( + (detailRow.log.errorMessage ?? '').includes('[redacted]'), + `the persisted error message was not scrubbed: ${detailRow.log.errorMessage}`, + ); + detail = 'client + request_logs scrubbed, type api_error'; + }); + upstream.reset(); + return detail; + }); + + await check('A-05: an oversized upstream message is clamped to 500 chars', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + const huge = `CLAMP-MARKER-${'x'.repeat(200_000)}`; + upstream.configure({ status: 500, body: JSON.stringify({ error: { message: huge, type: 'api_error' } }) }); + let detail = ''; + await withRecorderProvider(upstream, 'rec-clamp', async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + userAgent: 'e2e-a05-clamp', + }); + const body = (await response.json()) as { error?: { message?: string } }; + assert(body.error?.message, 'expected an error message'); + assert(body.error.message.length <= 500, `client message is ${body.error.message.length} chars`); + assert(body.error.message.length > 100, `message was over-truncated: ${body.error.message.length} chars`); + const row = await findLogByUserAgent('e2e-a05-clamp'); + assert(row, 'the clamped failure was never logged'); + const detailRow = await adminJson<{ log: { errorMessage: string | null } }>(`/logs/${row.id}`); + const persisted = detailRow.log.errorMessage ?? ''; + assert(persisted.length <= 500, `persisted message is ${persisted.length} chars (max 500)`); + assert(!persisted.includes('xxxxx'.repeat(200)), 'the 200 kB message was persisted unclamped'); + detail = `client=${body.error.message.length} chars, persisted=${persisted.length} chars`; + }); + upstream.reset(); + return detail; + }); + + await check('A-06: upstream_response_max_bytes aborts a larger buffered body with 502', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + upstream.reset(); + const large = JSON.stringify({ object: 'chat.completion', padding: 'y'.repeat(4_000) }); + upstream.configure({ status: 200, body: large }); + await adminJson('/settings', { method: 'PATCH', body: { upstream_response_max_bytes: '1024' } }); + try { + let detail = ''; + await withRecorderProvider(upstream, 'rec-cap', async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + userAgent: 'e2e-a06-cap', + }); + const body = (await response.json()) as { error?: { code?: string; message?: string } }; + assert(response.status === 502, `expected 502, got ${response.status}: ${JSON.stringify(body).slice(0, 200)}`); + assert(body.error?.code === 'upstream_response_too_large', `unexpected code ${body.error?.code}`); + assert( + (body.error?.message ?? '').includes('upstream_response_max_bytes'), + `message does not name the setting: ${body.error?.message}`, + ); + const row = await findLogByUserAgent('e2e-a06-cap'); + assert(row, 'the capped response was never logged'); + assert(row.status === 502, `log status=${row.status}`); + assert(row.errorCode === 'upstream_response_too_large' || row.errorCode === 'api_error', `log code=${row.errorCode}`); + detail = `502 ${body.error?.code} for a ${large.length}-byte body (cap 1024)`; + }); + return detail; + } finally { + await adminJson('/settings', { method: 'PATCH', body: { upstream_response_max_bytes: '0' } }); + upstream.reset(); + } + }); + + await check('A-07: a mixed-line-ending (\\r\\n\\n) SSE frame is forwarded without stalling', async () => { + await mockControl(MOCK_A_PORT, { frameTerminator: '\r\n\n' }); + try { + const startedAt = Date.now(); + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'Count from 1 to 2.' }], stream: true, max_tokens: 8 }, + userAgent: 'e2e-a07-mixed-eol', + }); + const text = await response.text(); + const elapsed = Date.now() - startedAt; + assert(response.ok, `status ${response.status}`); + // If `\r\n\n` were not recognized, frames would buffer until the idle timeout + // (`stream_idle_timeout_ms`); a fast, complete body proves the scanner worked. + const frames = text.split('\r\n\n').filter((frame) => frame.includes('data:')).length; + assert(frames >= 3, `expected >=3 frames terminated by \\r\\n\\n, got ${frames}`); + assert(text.includes('chat.completion.chunk'), 'mixed-EOL stream lost its chat chunks'); + assert(elapsed < 5_000, `mixed-EOL stream took ${elapsed}ms; frames likely stalled on \\n\\n`); + const row = await findLogByUserAgent('e2e-a07-mixed-eol'); + assert(row, 'the mixed-EOL stream was not logged'); + assert(row.ok === true && row.status === 200, `log status=${row.status} ok=${row.ok}`); + return `${frames} frames in ${elapsed}ms, one log row`; + } finally { + await mockControl(MOCK_A_PORT, { reset: true }); + } + }); + /* ------------------------------------------------------ OpenAI responses */ await check('responses API (non-stream)', async () => { const response = await gateway('/v1/responses', { body: { model: MODEL, input: 'Say the word: responses' } }); @@ -1538,6 +1950,83 @@ async function main(): Promise { } }); + await check('A-14: an upstream 501 (any 5xx) fails over to the next provider', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + await mockControl(MOCK_B_PORT, { reset: true }); + upstream.reset(); + // 501 is not in the old retry list, so this fails over only if every 5xx is retryable. + upstream.configure({ status: 501, body: JSON.stringify({ error: { message: 'not implemented', type: 'api_error' } }) }); + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'priority' } }); + await adminJson('/providers', { + body: { id: 'fo501-a', name: 'FO501 A', baseUrl: upstream.base, apiKey: MOCK_KEY, priority: 1 }, + }); + await adminJson('/providers', { body: { id: 'fo501-b', name: 'FO501 B', baseUrl: MOCK_B, apiKey: MOCK_KEY, priority: 2 } }); + try { + let detail = ''; + await withOnlyProviders(['fo501-a', 'fo501-b'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> }; + assert(response.ok, `expected failover success, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert((body.choices?.[0]?.message?.content ?? '').includes('mockB'), 'the healthy provider did not serve the failover'); + const attempts = Number(response.headers.get('x-opencode-router-attempts')); + assert(attempts === 2, `expected 2 attempts, got ${attempts}`); + assert( + response.headers.get('x-opencode-router-provider') === 'fo501-b', + `served by ${response.headers.get('x-opencode-router-provider')}`, + ); + detail = '501 → next provider, attempts=2'; + }); + return detail; + } finally { + upstream.reset(); + await adminJson('/settings', { method: 'PATCH', body: { rotation_strategy: 'round-robin' } }); + await adminJson('/providers/fo501-a', { method: 'DELETE' }); + await adminJson('/providers/fo501-b', { method: 'DELETE' }); + } + }); + + await check('A-13: wrong method → 405 + Allow, unknown path → 404, one log row each', async () => { + const before = await logTotal(); + + const put = await fetch(`${BASE}/v1/chat/completions`, { + method: 'PUT', + headers: { 'content-type': 'application/json', authorization: `Bearer ${gatewayKey}`, 'user-agent': 'e2e-a13-put' }, + body: JSON.stringify({ model: MODEL, messages: [{ role: 'user', content: 'ping' }] }), + }); + const putBody = (await put.json()) as { error?: { code?: string } }; + assert(put.status === 405, `PUT expected 405, got ${put.status}: ${JSON.stringify(putBody)}`); + assert(put.headers.get('allow') === 'POST', `PUT Allow=${put.headers.get('allow')}`); + assert(putBody.error?.code === 'method_not_allowed', `PUT code=${putBody.error?.code}`); + + const options = await fetch(`${BASE}/v1/chat/completions`, { + method: 'OPTIONS', + headers: { authorization: `Bearer ${gatewayKey}`, 'user-agent': 'e2e-a13-options' }, + }); + await options.text(); + assert(options.status === 405, `OPTIONS expected 405, got ${options.status}`); + assert(options.headers.get('allow') === 'POST', `OPTIONS Allow=${options.headers.get('allow')}`); + + const unknown = await fetch(`${BASE}/v1/nope`, { + method: 'GET', + headers: { authorization: `Bearer ${gatewayKey}`, 'user-agent': 'e2e-a13-unknown' }, + }); + const unknownBody = (await unknown.json()) as { error?: { code?: string } }; + assert(unknown.status === 404, `GET /v1/nope expected 404, got ${unknown.status}`); + assert(unknownBody.error?.code === 'unknown_endpoint', `nope code=${unknownBody.error?.code}`); + assert(unknown.headers.get('allow') === null, 'unknown paths must not advertise Allow'); + + // Three requests, three log rows: the catch-all must not duplicate rows. + const after = await waitForLogTotalStable(before + 3); + assert(after === before + 3, `expected exactly 3 new log rows, delta=${after - before}`); + const putRow = await findLogByUserAgent('e2e-a13-put'); + assert(putRow, 'the 405 response was never logged'); + assert(putRow.status === 405 && putRow.errorCode === 'method_not_allowed', `405 row status=${putRow.status} code=${putRow.errorCode}`); + return 'PUT/OPTIONS 405 + Allow: POST, GET /v1/nope 404, 3 log rows'; + }); + await check('short request_timeout_ms → 504 upstream_timeout, logged and attributed', async () => { await mockControl(MOCK_A_PORT, { reset: true }); await mockControl(MOCK_A_PORT, { delayMs: 5_000 }); @@ -1600,17 +2089,64 @@ async function main(): Promise { } }); + await check('A-01: retry-after is clamped to one hour', async () => { + await mockControl(MOCK_A_PORT, { reset: true }); + // Beyond the cap: an hour of cooldown is the documented maximum. + await mockControl(MOCK_A_PORT, { retryAfterSeconds: 31_536_000 }); + await adminJson('/settings', { method: 'PATCH', body: { provider_cooldown_ms: '1000' } }); + await adminJson('/providers', { body: { id: 'ra-clamp', name: 'RA Clamp', baseUrl: MOCK_A, apiKey: MOCK_KEY, priority: 1 } }); + try { + let detail = ''; + await withOnlyProviders(['ra-clamp'], async () => { + const response = await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'retry after clamp' }], max_tokens: 8 }, + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 429, `expected 429, got ${response.status}: ${JSON.stringify(body).slice(0, 150)}`); + assert(body.error?.code === 'all_providers_rate_limited', `unexpected code ${body.error?.code}`); + assert(response.headers.get('retry-after') === '3600', `retry-after=${response.headers.get('retry-after')}`); + const list = await adminJson<{ providers: Array<{ id: string; cooldownUntil: number | null }> }>('/providers'); + const row = list.providers.find((provider) => provider.id === 'ra-clamp'); + assert(row?.cooldownUntil !== null && row?.cooldownUntil !== undefined, 'no cooldown was recorded'); + const remaining = row.cooldownUntil - Date.now(); + assert(remaining <= 3_600_000 + 5_000, `cooldown=${remaining}ms exceeds the one-hour cap`); + assert(remaining > 3_500_000, `cooldown=${remaining}ms is not ~1h; the raw value was not clamped`); + detail = `retry-after 31536000s → cooldown ${Math.round(remaining / 1000)}s (cap 3600s)`; + }); + return detail; + } finally { + // Disable before resetting the mock: otherwise the recovery sweep would probe it. + await adminJson('/providers/ra-clamp', { method: 'PATCH', body: { enabled: false } }); + await mockControl(MOCK_A_PORT, { reset: true }); + await adminJson('/providers/ra-clamp', { method: 'DELETE' }); + await adminJson('/settings', { method: 'PATCH', body: { provider_cooldown_ms: '60000' } }); + } + }); + await check('all providers dead → 502 all_providers_failed', async () => { await adminJson('/providers/primary', { method: 'PATCH', body: { baseUrl: DEAD_UPSTREAM } }); await adminJson('/providers/secondary', { method: 'PATCH', body: { baseUrl: DEAD_UPSTREAM } }); try { const response = await gateway('/v1/chat/completions', { body: { model: MODEL, messages: [{ role: 'user', content: 'nobody home' }], max_tokens: 8 }, + userAgent: 'e2e-a02-total-failure', }); const body = (await response.json()) as { error?: { code?: string } }; assert(response.status === 502, `expected 502, got ${response.status}`); assert(body.error?.code === 'all_providers_failed', `unexpected code ${body.error?.code}`); - return '502 all_providers_failed'; + // A-02: real attempts happened, so the aggregated failure must stay attributed. + const attempts = Number(response.headers.get('x-opencode-router-attempts')); + assert(attempts >= 1, `attempts header=${response.headers.get('x-opencode-router-attempts')}`); + const providerId = response.headers.get('x-opencode-router-provider'); + assert(providerId === 'secondary', `provider header=${providerId}, expected the last attempted provider`); + assert(response.headers.get('x-opencode-router-name') === 'Mock B', `name header=${response.headers.get('x-opencode-router-name')}`); + assert(response.headers.get('x-opencode-router-request-id'), 'missing request id header'); + const row = await findLogByUserAgent('e2e-a02-total-failure'); + assert(row, 'the aggregated failure was never logged'); + assert(row.status === 502 && row.errorCode === 'all_providers_failed', `row status=${row.status} code=${row.errorCode}`); + assert(row.providerId === 'secondary', `log providerId=${row.providerId}, expected the last attempted provider`); + assert(row.attempts === attempts, `log attempts=${row.attempts} != header ${attempts}`); + return `502 attributed to secondary, attempts=${attempts}, 3 router headers`; } finally { await adminJson('/providers/primary', { method: 'PATCH', body: { baseUrl: MOCK_A } }); await adminJson('/providers/secondary', { method: 'PATCH', body: { baseUrl: MOCK_B } }); @@ -1695,8 +2231,56 @@ async function main(): Promise { return `requests=${body.totals.requests} tokens=${body.totals.tokensTotal} last60s=${body.requestsLast60s}/${body.errorsLast60s}`; }); + await check('A-03/B-17: activeRequests counts the whole gateway lifecycle and matches health', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + let detail = ''; + await withRecorderProvider(upstream, 'rec-active', async () => { + // A slow proxied call keeps the counter at 1 while it is in flight. + upstream.reset(); + upstream.configure({ delayMs: 1_500 }); + const slow = gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'ping slow' }], max_tokens: 8 }, + }); + await sleep(400); + const during = await adminJson<{ activeRequests: number; health: { activeRequests: number } }>('/stats?window=1h'); + assert(during.activeRequests === 1, `activeRequests during a proxied call=${during.activeRequests}, expected 1`); + // B-17: the cached body and the live health field must agree in one response. + assert( + during.health.activeRequests === during.activeRequests, + `health.activeRequests=${during.health.activeRequests} != activeRequests=${during.activeRequests}`, + ); + const response = await slow; + assert(response.ok, `slow request failed: ${response.status}`); + upstream.configure({}); + + // The models path uses the same gateway onRequest/onResponse counter. It answers + // from the local catalog, so a single in-flight sample races the handler; assert + // the invariants that are observable from HTTP: the burst never drives the + // counter negative and it returns to 0 when the gateway is idle again. + const modelsResponses = await Promise.all( + Array.from({ length: 12 }, () => + fetch(`${BASE}/v1/models`, { headers: { authorization: `Bearer ${gatewayKey}`, connection: 'keep-alive' } }), + ), + ); + assert(modelsResponses.every((entry) => entry.status === 200), 'a models request failed'); + await Promise.all(modelsResponses.map((entry) => entry.text())); + const idleDeadline = Date.now() + 3_000; + let idle = 99; + while (Date.now() < idleDeadline) { + idle = (await adminJson<{ activeRequests: number }>('/stats?window=1h')).activeRequests; + if (idle === 0) break; + await sleep(100); + } + assert(idle === 0, `activeRequests after completion=${idle}, expected 0 (never negative)`); + detail = '1 during a slow proxied call (health agrees), 0 after; 12 models requests left it at 0'; + }); + return detail; + }); + await check('request detail exposes attempt timeline', async () => { - const logs = await adminJson<{ logs: Array<{ id: string; attempts: number }> }>('/logs?limit=50'); + // Look past recent non-proxied rows (models, 405s) for one with attempts. + const logs = await adminJson<{ logs: Array<{ id: string; attempts: number }> }>('/logs?limit=500'); const target = logs.logs.find((log) => log.attempts > 0); assert(target, 'no proxied log rows with attempts recorded'); const detail = await adminJson<{ attempts: Array<{ providerId: string; ok: boolean }> }>(`/logs/${target.id}`); @@ -1723,6 +2307,13 @@ async function main(): Promise { /* aborted */ } })(); + // Wait for the deterministic initial frame instead of racing listener attach. + let ready = false; + for (let attempt = 0; attempt < 100 && !ready; attempt += 1) { + ready = events.join('').includes('event: stats'); + if (!ready) await new Promise((resolve) => setTimeout(resolve, 20)); + } + assert(ready, 'events endpoint never delivered its initial stats frame'); await gateway('/v1/chat/completions', { body: { model: MODEL, messages: [{ role: 'user', content: 'live event ping' }], max_tokens: 8 }, }); @@ -1737,6 +2328,55 @@ async function main(): Promise { return 'received request:start + request:end'; }); + await check('A-11: an oversized body returns 413 payload_too_large with no FST_ERR_ code', async () => { + let detail = ''; + await withAltServer({ BODY_LIMIT: '512' }, async (base) => { + const altCookie = await altLogin(base); + // The gateway refuses traffic without a key; create one on this throw-away server. + const keyResponse = await fetch(`${base}/admin/api/keys`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: altCookie }, + body: JSON.stringify({ name: 'a11' }), + }); + assert(keyResponse.ok, `creating the alt gateway key failed: ${keyResponse.status}`); + const altGatewayKey = ((await keyResponse.json()) as { plaintext: string }).plaintext; + const altJson = async (path: string): Promise => { + const response = await fetch(`${base}/admin/api${path}`, { headers: { cookie: altCookie } }); + assert(response.ok, `alt ${path} → ${response.status}`); + return (await response.json()) as T; + }; + const before = (await altJson<{ total: number }>('/logs?limit=1')).total; + const response = await fetch(`${base}/v1/chat/completions`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${altGatewayKey}`, 'user-agent': 'e2e-a11-413' }, + body: JSON.stringify({ model: MODEL, messages: [{ role: 'user', content: 'z'.repeat(2_000) }] }), + }); + const text = await response.text(); + assert(response.status === 413, `expected 413, got ${response.status}: ${text.slice(0, 200)}`); + const body = JSON.parse(text) as { error?: { code?: string; message?: string } }; + assert(body.error?.code === 'payload_too_large', `unexpected code ${body.error?.code}`); + assert(body.error?.message?.includes('512'), `message does not state the configured limit: ${body.error?.message}`); + assert(!text.includes('FST_ERR_'), `the Fastify internal error code leaked: ${text.slice(0, 200)}`); + + // Exactly one request_logs row, written by the gateway error handler. + const deadline = Date.now() + 5_000; + let total = before; + while (Date.now() < deadline) { + total = (await altJson<{ total: number }>('/logs?limit=1')).total; + if (total >= before + 1) break; + await sleep(100); + } + assert(total === before + 1, `expected exactly one new log row, delta=${total - before}`); + const logs = await altJson<{ logs: Array<{ status: number; errorCode: string | null; userAgent: string | null }> }>('/logs?limit=10'); + const row = logs.logs.find((entry) => entry.userAgent === 'e2e-a11-413'); + assert(row, 'the 413 request was never logged'); + assert(row.status === 413, `log status=${row.status}, expected 413`); + assert(row.errorCode === 'payload_too_large', `log errorCode=${row.errorCode}`); + detail = '413 payload_too_large, no FST_ERR_ string, one log row'; + }); + return detail; + }); + /* ----------------------------------------------------------------- settings */ await check('settings patch + read back (no hash leak)', async () => { await adminJson('/settings', { method: 'PATCH', body: { max_retries: '3', log_retention_days: '7' } }); @@ -1821,11 +2461,20 @@ async function main(): Promise { const line = text.split('\r\n').find((entry) => entry.includes(marker)); assert(line, 'marker user-agent missing from the CSV export'); assert(line.includes(`'${marker}`), `formula cell was not prefixed with a quote: ${line}`); - assert(csv.headers.get('x-export-truncated') === null, 'unexpected truncation header below the 500-row cap'); const json = await admin('/logs/export?format=json'); const payload = (await json.json()) as { count: number; total: number; truncated: boolean }; - assert(payload.truncated === false, 'export claims truncation with fewer than 500 rows'); - assert(payload.count === payload.total, `count ${payload.count} != total ${payload.total}`); + // The export caps at 500 rows; this run is longer than that, so the flags must + // agree with the cap instead of pretending the export is complete. + if (payload.total > 500) { + assert(payload.truncated === true, `export claims no truncation with ${payload.total} rows`); + assert(payload.count === 500, `export count=${payload.count}, expected the 500-row cap`); + assert(csv.headers.get('x-export-truncated') === 'true', 'missing x-export-truncated on a capped export'); + } else { + assert(payload.truncated === false, 'export claims truncation below the cap'); + assert(payload.count === payload.total, `count ${payload.count} != total ${payload.total}`); + assert(csv.headers.get('x-export-truncated') === null, 'unexpected truncation header below the cap'); + } + assert(line, 'the marker row disappeared from the capped export'); return `'${marker} escaped; count=total=${payload.count}, truncated=false`; }); @@ -1950,7 +2599,358 @@ async function main(): Promise { assert(current.ok, `the current session was revoked (${current.status})`); return `revoked=${revoke.revoked}, stale cookie 401, current session intact`; }); + + /* ------------------------------------------------- D-16 admin/API coverage */ + + await check('B-20: /admin/api/diagnostics requires a session and reports the documented shape', async () => { + const unauth = await admin('/diagnostics', { auth: false }); + assert(unauth.status === 401, `unauthenticated diagnostics expected 401, got ${unauth.status}`); + + const report = await adminJson<{ + scheduler: { running: boolean; lastSyncAt: number | null; nextSyncInMs: number | null }; + storage: { + dbPath: string; + walSizeBytes: number; + dbSizeBytes: number; + busyTimeoutMs: number; + logRows: number; + attemptRows: number; + sessionRows: number; + oldestLogTs: number | null; + }; + checks: Array<{ id: string; status: string; detail: string }>; + }>('/diagnostics'); + + assert(report.scheduler.running === true, 'scheduler should be running'); + for (const [field, value] of Object.entries(report.storage)) { + if (field === 'dbPath') { + assert(typeof value === 'string' && value.length > 0, 'storage.dbPath missing'); + continue; + } + if (field === 'oldestLogTs') { + assert(value === null || typeof value === 'number', `storage.oldestLogTs=${String(value)}`); + continue; + } + assert(typeof value === 'number' && Number.isFinite(value), `storage.${field}=${String(value)}`); + } + assert(report.storage.logRows > 0, 'storage.logRows should count the traffic this run produced'); + assert(report.storage.busyTimeoutMs > 0, `storage.busyTimeoutMs=${report.storage.busyTimeoutMs} (B-04 pragma missing)`); + // The seven documented checks, in order (docs/SPEC.md §3). + assert( + report.checks.map((entry) => entry.id).join(',') === + 'password.default,providers.enabled,keys.active,models.enabled,version.schema,clock.skew,providers.cooldown', + `unexpected checks: ${report.checks.map((entry) => entry.id).join(',')}`, + ); + assert( + report.checks.every((entry) => entry.status === 'ok' || entry.status === 'warn' || entry.status === 'fail'), + 'every check needs an ok/warn/fail status', + ); + assert( + report.checks.every((entry) => typeof entry.detail === 'string' && entry.detail.length > 0), + 'every check needs a detail line', + ); + // This run uses the default password and has providers/keys/models configured, + // so only the password check is expected to warn. + const warns = report.checks.filter((entry) => entry.status !== 'ok').map((entry) => entry.id); + assert(warns.includes('password.default'), `expected password.default to warn, warns=${warns.join(',') || 'none'}`); + assert( + !JSON.stringify(report).includes(MOCK_KEY), + 'diagnostics leaked provider key material', + ); + return `401 unauth, 7 checks, warns=${warns.join(',')}`; + }); + + await check('B-20: diagnostics on a fresh DB reports the documented warn checks', async () => { + let detail = ''; + await withAltServer({}, async (base) => { + const altCookie = await altLogin(base); + const report = (await ( + await fetch(`${base}/admin/api/diagnostics`, { headers: { cookie: altCookie } }) + ).json()) as { scheduler: { running: boolean }; storage: { logRows: number }; checks: Array<{ id: string; status: string }> }; + assert(report.scheduler.running === true, 'fresh server scheduler not running'); + assert(report.storage.logRows === 0, `fresh DB has ${report.storage.logRows} log rows`); + const statuses = new Map(report.checks.map((entry) => [entry.id, entry.status])); + for (const id of ['password.default', 'providers.enabled', 'keys.active', 'models.enabled']) { + assert(statuses.get(id) === 'warn', `fresh DB check ${id}=${statuses.get(id)}, expected warn`); + } + assert(statuses.get('clock.skew') === 'ok', `fresh DB clock.skew=${statuses.get('clock.skew')}`); + detail = 'fresh DB warns on password/providers/keys/models'; + }); + return detail; + }); + + await check('B-15: cross-site mutations are rejected, same-origin and login are not', async () => { + const before = await adminJson<{ settings: Record }>('/settings'); + const originalRetention = before.settings.log_retention_days; + + const crossSite = await admin('/settings', { + method: 'PATCH', + body: { log_retention_days: '11' }, + headers: { origin: 'https://evil.example' }, + }); + const crossBody = (await crossSite.json()) as { error?: { code?: string } }; + assert(crossSite.status === 403, `cross-origin PATCH expected 403, got ${crossSite.status}`); + assert(crossBody.error?.code === 'cross_site_request', `unexpected code ${crossBody.error?.code}`); + const afterReject = await adminJson<{ settings: Record }>('/settings'); + assert( + afterReject.settings.log_retention_days === originalRetention, + `the rejected cross-site mutation still changed the setting (${afterReject.settings.log_retention_days})`, + ); + + const secFetch = await admin('/settings', { + method: 'PATCH', + body: { log_retention_days: '11' }, + headers: { 'sec-fetch-site': 'cross-site' }, + }); + await secFetch.text(); + assert(secFetch.status === 403, `Sec-Fetch-Site: cross-site expected 403, got ${secFetch.status}`); + + // Same-origin and header-less mutations keep working (curl, e2e, dashboard). + const sameOrigin = await admin('/settings', { + method: 'PATCH', + body: { log_retention_days: '12' }, + headers: { origin: `http://127.0.0.1:${PORT}` }, + }); + assert(sameOrigin.ok, `same-origin PATCH failed: ${sameOrigin.status}`); + const afterAllowed = await adminJson<{ settings: Record }>('/settings'); + assert(afterAllowed.settings.log_retention_days === '12', `same-origin PATCH did not apply: ${afterAllowed.settings.log_retention_days}`); + + const headerless = await admin('/settings', { method: 'PATCH', body: { log_retention_days: originalRetention ?? '30' } }); + assert(headerless.ok, `header-less PATCH failed: ${headerless.status}`); + + // The login endpoint must stay reachable cross-site (the guard covers sessions only). + const crossLogin = await admin('/login', { + body: { password: '123456' }, + auth: false, + headers: { origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' }, + }); + assert(crossLogin.ok, `cross-site login was gated: ${crossLogin.status}`); + return '403 cross_site_request (Origin + Sec-Fetch-Site), no state change; same-origin/header-less/login fine'; + }); + + await check('B-11: apiKey validation rejects control characters, newlines and over-long values', async () => { + const cases: Array<[label: string, apiKey: string]> = [ + ['control char', 'a\u0001b'], + ['newline', 'line\nbreak'], + ['over-long', 'k'.repeat(4_097)], + ]; + for (const [label, apiKey] of cases) { + const response = await admin('/providers', { + body: { id: `bad-key-${label.replace(/\W+/g, '-')}`, name: 'Bad Key', baseUrl: MOCK_A, apiKey }, + }); + const text = await response.text(); + assert(response.status === 400, `${label}: expected 400, got ${response.status}: ${text.slice(0, 200)}`); + // The rejection must never echo the submitted value. + assert(!text.includes(apiKey.slice(0, 20)), `${label}: the rejected apiKey was echoed back`); + assert(!text.includes('\u0001'), `${label}: a control character reached the response`); + } + // A clean key still saves. + const ok = await adminJson<{ provider: { id: string } }>('/providers', { + body: { id: 'good-key-e2e', name: 'Good Key', baseUrl: MOCK_A, apiKey: MOCK_KEY, enabled: false }, + }); + assert(ok.provider.id === 'good-key-e2e', 'a valid apiKey was rejected'); + await adminJson('/providers/good-key-e2e', { method: 'DELETE' }); + return '400 for control char / newline / 4097 chars, no echo; valid key accepted'; + }); + + await check('B-12: the SSRF guard rejects CGNAT, protocol-assignment and benchmarking ranges', async () => { + let detail = ''; + // The main harness allows private hosts for the loopback mocks; a throw-away + // server with the guard enabled is where the extended ranges are observable. + await withAltServer({}, async (base) => { + const altCookie = await altLogin(base); + const seen: string[] = []; + for (const [index, baseUrl] of ['http://100.64.0.1/v1', 'http://192.0.0.5/v1', 'http://198.18.0.7/v1'].entries()) { + const response = await fetch(`${base}/admin/api/providers`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: altCookie }, + body: JSON.stringify({ id: `ssrf-${index}`, name: 'SSRF', baseUrl, apiKey: MOCK_KEY }), + }); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 400, `${baseUrl} expected 400, got ${response.status}`); + assert(body.error?.code === 'invalid_request', `${baseUrl} code=${body.error?.code}`); + seen.push(baseUrl); + } + detail = `400 for ${seen.join(', ')}`; + }); + return detail; + }); + + await check('B-13: the shared sync/probe path refuses a stored loopback provider (SSRF guard)', async () => { + // Route-level creation guards are covered above; this proves the *shared* + // `syncProviderModels`/`probeAndRecord` path that the scheduler also calls. The + // row has to be persisted by a guard-disabled harness first (this one allows + // private hosts for its mocks), then read back by a server with the guard on. + let detail = ''; + const legacyId = 'legacy-loop'; + await adminJson('/providers', { + body: { id: legacyId, name: 'Legacy Loopback', baseUrl: `http://127.0.0.1:${MOCK_A_PORT}/v1`, apiKey: MOCK_KEY, enabled: true, priority: 0 }, + }); + try { + const altPort = Number(process.env.E2E_ALT_PORT ?? (await freePort())); + const alt = startServer(dataDir, { port: altPort, env: { PROVIDER_ALLOW_PRIVATE_HOSTS: 'false' } }); + collect(alt); + try { + await waitForReady(`http://127.0.0.1:${altPort}/health`, alt, `guarded server on ${altPort}`); + const altCookie = await altLogin(`http://127.0.0.1:${altPort}`); + const servedBefore = (await mockStats(MOCK_A_PORT)).served; + for (const path of ['/models/sync', '/providers/legacy-loop/sync-models']) { + const response = await fetch(`http://127.0.0.1:${altPort}/admin/api${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', cookie: altCookie }, + body: JSON.stringify(path === '/models/sync' ? { providerId: legacyId } : {}), + }); + const body = (await response.json()) as { error?: { code?: string; message?: string } }; + assert( + response.status === 400, + `${path} expected 400 from the SSRF guard, got ${response.status}: ${JSON.stringify(body).slice(0, 200)}`, + ); + assert(body.error?.code === 'invalid_request', `${path} code=${body.error?.code}`); + assert( + (body.error?.message ?? '').includes('PROVIDER_ALLOW_PRIVATE_HOSTS'), + `${path} message is not the SSRF guard message: ${body.error?.message}`, + ); + } + // The guard runs before the fetch: the mock upstream must see no traffic. + const servedAfter = (await mockStats(MOCK_A_PORT)).served; + assert(servedAfter === servedBefore, `the guarded sync reached the network (${servedBefore} → ${servedAfter})`); + detail = `both sync paths → 400 invalid_request, mock served ${servedBefore}→${servedAfter}`; + } finally { + await stop(alt); + } + } finally { + await adminJson(`/providers/${legacyId}`, { method: 'DELETE' }).catch(() => undefined); + } + return detail; + }); + + await check('B-05/B-06: sync handles an unrecognized catalog, prunes an explicit empty one, and covers every provider', async () => { + assert(recorder, 'recorder not started'); + const upstream = recorder; + let detail = ''; + upstream.reset(); + // Force a clean recorder state: earlier checks leave a canned status behind. + upstream.configure({ status: 200 }); + // Substantial endpoint: the recorder answers `/models` with a real catalog. + await adminJson('/providers', { + body: { id: 'rec-sync', name: 'Recorder Sync', baseUrl: upstream.base, apiKey: MOCK_KEY, enabled: true, priority: 0 }, + }); + const baseline = await adminJson<{ providers: Array<{ id: string }>; syncProviderId: string | null; syncedAt: number | null }>('/models'); + try { + // 1. `{}` is not an empty catalog: keep the rows and warn. + upstream.configure({ status: 200, body: '{}' }); + const unrecognized = await adminJson<{ warning?: string; total: number }>('/models/sync', { + body: { providerId: 'rec-sync' }, + }); + assert(unrecognized.warning, 'an unrecognized catalog must carry a warning'); + const afterUnrecognized = await adminJson<{ providers: Array<{ id: string }>; syncedAt: number | null }>('/models'); + assert( + afterUnrecognized.providers.length === baseline.providers.length, + `an unrecognized catalog pruned rows: ${baseline.providers.length} → ${afterUnrecognized.providers.length}`, + ); + + // 2. A real catalog first, so the prune below has rows to remove. + upstream.configure({ status: 200 }); + const populated = await adminJson<{ added: number; total: number }>('/models/sync', { body: { providerId: 'rec-sync' } }); + assert(populated.total > 0, `the recorder catalog was not synced: ${JSON.stringify(populated)}`); + + // 3. An explicit empty array is a legitimate empty catalog: it prunes. + upstream.configure({ status: 200, body: JSON.stringify({ data: [] }) }); + const pruned = await adminJson<{ removed: number; total: number; warning?: string }>('/models/sync', { + body: { providerId: 'rec-sync' }, + }); + assert(!pruned.warning, `an explicit empty catalog must not warn: ${pruned.warning}`); + assert(pruned.removed > 0, `expected the explicit empty catalog to prune, removed=${pruned.removed}`); + // Manual rows are never pruned, so count only the synced catalog rows. + const afterPrune = await adminJson<{ models: Array<{ id: string; source?: string }> }>('/models'); + const syncedAfter = afterPrune.models.filter((model) => model.id.startsWith('recorded/')); + assert(syncedAfter.length === 0, `synced catalog not emptied: ${syncedAfter.map((model) => model.id).join(',')}`); + + // 4. A bare sync covers every enabled provider (AD-17/B-06). + upstream.configure({}); + const all = await adminJson<{ providers: Array<{ providerId: string; ok: boolean }>; total: number }>('/models/sync', { + body: {}, + }); + assert(Array.isArray(all.providers) && all.providers.length >= 3, `expected >=3 provider outcomes, got ${all.providers?.length}`); + assert(all.providers.some((outcome) => outcome.providerId === 'rec-sync'), 'the recorder provider was not synced'); + assert(all.providers.every((outcome) => typeof outcome.ok === 'boolean'), 'each outcome needs an ok flag'); + detail = `{} kept ${afterUnrecognized.providers.length} rows + warning, {"data":[]} pruned ${pruned.removed}, bare sync covered ${all.providers.length} providers`; + } finally { + await adminJson('/providers/rec-sync', { method: 'DELETE' }); + // Restore the canonical catalog for the checks that follow. + await adminJson('/models/sync', { body: { providerId: 'primary' } }); + upstream.reset(); + } + return detail; + }); + + await check('B-16: /audit and /activity reject junk limits like /logs', async () => { + for (const path of ['/audit?limit=abc', '/audit?limit=-1', '/activity?limit=0', '/activity?limit=1000']) { + const response = await admin(path); + const body = (await response.json()) as { error?: { code?: string } }; + assert(response.status === 400, `${path} expected 400, got ${response.status}`); + assert(body.error?.code === 'invalid_request', `${path} code=${body.error?.code}`); + } + for (const path of ['/audit', '/audit?limit=20', '/activity?limit=20']) { + const response = await admin(path); + assert(response.ok, `${path} expected 200, got ${response.status}`); + } + return '400 for limit=abc/-1/0/1000, defaults still fine'; + }); + + await check('B-18: the log model filter is a case-insensitive contains match with literal % and _', async () => { + // Produce one chat request so a row with `opencode/flint-40b-free` exists now. + await gateway('/v1/chat/completions', { + body: { model: MODEL, messages: [{ role: 'user', content: 'model filter' }], max_tokens: 8 }, + userAgent: 'e2e-b18-model-filter', + }); + const contains = await adminJson<{ logs: Array<{ model: string | null }>; total: number }>('/logs?model=flint&limit=50'); + assert(contains.total > 0, 'model=flint matched nothing'); + // `limit` is capped at 50 per page, so the page carries min(total, 50) rows. + assert(contains.logs.length > 0, 'model=flint returned an empty page'); + assert( + contains.logs.length <= contains.total, + `page=${contains.logs.length} exceeds total=${contains.total}`, + ); + assert(contains.logs.length === Math.min(contains.total, 50), `page=${contains.logs.length} vs total=${contains.total}`); + assert( + contains.logs.every((row) => (row.model ?? '').toLowerCase().includes('flint')), + 'a contains filter returned a row without the substring', + ); + const upper = await adminJson<{ total: number }>('/logs?model=FLINT&limit=5'); + assert(upper.total === contains.total, `case-insensitive match failed: FLINT=${upper.total} vs flint=${contains.total}`); + + // SQL LIKE metacharacters are literal, so `%` cannot match everything. + const wildcard = await adminJson<{ total: number; logs: Array<{ model: string | null }> }>('/logs?model=%25&limit=50'); + const totalLogs = await logTotal(); + assert(wildcard.total === 0, `model=% matched ${wildcard.total} rows; % must be literal`); + assert(wildcard.total < totalLogs, 'model=% behaved like a wildcard'); + const underscore = await adminJson<{ total: number }>('/logs?model=_&limit=5'); + assert(underscore.total === 0, `model=_ matched ${underscore.total} rows; _ must be literal`); + return `flint=${contains.total} (== page), FLINT=${upper.total}, %%=0, _=0`; + }); + + await check('B-10: deleting the syncing provider clears syncProviderId', async () => { + const created = await adminJson<{ provider: { id: string } }>('/providers', { + body: { id: 'sync-owner', name: 'Sync Owner', baseUrl: MOCK_B, apiKey: MOCK_KEY, enabled: true, priority: 0 }, + }); + assert(created.provider.id === 'sync-owner', 'provider not created'); + await adminJson('/models/sync', { body: { providerId: 'sync-owner' } }); + const synced = await adminJson<{ syncProviderId: string | null }>('/models'); + assert(synced.syncProviderId === 'sync-owner', `syncProviderId=${synced.syncProviderId}, expected sync-owner`); + + await adminJson('/providers/sync-owner', { method: 'DELETE' }); + const after = await adminJson<{ syncProviderId: string | null }>('/models'); + assert(after.syncProviderId === null, `syncProviderId still points at the deleted provider: ${after.syncProviderId}`); + + // Leave a coherent catalog behind for the remaining checks. + await adminJson('/models/sync', { body: { providerId: 'primary' } }); + const restored = await adminJson<{ syncProviderId: string | null }>('/models'); + assert(restored.syncProviderId === 'primary', `catalog not restored: ${restored.syncProviderId}`); + return 'deleted syncing provider → syncProviderId null, catalog restored'; + }); } finally { + if (recorder) await recorder.close(); for (const child of children.reverse()) await stop(child); rmSync(dataDir, { recursive: true, force: true }); } diff --git a/scripts/live-check.ts b/scripts/live-check.ts index d95d53a..3bf9747 100644 --- a/scripts/live-check.ts +++ b/scripts/live-check.ts @@ -105,6 +105,28 @@ async function gateway(path: string, payload: { body: unknown } | unknown): Prom }); } +/** + * Extracts the dashboard session cookie from a login response. A missing or malformed + * `Set-Cookie` becomes an actionable error that names the status and the redacted + * headers, rather than a `TypeError` on `null`. + */ +export function extractSessionCookie(response: Response, label = 'login'): string { + const setCookie = response.headers.get('set-cookie'); + if (setCookie === null || setCookie.trim().length === 0) { + const headers = [...response.headers.entries()] + .map(([name, value]) => `${name}: ${/^(set-)?cookie$/i.test(name) ? '[redacted]' : value.slice(0, 120)}`) + .join('; '); + throw new Error( + `${label} → ${response.status} ${response.statusText} without a Set-Cookie header; expected a dashboard session cookie (headers: ${headers || 'none'})`, + ); + } + const cookie = setCookie.split(';')[0]?.trim() ?? ''; + if (!cookie.includes('=')) { + throw new Error(`${label} → ${response.status} returned a malformed Set-Cookie header: ${setCookie.slice(0, 120)}`); + } + return cookie; +} + async function stop(child: ChildProcess | null): Promise { if (!child || child.exitCode !== null) return; child.kill('SIGTERM'); @@ -128,7 +150,7 @@ async function main(): Promise { await waitFor(`${BASE}/health`); const login = await admin('/login', { body: { password: '123456' }, auth: false }); - cookie = login.headers.get('set-cookie')!.split(';')[0]!; + cookie = extractSessionCookie(login); const providerTest = await admin('/providers/test', { body: { baseUrl: UPSTREAM, apiKey: UPSTREAM_KEY } }); const probe = (await providerTest.json()) as { ok: boolean; models: number; error: string | null; status: number }; diff --git a/scripts/mock-upstream.ts b/scripts/mock-upstream.ts index 80a2be2..de0c17a 100644 --- a/scripts/mock-upstream.ts +++ b/scripts/mock-upstream.ts @@ -59,6 +59,11 @@ interface Control { omitUsage: boolean; /** Inject a top-level `x_opencode` key into the first chat SSE data frame. */ chatStreamXOpencode: boolean; + /** + * D-16: frame terminator the chat stream emits. `\n\n` is the canonical form; + * `\r\n\n` proves the gateway's boundary scanner handles mixed line endings. + */ + frameTerminator: string; served: number; total: number; } @@ -72,6 +77,7 @@ const control: Control = { fidelityFrames: false, omitUsage: false, chatStreamXOpencode: false, + frameTerminator: '\n\n', served: 0, total: 0, }; @@ -110,7 +116,9 @@ function sse(res: ServerResponse, event: string | null, data: unknown): void { const lines: string[] = []; if (event) lines.push(`event: ${event}`); lines.push(`data: ${typeof data === 'string' ? data : JSON.stringify(data)}`); - res.write(`${lines.join('\n')}\n\n`); + // D-16: the terminator is configurable so the e2e suite can exercise the gateway's + // mixed-line-ending frame scanner (`\r\n\n`, `\n\r\n`, `\r\r`). + res.write(`${lines.join('\n')}${control.frameTerminator}`); } function sleep(ms: number): Promise { @@ -593,6 +601,7 @@ const server = createServer(async (req, res) => { control.fidelityFrames = false; control.omitUsage = false; control.chatStreamXOpencode = false; + control.frameTerminator = '\n\n'; } if (body.failAfter !== undefined) control.failAfter = body.failAfter; if (body.alwaysStatus !== undefined) control.alwaysStatus = body.alwaysStatus; @@ -602,6 +611,7 @@ const server = createServer(async (req, res) => { if (body.fidelityFrames !== undefined) control.fidelityFrames = body.fidelityFrames; if (body.omitUsage !== undefined) control.omitUsage = body.omitUsage; if (body.chatStreamXOpencode !== undefined) control.chatStreamXOpencode = body.chatStreamXOpencode; + if (body.frameTerminator !== undefined) control.frameTerminator = String(body.frameTerminator); json(res, 200, { ...control, authFailures: authFailures.slice(-5) }); return; } diff --git a/scripts/screenshots.ts b/scripts/screenshots.ts index d9c141c..21dfd9c 100644 --- a/scripts/screenshots.ts +++ b/scripts/screenshots.ts @@ -1,6 +1,6 @@ -import { spawn, type ChildProcess } from 'node:child_process'; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { access } from 'node:fs/promises'; +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { constants, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { access, stat } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -10,10 +10,12 @@ import { fileURLToPath } from 'node:url'; * upstreams), drives headless Chrome over CDP, captures every dashboard tab in dark * and light mode and reports console errors. * - * Usage: pnpm exec tsx scripts/screenshots.ts [--out ./tmp/screenshots] [--port 20193] [--strict] + * Usage: pnpm exec tsx scripts/screenshots.ts [--out ./tmp/screenshots] [--port 20193] + * [--mockPort 20192] [--cdpPort 9333] [--strict] * * --strict turns an unrunnable check (no Chrome) into a failure instead of a silent - * `SKIP` exit 0; CI runs the harness with it. Env: CHROME_PATH overrides the binary. + * `SKIP` exit 0; local runs without a browser print SKIP and exit 0. Env: CHROME_PATH + * overrides the binary. No CI job runs this harness (see README.md "Verification"). */ const args = process.argv.slice(2); @@ -44,20 +46,56 @@ const SHOTS: Array<{ path: string; name: string; theme: 'dark' | 'light' }> = [ /* --------------------------------------------------------------------- helpers */ /** - * Verifies a Chrome binary is usable. Without `--strict` a missing browser is a silent - * `SKIP` exit 0; with it (CI) the run fails, so a check that captured nothing cannot - * pass. `CHROME_PATH` is trusted as-is. + * True when `--version` output looks like a Chromium browser. The check is deliberately + * loose about the product name (Chrome/Chromium/HeadlessChrome/Edge all work) but + * strict about the version shape, so the Node binary or a random executable is rejected. + */ +export function isChromeVersionOutput(text: string): boolean { + // `Google Chrome 141.0.7390.54`, `Chromium 141.0.7390.54`, `edg/141.0.0.0`. + return /(chrome|chromium|edg)[a-z-]*[\/ ]v?[0-9]+/i.test(text); +} + +/** + * Runs ` --version` and returns its output, or null when it cannot run or does + * not identify as a browser. A non-zero exit or a timeout counts as "not Chrome". + */ +export function chromeVersion(binary: string, timeoutMs = 10_000): string | null { + try { + const result = spawnSync(binary, ['--version'], { encoding: 'utf8', timeout: timeoutMs, killSignal: 'SIGKILL' }); + if (result.error || result.status !== 0) return null; + const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim(); + return isChromeVersionOutput(output) ? output : null; + } catch { + return null; + } +} + +/** + * Verifies a Chrome binary is usable. A path must be a *regular executable file* that + * answers `--version` as a browser: a directory, a non-executable file or a different + * program (for example the Node binary) must not make the UI check report success. + * Without `--strict` a missing browser is a silent `SKIP` exit 0; with it the run fails, + * so a check that captured nothing cannot pass. `CHROME_PATH` is trusted as-is. */ export async function ensureChrome(chromePath: string, strict: boolean): Promise<'ok' | 'skip'> { if (process.env.CHROME_PATH) return 'ok'; + let problem = ''; try { - await access(chromePath); - return 'ok'; - } catch { - if (strict) throw new Error(`Chrome not found at ${chromePath}; --strict refuses to skip the UI check`); - console.log(`SKIP Chrome not found at ${chromePath}`); - return 'skip'; + const info = await stat(chromePath); + if (!info.isFile()) problem = 'is not a regular file'; + else { + await access(chromePath, constants.X_OK); + if (chromeVersion(chromePath) === null) problem = 'is not a Chromium browser (--version did not identify one)'; + } + } catch (error) { + problem = `is not usable (${error instanceof Error ? error.message : String(error)})`; } + if (problem.length === 0) return 'ok'; + + const message = `Chrome unusable at ${chromePath}: ${problem}`; + if (strict) throw new Error(`${message}; --strict refuses to skip the UI check`); + console.log(`SKIP ${message}`); + return 'skip'; } async function waitFor(url: string, timeoutMs = 30_000): Promise { diff --git a/scripts/verify.ts b/scripts/verify.ts new file mode 100644 index 0000000..dc8d295 --- /dev/null +++ b/scripts/verify.ts @@ -0,0 +1,114 @@ +/** + * `pnpm verify` — one local gate that mirrors CI. + * + * Runs the same stages as the required GitHub checks in order and stops at the first + * failure, so a local run and a CI run cannot drift apart silently: + * + * 1. typecheck — server + dashboard + tests/scripts (`pnpm typecheck`) + * 2. test — unit suite (`pnpm test`) + * 3. check:docs — documentation, route, setting and `.env.example` drift + * 4. build — `dist/` + `web/dist/` + * 5. test:e2e — end-to-end acceptance (real server + mock upstreams) + * + * `--fast` skips `build` and `test:e2e` for a quick pre-commit loop. The e2e stage binds + * fixed ports; override them with `E2E_PORT`/`E2E_MOCK_A_PORT`/`E2E_MOCK_B_PORT` when + * another run is using the defaults. + * + * Usage: + * pnpm verify + * pnpm verify --fast + * tsx scripts/verify.ts --list + */ +import { spawn } from 'node:child_process'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export interface VerifyStage { + /** npm script name, run through the package manager so it matches CI exactly. */ + script: string; + /** Human-readable stage label used in the timing lines. */ + label: string; + /** `true` when `--fast` skips the stage. */ + slow: boolean; +} + +export const VERIFY_STAGES: VerifyStage[] = [ + { script: 'typecheck', label: 'typecheck', slow: false }, + { script: 'test', label: 'unit tests', slow: false }, + { script: 'check:docs', label: 'documentation drift', slow: false }, + { script: 'build', label: 'build', slow: true }, + { script: 'test:e2e', label: 'end-to-end acceptance', slow: true }, +]; + +/** Stages a run with the given flags would execute, in order. */ +export function planStages(fast = false): VerifyStage[] { + return VERIFY_STAGES.filter((stage) => !fast || !stage.slow); +} + +export interface StageResult { + stage: VerifyStage; + status: 'passed' | 'failed' | 'skipped'; + durationMs: number; +} + +function runStage(stage: VerifyStage): Promise> { + const started = Date.now(); + return new Promise((resolvePromise) => { + const child = spawn('pnpm', ['run', stage.script], { stdio: 'inherit', env: process.env }); + child.on('error', (error) => { + console.error(`\n${stage.label}: could not start pnpm — ${error.message}`); + resolvePromise({ status: 'failed', durationMs: Date.now() - started }); + }); + child.on('exit', (code, signal) => { + const status = code === 0 ? 'passed' : 'failed'; + if (signal !== null) console.error(`\n${stage.label}: terminated by ${signal}`); + resolvePromise({ status, durationMs: Date.now() - started }); + }); + }); +} + +function formatSeconds(ms: number): string { + return `${(ms / 1000).toFixed(1)}s`; +} + +async function main(): Promise { + const args = process.argv.slice(2); + const fast = args.includes('--fast'); + if (args.includes('--list')) { + for (const stage of planStages(fast)) console.log(`${stage.label} (pnpm ${stage.script})`); + return; + } + + const stages = planStages(fast); + const results: StageResult[] = []; + console.log(`verify: running ${stages.length} stage(s)${fast ? ' (--fast)' : ''}\n`); + + for (const stage of stages) { + console.log(`\n=== ${stage.label} — pnpm ${stage.script} ===`); + const result = await runStage(stage); + results.push({ stage, ...result }); + console.log(`--- ${stage.label}: ${result.status} in ${formatSeconds(result.durationMs)}`); + if (result.status !== 'passed') { + console.log('\nverify summary:'); + results.forEach((entry, index) => { + console.log(` ${index + 1}. ${entry.stage.label} — ${entry.status} (${formatSeconds(entry.durationMs)})`); + }); + console.log(`\nFAILED at stage ${results.length} of ${stages.length} (${stage.label}). Fix it and re-run \`pnpm verify\`.`); + process.exitCode = 1; + return; + } + } + + console.log('\nverify summary:'); + for (const [index, entry] of results.entries()) { + console.log(` ${index + 1}. ${entry.stage.label} — passed (${formatSeconds(entry.durationMs)})`); + } + console.log(`\nAll ${results.length} stage(s) passed.`); +} + +if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((error) => { + console.error('verify crashed:', error); + process.exitCode = 1; + }); +} diff --git a/src/admin/auth.ts b/src/admin/auth.ts index e66491f..4058efb 100644 --- a/src/admin/auth.ts +++ b/src/admin/auth.ts @@ -10,8 +10,15 @@ import { clearSessionCookie, createSession, resolveSession, setSessionCookie } f export const LOGIN_WINDOW_MS = 5 * 60 * 1000; export const LOGIN_MAX_ATTEMPTS = 10; -/** FEAT-08: global failure cap, so one botnet cannot hammer the login from many IPs. */ -export const LOGIN_GLOBAL_MAX_ATTEMPTS = 50; +/** + * FEAT-08/AD-21: process-wide failure cap. It stays well above the per-IP cap so a + * distributed bot cannot lock the operator out; 50 used to be reachable by a single + * attacker and turned the guard into a denial of service against the dashboard. + */ +export const LOGIN_GLOBAL_MAX_ATTEMPTS = 500; + +/** Methods whose execution must be same-origin when a dashboard session is present. */ +const MUTATING_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']); interface AttemptRecord { count: number; @@ -97,6 +104,50 @@ function pruneAttempts(): void { } } +/** + * AD-21: CSRF defence in depth on top of `SameSite=Lax`. A mutation is rejected when + * the browser says it is cross-site or when the `Origin` host differs from the host + * the request was addressed to (an explicitly configured `PUBLIC_URL` wins, because + * a TLS-terminating proxy may rewrite `Host`). + * + * A missing `Origin` (curl, the e2e suite, same-origin `fetch` without the header) is + * allowed; this guard is a veto, never an authentication bypass. + */ +export function isCrossSiteRequest(ctx: AppContext, request: FastifyRequest): boolean { + const fetchSite = request.headers['sec-fetch-site']; + const site = Array.isArray(fetchSite) ? fetchSite[0] : fetchSite; + if (typeof site === 'string' && site.trim().toLowerCase() === 'cross-site') return true; + + const originHeader = request.headers.origin; + const origin = Array.isArray(originHeader) ? originHeader[0] : originHeader; + if (typeof origin !== 'string' || origin.length === 0) return false; + + let originHost: string; + try { + originHost = new URL(origin).host.toLowerCase(); + } catch { + // `Origin: null` (sandboxed frame, data: URL) and junk have no usable host. + return true; + } + if (originHost.length === 0) return true; + return originHost !== expectedHost(ctx, request); +} + +function expectedHost(ctx: AppContext, request: FastifyRequest): string { + const publicUrl = ctx.config.publicUrl; + if (publicUrl) { + try { + const host = new URL(publicUrl).host.toLowerCase(); + if (host.length > 0) return host; + } catch { + /* fall back to the Host header */ + } + } + const hostHeader = request.headers.host; + const host = Array.isArray(hostHeader) ? hostHeader[0] : hostHeader; + return typeof host === 'string' ? host.toLowerCase() : ''; +} + /** `onRequest` hook: rejects unauthenticated requests with `401 unauthorized`. */ export function createAuthGuard(ctx: AppContext) { return async function authGuard(request: FastifyRequest, reply: FastifyReply): Promise { @@ -111,6 +162,15 @@ export function createAuthGuard(ctx: AppContext) { return; } request.adminSession = resolved.session; + // Only session-authenticated mutations are gated: the public login/logout/session + // routes returned above, so a legitimate cross-site login page keeps working. + if (MUTATING_METHODS.has(request.method) && isCrossSiteRequest(ctx, request)) { + audit(ctx, 'auth.csrf.rejected', null, `${request.method} ${normalizeAdminPath(request.url)}`, request); + await reply.status(403).send({ + error: { message: 'Cross-site request rejected', code: 'cross_site_request' }, + }); + return; + } ctx.repo.touchSession(resolved.session.id); }; } diff --git a/src/admin/diagnostics.ts b/src/admin/diagnostics.ts new file mode 100644 index 0000000..8d5e1fa --- /dev/null +++ b/src/admin/diagnostics.ts @@ -0,0 +1,215 @@ +/** + * AD-18: `GET /admin/api/diagnostics` — one self-check endpoint for operators. + * + * Reports what the background scheduler last did, what the storage engine looks + * like and a list of pass/warn checks (default password, empty catalog, clock + * skew, active cooldowns...). It never returns a secret: no key material, no + * session ids and no upstream credentials. + */ +import { statSync } from 'node:fs'; +import type { AppContext } from '../core/context.js'; +import { verifyDashboardPassword } from '../core/seed.js'; +import { SCHEMA_VERSION } from '../db/schema.js'; +import { ADMIN_VERSION } from './util.js'; +import { getSchedulerStatus, type SchedulerStatus } from './scheduler.js'; + +export type DiagnosticStatus = 'ok' | 'warn' | 'fail'; + +export interface DiagnosticCheck { + id: string; + status: DiagnosticStatus; + detail: string; +} + +export interface DiagnosticsReport { + scheduler: SchedulerStatus; + storage: { + dbPath: string; + walSizeBytes: number; + dbSizeBytes: number; + busyTimeoutMs: number; + logRows: number; + attemptRows: number; + sessionRows: number; + oldestLogTs: number | null; + }; + checks: DiagnosticCheck[]; +} + +/** Schema generation this build understands, mirrored by `PRAGMA user_version`. */ +export const EXPECTED_SCHEMA_USER_VERSION = SCHEMA_VERSION; +/** Tables a usable database must have; a missing one means a partial/foreign file. */ +const REQUIRED_TABLES = [ + 'settings', + 'providers', + 'models', + 'api_keys', + 'request_logs', + 'request_attempts', + 'sessions', + 'audit_logs', +] as const; +/** Tolerated difference between the wall clock and the newest recorded timestamp. */ +export const CLOCK_SKEW_TOLERANCE_MS = 60_000; + +function queryNumber(ctx: AppContext, sql: string): number | null { + try { + const row = ctx.db.db.prepare(sql).get() as Record | undefined; + if (!row) return null; + const value = Object.values(row)[0]; + if (value === null || value === undefined) return null; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; + } catch { + return null; + } +} + +/** True when `sqlite_master` knows about `table` (partial/foreign files answer false). */ +function tableExists(ctx: AppContext, table: string): boolean { + try { + const row = ctx.db.db + .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?") + .get(table) as Record | undefined; + return row !== undefined; + } catch { + return false; + } +} + +/** + * Runs a repository read, falling back when the database cannot answer it (missing + * table, foreign file). Diagnostics must describe a broken database, not fail on it. + */ +function safeRead(read: () => T, fallback: T): T { + try { + return read(); + } catch { + return fallback; + } +} + +function fileSize(path: string): number { + try { + return statSync(path).size; + } catch { + return 0; + } +} + +function busyTimeoutMs(ctx: AppContext): number { + return queryNumber(ctx, 'PRAGMA busy_timeout') ?? 0; +} + +function newestRecordedTs(ctx: AppContext): number | null { + const logTs = queryNumber(ctx, 'SELECT MAX(ts) AS c FROM request_logs'); + const auditTs = queryNumber(ctx, 'SELECT MAX(ts) AS c FROM audit_logs'); + const newest = Math.max(logTs ?? 0, auditTs ?? 0); + return newest > 0 ? newest : null; +} + +function buildChecks(ctx: AppContext): DiagnosticCheck[] { + const checks: DiagnosticCheck[] = []; + const now = Date.now(); + + // 1. Default dashboard password. + const defaultPasswordInUse = safeRead( + () => verifyDashboardPassword(ctx, ctx.config.defaultDashboardPassword), + false, + ); + checks.push({ + id: 'password.default', + status: defaultPasswordInUse ? 'warn' : 'ok', + detail: defaultPasswordInUse + ? 'The default dashboard password is still in use; change it in Settings > Security' + : 'The dashboard password is not the built-in default', + }); + + // 2. Enabled provider. The reads below are guarded: a database missing a table (or + // written by a foreign build) must still produce a report instead of a 500 — that is + // exactly the situation this endpoint exists to diagnose. + const providers = safeRead(() => ctx.repo.listProviders(), []); + const enabledProviders = providers.filter((provider) => provider.enabled); + checks.push({ + id: 'providers.enabled', + status: enabledProviders.length > 0 ? 'ok' : 'warn', + detail: + enabledProviders.length > 0 + ? `${enabledProviders.length} enabled provider(s)` + : 'No enabled provider: the gateway cannot serve any request', + }); + + // 3. Active gateway key. + const keysActive = safeRead(() => ctx.repo.countActiveApiKeys(), 0); + checks.push({ + id: 'keys.active', + status: keysActive > 0 ? 'ok' : 'warn', + detail: keysActive > 0 ? `${keysActive} active gateway key(s)` : 'No active gateway key', + }); + + // 4. Enabled model. + const modelsEnabled = safeRead(() => ctx.repo.enabledModelIds().length, 0); + checks.push({ + id: 'models.enabled', + status: modelsEnabled > 0 ? 'ok' : 'warn', + detail: modelsEnabled > 0 ? `${modelsEnabled} enabled model(s)` : 'No enabled model', + }); + + // 5. Schema generation vs this build, plus the tables a usable file must contain. + const userVersion = queryNumber(ctx, 'PRAGMA user_version') ?? 0; + const missingTables = REQUIRED_TABLES.filter((table) => !tableExists(ctx, table)); + const schemaOk = userVersion === EXPECTED_SCHEMA_USER_VERSION && missingTables.length === 0; + checks.push({ + id: 'version.schema', + status: schemaOk ? 'ok' : 'warn', + detail: schemaOk + ? `schema user_version=${userVersion}, api ${ADMIN_VERSION}` + : missingTables.length > 0 + ? `schema user_version=${userVersion} is missing table(s): ${missingTables.join(', ')}` + : `schema user_version=${userVersion} (expected ${EXPECTED_SCHEMA_USER_VERSION}) for api ${ADMIN_VERSION}; docs may be stale`, + }); + + // 6. Clock skew against the newest recorded timestamp. + const newest = newestRecordedTs(ctx); + const skewed = newest !== null && newest > now + CLOCK_SKEW_TOLERANCE_MS; + checks.push({ + id: 'clock.skew', + status: skewed ? 'warn' : 'ok', + detail: skewed + ? `Newest recorded timestamp is ${Math.round((newest - now) / 1000)}s in the future; check the system clock` + : 'System clock is consistent with recorded timestamps', + }); + + // 7. Providers currently cooling down. + const cooling = providers.filter( + (provider) => provider.cooldownUntil !== null && provider.cooldownUntil > now, + ); + checks.push({ + id: 'providers.cooldown', + status: cooling.length === 0 ? 'ok' : 'warn', + detail: + cooling.length === 0 + ? 'No provider is cooling down' + : `${cooling.length} provider(s) cooling down: ${cooling.map((provider) => provider.id).join(', ')}`, + }); + + return checks; +} + +export function buildDiagnostics(ctx: AppContext): DiagnosticsReport { + const storage: DiagnosticsReport['storage'] = { + dbPath: ctx.config.dbPath, + walSizeBytes: fileSize(`${ctx.config.dbPath}-wal`), + dbSizeBytes: fileSize(ctx.config.dbPath), + busyTimeoutMs: busyTimeoutMs(ctx), + logRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM request_logs') ?? 0, + attemptRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM request_attempts') ?? 0, + sessionRows: queryNumber(ctx, 'SELECT COUNT(*) AS c FROM sessions') ?? 0, + oldestLogTs: queryNumber(ctx, 'SELECT MIN(ts) AS c FROM request_logs'), + }; + return { + scheduler: getSchedulerStatus(ctx), + storage, + checks: buildChecks(ctx), + }; +} diff --git a/src/admin/models.ts b/src/admin/models.ts index e066fef..f7fd3d6 100644 --- a/src/admin/models.ts +++ b/src/admin/models.ts @@ -21,6 +21,7 @@ import { import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT, + syncAllEnabledProviders, syncFailureMessage, syncProviderModels, } from './sync.js'; @@ -38,7 +39,9 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo scope.get('/models', async () => ({ models: ctx.repo.listModels(), syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + // AD-20: an empty value means "no syncing provider" (a deleted provider is + // cleared to ''), which the dashboard must render as null. + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, providers: ctx.repo.listProviders().map((provider) => ({ id: provider.id, name: provider.name })), })); @@ -140,13 +143,23 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo scope.post('/models/sync', async (request) => { const body = jsonBody(request); const requestedId = asString(body.providerId); - const provider = requestedId - ? ctx.repo.getProvider(requestedId) - : ctx.repo.listProviders().find((candidate) => candidate.enabled); - if (!provider) { - if (requestedId) throw new HttpError(404, 'provider_not_found', `Provider "${requestedId}" not found`); - fail(400, 'no_provider', 'No provider configured. Add one in the Providers tab first.'); + if (requestedId === null) { + // AD-17: a bare "sync" refreshes every enabled provider, not just the first. + if (ctx.repo.listProviders().every((candidate) => !candidate.enabled)) { + fail(400, 'no_provider', 'No provider configured. Add one in the Providers tab first.'); + } + const all = await syncAllEnabledProviders(ctx); + audit( + ctx, + 'model.sync', + null, + `providers=${all.providers.length} failed=${all.providers.filter((outcome) => !outcome.ok).length} added=${all.added} updated=${all.updated} removed=${all.removed} total=${all.total}`, + request, + ); + return all; } + const provider = ctx.repo.getProvider(requestedId); + if (!provider) throw new HttpError(404, 'provider_not_found', `Provider "${requestedId}" not found`); let result; try { result = await syncProviderModels(ctx, provider); @@ -160,19 +173,24 @@ export function registerModelRoutes(scope: FastifyInstance, ctx: AppContext): vo ); throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } - ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); - ctx.events.emitProvider({ - providerId: provider.id, - state: 'ok', - status: 200, - message: null, - ts: Date.now(), - }); + // AD-16: an unrecognized upstream catalog is a warning, not a healthy round-trip. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } audit( ctx, 'model.sync', provider.id, - `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + result.warning !== undefined + ? `warning=${result.warning}` + : `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, request, ); return result; diff --git a/src/admin/providers.ts b/src/admin/providers.ts index 1ecb6ff..0de4a09 100644 --- a/src/admin/providers.ts +++ b/src/admin/providers.ts @@ -10,6 +10,7 @@ import { asBool, asInt, asString, + assertApiKey, assertNoControlChars, assertPublicProviderUrl, audit, @@ -19,7 +20,14 @@ import { maskApiKey, requireString, } from './util.js'; -import { probeAndRecord, probeProvider, recordProbeSuccess, syncFailureMessage, syncProviderModels } from './sync.js'; +import { + SETTING_MODELS_SYNC_PROVIDER_ID, + probeAndRecord, + probeProvider, + recordProbeSuccess, + syncFailureMessage, + syncProviderModels, +} from './sync.js'; export interface ProviderView { id: string; @@ -107,6 +115,9 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); const apiKey = asString(body.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey is required'); + // AD-13: reject control/non-ASCII/over-long keys before they reach `fetch`, whose + // thrown message would otherwise echo the raw key. + assertApiKey(apiKey); const enabled = body.enabled === undefined ? true : asBool(body.enabled); if (enabled === null) fail(400, 'invalid_request', 'enabled must be true or false'); const priority = body.priority === undefined ? 100 : priorityFrom(body.priority); @@ -140,6 +151,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): if (body.apiKey !== undefined) { const apiKey = asString(body.apiKey); if (!apiKey) fail(400, 'invalid_request', 'apiKey must be a non-empty string'); + assertApiKey(apiKey); patch.apiKey = apiKey; changed.push('apiKey'); } @@ -170,7 +182,17 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): const id = (request.params as { id: string }).id; const current = loadProvider(ctx, id); // AD-02: the provider's synced models go with it (no FK constraints exist). - const { modelsRemoved } = ctx.repo.deleteProviderWithModels(id); + // AD-20: `models_sync_provider_id` must not keep pointing at the deleted provider; + // clearing it happens in the same transaction as the delete. + const { modelsRemoved } = ctx.repo.transaction(() => { + const removed = ctx.repo.deleteProviderWithModels(id); + if (ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) === id) { + // The settings table has no delete helper; the empty value reads as `null` in + // every admin view (`GET /admin/api/models`, `/settings`, `/bootstrap`). + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, ''); + } + return removed; + }); audit(ctx, 'provider.delete', id, `${current.name} modelsRemoved=${modelsRemoved}`, request); return { ok: true, modelsRemoved }; }); @@ -182,6 +204,7 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): const baseUrl = httpBaseUrl(body.baseUrl); assertPublicProviderUrl(baseUrl, ctx.config.providerAllowPrivateHosts); let apiKey = asString(body.apiKey); + if (apiKey) assertApiKey(apiKey); if (!apiKey) { const id = asString(body.id); if (!id) fail(400, 'invalid_request', 'apiKey is required'); @@ -254,19 +277,25 @@ export function registerProviderRoutes(scope: FastifyInstance, ctx: AppContext): ); throw new HttpError(502, 'sync_failed', syncFailureMessage(provider.name)); } - ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); - ctx.events.emitProvider({ - providerId: provider.id, - state: 'ok', - status: 200, - message: null, - ts: Date.now(), - }); + // AD-16: an unrecognized upstream catalog is a warning, not a success — never + // record it as a healthy provider round-trip. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } audit( ctx, 'provider.sync', provider.id, - `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, + result.warning !== undefined + ? `warning=${result.warning}` + : `added=${result.added} updated=${result.updated} removed=${result.removed} total=${result.total}`, request, ); return result; diff --git a/src/admin/scheduler.ts b/src/admin/scheduler.ts index 5e2e15f..c56d0e0 100644 --- a/src/admin/scheduler.ts +++ b/src/admin/scheduler.ts @@ -1,17 +1,18 @@ /** * Background maintenance for the admin layer. * - * - syncs provider models on the `model_sync_interval_ms` cadence when - * `auto_sync_models` is enabled and an enabled provider exists; + * - syncs every enabled provider's models on the `model_sync_interval_ms` cadence + * when `auto_sync_models` is enabled (AD-17); * - probes providers whose cooldown expired and clears it when they answer again - * (FEAT-02), so a rate-limited provider is not skipped until the next sync; + * (FEAT-02), so a rate-limited provider is not skipped until the next sync. A + * cursor rotates over the cooling candidates so a large tail is not starved; * - purges expired dashboard sessions every 10 minutes. * * All timers are `unref()`ed and every callback is wrapped so nothing throws * out of an interval. The returned function stops the scheduler cleanly. */ import type { AppContext } from '../core/context.js'; -import { probeAndRecord, syncProviderModels } from './sync.js'; +import { probeAndRecord, syncAllEnabledProviders } from './sync.js'; const MIN_SYNC_INTERVAL_MS = 30_000; const TICK_MS = 30_000; @@ -22,11 +23,66 @@ const COOLDOWN_PROBES_PER_TICK = 3; /** A recovery probe only needs to prove the provider answers `GET /models`. */ const COOLDOWN_PROBE_TIMEOUT_MS = 5_000; +export interface SchedulerStatus { + running: boolean; + lastSyncAt: number | null; + lastSyncError: string | null; + /** Milliseconds until the next scheduled sync, or null when it is not scheduled. */ + nextSyncInMs: number | null; + lastRecoveryAt: number | null; +} + +/** + * AD-18: `/admin/api/diagnostics` reports what the scheduler last did. The state is + * process-wide (one scheduler per process) and reset by every `startScheduler`. + */ +let runtime: { + running: boolean; + startedAt: number; + lastSyncAt: number | null; + lastSyncError: string | null; + lastRecoveryAt: number | null; +} = { running: false, startedAt: 0, lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; + +/** Test/ops helper: forget the observed scheduler state. */ +export function resetSchedulerStatus(): void { + runtime = { running: false, startedAt: 0, lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; +} + +export function getSchedulerStatus(ctx: AppContext): SchedulerStatus { + const configured = ctx.repo.getInt('model_sync_interval_ms', 300_000); + const intervalMs = Math.max(MIN_SYNC_INTERVAL_MS, Number.isFinite(configured) ? configured : 300_000); + const autoSync = ctx.repo.getBool('auto_sync_models'); + let nextSyncInMs: number | null = null; + if (runtime.running && autoSync) { + // Before the first sync the initial delay is the next attempt; afterwards the + // regular interval counts from the last successful/attempted sync. + const base = runtime.lastSyncAt ?? runtime.startedAt; + const nextAt = base + (runtime.lastSyncAt === null ? INITIAL_SYNC_DELAY_MS : intervalMs); + nextSyncInMs = Math.max(0, nextAt - Date.now()); + } + return { + running: runtime.running, + lastSyncAt: runtime.lastSyncAt, + lastSyncError: runtime.lastSyncError, + nextSyncInMs, + lastRecoveryAt: runtime.lastRecoveryAt, + }; +} + export function startScheduler(ctx: AppContext): () => void { let stopped = false; let syncing = false; let recovering = false; let lastSyncAt = 0; + /** + * AD-19: round-robin cursor over the cooling candidates. Providers probed in the + * current round are remembered by id, so the tail is reached on the next tick and + * no provider is probed twice while another has not been tried yet. + */ + let probedThisRound = new Set(); + + runtime = { running: true, startedAt: Date.now(), lastSyncAt: null, lastSyncError: null, lastRecoveryAt: null }; const log = (level: 'info' | 'warn', message: string, extra?: Record): void => { try { @@ -45,23 +101,25 @@ export function startScheduler(ctx: AppContext): () => void { const intervalMs = Math.max(MIN_SYNC_INTERVAL_MS, Number.isFinite(configured) ? configured : 300_000); const now = Date.now(); if (now - lastSyncAt < intervalMs) return; - const provider = ctx.repo.listProviders().find((candidate) => candidate.enabled); - if (!provider) return; + if (ctx.repo.listProviders().every((provider) => !provider.enabled)) return; syncing = true; lastSyncAt = now; - const result = await syncProviderModels(ctx, provider); + runtime.lastSyncAt = now; + // AD-17: sync every enabled provider, not just the first one in the list. + const result = await syncAllEnabledProviders(ctx); + runtime.lastSyncError = null; log('info', 'auto-synced provider models', { - providerId: result.providerId, + providers: result.providers.length, + failed: result.providers.filter((outcome) => !outcome.ok).length, added: result.added, updated: result.updated, removed: result.removed, total: result.total, - latencyMs: result.latencyMs, }); } catch (error) { - log('warn', 'scheduled model sync failed', { - error: error instanceof Error ? error.message : String(error), - }); + const message = error instanceof Error ? error.message : String(error); + runtime.lastSyncError = message; + log('warn', 'scheduled model sync failed', { error: message }); } finally { syncing = false; } @@ -84,27 +142,46 @@ export function startScheduler(ctx: AppContext): () => void { provider.status === 'cooldown' && provider.cooldownUntil !== null && provider.cooldownUntil <= now, - ) - .slice(0, COOLDOWN_PROBES_PER_TICK); - if (cooled.length === 0) return; + ); + if (cooled.length === 0) { + probedThisRound.clear(); + return; + } + // Skip candidates already probed in this round; start a new round once every + // current candidate has had a turn. + const remaining = cooled.filter((provider) => !probedThisRound.has(provider.id)); + if (remaining.length === 0) { + probedThisRound.clear(); + } + const batch = (remaining.length === 0 ? cooled : remaining).slice(0, COOLDOWN_PROBES_PER_TICK); + for (const provider of batch) probedThisRound.add(provider.id); recovering = true; - for (const provider of cooled) { + for (const provider of batch) { if (stopped) return; - const probe = await probeAndRecord(ctx, provider, { - cooldownMs: 0, - timeoutMs: COOLDOWN_PROBE_TIMEOUT_MS, - log: (detail) => log('warn', 'cooldown recovery probe failed', { providerId: provider.id, detail }), - }); - if (probe.ok) { - ctx.repo.updateProvider(provider.id, { cooldownUntil: null, status: 'ok' }); - ctx.events.emitProvider({ + try { + const probe = await probeAndRecord(ctx, provider, { + cooldownMs: 0, + timeoutMs: COOLDOWN_PROBE_TIMEOUT_MS, + log: (detail) => log('warn', 'cooldown recovery probe failed', { providerId: provider.id, detail }), + }); + if (probe.ok) { + ctx.repo.updateProvider(provider.id, { cooldownUntil: null, status: 'ok' }); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: probe.status, + message: null, + ts: Date.now(), + }); + runtime.lastRecoveryAt = Date.now(); + log('info', 'provider recovered from cooldown', { providerId: provider.id, latencyMs: probe.latencyMs }); + } + } catch (error) { + // One unroutable row (SSRF guard, driver error) must not abort the sweep. + log('warn', 'cooldown recovery probe failed', { providerId: provider.id, - state: 'ok', - status: probe.status, - message: null, - ts: Date.now(), + detail: error instanceof Error ? error.message : String(error), }); - log('info', 'provider recovered from cooldown', { providerId: provider.id, latencyMs: probe.latencyMs }); } } } catch (error) { @@ -143,6 +220,7 @@ export function startScheduler(ctx: AppContext): () => void { return () => { if (stopped) return; stopped = true; + runtime.running = false; clearInterval(syncTimer); clearInterval(purgeTimer); clearTimeout(initialTimer); diff --git a/src/admin/settings.ts b/src/admin/settings.ts index 5347f4e..908dc84 100644 --- a/src/admin/settings.ts +++ b/src/admin/settings.ts @@ -21,6 +21,7 @@ import { audit, fail, jsonBody, + queryInt, sanitizeSettings, settingTimestamp, } from './util.js'; @@ -28,7 +29,14 @@ import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT } from './syn const BOOL_SETTINGS = new Set(['auto_sync_models', 'model_allow_unknown']); -const INT_SETTINGS: Record = { +interface IntSetting { + min: number; + max: number; + /** When set, values below it are only valid as exactly `0` (an "off" sentinel). */ + zeroOrMin?: number; +} + +const INT_SETTINGS: Record = { max_retries: { min: 1, max: 10 }, provider_cooldown_ms: { min: 0, max: 3_600_000 }, request_timeout_ms: { min: 1_000, max: 3_600_000 }, @@ -37,6 +45,8 @@ const INT_SETTINGS: Record = { audit_retention_days: { min: 1, max: 3_650 }, // GW-05: per-chunk SSE idle deadline, well below the total request timeout. stream_idle_timeout_ms: { min: 1_000, max: 3_600_000 }, + // 0 means "unlimited"; any real cap must be at least 1 KiB so a normal response fits. + upstream_response_max_bytes: { min: 0, max: 1_073_741_824, zeroOrMin: 1_024 }, }; const ROTATION_STRATEGIES = new Set(['round-robin', 'priority', 'random']); @@ -62,6 +72,13 @@ function validateSetting(key: string, value: unknown): string | null { if (range) { const parsed = asInt(value); if (parsed === null) fail(400, 'invalid_request', `${key} must be an integer`); + if (range.zeroOrMin !== undefined && parsed !== 0 && parsed < range.zeroOrMin) { + fail( + 400, + 'invalid_request', + `${key} must be 0 (unlimited) or between ${range.zeroOrMin} and ${range.max}`, + ); + } if (parsed < range.min || parsed > range.max) { fail(400, 'invalid_request', `${key} must be between ${range.min} and ${range.max}`); } @@ -115,7 +132,7 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): sessionsActive: sessions.length, }, syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, }; }); @@ -215,8 +232,10 @@ export function registerSettingsRoutes(scope: FastifyInstance, ctx: AppContext): }); scope.get('/audit', async (request) => { - const requested = asInt((request.query as Record).limit) ?? 100; - const limit = Math.min(Math.max(requested, 1), 500); + // AD-22: `limit=abc`/`limit=-5` used to fall back silently; `/logs` rejects them, + // so both routes now share the documented 1..500 range. + const query = request.query as Record; + const limit = query.limit === undefined ? 100 : queryInt(query.limit, 'limit', 1, 500); return { items: ctx.repo.listAudit(limit) }; }); } diff --git a/src/admin/stats.ts b/src/admin/stats.ts index 205c708..e048078 100644 --- a/src/admin/stats.ts +++ b/src/admin/stats.ts @@ -10,13 +10,14 @@ import type { SessionRow } from '../types.js'; import { formatSseJson } from '../util/sse.js'; import { ADMIN_VERSION, - asInt, buildHealth, + queryInt, queryOf, sanitizeSettings, settingTimestamp, activeKeyCount, } from './util.js'; +import { buildDiagnostics } from './diagnostics.js'; import { SETTING_MODELS_SYNC_PROVIDER_ID, SETTING_MODELS_SYNCED_AT } from './sync.js'; interface WindowConfig { @@ -88,11 +89,11 @@ export function eventStreamAuthorized(ctx: AppContext, session: SessionRow | nul /** Per-client cap on frames buffered while `drain` is pending. */ const EVENTS_QUEUE_LIMIT = 256; -function cachedOverview(ctx: AppContext, key: string, config: WindowConfig): StatsOverview { +function cachedOverview(ctx: AppContext, key: string, config: WindowConfig, activeRequests: number): StatsOverview { const now = Date.now(); const cached = statsCache.get(key); if (cached && now - cached.at < STATS_CACHE_TTL_MS) return cached.overview; - const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, getActiveRequests()); + const overview = ctx.repo.statsOverview(config.windowMs, config.bucketMs, activeRequests); statsCache.set(key, { at: now, overview }); return overview; } @@ -137,22 +138,30 @@ export function registerStatsRoutes(scope: FastifyInstance, ctx: AppContext): vo modelCount: models.length, keyCount: keys.length, syncedAt: settingTimestamp(ctx, SETTING_MODELS_SYNCED_AT), - syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID), + syncProviderId: ctx.repo.getSetting(SETTING_MODELS_SYNC_PROVIDER_ID) || null, activeRequests: getActiveRequests(), settings: sanitizeSettings(ctx.repo.allSettings()).settings, }; }); + // AD-18: single self-check endpoint for operators; session-protected, `limit`-free. + scope.get('/diagnostics', async () => buildDiagnostics(ctx)); + scope.get('/stats', async (request) => { const { key, config } = windowFrom(request); - const overview = cachedOverview(ctx, key, config); + // AD-14: one snapshot of the live counter feeds both the body and `health`, so a + // cached aggregate can never disagree with the live field inside one response. + const activeRequests = getActiveRequests(); + const overview = cachedOverview(ctx, key, config, activeRequests); // `overview` already carries requestsLast60s/errorsLast60s from statsOverview. - return { ...overview, health: buildHealth(ctx), window: key }; + return { ...overview, activeRequests, health: buildHealth(ctx, activeRequests), window: key }; }); scope.get('/activity', async (request) => { - const requested = asInt(queryOf(request).limit) ?? 20; - const limit = Math.min(Math.max(requested, 1), 100); + // AD-22: reject junk/out-of-range limits like `/logs` does (documented 1..500) + // instead of silently clamping them. + const query = queryOf(request); + const limit = query.limit === undefined ? 20 : queryInt(query.limit, 'limit', 1, 500); const now = Date.now(); const logItems = ctx.repo.listLogs({ limit }).rows.map((row) => ({ diff --git a/src/admin/sync.ts b/src/admin/sync.ts index 214b73d..6631f0c 100644 --- a/src/admin/sync.ts +++ b/src/admin/sync.ts @@ -7,7 +7,7 @@ import type { ProviderRow } from '../types.js'; import { upstreamErrorFrom } from '../util/errors.js'; import { extractModels, type NormalizedModel } from '../util/models.js'; import { readJsonBody, upstreamFetch } from '../util/upstream.js'; -import { assertPublicProviderUrl } from './util.js'; +import { HttpError, assertPublicProviderUrl } from './util.js'; export const SYNC_TIMEOUT_MS = 20_000; @@ -25,6 +25,11 @@ export interface ProviderProbe { status: number; latencyMs: number; models: NormalizedModel[]; + /** + * AD-16: true when the 2xx body contained a recognizable model array, even an + * empty one. `false` means `{}`/HTML/`{data:null}` and must not prune the catalog. + */ + catalogLocated: boolean; /** Client-safe failure message ('' on success); never contains the response body. */ error: string; /** Server-side detail (upstream body excerpt); never returned to clients. */ @@ -40,6 +45,30 @@ export interface SyncResult { syncedAt: number; /** Extra: upstream `/models` round-trip measured for this sync. */ latencyMs: number; + /** + * AD-16: present when the upstream answered 2xx without a recognizable model + * list. The catalog is left untouched and `models_synced_at` is not advanced. + */ + warning?: string; +} + +/** Client-safe warning for an upstream 2xx body that is not a model list. */ +export const UNRECOGNIZED_CATALOG_WARNING = + 'Upstream returned no recognizable model list; the synced catalog was left unchanged'; + +/** + * AD-16: separates "explicit empty catalog" (prune as usual) from "unrecognized + * payload" (`{}`, HTML, `{data:null}`), which must never wipe synced rows. + */ +function locateModels(payload: unknown): { models: NormalizedModel[]; located: boolean } { + if (Array.isArray(payload)) return { models: extractModels(payload), located: true }; + if (payload !== null && typeof payload === 'object') { + const record = payload as Record; + if (Array.isArray(record.data) || Array.isArray(record.models)) { + return { models: extractModels(payload), located: true }; + } + } + return { models: extractModels(payload), located: false }; } /** Client-facing probe failure message — deliberately generic (no body echo). */ @@ -53,8 +82,8 @@ export function syncFailureMessage(providerName: string): string { } /** Detailed upstream error text; kept for logs only, never sent to clients. */ -function errorMessageFrom(status: number, body: string, baseUrl: string): string { - return upstreamErrorFrom(status, body, baseUrl).message; +function errorMessageFrom(status: number, body: string, baseUrl: string, secrets: readonly string[] = []): string { + return upstreamErrorFrom(status, body, baseUrl, secrets).message; } /** GETs `{baseUrl}/models` and reports success, latency and parsed models. */ @@ -71,33 +100,48 @@ export async function probeProvider( method: 'GET', timeoutMs, }); - const latencyMs = Date.now() - started; - if (!response.ok) { - let body = ''; - try { - body = await response.response.text(); - response.dispose(); - } catch { - body = ''; + // AD-15: the body read can throw (aborted socket, bad encoding); `dispose()` must + // still run so the abort/timeout machinery is released instead of leaking. + try { + const latencyMs = Date.now() - started; + if (!response.ok) { + let body = ''; + try { + body = await response.response.text(); + } catch { + body = ''; + } + return { + ok: false, + status: response.status, + latencyMs, + models: [], + catalogLocated: false, + error: probeFailureMessage(response.status), + detail: errorMessageFrom(response.status, body, credentials.baseUrl, [credentials.apiKey]), + }; } + const payload = await readJsonBody(response.response); + const located = locateModels(payload); return { - ok: false, + ok: true, status: response.status, latencyMs, - models: [], - error: probeFailureMessage(response.status), - detail: errorMessageFrom(response.status, body, credentials.baseUrl), + models: located.models, + catalogLocated: located.located, + error: '', + detail: null, }; + } finally { + response.dispose(); } - const payload = await readJsonBody(response.response); - response.dispose(); - return { ok: true, status: response.status, latencyMs, models: extractModels(payload), error: '', detail: null }; } catch (error) { return { ok: false, status: 0, latencyMs: Date.now() - started, models: [], + catalogLocated: false, error: probeFailureMessage(0), detail: error instanceof Error ? error.message : String(error), }; @@ -157,6 +201,9 @@ export async function probeAndRecord( timeoutMs?: number; }, ): Promise { + // AD-03: the scheduler probes stored rows directly, so the SSRF guard lives on the + // shared path instead of only on the routes. + assertPublicProviderUrl(provider.baseUrl, ctx.config.providerAllowPrivateHosts); const probe = await probeProvider( { baseUrl: provider.baseUrl, apiKey: provider.apiKey }, options.timeoutMs, @@ -192,6 +239,25 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) throw new Error(syncFailureMessage(provider.name)); } + if (!probe.catalogLocated) { + // AD-16: a 2xx without a model array (`{}`, HTML, `{data:null}`) is a failed sync, + // not an empty catalog: keep every row and leave `models_synced_at` untouched. + ctx.logger?.warn?.( + { providerId: provider.id, status: probe.status, detail: probe.detail }, + 'provider model sync returned an unrecognized catalog', + ); + return { + added: 0, + updated: 0, + removed: 0, + total: 0, + providerId: provider.id, + syncedAt: Date.now(), + latencyMs: probe.latencyMs, + warning: UNRECOGNIZED_CATALOG_WARNING, + }; + } + const syncedAt = Date.now(); // OPT-10: the caller already holds the row snapshot, so each upsert skips its own // `getModel`; the whole write set is one transaction (no partially synced catalog). @@ -246,3 +312,133 @@ export async function syncProviderModels(ctx: AppContext, provider: ProviderRow) latencyMs: probe.latencyMs, }; } + +/* ------------------------------------------------------ multi-provider sync (AD-17) */ + +/** Per-provider outcome of `syncAllEnabledProviders`. */ +export interface ProviderSyncOutcome { + providerId: string; + providerName: string; + ok: boolean; + /** Set when the upstream answered 2xx without a recognizable model list. */ + warning: string | null; + /** Client-safe failure message; the upstream detail stays in the server log. */ + error: string | null; + added: number; + updated: number; + removed: number; + total: number; + latencyMs: number; +} + +export interface SyncAllResult extends SyncResult { + /** Additive per-provider report; one entry per enabled provider, in list order. */ + providers: ProviderSyncOutcome[]; +} + +/** Two concurrent upstream round-trips keep a big catalog calm without serializing it. */ +export const SYNC_ALL_CONCURRENCY = 2; + +/** + * AD-17: `runModelSync`/`maybeSync` used to sync only the first enabled provider, so + * multi-provider deployments kept stale catalogs for every other one. Each provider + * is synced with the same single-provider path (one transaction each) and a failure + * for one provider never aborts the others. + */ +export async function syncAllEnabledProviders( + ctx: AppContext, + options: { concurrency?: number } = {}, +): Promise { + const providers = ctx.repo.listProviders().filter((provider) => provider.enabled); + const concurrency = Math.max( + 1, + Math.min(options.concurrency ?? SYNC_ALL_CONCURRENCY, providers.length || 1), + ); + const outcomes: ProviderSyncOutcome[] = []; + let cursor = 0; + + const worker = async (): Promise => { + while (cursor < providers.length) { + const index = cursor; + cursor += 1; + const provider = providers[index]!; + try { + const result = await syncProviderModels(ctx, provider); + outcomes[index] = { + providerId: provider.id, + providerName: provider.name, + ok: result.warning === undefined, + warning: result.warning ?? null, + error: null, + added: result.added, + updated: result.updated, + removed: result.removed, + total: result.total, + latencyMs: result.latencyMs, + }; + // Parity with the single-provider sync route: a healthy round-trip refreshes + // the provider's health counters, and an unrecognized catalog does not. + if (result.warning === undefined) { + ctx.repo.recordProviderSuccess(provider.id, result.latencyMs); + ctx.events.emitProvider({ + providerId: provider.id, + state: 'ok', + status: 200, + message: null, + ts: Date.now(), + }); + } + } catch (error) { + // The SSRF guard raises an authored HttpError (client-safe); every other + // failure is reported with the generic sync message and logged in detail. + const message = error instanceof HttpError ? error.message : syncFailureMessage(provider.name); + ctx.logger?.warn?.( + { providerId: provider.id, detail: error instanceof Error ? error.message : String(error) }, + 'provider model sync failed', + ); + outcomes[index] = { + providerId: provider.id, + providerName: provider.name, + ok: false, + warning: null, + error: message, + added: 0, + updated: 0, + removed: 0, + total: 0, + latencyMs: 0, + }; + } + } + }; + + await Promise.all(Array.from({ length: concurrency }, () => worker())); + + const succeeded = outcomes.filter((outcome) => outcome.ok); + const added = outcomes.reduce((sum, outcome) => sum + outcome.added, 0); + const updated = outcomes.reduce((sum, outcome) => sum + outcome.updated, 0); + const removed = outcomes.reduce((sum, outcome) => sum + outcome.removed, 0); + const total = outcomes.reduce((sum, outcome) => sum + outcome.total, 0); + const syncedAt = Date.now(); + + // A single enabled provider keeps the existing `models_sync_provider_id` semantics + // (written by `syncProviderModels` itself). With several providers no single id is + // meaningful, so the stamp is refreshed and the provider attribution cleared. + if (providers.length > 1 && succeeded.length > 0) { + ctx.repo.transaction(() => { + ctx.repo.setSetting(SETTING_MODELS_SYNCED_AT, String(syncedAt)); + ctx.repo.setSetting(SETTING_MODELS_SYNC_PROVIDER_ID, succeeded.length === 1 ? succeeded[0]!.providerId : ''); + }); + } + + return { + added, + updated, + removed, + total, + providerId: succeeded.length === 1 ? succeeded[0]!.providerId : '', + syncedAt, + latencyMs: outcomes.reduce((max, outcome) => Math.max(max, outcome.latencyMs), 0), + providers: outcomes, + }; +} diff --git a/src/admin/util.ts b/src/admin/util.ts index 24382b2..bfd86ff 100644 --- a/src/admin/util.ts +++ b/src/admin/util.ts @@ -103,15 +103,28 @@ export function optionalInt(value: unknown, field: string): number | null { return parsed; } +/** + * AD-12: the largest timestamp any client may filter on (9999-12-31T23:59:59.999Z). + * Without a bound a 400-digit `?since=` parsed to `Infinity` and silently returned + * an empty page instead of a `400`. + */ +export const MAX_TIMESTAMP_MS = 253_402_300_799_999; + export function asTimestamp(value: unknown): number | null { if (value === null || value === undefined || value === '') return null; - if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); + if (typeof value === 'number' && Number.isFinite(value)) { + return value >= 0 && value <= MAX_TIMESTAMP_MS ? Math.trunc(value) : null; + } if (typeof value === 'string') { const trimmed = value.trim(); if (trimmed.length === 0) return null; - if (/^\d+$/.test(trimmed)) return Number(trimmed); + if (/^\d+$/.test(trimmed)) { + const parsed = Number(trimmed); + if (!Number.isFinite(parsed) || parsed > MAX_TIMESTAMP_MS) return null; + return parsed; + } const parsed = Date.parse(trimmed); - if (Number.isFinite(parsed)) return parsed; + if (Number.isFinite(parsed) && parsed >= 0 && parsed <= MAX_TIMESTAMP_MS) return parsed; } return null; } @@ -151,12 +164,18 @@ const BLOCKED_V4: Array<{ bytes: number[]; bits: number }> = [ { bytes: [10, 0, 0, 0], bits: 8 }, { bytes: [172, 16, 0, 0], bits: 12 }, { bytes: [192, 168, 0, 0], bits: 16 }, + { bytes: [100, 64, 0, 0], bits: 10 }, // CGNAT (RFC 6598) / Tailscale + { bytes: [192, 0, 0, 0], bits: 24 }, // IETF protocol assignments (RFC 6890) + { bytes: [198, 18, 0, 0], bits: 15 }, // benchmarking (RFC 2544) ]; const BLOCKED_V6: Array<{ bytes: number[]; bits: number }> = [ + { bytes: v6Bytes('::'), bits: 128 }, // unspecified { bytes: v6Bytes('::1'), bits: 128 }, // loopback { bytes: v6Bytes('fc00::'), bits: 7 }, // unique-local { bytes: v6Bytes('fe80::'), bits: 10 }, // link-local + { bytes: v6Bytes('64:ff9b::'), bits: 96 }, // NAT64 (RFC 6052) + { bytes: v6Bytes('2002::'), bits: 16 }, // 6to4 (RFC 3056) ]; function v6Bytes(address: string): number[] { @@ -265,6 +284,26 @@ export function assertNoControlChars(value: string, field: string): void { } } +/** GW-10/AD-13: an API key is sent as an HTTP header, so it must be printable ASCII. */ +export const MAX_API_KEY_LENGTH = 4096; + +const PRINTABLE_ASCII = /^[\u0020-\u007e]+$/; + +/** + * Validates a user-submitted provider key without ever echoing it. A control + * character (CR/LF) makes `fetch` throw with the raw key in the message, and a + * non-ASCII byte throws `ERR_INVALID_CHAR` on the header write. + */ +export function assertApiKey(value: string, field = 'apiKey'): void { + assertNoControlChars(value, field); + if (!PRINTABLE_ASCII.test(value)) { + fail(400, 'invalid_request', `${field} must contain printable ASCII characters only`); + } + if (value.length > MAX_API_KEY_LENGTH) { + fail(400, 'invalid_request', `${field} must be at most ${MAX_API_KEY_LENGTH} characters`); + } +} + export function httpBaseUrl(value: unknown): string { const url = requireString(value, 'baseUrl'); assertNoControlChars(url, 'baseUrl'); @@ -402,7 +441,12 @@ export function activeKeyCount(ctx: AppContext): number { return ctx.repo.countActiveApiKeys(); } -export function buildHealth(ctx: AppContext): HealthSnapshot { +/** + * AD-14: `/stats` caches the expensive aggregates for ~2 s but reports + * `health.activeRequests` live. Both fields must come from one read of the + * counter, so callers pass the value they already snapshotted. + */ +export function buildHealth(ctx: AppContext, activeRequests: number = getActiveRequests()): HealthSnapshot { const now = Date.now(); const providers: ProviderHealthEntry[] = ctx.repo.listProviders().map((provider) => ({ id: provider.id, @@ -426,7 +470,7 @@ export function buildHealth(ctx: AppContext): HealthSnapshot { } return { status, - activeRequests: getActiveRequests(), + activeRequests, providers, modelsEnabled: ctx.repo.enabledModelIds().length, keysActive: activeKeyCount(ctx), @@ -445,6 +489,9 @@ export function settingTimestamp(ctx: AppContext, key: string): number | null { return Number.isFinite(parsed) ? parsed : null; } +/** AD-23: maximum accepted `/logs?search=` length (the query is a full table scan). */ +export const MAX_LOG_SEARCH_LENGTH = 200; + export function parseLogQuery(request: FastifyRequest): LogQuery { const query = queryOf(request); const surfaceRaw = asString(query.surface); @@ -459,6 +506,12 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { const stream = query.stream === undefined ? null : asBool(query.stream); if (ok === null && query.ok !== undefined) fail(400, 'invalid_request', 'ok must be true or false'); if (stream === null && query.stream !== undefined) fail(400, 'invalid_request', 'stream must be true or false'); + const search = asString(query.search); + // AD-23: `search` is a `LIKE '%…%'` scan; bound its length so a caller cannot hand + // the database an arbitrarily large pattern. + if (search !== null && search.length > MAX_LOG_SEARCH_LENGTH) { + fail(400, 'invalid_request', `search must be at most ${MAX_LOG_SEARCH_LENGTH} characters`); + } return { limit, offset, @@ -468,7 +521,7 @@ export function parseLogQuery(request: FastifyRequest): LogQuery { keyId: asString(query.keyId), ok, stream, - search: asString(query.search), + search, since: queryTimestamp(query.since, 'since'), until: queryTimestamp(query.until, 'until'), }; diff --git a/src/db/index.ts b/src/db/index.ts index 818c248..787a671 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -3,13 +3,25 @@ import { DatabaseSync } from 'node:sqlite'; import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; import type { AppConfig } from '../config.js'; -import { SCHEMA_SQL } from './schema.js'; +import { SCHEMA_SQL, SCHEMA_VERSION } from './schema.js'; export interface DbHandle { db: DatabaseSync; secret: string; } +/** Current `PRAGMA user_version`, or `null` when the file cannot answer it. */ +function schemaUserVersion(db: DatabaseSync): number | null { + try { + const row = db.prepare('PRAGMA user_version').get() as Record | undefined; + const value = row === undefined ? undefined : Object.values(row)[0]; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; + } catch { + return null; + } +} + /** * Opens (creating if needed) the sqlite database, applies the schema and makes * sure a persistent signing secret exists. @@ -18,6 +30,13 @@ export function openDatabase(config: AppConfig): DbHandle { const db = new DatabaseSync(config.dbPath); db.exec(SCHEMA_SQL); + // Stamp the schema generation only when it differs: the write needs the header lock, + // and an already-initialized file must not take it on every boot (a second process + // may be applying the schema while another holds a transaction). + if (schemaUserVersion(db) !== SCHEMA_VERSION) { + db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`); + } + const secretFile = resolve(config.dataDir, '.secret'); let secret = config.secret; if (!secret && existsSync(secretFile)) { diff --git a/src/db/repos.ts b/src/db/repos.ts index 6695582..8c590c5 100644 --- a/src/db/repos.ts +++ b/src/db/repos.ts @@ -43,8 +43,17 @@ export const DEFAULT_SETTINGS: Record = { model_allow_unknown: 'false', upstream_user_agent: 'opencode-router/1.0', stream_idle_timeout_ms: '120000', + // A-06: `0` means unlimited; any other value caps the buffered upstream + // response (the gateway reads it with `getInt`). + upstream_response_max_bytes: '0', }; +/** Longest `search` term accepted by `listLogs` (the clause stays a LIKE scan). */ +const MAX_LOG_SEARCH_CHARS = 200; + +/** Escapes the LIKE metacharacters so a user-supplied `%`/`_`/`\` matches literally. */ +const escapeLike = (value: string): string => value.replace(/[\\%_]/g, (match) => `\\${match}`); + export interface LogQuery { limit?: number; offset?: number; @@ -320,10 +329,28 @@ export class Repo { status === 529 || status >= 500 || (status >= 300 && status < 400); + // B-01: the deadline is monotonic — a shorter cooldown (or the scheduler's + // `cooldownMs: 0` probe) must never lower a cooldown that is still in force. + // `cooldownMs <= 0` therefore pins the provider to `now` only when nothing is + // active; a non-cooling failure still clears the column as before. + const nextCooldown = coolDown ? now + cooldownMs : null; this.stmt( - `UPDATE providers SET status=?, cooldown_until=?, last_error=?, last_checked_at=?, - failure_count=failure_count+1, updated_at=? WHERE id=?`, - ).run(rateLimited ? 'cooldown' : 'error', coolDown ? now + cooldownMs : null, error.slice(0, 500), now, now, id); + `UPDATE providers SET status=?, + cooldown_until=CASE + WHEN ? IS NULL THEN NULL + WHEN cooldown_until IS NOT NULL AND cooldown_until > ? THEN cooldown_until + ELSE ? END, + last_error=?, last_checked_at=?, failure_count=failure_count+1, updated_at=? WHERE id=?`, + ).run( + rateLimited ? 'cooldown' : 'error', + nextCooldown, + now, + nextCooldown, + error.slice(0, 500), + now, + now, + id, + ); } /* -------------------------------------------------------------------- models */ @@ -736,8 +763,10 @@ export class Repo { params.push(query.surface); } if (query.model) { - where.push('model = ?'); - params.push(query.model); + // B-18: "Model contains" — `LIKE` is ASCII case-insensitive by default in + // SQLite and the ESCAPE clause keeps `%`/`_`/`\` in the filter literal. + where.push("model LIKE '%' || ? || '%' ESCAPE '\\'"); + params.push(escapeLike(query.model)); } if (query.providerId) { where.push('provider_id = ?'); @@ -763,12 +792,15 @@ export class Repo { where.push('ts <= ?'); params.push(query.until); } - if (query.search) { + // B-18: `search` stays a scan (no FTS in this schema); the length is bounded + // so a hostile term cannot force SQLite into a huge LIKE pattern. + const search = query.search ? query.search.slice(0, MAX_LOG_SEARCH_CHARS) : ''; + if (search) { // `%`/`_` in the search term must be literals, not wildcards. where.push( "(model LIKE ? ESCAPE '\\' OR key_name LIKE ? ESCAPE '\\' OR provider_name LIKE ? ESCAPE '\\' OR error_message LIKE ? ESCAPE '\\')", ); - const like = `%${query.search.replace(/[\\%_]/g, (match) => `\\${match}`)}%`; + const like = `%${escapeLike(search)}%`; params.push(like, like, like, like); } const clause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : ''; @@ -786,34 +818,26 @@ export class Repo { return row ? this.mapLog(row) : null; } + /** B-03: both deletes share one transaction, so a crash cannot orphan attempts. */ deleteLogsBefore(ts: number): number { - const res = this.stmt('DELETE FROM request_logs WHERE ts < ?').run(ts); - this.stmt('DELETE FROM request_attempts WHERE ts < ?').run(ts); - return Number(res.changes); + return this.transaction(() => { + const res = this.stmt('DELETE FROM request_logs WHERE ts < ?').run(ts); + this.stmt('DELETE FROM request_attempts WHERE ts < ?').run(ts); + return Number(res.changes); + }); } + /** B-03: transactional counterpart of `deleteLogsBefore`. */ clearLogs(): number { - const res = this.stmt('DELETE FROM request_logs').run(); - this.stmt('DELETE FROM request_attempts').run(); - return Number(res.changes); + return this.transaction(() => { + const res = this.stmt('DELETE FROM request_logs').run(); + this.stmt('DELETE FROM request_attempts').run(); + return Number(res.changes); + }); } /* --------------------------------------------------------------------- stats */ - /** - * Nearest-rank percentile over the rows `ts >= since` with a non-null latency. - * `count` is the caller's `COUNT(latency_ms)` for the same predicate, so the - * OFFSET stays a single indexed lookup per percentile. - */ - private latencyPercentile(since: number, count: number, p: number): number { - if (count <= 0) return 0; - const index = Math.min(count - 1, Math.floor((p / 100) * count)); - const row = this.stmt( - 'SELECT latency_ms FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL ORDER BY latency_ms ASC LIMIT 1 OFFSET ?', - ).get(since, index) as Row | undefined; - return row ? num(row.latency_ms) : 0; - } - statsOverview(windowMs: number, bucketMs: number, activeRequests: number): StatsOverview { const since = Date.now() - windowMs; const totalsRow = this.stmt( @@ -831,11 +855,22 @@ export class Repo { ) .get(since) as Row; - const latencies = this.stmt('SELECT COUNT(latency_ms) AS c FROM request_logs WHERE ts >= ?').get(since) as Row; - const latencyCount = num(latencies.c); - // OPT-03: `ORDER BY latency_ms LIMIT 1 OFFSET k` uses the index instead of - // materializing and sorting every latency value of the window in JS. - const percentile = (p: number): number => this.latencyPercentile(since, latencyCount, p); + // B-02: every percentile comes from one ordered pass. The previous version ran + // a full `ORDER BY latency_ms ... OFFSET` per percentile (plus a COUNT), i.e. + // two extra sorts per cache miss; the window function replaces all three with a + // single statement and returns the nearest-rank values of the old definition. + const percentileRow = this.stmt( + `SELECT + COALESCE(MAX(CASE WHEN rn = MIN(total - 1, CAST((total * 50) / 100 AS INTEGER)) THEN latency_ms END), 0) AS p50, + COALESCE(MAX(CASE WHEN rn = MIN(total - 1, CAST((total * 95) / 100 AS INTEGER)) THEN latency_ms END), 0) AS p95 + FROM ( + SELECT latency_ms, + ROW_NUMBER() OVER (ORDER BY latency_ms ASC) - 1 AS rn, + COUNT(*) OVER () AS total + FROM request_logs WHERE ts >= ? AND latency_ms IS NOT NULL + )`, + ) + .get(since) as Row; const seriesRows = this.stmt( `SELECT CAST(ts / ? AS INTEGER) * ? AS bucket, @@ -941,8 +976,8 @@ export class Repo { reasoningTokens: num(totalsRow.reasoning_tokens), cachedTokens: num(totalsRow.cached_tokens), avgLatencyMs: Math.round(num(totalsRow.avg_latency)), - p50LatencyMs: percentile(50), - p95LatencyMs: percentile(95), + p50LatencyMs: num(percentileRow.p50), + p95LatencyMs: num(percentileRow.p95), avgTtfbMs: Math.round(num(totalsRow.avg_ttfb)), }, activeRequests, diff --git a/src/db/schema.ts b/src/db/schema.ts index 694a271..ef250e0 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -1,7 +1,21 @@ /** * SQLite schema. Executed idempotently on boot. */ + +/** + * Schema generation recorded in `PRAGMA user_version`. Bump it whenever a migration + * changes the shape of the database, so `/admin/api/diagnostics` can tell an operator + * that the data file was written by a different build. + * + * It is stamped by `openDatabase` (not by `SCHEMA_SQL`) because writing the header needs + * the database write lock: keeping the boot script lock-free when the file is already + * initialized lets a second process apply it while another holds a transaction. + */ +export const SCHEMA_VERSION = 1; + export const SCHEMA_SQL = ` +-- B-04: set before the WAL switch so lock contention during boot also waits. +PRAGMA busy_timeout = 5000; PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; diff --git a/src/gateway/errors.ts b/src/gateway/errors.ts index 1bf3b8b..b45e19f 100644 --- a/src/gateway/errors.ts +++ b/src/gateway/errors.ts @@ -32,17 +32,27 @@ export function installGatewayErrorHandler(scope: FastifyInstance, ctx: AppConte const surface = surfaceForUrl(request.url); const errorStatus = (error as FastifyError).statusCode; const status = error instanceof ApiError ? error.status : typeof errorStatus === 'number' ? errorStatus : 500; + const fastifyCode = (error as FastifyError).code; + // A-11: the body-limit failure must not expose the Fastify internal code + // (`FST_ERR_CTP_BODY_TOO_LARGE`) or claim a generic invalid request. + const payloadTooLarge = status === 413 || fastifyCode === 'FST_ERR_CTP_BODY_TOO_LARGE'; const apiError = error instanceof ApiError ? error - : new ApiError( - status >= 500 ? 'api_error' : 'invalid_request_error', - status >= 500 ? 'Internal server error.' : error.message, - { - status, - code: status >= 500 ? 'internal_error' : ((error as FastifyError).code ?? 'invalid_request'), - }, - ); + : payloadTooLarge + ? new ApiError( + 'invalid_request_error', + `Request body is too large; the configured body limit (BODY_LIMIT) is ${ctx.config.bodyLimit} bytes.`, + { status: 413, code: 'payload_too_large' }, + ) + : new ApiError( + status >= 500 ? 'api_error' : 'invalid_request_error', + status >= 500 ? 'Internal server error.' : error.message, + { + status, + code: status >= 500 ? 'internal_error' : (fastifyCode ?? 'invalid_request'), + }, + ); if (status >= 500) scope.log.error({ err: error, url: request.url }, 'gateway request failed'); if (reply.raw.headersSent || reply.raw.writableEnded) return; const state = request.gateway; diff --git a/src/gateway/forward-headers.ts b/src/gateway/forward-headers.ts index fdee0a0..2fb6ec2 100644 --- a/src/gateway/forward-headers.ts +++ b/src/gateway/forward-headers.ts @@ -17,6 +17,13 @@ const FORWARDED_HEADERS = [ 'openai-beta', 'accept', 'accept-language', + // A-09: provider-identity/attribution headers are client-supplied and carry no + // credential; dropping them broke project-scoped OpenAI routing and OpenRouter + // attribution. + 'openai-organization', + 'openai-project', + 'http-referer', + 'x-title', 'x-request-id', 'traceparent', 'tracestate', diff --git a/src/gateway/models-route.ts b/src/gateway/models-route.ts index 8502ad8..25443f8 100644 --- a/src/gateway/models-route.ts +++ b/src/gateway/models-route.ts @@ -43,7 +43,7 @@ export function toModelObject(model: ModelRow): Record { * Provider/attempts headers describe a proxied call, so they are never set here * (FIX-15); every `/v1/models*` response carries only the request id. */ -function finishModelsRequest( +export function finishModelsRequest( ctx: AppContext, request: FastifyRequest, reply: FastifyReply, @@ -73,7 +73,9 @@ function finishModelsRequest( return; } reply.header(ROUTER_REQUEST_ID_HEADER, state.requestId); - void reply.status(input.status); + // A-12: `reply.status()` returns the reply, so the call must not be discarded and + // the caller's status has to be applied before `send` runs. + reply.status(input.status); } export function registerModelsRoutes(app: FastifyInstance, ctx: AppContext): void { diff --git a/src/gateway/normalize.ts b/src/gateway/normalize.ts index 3fce890..b2cf207 100644 --- a/src/gateway/normalize.ts +++ b/src/gateway/normalize.ts @@ -10,6 +10,12 @@ export interface NormalizedBody { appliedEffort: string | null; /** True when `stream_options.include_usage` had to be injected. */ usageInjected: boolean; + /** + * A-04: true when this normalization actually changed the payload (model-id trim, + * reasoning-hint removal/rewrite or usage injection). The proxy picks raw bytes vs + * the normalized object from this flag instead of re-serializing both bodies. + */ + changed: boolean; } function asJson(value: unknown): Json | null { @@ -64,27 +70,39 @@ export function normalizeBody( options: { countTokens?: boolean } = {}, ): NormalizedBody { const next: Json = { ...body }; + let changed = false; // GW-11: the gateway routes and logs the trimmed model id, so the trimmed id is // also what the provider must receive (`" x "` would otherwise be rejected). if (typeof next.model === 'string' && next.model !== next.model.trim() && next.model.trim().length > 0) { next.model = next.model.trim(); + changed = true; } let requestedEffort = requestedEffortFor(surface, body); let appliedEffort: string | null = null; if (model && model.reasoning.supported === false) { - // Non-reasoning models: providers reject unknown reasoning hints. - delete next.reasoning_effort; - delete next.reasoning; - delete next.thinking; + // Non-reasoning models: providers reject unknown reasoning hints. Only a key that + // is actually present counts as a change (`undefined` is dropped by JSON anyway). + for (const key of ['reasoning_effort', 'reasoning', 'thinking']) { + if (next[key] !== undefined) { + delete next[key]; + changed = true; + } + } requestedEffort = null; } else if (model && model.reasoning.supported) { if (surface === 'chat' && requestedEffort !== null) { appliedEffort = resolveEffort(requestedEffort, model.reasoning.efforts); - if (appliedEffort !== null) next.reasoning_effort = appliedEffort; + if (appliedEffort !== null) { + if (next.reasoning_effort !== appliedEffort) changed = true; + next.reasoning_effort = appliedEffort; + } } else if (surface === 'responses' && requestedEffort !== null) { appliedEffort = resolveEffort(requestedEffort, model.reasoning.efforts); - if (appliedEffort !== null) next.reasoning = { ...(asJson(body.reasoning) ?? {}), effort: appliedEffort }; + if (appliedEffort !== null) { + if (asJson(body.reasoning)?.effort !== appliedEffort) changed = true; + next.reasoning = { ...(asJson(body.reasoning) ?? {}), effort: appliedEffort }; + } } // messages: `thinking` is passed through untouched, the budget is authoritative. } @@ -95,8 +113,9 @@ export function normalizeBody( if (existing?.include_usage !== true) { next.stream_options = { ...(existing ?? {}), include_usage: true }; usageInjected = true; + changed = true; } } - return { body: next, requestedEffort, appliedEffort, usageInjected }; + return { body: next, requestedEffort, appliedEffort, usageInjected, changed }; } diff --git a/src/gateway/not-found.ts b/src/gateway/not-found.ts index 27d6f0a..0cef54a 100644 --- a/src/gateway/not-found.ts +++ b/src/gateway/not-found.ts @@ -5,6 +5,33 @@ import { sendApiError, surfaceForUrl } from './errors.js'; import { recordRequestLog } from './logging.js'; import { gatewayState } from './preauth.js'; +interface KnownRoute { + /** Path (no query string) matcher. */ + match: (path: string) => boolean; + methods: readonly string[]; +} + +/** + * A-13: real gateway routes keyed by path, so a known path called with the wrong + * method gets a `405` + `Allow` instead of a misleading `404 unknown_endpoint`. + * `HEAD` is implied by `GET`, matching Fastify's exposeHeadRoutes default. + */ +const KNOWN_GATEWAY_ROUTES: readonly KnownRoute[] = [ + { match: (path) => path === '/v1/chat/completions', methods: ['POST'] }, + { match: (path) => path === '/v1/responses', methods: ['POST'] }, + { match: (path) => path === '/v1/messages', methods: ['POST'] }, + { match: (path) => path === '/v1/messages/count_tokens', methods: ['POST'] }, + { match: (path) => path === '/v1/models', methods: ['GET', 'HEAD'] }, + { match: (path) => path.startsWith('/v1/models/'), methods: ['GET', 'HEAD'] }, +]; + +function knownMethodsFor(path: string): readonly string[] | null { + for (const route of KNOWN_GATEWAY_ROUTES) { + if (route.match(path)) return route.methods; + } + return null; +} + /** * GW-04: unknown `/v1/*` paths used to fall through to the root not-found handler, * which runs outside the gateway scope — so the API-key hook never ran (anonymous @@ -12,15 +39,27 @@ import { gatewayState } from './preauth.js'; * * This catch-all lives inside the authenticated gateway scope and is registered * last, so real routes always win. It still writes exactly one log row and answers - * with the surface-shaped error envelope. + * with the surface-shaped error envelope; a known path with an unsupported method + * answers `405` plus an `Allow` header (A-13). */ export function registerUnknownGatewayRoutes(app: FastifyInstance, ctx: AppContext): void { const handler = async (request: FastifyRequest, reply: FastifyReply): Promise => { const state = gatewayState(request); const surface = surfaceForUrl(request.url); - const error = new ApiError('not_found_error', `Unknown endpoint: ${request.method} ${request.url}`, { - code: 'unknown_endpoint', - }); + const queryIndex = request.url.indexOf('?'); + const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); + const allowed = knownMethodsFor(path); + const error = + allowed === null + ? new ApiError('not_found_error', `Unknown endpoint: ${request.method} ${request.url}`, { + code: 'unknown_endpoint', + }) + : new ApiError( + 'invalid_request_error', + `${request.method} is not allowed on ${path}; supported method(s): ${allowed.join(', ')}.`, + { status: 405, code: 'method_not_allowed' }, + ); + if (allowed !== null) reply.header('allow', allowed.join(', ')); const userAgent = request.headers['user-agent']; state.logged = true; recordRequestLog(ctx, { @@ -45,4 +84,4 @@ export function registerUnknownGatewayRoutes(app: FastifyInstance, ctx: AppConte app.all('/v1/*', handler); // `/v1` itself is not covered by the wildcard; it is just as unknown. app.all('/v1', handler); -} \ No newline at end of file +} diff --git a/src/gateway/preauth.ts b/src/gateway/preauth.ts index d22035b..b26356b 100644 --- a/src/gateway/preauth.ts +++ b/src/gateway/preauth.ts @@ -81,10 +81,8 @@ function rejectUnauthenticated( const surface = surfaceForUrl(request.url); const userAgent = request.headers['user-agent']; - // Rejected calls still occupied an inbound socket; the pair keeps the counter - // accounting symmetric with the route handlers and floors at zero. - incActiveRequests(); - decActiveRequests(); + // The active-request counter is owned by the gateway onRequest/onResponse hooks + // (A-03), so a rejection here is already accounted for. // Every log row gets its paired start event, rejections included, so SSE // consumers never see an orphan `request:end`. @@ -136,6 +134,21 @@ export function gatewayState(request: FastifyRequest): GatewayRequestState { * when the client body is not valid UTF-8. */ export function installGatewayHooks(scope: FastifyInstance, ctx: AppContext): void { + // A-03: the whole gateway lifecycle (models routes and pre-attempt rejections + // included) is bracketed by exactly one inc/dec pair. The counting hook runs + // before authentication so a rejected request is still counted while in flight. + scope.addHook('onRequest', async (_request: FastifyRequest, reply: FastifyReply) => { + incActiveRequests(); + let released = false; + const release = (): void => { + if (released) return; + released = true; + decActiveRequests(); + }; + // `close` fires once for a finished, aborted, hijacked or injected response, so + // the counter is always released exactly once per request. + reply.raw.once('close', release); + }); scope.addHook('onRequest', createPreAuthHook(ctx)); // Encapsulated to this scope: admin keeps its own lenient parser. diff --git a/src/gateway/proxy.ts b/src/gateway/proxy.ts index 7f29140..f3f902d 100644 --- a/src/gateway/proxy.ts +++ b/src/gateway/proxy.ts @@ -1,7 +1,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; -import { decActiveRequests, incActiveRequests, type AppContext } from '../core/context.js'; +import type { AppContext } from '../core/context.js'; import type { ApiKeyRow, Json, ProviderRow, Surface, Usage } from '../types.js'; -import { ApiError, isRetryableStatus, upstreamErrorFrom } from '../util/errors.js'; +import { ApiError, isRetryableStatus, scrubSecrets, upstreamErrorFrom } from '../util/errors.js'; import { SseParser } from '../util/sse.js'; import { upstreamFetch, type UpstreamResponse } from '../util/upstream.js'; import { forwardHeaders } from './forward-headers.js'; @@ -48,15 +48,63 @@ const PROXY_ROUTES: ProxyRoute[] = [ }, ]; -/** Decodes `retry-after` (delta seconds or HTTP-date) into milliseconds. */ -export function retryAfterMs(value: string | null, now = Date.now()): number | null { +/** A-01: ceiling for an upstream `Retry-After`; a broken provider cannot pin a year-long cooldown. */ +export const MAX_RETRY_AFTER_MS = 3_600_000; + +export interface ParsedRetryAfter { + /** Clamped millisecond value used for the cooldown. */ + ms: number; + /** True when the raw upstream value exceeded `MAX_RETRY_AFTER_MS` and was clamped. */ + capped: boolean; + /** Raw header value, for a single debug log at the call site. */ + raw: string; +} + +/** + * A-01: decodes `retry-after` (delta seconds or HTTP-date) and clamps it to + * `MAX_RETRY_AFTER_MS` on both branches. + */ +export function parseRetryAfter(value: string | null, now = Date.now()): ParsedRetryAfter | null { if (value === null) return null; + const raw = value.trim(); + if (raw.length === 0) return null; + let ms: number | null = null; + if (/^\d+$/.test(raw)) { + ms = Number.parseInt(raw, 10) * 1000; + } else { + const date = Date.parse(raw); + if (Number.isFinite(date)) ms = Math.max(0, date - now); + } + if (ms === null || Number.isNaN(ms)) return null; + if (ms > MAX_RETRY_AFTER_MS) return { ms: MAX_RETRY_AFTER_MS, capped: true, raw }; + return { ms, capped: false, raw }; +} + +/** Decodes `retry-after` into (clamped) milliseconds. */ +export function retryAfterMs(value: string | null, now = Date.now()): number | null { + const parsed = parseRetryAfter(value, now); + return parsed === null ? null : parsed.ms; +} + +/** `upstream_response_max_bytes` maximum (1 GiB); `0` disables the cap. */ +export const MAX_UPSTREAM_RESPONSE_BYTES = 1_073_741_824; +/** Smallest meaningful non-zero cap (1 KiB); smaller values are ignored. */ +export const MIN_UPSTREAM_RESPONSE_BYTES = 1_024; + +/** + * A-06: parses the `upstream_response_max_bytes` setting. `0` (the default) means + * unlimited; a non-zero cap must be within 1 KiB..1 GiB. Anything else falls back to + * the documented default (`0`) instead of failing every request on a bad setting. + */ +export function parseUpstreamResponseMaxBytes(value: string | null | undefined): number { + if (value === null || value === undefined) return 0; const trimmed = value.trim(); - if (trimmed.length === 0) return null; - if (/^\d+$/.test(trimmed)) return Number.parseInt(trimmed, 10) * 1000; - const date = Date.parse(trimmed); - if (!Number.isFinite(date)) return null; - return Math.max(0, date - now); + if (!/^\d+$/.test(trimmed)) return 0; + const parsed = Number.parseInt(trimmed, 10); + if (!Number.isFinite(parsed)) return 0; + if (parsed === 0) return 0; + if (parsed < MIN_UPSTREAM_RESPONSE_BYTES || parsed > MAX_UPSTREAM_RESPONSE_BYTES) return 0; + return parsed; } function isTimeoutReason(reason: string | null): boolean { @@ -227,6 +275,8 @@ async function readResponseText(response: Response): Promise { interface AttemptOptions { requestId: string; attempt: number; + /** Upstream path, including the client's raw query string (A-08). */ + path: string; /** Total deadline for the whole upstream exchange (headers + body). */ timeoutMs: number; cooldownMs: number; @@ -252,7 +302,7 @@ async function runAttempt( upstream = await upstreamFetch({ baseUrl: provider.baseUrl, apiKey: provider.apiKey, - path: route.upstreamPath, + path: options.path, method: 'POST', ...(options.rawBody !== null ? { rawBody: options.rawBody } : { body: options.body }), headers: options.headers, @@ -302,7 +352,7 @@ async function runAttempt( status: 502, code: 'upstream_redirect', }) - : upstreamErrorFrom(upstream.status, text, provider.name); + : upstreamErrorFrom(upstream.status, text, provider.name, [provider.apiKey]); ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, @@ -333,10 +383,18 @@ async function runAttempt( } if (isRetryableStatus(upstream.status)) { - // FEAT-01: an upstream Retry-After is authoritative when longer than the - // configured cooldown, so the provider is not retried before it recovers. - const retryAfter = retryAfterMs(upstream.headers.get('retry-after')); - const cooldownMs = retryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, retryAfter); + // FEAT-01/A-01: an upstream Retry-After is authoritative when longer than the + // configured cooldown, but it is clamped so a hostile value cannot pin the + // provider in cooldown forever. + const parsedRetryAfter = parseRetryAfter(upstream.headers.get('retry-after')); + if (parsedRetryAfter?.capped === true) { + ctx.logger.debug( + { providerId: provider.id, retryAfter: parsedRetryAfter.raw, cappedMs: parsedRetryAfter.ms }, + 'upstream Retry-After clamped', + ); + } + const cooldownMs = + parsedRetryAfter === null ? options.cooldownMs : Math.max(options.cooldownMs, parsedRetryAfter.ms); ctx.repo.recordProviderFailure(provider.id, upstream.status, mapped.message, cooldownMs); emitProvider(ctx, { providerId: provider.id, @@ -397,7 +455,11 @@ async function runAttempt( const apiError = error instanceof ApiError ? error - : new ApiError('connection_error', error instanceof Error ? error.message : String(error)); + : new ApiError( + 'connection_error', + // Defence in depth (A-05/A-10): a runtime message must never carry the key. + scrubSecrets(error instanceof Error ? error.message : String(error), [provider.apiKey]), + ); ctx.repo.insertAttempt( newAttempt({ requestId: options.requestId, @@ -457,33 +519,58 @@ export function stripXOpencode(value: unknown): unknown { return changed ? out : value; } -/** Removes provider-internal `x_opencode` keys, keeping all other bytes when possible. */ -export function stripTopLevelXOpencode(buffer: Buffer): Buffer { - const text = buffer.toString('utf8'); - if (!text.includes('x_opencode')) return buffer; +/** + * A-06: string form of `stripTopLevelXOpencode`. The caller decodes the body once and + * reuses the returned text for the usage parse instead of decoding it twice. + */ +export function stripXOpencodeText(text: string): { text: string; changed: boolean } { + if (!text.includes('x_opencode')) return { text, changed: false }; try { const parsed = JSON.parse(text) as unknown; const stripped = stripXOpencode(parsed); - if (stripped !== parsed) return Buffer.from(JSON.stringify(stripped), 'utf8'); + if (stripped !== parsed) return { text: JSON.stringify(stripped), changed: true }; } catch { /* not JSON, forward untouched */ } - return buffer; + return { text, changed: false }; +} + +/** Removes provider-internal `x_opencode` keys, keeping all other bytes when possible. */ +export function stripTopLevelXOpencode(buffer: Buffer): Buffer { + const result = stripXOpencodeText(buffer.toString('utf8')); + return result.changed ? Buffer.from(result.text, 'utf8') : buffer; } -/** Rewrites a single SSE frame only when it carries a provider `x_opencode` key. */ +/** + * A-07: rewrites a single SSE frame only when it carries a provider `x_opencode` key. + * Every `data:` line of the frame is joined (SSE semantics) before parsing, and a + * change is re-emitted as one canonical `data:` line; an untouched frame is returned + * byte-identical so invalid UTF-8 / BOMs are never re-encoded. + */ export function rewriteSseFrame(frame: string): string { if (!frame.includes('x_opencode')) return frame; const lines = frame.split('\n'); - const index = lines.findIndex((line) => line.startsWith('data:')); - if (index === -1) return frame; - const payload = lines[index]!.slice(5).replace(/^ /, ''); + const dataIndexes: number[] = []; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]!.endsWith('\r') ? lines[index]!.slice(0, -1) : lines[index]!; + if (line.startsWith('data:')) dataIndexes.push(index); + } + if (dataIndexes.length === 0) return frame; + const payload = dataIndexes + .map((index) => { + const line = lines[index]!; + const body = (line.endsWith('\r') ? line.slice(0, -1) : line).slice(5).replace(/^ /, ''); + return body; + }) + .join('\n'); if (!payload.startsWith('{')) return frame; try { const parsed = JSON.parse(payload) as unknown; const stripped = stripXOpencode(parsed); if (stripped === parsed) return frame; - lines[index] = `data: ${JSON.stringify(stripped)}`; + lines[dataIndexes[0]!] = `data: ${JSON.stringify(stripped)}`; + // Drop the remaining data lines; a single canonical line stands for the frame. + for (let index = dataIndexes.length - 1; index >= 1; index -= 1) lines.splice(dataIndexes[index]!, 1); return lines.join('\n'); } catch { return frame; @@ -509,13 +596,37 @@ function writeFrame(reply: FastifyReply, frame: Buffer, delimiter: Buffer): bool } } -/** Returns the byte range of the frame terminator, favouring CRLFCRLF when earlier. */ -function nextBoundary(buffer: Buffer): { index: number; length: number } | null { - const lf = buffer.indexOf('\n\n'); - const crlf = buffer.indexOf('\r\n\r\n'); - if (lf === -1 && crlf === -1) return null; - if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 }; - return { index: lf, length: 2 }; +/** + * A-07: returns the byte range of the earliest SSE frame terminator. All separators + * Node streams may emit are recognized (`\r\n\r\n`, `\n\n`, `\r\n\n`, `\n\r\n`, `\r\r`), + * so a provider using a mixed line ending no longer stalls until the idle timeout. + */ +export function nextBoundary(buffer: Buffer): { index: number; length: number } | null { + let index = 0; + while (index < buffer.length) { + // Jump between candidate line-ending bytes so large frames are not scanned byte + // by byte in JS (the buffers can be up to the SSE frame cap). + const lf = buffer.indexOf(0x0a, index); + const cr = buffer.indexOf(0x0d, index); + if (lf === -1 && cr === -1) return null; + index = cr === -1 ? lf : lf === -1 ? cr : Math.min(lf, cr); + const byte = buffer[index]!; + const second = buffer[index + 1]; + if (byte === 0x0a) { + // \n\n / \n\r\n + if (second === 0x0a) return { index, length: 2 }; + if (second === 0x0d && buffer[index + 2] === 0x0a) return { index, length: 3 }; + } else { + // \r\r / \r\n\r\n / \r\n\n + if (second === 0x0d) return { index, length: 2 }; + if (second === 0x0a) { + if (buffer[index + 2] === 0x0d && buffer[index + 3] === 0x0a) return { index, length: 4 }; + if (buffer[index + 2] === 0x0a) return { index, length: 3 }; + } + } + index += 1; + } + return null; } /** @@ -799,10 +910,22 @@ async function jsonSurface( upstream: UpstreamResponse, attempts: number, ttfbMs: number, + maxBytes: number, ): Promise { let buffer: Buffer; try { - buffer = stripTopLevelXOpencode(Buffer.from(await upstream.response.arrayBuffer())); + // A-06: refuse an upstream that already declares an oversized body before it is + // buffered at all; the cap is opt-in (`0` = unlimited). + const declared = Number(upstream.headers.get('content-length')); + if (maxBytes > 0 && Number.isFinite(declared) && declared > maxBytes) { + try { + await upstream.response.body?.cancel(); + } catch { + /* body already gone */ + } + return tooLargeOutcome(ttfbMs, maxBytes); + } + buffer = Buffer.from(await upstream.response.arrayBuffer()); } catch (error) { // Nothing has been written to the client yet, so the caller can still return // an error response; a timeout must not surface as the upstream's 2xx status. @@ -820,18 +943,25 @@ async function jsonSurface( } finally { disposeUpstream(upstream); } - const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(buffer.toString('utf8')))); + // Decode the buffered body exactly once and reuse the text for the x_opencode strip + // and the usage parse (A-06); the original bytes are kept for byte-faithful output. + const decoded = buffer.toString('utf8'); + const stripped = stripXOpencodeText(decoded); + const bodyText = stripped.text; + const body = stripped.changed ? Buffer.from(bodyText, 'utf8') : buffer; + if (maxBytes > 0 && body.byteLength > maxBytes) return tooLargeOutcome(ttfbMs, maxBytes); + const usage = mergeUsage(emptyUsage(), extractUsageFromJson(parseJson(bodyText))); // GW-09: forward the upstream retry/rate-limit/request-id headers; the router and // the rewritten body (content-type/length) always win. const headers = forwardedResponseHeaders(upstream.headers, { 'content-type': upstream.headers.get('content-type') ?? 'application/json', - 'content-length': String(buffer.byteLength), + 'content-length': String(body.byteLength), ...routerHeaders(provider, requestId, attempts), }); try { reply.hijack(); reply.raw.writeHead(upstream.status, headers); - reply.raw.end(buffer); + reply.raw.end(body); } catch (error) { return { status: upstream.status, @@ -856,13 +986,18 @@ async function jsonSurface( }; } -/** - * `normalizeBody` returned a shallow copy; the raw bytes can only be reused when - * no logical change happened. The JSON round-trip is the documented comparison - * (FIX-09) and only decides *which* representation is sent, never rewrites it. - */ -function hasLogicalChange(original: Json, normalized: Json): boolean { - return JSON.stringify(normalized) !== JSON.stringify(original); +/** A-06: failure outcome for an upstream body that exceeds the configured cap. */ +function tooLargeOutcome(ttfbMs: number | null, maxBytes: number): SurfaceOutcome { + return { + status: 502, + ok: false, + aborted: false, + timedOut: false, + ttfbMs, + usage: emptyUsage(), + errorCode: 'upstream_response_too_large', + errorMessage: `Upstream response exceeds the configured upstream_response_max_bytes limit (${maxBytes} bytes).`, + }; } /* -------------------------------------------------------------------- handler */ @@ -881,8 +1016,6 @@ async function handleProxyRequest( const userAgentHeader = request.headers['user-agent']; const clientUserAgent = typeof userAgentHeader === 'string' ? userAgentHeader : null; - incActiveRequests(); - const key: ApiKeyRow | null = state.key; let modelId: string | null = null; let stream = false; @@ -937,8 +1070,12 @@ async function handleProxyRequest( const normalized = normalizeBody(surface, body, model, { countTokens: route.countTokens === true }); const normalizedBody = normalized.body; const rawBody = state.rawBody; - // Forward the client bytes verbatim whenever normalization changed nothing. - const upstreamBody = rawBody !== null && !hasLogicalChange(body, normalizedBody) ? null : normalizedBody; + // Forward the client bytes verbatim when normalization changed nothing; the + // explicit flag replaces the old double JSON.stringify comparison (A-04). + const upstreamBody = rawBody !== null && !normalized.changed ? null : normalizedBody; + // A-08: provider-specific query flags (`?beta=true`, `?version=…`) must survive. + const queryIndex = request.url.indexOf('?'); + const upstreamPath = `${route.upstreamPath}${queryIndex === -1 ? '' : request.url.slice(queryIndex)}`; const cooldownMs = Math.max(0, ctx.repo.getInt('provider_cooldown_ms', 60_000)); const maxRetries = Math.max(1, ctx.repo.getInt('max_retries', 3)); @@ -950,6 +1087,10 @@ async function handleProxyRequest( ctx.repo.getInt('stream_idle_timeout_ms', DEFAULT_STREAM_IDLE_MS), ); const upstreamUserAgent = ctx.repo.getSetting('upstream_user_agent') ?? 'opencode-router/1.0'; + // A-06: opt-in ceiling for buffered (non-streaming) upstream response bodies. + const upstreamResponseMaxBytes = parseUpstreamResponseMaxBytes( + ctx.repo.getSetting('upstream_response_max_bytes'), + ); const strategy = parseRotationStrategy(ctx.repo.getSetting('rotation_strategy')); const requestHeaders = forwardHeaders(request.headers, { acceptJson: !stream || route.countTokens === true }); @@ -985,6 +1126,7 @@ async function handleProxyRequest( const attempt = await runAttempt(ctx, fresh, route, { requestId, attempt: attemptNo, + path: upstreamPath, timeoutMs, cooldownMs, userAgent: upstreamUserAgent, @@ -1022,7 +1164,16 @@ async function handleProxyRequest( guard, idleMs: streamIdleMs, }) - : await jsonSurface(reply, surface, requestId, fresh, attempt.response, attempts, attempt.latencyMs); + : await jsonSurface( + reply, + surface, + requestId, + fresh, + attempt.response, + attempts, + attempt.latencyMs, + upstreamResponseMaxBytes, + ); usage = outcome.usage; ttfbMs = outcome.ttfbMs; logStatus = outcome.status; @@ -1068,6 +1219,9 @@ async function handleProxyRequest( throw fatalError; } else if (attempts > 0 && everyFailureRateLimited && lastStatus === 429) { // FEAT-06: hand SDK clients a concrete backoff instead of a hot retry loop. + // A-02: real attempts happened, so the log row and router headers are + // attributed to the last provider that answered. + provider = lastAttemptProvider; const cooldownUntil = smallestCooldownUntil(ctx.repo.listProviders()); const retryAfter = retryAfterSeconds(cooldownUntil); reply.header('retry-after', String(retryAfter)); @@ -1086,6 +1240,9 @@ async function handleProxyRequest( code: 'upstream_timeout', }); } else { + // A-02: attribute the aggregated failure to the last attempted provider + // (null when nothing was attempted, e.g. every candidate cooling down). + provider = lastAttemptProvider; // A 3xx from upstream is never replayed to the client as a redirect // (FIX-08), so only real error statuses are forwarded. const status = lastStatus !== null && lastStatus >= 400 ? lastStatus : (lastError?.status ?? 502); @@ -1127,7 +1284,6 @@ async function handleProxyRequest( } } finally { guard?.dispose(); - decActiveRequests(); state.logged = true; recordRequestLog(ctx, { requestId, diff --git a/src/gateway/rotation.ts b/src/gateway/rotation.ts index 4e8697c..f89776f 100644 --- a/src/gateway/rotation.ts +++ b/src/gateway/rotation.ts @@ -26,10 +26,10 @@ export function enabledProviders(providers: ProviderRow[]): ProviderRow[] { } /** Fisher-Yates shuffle on a copy; the cursor is meaningless for `random`. */ -function shuffled(providers: ProviderRow[]): ProviderRow[] { +function shuffled(providers: ProviderRow[], random: () => number): ProviderRow[] { const items = [...providers]; for (let index = items.length - 1; index > 0; index -= 1) { - const swap = Math.floor(Math.random() * (index + 1)); + const swap = Math.floor(random() * (index + 1)); const current = items[index]!; items[index] = items[swap]!; items[swap] = current; @@ -37,6 +37,11 @@ function shuffled(providers: ProviderRow[]): ProviderRow[] { return items; } +/** Test seam for the random strategy (A-15): production callers keep `Math.random`. */ +export interface RotationOptions { + random?: () => number; +} + /** * Puts the candidates in attempt order for the configured strategy: * @@ -48,9 +53,10 @@ function shuffled(providers: ProviderRow[]): ProviderRow[] { function orderedProviders( providers: ProviderRow[], strategy: RotationStrategy = 'round-robin', + random: () => number = Math.random, ): ProviderRow[] { if (providers.length === 0) return []; - if (strategy === 'random') return shuffled(providers); + if (strategy === 'random') return shuffled(providers, random); if (strategy === 'priority') return [...providers]; const start = cursor % providers.length; cursor = (start + 1) % providers.length; @@ -76,10 +82,11 @@ export function orderProviders( providers: ProviderRow[], now = Date.now(), strategy: RotationStrategy = 'round-robin', + options: RotationOptions = {}, ): ProviderRotation { const enabled = enabledProviders(providers); if (enabled.length === 0) return { candidates: [], cooldownFallback: false }; - const ordered = orderedProviders(enabled, strategy); + const ordered = orderedProviders(enabled, strategy, options.random); const warm = ordered.filter((provider) => provider.cooldownUntil === null || provider.cooldownUntil <= now); if (warm.length > 0) return { candidates: warm, cooldownFallback: false }; const leastCooling = [...ordered].sort((a, b) => (a.cooldownUntil ?? 0) - (b.cooldownUntil ?? 0)); diff --git a/src/index.ts b/src/index.ts index 1c0ed63..ba534d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ import { loadConfig } from './config.js'; import { openDatabase } from './db/index.js'; import { Repo } from './db/repos.js'; import { EventBus } from './core/events.js'; -import { seedDefaults, pruneLogs } from './core/seed.js'; +import { seedDefaults, pruneLogs, verifyDashboardPassword } from './core/seed.js'; import { registerGracefulShutdown } from './core/shutdown.js'; import { buildServer } from './server.js'; import { startScheduler } from './admin/scheduler.js'; @@ -26,6 +26,13 @@ async function main(): Promise { const app = await buildServer(ctx); seedDefaults(ctx); + // SEC-09: the shipped default password opens every fresh install, so say so loudly. + // A warning (not a failure) keeps first-run usable while making the risk visible. + if (verifyDashboardPassword(ctx, ctx.config.defaultDashboardPassword)) { + app.log.warn( + 'The dashboard password is still the built-in default. Change it in Settings > Security, or set DASHBOARD_PASSWORD before the first boot.', + ); + } const stopScheduler = startScheduler(ctx); app.addHook('onClose', async () => { diff --git a/src/util/errors.ts b/src/util/errors.ts index 56ce087..5f300f9 100644 --- a/src/util/errors.ts +++ b/src/util/errors.ts @@ -12,6 +12,20 @@ export type ErrorType = | 'connection_error' | 'upstream_error'; +/** Runtime membership set for the `ErrorType` union (A-05: never trust a provider's `type`). */ +const ERROR_TYPES: ReadonlySet = new Set([ + 'invalid_request_error', + 'authentication_error', + 'permission_error', + 'not_found_error', + 'rate_limit_error', + 'overloaded_error', + 'api_error', + 'timeout_error', + 'connection_error', + 'upstream_error', +]); + const STATUS_BY_TYPE: Record = { invalid_request_error: 400, authentication_error: 401, @@ -71,11 +85,69 @@ export function errorTypeForStatus(status: number): ErrorType { return 'api_error'; } +/** True when a provider-supplied `type` is one of the documented envelope types (A-05). */ +export function isErrorType(value: unknown): value is ErrorType { + return typeof value === 'string' && ERROR_TYPES.has(value); +} + +/** + * A-14: every `5xx` is retryable per SPEC §2.1 step 8 (`501`/`505`/`507`/... included); + * `408`/`409`/`425`/`429` are retryable without being server errors. + */ export function isRetryableStatus(status: number): boolean { - return status === 408 || status === 409 || status === 425 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504 || status === 529; + if (status === 408 || status === 409 || status === 425 || status === 429) return true; + return status >= 500 && status <= 599; +} + +/** Longest upstream error message persisted to `request_logs`/`providers.last_error`. */ +export const MAX_ERROR_MESSAGE_LENGTH = 500; + +const REDACTED = '[redacted]'; +// Credential shapes an upstream may echo back: auth header echoes, `Bearer …` and +// `sk-…` style tokens. The configured provider key is removed literally too. +const BEARER_TOKEN = /\bBearer\s+[A-Za-z0-9._~+/=-]{4,}/gi; +const SK_TOKEN = /\bsk-[A-Za-z0-9._-]{4,}/g; +const NAMED_SECRET = /\b(authorization|x-api-key|api[_-]?key)("?\s*[:=]\s*"?)[^"'\s,;}]+/gi; + +/** + * A-05: replaces every known credential (the configured provider key plus + * `Bearer …`/`sk-…`/`x-api-key`-shaped tokens) before an upstream message is + * persisted, logged or returned to a client. + */ +export function scrubSecrets(text: string, secrets: readonly string[] = []): string { + let out = text; + for (const secret of secrets) { + if (secret.length === 0) continue; + out = out.split(secret).join(REDACTED); + } + out = out.replace(BEARER_TOKEN, `Bearer ${REDACTED}`); + out = out.replace(SK_TOKEN, REDACTED); + out = out.replace(NAMED_SECRET, (_match, name: string, separator: string) => `${name}${separator}${REDACTED}`); + return out; +} + +/** + * A-05: control characters are removed, credentials scrubbed, and the result is + * clamped to `MAX_ERROR_MESSAGE_LENGTH`. Scrubbing runs before the clamp so a key + * cannot survive by straddling the cut. + */ +export function sanitizeErrorMessage(text: string, secrets: readonly string[] = []): string { + const printable = text.replace(/[\u0000-\u001F\u007F]/g, ''); + const scrubbed = scrubSecrets(printable, secrets); + return scrubbed.length > MAX_ERROR_MESSAGE_LENGTH ? scrubbed.slice(0, MAX_ERROR_MESSAGE_LENGTH) : scrubbed; } -export function upstreamErrorFrom(status: number, body: string, provider: string): ApiError { +/** + * Maps an upstream error body onto an `ApiError`. `secrets` are scrubbed from the + * resulting message so a provider echoing the request cannot leak its own key into + * `request_logs`, `providers.last_error` or a client-visible body (A-05). + */ +export function upstreamErrorFrom( + status: number, + body: string, + provider: string, + secrets: readonly string[] = [], +): ApiError { let message = `Upstream provider "${provider}" returned HTTP ${status}`; let type: ErrorType = errorTypeForStatus(status); let code: string | null = null; @@ -85,12 +157,14 @@ export function upstreamErrorFrom(status: number, body: string, provider: string if (typeof nested.message === 'string') message = nested.message; if (typeof parsed.type === 'string' && parsed.type === 'error') { const inner = parsed.error as Record | undefined; - if (inner && typeof inner.type === 'string') type = inner.type as ErrorType; + // An unknown type must never reach `ApiError.toJSON` as an undeclared value. + if (inner && isErrorType(inner.type)) type = inner.type; + else if (inner && typeof inner.type === 'string') type = 'api_error'; if (inner && typeof inner.message === 'string') message = inner.message; } if (typeof nested.code === 'string' || typeof nested.code === 'number') code = String(nested.code); } catch { - if (body.trim().length > 0) message = body.trim().slice(0, 500); + if (body.trim().length > 0) message = body.trim(); } - return new ApiError(type, message, { status, code: code ?? undefined }); + return new ApiError(type, sanitizeErrorMessage(message, secrets), { status, code: code ?? undefined }); } diff --git a/src/util/upstream.ts b/src/util/upstream.ts index 1c3e785..eb659e3 100644 --- a/src/util/upstream.ts +++ b/src/util/upstream.ts @@ -1,10 +1,35 @@ -import { ApiError } from './errors.js'; +import { ApiError, scrubSecrets } from './errors.js'; +/** + * Joins a provider base URL with an upstream path, keeping a query string that is + * already part of the base and appending with `&` instead of a second `?` (A-08). + */ export function joinUrl(baseUrl: string, path: string): string { - const base = baseUrl.replace(/\/+$/, ''); const suffix = path.startsWith('/') ? path : `/${path}`; + const queryIndex = baseUrl.indexOf('?'); + const basePath = queryIndex === -1 ? baseUrl : baseUrl.slice(0, queryIndex); + const baseQuery = queryIndex === -1 ? '' : baseUrl.slice(queryIndex + 1); + const base = basePath.replace(/\/+$/, ''); // A base that already ends in /v1 should not get a duplicated prefix. - return `${base}${suffix}`; + const joined = `${base}${suffix}`; + if (baseQuery.length === 0) return joined; + return joined.includes('?') ? `${joined}&${baseQuery}` : `${joined}?${baseQuery}`; +} + +/** + * A-10: a provider key with CR/LF/NUL would be smuggled into a header value; strip + * those characters before the credential is used. + */ +export function sanitizeCredential(value: string): string { + return value.replace(/[\r\n\0]/g, ''); +} + +/** + * Header values Node accepts: horizontal tab plus ASCII 0x20-0x7E and Latin-1 + * 0x80-0xFF. Anything else makes `fetch` throw with the raw value in the message. + */ +export function isValidHeaderValue(value: string): boolean { + return !/[^\t\x20-\x7E\x80-\xFF]/.test(value); } export interface UpstreamRequest { @@ -85,6 +110,16 @@ export function redactMessage(message: string, url: string): string { */ export async function upstreamFetch(req: UpstreamRequest): Promise { const url = joinUrl(req.baseUrl, req.path); + // A-10: a malformed key must fail with a fixed, value-free error instead of an + // undici `Headers.append` TypeError whose message quotes the raw credential. + const apiKey = sanitizeCredential(req.apiKey); + const authorization = `Bearer ${apiKey}`; + if (!isValidHeaderValue(authorization) || !isValidHeaderValue(apiKey)) { + throw new ApiError('api_error', 'Provider credentials are invalid', { + status: 502, + code: 'invalid_provider_credentials', + }); + } const controller = new AbortController(); let abortReason: string | null = null; const abortWith = (reason: string): void => { @@ -113,8 +148,8 @@ export async function upstreamFetch(req: UpstreamRequest): Promise ({ + status: 200, + payload: { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] } as unknown, + textThrows: false, + calls: [] as Array<{ baseUrl: string; apiKey: string; path: string }>, + disposed: 0, + byBaseUrl: null as null | ((baseUrl: string) => { status: number; payload: unknown }), +})); + +vi.mock('../src/util/upstream.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + upstreamFetch: async (request: { baseUrl: string; apiKey: string; path: string }) => { + upstream.calls.push({ baseUrl: request.baseUrl, apiKey: request.apiKey, path: request.path }); + const override = upstream.byBaseUrl?.(request.baseUrl); + const status = override ? override.status : upstream.status; + const payload = override ? override.payload : upstream.payload; + const body = typeof payload === 'string' ? payload : JSON.stringify(payload); + return { + status, + ok: status >= 200 && status < 300, + headers: new Headers({ 'content-type': 'application/json' }), + response: { + text: async () => { + if (upstream.textThrows) throw new Error('socket closed while reading'); + return body; + }, + json: async () => JSON.parse(body), + }, + dispose: () => { + upstream.disposed += 1; + }, + abort: () => {}, + abortReason: null, + }; + }, + }; +}); + +import { + LOGIN_GLOBAL_MAX_ATTEMPTS, + LOGIN_MAX_ATTEMPTS, + checkLoginRateLimit, + recordLoginFailure, + resetLoginAttempts, +} from '../src/admin/auth.js'; +import { registerAdminRoutes } from '../src/admin/index.js'; +import { SESSION_COOKIE, buildSessionCookie } from '../src/admin/session.js'; +import { clearStatsCache } from '../src/admin/stats.js'; +import { probeProvider, probeAndRecord } from '../src/admin/sync.js'; +import { + HttpError, + MAX_API_KEY_LENGTH, + assertApiKey, + assertPublicProviderUrl, + asTimestamp, +} from '../src/admin/util.js'; +import type { AppConfig } from '../src/config.js'; +import { decActiveRequests, incActiveRequests, type AppContext } from '../src/core/context.js'; +import { EventBus } from '../src/core/events.js'; +import { openDatabase, type DbHandle } from '../src/db/index.js'; +import { Repo } from '../src/db/repos.js'; +import { SCHEMA_VERSION } from '../src/db/schema.js'; +import type { ProviderRow, RequestLogRow } from '../src/types.js'; +import { provider, testConfig } from './helpers.js'; + +interface TestApp { + app: FastifyInstance; + ctx: AppContext; + repo: Repo; + handle: DbHandle; + dataDir: string; + cookie(): string; + login(password?: string): Promise; + request( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise; + json( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise; + close(): Promise; +} + +async function buildAdminApp(configOverrides: Partial = {}): Promise { + const dataDir = mkdtempSync(join(tmpdir(), 'okr-hardening-')); + const config: AppConfig = { ...testConfig(dataDir), bodyLimit: 64 * 1024, ...configOverrides }; + const handle = openDatabase(config); + const repo = new Repo(handle.db); + const ctx: AppContext = { + config, + db: handle, + repo, + events: new EventBus(), + logger: null as never, + startedAt: Date.now(), + }; + const app = Fastify({ logger: false, bodyLimit: config.bodyLimit, trustProxy: config.trustProxy }); + ctx.logger = app.log; + await app.register(fastifyCookie); + await registerAdminRoutes(app, ctx); + + const request = async ( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise => + app.inject({ + method: method as 'GET', + url, + ...(payload === undefined ? {} : { payload: payload as object }), + ...(cookie === undefined && headers === undefined + ? {} + : { headers: { ...(cookie === undefined ? {} : { cookie }), ...(headers ?? {}) } }), + }); + + return { + app, + ctx, + repo, + handle, + dataDir, + cookie(): string { + const session = repo.createSession({ + id: randomUUID(), + ttlMs: config.sessionTtlMs, + clientIp: '127.0.0.1', + userAgent: 'vitest', + }); + return `${SESSION_COOKIE}=${buildSessionCookie(ctx.db.secret, session.id, session.expiresAt)}`; + }, + async login(password = '123456'): Promise { + const response = await request('POST', '/admin/api/login', { password }); + const cookie = response.cookies.find((item) => item.name === SESSION_COOKIE); + if (!cookie) throw new Error(`login failed: ${response.statusCode} ${response.body}`); + return `${SESSION_COOKIE}=${cookie.value}`; + }, + request, + async json( + method: string, + url: string, + payload?: unknown, + cookie?: string, + headers?: Record, + ): Promise { + const response = await request(method, url, payload, cookie, headers); + return JSON.parse(response.body) as T; + }, + async close(): Promise { + await app.close(); + handle.db.close(); + rmSync(dataDir, { recursive: true, force: true }); + }, + }; +} + +let app: TestApp; + +beforeEach(async () => { + resetLoginAttempts(); + clearStatsCache(); + upstream.status = 200; + upstream.payload = { object: 'list', data: [{ id: 'm1' }, { id: 'm2' }] }; + upstream.textThrows = false; + upstream.calls = []; + upstream.disposed = 0; + upstream.byBaseUrl = null; + app = await buildAdminApp(); +}); + +afterEach(async () => { + await app.close(); +}); + +function seedProvider(id = 'p1', baseUrl = 'https://api.example.com/v1'): ProviderRow { + return app.repo.createProvider({ id, name: id.toUpperCase(), baseUrl, apiKey: 'stored-secret-key' }); +} + +/* ------------------------------------------------------------------- B-05 */ + +describe('B-05 sync prune guard', () => { + it('keeps the synced catalog when the upstream body is unrecognized', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual-1' }); + app.repo.setSetting('models_synced_at', '1111'); + app.repo.setSetting('models_sync_provider_id', 'p1'); + + for (const payload of [{}, 'not json', { data: null }]) { + upstream.payload = payload; + const body = await app.json<{ added: number; removed: number; warning?: string }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body.added).toBe(0); + expect(body.removed).toBe(0); + expect(body.warning).toContain('no recognizable model list'); + } + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['manual-1', 'sync-1']); + expect(app.repo.getSetting('models_synced_at')).toBe('1111'); + }); + + it('prunes the catalog for an explicit empty model array', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.upsertModel({ id: 'manual-1' }); + + upstream.payload = { data: [] }; + const body = await app.json<{ removed: number; warning?: string }>( + 'POST', + '/admin/api/models/sync', + { providerId: 'p1' }, + app.cookie(), + ); + expect(body.warning).toBeUndefined(); + expect(body.removed).toBe(1); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['manual-1']); + expect(app.repo.getSetting('models_synced_at')).not.toBeNull(); + }); +}); + +/* ------------------------------------------------------------------- B-06 */ + +describe('B-06 multi-provider sync', () => { + it('syncs every enabled provider and reports per-provider results', async () => { + seedProvider('p1', 'https://p1.example.com/v1'); + seedProvider('p2', 'https://p2.example.com/v1'); + upstream.byBaseUrl = (baseUrl) => + baseUrl.includes('p1') + ? { status: 200, payload: { data: [{ id: 'm-p1' }] } } + : { status: 200, payload: { data: [{ id: 'm-p2' }] } }; + + const body = await app.json<{ + providers: Array<{ providerId: string; ok: boolean; added: number }>; + added: number; + }>('POST', '/admin/api/models/sync', undefined, app.cookie()); + + expect(body.providers).toHaveLength(2); + expect(body.providers.map((entry) => entry.providerId).sort()).toEqual(['p1', 'p2']); + expect(body.providers.every((entry) => entry.ok)).toBe(true); + expect(body.added).toBe(2); + expect(app.repo.listModels().map((model) => model.id).sort()).toEqual(['m-p1', 'm-p2']); + // A multi-provider sync cannot attribute the catalog to one provider. + const models = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(models.syncProviderId).toBeNull(); + }); + + it('keeps the other providers when one sync fails', async () => { + seedProvider('p1', 'https://p1.example.com/v1'); + seedProvider('p2', 'https://p2.example.com/v1'); + upstream.byBaseUrl = (baseUrl) => + baseUrl.includes('p1') + ? { status: 200, payload: { data: [{ id: 'm-p1' }] } } + : { status: 500, payload: 'boom: internals' }; + + const body = await app.json<{ + providers: Array<{ providerId: string; ok: boolean; error: string | null }>; + }>('POST', '/admin/api/models/sync', undefined, app.cookie()); + const p1 = body.providers.find((entry) => entry.providerId === 'p1'); + const p2 = body.providers.find((entry) => entry.providerId === 'p2'); + expect(p1?.ok).toBe(true); + expect(p2?.ok).toBe(false); + expect(p2?.error).not.toContain('boom'); + expect(app.repo.listModels().map((model) => model.id)).toEqual(['m-p1']); + }); +}); + +/* ------------------------------------------------------------------- B-08 */ + +describe('B-08 probe dispose', () => { + it('disposes the upstream response when the body read throws', async () => { + upstream.status = 200; + upstream.textThrows = true; + const probe = await probeProvider({ baseUrl: 'https://api.example.com/v1', apiKey: 'k' }); + expect(probe.ok).toBe(false); + expect(upstream.disposed).toBe(1); + }); +}); + +/* ------------------------------------------------------------------- B-09 */ + +describe('B-09 timestamp finiteness', () => { + it('rejects overflowing digit strings and numeric values', () => { + expect(asTimestamp('1'.repeat(400))).toBeNull(); + expect(asTimestamp('99999999999999999999')).toBeNull(); + expect(asTimestamp(Number.MAX_VALUE)).toBeNull(); + expect(asTimestamp(-5)).toBeNull(); + }); + + it('still parses a valid epoch ms and ISO date', () => { + expect(asTimestamp(1_700_000_000_000)).toBe(1_700_000_000_000); + expect(asTimestamp('1700000000000')).toBe(1_700_000_000_000); + expect(asTimestamp('2026-01-02T03:04:05Z')).toBe(Date.parse('2026-01-02T03:04:05Z')); + }); + + it('returns 400 from /logs for an out-of-range ?since=', async () => { + const cookie = app.cookie(); + for (const value of ['99999999999999999999', '1'.repeat(400)]) { + const response = await app.request('GET', `/admin/api/logs?since=${value}`, undefined, cookie); + expect(response.statusCode, value).toBe(400); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('invalid_request'); + } + const ok = await app.request('GET', '/admin/api/logs?since=1700000000000', undefined, cookie); + expect(ok.statusCode).toBe(200); + }); +}); + +/* ------------------------------------------------------------------- B-10 */ + +describe('B-10 dangling sync provider id', () => { + it('clears models_sync_provider_id when its provider is deleted', async () => { + seedProvider(); + app.repo.upsertModel({ id: 'sync-1', providerId: 'p1', source: 'sync' }); + app.repo.setSetting('models_synced_at', '2222'); + app.repo.setSetting('models_sync_provider_id', 'p1'); + + const deleted = await app.request('DELETE', '/admin/api/providers/p1', undefined, app.cookie()); + expect(deleted.statusCode).toBe(200); + const models = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(models.syncProviderId).toBeNull(); + // Deleting an unrelated provider must not clear the current sync provider id. + seedProvider('p2'); + seedProvider('p3'); + app.repo.setSetting('models_sync_provider_id', 'p2'); + const unrelated = await app.request('DELETE', '/admin/api/providers/p3', undefined, app.cookie()); + expect(unrelated.statusCode).toBe(200); + const after = await app.json<{ syncProviderId: string | null }>('GET', '/admin/api/models', undefined, app.cookie()); + expect(after.syncProviderId).toBe('p2'); + }); +}); + +/* ------------------------------------------------------------------- B-11 */ + +describe('B-11 apiKey validation', () => { + it('rejects control, non-ASCII, empty and over-long keys without echoing them', async () => { + const cookie = app.cookie(); + const payloads: Array<{ apiKey: string; label: string }> = [ + { apiKey: 'SECRET-CONTROL\u0001', label: 'control' }, + { apiKey: 'SECRET-LATIN-\u00e9', label: 'latin-1' }, + { apiKey: 'SECRET\nNEWLINE', label: 'newline' }, + { apiKey: '', label: 'empty' }, + ]; + for (const { apiKey, label } of payloads) { + const response = await app.request( + 'POST', + '/admin/api/providers', + { name: 'p', baseUrl: 'https://api.example.com/v1', apiKey }, + cookie, + ); + expect(response.statusCode, label).toBe(400); + expect(response.body).not.toContain('SECRET'); + } + expect(app.repo.listProviders()).toHaveLength(0); + + // Over-long keys are rejected by the route (harness body limit is 64 KiB). + const longResponse = await app.request( + 'POST', + '/admin/api/providers', + { name: 'p', baseUrl: 'https://api.example.com/v1', apiKey: 'k'.repeat(MAX_API_KEY_LENGTH + 1) }, + cookie, + ); + expect(longResponse.statusCode).toBe(400); + expect(longResponse.body).not.toContain('kkkk'); + expect(() => assertApiKey('k'.repeat(MAX_API_KEY_LENGTH + 1))).toThrow(HttpError); + expect(MAX_API_KEY_LENGTH).toBe(4096); + }); + + it('accepts a normal key on create and patch', async () => { + const cookie = app.cookie(); + const created = await app.request( + 'POST', + '/admin/api/providers', + { id: 'p', name: 'p', baseUrl: 'https://api.example.com/v1', apiKey: 'sk-normal-key-123' }, + cookie, + ); + expect(created.statusCode).toBe(200); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-normal-key-123'); + + const patched = await app.request('PATCH', '/admin/api/providers/p', { apiKey: 'sk-rotated-key-456' }, cookie); + expect(patched.statusCode).toBe(200); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-rotated-key-456'); + + const rejected = await app.request('PATCH', '/admin/api/providers/p', { apiKey: 'bad\u00e9key' }, cookie); + expect(rejected.statusCode).toBe(400); + expect(app.repo.getProvider('p')?.apiKey).toBe('sk-rotated-key-456'); + }); +}); + +/* ------------------------------------------------------------------- B-12 */ + +describe('B-12 SSRF ranges', () => { + const blockedUrls = [ + 'http://100.64.0.1/v1', // CGNAT / Tailscale + 'http://100.127.255.254/v1', + 'http://192.0.0.5/v1', // IETF protocol assignments + 'http://198.18.0.1/v1', // benchmarking + 'http://198.19.255.255/v1', + 'http://[::]/v1', // unspecified + 'http://[64:ff9b::1]/v1', // NAT64 + 'http://[2002::1]/v1', // 6to4 + // Previously blocked ranges must stay blocked. + 'http://127.0.0.1/v1', + 'http://10.0.0.5/v1', + 'http://172.16.0.5/v1', + 'http://192.168.1.5/v1', + 'http://169.254.1.5/v1', + 'http://0.0.0.0/v1', + 'http://[::1]/v1', + 'http://[fc00::1]/v1', + 'http://[fe80::1]/v1', + ]; + + it('blocks the new CGNAT, IETF, benchmarking and IPv6 ranges', () => { + for (const url of blockedUrls) { + expect(() => assertPublicProviderUrl(url, false), url).toThrow(HttpError); + try { + assertPublicProviderUrl(url, false); + } catch (error) { + expect((error as HttpError).code).toBe('invalid_request'); + } + } + }); + + it('keeps public addresses allowed and the escape hatch working', () => { + for (const url of ['https://8.8.8.8/v1', 'https://1.1.1.1/v1', 'https://[2606:4700:4700::1111]/v1', 'https://api.example.com/v1']) { + expect(() => assertPublicProviderUrl(url, false), url).not.toThrow(); + } + expect(() => assertPublicProviderUrl('http://127.0.0.1/v1', true)).not.toThrow(); + }); +}); + +/* ------------------------------------------------------------------- B-13 */ + +describe('B-13 shared probe SSRF guard', () => { + it('refuses to probe a private stored provider and records no failure', async () => { + const recorded: string[] = []; + const ctx = { + config: { providerAllowPrivateHosts: false }, + repo: { + recordProviderFailure: (...args: unknown[]) => { + recorded.push(String(args[0])); + }, + recordProviderSuccess: () => {}, + }, + events: { emitProvider: () => {} }, + logger: { warn: () => {} }, + } as unknown as AppContext; + const row = provider('legacy', { baseUrl: 'http://127.0.0.1:9/v1' }); + + await expect(probeAndRecord(ctx, row, { cooldownMs: 0, log: () => {} })).rejects.toThrow(HttpError); + expect(upstream.calls).toHaveLength(0); + expect(recorded).toHaveLength(0); + }); +}); + +/* ------------------------------------------------------------------- B-14 */ + +describe('B-14 login global cap', () => { + it('keeps the raised global cap well above the per-IP cap', () => { + expect(LOGIN_MAX_ATTEMPTS).toBe(10); + expect(LOGIN_GLOBAL_MAX_ATTEMPTS).toBe(500); + }); + + it('lets the operator log in after 50 failures from distinct IPs', async () => { + for (let index = 0; index < 50; index += 1) recordLoginFailure(`198.51.100.${index}`); + // The per-IP counter for the dashboard IP is untouched and the global cap holds. + expect(checkLoginRateLimit('203.0.113.9')).toBeNull(); + const response = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(response.statusCode).toBe(200); + }); + + it('still blocks a single IP after 10 failures', async () => { + for (let index = 0; index < LOGIN_MAX_ATTEMPTS; index += 1) { + const failed = await app.request('POST', '/admin/api/login', { password: 'wrong' }); + expect(failed.statusCode).toBe(401); + } + expect(checkLoginRateLimit('127.0.0.1')?.scope).toBe('ip'); + const response = await app.request('POST', '/admin/api/login', { password: '123456' }); + expect(response.statusCode).toBe(429); + }); +}); + +/* ------------------------------------------------------------------- B-15 */ + +describe('B-15 CSRF guard', () => { + it('rejects a cross-origin Origin on a session-authenticated mutation', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '7' }, cookie, { + origin: 'https://evil.example.com', + }); + expect(response.statusCode).toBe(403); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('cross_site_request'); + // No state change. + expect(app.repo.getSetting('max_retries')).toBe('3'); + }); + + it('rejects Sec-Fetch-Site: cross-site', async () => { + const cookie = app.cookie(); + const response = await app.request('PATCH', '/admin/api/settings', { max_retries: '7' }, cookie, { + 'sec-fetch-site': 'cross-site', + }); + expect(response.statusCode).toBe(403); + expect(app.repo.getSetting('max_retries')).toBe('3'); + }); + + it('allows same-origin, absent Origin and same-origin Sec-Fetch-Site', async () => { + const cookie = app.cookie(); + const sameOrigin = await app.request('PATCH', '/admin/api/settings', { max_retries: '4' }, cookie, { + host: 'router.test', + origin: 'http://router.test', + }); + expect(sameOrigin.statusCode).toBe(200); + + const absent = await app.request('PATCH', '/admin/api/settings', { max_retries: '5' }, cookie); + expect(absent.statusCode).toBe(200); + + const sameSite = await app.request('PATCH', '/admin/api/settings', { max_retries: '6' }, cookie, { + 'sec-fetch-site': 'same-origin', + }); + expect(sameSite.statusCode).toBe(200); + expect(app.repo.getSetting('max_retries')).toBe('6'); + }); + + it('keeps POST /admin/api/login reachable cross-site', async () => { + const response = await app.request('POST', '/admin/api/login', { password: '123456' }, undefined, { + origin: 'https://some-login-page.example', + 'sec-fetch-site': 'cross-site', + }); + expect(response.statusCode).toBe(200); + }); + + it('trusts PUBLIC_URL over the Host header when configured', async () => { + const behindProxy = await buildAdminApp({ publicUrl: 'https://router.example.com' }); + try { + const cookie = behindProxy.cookie(); + const response = await behindProxy.request('PATCH', '/admin/api/settings', { max_retries: '8' }, cookie, { + host: '10.0.0.5:20125', + origin: 'https://router.example.com', + }); + expect(response.statusCode).toBe(200); + expect(behindProxy.repo.getSetting('max_retries')).toBe('8'); + } finally { + await behindProxy.close(); + } + }); +}); + +/* ------------------------------------------------------------------- B-16 */ + +describe('B-16 limit validation', () => { + it('rejects junk limits on /audit and /activity', async () => { + const cookie = app.cookie(); + for (const path of ['/admin/api/audit', '/admin/api/activity']) { + for (const limit of ['abc', '-1', '0', '1000']) { + const response = await app.request('GET', `${path}?limit=${limit}`, undefined, cookie); + expect(response.statusCode, `${path}?limit=${limit}`).toBe(400); + } + const ok = await app.request('GET', `${path}?limit=20`, undefined, cookie); + expect(ok.statusCode).toBe(200); + const absent = await app.request('GET', path, undefined, cookie); + expect(absent.statusCode).toBe(200); + } + }); +}); + +/* ------------------------------------------------------------------- B-17 */ + +describe('B-17 activeRequests consistency', () => { + it('reports cache-independent activeRequests in the body and health', async () => { + const cookie = app.cookie(); + // Prime the 2 s aggregate cache. + const first = await app.json<{ activeRequests: number; health: { activeRequests: number } }>( + 'GET', + '/admin/api/stats', + undefined, + cookie, + ); + const base = first.activeRequests; + expect(first.health.activeRequests).toBe(base); + + incActiveRequests(); + try { + // A cache hit must still report the live counter in both fields. + const cached = await app.json<{ activeRequests: number; health: { activeRequests: number } }>( + 'GET', + '/admin/api/stats?window=1h', + undefined, + cookie, + ); + expect(cached.activeRequests).toBe(base + 1); + expect(cached.health.activeRequests).toBe(base + 1); + } finally { + decActiveRequests(); + clearStatsCache(); + } + }); +}); + +/* ------------------------------------------------------------------- B-18 */ + +function logRow(overrides: Partial & { id: string }): RequestLogRow { + return { + ts: Date.now(), + keyId: 'k1', + keyName: 'e2e', + providerId: 'p1', + providerName: 'Primary', + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 10, + ttfbMs: 5, + inputTokens: 1, + outputTokens: 2, + totalTokens: 3, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: '127.0.0.1', + userAgent: 'test', + ...overrides, + }; +} + +describe('B-18 log search/model filters', () => { + it('matches `model` case-insensitively on a substring with a consistent total', async () => { + const now = Date.now(); + app.repo.insertLog(logRow({ id: 'm1', ts: now - 3_000, model: 'opencode/flint-40b-free' })); + app.repo.insertLog(logRow({ id: 'm2', ts: now - 2_000, model: 'OPENCODE/Flint-Large' })); + app.repo.insertLog(logRow({ id: 'm3', ts: now - 1_000, model: 'other/model' })); + + const cookie = app.cookie(); + const lower = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=flint', + undefined, + cookie, + ); + expect(lower.total).toBe(2); + expect(lower.logs.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + const paged = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=flint&limit=1', + undefined, + cookie, + ); + expect(paged.total).toBe(2); + expect(paged.logs).toHaveLength(1); + }); + + it('treats % and _ in the model filter as literals', async () => { + app.repo.insertLog(logRow({ id: 'pct', model: 'vendor/a%b' })); + app.repo.insertLog(logRow({ id: 'plain', model: 'vendor/axb' })); + const body = await app.json<{ logs: Array<{ id: string }>; total: number }>( + 'GET', + '/admin/api/logs?model=a%25b', + undefined, + app.cookie(), + ); + expect(body.total).toBe(1); + expect(body.logs[0]?.id).toBe('pct'); + }); + + it('rejects an over-long search term', async () => { + const cookie = app.cookie(); + const response = await app.request('GET', `/admin/api/logs?search=${'a'.repeat(201)}`, undefined, cookie); + expect(response.statusCode).toBe(400); + expect((JSON.parse(response.body) as { error: { message: string } }).error.message).toContain('at most 200'); + const ok = await app.request('GET', `/admin/api/logs?search=${'a'.repeat(200)}`, undefined, cookie); + expect(ok.statusCode).toBe(200); + }); +}); + +/* ------------------------------------------------- upstream_response_max_bytes */ + +describe('upstream_response_max_bytes validation', () => { + it('accepts exactly 0 (unlimited) or 1024..1073741824', async () => { + const cookie = app.cookie(); + for (const value of ['1024', '1073741824', '0']) { + const response = await app.request('PATCH', '/admin/api/settings', { upstream_response_max_bytes: value }, cookie); + expect(response.statusCode, value).toBe(200); + expect(app.repo.getSetting('upstream_response_max_bytes')).toBe(value); + } + for (const value of ['1', '1023', '1073741825', '-1', 'abc']) { + const response = await app.request('PATCH', '/admin/api/settings', { upstream_response_max_bytes: value }, cookie); + expect(response.statusCode, value).toBe(400); + const body = JSON.parse(response.body) as { error: { code: string } }; + expect(body.error.code, value).toBe('invalid_request'); + } + // The last successful write is untouched by the rejected patches. + expect(app.repo.getSetting('upstream_response_max_bytes')).toBe('0'); + }); +}); + +/* ------------------------------------------------------------------- B-20 */ + +describe('B-20 GET /admin/api/diagnostics', () => { + it('requires a dashboard session', async () => { + const response = await app.request('GET', '/admin/api/diagnostics'); + expect(response.statusCode).toBe(401); + expect((JSON.parse(response.body) as { error: { code: string } }).error.code).toBe('unauthorized'); + }); + + it('returns the documented shape with the expected warnings on a fresh database', async () => { + const body = await app.json<{ + scheduler: Record; + storage: Record; + checks: Array<{ id: string; status: string; detail: string }>; + }>('GET', '/admin/api/diagnostics', undefined, app.cookie()); + + expect(Object.keys(body).sort()).toEqual(['checks', 'scheduler', 'storage']); + expect(body.scheduler).toEqual({ + running: false, + lastSyncAt: null, + lastSyncError: null, + nextSyncInMs: null, + lastRecoveryAt: null, + }); + expect(body.storage).toMatchObject({ + dbPath: expect.any(String), + walSizeBytes: expect.any(Number), + dbSizeBytes: expect.any(Number), + busyTimeoutMs: expect.any(Number), + logRows: 0, + attemptRows: 0, + sessionRows: expect.any(Number), + oldestLogTs: null, + }); + expect(body.storage.dbSizeBytes as number).toBeGreaterThan(0); + + expect(body.checks.map((check) => check.id)).toEqual([ + 'password.default', + 'providers.enabled', + 'keys.active', + 'models.enabled', + 'version.schema', + 'clock.skew', + 'providers.cooldown', + ]); + const statuses = Object.fromEntries(body.checks.map((check) => [check.id, check.status])); + expect(statuses).toEqual({ + 'password.default': 'warn', + 'providers.enabled': 'warn', + 'keys.active': 'warn', + 'models.enabled': 'warn', + 'version.schema': 'ok', + 'clock.skew': 'ok', + 'providers.cooldown': 'ok', + }); + expect(body.checks.every((check) => check.detail.length > 0)).toBe(true); + + // No secret material is part of the report. + const serialized = JSON.stringify(body); + expect(serialized).not.toContain('dashboard_password_hash'); + expect(serialized).not.toContain(app.ctx.db.secret); + }); + + it('warns when the data file is missing a required table', async () => { + app.ctx.db.db.exec('DROP TABLE models'); + const body = await app.json<{ checks: Array<{ id: string; status: string; detail: string }> }>( + 'GET', + '/admin/api/diagnostics', + undefined, + app.cookie(), + ); + const schemaCheck = body.checks.find((check) => check.id === 'version.schema'); + expect(schemaCheck?.status).toBe('warn'); + expect(schemaCheck?.detail).toContain('models'); + }); + + it('warns when the data file declares a different schema generation', async () => { + app.ctx.db.db.exec('PRAGMA user_version = 99'); + try { + const body = await app.json<{ checks: Array<{ id: string; status: string; detail: string }> }>( + 'GET', + '/admin/api/diagnostics', + undefined, + app.cookie(), + ); + const schemaCheck = body.checks.find((check) => check.id === 'version.schema'); + expect(schemaCheck?.status).toBe('warn'); + expect(schemaCheck?.detail).toContain('99'); + } finally { + app.ctx.db.db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`); + } + }); +}); \ No newline at end of file diff --git a/tests/admin-scheduler.test.ts b/tests/admin-scheduler.test.ts new file mode 100644 index 0000000..73b2d55 --- /dev/null +++ b/tests/admin-scheduler.test.ts @@ -0,0 +1,311 @@ +/** + * AD-19: `src/admin/scheduler.ts` used to have zero coverage. These tests drive + * `startScheduler` with fake timers and assert the interval floor, the no-overlap + * guard, the never-throw wrapper, the session purge cadence, the cooldown sweep + * cursor, `stop()` and the `unref()` of every timer. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const sync = vi.hoisted(() => ({ + syncCalls: 0, + probeCalls: [] as string[], + /** Replaces the sync implementation; throw to exercise the failure path. */ + syncImpl: null as null | (() => Promise), + /** Replaces the probe implementation. */ + probeImpl: null as null | ((providerId: string) => Promise), +})); + +vi.mock('../src/admin/sync.js', () => ({ + syncAllEnabledProviders: async () => { + sync.syncCalls += 1; + if (sync.syncImpl) return await sync.syncImpl(); + return { added: 0, updated: 0, removed: 0, total: 0, providerId: '', syncedAt: Date.now(), latencyMs: 1, providers: [] }; + }, + probeAndRecord: async (_ctx: unknown, provider: { id: string }) => { + sync.probeCalls.push(provider.id); + if (sync.probeImpl) return await sync.probeImpl(provider.id); + return { ok: true, status: 200, latencyMs: 1, models: [], catalogLocated: true, error: '', detail: null }; + }, +})); + +import { getSchedulerStatus, resetSchedulerStatus, startScheduler } from '../src/admin/scheduler.js'; +import type { AppContext } from '../src/core/context.js'; +import type { ProviderRow } from '../src/types.js'; +import { provider } from './helpers.js'; + +interface FakeRepo { + providers: ProviderRow[]; + settings: Record; + purged: number; + updates: Array<{ id: string; patch: Record }>; + getBool(key: string): boolean; + getInt(key: string, fallback: number): number; + listProviders(): ProviderRow[]; + purgeExpiredSessions(): void; + updateProvider(id: string, patch: Record): void; +} + +interface FakeHarness { + ctx: AppContext; + repo: FakeRepo; + emitted: string[]; + warnings: string[]; +} + +function makeHarness(options: { providers?: ProviderRow[]; settings?: Record } = {}): FakeHarness { + const settings: Record = { + auto_sync_models: 'true', + model_sync_interval_ms: '300000', + ...options.settings, + }; + const emitted: string[] = []; + const warnings: string[] = []; + const repo: FakeRepo = { + providers: options.providers ?? [provider('p1')], + settings, + purged: 0, + updates: [], + getBool(key) { + return settings[key] === 'true'; + }, + getInt(key, fallback) { + const parsed = Number.parseInt(settings[key] ?? '', 10); + return Number.isFinite(parsed) ? parsed : fallback; + }, + listProviders() { + return repo.providers; + }, + purgeExpiredSessions() { + repo.purged += 1; + }, + updateProvider(id, patch) { + repo.updates.push({ id, patch }); + const row = repo.providers.find((candidate) => candidate.id === id); + if (row) Object.assign(row, patch); + }, + }; + const events = { + emitProvider: (event: { providerId: string }) => { + emitted.push(event.providerId); + }, + }; + const logger = { + info: () => {}, + warn: (extra: unknown, message?: string) => { + warnings.push(message ?? String(extra)); + }, + }; + const ctx = { + config: { providerAllowPrivateHosts: false }, + repo, + events, + logger, + } as unknown as AppContext; + return { ctx, repo, emitted, warnings }; +} + +const liveStops: Array<() => void> = []; + +function start(harness: FakeHarness): () => void { + const stop = startScheduler(harness.ctx); + liveStops.push(stop); + return stop; +} + +beforeEach(() => { + sync.syncCalls = 0; + sync.probeCalls = []; + sync.syncImpl = null; + sync.probeImpl = null; + resetSchedulerStatus(); +}); + +afterEach(() => { + while (liveStops.length > 0) liveStops.pop()!(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +describe('startScheduler', () => { + it('applies the 30 s minimum sync interval', async () => { + vi.useFakeTimers(); + const harness = makeHarness({ settings: { model_sync_interval_ms: '1000' } }); + start(harness); + + // Initial timer fires 5 s after boot. + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + + // t=30 s: only 25 s since the last sync, so the configured 1 s must not win. + await vi.advanceTimersByTimeAsync(25_000); + expect(sync.syncCalls).toBe(1); + + // t=60 s: 55 s since the last sync, the 30 s floor is satisfied. + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.syncCalls).toBe(2); + }); + + it('never overlaps two syncs when one tick is slow', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + let release = (): void => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + sync.syncImpl = async () => { + await gate; + return { providers: [] }; + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + + // Two more ticks pass while the first sync is still in flight. + await vi.advanceTimersByTimeAsync(60_000); + expect(sync.syncCalls).toBe(1); + + release(); + await vi.advanceTimersByTimeAsync(0); + }); + + it('never throws out of a tick and records the last sync error', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + sync.syncImpl = async () => { + throw new Error('upstream exploded'); + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.syncCalls).toBe(1); + expect(harness.warnings).toContain('scheduled model sync failed'); + expect(getSchedulerStatus(harness.ctx).lastSyncError).toBe('upstream exploded'); + + // The next interval still runs: one failure must not stop the scheduler. + await vi.advanceTimersByTimeAsync(330_000); + expect(sync.syncCalls).toBe(2); + }); + + it('purges expired sessions every 10 minutes', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + start(harness); + + await vi.advanceTimersByTimeAsync(10 * 60 * 1000); + expect(harness.repo.purged).toBe(1); + await vi.advanceTimersByTimeAsync(10 * 60 * 1000); + expect(harness.repo.purged).toBe(2); + }); + + it('recovers cooldowns and rotates the probe cursor over every provider', async () => { + vi.useFakeTimers(); + const cooling = ['p1', 'p2', 'p3', 'p4', 'p5'].map((id) => + provider(id, { status: 'cooldown', cooldownUntil: Date.now() - 1 }), + ); + const harness = makeHarness({ providers: cooling }); + start(harness); + + // Tick 1 probes the first three cooling providers. + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.probeCalls).toEqual(['p1', 'p2', 'p3']); + + // Tick 2 probes the remaining two; three consecutive ticks are disjoint and + // cover all five (tick 3 has nothing left to recover). + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.probeCalls).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + await vi.advanceTimersByTimeAsync(30_000); + expect(sync.probeCalls).toHaveLength(5); + + expect(harness.emitted).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + expect(harness.repo.updates.map((update) => update.id)).toEqual(['p1', 'p2', 'p3', 'p4', 'p5']); + for (const update of harness.repo.updates) { + expect(update.patch).toEqual({ cooldownUntil: null, status: 'ok' }); + } + expect(getSchedulerStatus(harness.ctx).lastRecoveryAt).not.toBeNull(); + }); + + it('survives a throwing probe without aborting the sweep', async () => { + vi.useFakeTimers(); + const cooling = ['p1', 'p2'].map((id) => provider(id, { status: 'cooldown', cooldownUntil: Date.now() - 1 })); + const harness = makeHarness({ providers: cooling }); + sync.probeImpl = async (providerId) => { + if (providerId === 'p1') throw new Error('ssrf guard'); + return { ok: true, status: 200, latencyMs: 1, models: [], catalogLocated: true, error: '', detail: null }; + }; + start(harness); + + await vi.advanceTimersByTimeAsync(5_000); + expect(sync.probeCalls).toEqual(['p1', 'p2']); + expect(harness.repo.updates.map((update) => update.id)).toEqual(['p2']); + }); + + it('stop() clears every timer and stops all work', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + const stop = start(harness); + expect(vi.getTimerCount()).toBe(3); + + stop(); + expect(vi.getTimerCount()).toBe(0); + expect(getSchedulerStatus(harness.ctx).running).toBe(false); + + await vi.advanceTimersByTimeAsync(60 * 60 * 1000); + expect(sync.syncCalls).toBe(0); + expect(harness.repo.purged).toBe(0); + + // Idempotent. + expect(() => stop()).not.toThrow(); + }); + + it('unrefs every timer', () => { + vi.useRealTimers(); + const unrefed: boolean[] = []; + const wrap = unknown }>(timer: T): T => { + const index = unrefed.push(false) - 1; + const original = timer.unref?.bind(timer); + timer.unref = () => { + unrefed[index] = true; + original?.(); + return timer; + }; + return timer; + }; + const realSetInterval = globalThis.setInterval; + const realSetTimeout = globalThis.setTimeout; + vi.spyOn(globalThis, 'setInterval').mockImplementation(((handler: () => void, timeout?: number) => + wrap(realSetInterval(handler, timeout))) as typeof globalThis.setInterval); + vi.spyOn(globalThis, 'setTimeout').mockImplementation(((handler: () => void, timeout?: number) => + wrap(realSetTimeout(handler, timeout))) as typeof globalThis.setTimeout); + + const harness = makeHarness(); + const stop = start(harness); + + expect(unrefed).toHaveLength(3); + expect(unrefed).toEqual([true, true, true]); + stop(); + }); + + it('reports its runtime status', async () => { + vi.useFakeTimers(); + const harness = makeHarness(); + const before = getSchedulerStatus(harness.ctx); + expect(before).toEqual({ + running: false, + lastSyncAt: null, + lastSyncError: null, + nextSyncInMs: null, + lastRecoveryAt: null, + }); + + start(harness); + const running = getSchedulerStatus(harness.ctx); + expect(running.running).toBe(true); + expect(running.nextSyncInMs).toBeGreaterThanOrEqual(0); + + await vi.advanceTimersByTimeAsync(5_000); + const afterSync = getSchedulerStatus(harness.ctx); + expect(afterSync.lastSyncAt).not.toBeNull(); + expect(afterSync.nextSyncInMs).toBeGreaterThan(0); + }); +}); \ No newline at end of file diff --git a/tests/db-hardening.test.ts b/tests/db-hardening.test.ts new file mode 100644 index 0000000..0ab0349 --- /dev/null +++ b/tests/db-hardening.test.ts @@ -0,0 +1,481 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Worker } from 'node:worker_threads'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { AttemptRow, RequestLogRow } from '../src/types.js'; +import { openDatabase, type DbHandle } from '../src/db/index.js'; +import { Repo } from '../src/db/repos.js'; +import { SCHEMA_SQL, SCHEMA_VERSION } from '../src/db/schema.js'; +import { createTestDb, testConfig, type TestDb } from './helpers.js'; + +let db: TestDb; + +beforeEach(() => { + db = createTestDb('okr-hardening-'); +}); + +afterEach(() => { + db.cleanup(); +}); + +function makeLog(overrides: Partial & { id: string }): RequestLogRow { + return { + ts: Date.now(), + keyId: 'k1', + keyName: 'e2e', + providerId: 'p1', + providerName: 'Primary', + model: 'a/model', + surface: 'chat', + stream: false, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 10, + ttfbMs: 5, + inputTokens: 1, + outputTokens: 2, + totalTokens: 3, + reasoningTokens: 0, + cachedTokens: 0, + attempts: 1, + clientIp: '127.0.0.1', + userAgent: 'test', + ...overrides, + }; +} + +function makeAttempt(overrides: Partial & { id: string; requestId: string }): AttemptRow { + return { + ts: Date.now(), + providerId: 'p1', + providerName: 'Primary', + attempt: 1, + status: 200, + ok: true, + errorCode: null, + errorMessage: null, + latencyMs: 5, + ...overrides, + }; +} + +/* ------------------------------------------------------------------------ B-01 */ + +describe('B-01: monotonic provider cooldown', () => { + it('keeps a longer active cooldown when a shorter failure arrives', () => { + db.repo.createProvider({ id: 'p', name: 'p', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('p', 429, 'slow down', 60_000); + const long = db.repo.getProvider('p')!.cooldownUntil!; + expect(long).toBeGreaterThan(Date.now()); + + // 5 s must not shorten the 60 s deadline already in force. + db.repo.recordProviderFailure('p', 503, 'again', 5_000); + expect(db.repo.getProvider('p')!.cooldownUntil).toBe(long); + + // The scheduler's `cooldownMs: 0` probe must not clear an active cooldown either. + db.repo.recordProviderFailure('p', 429, 'probe', 0); + const after = db.repo.getProvider('p')!; + expect(after.cooldownUntil).toBe(long); + expect(after.failureCount).toBe(3); + expect(after.status).toBe('cooldown'); + expect(after.lastError).toBe('probe'); + }); + + it('pins cooldownMs <= 0 to now only when no cooldown is active', () => { + db.repo.createProvider({ id: 'q', name: 'q', baseUrl: 'http://x/v1', apiKey: 'k' }); + const before = Date.now(); + db.repo.recordProviderFailure('q', 429, 'rate limited', 0); + const until = db.repo.getProvider('q')!.cooldownUntil; + expect(until).not.toBeNull(); + expect(until!).toBeGreaterThanOrEqual(before); + expect(until!).toBeLessThanOrEqual(Date.now()); + }); + + it('still clears the deadline when the failure is not cooldown-worthy', () => { + db.repo.createProvider({ id: 'r', name: 'r', baseUrl: 'http://x/v1', apiKey: 'k' }); + db.repo.recordProviderFailure('r', 429, 'slow down', 60_000); + expect(db.repo.getProvider('r')!.cooldownUntil).not.toBeNull(); + + db.repo.recordProviderFailure('r', 400, 'bad request', 60_000); + const row = db.repo.getProvider('r')!; + expect(row.cooldownUntil).toBeNull(); + expect(row.status).toBe('error'); + }); +}); + +/* ------------------------------------------------------------------------ B-02 */ + +/** Nearest-rank definition the old `latencyPercentile` implemented. */ +function referencePercentile(values: number[], p: number): number { + if (values.length === 0) return 0; + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * values.length))] ?? 0; +} + +/** + * Wraps `prepare` so the test can count how often the ordered latency statement is + * prepared and executed. The repo caches statements, so a second query per + * `statsOverview` call only shows up on the execution counter. + */ +function instrumentLatencyQueries(target: TestDb): { + repo: Repo; + latencyPrepares: () => number; + latencyExecutions: () => number; +} { + let prepares = 0; + let executions = 0; + const ordered = (sql: string): boolean => /ORDER BY latency_ms/i.test(sql); + const original = target.handle.db.prepare.bind(target.handle.db); + (target.handle.db as unknown as { prepare: (sql: string) => unknown }).prepare = (sql: string) => { + if (ordered(sql)) prepares += 1; + const statement = original(sql) as { + get: (...args: unknown[]) => unknown; + all: (...args: unknown[]) => unknown; + run: (...args: unknown[]) => unknown; + }; + return new Proxy(statement, { + get(inner, property) { + const value = Reflect.get(inner, property) as unknown; + if (typeof value !== 'function') return value; + return (...args: unknown[]) => { + if (ordered(sql)) executions += 1; + return (value as (...rest: unknown[]) => unknown).apply(inner, args); + }; + }, + }); + }; + return { repo: new Repo(target.handle.db), latencyPrepares: () => prepares, latencyExecutions: () => executions }; +} + +describe('B-02: single-pass latency percentiles', () => { + it('keeps the nearest-rank values for odd, even and null-bearing fixtures', () => { + expect(db.repo.statsOverview(3_600_000, 60_000, 0).totals.p50LatencyMs).toBe(0); + + const fixtures: Array> = [ + [10, 20, 30], + [10, 30], + [1, 7, 3, null, 99, 42, 5, 13, 8, 21], + [5], + Array.from({ length: 24 }, (_, index) => (index * 7) % 23), + ]; + for (const [fixture, latencies] of fixtures.entries()) { + const fixtureDb = createTestDb(`okr-b02-${fixture}-`); + try { + latencies.forEach((latency, index) => { + fixtureDb.repo.insertLog( + makeLog({ id: `f${fixture}-${index}`, latencyMs: latency, ts: Date.now() - 1_000 }), + ); + }); + const present = latencies.filter((value): value is number => value !== null); + const stats = fixtureDb.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs, `fixture ${fixture} p50`).toBe(referencePercentile(present, 50)); + expect(stats.totals.p95LatencyMs, `fixture ${fixture} p95`).toBe(referencePercentile(present, 95)); + expect(stats.totals.requests).toBe(latencies.length); + } finally { + fixtureDb.cleanup(); + } + } + }); + + it('prepares and executes exactly one ordered latency statement per statsOverview call', () => { + const spyDb = createTestDb('okr-b02-spy-'); + try { + const spy = instrumentLatencyQueries(spyDb); + for (const [index, latency] of [10, 20, 30].entries()) { + spyDb.repo.insertLog(makeLog({ id: `s${index}`, latencyMs: latency, ts: Date.now() - 1_000 })); + } + + const stats = spy.repo.statsOverview(3_600_000, 60_000, 0); + expect(stats.totals.p50LatencyMs).toBe(20); + expect(stats.totals.p95LatencyMs).toBe(30); + expect(spy.latencyPrepares()).toBe(1); + expect(spy.latencyExecutions()).toBe(1); + + // A second call reuses the cached statement: still one statement per call. + spy.repo.statsOverview(3_600_000, 60_000, 0); + expect(spy.latencyPrepares()).toBe(1); + expect(spy.latencyExecutions()).toBe(2); + } finally { + spyDb.cleanup(); + } + }); +}); + +/* ------------------------------------------------------------------------ B-03 */ + +function trackTransactions(target: TestDb): { calls: string[]; restore: () => void } { + const calls: string[] = []; + const original = target.handle.db.exec.bind(target.handle.db); + (target.handle.db as unknown as { exec: (sql: string) => unknown }).exec = (sql: string) => { + calls.push(sql); + return original(sql); + }; + return { + calls, + restore: () => { + (target.handle.db as unknown as { exec: (sql: string) => unknown }).exec = original; + }, + }; +} + +describe('B-03: transactional log pruning', () => { + it('deleteLogsBefore wraps both deletes in one transaction and returns the request_logs count', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'r1', ts: now })); + db.repo.insertLog(makeLog({ id: 'r2', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'a1', requestId: 'r1', ts: now })); + + const tracked = trackTransactions(db); + let removed: number; + try { + removed = db.repo.deleteLogsBefore(now + 1); + } finally { + tracked.restore(); + } + expect(removed!).toBe(2); + expect(tracked.calls.filter((sql) => /^BEGIN/i.test(sql))).toHaveLength(1); + expect(tracked.calls.filter((sql) => /^COMMIT/i.test(sql))).toHaveLength(1); + expect(db.repo.listAttempts('r1')).toHaveLength(0); + }); + + it('clearLogs empties both tables and reports the request_logs count', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'c1', ts: now })); + db.repo.insertLog(makeLog({ id: 'c2', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'ca', requestId: 'c1', ts: now })); + + const tracked = trackTransactions(db); + let removed: number; + try { + removed = db.repo.clearLogs(); + } finally { + tracked.restore(); + } + expect(removed!).toBe(2); + expect(tracked.calls.filter((sql) => /^BEGIN/i.test(sql))).toHaveLength(1); + expect(tracked.calls.filter((sql) => /^COMMIT/i.test(sql))).toHaveLength(1); + expect(db.repo.listLogs({ limit: 10 }).total).toBe(0); + expect(db.repo.listAttempts('c1')).toHaveLength(0); + }); + + it('an outer transaction that throws rolls back the prune of both tables', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'keep-1', ts: now })); + db.repo.insertAttempt(makeAttempt({ id: 'keep-a', requestId: 'keep-1', ts: now })); + + expect(() => + db.repo.transaction(() => { + db.repo.deleteLogsBefore(now + 1); + throw new Error('crash'); + }), + ).toThrow('crash'); + + expect(db.repo.listLogs({ limit: 10 }).total).toBe(1); + expect(db.repo.listAttempts('keep-1')).toHaveLength(1); + }); +}); + +/* ------------------------------------------------------------------------ B-04 */ + +const WRITE_WORKER = ` +const { DatabaseSync } = require('node:sqlite'); +const { parentPort, workerData } = require('node:worker_threads'); +const db = new DatabaseSync(workerData.dbPath); +try { + db.exec(workerData.schemaSql); + parentPort.postMessage({ phase: 'started' }); + const startedAt = Date.now(); + db.exec("INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('from-worker', 2, 'test', 'worker.insert', NULL, NULL)"); + parentPort.postMessage({ ok: true, waitedMs: Date.now() - startedAt }); +} catch (error) { + parentPort.postMessage({ ok: false, error: String((error && error.message) || error) }); +} finally { + db.close(); +} +`; + +interface WorkerOutcome { + ok?: boolean; + error?: string; + waitedMs?: number; + phase?: string; +} + +/** Runs the write in a real second connection so the busy handler can actually wait. */ +function startWriteWorker(dbPath: string, schemaSql: string): { started: Promise; result: Promise } { + const worker = new Worker(WRITE_WORKER, { eval: true, workerData: { dbPath, schemaSql } }); + let markStarted: () => void = () => {}; + const started = new Promise((resolve) => { + markStarted = resolve; + }); + const result = new Promise((resolve, reject) => { + worker.on('message', (message: WorkerOutcome) => { + if (message.phase === 'started') { + markStarted(); + return; + } + resolve(message); + void worker.terminate(); + }); + worker.on('error', reject); + }); + return { started, result }; +} + +function openOwnDb(prefix: string): { dbPath: string; handle: DbHandle; close: () => void } { + const dir = mkdtempSync(join(tmpdir(), prefix)); + const config = testConfig(dir); + const handle = openDatabase(config); + return { + dbPath: config.dbPath, + handle, + close: () => { + handle.db.close(); + rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +describe('B-04: PRAGMA busy_timeout in SCHEMA_SQL', () => { + it('ships the pragma and applies it to every connection opened by openDatabase', () => { + expect(SCHEMA_SQL).toContain('PRAGMA busy_timeout = 5000;'); + const own = openOwnDb('okr-b04-pragma-'); + try { + const row = own.handle.db.prepare('PRAGMA busy_timeout').get() as Record; + expect(Object.values(row)).toContain(5000); + } finally { + own.close(); + } + }); + + it('stamps the schema generation into PRAGMA user_version and re-stamps an older file', () => { + const dir = mkdtempSync(join(tmpdir(), 'okr-b04-version-')); + const config = testConfig(dir); + try { + const first = openDatabase(config); + const stamped = first.db.prepare('PRAGMA user_version').get() as Record; + expect(Object.values(stamped)).toContain(SCHEMA_VERSION); + // Simulate a file written by an older build: the next open must re-stamp it. + first.db.exec('PRAGMA user_version = 0'); + first.db.close(); + + const second = openDatabase(config); + try { + const restamped = second.db.prepare('PRAGMA user_version').get() as Record; + expect(Object.values(restamped)).toContain(SCHEMA_VERSION); + } finally { + second.db.close(); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + it('lets a second connection wait for the write lock instead of failing SQLITE_BUSY', async () => { + const own = openOwnDb('okr-b04-wait-'); + try { + own.handle.db.exec('BEGIN IMMEDIATE'); + own.handle.db.exec( + "INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('held', 1, 'test', 'hold', NULL, NULL)", + ); + + const worker = startWriteWorker(own.dbPath, SCHEMA_SQL); + await worker.started; + // Commit while the worker is blocked in ITS insert: with busy_timeout the + // worker retries internally and succeeds, without it the insert throws at once. + await new Promise((resolve) => setTimeout(resolve, 250)); + own.handle.db.exec('COMMIT'); + + const outcome = await worker.result; + expect(outcome.error).toBeUndefined(); + expect(outcome.ok).toBe(true); + expect(outcome.waitedMs ?? 0).toBeGreaterThan(50); + } finally { + try { + own.handle.db.exec('ROLLBACK'); + } catch { + /* already committed */ + } + own.close(); + } + }); + + it('control: the same second connection fails immediately with the pragma disabled', async () => { + const own = openOwnDb('okr-b04-control-'); + try { + own.handle.db.exec('BEGIN IMMEDIATE'); + own.handle.db.exec( + "INSERT INTO audit_logs (id, ts, actor, action, target, detail) VALUES ('held-control', 1, 'test', 'hold', NULL, NULL)", + ); + + const worker = startWriteWorker(own.dbPath, 'PRAGMA busy_timeout = 0;'); + await worker.started; + const outcome = await worker.result; + expect(outcome.ok).toBe(false); + expect(outcome.error ?? '').toMatch(/locked|busy/i); + } finally { + try { + own.handle.db.exec('ROLLBACK'); + } catch { + /* nothing held */ + } + own.close(); + } + }); +}); + +/* ------------------------------------------------------------------------ B-18 */ + +describe('B-18: log query filters', () => { + it('matches `model` case-insensitively on a substring and keeps total consistent', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'm1', ts: now - 3_000, model: 'opencode/flint-40b-free' })); + db.repo.insertLog(makeLog({ id: 'm2', ts: now - 2_000, model: 'OPENCODE/Flint-Large' })); + db.repo.insertLog(makeLog({ id: 'm3', ts: now - 1_000, model: 'other/model' })); + + const lower = db.repo.listLogs({ model: 'flint' }); + expect(lower.total).toBe(2); + expect(lower.rows.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + const upper = db.repo.listLogs({ model: 'FLINT' }); + expect(upper.total).toBe(2); + expect(upper.rows.map((row) => row.id).sort()).toEqual(['m1', 'm2']); + + // `total` counts the whole filtered set, not just the returned page. + const paged = db.repo.listLogs({ model: 'flint', limit: 1, offset: 1 }); + expect(paged.total).toBe(2); + expect(paged.rows).toHaveLength(1); + + expect(db.repo.listLogs({ model: 'nothing-like-this' }).total).toBe(0); + }); + + it('treats `%`, `_` and `\\` in the model filter literally', () => { + const now = Date.now(); + db.repo.insertLog(makeLog({ id: 'lit1', ts: now - 3_000, model: 'a%b' })); + db.repo.insertLog(makeLog({ id: 'lit2', ts: now - 2_000, model: 'axb' })); + db.repo.insertLog(makeLog({ id: 'lit3', ts: now - 1_000, model: 'a_b' })); + + const percent = db.repo.listLogs({ model: '%' }); + expect(percent.total).toBe(1); + expect(percent.rows[0]?.id).toBe('lit1'); + + expect(db.repo.listLogs({ model: 'a_b' }).total).toBe(1); + expect(db.repo.listLogs({ model: 'a_b' }).rows[0]?.id).toBe('lit3'); + expect(db.repo.listLogs({ model: '_' }).total).toBe(1); + expect(db.repo.listLogs({ model: 'a\\b' }).total).toBe(0); + }); + + it('bounds the search term to 200 characters instead of scanning an unbounded LIKE', () => { + const long = 'a'.repeat(200); + db.repo.insertLog(makeLog({ id: 'search-1', ts: Date.now() - 1_000, model: long })); + + // The full term (203 chars) is not a substring of the row; only the bounded + // 200-char prefix is, so a match proves the length clamp is in place. + expect(db.repo.listLogs({ search: `${long}zzz` }).total).toBe(1); + expect(db.repo.listLogs({ search: long }).total).toBe(1); + expect(db.repo.listLogs({ search: 'zzz' }).total).toBe(0); + }); +}); diff --git a/tests/gateway-hardening.test.ts b/tests/gateway-hardening.test.ts new file mode 100644 index 0000000..f5031e1 --- /dev/null +++ b/tests/gateway-hardening.test.ts @@ -0,0 +1,493 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import Fastify, { type FastifyInstance } from 'fastify'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getActiveRequests, type AppContext } from '../src/core/context.js'; +import { EventBus } from '../src/core/events.js'; +import { registerGatewayRoutes } from '../src/gateway/index.js'; +import { finishModelsRequest } from '../src/gateway/models-route.js'; +import { MAX_RETRY_AFTER_MS } from '../src/gateway/proxy.js'; +import { createTestDb, testConfig, type TestDb } from './helpers.js'; + +interface MockRequest { + url: string; + headers: IncomingMessage['headers']; + body: Buffer; +} + +interface MockUpstream { + baseUrl: string; + port: number; + requests: MockRequest[]; + close(): Promise; +} + +type MockHandler = (req: IncomingMessage, res: ServerResponse, body: Buffer) => void | Promise; + +const upstreams: MockUpstream[] = []; + +/** Loopback mock provider on an ephemeral port (never a fixed port). */ +async function startUpstream(handler: MockHandler): Promise { + const requests: MockRequest[] = []; + const server: Server = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (chunk: Buffer) => chunks.push(chunk)); + req.on('end', () => { + const body = Buffer.concat(chunks); + requests.push({ url: req.url ?? '', headers: req.headers, body }); + void handler(req, res, body); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + const upstream: MockUpstream = { + baseUrl: `http://127.0.0.1:${port}/v1`, + port, + requests, + close: () => + new Promise((resolve) => { + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; + upstreams.push(upstream); + return upstream; +} + +function jsonResponse(res: ServerResponse, status: number, payload: unknown, headers: Record = {}): void { + const body = Buffer.from(JSON.stringify(payload)); + res.writeHead(status, { 'content-type': 'application/json', 'content-length': String(body.length), ...headers }); + res.end(body); +} + +async function waitFor(fn: () => T | null | undefined | false, label: string, timeoutMs = 5_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const value = fn(); + if (value) return value as T; + if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + } +} + +let db: TestDb; +let app: FastifyInstance; +let ctx: AppContext; +let origin: string; +let port: number; +let apiKey: string; +/** A-03: counter samples taken by a root onSend hook while each request is in flight. */ +const activeSamples: number[] = []; + +function config() { + return testConfig(db.dataDir); +} + +async function buildApp(): Promise { + const cfg = config(); + app = Fastify({ logger: false, bodyLimit: cfg.bodyLimit }); + // Registered on the root before the encapsulated gateway scope so the hook is + // inherited by it and samples the counter while the request is still in flight. + app.addHook('preHandler', (_request, _reply, done) => { + activeSamples.push(getActiveRequests()); + done(); + }); + ctx = { + config: cfg, + db: db.handle, + repo: db.repo, + events: new EventBus(), + logger: app.log, + startedAt: Date.now(), + }; + await registerGatewayRoutes(app, ctx); + await app.listen({ port: 0, host: '127.0.0.1' }); + port = (app.server.address() as AddressInfo).port; + origin = `http://127.0.0.1:${port}`; +} + +function addProvider(id: string, baseUrl: string, priority: number, key = 'sk-provider'): void { + db.repo.createProvider({ id, name: id, baseUrl, apiKey: key, priority }); +} + +function gatewayFetch(path: string, init: RequestInit = {}): Promise { + const headers = new Headers(init.headers); + if (!headers.has('authorization')) headers.set('authorization', `Bearer ${apiKey}`); + if (init.body !== undefined && !headers.has('content-type')) headers.set('content-type', 'application/json'); + return fetch(`${origin}${path}`, { ...init, headers }); +} + +const chatBody = (patch: Record = {}): string => + JSON.stringify({ model: 'test/model', messages: [{ role: 'user', content: 'ping' }], ...patch }); + +const CHAT = '/v1/chat/completions'; + +beforeEach(async () => { + db = createTestDb('okr-hardening-'); + db.repo.upsertModel({ id: 'test/model', name: 'Test Model' }); + apiKey = db.repo.createApiKey('tests').plaintext; + db.repo.setSetting('rotation_strategy', 'priority'); + activeSamples.length = 0; + await buildApp(); +}); + +afterEach(async () => { + await app.close(); + // A-03: every request must release the shared counter, otherwise later tests lie. + await waitFor(() => getActiveRequests() === 0, 'active request counter released'); + db.cleanup(); + for (const upstream of upstreams.splice(0)) await upstream.close(); +}); + +describe('A-01 bounded Retry-After', () => { + it('A-01: clamps a numeric Retry-After above one hour before writing the cooldown', async () => { + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 429, { error: { message: 'slow down' } }, { 'retry-after': '31536000' }); + }); + addProvider('p1', upstream.baseUrl, 1); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + + const provider = db.repo.getProvider('p1'); + expect(provider?.cooldownUntil).not.toBeNull(); + const remaining = provider!.cooldownUntil! - Date.now(); + expect(remaining).toBeLessThanOrEqual(MAX_RETRY_AFTER_MS + 2_000); + expect(remaining).toBeGreaterThan(MAX_RETRY_AFTER_MS - 5_000); + }); + + it('A-01: clamps an HTTP-date Retry-After above one hour before writing the cooldown', async () => { + const farFuture = new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000).toUTCString(); + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 429, { error: { message: 'slow down' } }, { 'retry-after': farFuture }); + }); + addProvider('p1', upstream.baseUrl, 1); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(429); + + const remaining = db.repo.getProvider('p1')!.cooldownUntil! - Date.now(); + expect(remaining).toBeLessThanOrEqual(MAX_RETRY_AFTER_MS + 2_000); + expect(remaining).toBeGreaterThan(MAX_RETRY_AFTER_MS - 5_000); + }); +}); + +describe('A-02 failed-attempt provider attribution', () => { + it('A-02: attributes the aggregated failure and all router headers to the last provider', async () => { + // Loopback port 1 refuses immediately: two "dead" providers with real attempts. + addProvider('dead-a', 'http://127.0.0.1:1/v1', 1); + addProvider('dead-b', 'http://127.0.0.1:1/v1', 2); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(502); + const body = (await response.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('all_providers_failed'); + + expect(response.headers.get('x-opencode-router-provider')).toBe('dead-b'); + expect(response.headers.get('x-opencode-router-name')).toBe('dead-b'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + expect(response.headers.get('x-opencode-router-request-id')).toBeTruthy(); + + const logs = db.repo.listLogs({}).rows; + expect(logs).toHaveLength(1); + expect(logs[0]!.providerId).toBe('dead-b'); + expect(logs[0]!.providerName).toBe('dead-b'); + expect(logs[0]!.attempts).toBe(2); + expect(db.repo.listAttempts(logs[0]!.id)).toHaveLength(2); + }); +}); + +describe('A-03 active request accounting', () => { + it('A-03: counts a slow proxied request and a models request, then returns to zero', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const upstream = await startUpstream(async (_req, res) => { + await gate; + jsonResponse(res, 200, { id: 'x', usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }); + }); + addProvider('p-slow', upstream.baseUrl, 1); + + expect(getActiveRequests()).toBe(0); + const pending = gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + await waitFor(() => getActiveRequests() === 1, 'in-flight proxied request counted'); + release(); + const response = await pending; + expect(response.status).toBe(200); + await response.json(); + await waitFor(() => getActiveRequests() === 0, 'completed proxied request released'); + + // Models reads are counted too: the preHandler sample proves the counter was held + // held while the models handler produced its payload, and it is 0 afterwards. + activeSamples.length = 0; + const models = await gatewayFetch('/v1/models'); + expect(models.status).toBe(200); + await models.json(); + expect(activeSamples).toContain(1); + expect(getActiveRequests()).toBe(0); + }); +}); + +describe('A-04 single normalization decision', () => { + it('A-04: forwards an untouched body byte-for-byte and a changed body as normalized JSON', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const untouched = Buffer.from('{ "model" : "test/model" , "messages" : [ ] }'); + const first = await gatewayFetch(CHAT, { method: 'POST', body: untouched.toString('utf8') }); + expect(first.status).toBe(200); + await first.json(); + expect(upstream.requests[0]!.body.equals(untouched)).toBe(true); + + // A padded model id is rewritten, so the normalized object (not the raw bytes) is sent. + const padded = Buffer.from('{ "model" : " test/model " , "messages" : [ ] }'); + const second = await gatewayFetch(CHAT, { method: 'POST', body: padded.toString('utf8') }); + expect(second.status).toBe(200); + await second.json(); + const forwarded = upstream.requests[1]!.body; + expect(forwarded.equals(padded)).toBe(false); + expect(JSON.parse(forwarded.toString('utf8'))).toEqual({ model: 'test/model', messages: [] }); + }); +}); + +describe('A-05 bounded and scrubbed upstream error text', () => { + it('A-05: clamps, scrubs and validates errors from a 200 kB upstream body', async () => { + const secret = 'sk-live-super-secret-value'; + const huge = `${secret} ${'x'.repeat(200_000)}`; + const upstream = await startUpstream((_req, res) => { + jsonResponse(res, 500, { type: 'error', error: { type: 'mystery_type', message: huge, code: 'boom' } }); + }); + addProvider('p1', upstream.baseUrl, 1, secret); + db.repo.setSetting('max_retries', '1'); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(500); + const text = await response.text(); + expect(text).not.toContain(secret); + expect(text).not.toContain('x'.repeat(600)); + expect(text).toContain('[redacted]'); + const body = JSON.parse(text) as { error?: { type?: string; message?: string } }; + expect(body.error?.type).toBe('api_error'); + expect(body.error?.message?.length).toBeLessThanOrEqual(500); + + const log = db.repo.listLogs({}).rows[0]!; + expect(log.errorMessage!.length).toBeLessThanOrEqual(500); + expect(log.errorMessage).not.toContain(secret); + expect(db.repo.getProvider('p1')!.lastError).not.toContain(secret); + expect(db.repo.getProvider('p1')!.lastError).toContain('[redacted]'); + }); +}); + +describe('A-06 non-stream response ceiling', () => { + it('A-06: fails with 502 upstream_response_too_large when the cap is below the body size', async () => { + const payload = { id: 'big', pad: 'x'.repeat(4_096) }; + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, payload)); + addProvider('p1', upstream.baseUrl, 1); + + const unlimited = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(unlimited.status).toBe(200); + expect(((await unlimited.json()) as { pad: string }).pad).toHaveLength(4_096); + + db.repo.setSetting('upstream_response_max_bytes', '1024'); + const capped = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(capped.status).toBe(502); + const body = (await capped.json()) as { error?: { code?: string } }; + expect(body.error?.code).toBe('upstream_response_too_large'); + const cappedLog = db.repo.listLogs({}).rows.find((row) => row.errorCode === 'upstream_response_too_large'); + expect(cappedLog).toBeDefined(); + expect(cappedLog!.status).toBe(502); + }); + + it('A-06: decodes a buffered upstream body exactly once', async () => { + const payload = { id: 'x'.repeat(4_093) }; + const serialized = Buffer.from(JSON.stringify(payload)); + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, payload)); + addProvider('p1', upstream.baseUrl, 1); + + const spy = vi.spyOn(Buffer.prototype, 'toString'); + try { + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + await response.json(); + const decodes = (spy.mock.contexts as unknown[]).filter( + (context) => Buffer.isBuffer(context) && context.byteLength === serialized.byteLength, + ).length; + expect(decodes).toBe(1); + } finally { + spy.mockRestore(); + } + }); +}); + +describe('A-07 SSE frame boundaries', () => { + it('A-07: forwards a frame terminated with a mixed line ending without waiting for an idle timeout', async () => { + await startUpstream((_req, res) => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + res.write('data: {"id":"a"}\r\n\n'); + // Keep the connection open: only the boundary scanner can release this frame. + }); + const upstream = upstreams[upstreams.length - 1]!; + addProvider('p1', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: chatBody({ stream: true }), + headers: { accept: 'text/event-stream' }, + }); + expect(response.status).toBe(200); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + const collected = await Promise.race([ + (async () => { + let text = ''; + for (;;) { + const chunk = await reader.read(); + if (chunk.done) return text; + text += decoder.decode(chunk.value, { stream: true }); + if (text.includes('{"id":"a"}')) return text; + } + })(), + new Promise((resolve) => setTimeout(() => resolve(''), 3_000)), + ]); + await reader.cancel().catch(() => undefined); + expect(collected).toContain('{"id":"a"}'); + }); +}); + +describe('A-08 query-string forwarding', () => { + it('A-08: forwards the client query string on the proxied surfaces', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const chat = await gatewayFetch(`${CHAT}?beta=true`, { method: 'POST', body: chatBody() }); + expect(chat.status).toBe(200); + expect(upstream.requests[0]!.url).toBe('/v1/chat/completions?beta=true'); + + const messages = await gatewayFetch('/v1/messages?version=2025-01-01', { + method: 'POST', + body: JSON.stringify({ + model: 'test/model', + max_tokens: 8, + messages: [{ role: 'user', content: 'ping' }], + }), + }); + expect(messages.status).toBe(200); + expect(upstream.requests[1]!.url).toBe('/v1/messages?version=2025-01-01'); + }); +}); + +describe('A-09 forwarded client headers', () => { + it('A-09: forwards provider-identity headers and never client credentials or host', async () => { + const upstream = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'x' })); + addProvider('p1', upstream.baseUrl, 1); + + const response = await gatewayFetch(CHAT, { + method: 'POST', + body: chatBody(), + headers: { + 'openai-organization': 'org-123', + 'openai-project': 'proj-456', + 'http-referer': 'https://app.example/', + 'x-title': 'My App', + // The client's own gateway credential must never be relayed upstream. + 'x-api-key': apiKey, + }, + }); + expect(response.status).toBe(200); + const headers = upstream.requests[0]!.headers; + expect(headers['openai-organization']).toBe('org-123'); + expect(headers['openai-project']).toBe('proj-456'); + expect(headers['http-referer']).toBe('https://app.example/'); + expect(headers['x-title']).toBe('My App'); + // Router credentials always win; the gateway client key never reaches the provider. + expect(headers['authorization']).toBe('Bearer sk-provider'); + expect(headers['x-api-key']).toBe('sk-provider'); + expect(headers['x-api-key']).not.toBe(apiKey); + expect(headers['host']).toBe(`127.0.0.1:${upstream.port}`); + }); +}); + +describe('A-11 payload too large mapping', () => { + it('A-11: answers 413 payload_too_large without leaking the Fastify internal code', async () => { + addProvider('p1', 'http://127.0.0.1:1/v1', 1); + const oversized = JSON.stringify({ model: 'test/model', pad: 'x'.repeat(4_096) }); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: oversized }); + expect(response.status).toBe(413); + const text = await response.text(); + expect(text).not.toContain('FST_ERR'); + const body = JSON.parse(text) as { error?: { code?: string; message?: string } }; + expect(body.error?.code).toBe('payload_too_large'); + expect(body.error?.message).toContain(String(ctx.config.bodyLimit)); + expect(db.repo.listLogs({}).total).toBe(1); + }); +}); + +describe('A-12 models helper status', () => { + it('A-12: applies a non-200 status passed to finishModelsRequest', async () => { + const probe = Fastify({ logger: false }); + probe.get('/probe', async (request, reply) => { + request.gateway = { + requestId: 'probe-request', + startedAt: Date.now(), + key: null, + logged: false, + rawBody: null, + }; + finishModelsRequest(ctx, request, reply, { status: 201, ok: true, model: null }); + await reply.send({ object: 'list', data: [] }); + }); + const response = await probe.inject({ method: 'GET', url: '/probe' }); + await probe.close(); + expect(response.statusCode).toBe(201); + expect(response.json()).toEqual({ object: 'list', data: [] }); + expect(response.headers['x-opencode-router-request-id']).toBe('probe-request'); + }); +}); + +describe('A-13 method not allowed', () => { + it('A-13: answers 405 with Allow on known paths and 404 unknown_endpoint elsewhere', async () => { + addProvider('p1', 'http://127.0.0.1:1/v1', 1); + + const put = await gatewayFetch(CHAT, { method: 'PUT', body: chatBody() }); + expect(put.status).toBe(405); + expect(put.headers.get('allow')).toBe('POST'); + expect(((await put.json()) as { error?: { code?: string } }).error?.code).toBe('method_not_allowed'); + + const options = await gatewayFetch(CHAT, { method: 'OPTIONS' }); + expect(options.status).toBe(405); + expect(options.headers.get('allow')).toBe('POST'); + + const unknown = await gatewayFetch('/v1/nope'); + expect(unknown.status).toBe(404); + expect(((await unknown.json()) as { error?: { code?: string } }).error?.code).toBe('unknown_endpoint'); + + // Exactly one log row per client request, method failures included. + expect(db.repo.listLogs({}).total).toBe(3); + }); +}); + +describe('A-14 all-5xx failover', () => { + it('A-14: fails over to the next provider on an upstream 501', async () => { + const bad = await startUpstream((_req, res) => { + jsonResponse(res, 501, { error: { message: 'not implemented' } }); + }); + const good = await startUpstream((_req, res) => jsonResponse(res, 200, { id: 'ok' })); + addProvider('bad', bad.baseUrl, 1); + addProvider('good', good.baseUrl, 2); + + const response = await gatewayFetch(CHAT, { method: 'POST', body: chatBody() }); + expect(response.status).toBe(200); + expect(((await response.json()) as { id: string }).id).toBe('ok'); + expect(response.headers.get('x-opencode-router-provider')).toBe('good'); + expect(response.headers.get('x-opencode-router-attempts')).toBe('2'); + + const log = db.repo.listLogs({}).rows[0]!; + expect(log.attempts).toBe(2); + const attempts = db.repo.listAttempts(log.id).sort((a, b) => a.attempt - b.attempt); + expect(attempts.map((attempt) => attempt.status)).toEqual([501, 200]); + }); +}); \ No newline at end of file diff --git a/tests/gateway-normalize.test.ts b/tests/gateway-normalize.test.ts index 860e29a..0113bca 100644 --- a/tests/gateway-normalize.test.ts +++ b/tests/gateway-normalize.test.ts @@ -148,6 +148,99 @@ describe('normalizeBody', () => { }); }); +describe('A-04 explicit change flag', () => { + interface Fixture { + label: string; + surface: 'chat' | 'responses' | 'messages'; + body: Json; + model: ModelRow | null; + } + + const fixtures: Fixture[] = [ + { label: 'untouched', surface: 'chat', body: { model: 'm', messages: [] }, model: null }, + { label: 'model trim', surface: 'chat', body: { model: ' m ' }, model: null }, + { label: 'model already trimmed', surface: 'chat', body: { model: 'm' }, model: null }, + { label: 'usage injection', surface: 'chat', body: { model: 'm', stream: true }, model: null }, + { + label: 'usage already present', + surface: 'chat', + body: { model: 'm', stream: true, stream_options: { include_usage: true } }, + model: null, + }, + { + label: 'non-reasoning hint removal', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'high', reasoning: { effort: 'high' }, thinking: { type: 'enabled' } }, + model: plainModel, + }, + { + label: 'non-reasoning without hints', + surface: 'chat', + body: { model: 'm' }, + model: plainModel, + }, + { + label: 'chat effort rewrite', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'xhigh' }, + model: reasoningModel, + }, + { + label: 'chat effort already supported', + surface: 'chat', + body: { model: 'm', reasoning_effort: 'high' }, + model: reasoningModel, + }, + { + label: 'responses effort rewrite', + surface: 'responses', + body: { model: 'm', reasoning: { effort: 'xhigh', summary: 'auto' } }, + model: reasoningModel, + }, + { + label: 'responses effort already supported', + surface: 'responses', + body: { model: 'm', reasoning: { effort: 'high', summary: 'auto' } }, + model: reasoningModel, + }, + { + label: 'messages thinking passthrough', + surface: 'messages', + body: { model: 'm', thinking: { type: 'enabled', budget_tokens: 8_000 } }, + model: reasoningModel, + }, + { + label: 'undefined reasoning hint', + surface: 'chat', + body: { model: 'm', reasoning_effort: undefined }, + model: plainModel, + }, + ]; + + it('A-04: the flag agrees with the old serialized-body comparison on a fixture table', () => { + for (const fixture of fixtures) { + const out = normalizeBody(fixture.surface, fixture.body, fixture.model); + const oldChanged = JSON.stringify(out.body) !== JSON.stringify(fixture.body); + expect(out.changed, fixture.label).toBe(oldChanged); + } + }); + + it('A-04: flags reasoning removal, effort rewrite, model trim and usage injection', () => { + expect(normalizeBody('chat', { model: ' m ' }, null).changed).toBe(true); + expect(normalizeBody('chat', { model: 'm' }, null).changed).toBe(false); + expect(normalizeBody('chat', { model: 'm', stream: true }, null).changed).toBe(true); + expect( + normalizeBody('chat', { model: 'm', stream: true, stream_options: { include_usage: true } }, null).changed, + ).toBe(false); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'high', thinking: {} }, plainModel).changed).toBe( + true, + ); + expect(normalizeBody('chat', { model: 'm' }, plainModel).changed).toBe(false); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'xhigh' }, reasoningModel).changed).toBe(true); + expect(normalizeBody('chat', { model: 'm', reasoning_effort: 'high' }, reasoningModel).changed).toBe(false); + }); +}); + describe('model id normalization (GW-11)', () => { it('forwards the trimmed model id', () => { const out = normalizeBody('chat', { model: ' opencode/flint ' }, null); diff --git a/tests/gateway-proxy-helpers.test.ts b/tests/gateway-proxy-helpers.test.ts index 73394f0..7b4537b 100644 --- a/tests/gateway-proxy-helpers.test.ts +++ b/tests/gateway-proxy-helpers.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from 'vitest'; import { + MAX_RETRY_AFTER_MS, + MAX_UPSTREAM_RESPONSE_BYTES, bodyReadFailureStatus, forwardedResponseHeaders, + nextBoundary, + parseRetryAfter, + parseUpstreamResponseMaxBytes, retryAfterMs, retryAfterSeconds, rewriteSseFrame, @@ -107,6 +112,74 @@ describe('retryAfterMs', () => { expect(retryAfterMs('')).toBeNull(); expect(retryAfterMs('soon')).toBeNull(); }); + + it('A-01: clamps numeric and HTTP-date values above the one-hour cap', () => { + expect(MAX_RETRY_AFTER_MS).toBe(3_600_000); + expect(retryAfterMs('31536000')).toBe(MAX_RETRY_AFTER_MS); + expect(retryAfterMs('9'.repeat(400))).toBe(MAX_RETRY_AFTER_MS); + const now = 1_700_000_000_000; + const farFuture = new Date(now + 10 * 365 * 24 * 3600 * 1000).toUTCString(); + expect(retryAfterMs(farFuture, now)).toBe(MAX_RETRY_AFTER_MS); + // Exactly at the cap is not clamped; below it is untouched. + expect(retryAfterMs('3600')).toBe(3_600_000); + expect(retryAfterMs('3599')).toBe(3_599_000); + }); + + it('A-01: reports whether the parsed value was capped', () => { + expect(parseRetryAfter('31536000')).toMatchObject({ ms: MAX_RETRY_AFTER_MS, capped: true }); + expect(parseRetryAfter('2')).toMatchObject({ ms: 2_000, capped: false }); + expect(parseRetryAfter('soon')).toBeNull(); + expect(parseRetryAfter(null)).toBeNull(); + }); +}); + +describe('A-06 upstream_response_max_bytes parsing', () => { + it('A-06: accepts 0 and the 1 KiB..1 GiB range, ignoring everything else', () => { + expect(parseUpstreamResponseMaxBytes(null)).toBe(0); + expect(parseUpstreamResponseMaxBytes(undefined)).toBe(0); + expect(parseUpstreamResponseMaxBytes('0')).toBe(0); + expect(parseUpstreamResponseMaxBytes('1024')).toBe(1_024); + expect(parseUpstreamResponseMaxBytes(String(MAX_UPSTREAM_RESPONSE_BYTES))).toBe(MAX_UPSTREAM_RESPONSE_BYTES); + expect(parseUpstreamResponseMaxBytes('1023')).toBe(0); + expect(parseUpstreamResponseMaxBytes(String(MAX_UPSTREAM_RESPONSE_BYTES + 1))).toBe(0); + expect(parseUpstreamResponseMaxBytes('abc')).toBe(0); + expect(parseUpstreamResponseMaxBytes('-5')).toBe(0); + }); +}); + +describe('A-07 SSE frame boundaries', () => { + it('A-07: recognises every supported terminator shape', () => { + const terminators: Array<[string, number]> = [ + ['\n\n', 2], + ['\r\n\r\n', 4], + ['\r\n\n', 3], + ['\n\r\n', 3], + ['\r\r', 2], + ]; + for (const [terminator, length] of terminators) { + const buffer = Buffer.from(`data: {"a":1}${terminator}rest`); + const boundary = nextBoundary(buffer); + expect(boundary, JSON.stringify(terminator)).not.toBeNull(); + expect(boundary!.length).toBe(length); + expect(buffer.subarray(boundary!.index, boundary!.index + length).toString('utf8')).toBe(terminator); + } + expect(nextBoundary(Buffer.from('data: {"a":1}'))).toBeNull(); + }); + + it('A-07: strips x_opencode from a frame with two data lines and rewrites one canonical line', () => { + const frame = 'data: {"id":"x",\ndata: "x_opencode":{"session_id":"s"}}'; + const out = rewriteSseFrame(frame); + expect(out).not.toBe(frame); + expect(out).not.toContain('x_opencode'); + expect(out.split('\n')).toHaveLength(1); + expect(JSON.parse(out.slice(5).trim())).toEqual({ id: 'x' }); + }); + + it('A-07: leaves a frame without x_opencode byte-identical', () => { + const frame = 'event: message\ndata: {"id":"x","choices":[{"delta":"日本語"}]}'; + expect(rewriteSseFrame(frame)).toBe(frame); + expect(rewriteSseFrame('data: {"x_opencode"')).toBe('data: {"x_opencode"'); + }); }); describe('bodyReadFailureStatus (GW-03)', () => { diff --git a/tests/gateway-rotation.test.ts b/tests/gateway-rotation.test.ts index da71c71..de235e5 100644 --- a/tests/gateway-rotation.test.ts +++ b/tests/gateway-rotation.test.ts @@ -42,6 +42,49 @@ describe('orderProviders random', () => { expect(ids(ordered).sort()).toEqual(['a', 'b', 'c', 'd']); } }); + + it('A-15: produces the exact permutation for an injected RNG sequence', () => { + const candidates = [provider('a'), provider('b'), provider('c'), provider('d')]; + const rotation = orderProviders(candidates, 0, 'random', { random: () => 0 }); + // Fisher-Yates with random() === 0 swaps every index with 0: d,c,b,a -> b,c,d,a. + expect(ids(rotation.candidates)).toEqual(['b', 'c', 'd', 'a']); + + const sequence = [0.9, 0.2, 0.5]; + let index = 0; + const second = orderProviders(candidates, 0, 'random', { random: () => sequence[index++] ?? 0 }); + expect(ids(second.candidates)).toEqual(['c', 'b', 'a', 'd']); + }); + + it('A-15: still applies cooldown skipping and fallback with an injected RNG', () => { + const now = 1_000_000; + const warm = orderProviders( + [provider('warm'), provider('cool', { cooldownUntil: now + 5_000 })], + now, + 'random', + { random: () => 0 }, + ); + expect(warm.cooldownFallback).toBe(false); + expect(ids(warm.candidates)).toEqual(['warm']); + + const fallback = orderProviders( + [ + provider('late', { cooldownUntil: now + 60_000 }), + provider('soon', { cooldownUntil: now + 1_000 }), + ], + now, + 'random', + { random: () => 0 }, + ); + expect(fallback.cooldownFallback).toBe(true); + expect(ids(fallback.candidates)).toEqual(['soon', 'late']); + }); + + it('A-15: production default still uses Math.random and shuffles a copy', () => { + const candidates = [provider('a'), provider('b'), provider('c')]; + const rotation = orderProviders(candidates, 0, 'random'); + expect(ids(rotation.candidates).sort()).toEqual(['a', 'b', 'c']); + expect(ids(candidates)).toEqual(['a', 'b', 'c']); + }); }); describe('orderProviders cooldown handling', () => { diff --git a/tests/tooling.test.ts b/tests/tooling.test.ts index 256ea40..0b5d734 100644 --- a/tests/tooling.test.ts +++ b/tests/tooling.test.ts @@ -1,12 +1,84 @@ +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { MAX_SUBJECT_LENGTH, + buildFixtureRepo, commitRange, + createSelfTestCases, emptyRangeFails, + lint, + runSelfTest as runCommitSelfTest, + setRepoCwd, validateSubject, } from '../scripts/check-commit-messages.mjs'; -import { normalizePath } from '../scripts/check-docs.js'; -import { ensureChrome } from '../scripts/screenshots.js'; +import { + DOC_FILES, + collectConfigDefaults, + collectDocumentedDefaults, + collectDocumentedPaths, + collectEnvVarUsage, + collectRoutes, + collectSettingKeys, + normalizePath, + pathMatches, + runCheck, + runSelfTest as runDocsSelfTest, + writeFixtureTree, +} from '../scripts/check-docs.js'; +import { + checkEnvExampleParity, + createEnvExampleFixtures, + loadEnvExample, + parseEnvExample, + runSelfTest as runEnvSelfTest, +} from '../scripts/check-env-example.js'; +import { chromeVersion, ensureChrome, isChromeVersionOutput } from '../scripts/screenshots.js'; +import { extractSessionCookie } from '../scripts/live-check.js'; +import { planStages } from '../scripts/verify.js'; + +/* --------------------------------------------------------------------- fixtures */ + +const tempRoots: string[] = []; + +function makeRoot(prefix: string): string { + const root = mkdtempSync(join(tmpdir(), prefix)); + tempRoots.push(root); + return root; +} + +/** Writes a complete, self-consistent repo fixture tree (see `writeFixtureTree`). */ +function makeRepoFixture(): string { + const root = makeRoot('okr-tooling-'); + writeFixtureTree(root); + return root; +} + +function writeFixtureFile(root: string, rel: string, content: string): void { + const file = join(root, rel); + mkdirSync(join(file, '..'), { recursive: true }); + writeFileSync(file, content, 'utf8'); +} + +function readFixtureFile(root: string, rel: string): string { + return readFileSync(join(root, rel), 'utf8'); +} + +/** Replaces the first occurrence of `from` in a fixture file (fails loudly if absent). */ +function patchFixtureFile(root: string, rel: string, from: string, to: string): void { + const text = readFixtureFile(root, rel); + expect(text).toContain(from); + writeFixtureFile(root, rel, text.replace(from, to)); +} + +afterEach(() => { + vi.unstubAllEnvs(); + for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +/* --------------------------------------------------------- commit-message rules */ describe('commit-message validator', () => { const accepted: Array<[subject: string, body?: string, why?: string]> = [ @@ -60,7 +132,7 @@ describe('commit-message validator', () => { }); }); -describe('commit-message range handling', () => { +describe('commit-message range and --single handling', () => { it('builds the explicit base..head range', () => { expect(commitRange('origin/main', 'HEAD')).toBe('origin/main..HEAD'); }); @@ -75,9 +147,143 @@ describe('commit-message range handling', () => { expect(emptyRangeFails(undefined, undefined)).toBe(false); expect(emptyRangeFails('origin/main', '')).toBe(false); }); + + it('D-01: fails to lint an unknown sha instead of passing an empty check', () => { + expect(() => lint({ single: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' })).toThrow(/could not be read/); + }); + + it('D-01: an explicit range is never silently accepted as empty', () => { + // `lint` must fail (not return zero failures) when git finds nothing in a supplied + // range; the self-test below drives that against a real throw-away repository. + expect(emptyRangeFails('HEAD', 'HEAD')).toBe(true); + }); + + it('D-01: --single runs against a real commit in the repository', () => { + // The current HEAD is a real commit; linting it must not throw and must report the + // commit count, proving the CLI path used by CI's all-zero fallback works end to end. + const head = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(); + const result = lint({ single: head }); + expect(result.linted).toBe(1); + }); }); -describe('doc checker path normalization', () => { +describe('Defect 5: --single resolves the exact commit (no merge ancestor substitution)', () => { + let fixture: ReturnType | null = null; + + /** Builds the fixture repo and points the linter at it for the current test. */ + function useFixture(): ReturnType { + const repo = buildFixtureRepo(); + fixture = repo; + setRepoCwd(repo.dir); + return repo; + } + + afterEach(() => { + setRepoCwd(process.cwd()); + if (fixture) { + rmSync(fixture.dir, { recursive: true, force: true }); + fixture = null; + } + }); + + it('--single on a merge sha fails with the merge message', () => { + const repo = useFixture(); + // `git log -1 --no-merges ` would silently resolve to one of the merge's + // ancestors and lint that unrelated commit; the exact-object check must refuse. + expect(() => lint({ single: repo.merge })).toThrow(/is a merge commit/); + expect(() => lint({ single: repo.merge })).toThrow(/lint the squashed\/branch commit instead/); + }); + + it('--single on a normal sha still lints exactly that commit (subject failures detected)', () => { + const repo = useFixture(); + const result = lint({ single: repo.bad }); + expect(result.linted).toBe(1); + expect(result.failures).toHaveLength(1); + expect(result.failures[0]?.problems.join('\n')).toContain('does not match'); + + const goodResult = lint({ single: repo.good }); + expect(goodResult.linted).toBe(1); + expect(goodResult.failures).toEqual([]); + }); + + it('--single on an unknown sha still fails with "could not be read"', () => { + useFixture(); + expect(() => lint({ single: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' })).toThrow(/could not be read/); + }); + + it('an explicitly supplied base+head pair with zero commits still fails', () => { + const repo = useFixture(); + // The no-argument default range stays a local convenience (empty = nothing to + // validate), but an explicit pair must never pass an empty check. + expect(() => lint({ base: repo.good, head: repo.good })).toThrow(/No commits found/); + expect(emptyRangeFails(repo.good, repo.good)).toBe(true); + }); +}); + +describe('D-01/D-14: commit-linter self-test', () => { + it('passes on a healthy checker', () => { + expect(runCommitSelfTest()).toBe(0); + }); + + it('covers --single, empty ranges, bad types, periods, footers and PR titles', () => { + // `buildFixtureRepo` is exported, but the self-test is the contract here. Assert both + // that it passes and that it exercised every required defect class. + const lines: string[] = []; + const log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(' ')); + }); + try { + expect(runCommitSelfTest()).toBe(0); + } finally { + log.mockRestore(); + } + const okLines = lines.filter((line) => line.startsWith('ok ')); + expect(okLines.length).toBeGreaterThanOrEqual(9); + for (const expected of [ + 'good commit via --single', + 'bad type via --single', + 'unknown sha via --single', + 'trailing period', + 'missing BREAKING CHANGE footer', + 'empty explicit range', + 'bad PR title', + ]) { + expect(okLines.some((line) => line.includes(expected))).toBe(true); + } + }); + + it('exits non-zero when one expectation is deliberately inverted', () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => undefined); + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + try { + expect(runCommitSelfTest({ invertCase: 'bad type via --single' })).toBe(1); + } finally { + log.mockRestore(); + error.mockRestore(); + } + }); + + it('fixture cases include both expectations, so the self-test can fail', () => { + // `createSelfTestCases` needs real sha values; the self-test builds them. What matters + // here is that the case set is not all-positive (a self-test that cannot fail). + const lines: string[] = []; + const log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(' ')); + }); + try { + expect(runCommitSelfTest()).toBe(0); + } finally { + log.mockRestore(); + } + expect(lines.some((line) => line.includes('rejected:'))).toBe(true); + expect(lines.some((line) => line.includes('accepted 1 commit(s)'))).toBe(true); + expect(typeof createSelfTestCases).toBe('function'); + }); +}); + +/* ------------------------------------------------------------- check-docs internals */ + +describe('check-docs path normalization', () => { it('normalizes params and wildcards so code and docs compare equal', () => { expect(normalizePath('/v1/models/:id')).toBe('/v1/models/:p'); expect(normalizePath('/v1/models/*')).toBe('/v1/models/:p'); @@ -87,11 +293,289 @@ describe('doc checker path normalization', () => { expect(normalizePath('/')).toBe('/'); expect(normalizePath('/dashboard/')).toBe('/dashboard'); }); + + it('matches documented param routes against registered families', () => { + const documented = new Set(['/v1/models/:p']); + expect(pathMatches('/v1/models', documented)).toBe(true); + expect(pathMatches('/v1/keys', documented)).toBe(false); + }); }); -describe('screenshots harness Chrome guard', () => { - afterEach(() => { - vi.unstubAllEnvs(); +describe('D-03: check-docs collectors', () => { + it('finds env vars read anywhere under src/**, including the envBool/envInt helper form', () => { + const root = makeRepoFixture(); + writeFixtureFile( + root, + 'src/util/extra.ts', + "export const depth = envInt('EXTRA_DEPTH', 2);\nexport const mode = process.env.EXTRA_MODE ?? 'x';\nexport const quoted = envBool(\"EXTRA_QUOTED\", false);\n", + ); + const usage = collectEnvVarUsage(root); + expect([...usage.keys()]).toEqual([ + 'EXTRA_DEPTH', + 'EXTRA_MODE', + 'EXTRA_QUOTED', + 'FIXTURE_FLAG', + 'FIXTURE_LOG_LEVEL', + 'FIXTURE_PORT', + 'FIXTURE_RETRIES', + 'FIXTURE_SECRET', + 'NODE_ENV', + ]); + // Findings must point at the file that reads the var, not at src/config.ts always. + expect(usage.get('EXTRA_MODE')).toBe('src/util/extra.ts:2'); + }); + + it('accepts single-quoted, double-quoted and backtick route paths', () => { + const root = makeRepoFixture(); + writeFixtureFile( + root, + 'src/routes.ts', + [ + "app.get('/one', () => {});", + 'app.post("/two", () => {});', + 'app.put(`/three`, () => {});', + 'app.delete(/regex/, () => {});', + "app.get(notAString, () => {});", + ].join('\n'), + ); + const paths = collectRoutes(root).map((route) => `${route.method} ${route.path}`); + expect(paths).toContain('GET /one'); + expect(paths).toContain('POST /two'); + expect(paths).toContain('PUT /three'); + expect(paths.some((path) => path.includes('regex'))).toBe(false); + }); + + it('accepts an explicit method option instead of guessing POST', () => { + const root = makeRepoFixture(); + writeFixtureFile( + root, + 'src/explicit.ts', + "app.route({ method: 'PATCH', url: '/thing' });\napp.route({ method: ['GET', 'HEAD'], url: '/things' });\n", + ); + const paths = collectRoutes(root).map((route) => `${route.method} ${route.path}`); + expect(paths).toContain('PATCH /thing'); + // An array of methods registers one entry per method, not a guessed POST. + expect(paths).toContain('GET /things'); + expect(paths).toContain('HEAD /things'); + expect(paths).not.toContain('POST /things'); + }); + + it('collects DEFAULT_SETTINGS keys and config defaults', () => { + const root = makeRepoFixture(); + expect(collectSettingKeys(root)).toContain('fixture_setting'); + const defaults = collectConfigDefaults(root); + expect(defaults.get('FIXTURE_PORT')).toBe(1234); + expect(defaults.get('FIXTURE_FLAG')).toBe(false); + expect(defaults.get('FIXTURE_LOG_LEVEL')).toBe('info'); + // The real config: numeric helper defaults and expression defaults are extracted. + const real = collectConfigDefaults(process.cwd()); + expect(real.get('PORT')).toBe(20125); + expect(real.get('BODY_LIMIT')).toBe(134217728); + expect(real.get('SESSION_TTL_MS')).toBe(604800000); + expect(real.get('TRUST_PROXY')).toBe(false); + expect(real.get('HOST')).toBe('0.0.0.0'); + }); + + it('collects documented defaults from the SPEC env table', () => { + const root = makeRepoFixture(); + const docText = DOC_FILES.map((rel) => readFixtureFile(root, rel)).join('\n'); + expect([...collectDocumentedDefaults(docText)]).toContainEqual(['FIXTURE_PORT', '1234']); + // Placeholder paths are not comparable defaults. + const real = collectDocumentedDefaults(readFileSync(join(process.cwd(), 'docs/SPEC.md'), 'utf8')); + expect(real.get('PORT')).toBe('20125'); + expect(real.has('ROUTER_SECRET')).toBe(false); + }); + + it('collects documented paths and skips undocumented wildcard families', () => { + const paths = collectDocumentedPaths(['`GET /v1/models`', '`/admin/api/logs*`', '`POST /v1/messages`']); + expect(paths).toEqual(['/v1/messages', '/v1/models']); + // A method-declared wildcard names a real registered route, so it is kept. + expect(collectDocumentedPaths(['`ALL /v1/*`'])).toEqual(['/v1/*']); + }); +}); + +describe('D-04: check-docs drift comparison', () => { + it('passes a clean fixture tree', () => { + expect(runCheck(makeRepoFixture()).findings).toEqual([]); + }); + + it('flags an undocumented env var read anywhere under src/**', () => { + const root = makeRepoFixture(); + patchFixtureFile( + root, + 'src/config.ts', + "const fixtureFlag = process.env.FIXTURE_FLAG;", + 'const fixtureFlag = process.env.FIXTURE_FLAG;\nconst undocumented = process.env.UNDOCUMENTED_FLAG;', + ); + const findings = runCheck(root).findings.filter((finding) => finding.group === 'env vars'); + expect(findings.map((finding) => finding.message)).toContainEqual( + expect.stringContaining('UNDOCUMENTED_FLAG is read by src/config.ts'), + ); + }); + + it('flags an undocumented route', () => { + const root = makeRepoFixture(); + patchFixtureFile(root, 'src/admin/routes.ts', 'scope.get("/fixture/get");', 'scope.get("/fixture/undocumented");'); + const findings = runCheck(root).findings.filter((finding) => finding.group === 'routes'); + expect(findings.some((finding) => finding.message.includes('GET /fixture/undocumented'))).toBe(true); + }); + + it('flags a documented route no code implements', () => { + const root = makeRepoFixture(); + patchFixtureFile(root, 'docs/API.md', '# Fixture API\n', '# Fixture API\n\n`GET /v1/fixture/ghost`\n'); + const findings = runCheck(root).findings.filter((finding) => finding.group === 'routes'); + expect(findings.some((finding) => finding.message.includes('/v1/fixture/ghost is documented'))).toBe(true); + }); + + it('flags an undocumented setting key', () => { + const root = makeRepoFixture(); + patchFixtureFile(root, 'src/db/repos.ts', "fixture_setting: '1',", "fixture_setting: '1',\n new_setting: '2',"); + const findings = runCheck(root).findings.filter((finding) => finding.group === 'settings'); + expect(findings.some((finding) => finding.message.includes('new_setting'))).toBe(true); + }); + + it('matches admin routes against their /admin/api documented form', () => { + const root = makeRepoFixture(); + patchFixtureFile(root, 'docs/API.md', '# Fixture API\n', '# Fixture API\n\n`GET /admin/api/fixture/get`\n'); + expect(runCheck(root).findings.filter((finding) => finding.group === 'routes')).toEqual([]); + }); +}); + +describe('D-14: check-docs self-test', () => { + it('passes and covers every defect class', () => { + const { failures, cases } = runDocsSelfTest(); + expect(failures).toEqual([]); + expect(cases).toBeGreaterThanOrEqual(9); + }); + + it('fails when a fixture is deliberately mutated to a wrong expectation', () => { + const { failures } = runDocsSelfTest({ + mutateFixture: (fixture) => (fixture.name === 'clean fixture tree' ? { ...fixture, expectClean: false } : fixture), + }); + expect(failures).toHaveLength(1); + expect(failures[0]).toContain('clean fixture tree'); + }); + + it('fails when one expectation is deliberately inverted (self-test can fail)', () => { + const { failures } = runDocsSelfTest({ invertCase: 'undocumented env var' }); + expect(failures).toHaveLength(1); + expect(failures[0]).toContain('undocumented env var'); + expect(failures[0]).toContain('[inverted expectation]'); + }); +}); + +/* ------------------------------------------------------------ .env.example parity */ + +describe('D-05: .env.example parity', () => { + const baseOptions = { + configDefault: (name: string) => ({ FIXTURE_PORT: 1234, FIXTURE_FLAG: false })[name as 'FIXTURE_PORT'], + documentedDefaults: new Map([ + ['FIXTURE_PORT', '1234'], + ['FIXTURE_FLAG', 'false'], + ]), + requireDocumentedDefaults: 2, + }; + const codeVars = ['FIXTURE_PORT', 'FIXTURE_FLAG']; + + it('accepts a consistent template', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\nFIXTURE_FLAG=false\n'); + expect(checkEnvExampleParity({ keys, error: null }, codeVars, baseOptions).findings).toEqual([]); + }); + + it('counts a commented-out assignment as documentation', () => { + const keys = parseEnvExample('# FIXTURE_FLAG=false\nFIXTURE_PORT=1234\n'); + expect([...keys.keys()]).toEqual(['FIXTURE_FLAG', 'FIXTURE_PORT']); + expect(checkEnvExampleParity({ keys, error: null }, codeVars, baseOptions).findings).toEqual([]); + }); + + it('fails when an env var is missing from the template', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\n'); + const { findings } = checkEnvExampleParity({ keys, error: null }, codeVars, baseOptions); + expect(findings.map((finding) => finding.message)).toContainEqual( + expect.stringContaining('FIXTURE_FLAG is read by the server but missing'), + ); + }); + + it('fails on a template key no source file reads', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\nFIXTURE_FLAG=false\nSTALE_KEY=1\n'); + const { findings } = checkEnvExampleParity({ keys, error: null }, codeVars, baseOptions); + expect(findings.some((finding) => finding.message.includes('STALE_KEY'))).toBe(true); + }); + + it('allows runtime-only keys such as NODE_ENV', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\nFIXTURE_FLAG=false\nNODE_ENV=production\n'); + const { findings } = checkEnvExampleParity({ keys, error: null }, codeVars, baseOptions); + expect(findings).toEqual([]); + }); + + it('fails when a documented default contradicts the code', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\nFIXTURE_FLAG=false\n'); + const { findings, compared } = checkEnvExampleParity({ keys, error: null }, codeVars, { + ...baseOptions, + documentedDefaults: new Map([ + ['FIXTURE_PORT', '4321'], + ['FIXTURE_FLAG', 'false'], + ]), + }); + expect(compared).toBe(2); + expect(findings.some((finding) => finding.message.includes('documented with default "4321"'))).toBe(true); + }); + + it('fails when the documented-default table cannot be parsed at all', () => { + const keys = parseEnvExample('FIXTURE_PORT=1234\nFIXTURE_FLAG=false\n'); + const { findings } = checkEnvExampleParity({ keys, error: null }, codeVars, { + ...baseOptions, + documentedDefaults: new Map(), + }); + expect(findings.some((finding) => finding.message.includes('could be compared with docs/SPEC.md'))).toBe(true); + }); + + it('reports an unreadable template', () => { + const { findings } = checkEnvExampleParity({ keys: new Map(), error: 'boom' }, codeVars, baseOptions); + expect(findings).toHaveLength(1); + expect(findings[0]?.message).toContain('could not be parsed'); + }); + + it('passes the real repository (env example ↔ config ↔ SPEC defaults)', () => { + const envExample = loadEnvExample(process.cwd()); + expect(envExample.error).toBeNull(); + const { findings } = checkEnvExampleParity(envExample, collectEnvVarUsage(process.cwd()).keys(), { + configDefault: (name) => collectConfigDefaults(process.cwd()).get(name), + documentedDefaults: collectDocumentedDefaults( + DOC_FILES.map((rel) => readFileSync(join(process.cwd(), rel), 'utf8')).join('\n'), + ), + requireDocumentedDefaults: 4, + }); + // NODE_ENV is intentionally allowlisted as runtime-only in the CLI default. + expect(findings).toEqual([]); + }); + + it('self-test passes on the fixture set and would catch a wrong expectation', () => { + const { failures, cases } = runEnvSelfTest(); + expect(cases).toBeGreaterThanOrEqual(5); + expect(failures).toEqual([]); + // The parity checker must actually reject the recorded bad fixtures: a mutation of + // any one case flips it into the failure list. + const broken = createEnvExampleFixtures().filter((fixture) => !fixture.expectClean); + expect(broken.length).toBeGreaterThanOrEqual(4); + }); +}); + +/* ----------------------------------------------------------------- screenshots */ + +describe('D-06: screenshots Chrome guard', () => { + function chromeStub(output: string): string { + const root = makeRoot('okr-chrome-'); + const file = join(root, 'chrome-stub'); + writeFileSync(file, `#!/bin/sh\necho "${output}"\n`, { mode: 0o755 }); + return file; + } + + it('recognizes browser version output only', () => { + expect(isChromeVersionOutput('Google Chrome 141.0.7390.54')).toBe(true); + expect(isChromeVersionOutput('Chromium 141.0.7390.54')).toBe(true); + expect(isChromeVersionOutput('v26.13.1')).toBe(false); + expect(isChromeVersionOutput('')).toBe(false); }); it('skips a missing Chrome without --strict (exit 0 stays possible)', async () => { @@ -104,8 +588,134 @@ describe('screenshots harness Chrome guard', () => { await expect(ensureChrome('/nonexistent/chrome-binary', true)).rejects.toThrow(/--strict/); }); - it('accepts an existing binary', async () => { + it('rejects a directory and a non-executable file', async () => { + vi.stubEnv('CHROME_PATH', ''); + const dir = makeRoot('okr-dir-'); + await expect(ensureChrome(dir, false)).resolves.toBe('skip'); + const root = makeRoot('okr-noexec-'); + const file = join(root, 'chrome'); + writeFileSync(file, '#!/bin/sh\necho x\n', { mode: 0o644 }); + await expect(ensureChrome(file, false)).resolves.toBe('skip'); + }); + + it('rejects an executable that is not a browser (the Node binary)', async () => { + vi.stubEnv('CHROME_PATH', ''); + await expect(ensureChrome(process.execPath, false)).resolves.toBe('skip'); + await expect(ensureChrome(process.execPath, true)).rejects.toThrow(/not a Chromium browser/); + }); + + it('accepts a stub executable that reports a browser version', async () => { vi.stubEnv('CHROME_PATH', ''); - await expect(ensureChrome(process.execPath, false)).resolves.toBe('ok'); + const stub = chromeStub('Google Chrome 141.0.7390.54'); + if (process.platform === 'win32') return; // the stub is a POSIX shell script + await expect(ensureChrome(stub, true)).resolves.toBe('ok'); + expect(chromeVersion(stub)).toContain('Chrome'); }); -}); \ No newline at end of file + + it('trusts an explicit CHROME_PATH as documented', async () => { + vi.stubEnv('CHROME_PATH', '/custom/chrome'); + await expect(ensureChrome('/nonexistent/chrome-binary', true)).resolves.toBe('ok'); + }); +}); + +/* -------------------------------------------------------------------- live-check */ + +describe('D-13: live-check session cookie extraction', () => { + it('returns the cookie pair from a Set-Cookie header', () => { + const response = new Response('{}', { headers: { 'set-cookie': 'okr_session=abc123; HttpOnly; Path=/' } }); + expect(extractSessionCookie(response)).toBe('okr_session=abc123'); + }); + + it('fails with an actionable error instead of a TypeError when Set-Cookie is absent', () => { + const response = new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + let message = ''; + try { + extractSessionCookie(response, 'login'); + } catch (error) { + message = error instanceof Error ? error.message : String(error); + } + expect(message).toContain('login → 200'); + expect(message).toContain('without a Set-Cookie header'); + expect(message).toContain('content-type'); + }); + + it('redacts a malformed cookie value', () => { + const response = new Response('{}', { headers: { 'set-cookie': 'garbage' } }); + expect(() => extractSessionCookie(response)).toThrow(/malformed Set-Cookie/); + }); +}); + +/* ----------------------------------------------------------------------- verify */ + +describe('D-15: verify stage planning', () => { + it('runs all five CI-mirroring stages in order', () => { + expect(planStages().map((stage) => stage.script)).toEqual(['typecheck', 'test', 'check:docs', 'build', 'test:e2e']); + }); + + it('--fast skips build and e2e', () => { + expect(planStages(true).map((stage) => stage.script)).toEqual(['typecheck', 'test', 'check:docs']); + }); +}); + +/* ------------------------------------------------------------ e2e SSE lifecycle */ + +describe('D-07: e2e SSE readiness (no fixed sleep)', () => { + it('waits for the deterministic initial frame instead of sleeping', () => { + const source = readFileSync(join(process.cwd(), 'scripts/e2e.ts'), 'utf8'); + // The 200 ms listener-attach sleep that raced the SSE registration is gone... + expect(source).not.toContain('Give the SSE listener a moment to attach'); + expect(source).not.toContain('await sleep(200)'); + // ...and both SSE sections wait for the deterministic initial frame. + expect(source).toContain('events.length > 0) markReady()'); + expect(source).toContain("events.join('').includes('event: stats')"); + }); + + it('still asserts exactly one start/end pair per request', () => { + const source = readFileSync(join(process.cwd(), 'scripts/e2e.ts'), 'utf8'); + expect(source).toContain("assert(starts.length === 1, `expected 1 request:start"); + expect(source).toContain("assert(ends.length === 1, `expected 1 request:end"); + }); +}); + +/* ---------------------------------------------------------------- CI workflow */ + +describe('D-01/D-02/D-14: CI workflow wiring', () => { + const workflow = (): string => readFileSync(join(process.cwd(), '.github/workflows/ci.yml'), 'utf8'); + + it('never renames the required branch-protection job names', () => { + const text = workflow(); + for (const name of ['Commit messages', 'Lint & test', 'Build & e2e']) { + expect(text).toContain(`name: ${name}`); + } + }); + + it('uses --single on an all-zero push fallback instead of linting nothing', () => { + const text = workflow(); + expect(text).toContain('--single "$HEAD_SHA"'); + // The fallback must never call the linter with no arguments (the empty-range bug). + expect(text).not.toMatch(/check-commit-messages\.mjs\s*$/m); + }); + + it('passes DATA_DIR (and a temp WEB_DIST_DIR) to the dist smoke test', () => { + const text = workflow(); + expect(text).toContain('DATA_DIR="$(mktemp -d)"'); + expect(text).toContain('DATA_DIR="$DATA_DIR"'); + // The computed variable must be consumed on the server line, not left unused. + // The env assignments sit on the preceding (line-continued) shell line. + const lines = text.split('\n'); + const serverLine = lines.findIndex((line) => line.includes('node dist/src/index.js')); + expect(serverLine).toBeGreaterThan(0); + expect(lines[serverLine - 1]).toContain('DATA_DIR="$DATA_DIR"'); + expect(lines[serverLine - 1]).toContain('WEB_DIST_DIR="$WEB_DIST_DIR"'); + }); + + it('runs both negative self-tests in the quality job', () => { + const text = workflow(); + expect(text).toContain('tsx scripts/check-docs.ts --self-test'); + expect(text).toContain('node scripts/check-commit-messages.mjs --self-test'); + }); + + it('does not add a browser/Chrome CI job (explicitly deferred)', () => { + expect(workflow()).not.toMatch(/chrome|screenshots/i); + }); +}); diff --git a/tests/util-errors.test.ts b/tests/util-errors.test.ts new file mode 100644 index 0000000..af88f93 --- /dev/null +++ b/tests/util-errors.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import { + ApiError, + MAX_ERROR_MESSAGE_LENGTH, + isErrorType, + isRetryableStatus, + sanitizeErrorMessage, + scrubSecrets, + upstreamErrorFrom, +} from '../src/util/errors.js'; + +describe('isRetryableStatus (A-14)', () => { + it('A-14: treats every 5xx as retryable and keeps 408/409/425/429', () => { + for (const status of [500, 501, 502, 505, 507, 508, 510, 511, 599]) { + expect(isRetryableStatus(status), `status ${status}`).toBe(true); + } + expect(isRetryableStatus(408)).toBe(true); + expect(isRetryableStatus(409)).toBe(true); + expect(isRetryableStatus(425)).toBe(true); + expect(isRetryableStatus(429)).toBe(true); + expect(isRetryableStatus(529)).toBe(true); + }); + + it('A-14: keeps client errors and boundary statuses non-retryable', () => { + expect(isRetryableStatus(400)).toBe(false); + expect(isRetryableStatus(404)).toBe(false); + expect(isRetryableStatus(422)).toBe(false); + expect(isRetryableStatus(499)).toBe(false); + expect(isRetryableStatus(399)).toBe(false); + expect(isRetryableStatus(600)).toBe(false); + }); +}); + +describe('type validation (A-05)', () => { + it('A-05: only accepts the documented ErrorType union', () => { + expect(isErrorType('api_error')).toBe(true); + expect(isErrorType('rate_limit_error')).toBe(true); + expect(isErrorType('mystery_type')).toBe(false); + expect(isErrorType(7)).toBe(false); + expect(isErrorType(null)).toBe(false); + }); + + it('A-05: maps an unknown upstream type to api_error instead of casting it', () => { + const error = upstreamErrorFrom( + 400, + JSON.stringify({ type: 'error', error: { type: 'mystery_type', message: 'boom' } }), + 'p1', + ); + expect(error).toBeInstanceOf(ApiError); + expect(error.type).toBe('api_error'); + expect(error.message).toBe('boom'); + + const known = upstreamErrorFrom( + 400, + JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: 'bad' } }), + 'p1', + ); + expect(known.type).toBe('invalid_request_error'); + }); +}); + +describe('message clamping (A-05)', () => { + it('A-05: clamps a 200 kB upstream message to 500 chars after control-character stripping', () => { + const huge = `start${'a'.repeat(200_000)}end`; + const error = upstreamErrorFrom(500, JSON.stringify({ error: { message: huge } }), 'p1'); + expect(error.message.length).toBe(MAX_ERROR_MESSAGE_LENGTH); + expect(error.message.startsWith('start')).toBe(true); + expect(error.message).not.toContain('end'); + }); + + it('A-05: strips control characters from upstream bodies and defaults the message', () => { + const error = upstreamErrorFrom(502, 'line\u0000one\u0007two\nthree', 'p1'); + expect(error.message).toBe('lineonetwothree'); + expect(error.message).not.toMatch(/[\u0000-\u001F\u007F]/); + }); +}); + +describe('scrubSecrets (A-05)', () => { + it('A-05: replaces the configured provider key with [redacted]', () => { + const key = 'sk-live-super-secret-value'; + const text = `provider echoed Authorization: Bearer ${key} and said ${key}`; + const scrubbed = scrubSecrets(text, [key]); + expect(scrubbed).not.toContain(key); + expect(scrubbed).toContain('[redacted]'); + }); + + it('A-05: redacts credential-shaped tokens even without a configured secret', () => { + const scrubbed = scrubSecrets( + 'Bearer abcdef123456 sk-proj-abcdef123456 x-api-key: sk-other-123456 authorization=Bearer%20tok', + ); + expect(scrubbed).not.toContain('abcdef123456'); + expect(scrubbed).not.toContain('sk-proj-abcdef123456'); + expect(scrubbed).not.toContain('sk-other-123456'); + expect(scrubbed).toContain('[redacted]'); + }); + + it('A-05: sanitizeErrorMessage scrubs before clamping so a key cannot survive the cut', () => { + const key = 'sk-secret-that-sits-right-at-the-boundary'; + const text = `${'b'.repeat(MAX_ERROR_MESSAGE_LENGTH - 10)}${key}`; + const sanitized = sanitizeErrorMessage(text, [key]); + expect(sanitized.length).toBeLessThanOrEqual(MAX_ERROR_MESSAGE_LENGTH); + expect(sanitized).not.toContain(key); + expect(sanitized).not.toContain('sk-secret'); + }); + + it('A-05: upstreamErrorFrom scrubs the configured key from JSON and plain-text bodies', () => { + const key = 'sk-provider-9f8e7d6c'; + const json = upstreamErrorFrom( + 500, + JSON.stringify({ error: { message: `upstream rejected key ${key}` } }), + 'p1', + [key], + ); + expect(json.message).not.toContain(key); + expect(json.message).toContain('[redacted]'); + + const plain = upstreamErrorFrom(500, `raw body with ${key}`, 'p1', [key]); + expect(plain.message).not.toContain(key); + + const anthropic = upstreamErrorFrom( + 500, + JSON.stringify({ type: 'error', error: { type: 'overloaded_error', message: `key ${key}` } }), + 'p1', + [key], + ); + expect(anthropic.type).toBe('overloaded_error'); + expect(anthropic.message).not.toContain(key); + }); +}); \ No newline at end of file diff --git a/tests/util-upstream.test.ts b/tests/util-upstream.test.ts index ee18f41..925f1a8 100644 --- a/tests/util-upstream.test.ts +++ b/tests/util-upstream.test.ts @@ -48,6 +48,66 @@ describe('joinUrl', () => { expect(joinUrl('https://x.example/v1/', 'chat/completions')).toBe('https://x.example/v1/chat/completions'); expect(joinUrl('https://x.example', '/v1/models')).toBe('https://x.example/v1/models'); }); + + it('A-08: keeps a base query string and appends a path query with &', () => { + expect(joinUrl('https://host/v1?key=x', '/messages')).toBe('https://host/v1/messages?key=x'); + expect(joinUrl('https://host/v1?key=x', '/messages?beta=true')).toBe( + 'https://host/v1/messages?beta=true&key=x', + ); + expect(joinUrl('https://host/v1?', '/messages')).toBe('https://host/v1/messages'); + expect(joinUrl('https://host', '/messages?beta=true')).toBe('https://host/messages?beta=true'); + }); +}); + +describe('provider credential validation (A-10)', () => { + it('A-10: fails with a fixed 502 that never embeds an invalid key', async () => { + const hits: string[] = []; + const server = await listen((req, res) => { + hits.push(req.url ?? ''); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + const key = 'sk-bad\u0001key'; + const error = await upstreamFetch({ + baseUrl: server.base, + apiKey: key, + path: '/chat/completions', + body: { model: 'm' }, + timeoutMs: 2_000, + }).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(ApiError); + expect((error as ApiError).status).toBe(502); + expect((error as ApiError).code).toBe('invalid_provider_credentials'); + expect((error as ApiError).message).toBe('Provider credentials are invalid'); + expect((error as ApiError).message).not.toContain('sk-bad'); + expect((error as ApiError).message).not.toContain('\u0001'); + // The malformed credential never reached the network. + expect(hits).toEqual([]); + }); + + it('A-10: strips CR/LF/NUL from the key before building the auth headers', async () => { + let captured: IncomingMessage['headers'] | null = null; + const server = await listen((req, res) => { + captured = req.headers; + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{}'); + }); + const response = await upstreamFetch({ + baseUrl: server.base, + apiKey: 'sk-abc\r\nx-injected: 1\0', + path: '/chat/completions', + body: { model: 'm' }, + timeoutMs: 2_000, + }); + await response.response.text(); + response.dispose(); + + expect(captured).not.toBeNull(); + expect(captured!['x-injected']).toBeUndefined(); + expect(captured!['authorization']).toBe('Bearer sk-abcx-injected: 1'); + expect(captured!['x-api-key']).toBe('sk-abcx-injected: 1'); + }); }); describe('upstreamFetch redirects', () => { diff --git a/tests/web-a11y.test.ts b/tests/web-a11y.test.ts new file mode 100644 index 0000000..4e9f5cc --- /dev/null +++ b/tests/web-a11y.test.ts @@ -0,0 +1,172 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { fieldAriaIds, mergeDescribedBy } from '../web/src/lib/field-aria.js'; + +const webRoot = new URL('../web/src/', import.meta.url); +const stylesCss = readFileSync(fileURLToPath(new URL('styles.css', webRoot)), 'utf8'); +const inputSource = readFileSync(fileURLToPath(new URL('components/ui/Input.tsx', webRoot)), 'utf8'); +const miscSource = readFileSync(fileURLToPath(new URL('components/ui/misc.tsx', webRoot)), 'utf8'); + +/* ------------------------------------------------------------- CSS helpers */ + +function block(css: string, selector: string): string { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const match = new RegExp(`${escaped}\\s*\\{([\\s\\S]*?)\\n\\}`).exec(css); + if (!match?.[1]) throw new Error(`missing CSS block ${selector}`); + return match[1]; +} + +function token(cssBlock: string, name: string): string { + const match = new RegExp(`--${name}:\\s*([^;]+);`).exec(cssBlock); + if (!match?.[1]) throw new Error(`missing token --${name}`); + return match[1].trim(); +} + +function channel(value: number): number { + const srgb = value / 255; + return srgb <= 0.03928 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4; +} + +function luminance(hex: string): number { + const value = hex.replace('#', ''); + const r = Number.parseInt(value.slice(0, 2), 16); + const g = Number.parseInt(value.slice(2, 4), 16); + const b = Number.parseInt(value.slice(4, 6), 16); + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); +} + +/** WCAG 2.x contrast ratio between two opaque `#rrggbb` colours. */ +function contrastRatio(foreground: string, background: string): number { + const a = luminance(foreground); + const b = luminance(background); + const [hi, lo] = a >= b ? [a, b] : [b, a]; + return (hi + 0.05) / (lo + 0.05); +} + +const light = block(stylesCss, ':root'); +const dark = block(stylesCss, '.dark'); + +/* ------------------------------------------------------------------- tests */ + +describe('C-07 focus ring contrast', () => { + it('C-07: the ring clears the 3:1 non-text minimum on both surfaces', () => { + for (const [theme, tokens] of [ + ['light', light], + ['dark', dark], + ] as const) { + const ring = token(tokens, 'ring'); + expect(ring.startsWith('#'), `${theme} --ring must be an opaque hex colour`).toBe(true); + expect(contrastRatio(ring, token(tokens, 'bg')), `${theme} ring on --bg`).toBeGreaterThanOrEqual(3); + expect(contrastRatio(ring, token(tokens, 'bg-2')), `${theme} ring on --bg-2`).toBeGreaterThanOrEqual(3); + } + }); + + it('C-07: fields keep a keyboard focus indicator (no suppressed outline)', () => { + expect(block(stylesCss, '.input,\n.select,\n.textarea')).not.toContain('outline: none'); + const focusVisible = /\.input:focus-visible,\s*\n\.select:focus-visible,\s*\n\.textarea:focus-visible\s*\{([\s\S]*?)\n\}/.exec( + stylesCss, + ); + expect(focusVisible?.[1]).toContain('outline: 2px solid var(--ring)'); + expect(focusVisible?.[1]).toContain('outline-offset: 1px'); + }); +}); + +describe('C-16 subtle text contrast', () => { + it('C-16: --fg-subtle meets AA (4.5:1) on both surfaces in both themes', () => { + for (const [theme, tokens] of [ + ['light', light], + ['dark', dark], + ] as const) { + const subtle = token(tokens, 'fg-subtle'); + expect(contrastRatio(subtle, token(tokens, 'bg')), `${theme} subtle on --bg`).toBeGreaterThanOrEqual(4.5); + expect(contrastRatio(subtle, token(tokens, 'bg-2')), `${theme} subtle on --bg-2`).toBeGreaterThanOrEqual(4.5); + } + }); + + it('C-16: the hierarchy is preserved (muted stays stronger than subtle)', () => { + expect(contrastRatio(token(light, 'fg-muted'), token(light, 'bg'))).toBeGreaterThan( + contrastRatio(token(light, 'fg-subtle'), token(light, 'bg')), + ); + expect(contrastRatio(token(dark, 'fg-muted'), token(dark, 'bg'))).toBeGreaterThan( + contrastRatio(token(dark, 'fg-subtle'), token(dark, 'bg')), + ); + }); +}); + +describe('C-08 field aria wiring', () => { + it('C-08: an invalid field references its error node', () => { + const aria = fieldAriaIds('log-search', { hasError: true, hasHint: true }); + expect(aria.errorId).toBe('log-search-error'); + expect(aria.hintId).toBe('log-search-hint'); + expect(aria.describedBy).toBe('log-search-error'); + expect(aria.invalid).toBe(true); + }); + + it('C-08: a valid field with a hint describes the hint instead', () => { + const aria = fieldAriaIds('log-search', { hasHint: true }); + expect(aria.describedBy).toBe('log-search-hint'); + expect(aria.invalid).toBe(false); + }); + + it('C-08: a field with neither message describes nothing', () => { + expect(fieldAriaIds('x').describedBy).toBeUndefined(); + }); + + it('C-08: merging keeps caller ids and never duplicates', () => { + expect(mergeDescribedBy('external', 'field-hint')).toBe('external field-hint'); + expect(mergeDescribedBy(undefined, 'field-error')).toBe('field-error'); + expect(mergeDescribedBy('a a', 'a')).toBe('a'); + expect(mergeDescribedBy(undefined, undefined)).toBeUndefined(); + }); + + it('C-08: Field/controls consume the shared aria mapping', () => { + expect(inputSource).toContain('role="alert"'); + expect(inputSource).toContain('id={aria.errorId}'); + expect(inputSource).toContain('id={aria.hintId}'); + for (const component of ['TextInput', 'TextArea', 'Select']) { + expect(inputSource).toContain(`function ${component}(`); + } + expect(inputSource.match(/useControlAria\(/g)?.length ?? 0).toBeGreaterThanOrEqual(3); + }); +}); + +describe('C-09 switch semantics', () => { + const switchSource = /\nexport function Switch\(\{([\s\S]*?)\n\}\n/.exec(inputSource)?.[0] ?? ''; + + it('C-09: the switch is a role="switch" button wired to label and description', () => { + expect(switchSource).toContain('role="switch"'); + expect(switchSource).toContain('aria-checked={checked}'); + expect(switchSource).toContain('aria-labelledby={label ? labelId : undefined}'); + expect(switchSource).toContain('aria-describedby={description ? descriptionId : undefined}'); + }); + + it('C-09: no