diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5b84bde73..ce173f287 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -28,7 +28,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | --- | --- | --- | | Address and caller | `DefaultAddr`. The local token `magpie` and the per-agent `magpie-` (`TokenFor`). `agentOf` tells which agent asked, first by token, then by User-Agent. Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's `X-Anthropic-Surface: operon` (`isClaudeScience`). It is listed every model as `claude-magpie-` (`scienceModels`; its picker keeps only a `claude-` id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (`scienceTurn`, kept in `claude-science.model`). | [`gateway.go`](../../internal/gateway/gateway.go) | | TLS | `--tls-cert`/`--tls-key` (`MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY`) make `ListenAndServe`, `Relisten` (both through `Server.listen`) and `magpie web`'s page (`ServeTLS`) wrap the listener in `tlsListener`. A connection from another computer is `tls.Server` at once, so its plain HTTP gets net/http's 400. One from this computer (`fromThisComputer`: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (`sniffWait`), and 0x16 makes it TLS, so `URL()`, the agents, MCP servers, `ServedBy` and the healthcheck keep `http://127.0.0.1`. `certFiles.get` reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). `tlsConfig` refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). `Scheme()` gives the scheme of `LANURLs`, a scheme-less `MAGPIE_PUBLIC_URL` and the page's network links. Host and Origin checks (`foreignPage`, `rebound`) don't depend on the scheme. | [`tls.go`](../../internal/gateway/tls.go), [`lan.go`](../../internal/gateway/lan.go) | -| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost`, `*.localhost`, a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | +| HTTP surface | `Handler` routes `/v1/chat/completions`, `/v1/responses`, `/v1/messages` (each also without `/v1`), `/v1/models`, Gemini's `/v1beta/models/…`, the Codex backend path, `/v1/codex/models` (Codex's catalog shape for a Codex elsewhere with a gateway key, `codexCatalog`, kept to the key's models by `keyAllowed`; #1281), `/mcp/{name}`, `/mcp/magpie/web-search` and `/mcp/magpie/vision` (magpie's own web search and image recognition as MCP servers, below) and the `/v1/magpie/*` status endpoints. `/v1/alpha/search` (also without `/v1`, and on the Codex backend path for a magpie model) is Codex's web.run search (`alphaSearch`, `codex_search.go`): a ChatGPT account's model goes to the ChatGPT backend's `/alpha/search` on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's `search_query` is searched by `webSearch`, and when nothing answers the reason is a 200 with `output`, since Codex ends the turn on any failed web.run (anton on Discord). A GET on `/v1/responses` (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in `counted`, `corsGuard`, `callerGuard`, `withCaller` and `keyLimited`; `/v1/messages`, `/messages` and `/v1/messages/count_tokens` in `keepsSignIn` too. `corsGuard` (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (`settings.CORSOrigins`, cleaned to `scheme://host[:port]` by `settings.CleanOrigins`, which refuses a wildcard). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: `chrome-extension://` (Chromium, the id 32 letters a–p), `moz-extension://` (Firefox, the Internal UUID about:debugging shows, not the add-on id) and `safari-web-extension://` (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. For a listed origin it answers the preflight (204) and adds `Access-Control-Allow-Origin`, and every other request from it needs an enabled gateway key (`access.Authenticate`), even on loopback, or gets a 401. It takes the key from the caller `lanGuard` recorded too, since on the running server `lanGuard` has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (`foreignPage`): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" `text/plain` POST and spend their subscriptions blind. Only an `http`/`https` Origin is judged, and one on this computer (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) or the request's own origin (its host and port equal to `Host`, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on `/v1/magpie/omarchy`. Other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before; `null` is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (`localhostSubdomain`, #2256) needs a key the same way: Chrome and Firefox resolve `*.localhost` to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. `tauri.localhost` and `wails.localhost` stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use `tauri://` and `wails://`. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so `lanGuard` refuses it first (`rebound`, 403): a loopback request carrying a browser's marks (`Origin`, `Sec-Fetch-Site`/`Sec-Fetch-Mode`, a `Mozilla/` user agent) whose `Host` isn't this computer's (an IP, `localhost` but not a subdomain of it, which WebKit asks the DNS for (#2256), a container runtime's name for the host such as `host.docker.internal`, `MAGPIE_PUBLIC_URL`'s or `MAGPIE_ADDR`'s host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, `lanGuard` lets in one request without a key from anywhere: `POST /_magpie/claude-mcp/` with the token of a Claude subscription run now live (`ownCallback`, see [the Claude subscription bridge](claude-subscription-bridge.md)), the run's MCP helper calling back to a `MAGPIE_ADDR` that isn't loopback (#1546). Next, before the key or `rebound` is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with `MAGPIE_ALLOW_IPS` or Settings › Network › Allowed addresses (`settings.AllowIPs`; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (`RemoteAddr`, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (`refuseNotAllowed`). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with `settings.LoadChecked`: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (`lastAllow`), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with `LoadChecked` too and refuse such a file, as `settings.Save` does. `magpie web`'s server is wrapped in the same check (`AllowGuard`). Settings refuses a list that would leave out the address the page saving it is open from (`KeepsOut`); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (`allowSays`, Mathresearcher on Discord). | [`gateway.go`](../../internal/gateway/gateway.go), [`allow.go`](../../internal/gateway/allow.go), [`internal/settings/allowips.go`](../../internal/settings/allowips.go), [`cors.go`](../../internal/gateway/cors.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`internal/settings/origins.go`](../../internal/settings/origins.go) | | Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight` (`weightedFirst`). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `wrrMove`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/provider/routing.go`](../../internal/provider/routing.go) | diff --git a/internal/gateway/cors.go b/internal/gateway/cors.go index 6bb41166b..75a7b932e 100644 --- a/internal/gateway/cors.go +++ b/internal/gateway/cors.go @@ -5,6 +5,7 @@ import ( "net" "net/http" "net/url" + "runtime" "slices" "strings" @@ -36,6 +37,10 @@ import ( // app's webview send it as well). A key, as for a listed origin, still // lets such a client through; neither gets CORS headers, so a frame or a // local page still sends blind, as before. +// +// So is a page at a subdomain of localhost (localhostSubdomain, #2256): +// Safari and other WebKit views ask the DNS for such a name, and a +// resolver that answers it serves the page from anywhere. func corsGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") @@ -50,6 +55,11 @@ func corsGuard(next http.Handler) http.Handler { writeError(w, provider.Chat, http.StatusForbidden, "magpie doesn't answer a sandboxed frame or a local page (Origin: null) without a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") return } + if localhostSubdomain(origin) && !keyedCaller(r) { + log.Printf("refused %s %s from the web page %s: a localhost subdomain, with no gateway key", r.Method, r.URL.Path, origin) + writeError(w, provider.Chat, http.StatusForbidden, "magpie doesn't answer the web page "+origin+" without a gateway key: Safari and other WebKit browsers ask the network's DNS for a localhost subdomain, so the page may not be on this computer. Open it at localhost or 127.0.0.1, or create a key in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") + return + } next.ServeHTTP(w, r) return } @@ -102,10 +112,9 @@ func keyedCaller(r *http.Request) bool { // off, an extension holding host permissions), and no ordinary web page // can put one on a request, so those pass as before. "null" is not one of // them: any web page sends it from a sandboxed frame and a local file -// sends it too, which corsGuard judges (a gateway key, or 403). *.localhost -// counts as this computer: browsers resolve it to loopback, and Tauri's -// and Wails' webviews on Windows are http://tauri.localhost and -// http://wails.localhost, whose HTTP plugins send that Origin outside CORS. +// sends it too, which corsGuard judges (a gateway key, or 403). A +// subdomain of localhost isn't foreign here either, but corsGuard asks a +// gateway key of it (localhostSubdomain). func foreignPage(r *http.Request, origin string) bool { if origin == "" { return false @@ -135,6 +144,40 @@ func foreignPage(r *http.Request, origin string) bool { return true } +// webviewOS is the system magpie runs on, which localhostSubdomain asks; +// a variable so a test can be each. +var webviewOS = runtime.GOOS + +// localhostSubdomain: origin is an http(s) page at a subdomain of +// localhost (#2256, ggbdpq), which may not be on this computer. Chrome and +// Firefox resolve *.localhost to loopback by a rule of their own, but +// Safari and other WebKit views hand the name to the system resolver, and +// before macOS 26 that asks the network's DNS (WebKit bug 160504, closed +// when macOS 26 resolved it below WebKit; WebKitGTK asks whatever the +// system's resolver is). A resolver that answers — a captive portal's, a +// hostile network's — serves the page from anywhere, and it would send the +// "simple" POST Origin "null" was refused for (#2242). The request doesn't +// say which browser resolved the name, so every such page is held to a +// key. tauri.localhost and wails.localhost on Windows are left out: Tauri's +// and Wails' webviews there serve themselves at those names and their HTTP +// plugins send that Origin outside CORS, and no browser on Windows asks the +// DNS for them. On macOS and Linux those apps use tauri:// and wails://, so +// the two names are any page's there. +func localhostSubdomain(origin string) bool { + u, err := url.Parse(origin) + if err != nil { + return false + } + if s := strings.ToLower(u.Scheme); s != "http" && s != "https" { + return false + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + if !strings.HasSuffix(host, ".localhost") { + return false + } + return webviewOS != "windows" || host != "tauri.localhost" && host != "wails.localhost" +} + // hostPort is host[:port] lower-cased with the scheme's port filled in, so // https://a.example and a Host of a.example:443 compare equal. func hostPort(hp, scheme string) string { diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index 0a6c22ea0..49d89d274 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -276,7 +276,7 @@ func TestForeignPagesRefused(t *testing.T) { {"http://localhost:5173", "127.0.0.1:3425", loop, ""}, // a page on this computer {"http://127.0.0.2:8080", "127.0.0.1:3425", loop, ""}, // 127.0.0.0/8 {"http://[::1]:3000", "[::1]:3425", "[::1]:50123", ""}, // IPv6 loopback - {"http://tauri.localhost", "127.0.0.1:3425", loop, ""}, // Tauri's webview on Windows + {"http://tauri.localhost", "127.0.0.1:3425", loop, secret}, // a localhost subdomain, with a key (keyless on Windows: TestLocalhostSubdomainNeedsAKey) {"https://app.example.com", "127.0.0.1:3425", loop, secret}, // listed, with its key {"http://192.168.1.5:3425", "192.168.1.5:3425", "192.168.1.9:50123", secret}, // the gateway's own origin, shared on the LAN {"https://magpie.example.com", "magpie.example.com", loop, secret}, // its own origin behind a port-443 name, with a key (without one, a rebound page: TestReboundPageRefused) @@ -383,6 +383,135 @@ func TestOpaqueOriginNeedsAKey(t *testing.T) { } } +// A page at a subdomain of localhost (#2256, ggbdpq) is not this +// computer's in every browser: Chrome and Firefox resolve *.localhost to +// loopback by a rule of their own, but Safari and other WebKit views ask +// the system resolver, which before macOS 26 asks the network's DNS (WebKit +// bug 160504, closed when macOS 26 resolved it below WebKit). A resolver +// that answers such a name — a captive portal's, a hostile network's — +// serves the page from anywhere, and it then reaches the gateway two ways: +// cross-origin from http://evil.localhost with a "simple" text/plain POST, +// and rebound, at http://evil.localhost:3425 itself once the name turns to +// 127.0.0.1, where its GET carries no Origin. Both are held to an enabled +// gateway key, as Origin "null" is (#2242). localhost itself, which the +// system answers from its hosts file, is unchanged, and so are +// tauri.localhost and wails.localhost on Windows, where Tauri's and +// Wails' webviews serve themselves and no browser asks the DNS for them. +func TestLocalhostSubdomainNeedsAKey(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_PUBLIC_URL", "") + var hits atomic.Int64 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + secret, err := access.Update("add-key", access.Change{Name: "Local page"}) + if err != nil { + t.Fatal(err) + } + // what Safari sends: a "simple" POST, so no preflight comes first + do := func(method, path, host, origin, key string) *httptest.ResponseRecorder { + t.Helper() + var body io.Reader + if method == "POST" { + body = strings.NewReader(chatReq) + } + r := httptest.NewRequest(method, path, body) + r.RemoteAddr = "127.0.0.1:50123" + r.Host = host + site := "same-origin" + if origin != "" { + r.Header.Set("Origin", origin) + site = "cross-site" + } + r.Header.Set("Sec-Fetch-Site", site) + r.Header.Set("Sec-Fetch-Mode", "no-cors") + r.Header.Set("Content-Type", "text/plain;charset=UTF-8") + r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15") + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + w := httptest.NewRecorder() + lanGuard(New().Handler()).ServeHTTP(w, r) + return w + } + routes := []struct{ method, path string }{ + {"POST", "/v1/chat/completions"}, + {"POST", "/v1/messages"}, + {"POST", "/v1/responses"}, + {"POST", "/v1/embeddings"}, + {"GET", "/v1/models"}, + {"GET", "/v1/magpie/quotas"}, + } + const gw = "127.0.0.1:3425" + for _, os := range []string{"darwin", "linux", "windows"} { + t.Run(os, func(t *testing.T) { + was := webviewOS + webviewOS = os + t.Cleanup(func() { webviewOS = was }) + hits.Store(0) + // cross-origin, from a page at any subdomain; on macOS and + // Linux the two webview names too, which a hostile resolver + // answers as readily + pages := []string{"http://evil.localhost", "http://evil.localhost:8080", "HTTP://Free-Gift.LOCALHOST", "http://a.b.localhost"} + if os != "windows" { + pages = append(pages, "http://tauri.localhost", "http://wails.localhost") + } + for _, o := range pages { + for _, p := range routes { + if w := do(p.method, p.path, gw, o, ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "gateway key") || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("%s %s from %s with no key: %d %s", p.method, p.path, o, w.Code, w.Body) + } + } + } + // rebound: the page's own name turned to 127.0.0.1, its GET + // with no Origin and its POST with its own + for _, p := range routes { + o := "" + if p.method == "POST" { + o = "http://evil.localhost:3425" + } + if w := do(p.method, p.path, "evil.localhost:3425", o, ""); w.Code != http.StatusForbidden { + t.Errorf("%s %s rebound at evil.localhost with no key: %d %s", p.method, p.path, w.Code, w.Body) + } + } + if n := hits.Load(); n != 0 { + t.Fatalf("a localhost subdomain with no key reached the vendor %d times", n) + } + // with an enabled key it is answered, both ways, and reads + // nothing more (no CORS headers) + if w := do("POST", "/v1/chat/completions", gw, "http://evil.localhost", secret); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "ok") || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("cross-origin with its key: %d %s", w.Code, w.Body) + } + if w := do("GET", "/v1/models", "evil.localhost:3425", "", secret); w.Code != http.StatusOK { + t.Errorf("rebound with its key: %d %s", w.Code, w.Body) + } + // answered as before: a page at localhost itself, and the two + // webviews on Windows + keyless := []string{"http://localhost:5173", "http://127.0.0.1:8080"} + if os == "windows" { + keyless = append(keyless, "http://tauri.localhost", "http://wails.localhost") + } + for _, o := range keyless { + if w := do("POST", "/v1/chat/completions", gw, o, ""); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "ok") { + t.Errorf("%s as before: %d %s", o, w.Code, w.Body) + } + } + for _, host := range []string{"localhost:3425", "LOCALHOST.:3425", "docker.for.mac.localhost:3425"} { + if w := do("GET", "/v1/models", host, "", ""); w.Code != http.StatusOK { + t.Errorf("a browser at %s: %d %s", host, w.Code, w.Body) + } + } + }) + } +} + // A browser extension the user listed by its origin (#1051, SkyAerope on // Discord: an extension such as Sider, without host permissions, is held // to CORS like a page) is treated as a listed web page is, no more: its diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index a68317431..7d09c0f1a 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -364,13 +364,15 @@ func fromBrowser(r *http.Request) bool { var containerHostNames = []string{"host.docker.internal", "gateway.docker.internal", "host.containers.internal", "host.orb.internal", "docker.for.mac.localhost"} // ownHost: host (a Host header) names this computer — an IP, localhost, -// *.localhost, or one of the names above. +// or one of the names above. A subdomain of localhost doesn't (#2256): +// Safari and other WebKit views ask the DNS for it, so a page served at +// one from anywhere can have it turned to 127.0.0.1 after it loads. func ownHost(host string) bool { if h, _, err := net.SplitHostPort(host); err == nil { host = h } host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".") - if host == "" || net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") || slices.Contains(containerHostNames, host) { + if host == "" || net.ParseIP(host) != nil || host == "localhost" || slices.Contains(containerHostNames, host) { return true } if strings.EqualFold(host, PublicHost()) { diff --git a/internal/gateway/lan_rebind_test.go b/internal/gateway/lan_rebind_test.go index 02bec2e52..8e59ea8a4 100644 --- a/internal/gateway/lan_rebind_test.go +++ b/internal/gateway/lan_rebind_test.go @@ -47,11 +47,15 @@ func TestReboundPageRefused(t *testing.T) { if c := call("GET", evil, "User-Agent", "Mozilla/5.0 (Macintosh) Safari/605"); c != http.StatusForbidden || reached { t.Fatal("an older browser:", c) } - for _, host := range []string{"127.0.0.1:3425", "localhost:3425", "[::1]:3425", "wails.localhost", "host.docker.internal:3425", "LOCALHOST.:3425"} { + for _, host := range []string{"127.0.0.1:3425", "localhost:3425", "[::1]:3425", "host.docker.internal:3425", "LOCALHOST.:3425"} { if c := call("GET", host, chrome...); c != 200 || !reached { t.Fatal("a browser at", host, c) } } + // a subdomain of localhost is a name Safari asks the DNS for (#2256) + if c := call("GET", "wails.localhost", chrome...); c != http.StatusForbidden || reached { + t.Fatal("a browser at a localhost subdomain:", c) + } // an agent sends no browser marks, whatever name it was given if c := call("POST", evil, "Authorization", "Bearer magpie", "User-Agent", "claude-cli/2.1"); c != 200 || !reached { t.Fatal("an agent:", c)