gateway: a URL magpie didn't choose is downloaded from public addresses only, wherever the request came from

5241de909 held an image URL a caller names to public addresses. This
carries the same guarantee to every URL magpie downloads that isn't its
own fixed vendor endpoint, and drops where the request came from as a
reason to reach a private address.

What is downloaded through the one restricted client now (every resolved
address checked and pinned, the dialled address checked again, each of up
to 5 redirects checked the same; loopback, RFC 1918, fc00::/7, link-local
with metadata, CGNAT, multicast, unspecified, documentation/reserved,
IPv4-mapped, NAT64/6to4/Teredo forms all refused):
- a caller's reference image (fetchPicture, draw.go), as before;
- web_fetch's page (search_fetch.go), as before;
- an image a vendor answers by URL, downloaded for a b64_json caller
  (draw.go) - was the gateway's unrestricted client;
- /v1/videos/{id}/content's video URL from the vendor's status
  (video.go) - was the gateway's unrestricted client;
- generate_image's own download of the gateway's image URL
  (internal/imagemcp) - was http.DefaultClient.
A vendor's answer can be steered by what the model is asked to do, so
its URLs are treated as a caller's.

Policy: a request from this computer gets nothing more. The exemption for
a loopback request that wasn't from a web page or through a forwarding
header (withPrivateFetch/privateFetchAllowed) is gone: a reverse proxy or
relay on the same host makes every request it carries arrive that way.
Two explicit allowances remain:
- settings.json "fetchPrivate" (settings.FetchPrivate): names, name:port,
  IPs and CIDR ranges the user lets magpie download from. None by
  default, no Settings page, per-machine (KeepOwn, kept across a GUI
  save). A settings.json that can't be read lets nothing extra in.
- for a vendor's URL only, the host:port of that provider's own
  configured endpoints (a LAN or local provider serving its own images).
The refusal says to send the image itself or name the host in
fetchPrivate. A vendor image that can't be downloaded is still answered
by its URL; a video is a 502.

Audited and left alone: kiro, codex_search, codex_backend and the
catalog/provider http.DefaultClient uses (fixed vendor endpoints);
remoteVideoURL (p.Do to the provider); the MCP proxy and mcpauth (URLs
the user configured); community plugins (only fixed vendor endpoints,
nothing a request names).

Docs: docs/subsystems/gateway-routing.md (the guard paragraph, web_fetch,
test command), docs/subsystems/sync-backup.md (FetchPrivate stays on
each computer).

Tests (new or rewritten): TestEditImageURLFromThisComputer (loopback,
[::1], and loopback with X-Forwarded-For as a same-host reverse proxy:
400 naming fetchPrivate, the private server never asked; with
fetchPrivate ["127.0.0.1"] it is fetched, a non-image still refused),
TestFetchPrivateEntries, TestVendorImageURLAtPrivateAddressNotFetched
(127.0.0.1, a name resolving to it, ::ffff:127.0.0.1; the vendor's own
host:port still fetched), TestVideoContentAtPrivateAddressNotFetched,
imagemcp TestVendorImageAtPrivateAddressNotFetched. gui's
TestSettingsSaveKeepsWhatItDoesNotSend sets FetchPrivate. The two imagemcp
download tests and TestImageByURLIsFetchedForB64Caller now name their
local file server in fetchPrivate / resolve files.test to a public
address.

Broken by hand, each red, restored:
- draw.go inline fetch on s.client -> TestVendorImageURLAtPrivateAddressNotFetched red
- video.go on s.client -> TestVideoContentAtPrivateAddressNotFetched red
- imagemcp on http.DefaultClient -> its TestVendorImageAtPrivateAddressNotFetched red
- fetchPicture unrestricted (the old local bypass) -> TestEditImageURLFromThisComputer red
- fetchPrivate ignored -> TestEditImageURLFromThisComputer, TestFetchPrivateEntries red
Not distinguished: settings.Load in place of LoadChecked passes too (an
unparsable file with no last good generation gives no list either way).
Not tried: a real reverse proxy (nginx/caddy) in front of a running
magpie; the X-Forwarded-For loopback request stands in for it. Not tried
against a real vendor's image or video URL.

gofmt -l clean; go vet -tags nogui darwin, GOOS=linux, GOOS=windows clean.
Full suite: go test -tags nogui -timeout 45m ./... at 8b84dc902 plus this
change: every package ok except agent and gateway (timed out at 45m at
load average ~370, no test failed before the timeout) and gui
(TestSettingsSaveKeepsWhatItDoesNotSend, fixed here by adding
FetchPrivate; TestSetAnswersWhileDevinAndProvidersHang 12.4s under load,
(4726s) with -timeout 150m at load ~220.

Rebased onto ba132d68b (17 commits; only the doc test line conflicted).
At the rebased head: gofmt clean, vet darwin/linux/windows clean, and
the Image/Draw/Video/Fetch/Edit/Private/Public tests in gateway, imagemcp,
gui and settings ok.
This commit is contained in:
yetone
2026-10-16 20:12:05 +08:00
parent 7170b5d8bd
commit ea3dee96a8
13 changed files with 404 additions and 88 deletions
+4 -4
View File
@@ -548,8 +548,8 @@ Its second tool, `web_fetch` (`search_fetch.go`, #2286), reads a page by
its URL for an agent with no fetch tool of its own. The URL is the agent's,
so it is downloaded as a caller's image is (`webFetchClient`, which is
`publicClient`): public addresses only, every resolved address checked and
pinned, through at most five redirects each checked the same, a request
from this computer included. It reads for at most 30 seconds and 5 MiB. An
pinned, through at most five redirects each checked the same, wherever
the request came from. It reads for at most 30 seconds and 5 MiB. An
HTML page is decoded from its charset and given as Markdown (`htmlText`:
headings, lists, links made absolute, code; scripts, styles and hidden
elements dropped), other text as it is, anything else is a tool error, and
@@ -702,7 +702,7 @@ the row of the entry that id reaches, with its label, under the bare id.
[`bare_ids_test.go`](../../internal/gateway/bare_ids_test.go),
`TestBareModelIDsSetting` in `internal/gui`, and
`internal/gui/tests/bare-ids.test.cjs`.
- An image a caller names by URL that magpie downloads itself (an `/v1/images/edits` or `/v1/images/generations` reference image, for an images API that takes files, Gemini's own API or Code Assist: `fetchPicture` in [`draw.go`](../../internal/gateway/draw.go)) is downloaded from public addresses only (`publicClient` in [`image_fetch_guard.go`](../../internal/gateway/image_fetch_guard.go)). Every address the host resolves to must be public (`publicAddr`: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one), and the request goes to the address checked, so a name that resolves elsewhere the second time changes nothing; a direct connection is checked again on the address dialled (`privateDialer`). Through a proxy the proxy is sent that address, never the name (an `https://` CONNECT or SOCKS keeps the name for TLS and Host; a plain `http://` URL through an HTTP proxy is asked for by the address in Host too). Each redirect, up to 5, is checked the same, and what comes must sniff as an image. A request from this computer (`local`: loopback, not through a proxy or tunnel, and not from a web page, `fromBrowser`) may name a private address, since its sender reaches it already and a local agent may serve its images on localhost; one with a gateway key from elsewhere may not. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch, and an image the vendor itself answers by URL is downloaded as before (`FetchImage` with the gateway's client).
- A URL magpie downloads but didn't choose itself is downloaded from public addresses only, wherever the request came from ([`image_fetch_guard.go`](../../internal/gateway/image_fetch_guard.go)). That is an image a caller names (an `/v1/images/edits` or `/v1/images/generations` reference image, for an images API that takes files, Gemini's own API or Code Assist: `fetchPicture` in [`draw.go`](../../internal/gateway/draw.go), `publicClient`), a page `web_fetch` reads (`webFetchClient`), and an image or video a vendor answers by URL, which what the model was asked to draw or do can steer (the inline download for a `b64_json` caller in `draw.go` and `/v1/videos/{id}/content` in [`video.go`](../../internal/gateway/video.go), `vendorClient`; generate_image's own download in [`internal/imagemcp`](../../internal/imagemcp/imagemcp.go), `PublicClient`). Every address the host resolves to must be public (`publicAddr`: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one), and the request goes to the address checked, so a name that resolves elsewhere the second time changes nothing; a direct connection is checked again on the address dialled (`guardDialer`). Through a proxy the proxy is sent that address, never the name (an `https://` CONNECT or SOCKS keeps the name for TLS and Host; a plain `http://` URL through an HTTP proxy is asked for by the address in Host too). Each redirect, up to 5, is checked the same, and a caller's image must sniff as an image. A request from this computer gets nothing more: a reverse proxy or relay in front of magpie on the same host makes every request it carries arrive from loopback, so where a request came from is never a reason to reach a private address. Two things are: settings.json's `fetchPrivate` (`settings.FetchPrivate`, none by default, no Settings page, this computer's own and never brought by a sync or restore), a list of names, `name:port`s, IPs and CIDR ranges the user lets magpie download from (`allowFor`; a settings.json that can't be read lets nothing extra in), and for a vendor's URL the `host:port` of that provider's own endpoints, which the user named themselves (a provider on the LAN that serves its images from itself). A vendor's image that can't be downloaded is answered by its URL, never dropped; its video is a 502 naming why. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch.
## Verification
@@ -711,7 +711,7 @@ go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEac
go test -tags nogui ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow|TestRelayInputCap|TestEveryVendorsOverflow'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestBedrock'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer|TestFetchPrivateEntries|TestVendorImageURLAtPrivateAddress|TestVideoContentAtPrivateAddress'
go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
node --test internal/gui/tests/disabled-models.test.cjs
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs'
+2 -1
View File
@@ -36,7 +36,8 @@ those back from this computer's settings whenever a sync, a join, a Restore,
an Undo or a backup file brings settings in, and `hashes` blanks them, so
changing one is no change to push. They are: the window's size and whether it
was maximised, the fonts, the proxy, the gateway's port, sharing on the local
network (`LAN`) and the addresses let in to it (`AllowIPs`), the Dock, gateway
network (`LAN`) and the addresses let in to it (`AllowIPs`), the private
hosts magpie may download from (`FetchPrivate`), the Dock, gateway
mode, keeping awake, lightweight windows, WSL lookups, account discovery, when
allowances are read, recording gateway conversations, the Mac terminal a
session resumes in (`SessionTerminal`) and what the menu bar shows. Launch at
+9 -12
View File
@@ -431,7 +431,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
return
}
call.Provider, call.To = p.ID, provider.Chat
ctx, cancel := context.WithTimeout(withPrivateFetch(r.Context(), r), drawTimeout)
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
defer cancel()
// the account that drew, or refused last, is the one recorded
var (
@@ -481,15 +481,16 @@ func (s *Server) images(edit bool) http.HandlerFunc {
}
s.record(call)
// asked for the image itself, one the vendor keeps at a URL is
// fetched the way the vendor was reached: through its proxy, by
// the client that just had its answer (#1576: the 4K image a relay
// drew in 40 s was lost to generate_image's own download). One
// fetched through the vendor's proxy (#1576: the 4K image a relay
// drew in 40 s was lost to generate_image's own download), from
// public addresses or the vendor's own host only: the URL is in
// its answer, which the request can steer (vendorClient). One
// that can't be fetched is answered by its URL all the same, never
// dropped: it is drawn, and paid for.
data := make([]map[string]any, 0, len(out.Images))
for _, im := range out.Images {
if im.URL != "" && inline(d.Want) {
if b, mt, err := FetchImage(p.Via(r.Context()), s.client, im.URL); err == nil {
if b, mt, err := FetchImage(p.Via(r.Context()), vendorClient(p), im.URL); err == nil {
im = picture{Mime: mt, Data: b}
} else if s.debug {
log.Printf("images: %s's image at %s is answered by its URL: %v", p.ID, im.URL, err)
@@ -1273,14 +1274,10 @@ func readImagesAnswer(p provider.Provider, url string, b []byte, code int) (draw
// fetchPicture downloads an image an edit was given by URL, for an images
// API that takes only files. The URL is the caller's: it is fetched from
// public addresses only (publicClient), but for a request from this
// computer (withPrivateFetch), and what comes must be an image.
// public addresses only (publicClient), from wherever the request came,
// and what comes must be an image.
func (s *Server) fetchPicture(ctx context.Context, url string) ([]byte, string, error) {
c := publicClient
if privateFetchAllowed(ctx) {
c = s.client
}
b, _, err := FetchImage(ctx, c, url)
b, _, err := FetchImage(ctx, publicClient, url)
if err != nil {
return nil, "", fmt.Errorf("couldn't fetch the image at %s: %v", url, err)
}
+68 -2
View File
@@ -43,7 +43,9 @@ func (f *fileProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.asked = append(f.asked, r.URL.String())
f.mu.Unlock()
b, ok := f.files[r.URL.Path]
if r.URL.Host != "files.test" || !ok {
// the image's URL comes to the proxy pinned to the public address
// files.test was checked at (publicTransport)
if r.URL.Host != filesAddr || !ok {
w.WriteHeader(404)
return
}
@@ -57,6 +59,9 @@ func (f *fileProxy) got() []string {
return append([]string(nil), f.asked...)
}
// filesAddr is the public address files.test resolves to in these tests.
const filesAddr = "93.184.216.34:80"
// relayed is a gateway whose provider "relay" answers images with URLs on
// files.test, a host reached only through the provider's own proxy.
func relayed(t *testing.T, vendor http.HandlerFunc) (*Server, *fileProxy) {
@@ -76,6 +81,7 @@ func relayed(t *testing.T, vendor http.HandlerFunc) (*Server, *fileProxy) {
if err := catalog.SaveLive("relay", up.URL+"/v1", []catalog.Model{{ID: "gpt-image-2.5-sunburst"}}); err != nil {
t.Fatal(err)
}
resolveTo(t, map[string]string{"files.test": "93.184.216.34"})
return New(), px
}
@@ -118,7 +124,7 @@ func TestImageByURLIsFetchedForB64Caller(t *testing.T) {
if b, _ := base64.StdEncoding.DecodeString(a.Data[0].B64); !bytes.Equal(b, big) {
t.Fatalf("got %d bytes of %d", len(b), len(big))
}
if got := px.got(); len(got) != 1 || got[0] != "http://files.test/4k.png" {
if got := px.got(); len(got) != 1 || got[0] != "http://"+filesAddr+"/4k.png" {
t.Fatalf("the provider's proxy was asked %v", got)
}
if strings.Contains(asked[0], "response_format") {
@@ -197,3 +203,63 @@ func TestSizeOf(t *testing.T) {
}
}
}
// The URL a vendor answers an image with is in the vendor's answer, and
// what the model was steered to draw or do can steer it: one on this
// computer or its network is answered by URL, never downloaded and handed
// back as the image. The vendor's own host:port, which the user named
// themselves, is downloaded from.
func TestVendorImageURLAtPrivateAddressNotFetched(t *testing.T) {
fresh(t)
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
t.Setenv(k, "")
}
inside, hits := secret(t, string(pngBytes))
resolveTo(t, map[string]string{"inside.test": "127.0.0.1"})
_, port, _ := strings.Cut(strings.TrimPrefix(inside.URL, "http://"), ":")
var next sync.Mutex
answer := ""
var up *httptest.Server
up = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/files/own.png" {
w.Write(pngBytes)
return
}
next.Lock()
u := answer
next.Unlock()
io.WriteString(w, `{"created":1,"data":[{"url":"`+u+`"}]}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-image-2.5-sunburst"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("relay", up.URL+"/v1", []catalog.Model{{ID: "gpt-image-2.5-sunburst"}}); err != nil {
t.Fatal(err)
}
s := New()
draw := func(u string) fetchedAnswer {
t.Helper()
next.Lock()
answer = u
next.Unlock()
code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-2.5-sunburst","prompt":"a city","response_format":"b64_json"}`)
var a fetchedAnswer
json.Unmarshal([]byte(raw), &a)
if code != 200 || len(a.Data) != 1 {
t.Fatalf("%s: %d %.300s", u, code, raw)
}
return a
}
for _, u := range []string{inside.URL + "/admin.png", "http://inside.test:" + port + "/admin.png", "http://[::ffff:127.0.0.1]:" + port + "/admin.png"} {
if a := draw(u); a.Data[0].URL != u || a.Data[0].B64 != "" {
t.Fatalf("%s was answered %+v", u, a.Data[0])
}
}
if hits.Load() != 0 {
t.Fatalf("the private service was asked %d times", hits.Load())
}
if a := draw(up.URL + "/files/own.png"); a.Data[0].URL != "" || a.Data[0].B64 != base64.StdEncoding.EncodeToString(pngBytes) {
t.Fatalf("the vendor's own file: %+v", a.Data[0])
}
}
+148 -56
View File
@@ -14,22 +14,29 @@ import (
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// An image a caller names by URL (an edit's, or one to draw from) is
// downloaded by magpie itself for a vendor that takes only the bytes. The
// URL is the caller's, so the download goes only to public addresses:
// never to this computer (loopback), the user's own network (RFC 1918,
// fc00::/7), link-local addresses (169.254/16 with the cloud metadata
// service, fe80::/10), CGNAT (100.64/10, Tailscale's), or the other
// special ranges below — through any redirect too. Otherwise a gateway
// key's holder could have magpie read a service only this computer
// reaches and get its answer back as the "image".
// A URL magpie didn't choose itself is downloaded only from public
// addresses: an image a caller names (an edit's, or one to draw from) for
// a vendor that takes only the bytes, an image or video a vendor answers
// with (its URL may come from what the model was steered to say), and a
// page web_fetch reads. Never from this computer (loopback), the user's
// own network (RFC 1918, fc00::/7), link-local addresses (169.254/16 with
// the cloud metadata service, fe80::/10), CGNAT (100.64/10, Tailscale's),
// or the other special ranges below — through any redirect too. Otherwise
// whoever can send magpie a request could have it read a service only
// this computer reaches and get its answer back as the "image".
//
// A request from this computer itself (local: loopback, not through a
// proxy or tunnel, not from a web page) may name a private address: its
// sender reaches every one of them already, and a local agent's images
// may well be served on localhost.
// Where the request came from changes nothing: one that reaches magpie
// on loopback may well be a reverse proxy's or a relay's on the same
// machine, passing on someone else's. Two exceptions, both named by the
// user rather than guessed:
// - settings.json's fetchPrivate: hosts (name or name:port), addresses
// and CIDR ranges the user lets these downloads reach;
// - a vendor's answer may name its own host and port (a provider the
// user set up on localhost or their network serves its images there).
//
// How it holds:
// - the host is resolved, and every address it resolves to must be
@@ -49,25 +56,88 @@ import (
// through.
const imageRedirects = 5
type mayFetchPrivate struct{}
// errPrivateAddress is a URL that leads somewhere other than the public
// internet.
var errPrivateAddress = errors.New(`it is at a private address, which magpie doesn't download from: send the image itself (a data: URL or a file) instead, or name the host in settings.json's "fetchPrivate"`)
// withPrivateFetch is ctx for a request whose image URLs may name private
// addresses: one from this computer.
func withPrivateFetch(ctx context.Context, r *http.Request) context.Context {
if local(r) && !fromBrowser(r) {
return context.WithValue(ctx, mayFetchPrivate{}, true)
// fetchAllow is where a download may go beyond public addresses: the
// user's fetchPrivate, and the hosts a transport was made for.
type fetchAllow struct {
hosts map[string]bool // "name" (any port) or "name:port", lower case
nets []netip.Prefix
}
// allowFor reads fetchPrivate, and adds also. A settings.json that can't
// be read is unknown, so it allows nothing of its own.
func allowFor(also []string) fetchAllow {
a := fetchAllow{hosts: map[string]bool{}}
var list []string
if st, err := settings.LoadChecked(); err == nil {
list = st.FetchPrivate
}
return ctx
for _, e := range append(list, also...) {
e = strings.ToLower(strings.TrimSpace(e))
if e == "" {
continue
}
if p, err := netip.ParsePrefix(e); err == nil {
a.nets = append(a.nets, p.Masked())
} else if ip, err := netip.ParseAddr(strings.Trim(e, "[]")); err == nil {
a.nets = append(a.nets, netip.PrefixFrom(ip.Unmap(), ip.Unmap().BitLen()))
} else {
a.hosts[e] = true
}
}
return a
}
func privateFetchAllowed(ctx context.Context) bool {
ok, _ := ctx.Value(mayFetchPrivate{}).(bool)
return ok
// addr says a may be fetched from: public, or in a range the user named.
func (a fetchAllow) addr(ip netip.Addr) bool {
if publicAddr(ip) {
return true
}
for _, n := range a.nets {
if n.Contains(ip.Unmap()) {
return true
}
}
return false
}
// errPrivateAddress is a caller's image URL that leads somewhere other
// than the public internet.
var errPrivateAddress = errors.New("it is at a private address, which magpie downloads from only for a request from this computer: send the image itself (a data: URL or a file) instead")
// host says host:port was named itself, so whatever it resolves to may be
// fetched from.
func (a fetchAllow) host(host, port string) bool {
host = strings.ToLower(strings.Trim(host, "[]"))
return a.hosts[host] || a.hosts[net.JoinHostPort(host, port)]
}
// hostOf is u's host and port as fetchAllow names it, "" for none.
func hostOf(u string) string {
p, err := url.Parse(strings.TrimSpace(u))
if err != nil || p.Hostname() == "" {
return ""
}
port := p.Port()
if port == "" {
port = map[string]string{"http": "80", "https": "443"}[p.Scheme]
}
if port == "" {
return ""
}
return net.JoinHostPort(strings.ToLower(p.Hostname()), port)
}
// vendorClient downloads what a vendor answered with by URL: from public
// addresses, and the hosts its own endpoints are at.
func vendorClient(p provider.Provider) *http.Client {
var own []string
for _, u := range []string{p.Chat, p.Responses, p.Anthropic, p.Gemini} {
if h := hostOf(u); h != "" {
own = append(own, h)
}
}
return guardedClient(own...)
}
// lookupIP resolves a host for a caller's image; a test swaps it.
var lookupIP = func(ctx context.Context, host string) ([]netip.Addr, error) {
@@ -125,24 +195,30 @@ func publicAddr(a netip.Addr) bool {
return true
}
// privateDialer dials only public addresses, checked on the address the
// guardDialer dials only addresses ok allows, checked on the address the
// socket is about to connect to.
var privateDialer = &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
Control: func(_, address string, _ syscall.RawConn) error {
ap, err := netip.ParseAddrPort(address)
if err != nil || !publicAddr(ap.Addr()) {
return errPrivateAddress
}
return nil
},
func guardDialer(ok func(netip.Addr) bool) *net.Dialer {
return &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
Control: func(_, address string, _ syscall.RawConn) error {
ap, err := netip.ParseAddrPort(address)
if err != nil || !ok(ap.Addr()) {
return errPrivateAddress
}
return nil
},
}
}
// publicTransport sends a request to a public address only (see above).
type publicTransport struct{}
// privateDialer dials only public addresses.
var privateDialer = guardDialer(publicAddr)
func (publicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// publicTransport sends a request to a public address only (see above), or
// one fetchPrivate or also names.
type publicTransport struct{ also []string }
func (pt publicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
return nil, fmt.Errorf("%s isn't an http(s) URL", req.URL.Redacted())
}
@@ -165,15 +241,17 @@ func (publicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if len(addrs) == 0 {
return nil, fmt.Errorf("%s resolves to no address", host)
}
for _, a := range addrs {
if !publicAddr(a) {
return nil, errPrivateAddress
}
}
port := req.URL.Port()
if port == "" {
port = map[string]string{"http": "80", "https": "443"}[req.URL.Scheme]
}
allow := allowFor(pt.also)
named := allow.host(host, port)
for _, a := range addrs {
if !named && !allow.addr(a) {
return nil, errPrivateAddress
}
}
var tc *tls.Config
if upstreamTLS != nil {
tc = upstreamTLS.Clone()
@@ -190,7 +268,10 @@ func (publicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
ResponseHeaderTimeout: 2 * time.Minute,
}
if proxy == nil {
t.DialContext = privateDialer.DialContext
pinned := addrs[0].Unmap()
t.DialContext = guardDialer(func(a netip.Addr) bool {
return allow.addr(a) || named && a.Unmap() == pinned
}).DialContext
}
out := req.Clone(req.Context())
out.URL.Host = net.JoinHostPort(addrs[0].Unmap().String(), port)
@@ -208,14 +289,25 @@ func (publicTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return t.RoundTrip(out)
}
// publicClient downloads a caller's image: from public addresses only,
// through at most imageRedirects redirects, each checked the same.
var publicClient = &http.Client{
Transport: publicTransport{},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) > imageRedirects {
return fmt.Errorf("it redirects more than %d times", imageRedirects)
}
return nil
},
// publicClient downloads a URL magpie didn't choose: from public
// addresses only (and fetchPrivate's), through at most imageRedirects
// redirects, each checked the same.
var publicClient = guardedClient()
// PublicClient is publicClient, for a download outside the gateway of a
// URL magpie didn't choose (generate_image's of a vendor's image).
func PublicClient() *http.Client { return publicClient }
// guardedClient is publicClient that also reaches also's hosts
// ("name:port").
func guardedClient(also ...string) *http.Client {
return &http.Client{
Transport: publicTransport{also: also},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) > imageRedirects {
return fmt.Errorf("it redirects more than %d times", imageRedirects)
}
return nil
},
}
}
+73 -11
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"net/netip"
"os"
"strings"
"sync"
"sync/atomic"
@@ -149,25 +150,35 @@ func TestEditImageURLThroughProxyIsPinnedAndRedirectsChecked(t *testing.T) {
}
}
// A request from this computer may name an image on it (a local agent's
// own server): its sender reaches it anyway. A web page's request, or one
// come through a tunnel, may not. What is downloaded must be an image.
// Where a request came from gives it nothing: one from this computer is
// also what a reverse proxy or relay in front of magpie on the same host
// sends for anyone it serves, so it may not name a private address either.
// Only the user's own settings.json "fetchPrivate" lets one in, and what
// is then downloaded must still be an image.
func TestEditImageURLFromThisComputer(t *testing.T) {
s, e := easeled(t)
srv, hits := secret(t, string(pngBytes))
local := func(r *http.Request) { r.RemoteAddr = "127.0.0.1:50000" }
if code, raw := editFrom(t, s, srv.URL+"/img.png", local); code != 200 || hits.Load() != 1 || len(e.got("/v1/images/edits")) != 1 {
t.Fatalf("a local agent's image: %d %s", code, raw)
}
for name, edit := range map[string]func(*http.Request){
"tunnel": func(r *http.Request) { local(r); r.Header.Set("X-Forwarded-For", "203.0.113.9") },
"page": func(r *http.Request) { local(r); r.Header.Set("Sec-Fetch-Mode", "cors") },
"this computer": local,
"a reverse proxy here": func(r *http.Request) {
local(r)
r.Header.Set("X-Forwarded-For", "203.0.113.9")
},
"[::1]": func(r *http.Request) { r.RemoteAddr = "[::1]:50000" },
} {
editFrom(t, s, srv.URL+"/img.png", edit)
if hits.Load() != 1 {
t.Fatalf("%s: the private service was asked %d times", name, hits.Load())
if code, raw := editFrom(t, s, srv.URL+"/img.png", edit); code != 400 || !strings.Contains(raw, "private address") || !strings.Contains(raw, "fetchPrivate") {
t.Fatalf("%s: %d %s", name, code, raw)
}
}
if hits.Load() != 0 || len(e.got("/v1/images/edits")) != 0 {
t.Fatalf("the private service was asked %d times", hits.Load())
}
allowPrivate(t, "127.0.0.1")
if code, raw := editFrom(t, s, srv.URL+"/img.png", local); code != 200 || hits.Load() != 1 || len(e.got("/v1/images/edits")) != 1 {
t.Fatalf("named in fetchPrivate: %d %s", code, raw)
}
json, _ := secret(t, `{"admin_token":"s3cret"}`)
code, raw := editFrom(t, s, json.URL+"/status", local)
if code != 400 || !strings.Contains(raw, "isn't an image") || strings.Contains(raw, "s3cret") || len(e.got("/v1/images/edits")) != 1 {
@@ -175,6 +186,57 @@ func TestEditImageURLFromThisComputer(t *testing.T) {
}
}
// allowPrivate writes the user's settings.json "fetchPrivate" for the test.
func allowPrivate(t *testing.T, entries ...string) {
t.Helper()
was := settings.Load()
st := was
st.FetchPrivate = entries
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { settings.Save(was) })
}
// fetchPrivate's entries are a name, name:port, an IP or a range; a
// settings.json that can't be read lets nothing extra in.
func TestFetchPrivateEntries(t *testing.T) {
allowPrivate(t, "nas.lan", "box.lan:8080", "10.1.2.3", "192.168.7.0/24", "fd00::/8", " ", "not a range/99")
a := allowFor([]string{"vendor.lan:9000"})
for _, c := range []struct {
host, port string
ok bool
}{
{"nas.lan", "443", true}, {"NAS.lan", "80", true}, {"box.lan", "8080", true}, {"box.lan", "80", false},
{"vendor.lan", "9000", true}, {"vendor.lan", "9001", false}, {"other.lan", "80", false},
} {
if a.host(c.host, c.port) != c.ok {
t.Errorf("host %s:%s: %v", c.host, c.port, !c.ok)
}
}
for ip, ok := range map[string]bool{
"10.1.2.3": true, "10.1.2.4": false, "192.168.7.200": true, "192.168.8.1": false,
"fd12::1": true, "127.0.0.1": false, "169.254.169.254": false, "8.8.8.8": true,
} {
if a.addr(netip.MustParseAddr(ip)) != ok {
t.Errorf("%s: %v", ip, !ok)
}
}
if err := os.WriteFile(settings.Path(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
a = allowFor(nil)
if a.host("nas.lan", "443") || a.addr(netip.MustParseAddr("10.1.2.3")) {
t.Fatal("an unreadable settings.json let a private host in")
}
if got := hostOf("http://Box.lan/x"); got != "box.lan:80" {
t.Fatalf("hostOf: %q", got)
}
if got := hostOf("https://[fd00::1]/v1"); got != "[fd00::1]:443" {
t.Fatalf("hostOf: %q", got)
}
}
// The dialler checks the address it connects to, whatever name led there.
func TestPrivateDialerRefusesPrivateAddresses(t *testing.T) {
srv, hits := secret(t, "")
+3 -1
View File
@@ -1049,7 +1049,9 @@ func (s *Server) videosContent(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, 502, err.Error())
return
}
res, err := s.client.Do(req)
// the URL is in the vendor's answer, so it is fetched as one a caller
// names is: public addresses, or the vendor's own host (vendorClient)
res, err := vendorClient(p).Do(req)
if err != nil {
writeError(w, provider.Chat, 502, fmt.Sprintf("the video couldn't be fetched: %v", err))
return
+38
View File
@@ -621,3 +621,41 @@ func TestVideoSecondsAndResolutionAsAsked(t *testing.T) {
t.Errorf("1080p on 1.5: %v", sent)
}
}
// The video's URL is in the vendor's answer: one on this computer or its
// network is not downloaded and streamed back as the video, unless the
// user's settings.json "fetchPrivate" names it.
func TestVideoContentAtPrivateAddressNotFetched(t *testing.T) {
grokSignedIn(t)
inside, hits := secret(t, "secret-bytes")
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/v1/videos/generations":
io.WriteString(w, `{"request_id":"req-1"}`)
case "/v1/videos/req-1":
io.WriteString(w, `{"status":"done","progress":100,"model":"grok-imagine-video","video":{"url":"`+inside.URL+`/admin.mp4","duration":6}}`)
default:
w.WriteHeader(404)
}
}))
t.Cleanup(up.Close)
was := provider.GrokBase
provider.GrokBase = up.URL + "/v1"
t.Cleanup(func() { provider.GrokBase = was })
s := New()
_, obj, raw, _ := request(t, s, "POST", "/v1/videos", "application/json", `{"model":"grok/grok-imagine-video","prompt":"a kite"}`)
id, _ := obj["id"].(string)
if id == "" {
t.Fatalf("%s", raw)
}
code, _, raw, _ := request(t, s, "GET", "/v1/videos/"+id+"/content", "", "")
if code == 200 || strings.Contains(string(raw), "secret-bytes") || hits.Load() != 0 {
t.Fatalf("%d %s, the private service asked %d times", code, raw, hits.Load())
}
allowPrivate(t, "127.0.0.1")
code, _, raw, _ = request(t, s, "GET", "/v1/videos/"+id+"/content", "", "")
if code != 200 || string(raw) != "secret-bytes" || hits.Load() != 1 {
t.Fatalf("named in fetchPrivate: %d %s", code, raw)
}
}
+1
View File
@@ -1196,6 +1196,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.Port = cur.Port // set on its own (port below), which moves the gateway
in.CORSOrigins = cur.CORSOrigins // set on its own (cors below)
in.AllowIPs = cur.AllowIPs // set on its own (allowips below)
in.FetchPrivate = cur.FetchPrivate // in settings.json only
in.GitHubToken = cur.GitHubToken // set on its own (github-token below), never sent to the page
in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own
in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only
+1
View File
@@ -141,6 +141,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
Port: 3591,
CORSOrigins: []string{"http://localhost:3000"},
AllowIPs: []string{"203.0.113.7"},
FetchPrivate: []string{"nas.lan"},
GitHubToken: "ghp_kept",
RequestArchive: true,
RequestArchiveMaxMB: 64,
+47
View File
@@ -18,6 +18,7 @@ import (
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/settings"
)
// fourK is a real 3840x2160 PNG of about the size #1576's relay sent
@@ -107,6 +108,19 @@ func (c *client) await(args map[string]any) (map[string]any, string) {
return nil, ""
}
// fetchLocal lets these tests' vendor, a server on this computer, be
// downloaded from: the user's fetchPrivate naming loopback.
func fetchLocal(t *testing.T) {
t.Helper()
was := settings.Load()
st := was
st.FetchPrivate = []string{"127.0.0.1"}
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { settings.Save(was) })
}
func shorterWaits(t *testing.T, stall time.Duration) {
wasWithin, wasStall := answerWithin, gateway.ImageStall
answerWithin, gateway.ImageStall = 200*time.Millisecond, stall
@@ -126,6 +140,7 @@ func TestFourKImageByURLIsSaved(t *testing.T) {
}
t.Logf("the 4K PNG is %.1f MB", float64(len(big))/(1<<20))
shorterWaits(t, time.Second)
fetchLocal(t)
files := httptest.NewServer(slowFile(big, 100*time.Millisecond, 0)) // ~4 s in all
t.Cleanup(files.Close)
g := &urlGateway{urls: []string{files.URL + "/4k.png"}}
@@ -173,6 +188,7 @@ func TestFourKImageAsB64IsSaved(t *testing.T) {
func TestStalledDownloadSaysWhereTheImageIs(t *testing.T) {
big := fourK()
shorterWaits(t, 300*time.Millisecond)
fetchLocal(t)
stuck := httptest.NewServer(slowFile(big, 0, 3<<20))
t.Cleanup(stuck.Close)
fine := httptest.NewServer(slowFile(big, 0, 0))
@@ -194,3 +210,34 @@ func TestStalledDownloadSaysWhereTheImageIs(t *testing.T) {
t.Fatalf("saved %d bytes of %d", len(b), len(big))
}
}
// The URL an image is answered by is the vendor's, and what the model was
// steered to draw can steer it: one on this computer or its network is
// not downloaded unless the user's fetchPrivate names it, and the answer
// says where the image is.
func TestVendorImageAtPrivateAddressNotFetched(t *testing.T) {
shorterWaits(t, time.Second)
var hits sync.Mutex
n := 0
inside := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Lock()
n++
hits.Unlock()
w.Write([]byte("\x89PNG\r\n\x1a\n secret"))
}))
t.Cleanup(inside.Close)
project := t.TempDir()
c := initialized(t, &urlGateway{urls: []string{inside.URL + "/admin.png"}}, project)
r, out := c.await(map[string]any{"prompt": "a city", "path": "city.png"})
if r["isError"] != true || !strings.Contains(out, "private address") || !strings.Contains(out, inside.URL+"/admin.png") {
t.Fatalf("%v: %s", r["isError"], out)
}
hits.Lock()
defer hits.Unlock()
if n != 0 {
t.Fatalf("the private server was asked %d times", n)
}
if _, err := os.Stat(filepath.Join(project, "city.png")); err == nil {
t.Fatal("something was saved")
}
}
+1 -1
View File
@@ -459,7 +459,7 @@ func (s *server) generate(raw json.RawMessage) (string, error) {
continue
}
case d.URL != "":
if img, mt, err = gateway.FetchImage(context.Background(), http.DefaultClient, d.URL); err != nil {
if img, mt, err = gateway.FetchImage(context.Background(), gateway.PublicClient(), d.URL); err != nil {
lost = append(lost, fmt.Sprintf("image %d was drawn but couldn't be downloaded (%v); the vendor keeps it at %s for a while: download it from there", i+1, err, d.URL))
continue
}
+9
View File
@@ -117,6 +117,14 @@ type Settings struct {
// its place (gateway.AllowIPs). This computer's own (KeepOwn), as LAN
// is: the addresses are of the network this computer is on.
AllowIPs []string `json:"allowIPs,omitempty"`
// FetchPrivate are the private hosts and ranges (a name, name:port, an
// IP or a CIDR range) magpie may download a URL from that it didn't
// choose itself: an image or video a request names or a vendor answers
// with, or a page web_fetch reads. None by default: such a URL is
// downloaded from public addresses only, whoever sent the request and
// from wherever (gateway.publicClient). In settings.json only; it names
// this computer's own network, so it isn't synced (KeepOwn).
FetchPrivate []string `json:"fetchPrivate,omitempty"`
// Port is the gateway's port on this computer, 0 for DefaultPort.
// MAGPIE_ADDR, where it is set, comes first (GatewayAddr).
Port int `json:"port,omitempty"`
@@ -943,6 +951,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.QuotaReads = cur.QuotaReads
s.NoAccountDiscovery = cur.NoAccountDiscovery
s.LAN, s.AllowIPs = cur.LAN, cur.AllowIPs
s.FetchPrivate = cur.FetchPrivate
s.SessionTerminal = cur.SessionTerminal
}