Backtestshugorun-20261005-133023#15301

Issue #15301 Merged fix PR # Run 5 Oct 2026 · run-20261005-133023 gohugoio/hugo

Improve/document security.http.urls override behavior

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

The issue asks for the security.http.urls override behavior to be improved and/or documented.

Patch A does both directly.
- It replaces the exact-equality check with `isNoBroaderThan`. Users who tighten the default policy, for example by adding extra deny rules or reordering the defaults, keep the dial-time internal-address check. Users who broaden it, for example with custom allow rules, removed default deny rules, or a deny-only list, still opt out as before. This closes a real gap where tightening the policy silently disabled the protection.
- It adds a clear reason to the AccessDeniedError message.
- It adds a thorough 'Internal addresses' docs section with examples and a caution, plus a cross-link from GetRemote.
- It adds unit tests for both the tightened and broadened cases, and an integration test with the transport. The tightened-case tests would fail before the change, since exact equality would have skipped the check.

Patch B mostly addresses a different concern: a new `proxyFromEnvironment` option.
- It disables env proxies by default, which is a behavior change that could break existing users relying on HTTP_PROXY.
- It adds complex context-based proxy plumbing and a new dependency on httpproxy.
- It adds one paragraph documenting the override behavior, but does not improve the override logic itself.
- Its tests cover the proxy feature, not the issue's override behavior.

This is unrelated scope that adds risk. Patch A is the better fix.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

2h 4m

Wall-clock time in the container

Full test suite

No new failures

3,755 passed · 100 skipped · 3,857 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

177vs 167 merged

Changed lines, ours vs merged

In d6e6f9e500eebdeae8e28de830fff2e3bfc7d534 (unreleased) we added a dial-time URL validation to catch URLs that's valid according to the whitelist but that resolves to a loopback, private or link-local IP addresses. That check is skipped it if the user has a custom security.http.urls setup, as it would not make sense to block local development servers.

See CheckAllowedHTTPAddress.

This has been reported by @Reload3d as a potential security issue, and while I think the current behaviour is the pragmatic correct approach, I'm creating this issue for visibility and to see if this can be improved further (e.g. better documentation).

The two patches

Our patch+168 −9
config/security/securityConfig.goindex f7cc157b8..0c6396b22 100644@@ -224,19 +224,24 @@ func (c Config) CheckAllowedHTTPURL(u string) error { // link-local (including the cloud metadata endpoint) address would otherwise // satisfy the policy and let resources.GetRemote reach an internal endpoint. // We deny any non–global-unicast or private address here to close that gap.+//+// The check is enforced as long as every allow rule in security.http.urls is+// one of the default allow rules and all of the default deny rules are kept+// (e.g. the default allowlist with extra deny rules added); rules are compared+// by their text. Otherwise (e.g. any custom allow rule, or a default deny+// rule removed) the user has opted into whatever hosts they listed, including+// internal ones (e.g. a local dev server), so we do not second-guess+// the resolved address. func (c Config) CheckAllowedHTTPAddress(network, address string) error {-	// Only enforced under the default hardened allowlist. If the user has-	// customized security.http.urls they have opted into whatever hosts they-	// listed, including internal ones (e.g. a local dev server), so we do not-	// second-guess the resolved address.-	if !slices.Equal(c.HTTP.URLs.patternsStrings, DefaultConfig.HTTP.URLs.patternsStrings) {+	if !c.HTTP.URLs.isNoBroaderThan(DefaultConfig.HTTP.URLs) { 		return nil 	}-	deny := func(name string) error {+	deny := func(name, reason string) error { 		return &AccessDeniedError{ 			name:     name, 			path:     "security.http.urls", 			policies: c.ToTOML(),+			reason:   reason, 		} 	} 	host, _, err := net.SplitHostPort(address)@@ -247,10 +252,12 @@ func (c Config) CheckAllowedHTTPAddress(network, address string) error { 	if err != nil { 		// The dial hook always hands us a resolved IP literal; anything else 		// is unexpected, so fail closed.-		return deny(address)+		return deny(address, "the dialed address is not an IP address") 	} 	if !isPublicAddr(ip) {-		return deny(host)+		return deny(host, "the host resolved to a loopback, private, link-local or otherwise non-public IP address, "++			"which is blocked unless security.http.urls is customized with allow rules beyond the default "++			"(note that this disables the check for all allowed hosts)") 	} 	return nil }@@ -463,9 +470,16 @@ type AccessDeniedError struct { 	path     string 	name     string 	policies string++	// reason optionally explains why access was denied when that is not+	// obvious from the policy alone.+	reason string }  func (e *AccessDeniedError) Error() string {+	if e.reason != "" {+		return fmt.Sprintf("access denied: %q is not whitelisted in policy %q: %s; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.reason, e.policies)+	} 	return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies) } config/security/securityConfig_test.goindex 4ac059a67..83b959c36 100644@@ -296,6 +296,50 @@ func TestCheckAllowedHTTPAddress(t *testing.T) { 	} } +// The dial-time address check must only stand down when the user has+// broadened security.http.urls, not when they have tightened it.+func TestCheckAllowedHTTPAddressCustomURLs(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	decode := func(urls string) Config {+		cfg, err := config.FromConfigString("[security.http]\nurls = "+urls, "toml")+		c.Assert(err, qt.IsNil)+		pc, err := DecodeConfig(cfg)+		c.Assert(err, qt.IsNil)+		return pc+	}++	const internal = "169.254.169.254:80"++	for _, urls := range []string{+		// Default plus an extra deny rule.+		`['(?i)^https?://[a-z0-9]', '! (?i)^https?://\d+\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@', '! ^https://evil\.example\.com']`,+		// The default rules in a different order.+		`['! (?i)^https?://\d+\.', '(?i)^https?://[a-z0-9]', '! (?i)localhost', '! (?i)^https?://[^/?#]*@']`,+	} {+		pc := decode(urls)+		err := pc.CheckAllowedHTTPAddress("tcp", internal)+		c.Assert(err, qt.IsNotNil, qt.Commentf(urls))+		c.Assert(err, qt.ErrorMatches, `(?s).*is not whitelisted in policy "security\.http\.urls": the host resolved to a loopback, private, link-local or otherwise non-public IP address.*`, qt.Commentf(urls))+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "93.184.216.34:80"), qt.IsNil, qt.Commentf(urls))+	}++	for _, urls := range []string{+		`['.*']`,+		`['^http://localhost:1313/']`,+		// Default plus an extra allow rule.+		`['(?i)^https?://[a-z0-9]', '! (?i)^https?://\d+\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@', '^http://127\.0\.0\.1:8080/']`,+		// Default with a deny rule removed.+		`['(?i)^https?://[a-z0-9]', '! (?i)^https?://\d+\.', '! (?i)^https?://[^/?#]*@']`,+		// Deny-only list implicitly allows everything else.+		`['! (?i)^https?://\d+\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@']`,+	} {+		pc := decode(urls)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", internal), qt.IsNil, qt.Commentf(urls))+	}+}+ func TestCheckAllowedHTTPURLAtInPathIssue14825(t *testing.T) { 	t.Parallel() 	c := qt.New(t)config/security/whitelist.goindex 8a4335baa..cf0b6c272 100644@@ -17,6 +17,7 @@ import ( 	"encoding/json" 	"fmt" 	"regexp"+	"slices" 	"strings"  	"github.com/gohugoio/hugo/hugofs/hglob"@@ -135,6 +136,49 @@ func (w Whitelist) Accept(name string) bool { 	return false } +// isNoBroaderThan reports whether w, judged by its pattern strings, accepts+// no more than other: w must accept none, or every allow rule in w must also+// be an allow rule in other and every deny rule in other must also be a deny+// rule in w. A w with only deny rules implicitly allows everything not denied,+// so it is only considered no broader if other is also deny-only.+func (w Whitelist) isNoBroaderThan(other Whitelist) bool {+	if w.acceptNone {+		return true+	}+	if other.acceptNone {+		return false+	}+	wAllow, wDeny := w.splitPatterns()+	oAllow, oDeny := other.splitPatterns()+	if len(wAllow) == 0 && len(oAllow) > 0 {+		return false+	}+	for _, p := range wAllow {+		if !slices.Contains(oAllow, p) {+			return false+		}+	}+	for _, p := range oDeny {+		if !slices.Contains(wDeny, p) {+			return false+		}+	}+	return true+}++// splitPatterns returns the allow and deny pattern strings of w, the latter+// without the negation prefix.+func (w Whitelist) splitPatterns() (allow, deny []string) {+	for _, p := range w.patternsStrings {+		if raw, ok := strings.CutPrefix(p, hglob.NegationPrefix); ok {+			deny = append(deny, raw)+		} else {+			allow = append(allow, p)+		}+	}+	return+}+ func (w Whitelist) String() string { 	return fmt.Sprint(w.patternsStrings) }docs/content/en/configuration/security.mdindex 9efbc0148..06bb5e2dd 100644@@ -35,7 +35,7 @@ This is the default security configuration: : (`[]string`) Applicable to the `resources.GetRemote` function, a slice of [regular expressions](g) matching the `Content-Type` in HTTP responses that Hugo trusts, bypassing file content analysis for media type detection.  `http.urls`-: (`[]string`) A slice of [regular expressions](g) matching the URLs that the `resources.GetRemote` function is allowed to access.+: (`[]string`) A slice of [regular expressions](g) matching the URLs that the `resources.GetRemote` function is allowed to access. See [internal addresses](#internal-addresses).  `node.permissions.disable` : {{< new-in 0.161.0 />}}@@ -76,6 +76,35 @@ urls = ['.*', '! ^https?://evil\.example\.com']  Setting an allowlist to the string `none` will completely disable the associated feature. +## Internal addresses++The `http.urls` allowlist only inspects the text of the URL. A host name that passes the allowlist may still resolve to an internal address, for example a loopback (`127.0.0.1`), private network (`10.0.0.0/8`), or link-local address such as the cloud metadata endpoint (`169.254.169.254`). To prevent the `resources.GetRemote` function from reaching internal endpoints, Hugo also validates the resolved IP address when it connects, including on redirects, and denies connections to any address that is not publicly routable.++This address check is enforced as long as every allow rule in `http.urls` is one of the default allow rules and all of the default deny rules are kept, for example when you only add deny rules to the default allowlist. Rules are compared by their text, not by what they match. If you add any other allow rule, even one narrower than the default such as `^https://api\.example\.com/`, or remove one of the default deny rules, Hugo assumes you have opted into the hosts you listed, including internal ones such as a local development server, and the address check is disabled.++For example, the configuration below tightens the default policy, so the address check remains enforced:++```toml+[security.http]+urls = [+  '(?i)^https?://[a-z0-9]',+  '! (?i)^https?://\d+\.',+  '! (?i)localhost',+  '! (?i)^https?://[^/?#]*@',+  '! ^https?://evil\.example\.com',+]+```++The configuration below allows a local development server, so the address check is disabled for all URLs:++```toml+[security.http]+urls = ['^http://localhost:1313/']+```++> [!CAUTION]+> When the address check is disabled, any host name allowed by `http.urls` is fetched regardless of the address it resolves to. If the DNS records of an allowed host are controlled by a third party, that host could be made to resolve to an internal address. Keep your allow rules as specific as possible, and only customize `http.urls` in environments where reaching internal addresses is acceptable.+ ## Environment variables  You can also override your project configuration with environment variables. For example, to block `resources.GetRemote` from accessing any URL:docs/content/en/functions/resources/GetRemote.mdindex d8c3138a7..442caa29f 100644@@ -230,6 +230,8 @@ Note that the entry above is: - An _addition_ to the allowlist; it does not _replace_ the allowlist - An array of [regular expressions](g) +The URLs that the `resources.GetRemote` function is allowed to access are controlled by the `security.http.urls` allowlist. With the default allowlist, Hugo also refuses to connect to a host that resolves to a loopback, private, or link-local address. See [internal addresses][] for details, including when customizing the allowlist disables this check.+ [Content-Type]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type [`Data.Headers`]: /methods/resource/data/#headers [`Data`]: /methods/resource/data/@@ -237,3 +239,4 @@ Note that the entry above is: [`try`]: /functions/go-template/try/ [allowlist]: https://en.wikipedia.org/wiki/Whitelist [configure file caches]: /configuration/caches/+[internal addresses]: /configuration/security/#internal-addressesresources/resource_factories/create/remote_test.goindex f9830c842..dabfd621d 100644@@ -173,3 +173,28 @@ urls = ['.*'] 	c.Assert(err, qt.IsNil) 	resp.Body.Close() }++// Tightening security.http.urls (the default plus an extra deny rule) must keep+// the dial-time check in place.+func TestSecureBaseTransportBlocksInternalAddressTightenedURLs(t *testing.T) {+	t.Parallel()++	c := qt.New(t)++	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		w.Write([]byte("secret"))+	}))+	t.Cleanup(srv.Close)++	req, err := http.NewRequest("GET", srv.URL, nil)+	c.Assert(err, qt.IsNil)++	sec, err := security.DecodeConfig(config.FromTOMLConfigString(`+[security.http]+urls = ['(?i)^https?://[a-z0-9]', '! (?i)^https?://\d+\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@', '! ^https://evil\.example\.com']+`))+	c.Assert(err, qt.IsNil)+	_, err = newSecureBaseTransport(sec).RoundTrip(req)+	c.Assert(err, qt.IsNotNil)+	c.Assert(security.IsAccessDenied(err), qt.IsTrue)+} 
Merged fix · PR #+163 −4
config/security/securityConfig.goindex f7cc157b8..a2708288a 100644@@ -128,6 +128,12 @@ type HTTP struct { 	// URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). 	URLs Whitelist `json:"urls"` +	// Whether to honor the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment+	// variables for remote HTTP. Off by default, as a proxy hides the+	// resolved destination address from the security policy.+	// <docsmeta>{ "newIn": "0.166.0" }</docsmeta>+	ProxyFromEnvironment bool `json:"proxyFromEnvironment"`+ 	// HTTP methods to allow. 	Methods Whitelist `json:"methods"` config/security/securityConfig_test.goindex 4ac059a67..e6f8c68e3 100644@@ -135,7 +135,7 @@ func TestToTOML(t *testing.T) { 	got := DefaultConfig.ToTOML()  	c.Assert(got, qt.Equals,-		"[security]\n  allowContent = ['! ^text/html$', '! ^text/org$']\n  enableInlineShortcodes = false\n\n  [security.exec]\n    allow = ['^(dart-)?sass$', '^go$', '^git$', '^node$', '^postcss$']\n    osEnv = ['(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$']\n\n  [security.funcs]\n    getenv = ['^HUGO_', '^CI$']\n\n  [security.http]\n    methods = ['(?i)GET|POST']\n    urls = ['(?i)^https?://[a-z0-9]', '! (?i)^https?://\\d+\\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@']\n\n  [security.node]\n    [security.node.permissions]\n      allowAddons = ['tailwindcss']\n      allowChildProcess = ['tailwindcss']\n      allowRead = ['.']\n      allowWorker = ['tailwindcss']\n      allowWrite = []\n      disable = false",+		"[security]\n  allowContent = ['! ^text/html$', '! ^text/org$']\n  enableInlineShortcodes = false\n\n  [security.exec]\n    allow = ['^(dart-)?sass$', '^go$', '^git$', '^node$', '^postcss$']\n    osEnv = ['(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$']\n\n  [security.funcs]\n    getenv = ['^HUGO_', '^CI$']\n\n  [security.http]\n    methods = ['(?i)GET|POST']\n    proxyFromEnvironment = false\n    urls = ['(?i)^https?://[a-z0-9]', '! (?i)^https?://\\d+\\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@']\n\n  [security.node]\n    [security.node.permissions]\n      allowAddons = ['tailwindcss']\n      allowChildProcess = ['tailwindcss']\n      allowRead = ['.']\n      allowWorker = ['tailwindcss']\n      allowWrite = []\n      disable = false", 	) } @@ -156,6 +156,7 @@ func TestDecodeConfigDefault(t *testing.T) { 	c.Assert(pc.HTTP.Methods.Accept("get"), qt.IsTrue) 	c.Assert(pc.HTTP.Methods.Accept("DELETE"), qt.IsFalse) 	c.Assert(pc.HTTP.MediaTypes.Accept("application/msword"), qt.IsFalse)+	c.Assert(pc.HTTP.ProxyFromEnvironment, qt.IsFalse)  	c.Assert(pc.Exec.OsEnv.Accept("PATH"), qt.IsTrue) 	c.Assert(pc.Exec.OsEnv.Accept("GOROOT"), qt.IsTrue)docs/content/en/configuration/security.mdindex 9efbc0148..54ebb4521 100644@@ -34,9 +34,15 @@ This is the default security configuration: `http.mediaTypes` : (`[]string`) Applicable to the `resources.GetRemote` function, a slice of [regular expressions](g) matching the `Content-Type` in HTTP responses that Hugo trusts, bypassing file content analysis for media type detection. +`http.proxyFromEnvironment`+: {{< new-in 0.166.0 />}}+: (`bool`) Whether the `resources.GetRemote` function honors the `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` environment variables. Default is `false`. When a proxy is used, Hugo connects to the proxy rather than the destination, so the resolved address validation described under `http.urls` does not apply.+ `http.urls` : (`[]string`) A slice of [regular expressions](g) matching the URLs that the `resources.GetRemote` function is allowed to access. +  The default allowlist denies URLs with an IP address or `localhost` as the host name. In addition, with the default allowlist, Hugo validates the resolved address when connecting and rejects connections to loopback, private, link-local, and other non-public addresses, e.g. a host name that resolves to a cloud metadata endpoint. This validation is disabled if you override `http.urls`, as the override may intentionally allow access to hosts on your local network, such as a development server.+ `node.permissions.disable` : {{< new-in 0.161.0 />}} : (`bool`) Whether to disable the Node.js [permission model][]. When `false`, Hugo runs Node.js tools with the `--permission` flag, restricting their file system and resource access to what is explicitly allowed below. Default is `false`.docs/data/docs.yamlindex b392c6a71..bf63fb6b0 100644@@ -2240,6 +2240,7 @@ config:       mediaTypes: null       methods:       - (?i)GET|POST+      proxyFromEnvironment: false       urls:       - (?i)^https?://[a-z0-9]       - '! (?i)^https?://\d+\.'resources/resource_factories/create/create.goindex a34f9fc7b..1570c2648 100644@@ -16,9 +16,11 @@ package create  import (+	"context" 	"errors" 	"net" 	"net/http"+	"net/url" 	"os" 	"path" 	"path/filepath"@@ -26,6 +28,8 @@ import ( 	"syscall" 	"time" +	"golang.org/x/net/http/httpproxy"+ 	"github.com/bep/helpers/contexthelpers"  	"github.com/bep/logg"@@ -65,6 +69,7 @@ type contextKey uint8  const ( 	contextKeyResourceID contextKey = iota+	contextKeyProxyURL )  // New creates a new Client with the given specification.@@ -154,17 +159,80 @@ func New(rs *resources.Spec) *Client { // hook that validates the resolved destination address against the security // policy, so a hostname resolving to an internal address cannot be used to // reach internal endpoints. See CheckAllowedHTTPAddress.+//+// Proxies are only used when security.http.proxyFromEnvironment is enabled.+// A proxied connection is dialed to the proxy, not the destination, so the+// address check is skipped for that dial; the user has opted into trusting+// the proxy with the destination. The proxy decision is carried per request+// in its context, so a direct dial is always validated, even to the proxy's+// own address. func newSecureBaseTransport(sec security.Config) http.RoundTripper { 	base := http.DefaultTransport.(*http.Transport).Clone()-	d := &net.Dialer{+	secureDialer := &net.Dialer{ 		Timeout:   30 * time.Second, 		KeepAlive: 30 * time.Second, 		Control: func(network, address string, _ syscall.RawConn) error { 			return sec.CheckAllowedHTTPAddress(network, address) 		}, 	}-	base.DialContext = d.DialContext-	return base+	base.Proxy = nil+	base.DialContext = secureDialer.DialContext++	if !sec.HTTP.ProxyFromEnvironment {+		return base+	}++	proxyFromCtx := func(ctx context.Context) *url.URL {+		u, _ := ctx.Value(contextKeyProxyURL).(*url.URL)+		return u+	}+	base.Proxy = func(req *http.Request) (*url.URL, error) {+		return proxyFromCtx(req.Context()), nil+	}+	proxyDialer := &net.Dialer{Timeout: secureDialer.Timeout, KeepAlive: secureDialer.KeepAlive}+	base.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {+		if u := proxyFromCtx(ctx); u != nil && canonicalAddr(u) == addr {+			return proxyDialer.DialContext(ctx, network, addr)+		}+		return secureDialer.DialContext(ctx, network, addr)+	}+	return &proxyTransport{base: base, proxyFunc: httpproxy.FromEnvironment().ProxyFunc()}+}++// proxyTransport resolves the proxy for each request up front and stores it+// in the request context, where both the Proxy and DialContext hooks of base+// can see it.+type proxyTransport struct {+	base      *http.Transport+	proxyFunc func(*url.URL) (*url.URL, error)+}++func (t *proxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {+	u, err := t.proxyFunc(req.URL)+	if err != nil {+		return nil, err+	}+	if u != nil {+		req = req.WithContext(context.WithValue(req.Context(), contextKeyProxyURL, u))+	}+	return t.base.RoundTrip(req)+}++// canonicalAddr mirrors net/http's canonicalAddr: the host:port the transport+// dials for u, with the port defaulted from the scheme.+func canonicalAddr(u *url.URL) string {+	port := u.Port()+	if port == "" {+		switch u.Scheme {+		case "http":+			port = "80"+		case "https":+			port = "443"+		case "socks5", "socks5h":+			port = "1080"+		}+	}+	return net.JoinHostPort(u.Hostname(), port) }  // Copy copies r to the new targetPath.resources/resource_factories/create/remote_test.goindex f9830c842..d7bb98361 100644@@ -14,8 +14,10 @@ package create  import (+	"io" 	"net/http" 	"net/http/httptest"+	"sync/atomic" 	"testing"  	qt "github.com/frankban/quicktest"@@ -173,3 +175,78 @@ urls = ['.*'] 	c.Assert(err, qt.IsNil) 	resp.Body.Close() }++// Proxies from the environment are ignored unless+// security.http.proxyFromEnvironment is enabled. When enabled, the dial-time+// address check does not apply to the proxy itself. See issue 15302.+func TestSecureBaseTransportProxyFromEnvironment(t *testing.T) {+	c := qt.New(t)++	var proxyHits, targetHits atomic.Int32+	proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		proxyHits.Add(1)+		w.Write([]byte("via proxy"))+	}))+	t.Cleanup(proxy.Close)+	target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		targetHits.Add(1)+		w.Write([]byte("direct"))+	}))+	t.Cleanup(target.Close)++	t.Setenv("HTTP_PROXY", proxy.URL)+	t.Setenv("NO_PROXY", "")+	t.Setenv("no_proxy", "")++	decode := func(toml string) security.Config {+		sec, err := security.DecodeConfig(config.FromTOMLConfigString(toml))+		c.Assert(err, qt.IsNil)+		return sec+	}+	fetch := func(sec security.Config, u string) (string, error) {+		req, err := http.NewRequest("GET", u, nil)+		c.Assert(err, qt.IsNil)+		resp, err := newSecureBaseTransport(sec).RoundTrip(req)+		if err != nil {+			return "", err+		}+		defer resp.Body.Close()+		b, err := io.ReadAll(resp.Body)+		c.Assert(err, qt.IsNil)+		return string(b), nil+	}++	// Default: proxy ignored, fetched directly.+	body, err := fetch(decode(`+[security.http]+urls = ['.*']+`), target.URL)+	c.Assert(err, qt.IsNil)+	c.Assert(body, qt.Equals, "direct")+	c.Assert(proxyHits.Load(), qt.Equals, int32(0))+	c.Assert(targetHits.Load(), qt.Equals, int32(1))++	// Enabled: the loopback proxy is dialed even under the default hardened+	// policy, and the destination is never dialed directly.+	body, err = fetch(decode(`+[security.http]+proxyFromEnvironment = true+`), "http://example.com/")+	c.Assert(err, qt.IsNil)+	c.Assert(body, qt.Equals, "via proxy")+	c.Assert(proxyHits.Load(), qt.Equals, int32(1))+	c.Assert(targetHits.Load(), qt.Equals, int32(1))++	// Enabled, but loopback destinations are never proxied: the address+	// check still applies to the direct dial, also when the destination is+	// the proxy's own address.+	for _, u := range []string{target.URL, proxy.URL} {+		_, err = fetch(decode(`+[security.http]+proxyFromEnvironment = true+`), u)+		c.Assert(security.IsAccessDenied(err), qt.IsTrue, qt.Commentf(u))+	}+	c.Assert(proxyHits.Load(), qt.Equals, int32(1))+	c.Assert(targetHits.Load(), qt.Equals, int32(1))+}