fix(web): dial all validated IPs for dual-stack fallback (I1); fix live SSRF test to await fetch (M1)

This commit is contained in:
sausheong committed 2026-06-13 11:56:30 +08:00
1 parent fb5103fb87
commit d6db565d7c
3 files changed
+49 -8

No files matched your search

+16 -6
View File
@@ -25,19 +25,29 @@ func SafeHTTPClient(timeout time.Duration) *http.Client {
if err != nil {
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
}
var dialIP net.IP
// Fail closed: if ANY resolved IP is private, refuse — this defeats
// DNS-rebinding where one A record is public and another is private.
for _, ip := range ips {
if isPrivateIP(ip) {
return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
}
if dialIP == nil {
dialIP = ip
}
}
if dialIP == nil {
if len(ips) == 0 {
return nil, fmt.Errorf("no usable address for %q", host)
}
return dialer.DialContext(ctx, network, net.JoinHostPort(dialIP.String(), port))
// Try each validated public IP in order, falling back on dial
// failure so dual-stack hosts still connect on IPv4-only or
// IPv6-broken networks (stock happy-eyeballs is bypassed because we
// dial literal IPs to pin the validated address).
var lastErr error
for _, ip := range ips {
conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if derr == nil {
return conn, nil
}
lastErr = derr
}
return nil, lastErr
},
}
return &http.Client{
+11
View File
@@ -39,5 +39,16 @@ func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) {
require.Error(t, err)
}
func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) {
// 192.0.2.1 is RFC5737 TEST-NET-1 (public, unrouteable). It is NOT in the
// private blocklist, so validation passes and we should get a DIAL error
// (timeout/unreachable), not a "blocked" validation error — proving the
// path dials rather than rejecting.
client := SafeHTTPClient(2 * time.Second)
_, err := client.Get("http://192.0.2.1/")
require.Error(t, err)
require.NotContains(t, err.Error(), "internal address")
}
var _ = isPrivateIP(net.IPv4(127, 0, 0, 1))
var _ = strings.TrimSpace