From 1c047f36858836485915ad6ae19a44d536bbf3b0 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 22:14:18 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20another=20computer=20is=20let=20in?= =?UTF-8?q?=20by=20the=20gateway=20key=20it=20sends=20wherever=20its=20cli?= =?UTF-8?q?ent=20puts=20it,=20beside=20an=20empty,=20placeholder=20or=20st?= =?UTF-8?q?ale=20token=20(=E6=82=A0=E6=82=A0=E5=93=A5=20on=20Discord:=20ma?= =?UTF-8?q?gpie=20shared=20on=20a=20NAS,=20a=20client's=20model=20list=20f?= =?UTF-8?q?rom=20http://192.168.0.200:3425=20failed,=20Anthropic=20Message?= =?UTF-8?q?s=20format,=20while=20from=20magpie=20on=20127.0.0.1=20it=20cam?= =?UTF-8?q?e)=20=E2=80=94=20loopback=20takes=20any=20token,=20so=20a=20req?= =?UTF-8?q?uest=20from=20this=20computer=20is=20answered=20whatever=20key?= =?UTF-8?q?=20it=20carries,=20but=20one=20from=20another=20computer=20is?= =?UTF-8?q?=20let=20in=20only=20by=20an=20enabled=20gateway=20key,=20and?= =?UTF-8?q?=20the=20key=20was=20read=20from=20one=20place:=20callerKey=20t?= =?UTF-8?q?ook=20Authorization=20whenever=20the=20header=20was=20there,=20?= =?UTF-8?q?and=20looked=20at=20x-api-key,=20x-goog-api-key=20or=20=3Fkey?= =?UTF-8?q?=3D=20only=20when=20it=20wasn't.=20A=20client=20that=20sends=20?= =?UTF-8?q?the=20key=20in=20x-api-key=20with=20"Authorization:=20Bearer=20?= =?UTF-8?q?"=20beside=20it=20(no=20token=20set),=20"Bearer=20undefined",?= =?UTF-8?q?=20or=20a=20stale=20token=20there=20(ANTHROPIC=5FAUTH=5FTOKEN?= =?UTF-8?q?=20left=20at=20magpie)=20was=20refused=20from=20the=20network?= =?UTF-8?q?=20=E2=80=94=20"no=20API=20key=20was=20sent"=20or=20"not=20an?= =?UTF-8?q?=20enabled=20magpie=20gateway=20key"=20=E2=80=94=20while=20the?= =?UTF-8?q?=20same=20request=20on=20127.0.0.1=20listed=20the=20models;=20"?= =?UTF-8?q?bearer=20"=20in=20lower=20case=20was=20read=20as=20the=20k?= =?UTF-8?q?ey=20"bearer=20".=20Now=20callerKeys=20reads=20every=20pla?= =?UTF-8?q?ce=20a=20key=20comes=20(Authorization's=20bearer=20token,=20any?= =?UTF-8?q?=20case,=20then=20x-api-key,=20x-goog-api-key,=20=3Fkey=3D),=20?= =?UTF-8?q?passing=20over=20an=20empty=20one,=20and=20identifyCaller=20let?= =?UTF-8?q?s=20the=20request=20in=20by=20whichever=20is=20an=20enabled=20g?= =?UTF-8?q?ateway=20key,=20the=20refusal=20still=20naming=20the=20first;?= =?UTF-8?q?=20a=20key-shaped=20value=20in=20any=20of=20them=20(managedKey)?= =?UTF-8?q?=20also=20has=20a=20request=20from=20this=20computer=20counted?= =?UTF-8?q?=20by=20its=20key.=20Nothing=20is=20let=20in=20that=20wasn't=20?= =?UTF-8?q?carrying=20an=20enabled=20key.=20Nothing=20else=20differed=20fo?= =?UTF-8?q?r=20the=20network:=20the=20gateway=20checks=20no=20Host=20heade?= =?UTF-8?q?r=20(Host=20192.168.0.200:3425=20is=20answered),=20lists=20the?= =?UTF-8?q?=20same=20catalog=20to=20a=20keyed=20LAN=20caller=20as=20to=20l?= =?UTF-8?q?oopback=20(no=20per-key=20model=20filter),=20and=20answers=20/v?= =?UTF-8?q?1/models,=20/models=20and=20/v1/models=3Flimit=3D=20alike,=20in?= =?UTF-8?q?=20a=20shape=20Anthropic=20and=20OpenAI=20clients=20both=20read?= =?UTF-8?q?.=20TestLANModelsWithKeyBesideAnotherToken=20(from=20192.168.0.?= =?UTF-8?q?9=20to=20Host=20192.168.0.200:3425:=20the=20key=20in=20x-api-ke?= =?UTF-8?q?y=20beside=20an=20empty,=20bare,=20"undefined"=20or=20"magpie"?= =?UTF-8?q?=20bearer,=20lower-case=20bearer,=20x-goog-api-key=20beside=20a?= =?UTF-8?q?=20stale=20bearer,=20over=20/v1/models,=20/models=20and=20=3Fli?= =?UTF-8?q?mit=3D1000,=20each=20listed=20and=20counted=20by=20the=20key;?= =?UTF-8?q?=20a=20wrong=20key=20or=20none=20still=20401;=20loopback=20coun?= =?UTF-8?q?ted=20by=20the=20key=20beside=20a=20token)=20fails=20without=20?= =?UTF-8?q?the=20change=20(401=20"no=20API=20key=20was=20sent"=20for=20the?= =?UTF-8?q?=20key=20beside=20"Bearer=20").=20go=20vet=20./internal/...,=20?= =?UTF-8?q?go=20build=20-tags=20nogui=20(darwin,=20GOOS=3Dlinux),=20GOOS?= =?UTF-8?q?=3Dwindows=20go=20build,=20go=20test=20-tags=20nogui=20-count?= =?UTF-8?q?=3D1=20./...=20under=20a=20temp=20HOME=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/lan.go | 63 +++++++++++++++++++++++++++------- internal/gateway/lan_test.go | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 12 deletions(-) diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 7989657ac..255884f65 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "strings" "sync" @@ -182,7 +183,7 @@ func lanGuard(next http.Handler) http.Handler { http.Error(w, "magpie isn't shared on the local network", http.StatusForbidden) return } - if (remote && shared) || (!remote && access.Managed(callerKey(r))) { + if (remote && shared) || (!remote && managedKey(r)) { var ok bool r, ok = identifyCaller(w, r) if !ok { @@ -199,7 +200,7 @@ func lanGuard(next http.Handler) http.Handler { // callerGuard also covers embedded handlers used by the web app and tests. func callerGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if access.Caller(r.Context()).KeyID == "" && access.Managed(callerKey(r)) && (local(r) || settings.Load().LAN) { + if access.Caller(r.Context()).KeyID == "" && managedKey(r) && (local(r) || settings.Load().LAN) { var ok bool r, ok = identifyCaller(w, r) if !ok { @@ -211,10 +212,15 @@ func callerGuard(next http.Handler) http.Handler { } func identifyCaller(w http.ResponseWriter, r *http.Request) (*http.Request, bool) { - key := callerKey(r) - who, ok := access.Authenticate(key) + var who access.Identity + ok := false + for _, k := range callerKeys(r) { + if who, ok = access.Authenticate(k); ok { + break + } + } if !ok && !local(r) { - msg := refusedKey(key) + msg := refusedKey(callerKey(r)) log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, msg) writeError(w, provider.Chat, http.StatusUnauthorized, msg) return r, false @@ -264,17 +270,50 @@ func sharedWith(r *http.Request) bool { return ok } -// callerKey is the API key a request carries, however its client sends one. +// callerKey is the API key a request carries, however its client sends one: +// the first of callerKeys, "" for none. func callerKey(r *http.Request) string { - if a := r.Header.Get("Authorization"); a != "" { - return strings.TrimSpace(strings.TrimPrefix(a, "Bearer ")) + if ks := callerKeys(r); len(ks) > 0 { + return ks[0] } - for _, h := range []string{"x-api-key", "x-goog-api-key"} { - if v := r.Header.Get(h); v != "" { - return v + return "" +} + +// callerKeys are the API keys a request carries, in the order they are +// read: Authorization's bearer token, x-api-key, x-goog-api-key, ?key=. A +// header that carries none ("Authorization: Bearer ", sent beside an +// x-api-key by a client with no token set) is passed over, and a client +// that sends two different values — a stale or placeholder token in +// Authorization (ANTHROPIC_AUTH_TOKEN left at magpie), the key in x-api-key +// — is let in by whichever is an enabled gateway key. Loopback takes any +// token, so this mattered only from another computer, which was refused +// what this one was answered (悠悠哥 on Discord: a client's model list from +// magpie shared on a NAS failed, from magpie on 127.0.0.1 it came). +func callerKeys(r *http.Request) []string { + var out []string + add := func(v string) { + if v = strings.TrimSpace(v); v != "" && !slices.Contains(out, v) { + out = append(out, v) } } - return r.URL.Query().Get("key") + a := strings.TrimSpace(r.Header.Get("Authorization")) + if len(a) >= 7 && strings.EqualFold(a[:7], "Bearer ") { + a = a[7:] + } else if strings.EqualFold(a, "Bearer") { + a = "" + } + add(a) + for _, h := range []string{"x-api-key", "x-goog-api-key"} { + add(r.Header.Get(h)) + } + add(r.URL.Query().Get("key")) + return out +} + +// managedKey: the request carries a named gateway key's form (sk-magpie-…) +// in any of the places a key is read. +func managedKey(r *http.Request) bool { + return slices.ContainsFunc(callerKeys(r), access.Managed) } // refusedKey says why a caller's key was turned away: none came, or the diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go index dbdcf0a30..b75d9f2b0 100644 --- a/internal/gateway/lan_test.go +++ b/internal/gateway/lan_test.go @@ -5,9 +5,11 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" ) @@ -175,3 +177,67 @@ func TestInContainer(t *testing.T) { } } } + +// Another computer lists the models with the key it was given whatever +// else its client sends beside it: an empty or placeholder Authorization +// with the key in x-api-key, a stale token there, "bearer" in lower case +// (悠悠哥 on Discord: a client's model list from magpie shared on a NAS +// failed, while from magpie on 127.0.0.1, which takes any token, it came). +// The request comes as it would from the network: another address, the +// NAS's address as its Host. +func TestLANModelsWithKeyBesideAnotherToken(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + t.Setenv("MAGPIE_ADDR", "") + keys, secrets := newCaller(t, "PC") + key := secrets[0] + var who string + h := lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + who = access.Caller(r.Context()).KeyID + New().Handler().ServeHTTP(w, r) + })) + list := func(from, path string, hdr ...string) (int, string) { + who = "" + r := httptest.NewRequest("GET", "http://192.168.0.200:3425"+path, nil) + r.RemoteAddr = from + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + for _, hdr := range [][]string{ + {"x-api-key", key, "anthropic-version", "2023-06-01"}, + {"x-api-key", key, "Authorization", "Bearer " + key, "anthropic-version", "2023-06-01"}, + {"x-api-key", key, "Authorization", "Bearer "}, + {"x-api-key", key, "Authorization", "Bearer"}, + {"x-api-key", key, "Authorization", "Bearer undefined"}, + {"x-api-key", key, "Authorization", "Bearer magpie"}, + {"Authorization", "bearer " + key}, + {"Authorization", "Bearer magpie", "x-goog-api-key", key}, + } { + for _, path := range []string{"/v1/models", "/models", "/v1/models?limit=1000"} { + c, b := list("192.168.0.9:50123", path, hdr...) + if c != 200 || !strings.Contains(b, `"id":"fake/m1"`) { + t.Fatalf("%s %q: %d %s", path, hdr, c, b) + } + if who != keys[0].ID { + t.Fatalf("%s %q: counted as %q, not the key", path, hdr, who) + } + } + } + // a key the gateway doesn't have is refused wherever it is sent + for _, hdr := range [][]string{ + {"x-api-key", "sk-magpie-wrong", "Authorization", "Bearer magpie"}, + {"Authorization", "Bearer "}, + {"x-api-key", key + "x"}, + } { + if c, _ := list("192.168.0.9:50123", "/v1/models", hdr...); c != http.StatusUnauthorized { + t.Fatalf("%q got %d", hdr, c) + } + } + // this computer is counted by the key beside a token too + if c, _ := list("127.0.0.1:50123", "/v1/models", "Authorization", "Bearer anything", "x-api-key", key); c != 200 || who != keys[0].ID { + t.Fatalf("loopback: %d, counted as %q", c, who) + } +}