egressproxy

package
v0.111.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 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 egressproxy is a credential-injecting forward proxy that listens on loopback only, so a browser that cannot authenticate to an upstream proxy can still be forced through one.

Why this exists

Chromium cannot log in to an upstream proxy from a URL or a flag (--proxy-server ignores credentials, and a 407 is unanswerable in headless mode). The fleet's egress proxy (Webshare, picked per request by proxysupplier) needs a Proxy-Authorization header. This package sits in between: the browser is started with --proxy-server pointing at the local listener, the listener asks a proxysupplier.Supplier for an upstream, adds the header and relays. Every browser isolation mode (shared tab, isolated context, process per render) inherits it because the proxy is a browser-level flag.

What it serves

  • CONNECT host:port: a tunnel. The proxy sends CONNECT to the upstream with Proxy-Authorization, relays success as 200 and splices the two sockets.
  • Absolute-URI plain HTTP (GET http://host/path): forwarded to the upstream with Proxy-Authorization; hop-by-hop and Proxy-* headers from the browser are removed. WebSocket upgrades over plain HTTP are spliced after the upstream's 101.

Fail closed

There is no direct path to a target. The only direct dial is to the upstream proxy itself. When the supplier returns "" (nothing configured, every exit IP cooling down) or an address that loops back to this listener, the request is answered 503 and the target is never contacted. Config.RequireUpstream only makes Start refuse a nil Supplier; it does not open a direct path. Destinations that must be reached without the proxy (fleet-internal hosts, see egress.Direct) belong in the browser's --proxy-bypass-list, not here.

SSRF guard

Before the upstream is dialed the target host goes through Config.Guard (DefaultGuard: safehttp.GuardHost, so loopback, private, link-local and metadata addresses, hostnames resolving to them, and the compliance denylist are answered 403, honouring SAFEHTTP_ALLOW_PRIVATE_IPS and SAFEHTTP_ALLOW_PRIVATE_HOSTS). Verdicts are cached per host:port for 30 s in a bounded cache. The upstream resolves the target name itself, so the guard cannot close a DNS-rebinding gap; it is defence in depth against pages that steer the browser at internal address literals.

Retry and result feedback

A CONNECT is attempted on at most two upstreams inside DialTimeout, retrying only while nothing has been relayed to the browser. If the supplier implements proxysupplier.ResultReporter the proxy calls MarkResult(addr, false) on a dial or handshake failure, a 407 and a 5xx answer to CONNECT, and MarkResult(addr, true) on an established tunnel. A plain HTTP request is retried only when it is safe to repeat (a dial failure, or a body-less GET/HEAD/OPTIONS). Set Config.IgnoreUpstream5xx when the upstream answers 5xx for a dead target rather than a bad exit IP, so good IPs are not put in cooldown.

Limits

MaxConns (256) concurrent client connections, the excess answered 503 at once; DialTimeout (10 s); IdleTimeout (60 s, nothing moved in either direction); ReadHeaderTimeout (15 s); MaxTunnelBytes (64 MiB per direction of one tunnel, 0 = unlimited). ConfigFromEnv reads EGRESSPROXY_* overrides.

Metrics

Registered on Config.Registerer (default promx.Registry(), so call it after promx.Init / telemetry.Init): egressproxy_requests_total{kind,result}, egressproxy_bytes_total{direction}, egressproxy_active_tunnels, egressproxy_upstream_attempts_total{result} and egressproxy_request_duration_seconds{kind}. Labels are fixed strings: no host, no upstream address, no credential.

Logging

Logs carry the upstream's host:port, its scheme and a result, never the credentialed URL, and are rate limited per cause.

Usage

cfg := egressproxy.ConfigFromEnv()
cfg.Supplier = proxysupplier.New() // PROXY_SUPPLIER=webshare_direct|env|multi
cfg.Registerer = promx.Registry()
p, err := egressproxy.Start(ctx, cfg)
if err != nil {
    return err
}
defer p.Close()

opts = append(opts,
    chromedp.Flag("proxy-server", p.URL()),
    // Send loopback through the proxy too, so the guard refuses it.
    chromedp.Flag("proxy-bypass-list", "<-loopback>"),
    // Chromium's own background traffic (component updater, time sync,
    // Google endpoints) also goes through the proxy: switch it off so it
    // does not spend upstream bandwidth or put exit IPs in cooldown.
    chromedp.Flag("disable-background-networking", true),
    chromedp.Flag("disable-component-update", true),
    chromedp.Flag("disable-sync", true),
)

To keep one exit IP per site (a proxysupplier.KeyedSupplier such as webshare_direct), give the proxy a key:

cfg.KeyFunc = func(t egressproxy.Target) string { return t.Host }

Index

Constants

View Source
const (
	DefaultMaxConns          = 256
	DefaultDialTimeout       = 10 * time.Second
	DefaultIdleTimeout       = 60 * time.Second
	DefaultReadHeaderTimeout = 15 * time.Second
	DefaultMaxTunnelBytes    = int64(64 << 20)
	DefaultGuardCacheTTL     = 30 * time.Second
	DefaultGuardCacheSize    = 4096
)

Defaults applied by DefaultConfig and ConfigFromEnv.

View Source
const (
	EnvMaxConns          = "EGRESSPROXY_MAX_CONNS"
	EnvDialTimeout       = "EGRESSPROXY_DIAL_TIMEOUT"
	EnvIdleTimeout       = "EGRESSPROXY_IDLE_TIMEOUT"
	EnvReadHeaderTimeout = "EGRESSPROXY_READ_HEADER_TIMEOUT"
	EnvMaxTunnelBytes    = "EGRESSPROXY_MAX_TUNNEL_BYTES"
	EnvRequireUpstream   = "EGRESSPROXY_REQUIRE_UPSTREAM"
	EnvIgnoreUpstream5xx = "EGRESSPROXY_IGNORE_UPSTREAM_5XX"
	EnvGuardCacheTTL     = "EGRESSPROXY_GUARD_CACHE_TTL"
)

Environment variables read by ConfigFromEnv.

Variables

View Source
var (
	// ErrDenied marks a target the guard refuses (answered 403). Custom guards
	// may return it or any other error; only ErrGuardUnavailable changes the
	// answer.
	ErrDenied = errors.New("egressproxy: target denied by the SSRF guard")
	// ErrGuardUnavailable marks a guard that could not reach a verdict, for
	// example because the target name did not resolve. The request is refused
	// (fail closed) with 502 instead of 403, and the verdict is cached only
	// briefly.
	ErrGuardUnavailable = errors.New("egressproxy: SSRF guard could not decide")
)
View Source
var (
	// ErrNoSupplier is returned by Start when RequireUpstream is set and
	// Config.Supplier is nil.
	ErrNoSupplier = errors.New("egressproxy: RequireUpstream is set but Config.Supplier is nil")
)

Errors returned by Start.

Functions

func DefaultGuard

func DefaultGuard(ctx context.Context, host, port string) error

DefaultGuard is the guard used when Config.Guard is nil. It reuses safehttp.GuardHost, so it rejects literal loopback, private, link-local (cloud metadata 169.254.169.254), CGNAT and ULA addresses, hostnames that resolve to any of them, and the compliance denylist, and it honours the same SAFEHTTP_ALLOW_PRIVATE_IPS / SAFEHTTP_ALLOW_PRIVATE_HOSTS allow-lists.

The upstream proxy resolves the target name itself, so this check cannot close a DNS-rebinding gap; it stops the browser from being steered at internal address literals and at names that already point inside.

Types

type Config

type Config struct {
	// Supplier picks the upstream proxy per connection or request. It is the
	// only way out: there is no direct path to a target in this package.
	Supplier proxysupplier.Supplier

	// KeyFunc, when set and the Supplier also implements
	// proxysupplier.KeyedSupplier, gives the key passed to ProxyURLForKey (for
	// example the target host, to keep one exit IP per site). An empty key
	// means "no preference" and the supplier's ProxyURL is used. A retry always
	// uses ProxyURL: after a failure stickiness no longer matters.
	KeyFunc func(Target) string

	// RequireUpstream makes Start fail with ErrNoSupplier when Supplier is nil.
	// DefaultConfig and ConfigFromEnv set it to true. It does NOT enable any
	// direct path: whatever its value, a request for which no upstream is
	// available is refused with 503 and the target is never dialed.
	RequireUpstream bool

	// Guard is the SSRF check run on every target before the upstream is
	// dialed. Nil selects DefaultGuard. Its verdicts are cached per host:port
	// for GuardCacheTTL (denials as long as allows; "unavailable" verdicts
	// only briefly).
	Guard Guard

	// GuardCacheTTL and GuardCacheSize bound the verdict cache (defaults 30 s,
	// 4096 entries; the cache is cleared wholesale when full).
	GuardCacheTTL  time.Duration
	GuardCacheSize int

	// MaxConns caps concurrent client connections (default 256). A connection
	// over the cap is answered 503 immediately and closed.
	MaxConns int

	// DialTimeout bounds one request's upstream selection, dial and CONNECT
	// handshake across both attempts (default 10 s). The first attempt may use
	// at most 60% of it so that a hanging upstream still leaves time for the
	// retry.
	DialTimeout time.Duration

	// IdleTimeout closes a connection (and its upstream) when nothing moved in
	// either direction for this long (default 60 s).
	IdleTimeout time.Duration

	// ReadHeaderTimeout bounds reading one request's headers (default 15 s).
	ReadHeaderTimeout time.Duration

	// MaxTunnelBytes caps the bytes relayed in each direction of one tunnel
	// (and the request/response body of one plain HTTP exchange). Exceeding it
	// closes the tunnel and counts a byte_cap result. 0 or negative means
	// unlimited; DefaultConfig sets 64 MiB.
	MaxTunnelBytes int64

	// IgnoreUpstream5xx stops an upstream 5xx answer to CONNECT from counting
	// as an upstream failure: no MarkResult(false), no retry, the status is
	// relayed. By default a 5xx marks the exit IP bad, which for webshare_direct
	// starts a cooldown; set this when the upstream uses 5xx to report a dead
	// target rather than a bad exit IP.
	IgnoreUpstream5xx bool

	// Registerer receives the egressproxy_* metrics. Nil uses promx.Registry(),
	// the registry the service's /metrics serves once promx.Init (or
	// telemetry.Init) has run. A collector that is already registered (a second
	// Proxy in the same process) is reused.
	Registerer prometheus.Registerer

	// Logger receives operational logs (host:port of the upstream, scheme,
	// result; never the credentialed URL). Nil uses slog.Default().
	Logger *slog.Logger

	// Now is the clock for log rate limiting and the guard cache; nil uses
	// time.Now. Tests inject a fake.
	Now func() time.Time
}

Config configures Start. Start from DefaultConfig or ConfigFromEnv and set Supplier; a bare Config literal has no byte cap and does not require an upstream at start-up (zero means "off" for MaxTunnelBytes, as documented on each field). Durations and counts that cannot be zero (MaxConns, the timeouts, the guard cache) fall back to the defaults when they are <= 0.

func ConfigFromEnv

func ConfigFromEnv() Config

ConfigFromEnv returns DefaultConfig with environment overrides applied. It does not set Supplier, Guard, KeyFunc, Registerer or Logger. A value that does not parse (or is out of range) is ignored and the default stays.

EGRESSPROXY_MAX_CONNS             integer > 0
EGRESSPROXY_DIAL_TIMEOUT          duration (10s)
EGRESSPROXY_IDLE_TIMEOUT          duration (60s)
EGRESSPROXY_READ_HEADER_TIMEOUT   duration (15s)
EGRESSPROXY_MAX_TUNNEL_BYTES      integer bytes; 0 = unlimited
EGRESSPROXY_REQUIRE_UPSTREAM      bool (true)
EGRESSPROXY_IGNORE_UPSTREAM_5XX   bool (false)
EGRESSPROXY_GUARD_CACHE_TTL       duration (30s)

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the documented defaults with RequireUpstream set. The caller still has to set Supplier.

type Guard

type Guard func(ctx context.Context, host, port string) error

Guard decides whether the proxy may open a path to host:port at all. A nil error allows it. An error that wraps ErrGuardUnavailable answers 502; any other error answers 403. The guard runs before the upstream proxy is dialed. See DefaultGuard.

type Proxy

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

Proxy is a running local forward proxy. Create it with Start and stop it with Close.

func Start

func Start(ctx context.Context, cfg Config) (*Proxy, error)

Start listens on 127.0.0.1 on an ephemeral port and serves until ctx is cancelled or Close is called. It never listens on any other interface.

func (*Proxy) Addr

func (p *Proxy) Addr() string

Addr returns the listen address, "127.0.0.1:PORT".

func (*Proxy) Close

func (p *Proxy) Close() error

Close stops accepting, closes every open connection and tunnel and waits for the handlers to finish. It is safe to call more than once.

func (*Proxy) URL

func (p *Proxy) URL() string

URL returns the proxy URL to hand to a browser, "http://127.0.0.1:PORT".

type Target

type Target struct {
	// Kind is "connect" for a CONNECT tunnel and "http" for a plain
	// absolute-URI request.
	Kind string
	// Host and Port are the destination the browser asked for (no brackets
	// around an IPv6 literal; Port defaults to 80 for plain HTTP).
	Host string
	Port string
	// Client is the address of the local connection (a loopback port of the
	// browser process).
	Client net.Addr
}

Target describes one browser request the proxy is about to serve. It is handed to Config.KeyFunc. It never carries upstream credentials.

Jump to

Keyboard shortcuts

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