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
This commit is contained in:
yetone
2026-10-13 18:15:06 +08:00
parent 6d7b440924
commit 5241de909a
4 changed files with 430 additions and 4 deletions
+2
View File
@@ -511,12 +511,14 @@ 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).
## Verification
```sh
go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestSub2APIThinkingOffRefused|TestRefusesThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer'
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'
+14 -4
View File
@@ -403,7 +403,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
w, d.Prompt, unmask = redactedPrompt(w, d.Prompt)
defer unmask()
call.Provider, call.To = p.ID, provider.Chat
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
ctx, cancel := context.WithTimeout(withPrivateFetch(r.Context(), r), drawTimeout)
defer cancel()
// the account that drew, or refused last, is the one recorded
drew, out, code, capBack, err := s.drawOnAccounts(ctx, r, p, model, d)
@@ -1163,13 +1163,23 @@ 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.
// 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.
func (s *Server) fetchPicture(ctx context.Context, url string) ([]byte, string, error) {
b, _, err := FetchImage(ctx, s.client, url)
c := publicClient
if privateFetchAllowed(ctx) {
c = s.client
}
b, _, err := FetchImage(ctx, c, url)
if err != nil {
return nil, "", fmt.Errorf("couldn't fetch the image at %s: %v", url, err)
}
return b, http.DetectContentType(b), nil
mt := http.DetectContentType(b)
if !strings.HasPrefix(mt, "image/") {
return nil, "", fmt.Errorf("couldn't use the image at %s: it isn't an image (it reads as %s)", url, mt)
}
return b, mt, nil
}
// inline says a response_format asks for the image itself.
+221
View File
@@ -0,0 +1,221 @@
package gateway
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"syscall"
"time"
"github.com/yetone/magpie/internal/netproxy"
)
// 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 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.
//
// How it holds:
// - the host is resolved, and every address it resolves to must be
// public; the request is then sent to the address checked (pinned),
// with the host kept for the Host header and TLS, so a name that
// resolves differently the second time (DNS rebinding) changes
// nothing;
// - a direct connection is checked again on the address actually
// dialled (privateDialer's Control);
// - through a proxy (magpie's, the provider's, the system's) the proxy
// is dialled, and it is sent the pinned address, never the name, so
// it can't resolve it to another (an https:// CONNECT, SOCKS, or a
// plain http:// request whose Host is then the address too);
// - each redirect goes through the same, at most imageRedirects of them.
// imageRedirects is how many redirects a caller's image URL is followed
// through.
const imageRedirects = 5
type mayFetchPrivate struct{}
// 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)
}
return ctx
}
func privateFetchAllowed(ctx context.Context) bool {
ok, _ := ctx.Value(mayFetchPrivate{}).(bool)
return ok
}
// 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")
// lookupIP resolves a host for a caller's image; a test swaps it.
var lookupIP = func(ctx context.Context, host string) ([]netip.Addr, error) {
return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
}
// specialNets are ranges no caller's image is fetched from beyond those
// net/netip names (loopback, private, link-local, multicast, unspecified).
var specialNets = func() []netip.Prefix {
var out []netip.Prefix
for _, s := range []string{
"0.0.0.0/8", // "this" network
"100.64.0.0/10", // CGNAT, Tailscale
"192.0.0.0/24", // IETF protocol assignments
"192.0.2.0/24", // documentation
"198.18.0.0/15", // benchmarking
"198.51.100.0/24", // documentation
"203.0.113.0/24", // documentation
"240.0.0.0/4", // reserved, broadcast
"::/96", // IPv4-compatible (deprecated)
"100::/64", // discard
"2001::/32", // Teredo
"2001:db8::/32", // documentation
"fec0::/10", // site-local (deprecated)
"64:ff9b:1::/48", // local-use NAT64
} {
out = append(out, netip.MustParsePrefix(s))
}
return out
}()
// publicAddr says a may be fetched a caller's image from.
func publicAddr(a netip.Addr) bool {
a = a.Unmap() // ::ffff:127.0.0.1 is 127.0.0.1
if !a.IsValid() || a.IsLoopback() || a.IsPrivate() || a.IsUnspecified() ||
a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() || a.IsInterfaceLocalMulticast() || a.IsMulticast() {
return false
}
for _, n := range specialNets {
if n.Contains(a) {
return false
}
}
if a.Is6() {
b := a.As16()
// an IPv4 address inside an IPv6 one: NAT64 (64:ff9b::/96) and
// 6to4 (2002::/16) reach it
if netip.MustParsePrefix("64:ff9b::/96").Contains(a) {
return publicAddr(netip.AddrFrom4([4]byte{b[12], b[13], b[14], b[15]}))
}
if b[0] == 0x20 && b[1] == 0x02 {
return publicAddr(netip.AddrFrom4([4]byte{b[2], b[3], b[4], b[5]}))
}
}
return true
}
// privateDialer dials only public addresses, 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
},
}
// publicTransport sends a request to a public address only (see above).
type publicTransport struct{}
func (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())
}
host := req.URL.Hostname()
if host == "" {
return nil, errors.New("the URL names no host")
}
// the proxy this request would take, as any other of magpie's: chosen
// by the name, before it is pinned to an address
proxy, err := netproxy.Func(req)
if err != nil {
return nil, err
}
var addrs []netip.Addr
if a, err := netip.ParseAddr(strings.TrimSuffix(strings.TrimPrefix(host, "["), "]")); err == nil {
addrs = []netip.Addr{a}
} else if addrs, err = lookupIP(req.Context(), host); err != nil {
return nil, err
}
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]
}
var tc *tls.Config
if upstreamTLS != nil {
tc = upstreamTLS.Clone()
} else {
tc = &tls.Config{}
}
tc.ServerName = host
t := &http.Transport{
Proxy: func(*http.Request) (*url.URL, error) { return proxy, nil },
TLSClientConfig: tc,
ForceAttemptHTTP2: true,
DisableKeepAlives: true,
TLSHandshakeTimeout: 30 * time.Second,
ResponseHeaderTimeout: 2 * time.Minute,
}
if proxy == nil {
t.DialContext = privateDialer.DialContext
}
out := req.Clone(req.Context())
out.URL.Host = net.JoinHostPort(addrs[0].Unmap().String(), port)
out.Host = req.Host
if out.Host == "" {
out.Host = req.URL.Host
}
// a plain http:// URL through an HTTP proxy is sent to it whole, its
// host taken from Host: the proxy would resolve the name again, so it
// is given the address instead (a site that serves only by name won't
// answer it; https://, and any URL through SOCKS, keep the name)
if proxy != nil && req.URL.Scheme == "http" && (proxy.Scheme == "http" || proxy.Scheme == "https") {
out.Host = out.URL.Host
}
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
},
}
+193
View File
@@ -0,0 +1,193 @@
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")
}
}