Skip to content

feat(server): make CORS configuration configurable - #484

Merged
dubadub merged 21 commits into
mainfrom
feat/configurable-cors
Sep 4, 2026
Merged

dubadub merged 21 commits into
mainfrom
feat/configurable-cors

Conversation

@dubadub

@dubadub dubadub commented Sep 3, 2026

Copy link
Copy Markdown
Member

Closes #465.

cook server applied one hardcoded CORS policy that was wrong in both directions: too permissive (any page could reach the mutating routes of a --host-exposed server) and too restrictive (allow_headers was never set, so a cross-origin JSON POST failed preflight and legitimate integrations had to patch the binary).

What changed

  • --cors-origin <ORIGIN> — repeatable; * for any origin, the default.
  • --cors-allow-credentials — requires explicit origins; errors against a wildcard.
  • content-type is now always an allowed request header, so cross-origin JSON works.
  • Under a wildcard origin, cross-origin writes are refused with 403. Naming origins with --cors-origin lets those origins write.
  • --no-cors is renamed --no-csrf-check — it gates the same-origin check and never touched the CORS layer. The old spelling still works as a hidden alias.

The part worth reviewing

The obvious implementation — allow_methods([GET]) for a wildcard origin — does not work, and shipping it would have made the default more permissive than the code it replaced.

POST is a CORS-safelisted method, so per the Fetch standard a browser only consults Access-Control-Allow-Methods for methods that are not safelisted. Access-Control-Allow-Methods: GET blocks PUT and DELETE but never POST. Demonstrated in a real browser: a cross-origin page wrote to seed/config/pantry.conf via POST /api/pantry/add. And the only thing blocking cross-origin JSON POST before this PR was the unset allow_headers failing the preflight by accident — which the issue correctly asks us to remove.

So read-only is enforced server-side, by a small write guard, and the CORS headers describe the policy rather than enforce it. The guard, in order:

  1. GET/HEAD/OPTIONS pass.
  2. No Origin header → pass. curl, scripts and every non-browser client send none, and the API has no authentication for them to bypass.
  3. Origin matching the request's Host → pass (same-origin; the web UI's own writes).
  4. Origin in the --cors-origin list → pass.
  5. Otherwise 403.

It reads the real Host header only, never Forwarded / X-Forwarded-Host — an earlier revision used axum-extra's Host extractor, and Origin: http://evil.test plus X-Forwarded-Host: evil.test passed as same-origin (abe2976).

Compatibility

Cross-origin browser writes now need --cors-origin. Same-origin traffic is unaffected, and so is anything that isn't a browser — curl and existing scripts send no Origin and pass by rule 2.

Behind a reverse proxy that rewrites Host, pass the public origin: --cors-origin https://cook.example.com. A proxy that passes Host through unchanged needs no configuration.

A deliberate non-fix

origin_matches_host ignores the scheme, so Origin: https://a.test matches Host: a.test. That is the normal TLS-terminating-proxy case, and rejecting it would break those deployments. The converse reading — an https:// page reaching a plaintext server on port 80 — is blocked by browsers' mixed-content policy. Documented and pinned by a test rather than left implicit.

Testing

24 unit tests in src/server/cors.rs (flag validation, origin parsing, guard rules) and 14 end-to-end tests in tests/cors_test.rs that boot a real server. The cross-origin POST case is tested with a real request, not a preflight: AllowOrigin::any() answers * on every preflight, so the headers alone cannot show whether the write was refused.

Design: docs/superpowers/specs/2026-09-03-server-cors-config-design.md

Follow-up

Re-run cooklang.org's scripts/sync-cli-docs.sh after merge to pick up docs/api.md and docs/server.md.

https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh

Design for #465. Default becomes wildcard origin with
GET-only methods; explicit --cors-origin unlocks POST/PUT/DELETE and
--cors-allow-credentials. content-type is always allowed. The existing
--no-cors flag (a CSRF check, not CORS) is renamed to --no-csrf-check
with a hidden alias.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
tower-http compares the browser's Origin header byte for byte, so a
configured origin differing in case or carrying a path, query, fragment,
userinfo or bad port silently never matches. Reject those at startup
instead of failing invisibly at request time.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
Splitting the port off the first colon broke http://[::1]:3000, which is
what a browser sends when the server is reached over IPv6 — and it made
userinfo report as a bad port. Check the host rules first, then split the
port off the right.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
http://[] and http://:3000 both parsed cleanly and would then never
match anything. Capture the host from both the bracketed and plain
branches and require it to be non-empty.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
The default is now a wildcard origin restricted to GET. Naming explicit
origins unlocks POST/PUT/DELETE, and content-type is always allowed so
cross-origin JSON requests can pass preflight.

Closes #465

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
POST is a CORS-safelisted method, so Access-Control-Allow-Methods: GET
does not stop a cross-origin POST; verified in a real browser. Adding
content-type to allow_headers also removes the accidental protection
today's unset allow_headers provides, making the new default more
permissive than the code it replaces.

Enforce reads-only server-side with a write guard instead, and leave the
CORS headers to describe the policy rather than enforce it.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
ensure_usable_cors_rules runs in Layer::layer, not in the builder chain,
so constructing a CorsLayer never exercised it. Also narrow methods() to
private and drop redundant clap attributes.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
The flag gates same-origin enforcement on modifying requests, not the
CORS layer. --no-cors is kept as a hidden alias so existing invocations
keep working.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
POST is a CORS-safelisted method, so Access-Control-Allow-Methods: GET
never stops a cross-origin POST — the header policy cannot make the
default read-only. Enforce it server-side instead: a mutating request
carrying an Origin must be same-origin or named by --cors-origin.

Requests with no Origin still pass, so curl and existing scripts are
unaffected, and --no-csrf-check skips the guard for proxy setups that
need it.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
The cross-origin POST case needs a real request, not a preflight: a
wildcard origin always answers Access-Control-Allow-Origin: *, so the
headers alone cannot show whether the write was refused.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
axum_extra's Host extractor prefers Forwarded / X-Forwarded-Host, so
`Origin: http://evil.test` plus `X-Forwarded-Host: evil.test` read as
same-origin and the cross-origin write went through. Those headers are
set by whoever is on the other end of a direct connection, so a security
decision must not depend on them.

Not browser-reachable — a page cannot set X-Forwarded-Host without a
preflight, and allow_headers permits only content-type — and a
non-browser client never needed it, since omitting Origin passes by
design. Removed anyway rather than left as a latent hazard. Deployments
behind a proxy that rewrites Host name their public origin with
--cors-origin.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
create_recipe used axum-extra's Host extractor, which prefers
X-Forwarded-Host over the real Host header — the same precedence removed
from the write guard. Share one host_header helper between them, and
treat a duplicated Host header as no host so a raw client cannot choose
which one the check sees.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
Also records why origin_matches_host deliberately ignores the scheme: a
TLS-terminating proxy passing Host through is the normal case for an
https origin, and the converse is blocked by mixed-content policy.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
The fixture had no pantry.conf, so POST /api/pantry/add returned 404
whether or not the guard allowed it, and assert_ne!(403) proved nothing.
Give the fixture a pantry, assert the real status, and pin HOME so a
global config on the developer's machine cannot change the outcome.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
Fourteen tests each boot their own server, so a parallel run spawns more
at once than the suite this pattern came from; 10s was not always enough
on a loaded machine.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
It claimed a wildcard origin allows GET only. The header policy cannot
enforce that -- POST is CORS-safelisted -- so say what actually happens:
cross-origin writes are refused with 403.

Claude-Session: https://claude.ai/code/session_013cPWotrjEY4Jac87e6vHsh
@claude

claude Bot commented Sep 3, 2026

Copy link
Copy Markdown

Review

Overall this is a well-designed, well-tested fix. The core insight — that allow_methods([GET]) cannot block a cross-origin POST because POST is CORS-safelisted, so read-only-by-default has to be enforced server-side rather than via CORS headers — is correct and is a real security fix, not just a config knob. The PR description's framing of "CORS headers describe the policy, a write guard enforces it" matches what's actually implemented in src/server/cors.rs.

Strengths

  • write_guard is applied once, at the top of the whole router (src/server/mod.rs:240-249), wrapping /api/*, the UI routes, and static serving alike. That's much safer than gating individual handlers, where a future new mutating route could easily be added without the check.
  • Host handling is careful and deliberately narrow: host_header() reads the raw Host header only, treats >1 Host header as "no host" (fail closed) rather than picking the first, and explicitly does not consult Forwarded/X-Forwarded-Host — with a regression test (a_forwarded_host_header_cannot_fake_same_origin) pinning the exact bypass (abe2976) that an earlier revision allowed. That's a good instinct — proxy headers are attacker-controlled on a direct connection.
  • The scheme-agnostic origin_matches_host comparison is a documented, intentional trade-off (TLS-terminating proxy case), not an oversight, and it's backed by a test (the_scheme_is_not_compared) plus a comment explaining why the converse direction is safe (mixed-content blocking). Good to see the "deliberate non-fix" written down instead of left implicit.
  • Test coverage is unusually good for this kind of change: the cors_test.rs module doc explicitly explains why a preflight-only test cannot prove the write guard works (AllowOrigin::any() answers every preflight regardless), so real non-preflight POSTs are used to actually exercise the guard. That's the right level of paranoia for a security-relevant test suite, and it protects future contributors from "simplifying" the tests into something that silently stops testing the thing that matters.
  • Origin parsing (parse_origin) rejects inputs that would silently never match at request time (trailing slash, uppercase, userinfo, malformed IPv6, bad port) rather than accepting them and failing mysteriously later — good defensive validation with tests for both the rejected and accepted shapes.
  • --no-cors → --no-csrf-check rename with a hidden alias is a nice example of fixing a misleading name without a breaking change.

Things worth a second look

  1. --no-csrf-check disables more than its name/help text's primary framing suggests. The flag's doc comment says "Disable same-origin enforcement on requests that modify recipes," which is accurate, but it also fully disables the new cross-origin write guard for the JSON API (not just the POST /new form CSRF check it originally gated). That's intentional and documented in docs/server.md, but since this flag now controls two previously-separate protections (form CSRF and API write-guard) under one switch, it might be worth double-checking that's the desired blast radius for anyone reaching for --no-csrf-check only because they're behind a proxy that rewrites Host — they'd also be opening up cross-origin API writes as a side effect, with no way to keep one without the other.

  2. Minor: Origin header duplication isn't checked the way Host is. host_header() explicitly fails closed if a request carries two Host headers, but allows_write() uses headers.get(header::ORIGIN), which silently takes the first of multiple Origin headers if present. Real browsers never send more than one, so this isn't reachable from a browser, but given how much care went into the Host handling it seems like an inconsistency worth a one-line comment (or a match) explaining why Origin doesn't need the same treatment.

  3. parse_origin's scheme validation doesn't require the scheme to start with a letter (RFC 3986 requires ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )), so e.g. 1http://a.test would currently be accepted. Extremely unlikely to matter in practice since no real browser would send such an Origin, but since the whole point of this validation is to catch operator typos before they silently never match, it's a small gap in an otherwise very thorough check.

  4. Large planning artifacts committed under docs/superpowers/ (a 1222-line implementation plan and a 269-line design spec) — I see this matches existing convention in the repo (there are ~20 other files there already), so this isn't a new pattern, just flagging in case it wasn't intentional for this PR to add two more.

Nits

  • The PR touches src/server/ui.rs's validate_same_origin to reuse cors::origin_matches_host, and deliberately keeps a stricter rule there (reject if neither Origin nor Referer is present) than the API's allows_write (missing Origin = pass, assumed non-browser). That's a good distinction given the form-POST vs. JSON-API threat models, but it might be worth a one-line comment at the call site in create_recipe cross-referencing allows_write so a future reader doesn't "fix" the asymmetry by mistake.

No blocking issues found — the write-guard design, the Host-spoofing test, and the honest documentation of trade-offs (mixed scheme matching, --no-csrf-check's scope) give me good confidence in this. Nice work tracking down that allow_methods([GET]) doesn't actually stop POST — that's a subtle enough detail about the Fetch spec that it would have been easy to ship the vulnerable version and believe it was fixed.

🤖 Generated with Claude Code

@dubadub
dubadub merged commit 282eaaa into main Sep 4, 2026
6 checks passed
@dubadub
dubadub deleted the feat/configurable-cors branch September 4, 2026 17:40
LeMyst added a commit that referenced this pull request Sep 30, 2026
)

Without --cors-origin the server answered every GET with
Access-Control-Allow-Origin: *, so any website the user visited could read
a local `cook server`: the whole recipe collection, /api/static, the sync
status and the base path in /preferences. The wildcard has been the
default since the Rust rewrite (11adb04) and was made explicit in
979addf / 26f7bf0 (#484).

- No --cors-origin now means no CORS layer at all. `--cors-origin '*'`
  restores the previous read-only wildcard.
- A new host_guard answers only requests sent to localhost, an IP
  address, or the host of a --cors-origin. A page that rebinds its own
  name to the server is same-origin as far as the browser is concerned
  and its GETs carry no Origin, so Host is the only thing that gives it
  away. #523 already applied this rule to writes; it now covers reads,
  the SSE stream and the websocket too. --no-csrf-check turns it off.
- Help text, docs/server.md, docs/api.md, /api-docs, README and
  docker-compose.yml describe the new behaviour.

Closes #546

Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

server: make CORS configuration configurable

1 participant