gateway: a page at a localhost subdomain spends a subscription only with a gateway key, as Origin null does (#2256, ggbdpq)
What changed
- corsGuard refuses (403) an http(s) Origin at a subdomain of localhost
unless the call carries an enabled gateway key (localhostSubdomain),
the rule Origin "null" got in #2242. foreignPage still passes it, so a
page there that holds a key keeps working; neither gets CORS headers.
- Why: Chrome and Firefox resolve *.localhost to loopback themselves,
but Safari and other WebKit views hand the name to the system
resolver, which before macOS 26 asks the network's DNS (WebKit bug
160504, closed MOVED: "implemented in OS frameworks below WebKit",
2025-09-19; fails on macOS 15.7). A captive portal's or hostile
network's resolver serves such a page from anywhere, and its "simple"
text/plain POST spent subscriptions with no key.
- 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://, so the two names
are any page's there, and a hostile resolver answers them as readily
as any other (the residual the report left open). webviewOS
(runtime.GOOS) lets the test be each system.
- The same page also reached the gateway rebound: at evil.localhost:3425
once the name turns to 127.0.0.1, its GET carries no Origin, and
lanGuard's ownHost counted every *.localhost Host as this computer, so
GET /v1/models and /v1/magpie/quotas answered 200. ownHost no longer
counts a subdomain of localhost (localhost itself and
docker.for.mac.localhost still count); a browser at one needs a key.
- TestForeignPagesRefused's tauri.localhost row now sends a key, and
TestReboundPageRefused expects wails.localhost refused.
- docs/subsystems/gateway-routing.md says both.
Ran
- TestLocalhostSubdomainNeedsAKey (darwin, linux and windows as
webviewOS; six routes; cross-origin and rebound; the fake vendor never
reached): fails on origin/main 00501401a (76 errors, e.g. "POST
/v1/chat/completions from http://evil.localhost with no key: 200"),
passes with the change.
- Broken by hand, each red: ownHost counting *.localhost again (the
rebound GETs 200); localhostSubdomain always false; the Windows-only
exception dropped (tauri.localhost answered keyless on darwin).
- The cors, rebind, LAN, usage-ingest and allow-list tests: ok.
- gofmt -l clean; go vet ./..., GOOS=windows go vet ./...,
GOOS=linux go vet -tags nogui ./... clean.
- go test -p 4 ./... (macOS): ok in every package but internal/agent and internal/gateway, which hit the 10m package timeout under load ~30 with no test hung (the running test 1-2s old); rerun with -timeout 40m: gateway ok 551s, agent ok 426s.
Not tried: a real Safari on macOS 15 against a resolver that answers
*.localhost; Tauri or Wails apps on Windows.
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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 <key> (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 <key> (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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user