netproxy

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: AGPL-3.0 Imports: 18 Imported by: ? modules, 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 netproxy routes outbound connections through an HTTP CONNECT proxy.

It exists for hosts where the only way out is an egress proxy that allows "CONNECT host:443" (hosted agent sandboxes, locked-down corporate VMs): outbound UDP is blocked, direct TCP is killed, and local DNS for the target hostnames may be poisoned. Everything here therefore keeps the target as a HOSTNAME all the way to the proxy — nothing in this package resolves a target address locally — and TLS stays end-to-end between the caller and the real server (the proxy only ever sees an opaque tunnel).

Two pieces:

  • Resolver decides, per target, which proxy (if any) to use: an explicit URL, the conventional environment variables (HTTPS_PROXY, ALL_PROXY, NO_PROXY, ...), or none. The same decision is exposed as a per-address lookup for raw TCP dials (ProxyForAddr) and as an http.Transport.Proxy function (ProxyForRequest), so HTTP clients and raw TCP dials follow identical rules.
  • Dialer is a DialContext-compatible dialer that tunnels through the proxy the Resolver picks, or dials directly when there is none.

Rotating credentials

Some egress proxies (Meta Muse's, for one) rotate the credentials embedded in HTTPS_PROXY every few minutes. A fresh shell sees the current value; a long-running process keeps its launch-time copy and gets 407 Proxy Authentication Required on every new CONNECT, while tunnels it already opened stay up. A Resolver therefore re-reads its proxy settings:

  • on a timer (DefaultRefreshInterval, see WithRefreshInterval): the first lookup after the interval has passed starts a refresh in the background and, like every lookup, answers from the settings in hand, so a slow refresh never holds up a connection;
  • immediately when a proxy rejects its credentials: Dialer and RefreshingTransport then refresh once and retry once on a new connection, and only when the refresh produced different credentials.

A ModeAuto Resolver re-reads the process environment. WithRefreshCommand adds a command whose output is the current proxy URL, for processes whose own environment never changes; by convention programs take that command from EnvRefreshCommand (PILOT_PROXY_CMD). Concurrent rejections share one refresh, and a failed refresh keeps the last good settings.

Proxy credentials (URL userinfo) are only ever written to the proxy in a Proxy-Authorization header. They never appear in errors or in the output of Redact / Resolver.String, which is what callers must use for logging. A refresh command's output is treated the same way and is never logged.

Index

Constants

View Source
const (
	// ModeAuto takes the proxy from the environment (see FromEnvironment).
	ModeAuto = "auto"
	// ModeOff never uses a proxy.
	ModeOff = "off"
	// ModeExplicit uses one explicitly configured proxy URL for every target.
	ModeExplicit = "explicit"
)

Mode names. Parse accepts ModeAuto and ModeOff (case-insensitive) in addition to an explicit proxy URL; Resolver.Mode reports one of the three.

View Source
const DefaultRefreshInterval = 60 * time.Second

DefaultRefreshInterval is how long a refreshing Resolver uses the settings it last read before a lookup starts reading them again.

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout bounds a Dialer's connection establishment when neither Dialer.Timeout nor the context sets a tighter limit.

View Source
const EnvRefreshCommand = "PILOT_PROXY_CMD"

EnvRefreshCommand is the environment variable that, by convention, holds the refresh command for WithRefreshCommand, e.g.

PILOT_PROXY_CMD='bash -c '\''printf %s "$https_proxy"'\'''

netproxy never reads it on its own: a program opts in by passing WithRefreshCommand(os.Getenv(EnvRefreshCommand)).

Variables

This section is empty.

Functions

func Redact

func Redact(u *url.URL) string

Redact renders a proxy URL for logging as scheme://host:port, replacing any userinfo (user name and password alike) with "***" and dropping the path, query and fragment. Redact(nil) is "".

A URL with "@" in its path, query, fragment or opaque part is taken to be a proxy URL whose credentials held an unescaped '/', '?' or '#', which url.Parse splits so that part of the credentials lands in Host. Redact then withholds everything before the last "@" and shows only what follows it as the host.

func RefreshingTransport added in v0.5.15

func RefreshingTransport(base *http.Transport, r *Resolver) http.RoundTripper

RefreshingTransport returns an http.RoundTripper for HTTP clients behind a proxy that rotates its credentials. It sends requests through a copy of base (http.DefaultTransport when base is nil) whose Proxy is r.ProxyForRequest, so every new connection uses the current credentials, and, when the proxy rejects them on CONNECT, refreshes r and retries the request once — only when the refresh produced different credentials, and only for a request that can be sent again:

  • GET, HEAD, OPTIONS and TRACE requests, and requests carrying an Idempotency-Key or X-Idempotency-Key header, without a body or with GetBody set;
  • after a 407, any request with GetBody set: the proxy refused the tunnel, so the server never saw the first attempt.

A request that cannot be replayed (a POST whose body cannot be rewound, say) gets the error, but the refresh still happens, so the next request goes out with fresh credentials.

net/http reports a refused CONNECT only as an error holding the proxy's reason phrase — "Proxy Authentication Required", "unknown status code" when there is none, or whatever text the proxy chose — without the status code. RefreshingTransport therefore reads the status from the CONNECT response itself (http.Transport.OnProxyConnectResponse, chained after base's own hook) and turns every non-200 answer into a *ConnectError, whose message never includes proxy-supplied text.

A CONNECT response net/http cannot parse ("malformed HTTP status code", say), which is how some proxies' rejections surface, also triggers a refresh, and its error likewise says only what was wrong with the response, never its text. That holds only while the tunnel is being set up: once net/http has a connection to send the request on, an unparseable response came from the server through the tunnel, and its error is returned untouched, without a refresh. Having no status code to prove it a refusal, such a rejection is retried only for the idempotent methods above.

net/http pools connections by proxy URL, credentials included, so once a refresh changes the proxy settings, the idle connections opened under the old ones can never be picked again. The first request after such a change therefore closes the idle connections (in-flight ones finish normally). The returned RoundTripper has a CloseIdleConnections method, so http.Client.CloseIdleConnections reaches the copy of base.

Types

type ConnectError

type ConnectError struct {
	// Target is the "host:port" the CONNECT asked for.
	Target string
	// StatusCode is the proxy's HTTP status, e.g. 407 or 403.
	StatusCode int
}

ConnectError is returned when the proxy answers CONNECT with a non-2xx status. Its message never includes credentials or proxy-supplied text.

func (*ConnectError) Error

func (e *ConnectError) Error() string

type Dialer

type Dialer struct {
	// Resolver picks the proxy per target. nil never proxies.
	Resolver *Resolver

	// Timeout bounds the whole establishment: the TCP connect to the proxy
	// (or to the target when dialing directly), the TLS handshake with an
	// https:// proxy, and the CONNECT exchange, including a credential
	// refresh and the one retry after a rejection. Zero means
	// DefaultTimeout. An earlier deadline on the DialContext context wins.
	Timeout time.Duration

	// Forward dials the proxy itself, and the target when no proxy applies.
	// nil uses a net.Dialer.
	Forward func(ctx context.Context, network, addr string) (net.Conn, error)

	// TLSConfig configures the TLS session with an https:// proxy (not with
	// the target). nil uses defaults; ServerName defaults to the proxy host.
	TLSConfig *tls.Config
}

Dialer opens stream connections, tunnelling them through the HTTP CONNECT proxy its Resolver picks for each target and dialing directly when there is none. The zero value (or a nil *Dialer) always dials directly.

DialContext has the signature of (*net.Dialer).DialContext, so a Dialer drops into anything that accepts a dial function:

d := netproxy.NewDialer(resolver)
conn, err := d.DialContext(ctx, "tcp", "registry.example.net:443")

The target address is sent to the proxy verbatim ("CONNECT host:port") and never resolved locally, so it works when local DNS for the target is broken or poisoned. Callers that want TLS wrap the returned conn with tls.Client themselves; TLS then runs end-to-end with the real server.

When the proxy rejects the credentials (407 Proxy Authentication Required, or a CONNECT response so garbled it cannot be parsed, which is how some proxies' rejections arrive), the Dialer refreshes the Resolver (see Resolver.Refresh) and, if that produced different credentials, retries once on a new connection. Tunnels opened earlier are never touched. A Resolver with nothing to refresh gets no retry.

Errors never quote the proxy's response: a 407 or other refusal is a *ConnectError, and a response that cannot be parsed is reported by what was wrong with it ("malformed HTTP status code", say) without its text.

func NewDialer

func NewDialer(r *Resolver) *Dialer

NewDialer returns a Dialer that routes connections as r decides.

func (*Dialer) Dial

func (d *Dialer) Dial(network, addr string) (net.Conn, error)

Dial is DialContext with a background context.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

DialContext connects to addr ("host:port") on network, through the proxy the Resolver selects for addr or directly when it selects none. Only "tcp", "tcp4" and "tcp6" can be tunnelled.

type EnvError

type EnvError struct {
	// Var is the environment variable, e.g. "HTTP_PROXY".
	Var string
	// Err says why the value is unusable.
	Err error
}

EnvError reports a proxy environment variable whose value cannot be used. Its message names the variable and never includes the value's credentials.

func (*EnvError) Error

func (e *EnvError) Error() string

func (*EnvError) Unwrap

func (e *EnvError) Unwrap() error

type Option added in v0.5.15

type Option func(*options)

Option configures a Resolver built by NewResolver.

func WithRefreshCommand added in v0.5.15

func WithRefreshCommand(command string) Option

WithRefreshCommand makes the Resolver take its proxy URL from the output of command, run with "sh -c" in the process's environment, stdin and stderr discarded, for at most 10 seconds. On Unix the command runs in a process group of its own, and a run that times out has the whole group killed, so the processes it started do not outlive it. The output, surrounding whitespace trimmed, must be one http:// or https:// proxy URL with its current credentials. It is never logged or included in errors.

The command runs when NewResolver builds the Resolver, again in the background at most every refresh interval, and whenever a proxy rejects the credentials. Its URL replaces the explicit URL, or in ModeAuto the environment's proxy URLs, while NO_PROXY and the loopback exemption keep applying. If a run fails, or prints nothing or something that is not a proxy URL, the last good URL stays in use.

A child process inherits this process's environment, so the command must read the current value from somewhere that tracks the rotation — in Meta Muse a new bash does: bash -c 'printf %s "$https_proxy"'. The command is trusted configuration, like the proxy URL itself. An empty command leaves the Resolver unchanged, so wiring an unset EnvRefreshCommand is harmless.

func WithRefreshErrorHandler added in v0.5.15

func WithRefreshErrorHandler(fn func(error)) Option

WithRefreshErrorHandler has fn called with the error when a refresh fails, once per run of consecutive failures: after a failure it is not called again until a refresh has succeeded. The error never contains credentials or the refresh command's output (a WithRefreshFunc function's own errors aside). fn is called from the refreshing goroutine and must not block.

func WithRefreshFunc added in v0.5.15

func WithRefreshFunc(fn func(ctx context.Context) (string, error)) Option

WithRefreshFunc is WithRefreshCommand for a Go function: fn returns the current proxy URL, under the same rules as a refresh command's output. It must honour ctx, which carries the 10 second refresh deadline. Its errors are passed on (prefixed "netproxy: proxy refresh: "), so they must not contain credentials. A nil fn leaves the Resolver unchanged.

func WithRefreshInterval added in v0.5.15

func WithRefreshInterval(d time.Duration) Option

WithRefreshInterval sets how long the Resolver uses the settings it last read before a lookup starts reading them again. That timed refresh runs in the background: the lookup that starts it, and every lookup while it runs, answers from the settings in hand, so a slow or hung refresh source never holds up a dial or a request (a proxy rejecting those settings is what waits for a refresh). Zero means DefaultRefreshInterval; a negative interval turns timed refreshes off, leaving only the refreshes a rejected credential triggers (and explicit Refresh calls).

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver decides which proxy, if any, an outbound connection to a given target should go through. A nil *Resolver is valid and never proxies. Resolvers are safe for concurrent use.

Off and Explicit Resolvers without a refresh source never change. A ModeAuto Resolver, and any Resolver with a refresh source (WithRefreshCommand, WithRefreshFunc), re-reads its settings over time; see the package documentation under "Rotating credentials".

func Explicit

func Explicit(proxyURL string) (*Resolver, error)

Explicit returns a Resolver that sends every target — including loopback and anything NO_PROXY would exempt — through proxyURL. The URL must use the http or https scheme ("http://[user:pass@]host[:port]"); a URL with no scheme is taken as http. The port defaults to 80 for http and 443 for https. Everything up to the last "@" is the userinfo, so credentials may hold unescaped '/', '?', '#' or '@'; percent-escapes in them are decoded.

The Resolver never changes; NewResolver with WithRefreshCommand builds one whose credentials follow a refresh source.

func FromEnvironment

func FromEnvironment() (*Resolver, error)

FromEnvironment returns a Resolver built from the conventional proxy environment variables:

  • TLS and raw TCP targets (ProxyForAddr, and https:// / wss:// requests) use the first usable one of HTTPS_PROXY, https_proxy, ALL_PROXY, all_proxy.
  • Plain http:// / ws:// requests use the first usable one of HTTP_PROXY, http_proxy, and otherwise the same proxy as TLS targets. HTTP_PROXY (upper case) is ignored when REQUEST_METHOD is set, as net/http does, so a CGI request header cannot inject a proxy.
  • NO_PROXY / no_proxy exempts targets: a comma- or space-separated list of host names (matching the name and its subdomains; a leading "." or "*." matches subdomains only), IP addresses, CIDR ranges, each optionally with ":port", or "*" for everything. localhost and loopback addresses are always exempt.

Each variable is parsed on its own, so one bad value never disables another. A value is unusable when it is malformed or names a scheme other than http or https (socks5://, for example). An unusable HTTP_PROXY, http_proxy, ALL_PROXY or all_proxy is skipped (the next variable in its list applies) and reported by Warnings. Only an unusable HTTPS_PROXY or https_proxy, which explicitly names the TLS proxy, makes FromEnvironment fail, with an *EnvError naming it.

The variables are read now, and read again at most every DefaultRefreshInterval and whenever a proxy rejects the credentials (see Refresh), so a process whose environment is updated in place follows it. A later reading that fails keeps the previous one.

An environment with no usable proxy variables yields a Resolver that does not proxy (Enabled reports false). Neither errors nor warnings ever echo a value's credentials.

func NewResolver added in v0.5.15

func NewResolver(spec string, opts ...Option) (*Resolver, error)

NewResolver is Parse with options, for example a refresh command for proxies that rotate their credentials:

r, err := netproxy.NewResolver(spec,
	netproxy.WithRefreshCommand(os.Getenv(netproxy.EnvRefreshCommand)),
	netproxy.WithRefreshErrorHandler(func(err error) {
		slog.Warn("proxy credential refresh failed", "err", err)
	}))

Options do not apply to "off". With a refresh source, NewResolver runs it once before returning; if that run fails, the Resolver starts from the environment ("auto") or the given URL, and the error goes to the WithRefreshErrorHandler function.

func Off

func Off() *Resolver

Off returns a Resolver that never uses a proxy.

func Parse

func Parse(spec string) (*Resolver, error)

Parse builds a Resolver from a -proxy style setting: "auto" (or "") reads the environment via FromEnvironment, "off" disables proxying, and anything else is an explicit proxy URL (see Explicit). Deciding whether "auto" applies at all (for example only in a TCP-only transport mode) is the caller's policy; compare the setting against ModeAuto for that.

Parse(spec) is NewResolver(spec) without options.

func (*Resolver) Enabled

func (r *Resolver) Enabled() bool

Enabled reports whether the Resolver can route any target through a proxy. It is false for Off, for a nil Resolver and for an environment without proxy variables. A Resolver with a refresh source reports true: the source can supply a proxy at any time.

func (*Resolver) Mode

func (r *Resolver) Mode() string

Mode reports ModeAuto, ModeOff or ModeExplicit. A nil Resolver is ModeOff.

func (*Resolver) ProxyForAddr

func (r *Resolver) ProxyForAddr(addr string) (*url.URL, error)

ProxyForAddr returns the proxy to tunnel a raw TCP (or TLS) connection to addr ("host:port") through, or nil to dial directly. addr is inspected as text only; host names are never resolved. When the refresh interval has passed, the lookup starts a refresh in the background (see WithRefreshInterval) and answers from the current settings; it never waits for a refresh.

func (*Resolver) ProxyForRequest

func (r *Resolver) ProxyForRequest(req *http.Request) (*url.URL, error)

ProxyForRequest returns the proxy for req, or nil for a direct connection. Its signature matches http.Transport.Proxy:

tr.Proxy = resolver.ProxyForRequest

https:// and wss:// requests follow exactly the same rules as ProxyForAddr (net/http then tunnels them with CONNECT, sending the host name); http:// and ws:// requests prefer HTTP_PROXY in ModeAuto. The result is always the current proxy URL, and like ProxyForAddr the lookup never waits for a refresh; RefreshingTransport also retries a request once when the proxy rejects the credentials.

func (*Resolver) Refresh added in v0.5.15

func (r *Resolver) Refresh(ctx context.Context) error

Refresh re-reads the Resolver's settings now: the environment in ModeAuto, and the refresh source if there is one. A refresh already in progress is joined rather than repeated. On error the previous settings stay in use. Refresh is a no-op for Resolvers with nothing to re-read (nil, Off, and Explicit without a refresh source). The error never contains credentials; ctx only bounds the wait.

func (*Resolver) String

func (r *Resolver) String() string

String describes the Resolver for logs, with credentials redacted, e.g. "off", "http://***@proxy.internal:3128" or "auto: http://***@proxy.internal:3128 (NO_PROXY=localhost,.corp)". Resolvers with a refresh source add " (credentials refreshed by command)" or " (credentials refreshed by callback)".

func (*Resolver) Warnings

func (r *Resolver) Warnings() []error

Warnings reports the proxy environment variables the current reading of the environment skipped because their values are unusable, one *EnvError per variable, in precedence order. It is empty for Resolvers that do not read the environment. The messages are safe to log.

Jump to

Keyboard shortcuts

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