diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b84be2699..363511015 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -16,7 +16,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). | Part | Responsibility | Source | | --- | --- | --- | | 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. | [`gateway.go`](../../internal/gateway/gateway.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, `/mcp/{name}` and the `/v1/magpie/*` status endpoints. 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`. `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). 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. A request with any other Origin, or none, passes through with no CORS headers, as before. | [`gateway.go`](../../internal/gateway/gateway.go), [`cors.go`](../../internal/gateway/cors.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, `/mcp/{name}` and the `/v1/magpie/*` status endpoints. 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`. `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). 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. There is no `Host` check, so a page whose own name resolves to 127.0.0.1 (DNS rebinding) counts as same-origin. | [`gateway.go`](../../internal/gateway/gateway.go), [`cors.go`](../../internal/gateway/cors.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`), auto stand-ins, then `provider.Resolve`. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.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). 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 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) | @@ -59,7 +59,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). ## Verification ```sh -go test -tags nogui ./internal/gateway -run 'TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted' +go test -tags nogui ./internal/gateway -run 'TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused' go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestSkipsRedaction' ``` diff --git a/internal/gateway/cors.go b/internal/gateway/cors.go index 654e9800d..70b2abbc2 100644 --- a/internal/gateway/cors.go +++ b/internal/gateway/cors.go @@ -1,7 +1,10 @@ package gateway import ( + "log" + "net" "net/http" + "net/url" "slices" "strings" @@ -19,10 +22,21 @@ import ( // the same port) could spend the user's subscriptions. A page not listed // gets no CORS headers, as before, and a request with no Origin (every // agent's) passes untouched. +// +// Any other web page is refused (403, foreignPage): on loopback a call +// needs no key and the body's Content-Type isn't checked, so a page the +// 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. func corsGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") if origin == "" || !corsAllowed(origin) { + if foreignPage(r, origin) { + log.Printf("refused %s %s from the web page %s: not one listed in Settings", r.Method, r.URL.Path, origin) + 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 + } next.ServeHTTP(w, r) return } @@ -54,6 +68,69 @@ func corsGuard(next http.Handler) http.Handler { }) } +// 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, +// such as magpie's web app on a LAN address), so a browser sent it for a +// 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 +// 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. +func foreignPage(r *http.Request, origin string) bool { + if origin == "" { + return false + } + u, err := url.Parse(origin) + if err != nil { + // a browser's always parses; an unreadable http one is no page of ours + return strings.HasPrefix(strings.ToLower(origin), "http") + } + scheme := strings.ToLower(u.Scheme) + if scheme != "http" && scheme != "https" { + return false + } + host := strings.ToLower(u.Hostname()) + if host == "localhost" || strings.HasSuffix(host, ".localhost") { + return false + } + if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { + return false + } + if hostPort(u.Host, scheme) == hostPort(r.Host, scheme) { + return false + } + if r.URL.Path == "/v1/magpie/omarchy" && siteOrigin(origin) { + return false + } + return true +} + +// 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 { + hp = strings.ToLower(hp) + if hp == "" { + return "" + } + if h, p, err := net.SplitHostPort(hp); err == nil { + return net.JoinHostPort(strings.Trim(h, "[]"), p) + } + port := "80" + if scheme == "https" { + port = "443" + } + return net.JoinHostPort(strings.Trim(hp, "[]"), port) +} + // corsAllowed: origin is one the user listed. func corsAllowed(origin string) bool { saved := settings.Load().CORSOrigins diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go index ab01fddcb..3226166ae 100644 --- a/internal/gateway/cors_test.go +++ b/internal/gateway/cors_test.go @@ -5,6 +5,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "github.com/yetone/magpie/internal/access" @@ -160,3 +161,122 @@ func TestCORSKeyThroughTheServer(t *testing.T) { } } } + +// Any web page the user visits could make the browser send a "simple" +// text/plain POST to 127.0.0.1:3425, which on loopback needs no key, and +// spend the user's subscriptions without reading the reply. A page whose +// 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. +func TestForeignPagesRefused(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: "Web app"}) + if err != nil { + t.Fatal(err) + } + s := settings.Load() + s.CORSOrigins = []string{"https://app.example.com"} + s.LAN = true + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + h := New().Handler() + type call struct{ method, path, body string } + msg := `{"model":"plan/m1","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}` + do := func(c call, origin, host, remote, key string) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(c.method, c.path, strings.NewReader(c.body)) + r.RemoteAddr = remote + if host != "" { + r.Host = host + } + // what a page's fetch(..., {mode: "no-cors"}) or a form sends + r.Header.Set("Content-Type", "text/plain;charset=UTF-8") + if origin != "" { + r.Header.Set("Origin", origin) + } + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + w := httptest.NewRecorder() + lanGuard(h).ServeHTTP(w, r) + return w + } + chat := call{"POST", "/v1/chat/completions", chatReq} + routes := []call{ + chat, + {"POST", "/chat/completions", chatReq}, + {"POST", "/v1/responses", `{"model":"plan/m1","input":"hi"}`}, + {"POST", "/responses", `{"model":"plan/m1","input":"hi"}`}, + {"GET", "/v1/responses", ""}, + {"POST", "/v1/messages", msg}, + {"POST", "/messages", msg}, + {"POST", "/v1/messages/count_tokens", msg}, + {"POST", "/v1/systemone", msg}, + {"POST", "/v1beta/models/plan/m1:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, + {"POST", "/v1/embeddings", `{"model":"plan/m1","input":"hi"}`}, + {"POST", "/v1/rerank", `{"model":"plan/m1","query":"hi","documents":["a"]}`}, + {"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`}, + {"POST", "/v1/videos", `{"model":"plan/m1","prompt":"hi"}`}, + {"POST", CodexPath + "/responses", `{"model":"plan/m1","input":"hi"}`}, + {"POST", "/mcp/notes", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`}, + {"POST", "/_magpie/claude-mcp/tok", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`}, + {"POST", provider.RemoteRefreshPath, ""}, + {"GET", "/v1/magpie/quotas", ""}, + {"GET", "/v1/models", ""}, + {"OPTIONS", "/v1/chat/completions", ""}, + } + const loop = "127.0.0.1:50123" + for _, o := range []string{"https://evil.example", "http://evil.example:3425", "http://localhost.evil.example", "http://192.168.1.7:3000", "HTTPS://Evil.Example", "https://usemagpie.ai"} { + for _, c := range routes { + if w := do(c, o, "127.0.0.1:3425", loop, ""); w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "web page") || w.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("%s %s from %s: %d %s", c.method, c.path, o, w.Code, w.Body) + } + } + } + // a gateway key doesn't let an unlisted page in either + 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) + } + if n := hits.Load(); n != 0 { + t.Fatalf("a refused page reached the vendor %d times", n) + } + + // answered as before + for _, c := range []struct{ origin, host, remote, key string }{ + {"", "127.0.0.1:3425", loop, ""}, // every agent + {"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 + {"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, ""}, // its own origin behind a port-443 name + {"null", "127.0.0.1:3425", loop, ""}, // a sandboxed frame, a file:// page + {"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, ""}, + {"vscode-webview://1abc", "127.0.0.1:3425", loop, ""}, // an editor's webview + {"chrome-extension://abcdefghijklmnop", "127.0.0.1:3425", loop, ""}, // an extension + } { + if w := do(chat, c.origin, c.host, c.remote, c.key); w.Code != 200 || !strings.Contains(w.Body.String(), "ok") { + t.Errorf("%q to %s: %d %s", c.origin, c.host, w.Code, w.Body) + } + } + // usemagpie.ai still reads the Omarchy theme, and only that + if w := do(call{"GET", "/v1/magpie/omarchy", ""}, "https://usemagpie.ai", "127.0.0.1:3425", loop, ""); w.Code == http.StatusForbidden { + t.Errorf("usemagpie.ai's Omarchy theme: %d %s", w.Code, w.Body) + } +}