safehttp

package
v0.116.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 26 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package safehttp is the HTTP client for the PUBLIC internet: an *http.Client that refuses to connect to internal addresses (SSRF), plus the URL and IP checks it is built from.

NewClient returns a client whose dialer rejects loopback, unspecified, multicast, link-local, private (RFC 1918), CGNAT and ULA targets. The check runs before DNS resolution and again at socket creation (Dialer.Control), so a hostname that rebinds to 169.254.169.254 after the first lookup is stopped too. A blocked target fails with ErrBlocked.

client := safehttp.NewClient(
    safehttp.WithTimeout(10*time.Second),
    safehttp.WithUserAgent(ua.Build(serviceID, version)),
)

The pieces are usable on their own:

  • NormalizeURL and ValidateURL parse and vet a user-supplied URL (http or https, with a host); CheckURL adds the host guard in one call.
  • IsBlocked, IsBlockedForHost and GuardHost classify an IP or a host name.
  • WithEgressAllowlist and WithDenyAllEgress restrict the hosts a client may reach at all.
  • WithTraceCollector, WithBackoffCoordinator and WithDegradedSink wire the client into the fleet's call tracing, backoff coordination and the response envelope's degraded list.
  • WithPersistentBreakerState keeps circuit-breaker state across restarts.
  • WithoutFetchCache and WithoutFetchCacheContext skip the fleet fetch cache for one client or one request.
  • WithoutProxy and RequireProxy control whether the client uses the configured egress proxy.

Not for calls inside the mesh

The guard blocks private addresses on purpose, so a call to a sibling fleet service (http://go-fleet-*:<port>) through this client fails at once with ErrBlocked. Calls inside the mesh use a plain net/http.Client with a short timeout instead.

Environment

SAFEHTTP_ALLOW_PRIVATE_IPS (a comma-separated list of literal IPs) and SAFEHTTP_ALLOW_PRIVATE_HOSTS exempt specific trusted targets from the private network check. See IsBlocked and IsBlockedForHost for why the IP-only allowlist is not safe for a service that fetches arbitrary caller-supplied host names.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrBlocked is returned when a target resolves to a non-public network.
	ErrBlocked = errors.New("blocked address: resolves to a non-public network")
	// ErrInvalidScheme is returned for non-http(s) URLs.
	ErrInvalidScheme = errors.New("scheme must be http or https")
	// ErrMissingHost is returned when a URL has no host component.
	ErrMissingHost = errors.New("missing host")
	// ErrEgressNotAllowed is returned when a request targets a host that
	// is not in the configured outbound allowlist (see WithEgressAllowlist
	// / WithDenyAllEgress). The check fires AFTER the SSRF guard but
	// BEFORE any network I/O — no DNS resolution, no TCP connect.
	ErrEgressNotAllowed = errors.New("egress not allowed")
)
View Source
var ErrDomainDenied = errors.New("safehttp: domain is not permitted through this service (compliance policy)")

ErrDomainDenied is returned when a target hostname matches the fleet-wide compliance denylist (see deniedDomains). It is distinct from ErrBlocked (private-network/SSRF) and ErrEgressNotAllowed (per-client opt-in allowlist) so callers can surface a specific compliance message instead of a generic block.

View Source
var TestAllowedHosts = []string{
	"8.8.8.8",
	"1.1.1.1",
	"93.184.216.34",
}

TestAllowedHosts is a canonical list of public IPs that must NOT be blocked.

View Source
var TestBlockedHosts = []string{
	"127.0.0.1",
	"::1",
	"10.0.0.1",
	"172.16.0.1",
	"192.168.1.1",
	"169.254.169.254",
	"fc00::1",
	"100.64.0.1",
}

TestBlockedHosts is a canonical list of hosts/IPs that every service's SSRF guard must reject. Use in table-driven tests instead of copying the list.

Functions

func CheckURL

func CheckURL(ctx context.Context, rawURL string) (*url.URL, error)

CheckURL normalizes rawURL, validates scheme, and guards the host against RFC1918/loopback/CGNAT/ULA addresses. It is the one-call replacement for the parse ��� ValidateURL ��� GuardHost pattern used in every service handler. Returns the validated, ready-to-use *url.URL.

Rebind caveat: the host verdict is cached for up to guardCacheTTL (see GuardHost). When you then dial through this package's NewClient, the Dialer.Control re-check re-validates the actually-connected IP, so a stale "allowed" verdict is harmless. But if you validate with CheckURL and then connect with a plain net/http.Client (no safehttp dialer — e.g. the intra-mesh sibling-call pattern), there is NO Control backstop, so do not rely on CheckURL alone as a DNS-rebind defense for that path.

func DeniedDomains

func DeniedDomains() []string

DeniedDomains returns a sorted copy of the compliance denylist, for services that need to log, display, or cross-check the same list without going through IsDomainDenied (e.g. an admin UI, or a non-Go sibling's parity test fixture).

func GuardHost

func GuardHost(ctx context.Context, host string) error

GuardHost resolves host and returns ErrBlocked if any returned IP is in a blocked range. Accepts a bare IP literal as well as a hostname. DNS is revalidated with a 3-second timeout (DNS-rebind safe when combined with the Dialer.Control re-check in NewClient).

Definitive verdicts (allowed / ErrBlocked) for hostnames are cached for a short TTL (guardCacheTTL) so the per-request validation path (CheckURL) and the dialer don't re-resolve the same host on every call. Transient DNS lookup failures are never cached. The cache is NOT a security boundary: the Dialer.Control re-check validates the actually-connected IP independently, so a stale "allowed" verdict can never let a connection reach a blocked address.

func GuardedDialer

func GuardedDialer(portCheck bool) func(ctx context.Context, network, addr string) (net.Conn, error)

GuardedDialer returns a DialContext func that blocks connections to private or internal addresses. Set portCheck=true to restrict to ports 80 and 443. The guard runs before DNS resolution and again at socket creation time (Dialer.Control) to defend against DNS-rebind attacks.

func IsBlocked

func IsBlocked(ip net.IP) bool

IsBlocked reports whether ip falls in any blocked range: loopback, unspecified, multicast, link-local, private (RFC1918), CGNAT (100.64.0.0/10), 0.0.0.0/8, or ULA (fc00::/7). An IPv6 address that embeds an IPv4 one (IPv4-mapped, NAT64 64:ff9b::/96, 6to4 2002::/16) is blocked when the embedded IPv4 address is.

Honors SAFEHTTP_ALLOW_PRIVATE_IPS — a comma-separated list of literal IPs that bypass the private-network check. Use it ONLY for trusted fleet egress targets (e.g. a LAN-IP loopback past the public NAT hairpin); leaving it unset keeps the SSRF defense intact.

CAUTION — IsBlocked's allowlist is IP-only: it says nothing about which HOSTNAME produced ip. That's fine for a fixed, hardcoded target (e.g. a client that only ever calls one known internal URL). It is NOT safe to rely on for a service that resolves and fetches ARBITRARY caller-supplied hostnames (a URL-fetching proxy/analyzer): once an IP is allowlisted, every hostname that happens to resolve to it — including unrelated internal-only vhosts sharing the same gateway address — is reachable too. Callers in that shape should route through GuardHost/the safehttp dialer (which additionally consult SAFEHTTP_ALLOW_PRIVATE_HOSTS via IsBlockedForHost) rather than gate on IsBlocked(ip) alone. See IsBlockedForHost.

Example
package main

import (
	"fmt"
	"net"

	"github.com/baditaflorin/go-common/safehttp"
)

func main() {
	fmt.Println(safehttp.IsBlocked(net.ParseIP("10.0.0.5")))
	fmt.Println(safehttp.IsBlocked(net.ParseIP("169.254.169.254")))
	fmt.Println(safehttp.IsBlocked(net.ParseIP("8.8.8.8")))
}
Output:
true
true
false

func IsBlockedForHost

func IsBlockedForHost(host string, ip net.IP) bool

IsBlockedForHost is IsBlocked with an additional, narrower bypass: when SAFEHTTP_ALLOW_PRIVATE_HOSTS is configured, an IP that is on the SAFEHTTP_ALLOW_PRIVATE_IPS allowlist is only treated as reachable for hostnames that are ALSO on SAFEHTTP_ALLOW_PRIVATE_HOSTS. Both lists must agree before a blocked-range IP is let through.

Why this exists: a fleet's split-horizon internal DNS commonly rewrites a whole family of hostnames — the operator's own public sites AND every sibling fleet service's hostname — to the SAME internal gateway IP (to skip a NAT hairpin). Allowlisting that IP with SAFEHTTP_ALLOW_PRIVATE_IPS alone (via IsBlocked) would let a caller reach ANY hostname that resolves there, not just the intended ones — including internal-only sibling services that share the gateway address and have no other network-layer protection (e.g. an internal-only service configured with auth: none, gated purely by an upstream IP allowlist that already trusts the whole internal LAN). That's a real SSRF pivot for any service whose job is fetching ARBITRARY caller-supplied URLs (a URL-fetching proxy/analyzer), because the attacker fully controls the hostname.

IsBlockedForHost closes that gap: set SAFEHTTP_ALLOW_PRIVATE_HOSTS to the specific hostname(s) that are actually meant to resolve privately (e.g. "example.com,example.org" — subdomains included automatically) alongside SAFEHTTP_ALLOW_PRIVATE_IPS with the gateway IP(s). Only that combination is treated as safe; every other hostname that happens to resolve to the same private IP stays blocked exactly as before.

Backward compatible: when SAFEHTTP_ALLOW_PRIVATE_HOSTS is unset (the default — nothing in the fleet sets it today), IsBlockedForHost behaves identically to IsBlocked, so this is a pure opt-in.

GuardHost and the safehttp dialer's DNS-rebind re-check both call this instead of IsBlocked, so both real enforcement points honor the host-scoped allowlist. Call sites that only ever see a raw IP literal placed directly in a URL (no hostname to scope by — the caller already controls the IP directly) intentionally keep calling IsBlocked unchanged.

func IsDomainDenied

func IsDomainDenied(host string) bool

IsDomainDenied reports whether host, or any parent domain of host, is on the compliance denylist. Matching is exact-or-subdomain: both "rutracker.org" and "tracker.rutracker.org" match the "rutracker.org" entry. host may be a bare hostname, "Host.With.Trailing.Dot.", or "host:port" — scheme prefixes are not stripped, so pass u.Hostname() rather than a raw URL string.

func NegotiatedProtocol

func NegotiatedProtocol(resp *http.Response) string

NegotiatedProtocol returns the TLS ALPN protocol the server selected for resp (e.g. "h2" or "http/1.1"), or "" when resp carried no TLS state (plain HTTP, or a nil/errored response). It is nil-safe.

To get a reliable "h2" here the client MUST be built with WithForceHTTP2 — the default safehttp transport installs a custom dialer, which makes net/http conservatively disable HTTP/2 and omit "h2" from the ClientHello ALPN, so this field comes back empty even against HTTP/2-capable origins. WithForceHTTP2 + NegotiatedProtocol is the fleet-canonical replacement for a dedicated TCP/443 ALPN-probe handshake.

Fetch-cache callers: since v0.71.0, WithForceHTTP2 also opts the client out of the process-wide default fetch-cache delegate. Before that, a delegate-served response was reconstructed from cached bytes with no live TLS connection behind it — resp.TLS was always nil, so this function returned "" (or, worse, callers reading resp.Proto directly saw a hardcoded "HTTP/1.1") no matter what the origin actually negotiated. If you're inspecting a response from a client built WITHOUT WithForceHTTP2 (or one with an explicit WithFetchDelegate), an empty result here still means "unknown", not "confirmed HTTP/1.1".

func NewClient

func NewClient(opts ...Option) *http.Client

NewClient returns an *http.Client with a guarded transport. The transport blocks private/internal IPs on every dial, including after redirects, making it safe against DNS-rebind and open-redirect SSRF chains.

NewClient panics when the proxy setup is wrong: WithoutProxy together with RequireProxy, or RequireProxy (or FLEET_REQUIRE_PROXY=1) with no proxy variable set. That is a deployment mistake and the service should stop at start-up, so call NewClient from start-up code. Code that runs per request or in a goroutine, and checks that want to report the problem instead of crashing, use NewClientE.

Example

NewClient is the client for the PUBLIC internet: it refuses loopback, private, link-local and CGNAT targets, again at connect time, so a DNS name that rebinds to 169.254.169.254 is stopped too. Calls to sibling fleet services on the private mesh must use a plain net/http.Client instead.

package main

import (
	"time"

	"github.com/baditaflorin/go-common/safehttp"
	"github.com/baditaflorin/go-common/ua"
)

func main() {
	client := safehttp.NewClient(
		safehttp.WithTimeout(10*time.Second),
		safehttp.WithUserAgent(ua.Build("go_example", "v1.0.0")),
	)
	_ = client // client.Get("https://example.com") ...
}

func NewClientE

func NewClientE(opts ...Option) (*http.Client, error)

NewClientE is NewClient that returns an error where NewClient panics: when WithoutProxy and RequireProxy are both set, and when RequireProxy (or FLEET_REQUIRE_PROXY=1 without WithoutProxy) is in force but no HTTPS_PROXY, https_proxy, HTTP_PROXY or http_proxy variable is set. The error text is the text NewClient panics with. No client is returned with an error, so a caller that fails closed on the error never reaches the network without the proxy.

Use it where a panic is not acceptable: lazily built clients on a request path or in a worker goroutine, and /selftest or start-up checks that report the problem instead of crashing the process.

func NormalizeURL

func NormalizeURL(raw string) (*url.URL, error)

NormalizeURL parses raw into a validated *url.URL. Prepends "https://" if no scheme is present. Trims whitespace.

Example
package main

import (
	"fmt"

	"github.com/baditaflorin/go-common/safehttp"
)

func main() {
	u, err := safehttp.NormalizeURL("  example.com/path ")
	fmt.Println(u, err)
	_, err = safehttp.NormalizeURL("ftp://example.com")
	fmt.Println(err)
}
Output:
https://example.com/path <nil>
scheme must be http or https

func RequireFetchCacheContext

func RequireFetchCacheContext(ctx context.Context) context.Context

RequireFetchCacheContext marks a request that must be served by the process-wide fetch-cache delegate. This is used for explicit archive-only requests, such as source=commoncrawl. It overrides WithoutFetchCache and WithoutFetchCacheContext so callers cannot accidentally escape to the live origin. If no delegate can serve the request, safehttp returns a synthetic 502 response instead of making a direct request.

func RequiredFetchCacheFromContext

func RequiredFetchCacheFromContext(ctx context.Context) bool

RequiredFetchCacheFromContext reports whether ctx requires outbound GETs to use a fetch-cache delegate. This is exposed so server middleware and tests can verify that an explicit archive source cannot fall through to the origin.

func SetAllowedPrivateHosts

func SetAllowedPrivateHosts(hosts []string)

SetAllowedPrivateHosts replaces the hostname allowlist at runtime (mainly for tests). Production callers should prefer the SAFEHTTP_ALLOW_PRIVATE_HOSTS env var.

func SetAllowedPrivateIPs

func SetAllowedPrivateIPs(ips []net.IP)

SetAllowedPrivateIPs replaces the allowlist at runtime. Production callers should prefer the env-var path so operators can add a new fleet IP without rebuilding the binary.

func SetDefaultBackoffObserver

func SetDefaultBackoffObserver(o BackoffObserver)

SetDefaultBackoffObserver installs a process-wide backoff observer. Pass nil to disable. Wired by promx.AutoWire.

func SetDefaultFetchDelegate

func SetDefaultFetchDelegate(d FetchDelegate)

SetDefaultFetchDelegate installs a process-wide default fetch delegate. Calling it after NewClient has already constructed clients is safe but only affects subsequently-built clients — existing transports keep their original (nil or per-call) delegate.

Pass nil to disable the default.

func SetDefaultObserver

func SetDefaultObserver(o EgressObserver)

SetDefaultObserver installs a process-wide default observer. Calling it after NewClient has already constructed clients is safe but only affects subsequently-built clients — existing transports keep their original (nil or per-call) observer.

Pass nil to disable the default.

func ShutdownBreakerState

func ShutdownBreakerState(c *http.Client) error

ShutdownBreakerState flushes and stops the persistent-state background loop for a client previously constructed with WithPersistentBreakerState. Idempotent. Returns nil if the client has no associated state (common — most callers don't opt in) so it's safe to `defer` unconditionally.

func ValidateURL

func ValidateURL(u *url.URL) error

ValidateURL checks that u uses http or https and has a non-empty host.

func WithoutFetchCacheContext

func WithoutFetchCacheContext(ctx context.Context) context.Context

WithoutFetchCacheContext returns a child context that disables fetch-cache delegate routing for any safehttp request made with it. Eligible GETs go direct to origin instead of through the process-wide DefaultFetchDelegate, unless the context is also marked with RequireFetchCacheContext.

This is a per-request override that works even on clients built before server.New installed the default delegate, and even on the package-level default client — without having to thread a WithoutFetchCache() option through every call site.

The canonical user is the selftest suite: /selftest must validate the service's REAL outbound path (DNS + TLS + origin), not whatever the fleet cache happens to have warm. Routing selftest's live probes through a cold cache made them slow enough to trip `fleet-runner deploy`'s 8 s smoke /selftest timeout, false-failing otherwise-healthy deploys and rolling them back. Bypassing the cache for selftest keeps the gate fast and honest.

An explicit per-client WithFetchDelegate still wins — a caller that wired a delegate on purpose is asking for it.

Types

type BackoffEvent

type BackoffEvent struct {
	Host           string
	PriorStatus    int
	Outcome        string
	ConsultLatency time.Duration
	Waited         time.Duration
}

BackoffEvent is the per-consultation payload handed to a BackoffObserver. Outcome is one of:

"consulted_no_wait"  — coordinator returned wait_ms=0
"consulted_waited"   — coordinator returned wait_ms>0 and we slept
"unreachable"        — coordinator network failure (fail-open)

type BackoffObserver

type BackoffObserver interface {
	ObserveBackoff(BackoffEvent)
}

BackoffObserver receives one event per backoff-coordinator consultation (the WithBackoffCoordinator hook). Implementations MUST NOT block — callbacks run inline on the request hot path. The canonical implementation lives in go-common/promx and records safehttp_backoff_consult_total / duration.

safehttp deliberately defines the contract here rather than importing a metrics library: safehttp keeps zero metric-stack deps.

func DefaultBackoffObserver

func DefaultBackoffObserver() BackoffObserver

DefaultBackoffObserver returns the current process-wide observer or nil.

type BreakerStateOption

type BreakerStateOption func(*breakerStateConfig)

BreakerStateOption tweaks the persistent-breaker-state behaviour.

func WithPersistInterval

func WithPersistInterval(d time.Duration) BreakerStateOption

WithPersistInterval sets how often the breaker state is flushed to disk while the process is running. Default 60s. Values below 100ms are clamped to 100ms — a tighter loop is almost certainly a test artefact.

func WithSaveOnShutdown

func WithSaveOnShutdown(save bool) BreakerStateOption

WithSaveOnShutdown controls whether ShutdownBreakerState flushes once more on the way out. Default true; pass false if the caller owns shutdown ordering and wants to skip the final write.

type EgressEvent

type EgressEvent struct {
	Method    string
	Host      string
	Scheme    string
	Path      string
	Status    int // 0 if Err != nil
	Duration  time.Duration
	Bytes     int64  // response body bytes actually read; see doc above
	ViaProxy  bool   // true if the request was sent through an HTTP(S)_PROXY
	ProxyHost string // host of the proxy used, "" if direct
	// Channel buckets HOW the response was obtained: "direct" (no proxy),
	// "proxy" (via HTTPS_PROXY/egress proxy), or "cache_hit" (served from
	// the fleet fetch-cache delegate, no live origin fetch this call).
	// Bounded, Prometheus-safe (3 values). Empty string on events emitted
	// before this field existed is equivalent to "direct" for ViaProxy=false
	// events and "proxy" for ViaProxy=true — callers double-keying on both
	// fields stay correct either way.
	Channel string
	Outcome EgressOutcome // bucketed for label cardinality safety
	Err     error         // nil on HTTP-level responses (even 4xx/5xx)
}

EgressEvent is the per-request payload handed to an EgressObserver. All fields are populated whether the request succeeded or failed; Err is non- nil when the round-trip itself failed (DNS, dial, TLS, timeout, SSRF block). HTTP-level non-2xx responses are NOT errors — inspect Status.

Outcome is a coarse bucket safe to use as a Prometheus label (bounded cardinality). Host is the request URL's hostname (no port). Bytes is the number of response body bytes the caller actually read (see EgressObserver's timing doc above), falling back to Content-Length only when the caller closed the body without reading it at all.

type EgressObserver

type EgressObserver interface {
	ObserveEgress(EgressEvent)
}

EgressObserver receives one event per completed outbound HTTP attempt (success, error, or timeout). Implementations MUST NOT block — observer callbacks run inline on a request hot path. The canonical implementation lives in go-common/promx and records Prometheus counters/histograms.

Timing (since the Bytes-accuracy fix): for a request that got a response body, the event fires when the caller closes resp.Body — the one point in the http.Response contract every well-behaved caller is guaranteed to reach — NOT synchronously when RoundTrip returns. Duration/Status/Outcome reflect the round-trip itself (captured before the body is ever touched); only the emission MOMENT moves to Close(), so Bytes can be the caller's actual read count instead of a Content-Length guess. A caller that never closes resp.Body will not get an event for that request — that was already a resource leak (connection never returned to the pool) independent of this package. Requests with no body (errors, SSRF blocks) still emit synchronously in RoundTrip exactly as before.

safehttp deliberately defines the contract here rather than importing a metrics library directly: go-common/safehttp keeps zero metric-stack deps, services pull in promx (and its prometheus/client_golang transitive set) only when they want fleet metrics.

func DefaultObserver

func DefaultObserver() EgressObserver

DefaultObserver returns the current process-wide default, or nil if none is set. Exposed mainly for tests; production code does not need to read this directly.

type EgressOutcome

type EgressOutcome string

EgressOutcome buckets request results into a small, label-safe set.

const (
	OutcomeSuccess     EgressOutcome = "success"      // 2xx
	OutcomeRedirect    EgressOutcome = "redirect"     // 3xx (post-CheckRedirect)
	OutcomeClientError EgressOutcome = "client_error" // 4xx
	OutcomeServerError EgressOutcome = "server_error" // 5xx
	OutcomeBlocked     EgressOutcome = "blocked"      // SSRF guard rejected the dial
	OutcomeDNSFail     EgressOutcome = "dns_fail"     // resolver failure
	OutcomeTimeout     EgressOutcome = "timeout"      // context deadline / Transport timeout
	OutcomeTLSFail     EgressOutcome = "tls_fail"     // handshake failure not covered by the 1.2 fallback
	OutcomeNetError    EgressOutcome = "net_error"    // dial reset / EOF / generic transport error
)

type FetchDelegate

type FetchDelegate interface {
	FetchGet(ctx context.Context, url string, header http.Header) (*FetchResult, error)
}

FetchDelegate routes a plain GET through an alternate fetcher (e.g. the fleet fetch-cache). Implementations MUST be safe for concurrent use. A non-nil error normally falls through to direct egress; requests marked with RequireFetchCacheContext fail closed instead.

The concrete fleet-fetch-cache-backed adapter lives in go-common/ server (which imports both safehttp and fleetfetch). safehttp itself must NOT import fleetfetch — that would create an import cycle, since fleetfetch imports safehttp for its SSRF-safe fallback. The interface here is the seam that keeps the dependency one-directional.

func DefaultFetchDelegate

func DefaultFetchDelegate() FetchDelegate

DefaultFetchDelegate returns the current process-wide default, or nil if none is set. Exposed mainly for tests and for server.New's wiring; production code does not need to read this directly.

type FetchResult

type FetchResult struct {
	Status int
	Header http.Header
	Body   []byte
}

FetchResult is a delegate's response to a routed GET. Body is the upstream response body verbatim; Header is the upstream response header set (may be nil). Status is the upstream HTTP status code.

type Option

type Option func(*options)

Option configures NewClient.

func RequireProxy

func RequireProxy() Option

RequireProxy asserts HTTPS_PROXY (or HTTP_PROXY) is set in the environment at NewClient time. Services declared `proxy_egress: true` in service.yaml should pass this so a misconfigured deploy fails loudly at startup instead of silently leaking the dockerhost IP. Mutually exclusive with WithoutProxy. A missing variable makes NewClient panic; NewClientE returns the error instead.

Fleet-wide enforcement: when the environment variable FLEET_REQUIRE_PROXY=1 is set (rendered by fleet-runner deploy for every service with proxy_egress: true), NewClient behaves as if RequireProxy() was passed even when the caller forgot to. This is the belt-and-suspenders gate that catches every caller that grabs safehttp.NewClient() without thinking about proxy posture — see the 2026-05-21 Hetzner abuse complaint where five fleet tools leaked from the dockerhost IP because their NewClient() calls omitted RequireProxy() and the HTTPS_PROXY env happened to be unset at startup. WithoutProxy() still wins so SSRF probers, smuggling tests, and port scanners can opt out explicitly.

func WithBackoffCoordinator

func WithBackoffCoordinator(url string) Option

WithBackoffCoordinator configures consultation with go-fleet-backoff-coordinator (ADR-0013) before each retry attempt against a host that recently returned 5xx or 429. safehttp POSTs <url>/backoff with {host, last_response:{status, retry_after_header, ts}} and sleeps up to {wait_ms} (capped) in the response before the retry attempt. Coordinator outage = fall through to local backoff (current behaviour); never blocks indefinitely.

Recommended: read BACKOFF_COORDINATOR_URL from env.

func WithDegradedSink

func WithDegradedSink(sink *[]string) Option

WithDegradedSink wires a caller-passed *[]string slice that gets "<callee-host>-down" appended on 5xx or network-timeout responses. The caller is expected to surface this in its own response (e.g. degraded[] in the JSON envelope) so consumers know which sibling silently fell back to local logic.

Append is concurrency-safe (mu-protected internally). Caller owns the slice lifecycle and is responsible for resetting it per request.

Recommended call site:

var degraded []string
c := safehttp.NewClient(safehttp.WithDegradedSink(&degraded), ...)
... handle the request, surface degraded in the response ...

func WithDenyAllEgress

func WithDenyAllEgress() Option

WithDenyAllEgress is sugar for WithEgressAllowlist with no entries — every outbound call returns ErrEgressNotAllowed. Intended for services that MUST NOT make external calls (e.g. selftest-only fixtures, sandbox harnesses).

func WithEgressAllowlist

func WithEgressAllowlist(hosts ...string) Option

WithEgressAllowlist restricts outbound requests to the given hostnames. Any GET/POST/etc. whose URL.Hostname() is not in the list returns ErrEgressNotAllowed without making a network call.

Pass hostnames as exact matches: "api.hetzner.cloud", "api.github.com". Wildcards are NOT supported — keep the rule literal to force operators to register each fan-out destination explicitly (typically sourced from service.yaml auth.calls_external).

Matching is case-insensitive (DNS hostnames are case-insensitive per RFC 1035) and ignores the URL port — only the bare host is compared.

Not calling WithEgressAllowlist (the default) means "no allowlist enforcement" — existing safehttp behavior is unchanged. To explicitly forbid all outbound calls, use WithDenyAllEgress.

The check runs AFTER the existing SSRF guard (private-IP blocking) but BEFORE any network I/O is performed, so a blocked call resolves no DNS and opens no socket.

func WithFetchDelegate

func WithFetchDelegate(d FetchDelegate) Option

WithFetchDelegate attaches a FetchDelegate to this client. The delegate routes the client's eligible outbound GETs (no body, no Range header) through an alternate fetcher; on a delegate error the transport falls through to the normal direct path. A per-client delegate takes precedence over the process-wide DefaultFetchDelegate and applies even to WithoutProxy clients (the caller asked for it explicitly).

func WithForceHTTP2

func WithForceHTTP2() Option

WithForceHTTP2 sets Transport.ForceAttemptHTTP2 so the client offers "h2" in the TLS ClientHello ALPN and transparently upgrades to HTTP/2 against capable origins. Read the negotiated protocol back with NegotiatedProtocol(resp).

Why it is not the default: NewClient installs a custom DialContext (the SSRF guard). Per net/http semantics, providing a custom dialer or TLS config "conservatively disables HTTP/2" unless ForceAttemptHTTP2 is set. So by default the transport offers no "h2" in ALPN and resp.TLS.NegotiatedProtocol comes back empty even for HTTP/2-capable servers — most visibly on HEAD requests, where there is no body whose transfer would otherwise reveal the protocol. Services that need the negotiated ALPN (e.g. telling a modern HTTP/2 origin apart from a legacy HTTP/1.1-only one) previously worked around this with a dedicated TCP/443 TLS handshake; WithForceHTTP2 + NegotiatedProtocol is the fleet-canonical replacement.

HTTP/2 still rides the same SSRF-guarded dialer and the TLS-1.2 fallback transport, so the SSRF and handshake-recovery guarantees are unchanged.

Fetch-cache interaction: WithForceHTTP2 also disqualifies this client from the process-wide DefaultFetchDelegate (the fleet fetch-cache), same as WithoutProxy/WithoutFetchCache. A delegate-served response is reconstructed from cached bytes with no live TLS connection behind it, so resp.TLS is always nil and NegotiatedProtocol(resp) always comes back "" regardless of what the origin actually negotiated — routing a ForceHTTP2 client through the cache silently defeats the option. An explicit per-client WithFetchDelegate() is still honored (it's a deliberate opt-in); only the default delegate is skipped.

func WithMaxIdleConnsPerHost

func WithMaxIdleConnsPerHost(n int) Option

WithMaxIdleConnsPerHost sets Transport.MaxIdleConnsPerHost — the number of idle keep-alive connections safehttp will pool per upstream host.

The Go standard library defaults this to 2, which silently caps connection reuse: a service issuing many concurrent requests to the same host opens (and tears down) a fresh TCP+TLS connection for everything past the 2nd in-flight request. safehttp raises the default to 10 (defaultMaxIdleConnsPerHost). Raise it further for hot single-upstream callers (e.g. a tight crawl/poll loop against one API); n is clamped below MaxIdleConns (20) by the transport regardless. A value <= 0 restores the safehttp default.

func WithMaxRedirects

func WithMaxRedirects(n int) Option

WithMaxRedirects sets the redirect limit (default 5).

func WithObserver

func WithObserver(o EgressObserver) Option

WithObserver attaches an EgressObserver to the client. The observer receives one EgressEvent per round-trip attempt, inline on the hot path (so the implementation must be cheap and non-blocking). Use promx .NewEgressCollectors(...) in a service to get fleet-canonical metrics without writing a custom observer.

func WithPersistentBreakerState

func WithPersistentBreakerState(path string, opts ...BreakerStateOption) Option

WithPersistentBreakerState wires the local backoff-coordinator client state (the last-known-bad host list) to a disk-backed store at the given path. Only meaningful when paired with WithBackoffCoordinator — without it, there is no state to persist.

At construction the file (if present) is read and the in-memory state is warmed with it; on a periodic ticker (default 60s) and on ShutdownBreakerState, the state is written atomically (write to "<path>.tmp" then rename) so a crash mid-write cannot corrupt the file.

All failure modes are warnings, never fatal: persistence is best-effort observability, not load-bearing infrastructure.

Typical use:

cli := safehttp.NewClient(
    safehttp.WithBackoffCoordinator(os.Getenv("BACKOFF_COORDINATOR_URL")),
    safehttp.WithPersistentBreakerState("/var/lib/myservice/breaker.json"),
)
defer safehttp.ShutdownBreakerState(cli)

func WithPortCheck

func WithPortCheck() Option

WithPortCheck restricts outbound connections to ports 80 and 443 only.

func WithProxyConnectResponseHook

func WithProxyConnectResponseHook(hook ProxyConnectResponseHook) Option

WithProxyConnectResponseHook installs a narrowly scoped observer for proxy CONNECT responses. It is intended for proxy-specific policy signals that the standard transport otherwise reduces to an untyped request error.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the total request timeout (default 8s).

func WithTraceCollector

func WithTraceCollector(url string) Option

WithTraceCollector configures auto-emit of call traces to go-fleet-call-tracer (ADR-0011). Each completed request POSTs a trace record to <url>/traces with the fields the tracer's POST /traces handler expects: {trace_id, span_id, from_service, to_service, method, path, status, duration_ms, ts}. Async, fire-and-forget — must NOT block the request. Failure to emit is logged at most once per minute (rate-limited) and silently dropped.

Recommended: read CALL_TRACER_URL from env in main.go and pass here. If env unset, skip the option — safehttp falls through to current behaviour.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent on all requests including redirects.

func WithoutFetchCache

func WithoutFetchCache() Option

WithoutFetchCache forces this client onto the direct egress path even when a process-wide DefaultFetchDelegate is installed. Use for clients that must observe real origin behavior (SSRF probers, smuggling detectors, latency/availability monitors) but that don't otherwise set WithoutProxy. An explicit WithFetchDelegate or a context marked by RequireFetchCacheContext still wins over this flag.

Note: WithForceHTTP2() implies this same bypass automatically (see that option's doc comment) — you don't need to also pass WithoutFetchCache() alongside it. Reach for WithoutFetchCache directly when you need a real-origin probe but don't need ForceAttemptHTTP2 for some other reason (e.g. an availability check that only cares about status code / latency, not ALPN).

func WithoutProxy

func WithoutProxy() Option

WithoutProxy explicitly disables proxy use even if HTTP_PROXY / HTTPS_PROXY are set in the environment. Use for services that legitimately need a direct egress path (SSRF probers, smuggling tests, port scanners) where routing through the fleet proxy would defeat the purpose. Mutually exclusive with RequireProxy — passing both panics in NewClient (NewClientE returns the error instead).

type ProxyConnectResponseHook

type ProxyConnectResponseHook func(context.Context, *url.URL, *http.Request, *http.Response) error

ProxyConnectResponseHook observes the HTTP response to an HTTPS proxy CONNECT request before net/http validates that response. Returning an error aborts the request; hooks should classify only an explicit proxy response, not infer outcomes from ordinary origin status codes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL