diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3ac584ddb..82d365452 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`. `null` and other schemes (`app://`, `file://`, `tauri://`, `vscode-webview://`, `chrome-extension://`) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. 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 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) | | 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/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 11cf14cb2..464eb6b1a 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -317,8 +317,8 @@ however old, so a client's history can be backfilled. - **Who may post:** the GET routes' rule, through the same `lanGuard`: this machine, or another with an enabled gateway key while shared. On top of that a browser page (`fromBrowser`) needs a key wherever it is, - since `corsGuard` lets a localhost page and `Origin: null` through, and - a held key is refused. `TestUsageIngestAccess`. + since `corsGuard` lets a localhost page through keyless (`Origin: null` + needs a key there too, #2242), and a held key is refused. `TestUsageIngestAccess`. - **Writing:** `usage.IngestReported` ([`internal/usage/reported.go`](../../internal/usage/reported.go)) appends under the same mutex and to the same file as `usage.Append`, diff --git a/internal/gateway/cors.go b/internal/gateway/cors.go index 2534501f2..6bb41166b 100644 --- a/internal/gateway/cors.go +++ b/internal/gateway/cors.go @@ -29,6 +29,13 @@ import ( // user merely visits could send a "simple" text/plain POST and spend their // subscriptions blind. Such a page never read a reply before (no CORS // headers), so refusing it breaks nothing that worked. +// +// An Origin of "null" is refused too (403) unless the call carries an +// enabled gateway key: any web page can send it from a sandboxed iframe, +// which is that same "simple" POST one frame away (a file:// page and an +// 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. func corsGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") @@ -38,6 +45,11 @@ func corsGuard(next http.Handler) http.Handler { writeError(w, provider.Chat, http.StatusForbidden, "magpie doesn't answer the web page "+origin+": list it in Settings → Network and sharing → Web pages to let it call magpie with a gateway key") return } + if origin == "null" && !keyedCaller(r) { + log.Printf("refused %s %s from Origin: null: a sandboxed frame or a local page, with no gateway key", r.Method, r.URL.Path) + 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 + } next.ServeHTTP(w, r) return } @@ -60,9 +72,7 @@ func corsGuard(next http.Handler) http.Handler { } // lanGuard, in front of Handler on the real server, has already // taken the key and put magpie's own token in its place - keyed := access.Caller(r.Context()).KeyID != "" || - slices.ContainsFunc(callerKeys(r), func(k string) bool { _, ok := access.Authenticate(k); return ok }) - if !keyed { + if !keyedCaller(r) { writeError(w, provider.Chat, http.StatusUnauthorized, "a web page or browser extension calls magpie with a gateway key: create one in magpie's Gateway page and send it as Authorization: Bearer (or x-api-key)") return } @@ -70,6 +80,14 @@ func corsGuard(next http.Handler) http.Handler { }) } +// keyedCaller: the request carries an enabled gateway key — the caller +// lanGuard recorded, or one in its own headers, which is where a handler +// called without lanGuard finds it (the web app's embedded calls, tests). +func keyedCaller(r *http.Request) bool { + return access.Caller(r.Context()).KeyID != "" || + slices.ContainsFunc(callerKeys(r), func(k string) bool { _, ok := access.Authenticate(k); return ok }) +} + // foreignPage: origin is an http(s) web page that is neither on this // computer (localhost, *.localhost, 127.0.0.0/8, [::1], any port) nor the // request's own origin (a page served at the address the request names, @@ -77,13 +95,14 @@ func corsGuard(next http.Handler) http.Handler { // site elsewhere. usemagpie.ai may still read the Omarchy theme // (omarchyTheme). // -// Only http and https are judged. "null" (a sandboxed frame, a file:// -// page, some Electron renderers) and other schemes — app://, file://, -// tauri://, vscode-webview://, chrome-extension:// — come from desktop -// apps, editor webviews and browser extensions. Such a client could call -// magpie before only because it doesn't enforce CORS (a webview with web -// security off, an extension holding host permissions), and no ordinary -// web page can send those origins, so they pass as before. *.localhost +// Only http and https are judged. A scheme only an app or an extension +// can send — app://, file://, tauri://, vscode-webview://, +// chrome-extension:// — comes from desktop apps, editor webviews and +// browser extensions that don't enforce CORS (a webview with web security +// 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. diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index a7dc84d77..0a6c22ea0 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -177,8 +177,9 @@ func TestCORSKeyThroughTheServer(t *testing.T) { // http(s) origin isn't listed, on this computer or the gateway's own // address is refused on every route before anything reaches a vendor; // pages on this computer, listed ones, the gateway's own origin, agents -// (no Origin) and desktop apps, webviews and extensions (null and -// non-http origins) are answered as before. +// (no Origin) and apps and extensions (non-http schemes) are answered as +// before. Origin "null" is a page's too (TestOpaqueOriginNeedsAKey): a +// key is asked of it, so it is gone from the rows below. func TestForeignPagesRefused(t *testing.T) { fresh(t) var hits atomic.Int64 @@ -260,6 +261,11 @@ func TestForeignPagesRefused(t *testing.T) { if w := do(chat, "https://evil.example", "127.0.0.1:3425", loop, secret); w.Code != http.StatusForbidden { t.Errorf("unlisted page with a key: %d", w.Code) } + // ... nor does one sandboxed frame, whose Origin "null" any page can + // send: it is refused with the others, and asks for a gateway key + if w := do(chat, "null", "127.0.0.1:3425", loop, ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "gateway key") { + t.Errorf("a sandboxed frame with no key: %d %s", w.Code, w.Body) + } if n := hits.Load(); n != 0 { t.Fatalf("a refused page reached the vendor %d times", n) } @@ -274,7 +280,7 @@ func TestForeignPagesRefused(t *testing.T) { {"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) - {"null", "127.0.0.1:3425", loop, ""}, // a sandboxed frame, a file:// page + {"null", "127.0.0.1:3425", loop, secret}, // a sandboxed frame or a file:// page, with its key {"app://cherry", "127.0.0.1:3425", loop, ""}, // an Electron renderer {"file://", "127.0.0.1:3425", loop, ""}, {"tauri://localhost", "127.0.0.1:3425", loop, ""}, @@ -291,6 +297,92 @@ func TestForeignPagesRefused(t *testing.T) { } } +// Origin "null" is not an app's: a sandboxed frame sends it on any web +// page's behalf (a file:// page and some webviews send it too), so one +// iframe on a page the user visits could send the "simple" text/plain +// POST and spend a subscription with no key, which is the case corsGuard +// exists for. It is held to an enabled gateway key, as a listed page is +// Real browsers proved the request and its null Origin arrive with no +// preflight (2026-10-15): a sandboxed frame on a public https page +// reached loopback in WebKit 27.2 — Chromium 156 and Firefox 157 refuse +// the cross-site request themselves (Local Network Access) — and a +// file:// page reached it in all three. A scheme only an app or an +// extension can send is answered as before. +func TestOpaqueOriginNeedsAKey(t *testing.T) { + fresh(t) + 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 a browser sends from a sandboxed frame or an opened file: a + // "simple" POST, so no preflight comes first + do := func(method, path, 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 = "127.0.0.1:3425" + r.Header.Set("Origin", origin) + r.Header.Set("Sec-Fetch-Site", "cross-site") + r.Header.Set("Sec-Fetch-Mode", "no-cors") + r.Header.Set("Sec-Fetch-Dest", "empty") + 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/27.2 Safari/605.1.15") + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + w := httptest.NewRecorder() + lanGuard(New().Handler()).ServeHTTP(w, r) + return w + } + for _, p := range []struct{ method, path string }{ + {"POST", "/v1/chat/completions"}, + {"POST", "/v1/messages"}, + {"POST", "/v1/images/generations"}, + {"POST", "/v1/embeddings"}, + {"GET", "/v1/models"}, + } { + if w := do(p.method, p.path, "null", ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "gateway key") || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("%s %s with no key: %d %v %s", p.method, p.path, w.Code, w.Header(), w.Body) + } + } + if hits.Load() != 0 { + t.Fatalf("a sandboxed frame with no key reached the vendor %d times", hits.Load()) + } + // with an enabled key it is answered as before, and reads nothing + // either way (no CORS headers: only a listed origin the user named + // gets those) + if w := do("POST", "/v1/chat/completions", "null", secret); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "ok") || w.Header().Get("Access-Control-Allow-Origin") != "" || hits.Load() != 1 { + t.Errorf("with its key: %d %v %s", w.Code, w.Header(), w.Body) + } + // a key turned off is no key + keys, _ := access.List() + access.Update("off-key", access.Change{Key: keys[len(keys)-1].ID}) + if w := do("POST", "/v1/chat/completions", "null", secret); w.Code != http.StatusForbidden { + t.Errorf("with a key turned off: %d %s", w.Code, w.Body) + } + access.Update("on-key", access.Change{Key: keys[len(keys)-1].ID}) + // a scheme only that app or extension can send is untouched + for _, o := range []string{"app://cherry", "tauri://localhost", "vscode-webview://1abc", "chrome-extension://abcdefghijklmnop"} { + if w := do("POST", "/v1/chat/completions", o, ""); w.Code != http.StatusOK { + t.Errorf("%s as before: %d %s", o, 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/usage_ingest.go b/internal/gateway/usage_ingest.go index 81881ec79..92dfccd77 100644 --- a/internal/gateway/usage_ingest.go +++ b/internal/gateway/usage_ingest.go @@ -36,8 +36,8 @@ import ( // GET /v1/magpie/usage is: this computer, or another with an enabled // gateway key while magpie is shared. A request with a browser's marks // needs an enabled gateway key even from this computer: corsGuard lets -// a page on localhost or 127.0.0.1 (any port) and an opaque origin -// through, and none of them should be able to write what the page counts. +// a page on localhost or 127.0.0.1 (any port) through keyless, and it +// shouldn't be able to write what the page counts. const ( // ingestMaxBody is the most a post may carry: a full batch of diff --git a/internal/gateway/usage_ingest_test.go b/internal/gateway/usage_ingest_test.go index 49ed3df9a..5e0a91cd9 100644 --- a/internal/gateway/usage_ingest_test.go +++ b/internal/gateway/usage_ingest_test.go @@ -192,7 +192,7 @@ func TestUsageIngestTouchesNoLimit(t *testing.T) { // Who may report: this computer; another only with an enabled key while // shared; a browser page, from anywhere, only with a key, since corsGuard -// lets a page on localhost and an opaque origin through; never a key held +// lets a page on localhost through keyless (an opaque origin it refuses); // to a budget. Nothing refused is written. func TestUsageIngestAccess(t *testing.T) { do := ingestServer(t)