Skip to content

fix(api): stop an unusable key header from bypassing server auth - #394

Merged
neuromechanist merged 1 commit into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-393-openai-header-bypass
Sep 17, 2026
Merged

neuromechanist merged 1 commit into
feature/issue-360-epic-anthropic-platformfrom
feature/issue-393-openai-header-bypass

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Closes #393.

The hole

X-OpenAI-API-Key bypassed the server API key requirement on every RequireAuth endpoint (/ask, /chat, ...), left over from when OSA had an OpenAI code path. It does not have one now: resolve_byok resolves only X-Anthropic-API-Key and X-OpenRouter-Key, so the OpenAI header was read for the bypass decision and then dropped, and the request went on to run on the community's key or the platform's.

Confirmed against a running server with REQUIRE_API_AUTH=true before the fix:

Request Status
no key 401
wrong admin key 403
X-OpenAI-API-Key: literally-anything 200
X-OpenRouter-Key: ... 200 (intended)

Anyone who sent that header with any value got answers billed to us.

The fix

The bypass now accepts exactly the two headers resolve_byok understands, and the openai_key_header extractor is gone. That equality is the whole safety argument for having a bypass at all: the header you send is the credential your request runs on, so a junk value fails upstream against your own provider and there is nothing to gain. A header accepted here but dropped afterwards breaks that argument, which is what happened.

Tests

  • The OpenAI header alone now gets 401 (replaces the test that asserted the bug).
  • Both real BYOK headers still bypass, parametrized over ByokCredential.provider so a third provider cannot be added without a bypass test.
  • A signature check pins the set of headers verify_api_key declares to the set of providers ByokCredential allows, so no future header can bypass without something downstream to resolve it, and a resolvable provider cannot be left out of the bypass.
  • verify_admin_api_key is asserted to read no BYOK header at all.

Both new assertions were confirmed to fail with the old code restored, then pass again with the fix.

  • uv run pytest tests/test_api tests/test_frontend -q -> 454 passed
  • uv run ruff check . and ruff format --check . clean

Also

  • Dropped the header from the BYOK table in deploy/DEPLOYMENT_ARCHITECTURE.md, and stated that the two listed headers are the only ones. The CLI example there now leads with an Anthropic key.
  • Corrected the _expected_byok_headers docstring in tests/test_frontend/test_widget_drift.py, which described the old bypass as still present.

X-OpenAI-API-Key bypassed the server API key requirement on every
RequireAuth endpoint, left over from when there was an OpenAI code path.
There is not one now: resolve_byok knows only Anthropic and OpenRouter,
so the header's value was read for the bypass and then dropped, and the
request ran on the community's key or the platform's. Sending the header
with any value at all bought answers on our bill. Confirmed against a
running server before the fix: no key gave 401 and a wrong admin key gave
403, but `X-OpenAI-API-Key: literally-anything` gave 200.

The bypass now accepts exactly the two headers resolve_byok understands,
which is the whole safety argument for having a bypass: the header you
send is the credential your request runs on, so junk fails upstream
against your own provider.

Tested: the OpenAI header alone now gets 401, both real BYOK headers
still bypass, and a signature check pins the set of headers
verify_api_key reads to the set of providers ByokCredential allows, so a
future header cannot bypass without something to resolve it. Both new
assertions were confirmed to fail with the old code in place.
Also drops the header from the BYOK table in deploy/DEPLOYMENT_ARCHITECTURE.md.

Closes #393
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round (pr-review-toolkit, Sonnet) against origin/feature/issue-360-epic-anthropic-platform...HEAD: no critical or important findings.

Independently confirmed by the reviewer, which is the part that mattered here, since removing an accepted header can only break a caller that sent it:

  • Nothing in the repo ever sent X-OpenAI-API-Key. The widget maps only anthropic and openrouter and sends no header for an unknown provider; the Cloudflare worker's CORS list and byokHeaders forward list never carried it; src/cli/client.py sets only the two real headers; no module imports openai_key_header or openai_key.
  • No analogous mismatch elsewhere: verify_admin_api_key and verify_scoped_admin_key read no BYOK header at all, and the pre-existing worker drift test already bars a stale credential-shaped header from the worker lists.
  • Tests run against a real FastAPI app through real dependency injection, no mocks. 19 passed in the two touched test files, 454 across tests/test_api and tests/test_frontend.

One informational note, skipped deliberately: uv run ty check reports unresolved-attribute: Object of type SecurityBase has no attribute name on the .model.name lookups. FastAPI annotates APIKeyHeader.model as the base SecurityBase; the runtime object is an APIKey, which does have name, so this is a third-party annotation gap rather than a defect. The same lookup already existed unchanged at tests/test_frontend/test_widget_drift.py:230, ty is not wired into CI or pre-commit here (only ruff check and ruff format), and the repo currently reports 306 such diagnostics. Adding casts for 6 of them would be inconsistent noise; wiring ty into CI is its own piece of work.

@neuromechanist
neuromechanist merged commit ef6e0f6 into feature/issue-360-epic-anthropic-platform Sep 17, 2026
9 of 12 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-393-openai-header-bypass branch September 17, 2026 17:37
neuromechanist added a commit that referenced this pull request Sep 19, 2026
PR #394's own description says the request ran on 'the community's
key or the platform's', not definitively the platform's key. Match
the ADRs' wording to the source instead of overstating certainty.
neuromechanist added a commit that referenced this pull request Sep 19, 2026
…#414)

* fix: validate ANTHROPIC_WORKSPACE_ID at Settings construction, not first request

* fix: correct stale Phase 2 docstring/comment, enforce cache_ttl on reassignment

* fix: warn on unresolvable bare default_model ids

* fix: warn when default_model_provider will be ignored

* fix: type key_source as Literal at _check_model_cost and AssistantWithMetrics

* fix: fail loud when no OpenRouter API key is available

* fix: scope BYOK auth bypass to endpoints that actually spend the credential

Mirror management (mirrors.py) and session list/get/delete endpoints used
the same RequireAuth dependency as /ask and /chat, whose BYOK bypass is
only safe because those endpoints actually spend the caller-supplied key
against a real LLM. A syntactically-plausible header value on the mirror
or session endpoints granted access with no real credential at all. Both
now use RequireAdminAuth, which has no BYOK bypass.

Also adds construction-time invariant enforcement to ByokCredential and
ProviderChoice, closing a gap where a future caller passing an empty key
would silently run on the platform's key with cost enforcement disabled.

* fix: verify BYOK key reaches the real outbound Anthropic request

test_byok_http.py's two HTTP-boundary tests used respx to mock
api.anthropic.com, but the installed anthropic SDK (1.6.0) vendors its own
isolated httpx fork (httpx2/httpcore2), which respx cannot intercept.
Confirmed by direct testing: the respx route silently never matched and
both tests were making a real network call to api.anthropic.com on every
run, safely (a garbage test key just got a real 401, converted to a 500
by the endpoint's own exception handler, which happened to satisfy the
old, weaker status_code != 403 assertion regardless of whether any
mocking occurred at all).

Rewrites the mock to patch langchain_anthropic's own client-construction
function with an httpx2.MockTransport instead, and asserts the caller's
key actually reaches the mocked request -- closing the gap on the bug
class that already shipped twice (#393/#394): a silent fallback to the
platform's key would have passed every existing assertion.

Also strengthens the equivalent unit-level assertion in
test_anthropic_llm.py's BYOK construction test.

* chore: address remaining nice-to-have findings from the PR #403 review

- Reuse anthropic_key_header/openrouter_key_header's header name in
  /ask and /chat instead of duplicating the literal string.
- Add a two-call regression test for the cache-breakpoint mutation fix,
  more directly mirroring the original bug report.
- Add a regression test proving an empty-string BYOK header does not
  bypass server auth.
- Document the accepted 'mock one layer above the HTTP boundary' pattern
  in .rules/testing_guidelines.md.

* fix(ci): make CI install locked dependencies instead of drifting latest

test.yml and tests.yml both installed dependencies via `pip install`/
`uv pip install --system` with no lockfile, so every CI run re-resolved
versions fresh from pyproject.toml's floor constraints instead of using
uv.lock - unlike deploy/Dockerfile, which correctly uses `uv sync --frozen`.

This silently drifted CI onto fastapi 0.141.1 / starlette 1.6.0 (a major
Starlette version bump) against the locked fastapi 0.128.0 / starlette
0.50.0 that local dev and production actually run. That newer Starlette
breaks route/dependant introspection in a way that made this PR's new
TestEndpointsThatDoNotSpendByokRequireAdminAuth tests see zero registered
routes for /mirrors and /sessions in CI, while passing locally and in a
container with locked versions - reproduced and confirmed both ways.

Switched every install step to `uv sync --frozen --extra dev` (`dev`
already depends on `[server]`, so this pulls in FastAPI etc. too) and the
corresponding run steps to `uv run pytest`/`uv run ruff`, so CI now tests
against the exact versions the lockfile pins and production deploys,
instead of whatever happens to be newest on a given day.

* fix: scope BYOK auth bypass on GET /health/communities

Same vulnerability class as mirrors.py and the session endpoints, missed
in the first pass: this endpoint never spends a BYOK credential against
an LLM (it returns a full per-community diagnostic dump -- API key
status, CORS origin count, document counts, warnings), so RequireAuth's
BYOK bypass let any syntactically-plausible header value read it with no
real credential at all. Switched to RequireAdminAuth.

Also adds a generalized structural test (in addition to a dedicated
health.py case): enumerates every route depending on verify_api_key and
asserts it's exactly /ask and /chat, so a future endpoint added with
RequireAuth by copy-paste fails immediately regardless of its path,
instead of needing a new dedicated test case added after the fact.
neuromechanist added a commit that referenced this pull request Sep 19, 2026
…Records (#409)

* docs: migrate CLAUDE.md content to AGENTS.md

CLAUDE.md is now a thin @AGENTS.md adapter, following the cross-tool
AGENTS.md convention. Also drops the Code Exploration with Serena section
(Serena MCP is no longer carried forward for this project).

* docs: add code_review, self_improve, and ci_cd rule files

Adds the missing pr-review-toolkit, rule-evolution, and CI/CD
reference rules from the plugin template. ci_cd.md is adapted to
describe this repo's actual workflows rather than generic examples.

* docs: fix stale git.md/python.md, merge testing.md improvements

git.md and python.md contradicted actual project conventions (branch
from main, conda/pip/mypy) rather than the real workflow (branch from
develop, UV/ruff/ty). Rewritten to match AGENTS.md and the global
instructions. testing.md gains back a couple of generic template
improvements (JS framework note, CI integration pointer) without
losing the project-specific LLM/exemplar testing section.

* docs: add Architecture Decision Records for existing decisions

Introduces docs/adr/ (MADR format) and backfills nine ADRs for
decisions already made but only documented informally: the
develop/main branch and versioning strategy, the develop-sync and
release-image-race incidents and their fixes, the Anthropic Claude
Platform migration, today's PR-review enforcement, and the original
architecture choices in .context/plan.md and .context/research.md
(LangGraph, no external database, BYOK, Astral tooling).

* fix: correct branch-protection docs to match live ruleset state

ADR 0005 and AGENTS.md described the review requirement as having no
admin bypass, but the user asked for the bypass to be restored after
that version was written, then had a second ruleset added to
close the deletion-protection gap that reintroduced. Rewrite ADR 0005
to document the full history and final live state (verified against
gh api), add the exact re-verification commands, and update AGENTS.md
and code_review.md to match rather than describe a stale intermediate
state.

* fix: correct python.md/ADR 0009 line-length and mypy/ty claims

pyproject.toml sets ruff line-length to 100, not the Black-default 88
these files claimed. The ty-not-mypy rule was stated as settled
practice, but pyproject.toml still depends on and configures mypy and
ty appears nowhere in the repo; reworded both to be honest that this
is the target direction, not the current state, and filed #412 to
track the actual migration.

* fix: stop self_improve.md citing a nonexistent scratch_history.md

.context/scratch_history.md doesn't exist in this repo; point at files
that do (.context/plan.md, .context/research.md) and note it should
be created on first real use instead of treated as an existing
source to mine.

* fix: identify tests.yml, not test.yml, as the merge-gating workflow

test.yml only triggers on push/PR to main and its job names
(Unit Tests (Python X)) don't match the required status check names.
tests.yml's Test job (matrix 3.11/3.12) is what actually produces the
Test (3.11)/Test (3.12) checks both rulesets require, and it's the
only one of the two that runs on a PR into develop. Also corrects the
Python matrix claim: test.yml covers 3.13 too, but that isn't part of
what branch protection checks.

* fix: soften ADR 0004/0008 overstated claim about PR #394's bug

PR #394's own description says the request ran on 'the community's
key or the platform's', not definitively the platform's key. Match
the ADRs' wording to the source instead of overstating certainty.

* chore: remove orphaned .serena/ directory

Serena MCP was dropped from AGENTS.md/.rules/ earlier in this branch;
nothing points at .serena/ anymore, so remove it rather than leave a
directory with no documentation telling anyone to use it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant