Backtestshugorun-20261009-153657#15301

Issue #15301 Merged fix PR #15305 Run 9 Oct 2026 · run-20261009-153657 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 whether the behavior where `CheckAllowedHTTPAddress` stands down whenever `security.http.urls` is customized can be improved, or at least better documented.

Patch A addresses the root of that concern. It replaces the all-or-nothing `slices.Equal` bypass with a finer rule:
- Public addresses always pass.
- Allowlists that only admit specific hosts keep trusting their resolved addresses, so local dev servers and intranet hosts still work.
- Allowlists that admit arbitrary hostnames (the default plus extra deny rules, `.*`, TLD-restricted patterns) only allow a non-public resolved address if the same address, or `localhost` for loopback, would be accepted as a literal.

This closes the reported gap. For example, a user who tightens the default with one more deny rule no longer silently loses the DNS-rebinding protection. It also keeps the pragmatic dev-server escape hatch.

The probe-hostname heuristic is admittedly imperfect. A pattern that admits any host only for a specific path is treated as specific-hosts. However, the patch documents this limitation explicitly, and it is strictly safer than the previous behavior.

Patch A's tests are targeted and would fail before the change:
- The default plus an extra deny rule now denies loopback, metadata, and IPv4-mapped/NAT64 addresses.
- Broad lists still deny internal addresses.
- An explicit dev server is allowed only on the listed port.
- A transport-level test shows a broad custom policy blocking the loopback httptest server.

Its docs add a clear 'Resolved addresses' section.

Patch B only documents the existing behavior in one paragraph. It leaves the bypass unchanged, so it does not improve the security property at all. Most of its diff is an unrelated new feature: the `proxyFromEnvironment` option. That feature adds a custom `proxyTransport`, context-carried proxy URLs, a `canonicalAddr` reimplementation, and a new dependency import. It also changes default behavior by disabling environment proxies, a potentially breaking change for users behind corporate proxies. This is scope creep that adds risk and obscures the minimal doc fix, and its tests cover the proxy feature rather than the issue.

Patch A is the better fix on correctness, tests, and scope.

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

35m 16s

Wall-clock time in the container

Full test suite

No new failures

836 passed · 51 skipped · 887 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

220vs 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+204 −16
config/security/securityConfig.goindex f7cc157b8..67c4bf2f8 100644@@ -223,15 +223,21 @@ func (c Config) CheckAllowedHTTPURL(u string) error { // the resolved address, so a hostname that resolves to a loopback, private or // 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.+// We close that gap by denying non-public (loopback, private, link-local,+// reserved etc.) addresses, with these rules:+//+//   - A public address is always allowed; the URL text was already checked.+//   - If the allowlist only admits specific hosts (it rejects an arbitrary+//     hostname), the user has listed exactly the hosts they trust, including+//     internal ones such as a local dev server or an intranet host, so the+//     resolved address is not second-guessed.+//   - If the allowlist admits arbitrary hostnames (e.g. the default policy, or+//     ['.*']), a non-public address is only allowed if the allowlist would+//     also accept that address written directly in the URL (e.g.+//     "http://127.0.0.1:1313/", or "http://localhost:1313/" for loopback).+//     That way DNS cannot be used to reach an address the policy would deny+//     if written as a literal. 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) {-		return nil-	} 	deny := func(name string) error { 		return &AccessDeniedError{ 			name:     name,@@ -239,9 +245,9 @@ func (c Config) CheckAllowedHTTPAddress(network, address string) error { 			policies: c.ToTOML(), 		} 	}-	host, _, err := net.SplitHostPort(address)+	host, port, err := net.SplitHostPort(address) 	if err != nil {-		host = address+		host, port = address, "" 	} 	ip, err := netip.ParseAddr(host) 	if err != nil {@@ -249,10 +255,56 @@ func (c Config) CheckAllowedHTTPAddress(network, address string) error { 		// is unexpected, so fail closed. 		return deny(address) 	}-	if !isPublicAddr(ip) {-		return deny(host)+	if isPublicAddr(ip) {+		return nil 	}-	return nil+	if !acceptsArbitraryHost(c.HTTP.URLs) {+		return nil+	}+	if acceptsAddressURL(c.HTTP.URLs, ip, port) {+		return nil+	}+	return deny(host)+}++// httpProbeHosts are hostnames that no allowlist naming specific hosts would+// match: one in the reserved .invalid TLD (RFC 2606), and one in a common+// public TLD to catch allowlists that restrict the TLD but not the name.+var httpProbeHosts = []string{"hugo-address-probe.invalid", "hugo-address-probe.com"}++// acceptsArbitraryHost reports whether w admits URLs for any hostname, i.e.+// whether the hosts it admits are determined by DNS rather than by the user.+func acceptsArbitraryHost(w Whitelist) bool {+	for _, h := range httpProbeHosts {+		if w.Accept("http://"+h+"/") || w.Accept("https://"+h+"/") {+			return true+		}+	}+	return false+}++// acceptsAddressURL reports whether w accepts a URL that names ip (and port,+// if set) directly, or, for loopback addresses, via localhost.+func acceptsAddressURL(w Whitelist, ip netip.Addr, port string) bool {+	ip = ip.Unmap().WithZone("")+	hosts := []string{ip.String()}+	if ip.Is6() {+		hosts[0] = "[" + hosts[0] + "]"+	}+	if ip.IsLoopback() {+		hosts = append(hosts, "localhost")+	}+	for _, scheme := range []struct{ name, defaultPort string }{{"http", "80"}, {"https", "443"}} {+		for _, h := range hosts {+			if port != "" && w.Accept(scheme.name+"://"+h+":"+port+"/") {+				return true+			}+			if (port == "" || port == scheme.defaultPort) && w.Accept(scheme.name+"://"+h+"/") {+				return true+			}+		}+	}+	return false }  // Special-purpose ranges that Go classifies as global unicast andconfig/security/securityConfig_test.goindex 4ac059a67..85e48914a 100644@@ -296,6 +296,93 @@ func TestCheckAllowedHTTPAddress(t *testing.T) { 	} } +// A custom security.http.urls must only turn off the resolved address check+// to the extent the user has actually opted into internal addresses.+func TestCheckAllowedHTTPAddressCustomURLs(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	decode := func(c *qt.C, 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+	}+	assertDenied := func(c *qt.C, pc Config, addr string) {+		err := pc.CheckAllowedHTTPAddress("tcp", addr)+		c.Assert(err, qt.IsNotNil, qt.Commentf(addr))+		c.Assert(err, qt.ErrorMatches, `(?s).*is not whitelisted in policy "security\.http\.urls".*`, qt.Commentf(addr))+	}++	c.Run("Default plus an extra deny rule still checks the address", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['(?i)^https?://[a-z0-9]', '! (?i)^https?://\d+\.', '! (?i)localhost', '! (?i)^https?://[^/?#]*@', '! (?i)evil\.example\.com']`)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "93.184.216.34:443"), qt.IsNil)+		for _, addr := range []string{+			"127.0.0.1:80",+			"[::1]:443",+			"10.0.0.1:8080",+			"169.254.169.254:80",+			"[::ffff:169.254.169.254]:80",+			"[64:ff9b::a9fe:a9fe]:80",+		} {+			assertDenied(c, pc, addr)+		}+	})++	c.Run("Broad list allowing public IP literals still checks the address", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['^https?://', '! (?i)^https?://(localhost|127\.|10\.|169\.254\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[)']`)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "93.184.216.34:443"), qt.IsNil)+		for _, addr := range []string{+			"127.0.0.1:80",+			"[::1]:80",+			"10.0.0.1:80",+			"169.254.169.254:80",+			"192.168.1.1:443",+		} {+			assertDenied(c, pc, addr)+		}+	})++	c.Run("Broad list with an explicit local dev server", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['^https://[a-z][a-z0-9-]*\.[a-z]', '^http://localhost:1313/','^http://192\.168\.1\.10/']`)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "127.0.0.1:1313"), qt.IsNil)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "[::1]:1313"), qt.IsNil)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "192.168.1.10:80"), qt.IsNil)+		assertDenied(c, pc, "127.0.0.1:8080")+		assertDenied(c, pc, "192.168.1.10:8080")+		assertDenied(c, pc, "192.168.1.11:80")+	})++	c.Run("Broad list restricted to common TLDs still checks the address", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['(?i)^https?://[a-z0-9.-]+\.(com|net|org)/']`)+		c.Assert(pc.CheckAllowedHTTPAddress("tcp", "93.184.216.34:443"), qt.IsNil)+		for _, addr := range []string{"127.0.0.1:80", "10.0.0.1:443", "169.254.169.254:80"} {+			assertDenied(c, pc, addr)+		}+	})++	c.Run("Allow all", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['.*']`)+		for _, addr := range []string{"127.0.0.1:80", "[::1]:1313", "169.254.169.254:80", "10.0.0.1:8080"} {+			c.Assert(pc.CheckAllowedHTTPAddress("tcp", addr), qt.IsNil, qt.Commentf(addr))+		}+	})++	c.Run("Specific hosts only trusts their resolved addresses", func(c *qt.C) {+		c.Parallel()+		pc := decode(c, `['^https://api\.example\.com/', '^http://cms\.intranet/', '^http://localhost:1313/']`)+		for _, addr := range []string{"127.0.0.1:1313", "10.0.0.5:80", "93.184.216.34:443"} {+			c.Assert(pc.CheckAllowedHTTPAddress("tcp", addr), qt.IsNil, qt.Commentf(addr))+		}+	})+}+ func TestCheckAllowedHTTPURLAtInPathIssue14825(t *testing.T) { 	t.Parallel() 	c := qt.New(t)docs/content/en/configuration/security.mdindex 9efbc0148..9c2896cf9 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 [resolved addresses](#resolved-addresses).  `node.permissions.disable` : {{< new-in 0.161.0 />}}@@ -76,6 +76,18 @@ urls = ['.*', '! ^https?://evil\.example\.com']  Setting an allowlist to the string `none` will completely disable the associated feature. +## Resolved addresses++The `http.urls` allowlist matches the URL text only. A hostname that passes the allowlist can still resolve to a loopback, private, link-local, or otherwise non-public IP address, for example a cloud metadata endpoint such as `169.254.169.254`. To prevent this, Hugo also checks the IP address it is about to connect to when fetching a remote resource:++- A connection to a public IP address is always allowed.+- If the allowlist only admits specific hosts, Hugo trusts the addresses those hosts resolve to, including non-public ones. This lets you fetch from a local development server or an intranet host that you list explicitly, for example `urls = ['^https://api\.example\.com/', '^http://localhost:1313/']`.+- If the allowlist admits arbitrary hostnames, as the default allowlist and `['.*']` do, a connection to a non-public IP address is only allowed if the allowlist would also accept that address written directly in the URL, for example `http://192.168.1.10/` or `http://127.0.0.1:1313/`. For loopback addresses, `http://localhost:1313/` also counts.++Hugo decides whether an allowlist admits arbitrary hostnames by checking whether it accepts the unlisted hostnames `hugo-address-probe.invalid` and `hugo-address-probe.com`. An allowlist that only admits arbitrary hostnames for a particular path, file extension, or port, such as `['^https://[^/]+/assets/']`, is treated as admitting specific hosts, so the address check is skipped. Avoid such patterns if your project may fetch untrusted URLs.++With the default allowlist, which denies IP literals and `localhost`, connections to non-public addresses are always denied. Adding deny rules to the default allowlist keeps this protection. For the same reason, adding an allow rule for an intranet host to the default allowlist is not enough to fetch from it, because the default deny rules still reject its IP address. List only the specific hosts you need instead. If you replace the allowlist with one that admits every URL, such as `['.*']`, any hostname can reach internal addresses on your network. Only do this if you trust every URL your project passes to `resources.GetRemote`.+ ## Environment variables  You can also override your project configuration with environment variables. For example, to block `resources.GetRemote` from accessing any URL:resources/resource_factories/create/remote_test.goindex f9830c842..b2f9444af 100644@@ -162,8 +162,8 @@ func TestSecureBaseTransportBlocksInternalAddress(t *testing.T) { 	c.Assert(err, qt.IsNotNil) 	c.Assert(security.IsAccessDenied(err), qt.IsTrue) -	// Customized policy: the user has opted into their own hosts, so the dial-	// check stands down and the fetch succeeds.+	// Customized policy that admits any URL, including IP literals: loopback+	// could be fetched directly anyway, so the fetch succeeds. 	sec, err := security.DecodeConfig(config.FromTOMLConfigString(` [security.http] urls = ['.*']@@ -172,4 +172,41 @@ urls = ['.*'] 	resp, err := newSecureBaseTransport(sec).RoundTrip(req) 	c.Assert(err, qt.IsNil) 	resp.Body.Close()++	// Customized policy naming specific hosts only: the user has opted into+	// their own hosts (e.g. a local dev server), so the fetch succeeds.+	sec, err = security.DecodeConfig(config.FromTOMLConfigString(`+[security.http]+urls = ['^https://api\.example\.com/', '^http://localhost:\d+/']+`))+	c.Assert(err, qt.IsNil)+	resp, err = newSecureBaseTransport(sec).RoundTrip(req)+	c.Assert(err, qt.IsNil)+	resp.Body.Close()+}++// Customizing security.http.urls with a list that still admits arbitrary+// hostnames, but not internal addresses, must not turn off the resolved+// address check (e.g. tightening the default with an extra deny rule).+func TestSecureBaseTransportBlocksInternalAddressCustomBroadPolicy(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?://[^/?#]*@', '! (?i)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 #15305+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 e51915c49..6d2578339 100644@@ -2253,6 +2253,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))+}