gateway: a browser's CORS preflight from another machine is answered, not asked for a key (#4931)
From the report (magpie 0.1.2698, macOS 27.0.1, LAN sharing on, gateway port 3425): a page at https://learn.trancy.org, listed in Settings -> Network and sharing -> Web pages, failed to add itself as a custom engine ("Failed to fetch"). The same OPTIONS preflight for /v1/models, declaring GET and the authorization header with no key on it, was answered 204 with the CORS headers at http://127.0.0.1:3425 and refused 401 with no CORS headers at the machine's LAN address and behind an HTTPS reverse proxy (Nginx Proxy Manager, no CORS handling of its own); the browser logged net::ERR_FAILED, corsError: PreflightMissingAllowOriginHeader, and gave up before the keyed POST. The 401 body was the gateway's own "no API key was sent: send a magpie gateway key as Authorization: Bearer <key> (or x-api-key)". lanGuard sits in front of Handler (Front, oneport.go), and corsGuard is inside Handler, so a request from another machine met the key check first: with the gateway shared (or listening on the network), identifyCaller refused the keyless preflight 401 before corsGuard could see it. On loopback lanGuard asks no key, which is why the same preflight was answered there. A preflight is an OPTIONS that declares the call to come, and per what CORS asks of it carries no key and no body: the browser cannot send one. lanGuard now hands a preflight (corsPreflight: an OPTIONS with an Origin and an Access-Control-Request-Method) to corsGuard instead, after the allow list and the shared/on-network rules have judged it as they judge every request. corsGuard answers a listed origin's with its 204 and headers and refuses any other page's as on loopback; the call the preflight asks after still needs an enabled gateway key, and an OPTIONS that declares no call is no preflight. `magpie web`'s page port, which hands client routes to the same Front, is covered by the same change. Tests (internal/gateway/cors_test.go), from the report's three-row table: - TestCORSPreflightFromLAN: the loopback preflight answered 204 (the row that already worked), the LAN-direct one and the reverse-proxy one (X-Forwarded-For, loopback peer) answered 204 with Allow-Origin and Allow-Headers; an unlisted origin's preflight refused with no CORS headers; a keyless GET and a plain OPTIONS from the LAN still 401; a preflight while magpie isn't shared still refused. Broken by hand (the preflight handoff taken back out of lanGuard): the LAN-direct and reverse-proxy rows go red, 401 with the report's own error body, while the loopback row stays green; restored, ok. Run (macOS arm64, this tree, -tags nogui): - go test -run 'TestCORS|TestLAN|TestForeignPages|TestOpaqueOrigin| TestLocalhostSubdomain|TestRebound|TestOnePort|TestFront' ./internal/gateway: ok. - the same with -race: ok. - go vet ./internal/gateway, and with GOOS=linux and GOOS=windows: ok. - go build . with GOOS=darwin, GOOS=linux and GOOS=windows: ok (the darwin cgo enum-conversion warnings in internal/gui are pre-existing). - gofmt -l on the three touched files: clean. - go test -count=1 -timeout 50m -tags nogui ./internal/gateway: every test ok except TestCodexPoolSaysTheClientsVersion, the known #4807 (another test's Codex identity reaches it in a full package run); it passes run alone at this head. - go test -tags nogui -count=1 ./internal/access ./internal/settings .: ok. ./internal/gui: TestProxyCheckSaysAProxyPassedBy fails, and fails the same way run alone on the untouched basea3768cdd1— this machine's environment, not this change (the test drives checkProxy's ALL_PROXY walk, nothing of the gateway). Not tried: a real Trancy page against a real LAN address and a real Nginx Proxy Manager install; the report's LAN and proxy rows are taken from its measured curl and browser evidence, and reproduced here at the lanGuard/corsGuard seam with httptest instead. A preflight arriving while magpie isn't shared is still refused, so the browser reports the preflight, not the later call, as the failure — the network's rules come first, as the report asks. Review, changed from ggbdpq's patch (security): the patch let every keyless preflight from another computer past lanGuard's key check. corsGuard passes some unlisted origins on with no key (a page on this computer by name or address, *.localhost, the request's own origin, an app's or extension's scheme), and a route that takes OPTIONS (Codex's backend relay, the MCP paths) would then serve such a "preflight" with the user's sign-in. lanGuard now hands on only a preflight whose origin is listed (corsAllowed); every other one meets the key check as before, Origin null included. No request other than an OPTIONS with Origin and Access-Control-Request-Method skips the key: a POST, GET or DELETE carrying a preflight's headers is 401. TestCORSPreflightFromLANReachesNothing (added in review) sends a keyless preflight from the LAN for Codex's relay, an MCP path and /v1/models from localhost, 127.0.0.1, foo.localhost, the request's own origin, an extension, app://, null and a foreign site: none reaches the handler or gets CORS headers. The listed origin's is answered by corsGuard alone, and other methods with its headers are 401. A rebound page never gets here: lanGuard's rebound check runs on loopback first, and from the LAN the key check stands. Broken by hand at the reviewed head: the corsAllowed condition removed, this test red (TestCORSPreflightFromLAN stays green); the whole handoff reverted, both red. Restored, green. Run at the pushed tree (this stack of nine on origin/main3c2dceb34), on mote (macOS arm64, Go 1.26.8): - go test -count=1 -timeout 45m ./internal/catalog/... ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...: catalog, plugin and davsync ok; gateway red on one test only, TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's Codex identity reaches it in a full package run). It passes run alone at this tree, 3 of 3. - go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l on every tracked .go file: clean. - The hand breaks above ran on this stack before its rebase onto3c2dceb34. That commit changed member.go only, nothing these tests reach. Not tried: the GUI suite, since no GUI file changed. Windows and Linux test runs (the Claude bridge tests use a shell fake and skip on Windows). No real vendor, Claude Code or network was used; every case runs against fakes. Generated-by: GLM-5.3-Flash (ZCode)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -67,7 +67,7 @@ func corsGuard(next http.Handler) http.Handler {
|
||||
h.Set("Access-Control-Allow-Origin", origin)
|
||||
h.Add("Access-Control-Expose-Headers", SessionHeader)
|
||||
h.Add("Vary", "Origin")
|
||||
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
if corsPreflight(r) {
|
||||
h.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
if asked := corsHeaders(r.Header.Get("Access-Control-Request-Headers")); asked != "" {
|
||||
h.Set("Access-Control-Allow-Headers", asked)
|
||||
@@ -207,6 +207,15 @@ func corsAllowed(origin string) bool {
|
||||
return err == nil && len(o) == 1 && slices.Contains(list, o[0])
|
||||
}
|
||||
|
||||
// corsPreflight: r is a browser's CORS preflight, an OPTIONS that
|
||||
// declares the actual call to come. A browser puts no key on one —
|
||||
// neither an Origin-headered one on the headers it asks for — which is
|
||||
// why lanGuard passes one to this file's guard before asking for a key
|
||||
// (#4931).
|
||||
func corsPreflight(r *http.Request) bool {
|
||||
return r.Method == http.MethodOptions && r.Header.Get("Origin") != "" && r.Header.Get("Access-Control-Request-Method") != ""
|
||||
}
|
||||
|
||||
// corsHeaders is a preflight's Access-Control-Request-Headers as the
|
||||
// answer allows them: the header names asked for, nothing else.
|
||||
func corsHeaders(asked string) string {
|
||||
|
||||
@@ -614,3 +614,155 @@ func TestCORSExtensionOrigin(t *testing.T) {
|
||||
t.Errorf("another extension: %d %v", w.Code, w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
// A preflight that reaches the gateway from another machine was refused
|
||||
// 401 for the key a preflight may not carry (#4931: the same preflight
|
||||
// for a listed origin was answered 204 on loopback and 401, with no CORS
|
||||
// headers, on the LAN address and behind an HTTPS reverse proxy, whose
|
||||
// forwarding header makes it remote from loopback too — a browser
|
||||
// reports it as PreflightMissingAllowOriginHeader and the page's fetch
|
||||
// fails). lanGuard now hands a preflight to corsGuard, which answers a
|
||||
// listed origin's and refuses any other page's, while the call it asks
|
||||
// after still needs the key, and the network's rules (the allow list,
|
||||
// sharing on the LAN) are judged first, as for every request.
|
||||
func TestCORSPreflightFromLAN(t *testing.T) {
|
||||
fresh(t)
|
||||
s := settings.Load()
|
||||
s.CORSOrigins = []string{"https://learn.trancy.org"}
|
||||
s.LAN = true
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := lanGuard(New().Handler())
|
||||
do := func(remote, host, method, origin, key string, hdr map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, "/v1/models", nil)
|
||||
r.RemoteAddr = remote
|
||||
r.Host = host
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
if key != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+key)
|
||||
}
|
||||
for k, v := range hdr {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
pf := map[string]string{"Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "authorization"}
|
||||
const trancy = "https://learn.trancy.org"
|
||||
const lan = "192.168.1.9:50123"
|
||||
const lanHost = "192.168.1.5:3425"
|
||||
|
||||
// the issue's first row: on loopback the preflight was answered
|
||||
if w := do("127.0.0.1:50123", "127.0.0.1:3425", "OPTIONS", trancy, "", pf); w.Code != http.StatusNoContent ||
|
||||
w.Header().Get("Access-Control-Allow-Origin") != trancy || w.Header().Get("Access-Control-Allow-Headers") != "authorization" {
|
||||
t.Errorf("loopback preflight: %d %v", w.Code, w.Header())
|
||||
}
|
||||
// direct on the LAN: was 401, with no CORS headers
|
||||
if w := do(lan, lanHost, "OPTIONS", trancy, "", pf); w.Code != http.StatusNoContent ||
|
||||
w.Header().Get("Access-Control-Allow-Origin") != trancy || w.Header().Get("Access-Control-Allow-Headers") != "authorization" {
|
||||
t.Errorf("LAN preflight: %d %v", w.Code, w.Header())
|
||||
}
|
||||
// behind a reverse proxy that forwards with a header (nginx): was 401
|
||||
if w := do("127.0.0.1:50123", "magpie.example.com", "OPTIONS", trancy, "",
|
||||
map[string]string{"Access-Control-Request-Method": "GET", "Access-Control-Request-Headers": "authorization", "X-Forwarded-For": "203.0.113.7"}); w.Code != http.StatusNoContent ||
|
||||
w.Header().Get("Access-Control-Allow-Origin") != trancy {
|
||||
t.Errorf("proxied preflight: %d %v", w.Code, w.Header())
|
||||
}
|
||||
|
||||
// a page not listed is refused, as on loopback: no 204, no headers
|
||||
if w := do(lan, lanHost, "OPTIONS", "https://evil.example", "", pf); w.Header().Get("Access-Control-Allow-Origin") != "" || w.Code == http.StatusNoContent {
|
||||
t.Errorf("unlisted origin's preflight: %d %v", w.Code, w.Header())
|
||||
}
|
||||
// the call the preflight asks after still needs the key
|
||||
if w := do(lan, lanHost, "GET", trancy, "", nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("keyless call from the LAN: %d", w.Code)
|
||||
}
|
||||
// an OPTIONS that declares no call is no preflight
|
||||
if w := do(lan, lanHost, "OPTIONS", trancy, "", nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("plain OPTIONS from the LAN: %d", w.Code)
|
||||
}
|
||||
// and while magpie isn't shared, the network's rules refuse a
|
||||
// preflight as they refuse everything else from another machine
|
||||
s.LAN = false
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := do(lan, lanHost, "OPTIONS", trancy, "", pf); w.Code == http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != "" {
|
||||
t.Errorf("preflight while not shared: %d %v", w.Code, w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
// A preflight from another machine is let past the key check for a listed
|
||||
// origin alone, and then corsGuard answers it with nothing behind it
|
||||
// reached (#4931). corsGuard passes some unlisted origins on unkeyed (a
|
||||
// page on this computer, the request's own origin, an app's scheme), and
|
||||
// a route that takes OPTIONS (Codex's relay, the MCP paths) would serve
|
||||
// such a "preflight" with no key, so those meet the key check as before;
|
||||
// and no request but a preflight skips it for a preflight's headers.
|
||||
func TestCORSPreflightFromLANReachesNothing(t *testing.T) {
|
||||
fresh(t)
|
||||
s := settings.Load()
|
||||
s.CORSOrigins = []string{"https://learn.trancy.org"}
|
||||
s.LAN = true
|
||||
if err := settings.Save(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var reached []string
|
||||
srv := lanGuard(corsGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reached = append(reached, r.Method+" "+r.URL.Path+" "+r.Header.Get("Origin"))
|
||||
w.WriteHeader(http.StatusTeapot)
|
||||
})))
|
||||
const lan = "192.168.1.9:50123"
|
||||
const lanHost = "192.168.1.5:3425"
|
||||
do := func(method, path, origin string, hdr map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.RemoteAddr = lan
|
||||
r.Host = lanHost
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
for k, v := range hdr {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
srv.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
pf := map[string]string{"Access-Control-Request-Method": "POST", "Access-Control-Request-Headers": "authorization"}
|
||||
for _, path := range []string{CodexPath + "/responses", "/mcp/github", "/v1/models"} {
|
||||
for _, origin := range []string{
|
||||
"http://localhost:5173", // a page on this computer
|
||||
"http://127.0.0.1:8080", // the same, by address
|
||||
"http://foo.localhost", // a localhost subdomain
|
||||
"http://" + lanHost, // the request's own origin
|
||||
"chrome-extension://abcdef", // an extension
|
||||
"app://obsidian.md", // an app's scheme
|
||||
"null", // a sandboxed frame
|
||||
"https://evil.example", // a site elsewhere
|
||||
} {
|
||||
reached = nil
|
||||
w := do(http.MethodOptions, path, origin, pf)
|
||||
if len(reached) > 0 || w.Code == http.StatusNoContent || w.Header().Get("Access-Control-Allow-Origin") != "" {
|
||||
t.Errorf("keyless preflight for %s from %s: %d %v, reached %v", path, origin, w.Code, w.Header(), reached)
|
||||
}
|
||||
}
|
||||
// a listed origin's preflight is answered, by corsGuard alone
|
||||
reached = nil
|
||||
if w := do(http.MethodOptions, path, "https://learn.trancy.org", pf); w.Code != http.StatusNoContent || len(reached) > 0 {
|
||||
t.Errorf("listed preflight for %s: %d, reached %v", path, w.Code, reached)
|
||||
}
|
||||
// a preflight's headers on any other method skip nothing
|
||||
for _, m := range []string{http.MethodPost, http.MethodGet, http.MethodDelete} {
|
||||
reached = nil
|
||||
if w := do(m, path, "https://learn.trancy.org", pf); w.Code != http.StatusUnauthorized || len(reached) > 0 {
|
||||
t.Errorf("keyless %s for %s with a preflight's headers: %d, reached %v", m, path, w.Code, reached)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,6 +368,21 @@ func lanGuard(next http.Handler) http.Handler {
|
||||
http.Error(w, "magpie isn't shared on the local network", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
// a browser's preflight carries no key, and CORS forbids putting
|
||||
// one on it: a listed origin's could never pass the key check
|
||||
// below, so corsGuard, next, answers it (204 and the headers) with
|
||||
// nothing behind it reached, while the call it asks after still
|
||||
// needs the key (#4931: a preflight from another machine, direct on
|
||||
// the LAN or behind a reverse proxy, was refused 401 for the key it
|
||||
// may not carry, and the browser gave up before the keyed call).
|
||||
// Any other origin's meets the key check as before: corsGuard
|
||||
// passes some on (a page on this computer, the request's own
|
||||
// origin, an app's scheme), and a route that takes OPTIONS
|
||||
// (Codex's relay, the MCP paths) would serve it with no key.
|
||||
if remote && corsPreflight(r) && corsAllowed(r.Header.Get("Origin")) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
// the key page itself is the same bytes for everyone, so it is
|
||||
// opened before the key it asks for is typed; its data isn't
|
||||
if remote && keyPageOpen(r) {
|
||||
|
||||
Reference in New Issue
Block a user