Files
magpie/internal/gateway/image_fetch_guard_test.go
T
yetone 5241de909a gateway: an image URL a caller sends is downloaded only from public addresses
An images request (/v1/images/edits, /v1/images/generations) may name a
reference image by URL. For a model that takes the image as bytes (an
images API's multipart edit, Gemini's own API, Code Assist), magpie
downloaded the URL itself with the gateway's client, to any address and
through any redirect, and sent what came to the vendor as the image.

fetchPicture, the one place a caller's URL is downloaded (all three draw
paths go through it), now uses publicClient (image_fetch_guard.go):
- the host is resolved and every address must be public (publicAddr:
  not loopback, RFC 1918, fc00::/7, link-local incl. 169.254.169.254,
  CGNAT 100.64/10, unspecified, multicast, documentation/reserved
  ranges, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one);
- the request is pinned to the address checked (Host and TLS
  ServerName keep the name), so a name resolving differently later
  changes nothing; a direct dial is checked again in the dialer's
  Control on the address actually connected;
- through a proxy (magpie's, the provider's, the system's) the proxy is
  chosen by the name and sent the pinned address (CONNECT or SOCKS);
  a plain http:// URL through an HTTP proxy is asked for by address in
  Host too, since Go writes the absolute URI from Host;
- redirects (at most 5) go through the same transport; only http(s);
  no keep-alives; the existing 64 MB / stall / 5-minute limits stay;
- what comes back must sniff as image/*, else 400 without the body.

Policy: a request from this computer (local(): loopback, no proxy or
tunnel headers, and not fromBrowser) keeps downloading from anywhere,
since its sender reaches those addresses already and a local agent may
serve images on localhost. Everyone else, a gateway key's holder
included, is held to public addresses. Vendor-returned image URLs
(FetchImage for b64_json, imagemcp, video content) are unchanged: they
are the vendor's, not the caller's. No other gateway path downloads a
caller's URL: chat/Responses/Anthropic/Gemini image URLs are passed on
for the vendor to fetch. Documented in docs/subsystems/gateway-routing.md.

Run:
- go test -race -count=3 -run 'PublicAddr|EditImageURL|PrivateDialer'
- broke by hand, each went red: old client in fetchPicture (all three
  e2e tests), no Unmap (::ffff:100.64.0.1), no pinning (proxy test
  sees the name), no resolve check (redirect to 192.168.1.10 through
  the proxy served), no dialer check, no image sniff, browser allowed
- go test -tags nogui ./internal/gateway/... (full)
- gofmt -l; go vet -tags nogui for darwin, GOOS=linux, GOOS=windows
- not tried: an https:// image through a real HTTP or SOCKS proxy
2026-10-13 18:15:06 +08:00

194 lines
6.9 KiB
Go

package gateway
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/settings"
)
func TestPublicAddr(t *testing.T) {
for s, want := range map[string]bool{
"127.0.0.1": false, "127.9.9.9": false, "10.1.2.3": false, "172.16.0.1": false,
"192.168.1.1": false, "169.254.169.254": false, "100.64.0.1": false, "100.100.100.100": false,
"0.0.0.0": false, "224.0.0.1": false, "255.255.255.255": false,
"::1": false, "::": false, "::ffff:127.0.0.1": false, "::ffff:10.0.0.1": false,
"::ffff:169.254.169.254": false, "::ffff:100.64.0.1": false, "fe80::1": false, "fc00::1": false, "fd12::1": false,
"ff02::1": false, "64:ff9b::7f00:1": false, "2002:7f00:1::": false, "::7f00:1": false,
"8.8.8.8": true, "93.184.216.34": true, "::ffff:8.8.8.8": true, "2606:4700::1111": true,
"64:ff9b::808:808": true,
} {
if got := publicAddr(netip.MustParseAddr(s)); got != want {
t.Errorf("publicAddr(%s) = %v, want %v", s, got, want)
}
}
}
// secret is a service only this computer reaches; what it was asked is
// counted.
func secret(t *testing.T, body string) (*httptest.Server, *atomic.Int32) {
t.Helper()
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
io.WriteString(w, body)
}))
t.Cleanup(srv.Close)
return srv, &hits
}
func editFrom(t *testing.T, s *Server, url string, edit func(*http.Request)) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/images/edits", strings.NewReader(`{"model":"art/gpt-image-1","prompt":"make it blue","image":"`+url+`"}`))
req.Header.Set("Content-Type", "application/json")
if edit != nil {
edit(req)
}
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
func resolveTo(t *testing.T, names map[string]string) {
t.Helper()
was := lookupIP
lookupIP = func(_ context.Context, host string) ([]netip.Addr, error) {
if a, ok := names[host]; ok {
return []netip.Addr{netip.MustParseAddr(a)}, nil
}
return was(context.Background(), host)
}
t.Cleanup(func() { lookupIP = was })
}
// An image URL a caller sends to be edited is downloaded by magpie for an
// images API that takes files only. From another computer (a gateway
// key's holder) it is never downloaded from this computer or its network,
// however the URL names it.
func TestEditImageURLNotFetchedFromPrivateAddresses(t *testing.T) {
s, e := easeled(t)
srv, hits := secret(t, string(pngBytes))
port := srv.URL[strings.LastIndex(srv.URL, ":")+1:]
resolveTo(t, map[string]string{"inside.test": "127.0.0.1", "nat64.test": "64:ff9b::7f00:1"})
for _, u := range []string{
srv.URL + "/img.png",
"http://localhost:" + port + "/img.png",
"http://[::1]:" + port + "/img.png",
"http://[::ffff:127.0.0.1]:" + port + "/img.png",
"http://inside.test:" + port + "/img.png",
"http://nat64.test:" + port + "/img.png",
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.1/img.png",
"http://0.0.0.0:" + port + "/img.png",
} {
code, raw := editFrom(t, s, u, nil)
if code != 400 || !strings.Contains(raw, "private address") {
t.Errorf("%s: %d %s", u, code, raw)
}
}
if n := hits.Load(); n != 0 {
t.Fatalf("the private service was asked %d times", n)
}
if sent := e.got("/v1/images/edits"); len(sent) != 0 {
t.Fatalf("the vendor was sent %d edits", len(sent))
}
}
// Through a proxy the dialler can't see where it goes: the proxy is sent
// the address that was checked, never the name, and a redirect to a
// private address is refused before it is asked for.
func TestEditImageURLThroughProxyIsPinnedAndRedirectsChecked(t *testing.T) {
s, e := easeled(t)
srv, hits := secret(t, string(pngBytes))
var mu sync.Mutex
var asked []string
seen := func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), asked...) }
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.URL.String()+" Host="+r.Host)
mu.Unlock()
switch r.URL.Path {
case "/img.png":
w.Write(pngBytes)
case "/hop":
http.Redirect(w, r, srv.URL+"/img.png", http.StatusFound)
case "/far":
http.Redirect(w, r, "http://inside.test/img.png", http.StatusFound)
}
}))
t.Cleanup(proxy.Close)
st := settings.Load()
st.Proxy = proxy.URL
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
resolveTo(t, map[string]string{"pics.test": "93.184.216.34", "inside.test": "192.168.1.10"})
code, raw := editFrom(t, s, "http://pics.test/img.png", nil)
if code != 200 || len(e.got("/v1/images/edits")) != 1 {
t.Fatalf("a public image: %d %s", code, raw)
}
if a := seen(); len(a) != 1 || a[0] != "http://93.184.216.34:80/img.png Host=93.184.216.34:80" {
t.Fatalf("the proxy was asked %q", a)
}
for _, u := range []string{"http://pics.test/hop", "http://pics.test/far"} {
if code, raw := editFrom(t, s, u, nil); code != 400 || !strings.Contains(raw, "private address") {
t.Errorf("%s: %d %s", u, code, raw)
}
}
if a := seen(); hits.Load() != 0 || len(a) != 3 {
t.Fatalf("private service asked %d times, proxy asked %q", hits.Load(), a)
}
}
// 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.
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") },
} {
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())
}
}
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 {
t.Fatalf("not an image: %d %s", code, raw)
}
}
// The dialler checks the address it connects to, whatever name led there.
func TestPrivateDialerRefusesPrivateAddresses(t *testing.T) {
srv, hits := secret(t, "")
for _, addr := range []string{srv.Listener.Addr().String(), "[::1]:9"} {
c, err := privateDialer.DialContext(context.Background(), "tcp", addr)
if err == nil {
c.Close()
}
if !errors.Is(err, errPrivateAddress) {
t.Errorf("%s: %v", addr, err)
}
}
if hits.Load() != 0 {
t.Fatal("the private service was asked")
}
}