gateway: a sandboxed frame's Origin: null spends a subscription only with a gateway key (#2242, JasonBuildAI)
A sandboxed iframe, or a page opened from file://, sends `Origin: null`.
foreignPage judges only http and https origins, so corsGuard let "null"
through without a key. A simple text/plain POST from such a page (no
preflight) reached /v1/chat/completions and spent the user's
subscription. corsGuard is where every route's same-origin is decided,
so the fix goes there: a request with Origin: null is answered only
when it carries a working gateway key (keyedCaller, which the listed-
origin 401 path now uses too). It gets 403 and a message that says how
to send a key. App schemes (app://…) and requests with no Origin are
unchanged.
The patch is JasonBuildAI's fe11a8abd (fork branch
fix/null-origin-keyless-spend-a13b21). docs/subsystems/gateway-sessions.md
also says that a null Origin needs a key.
What was run, at this commit's parent 8e8316ed2 vs. this tree:
- Repro with a sandbox HOME, a fake upstream on 127.0.0.1:3672 that logs
each hit, and `magpie serve` on 127.0.0.1:3671. On main, curl POST
with Origin: null got 200 and reached the vendor. A sandboxed srcdoc
iframe in a file:// page, in Playwright WebKit and Chromium, reached
it too (2 hits). Fixed: null POST and GET /v1/models got 403,
app://cherry and no-Origin got 200, and both browsers were refused
with 0 upstream hits.
- With main's cors.go and the new tests, TestForeignPagesRefused and
TestOpaqueOriginNeedsAKey FAIL ("a sandboxed frame with no key reached
the vendor 5 times"). With the fix both pass.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui and GOOS=windows
clean.
- HOME=<scratch> go test -tags nogui ./...: every package ok except
internal/gateway and internal/agent. Those hit the 10m timeout at load
average 76-91: the running tests were 14s and 23s old, not hung. Rerun
with -timeout 40m: gateway ok (724s), agent ok (620s).
Co-authored-by: JasonBuildAI <jasonbuildai@gmail.com>
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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`,
|
||||
|
||||
+29
-10
@@ -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 <key> (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 <key> (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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user