gui: magpie web's port answers the gateway's /v1 routes too, so one proxy location serves both (zgcwkj on Discord)

zgcwkj puts magpie behind nginx on one domain and wanted the browser UI
(magpie web / serve --web, 127.0.0.1:3430) and the gateway (:3425) from
one port, so one location works. Now the web port hands every gateway
client route to the gateway: /v1/..., /v1beta/..., /models, /chat/completions,
/responses, /messages, /images, /embeddings, /rerank, /audio, /videos,
/muse-code/models, /backend-api/codex/..., the search path and /mcp/...
(gateway.ClientPath). Everything else stays the page's, behind webGuard as
before. /api/* stays split: on the web port it is the UI's API; Ollama's
/api/* and Claude Desktop's /api/hello still need the gateway port, since
the two can't share the path.

Security: a handed-over request goes through the gateway's whole own
stack, not a copy of it. gateway.Server.Front() is lanGuard(Handler()),
built once; ListenAndServe serves the same handler. When this process
serves the gateway, the web port calls Front() in process; when another
magpie does, toGateway reverse-proxies to gateway.URL(), keeps the Host,
copies Forwarded/X-Forwarded-* back (ReverseProxy strips them), and adds
X-Forwarded-For for a non-loopback peer, so remote, proxied, rebound,
Origin null, *.localhost and foreign-Origin requests are judged exactly as
on the gateway port. The web cookie is never a gateway key. Paths that
aren't clean (/v1/../api, /v1//x, /v1/./x) are not client paths, so they
never reach the gateway as one. The allow list (AllowGuard) still wraps
both.

Tests:
- TestClientPathCoversHandler reads every mux pattern Handler registers
  and fails when one is neither a ClientPath nor /, /api/* or /_magpie/*,
  so a new gateway route has to be placed.
- TestClientPathOnlyClean.
- TestWebOnePortServedHere / ServedElsewhere: with no web cookie, the UI
  API (/api/settings) is never reached for: no Origin (GET, POST),
  Origin null, a foreign Origin, a rebound Host (GET, POST), through a
  proxy (XFF), from another machine, /v1/../api, /v1/%2e%2e/api,
  /v1//api, and with a gateway key. The gateway routes on the web port:
  local agent 200; Origin null POST 403; foreign Origin 403; rebound Host
  403 (with the page's cookie too); proxy or remote without a key 401
  (with the page's cookie too); with a gateway key 200; not shared 403.
- TestWebAssetsAreNoClientPath: no embedded asset shadows a client path.

Run (full packages at the first rebase, on origin/main 0b72ccbef):
- go test ./internal/gateway ./internal/gui -count=1 -timeout 45m:
  ok (gateway 644s, gui 193s).
- Rebased again on origin/main 8b460833e (upstream touched catalog,
  provider, redact and usage only); at this head: the three builds and
  the vets below again, and go test -run 'TestClientPath|TestWeb'
  ./internal/gateway ./internal/gui: ok. The full packages were not
  rerun at this head.
- gofmt -l internal/gateway internal/gui: empty
- go vet ./internal/gateway ./internal/gui; GOOS=linux go vet -tags
  nogui ./internal/gateway ./internal/gui ./internal/cli; GOOS=windows go
  vet ./internal/gateway ./internal/gui: ok
- go build .; GOOS=linux go build -tags nogui .; GOOS=windows go build .: ok

Broken by hand, each red, then restored:
- no onePort (the old web handler): agent 401 not 200, Origin null 401
  not 403 (ServedHere).
- Front without lanGuard: rebound Host 200, proxy without a key 200.
- toGateway not copying the forwarding headers: proxy without a key 200,
  not shared 200 (ServedElsewhere).
- no X-Forwarded-For for a remote peer: another machine 200.
- Host not kept: rebound Host 200.
- ClientPath taking unclean paths: TestClientPathOnlyClean red (4 paths).
  The gui tests stay green under this break, since the gateway's mux
  answers /v1/../api/settings with a redirect, not the UI API; the clean
  check is a second wall.

Real try: the built binary, `magpie serve --web=127.0.0.1:3472` under a
sandbox HOME (MAGPIE_ADDR=127.0.0.1:3471, MAGPIE_NO_ACCOUNTS=1,
MAGPIE_TEST_SANDBOX), then Homebrew's nginx 1.31.7 (bottle unpacked in a
scratch folder, proxy_pass to 3472 with Host and X-Forwarded-For) on
127.0.0.1:3473. Direct on 3472: / 401, /?k= 303, /api/settings 401
without and 200 with the cookie, /v1/models 200, Origin null POST 403,
foreign Origin 403, X-Forwarded-For 403 (not shared). Through nginx, not
shared: /v1/models 403 with the "came through a proxy" reason; the UI
signs in with /?k= and /api/settings is 200 with its cookie. Sharing
turned on and a key added from the UI API through nginx: /v1/models 401
without a key and 401 with only the page's cookie, 200 with the key;
/v1/messages and a streamed /v1/chat/completions with the key reach the
gateway (404: the sandbox has no provider); /api/settings with the key
401; Origin null and foreign Origin without a key 401; /v1/../api/settings
401; /api/tags 401 (the page's API, not Ollama's). A rebound Host on
either port is refused only for a request that looks like a browser's
(Sec-Fetch-Site), the same as the gateway port before.

Not tried: a real model reply (and so a long stream) through the one
port, since the sandbox has no provider; https, WebSocket (Codex's
/backend-api/codex websocket) through nginx; Windows and Linux, other
than vet and build; the GUI suite (no GUI asset changed).
This commit is contained in:
yetone
2026-10-25 04:01:52 +08:00
parent 8b460833e0
commit 1b32bdcfcb
11 changed files with 403 additions and 12 deletions
+18 -5
View File
@@ -1780,8 +1780,18 @@ External clients behind a reverse proxy need an enabled gateway key
them, unless the proxy authenticates its clients itself
(`MAGPIE_TRUST_PROXY=1`, below). A public URL with no port of
its own — a reverse proxy's `https://magpie.example.com` — is the address
`magpie web` prints for its own page too, so the proxy must forward `/v1`
and `/v1beta` to the gateway's port and the rest to the page's. When the
`magpie web` prints for its own page too. One location is enough: the
page's port (`127.0.0.1:3430`) answers the gateway's client routes as well
(`/v1/…`, `/v1beta/…`, `/mcp/…`, `/backend-api/codex/…` and the same
routes without `/v1`), handing them to the gateway, so a proxy that sends
everything to the page's port serves the page at `https://magpie.example.com/`
and the agents at `https://magpie.example.com/v1`. Those routes are judged
there exactly as on the gateway's port (the allow list, a gateway key from
another machine or through the proxy, the Origin and Host checks); the
page's sign-in cookie is no gateway key, and the page and its `/api` still
need the page's key. Ollama's `/api/*` and Claude Desktop's `/api/hello`
are the page's own namespace on that port, so a client of those is given
the gateway's own port. When the
proxy and magpie run on the same machine, a request it forwards over
loopback carries a forwarding header and needs a gateway key as one from
the network does (see [Providers and the gateway](#providers-and-the-gateway)); a proxy that
@@ -1823,8 +1833,9 @@ from `/api/tags`, each one's tools, vision, thinking and window from
`/api/show`, and chats on `/v1/chat/completions`. Ollama's own chat
(`/api/chat`, `/api/generate`, so `ollama run`) isn't served. Copilot sends
no key, so this works on this computer only; behind a reverse proxy with a
single public URL, `/api` goes to `magpie web`'s page, so give the
gateway's own port.
single public URL, `/api` goes to `magpie web`'s page (which answers the
gateway's `/v1` routes but not its `/api` ones), so give the gateway's own
port.
Requests pass straight through when the vendor speaks the agent's API and
are translated otherwise, streaming, tool calls and reasoning included. The
@@ -2309,7 +2320,9 @@ The service serves only the gateway unless asked for the page:
`magpie daemon install --web` (or `magpie daemon web on` once installed)
runs `magpie serve --web`, which serves the gateway and `magpie web`'s
page from one process, so the page shows the service's own gateway,
providers and accounts. It listens on `127.0.0.1:3430`; `--lan` puts it on
providers and accounts. It listens on `127.0.0.1:3430`, which answers the
gateway's `/v1` routes too (see [Connecting anything else](#connecting-anything-else)), so one
reverse-proxy location serves both; `--lan` puts it on
`0.0.0.0:3430` and `--addr host:port` anywhere, with the same warning as
`magpie web --lan`: anyone with the link can change your settings. Its key
is made once and kept in the service file (as `MAGPIE_WEB_KEY`, readable by
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -403,6 +403,9 @@ type Server struct {
// taken off it (see Relisten)
lnMu sync.Mutex
ln net.Listener
// front is Front's handler, built once
frontOnce sync.Once
front http.Handler
// handedOff: another magpie serves the port now, and this one's end
// waits for its requests in flight to finish (handover.go)
handedOff atomic.Bool
@@ -582,7 +585,7 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
freshCtx, stopFresh := context.WithCancel(ctx)
defer stopFresh()
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath(), plugin.ToolsPath(), access.Path())
srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}
srv := &http.Server{Handler: s.Front(), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}
// the magpie serving the gateway, and only it, keeps the saved accounts
// signed in, so two never refresh one sign-in at once
go provider.KeepLoginsAlive(ctx)
+46
View File
@@ -0,0 +1,46 @@
package gateway
import (
"net/http"
"path"
"strings"
)
// Front is what the gateway's own listener serves: Handler behind
// lanGuard, built once. `magpie web`'s port hands the gateway's client
// routes (ClientPath) to it too, so a request there is judged exactly as
// one on the gateway's port: the allow list, a key from another machine
// or through a proxy, a rebound page's Host, and corsGuard's Origin rules.
func (s *Server) Front() http.Handler {
s.frontOnce.Do(func() { s.front = lanGuard(s.Handler()) })
return s.front
}
// clientPrefixes are the gateway's client routes (Handler) that a page
// served on a port of its own passes on to the gateway: everything an
// agent or an SDK calls with the gateway as its base URL.
var clientPrefixes = []string{
"/v1", "/v1beta",
"/models", "/chat/completions", "/responses", "/messages",
"/images", "/embeddings", "/rerank", "/audio", "/videos",
"/muse-code/models", CodexPath, AlphaSearchPath, "/mcp",
}
// ClientPath: p is one of the gateway's client routes, which `magpie web`
// answers on its own port too by handing it to the gateway, so one address
// (one reverse-proxy location) serves the page and the agents (zgcwkj on
// Discord). The page's own routes keep its key: /api/* is the page's, so
// the Ollama and Claude Desktop routes there, and the Claude helper's
// callbacks under /_magpie/, stay on the gateway's port alone. A path that
// isn't clean (a "..", a "//") is none, and stays behind the page's key.
func ClientPath(p string) bool {
if p == "" || path.Clean(p) != strings.TrimSuffix(p, "/") && p != "/" {
return false
}
for _, pre := range clientPrefixes {
if p == pre || strings.HasPrefix(p, pre+"/") {
return true
}
}
return false
}
+75
View File
@@ -0,0 +1,75 @@
package gateway
import (
"os"
"regexp"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Every route Handler registers is either a client route `magpie web`'s
// port hands to the gateway (ClientPath), or one named here that stays on
// the gateway's port alone: its info page at /, the /api/* routes (the
// page's own namespace there) and the Claude helper's callbacks under
// /_magpie/. A route added to Handler and to neither fails this, so the
// one-port page doesn't miss it, or take it, by accident.
func TestClientPathCoversHandler(t *testing.T) {
src, err := os.ReadFile("gateway.go")
if err != nil {
t.Fatal(err)
}
start := strings.Index(string(src), "func (s *Server) Handler() http.Handler {")
end := strings.Index(string(src)[start:], "\n}\n")
body := string(src)[start : start+end]
consts := map[string]string{
"claudeMCPPath": claudeMCPPath, "CodexPath": CodexPath, "CodexCatalogPath": CodexCatalogPath,
"AlphaSearchPath": AlphaSearchPath, "HeapPath": HeapPath, "CPUPath": CPUPath,
"GoroutinesPath": GoroutinesPath, "SearchMCPPath": SearchMCPPath, "VisionMCPPath": VisionMCPPath,
"ToolsMCPPath": ToolsMCPPath, "provider.RemoteCardsPath": provider.RemoteCardsPath,
"provider.RemoteRefreshPath": provider.RemoteRefreshPath,
}
re := regexp.MustCompile(`mux\.HandleFunc\(((?:"[^"]*"|[A-Za-z.]+)(?:\s*\+\s*(?:"[^"]*"|[A-Za-z.]+))*),`)
n := 0
for _, m := range re.FindAllStringSubmatch(body, -1) {
pat := ""
for _, part := range strings.Split(m[1], "+") {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, `"`) {
pat += strings.Trim(part, `"`)
} else if v, ok := consts[part]; ok {
pat += v
} else {
t.Fatalf("Handler names %s, which this test doesn't know: add it to consts", part)
}
}
if i := strings.IndexByte(pat, ' '); i >= 0 {
pat = pat[i+1:]
}
p := strings.NewReplacer("{$}", "", "{id...}", "x", "{call...}", "x", "{id}", "x", "{token}", "x", "{name}", "x").Replace(pat)
n++
stays := p == "/" || strings.HasPrefix(p, "/api/") || strings.HasPrefix(p, "/_magpie/")
if ClientPath(p) == stays {
t.Errorf("%s (%s): ClientPath %v", pat, p, ClientPath(p))
}
}
if n < 60 {
t.Fatalf("found %d routes in Handler: the pattern no longer reads it", n)
}
}
// A path that isn't clean stays behind the page's key: the gateway's mux
// would redirect it elsewhere, and "/v1/../api/state" is the page's API.
func TestClientPathOnlyClean(t *testing.T) {
for _, p := range []string{"", "/", "/api/state", "/api/v1/models", "/v1/../api/state", "/v1//models", "/v1/./models", "/v1x", "/v1betax/models", "/boot.js", "/_magpie/sign-in", "/mcpx", "/v1/models/../../api/settings"} {
if ClientPath(p) {
t.Errorf("%q is a client path", p)
}
}
for _, p := range []string{"/v1", "/v1/", "/v1/models", "/v1/chat/completions", "/v1beta/models/gemini:generateContent", "/mcp/magpie/tools", "/backend-api/codex/responses", "/messages"} {
if !ClientPath(p) {
t.Errorf("%q is not a client path", p)
}
}
}
+67 -1
View File
@@ -10,6 +10,7 @@ import (
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
@@ -103,7 +104,7 @@ func StartWeb(addr, version string) (*Web, error) {
}
w.Link = scheme + "://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)
w.srv = &http.Server{
Handler: gateway.AllowGuard(webHandler(port, key, keep, Handler(webHost{quit}, startBackend()))),
Handler: webServed(port, key, keep, Handler(webHost{quit}, startBackend())),
ReadHeaderTimeout: 30 * time.Second,
}
go w.srv.Serve(ln)
@@ -321,6 +322,13 @@ func LANAddrs() []string {
return out
}
// webServed is all `magpie web` on port serves: the gateway's client
// routes, judged by the gateway (onePort), and the page and its API behind
// the allow list and the key.
func webServed(port, key string, keep time.Duration, page http.Handler) http.Handler {
return onePort(gateway.AllowGuard(webHandler(port, key, keep, page)))
}
// webHandler is what `magpie web` on port serves: the page and its API
// behind the key, compressed for the browser.
func webHandler(port, key string, keep time.Duration, page http.Handler) http.Handler {
@@ -375,3 +383,61 @@ func compressible(ct string) bool {
// isWeb: the page is served to a browser by `magpie web`.
func isWeb(w Windows) bool { _, ok := w.(webHost); return ok }
// onePort hands the gateway's client routes (gateway.ClientPath: /v1/…,
// /v1beta/…, /mcp/…) on the page's port to the gateway, so the page and the
// agents share one address and a reverse proxy needs one location for both
// (zgcwkj on Discord). Each such request is judged by the gateway's own
// guards (Server.Front), not the page's key: an agent has no cookie, and a
// request from another machine or through a proxy needs a gateway key
// while magpie is shared, as on the gateway's port. Everything else (the
// page, its /api/*) stays behind the page's allow list and key.
func onePort(page http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if !gateway.ClientPath(r.URL.Path) {
page.ServeHTTP(rw, r)
return
}
if gw := served.Load(); gw != nil {
gw.Front().ServeHTTP(rw, r)
return
}
toGateway.ServeHTTP(rw, r)
})
}
// toGateway passes a client route on to the gateway another magpie serves
// here (the service, the app), as it came: its Host, so a rebound page's
// name is still refused, and its forwarding headers, so a request a proxy
// passed on is still one from another machine. One from another machine
// straight to this port gets the peer's address added as X-Forwarded-For,
// as the gateway would otherwise see this process's loopback call and ask
// it no key.
var toGateway = &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) {
u, _ := url.Parse(gateway.URL())
pr.SetURL(u)
pr.Out.Host = pr.In.Host
// Rewrite starts from a request with these taken off
for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto"} {
if v := pr.In.Header.Values(h); len(v) > 0 {
pr.Out.Header[h] = append([]string(nil), v...)
}
}
if !loopbackPeer(pr.In.RemoteAddr) {
pr.SetXForwarded()
}
},
FlushInterval: -1, // streams as they come
ErrorHandler: func(rw http.ResponseWriter, r *http.Request, err error) {
log.Printf("magpie web: %s %s: the gateway at %s: %v", r.Method, r.URL.Path, gateway.URL(), err)
http.Error(rw, "magpie's gateway at "+gateway.URL()+" doesn't answer: "+err.Error(), http.StatusBadGateway)
},
}
// loopbackPeer: addr (a RemoteAddr) is on this computer's loopback.
func loopbackPeer(addr string) bool {
h, _, err := net.SplitHostPort(addr)
ip := net.ParseIP(h)
return err == nil && ip != nil && ip.IsLoopback()
}
+188
View File
@@ -0,0 +1,188 @@
package gui
import (
"io/fs"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/settings"
)
// onePortHome is a fresh magpie home for one test: settings and keys of
// its own.
func onePortHome(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
}
// onePortKey shares magpie and makes an enabled gateway key.
func onePortKey(t *testing.T) string {
t.Helper()
s := settings.Load()
s.LAN = true
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
k, err := access.Update("add-key", access.Change{Name: "nginx"})
if err != nil {
t.Fatal(err)
}
return k
}
// onePortCall is a request to h from peer, with hdr's pairs, the page's
// cookie added when cookie isn't "".
func onePortCall(t *testing.T, h http.Handler, method, target, peer, host, cookie string, hdr ...string) *httptest.ResponseRecorder {
t.Helper()
var body *strings.Reader
if method == "POST" {
body = strings.NewReader(`{"model":"none/none","messages":[{"role":"user","content":"hi"}]}`)
} else {
body = strings.NewReader("")
}
r := httptest.NewRequest(method, target, body)
r.RemoteAddr = peer
r.Host = host
r.Header.Set("Content-Type", "text/plain") // a page's "simple" POST
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
if cookie != "" {
r.AddCookie(&http.Cookie{Name: "magpie_web_3430", Value: cookie})
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
var chromeMarks = []string{"User-Agent", "Mozilla/5.0 (Macintosh) Chrome/140", "Sec-Fetch-Site", "same-origin", "Sec-Fetch-Mode", "cors"}
// onePortCases checks what `magpie web`'s port answers, the gateway being
// reached through gw (this process's, or another magpie's): its client
// routes as the gateway's own port would, and the page's API never without
// the page's key, whatever route, Origin or Host a request takes.
func onePortCases(t *testing.T, h http.Handler, reached *bool) {
t.Helper()
const lo, here = "127.0.0.1:50001", "127.0.0.1:3430"
const evil = "rebind.attacker.example:3430"
api := func(name, method, target, peer, host string, hdr ...string) {
t.Helper()
*reached = false
w := onePortCall(t, h, method, target, peer, host, "", hdr...)
if *reached || w.Code < 300 || w.Code == http.StatusMovedPermanently {
t.Errorf("the page's API %s: %d, reached %v: %s", name, w.Code, *reached, w.Body.String())
}
}
// the page's API: no cookie, no way in
api("with no Origin", "GET", "/api/settings", lo, here)
api("with no Origin, a POST", "POST", "/api/settings", lo, here)
api("from Origin: null", "POST", "/api/settings", lo, here, "Origin", "null")
api("from a foreign Origin", "POST", "/api/settings", lo, here, "Origin", "https://evil.example")
api("under a rebound Host", "GET", "/api/settings", lo, evil, chromeMarks...)
api("under a rebound Host, a POST", "POST", "/api/settings", lo, evil, append([]string{"Origin", "http://" + evil}, chromeMarks...)...)
api("through a proxy", "GET", "/api/settings", lo, "magpie.example.com", "X-Forwarded-For", "203.0.113.9")
api("from another machine", "GET", "/api/settings", "10.0.0.5:50001", here)
// nor by a path that names a client route on its way to the API
api("by /v1/../api", "GET", "/v1/../api/settings", lo, here)
api("by /v1/%2e%2e/api", "GET", "/v1/%2e%2e/api/settings", lo, here)
api("by /v1//api", "GET", "/v1//api/settings", lo, here)
// a gateway key is no key to the page
key := onePortKey(t)
api("with a gateway key", "GET", "/api/settings", lo, here, "Authorization", "Bearer "+key)
*reached = false
if w := onePortCall(t, h, "POST", "/api/settings", lo, here, onePortWebKey); w.Code != http.StatusTeapot || !*reached {
t.Fatalf("the page's API with its cookie: %d", w.Code)
}
gw := func(name string, want int, method, target, peer, host, cookie string, hdr ...string) {
t.Helper()
*reached = false
w := onePortCall(t, h, method, target, peer, host, cookie, hdr...)
if w.Code != want || *reached {
t.Errorf("the gateway %s: %d, want %d (page reached %v): %s", name, w.Code, want, *reached, w.Body.String())
}
}
// the gateway's client routes, judged as on its own port
gw("for an agent here", 200, "GET", "/v1/models", lo, here, "")
gw("from Origin: null", 403, "POST", "/v1/chat/completions", lo, here, "", "Origin", "null")
gw("from a foreign Origin", 403, "POST", "/v1/chat/completions", lo, here, "", "Origin", "https://evil.example")
gw("under a rebound Host", 403, "GET", "/v1/models", lo, evil, "", chromeMarks...)
gw("under a rebound Host, a POST", 403, "POST", "/v1/chat/completions", lo, evil, "", append([]string{"Origin", "http://" + evil}, chromeMarks...)...)
// the page's own cookie is no gateway key either
gw("under a rebound Host with the page's cookie", 403, "GET", "/v1/models", lo, evil, onePortWebKey, chromeMarks...)
gw("through a proxy without a key", 401, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9")
gw("through a proxy with the page's cookie", 401, "GET", "/v1/models", lo, "magpie.example.com", onePortWebKey, "X-Forwarded-For", "203.0.113.9")
gw("from another machine without a key", 401, "GET", "/v1/models", "10.0.0.5:50001", here, "")
gw("through a proxy with a gateway key", 200, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9", "Authorization", "Bearer "+key)
gw("from another machine with a gateway key", 200, "GET", "/v1/models", "10.0.0.5:50001", here, "", "Authorization", "Bearer "+key)
// not shared: another machine, or a proxy, isn't answered at all
s := settings.Load()
s.LAN = false
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
gw("through a proxy, not shared", 403, "GET", "/v1/models", lo, "magpie.example.com", "", "X-Forwarded-For", "203.0.113.9", "Authorization", "Bearer "+key)
gw("from another machine, not shared", 403, "GET", "/v1/models", "10.0.0.5:50001", here, "", "Authorization", "Bearer "+key)
}
const onePortWebKey = "0123456789abcdef0123456789abcdef"
func onePortPage(reached *bool) http.Handler {
return webServed("3430", onePortWebKey, 0, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
*reached = true
rw.WriteHeader(http.StatusTeapot)
}))
}
// zgcwkj on Discord: one reverse-proxy location for the page and the
// agents. `magpie web`'s port hands the gateway's client routes to the
// gateway this process serves, through the gateway's own guards.
func TestWebOnePortServedHere(t *testing.T) {
onePortHome(t)
g := gateway.New()
prev := served.Swap(g)
t.Cleanup(func() { served.Store(prev) })
var reached bool
onePortCases(t, onePortPage(&reached), &reached)
}
// With another magpie serving the gateway (the service, the app), the page
// passes the client routes on to it, and they are judged there as they
// came: Host, Origin and a proxy's forwarding headers kept, and one from
// another machine marked as such.
func TestWebOnePortServedElsewhere(t *testing.T) {
onePortHome(t)
other := httptest.NewServer(gateway.New().Front())
t.Cleanup(other.Close)
u, _ := url.Parse(other.URL)
t.Setenv("MAGPIE_ADDR", u.Host)
prev := served.Swap(nil)
t.Cleanup(func() { served.Store(prev) })
var reached bool
onePortCases(t, onePortPage(&reached), &reached)
}
// No file of the page is at a client route, where the gateway would
// answer in its place.
func TestWebAssetsAreNoClientPath(t *testing.T) {
fs.WalkDir(staticFS(), ".", func(p string, d fs.DirEntry, err error) error {
if err == nil && gateway.ClientPath("/"+p) {
t.Errorf("the page's /%s is a gateway client route", p)
}
return nil
})
}
+1 -1
View File
@@ -89,7 +89,7 @@
<div class="table-wrap"><table>
<tr><td><b>Image</b></td><td><code>ghcr.io/yetone/magpie</code>, for <code>linux/amd64</code> and <code>linux/arm64</code></td></tr>
<tr><td><b>Tags</b></td><td><code>latest</code> (the newest release), <code>0.1.1150</code> (one release), <code>0.1</code>, <code>edge</code> (every change on <code>main</code>)</td></tr>
<tr><td><b>Ports</b></td><td><code>3425</code> the gateway agents call; <code>3430</code> the browser UI, when the container runs <code>magpie web</code></td></tr>
<tr><td><b>Ports</b></td><td><code>3425</code> the gateway agents call; <code>3430</code> the browser UI, when the container runs <code>magpie web</code>; it answers the gateway’s <code>/v1</code> routes too, so a reverse proxy needs only this port</td></tr>
<tr><td><b>Volume</b></td><td><code>/config</code>: providers, keys, sign-ins, plugins and usage</td></tr>
<tr><td><b>User</b></td><td>nonroot (uid 65532)</td></tr>
</table></div>
+1 -1
View File
@@ -89,7 +89,7 @@
<div class="table-wrap"><table>
<tr><td><b>イメージ</b></td><td><code>ghcr.io/yetone/magpie</code>(<code>linux/amd64</code> と <code>linux/arm64</code>)</td></tr>
<tr><td><b>タグ</b></td><td><code>latest</code>(最新リリース)、<code>0.1.1150</code>(特定のリリース)、<code>0.1</code>、<code>edge</code>(<code>main</code> の変更ごと)</td></tr>
<tr><td><b>ポート</b></td><td><code>3425</code> はエージェントが呼ぶゲートウェイ、<code>3430</code> はコンテナが <code>magpie web</code> を動かすときのブラウザ UI</td></tr>
<tr><td><b>ポート</b></td><td><code>3425</code> はエージェントが呼ぶゲートウェイ、<code>3430</code> はコンテナが <code>magpie web</code> を動かすときのブラウザ UI。ゲートウェイの <code>/v1</code> ルートにも応えるので、リバースプロキシはこのポートだけで足ります</td></tr>
<tr><td><b>ボリューム</b></td><td><code>/config</code>:プロバイダ、キー、サインイン、プラグイン、使用量</td></tr>
<tr><td><b>ユーザー</b></td><td>nonroot(uid 65532)</td></tr>
</table></div>
+1 -1
View File
@@ -89,7 +89,7 @@
<div class="table-wrap"><table>
<tr><td><b>镜像</b></td><td><code>ghcr.io/yetone/magpie</code>,支持 <code>linux/amd64</code> 和 <code>linux/arm64</code></td></tr>
<tr><td><b>标签</b></td><td><code>latest</code>(最新正式版)、<code>0.1.1150</code>(某个版本)、<code>0.1</code>、<code>edge</code>(<code>main</code> 上的每次改动)</td></tr>
<tr><td><b>端口</b></td><td><code>3425</code> 是 Agent 调用的网关;<code>3430</code> 是容器运行 <code>magpie web</code> 时的 Web 界面</td></tr>
<tr><td><b>端口</b></td><td><code>3425</code> 是 Agent 调用的网关;<code>3430</code> 是容器运行 <code>magpie web</code> 时的 Web 界面;它也响应网关的 <code>/v1</code> 路由,所以反向代理只需转发这一个端口</td></tr>
<tr><td><b>数据卷</b></td><td><code>/config</code>:供应商、密钥、登录、插件和用量</td></tr>
<tr><td><b>用户</b></td><td>nonroot(uid 65532)</td></tr>
</table></div>