proxy

package
v3.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 28 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUpstreamSchemeNotAllowed is returned when the proxied URL uses a
	// scheme outside the configured allowlist (default: http, https).
	ErrUpstreamSchemeNotAllowed = errors.New("proxy: upstream scheme is not allowed")

	// ErrUpstreamHostInvalid is returned when the proxied URL is empty,
	// missing a host or cannot be parsed (the *url.Error is wrapped too).
	ErrUpstreamHostInvalid = errors.New("proxy: upstream host is empty or invalid")

	// ErrUpstreamHostBlocked is returned when the proxied URL resolves to an address inside a
	// blocked range (loopback, RFC 1918 private, link-local, multicast, unspecified, CGNAT or
	// another special-use range) and AllowPrivateIPs is false. So is an unresolvable host, as the
	// check fails closed; ErrUpstreamHostUnresolvable tells the two apart.
	ErrUpstreamHostBlocked = errors.New("proxy: upstream host resolves to a blocked address")

	// ErrUpstreamHostUnresolvable is returned with ErrUpstreamHostBlocked when a lookup fails or
	// answers with no address; errors.As finds the *net.DNSError of a failed lookup.
	ErrUpstreamHostUnresolvable = errors.New("proxy: upstream host could not be resolved")

	// ErrUpstreamNotOrigin is returned when a Balancer server carries more
	// than a scheme and a host: a path, userinfo, query or fragment. The
	// balancer dials the host only, so the rest would be dropped silently,
	// and "http://backend/api" would reach all of the upstream, not "/api".
	ErrUpstreamNotOrigin = errors.New("proxy: upstream must be a scheme and host only")

	// ErrRedirectDowngrade is returned when DoRedirects encounters a
	// redirect from an HTTPS upstream to a plaintext HTTP target and
	// AllowHTTPSDowngrade is false.
	ErrRedirectDowngrade = errors.New("proxy: HTTPS to HTTP redirect blocked")
)

Sentinel errors returned when an upstream target violates the configured proxy security policy.

View Source
var ConfigDefault = Config{
	Next:                 nil,
	ModifyRequest:        nil,
	ModifyResponse:       nil,
	MaxConnsPerHost:      defaultMaxConnsPerHost,
	MaxResponseBodySize:  defaultMaxResponseBodySize,
	Timeout:              fasthttp.DefaultLBClientTimeout,
	KeepConnectionHeader: false,
}

ConfigDefault is the default config

Functions

func Balancer

func Balancer(config ...Config) fiber.Handler

Balancer creates a load balancer among multiple upstream servers. Servers (or a Client with Clients) is required: without one Balancer panics at startup.

func BalancerForward

func BalancerForward(servers []string, clients ...*fasthttp.Client) fiber.Handler

BalancerForward Forward performs the given http request with round robin algorithm to server and fills the given http response. This method will return a fiber.Handler.

As with DomainForward, every server is parsed and policy-checked at handler construction. A misconfigured entry panics at startup.

SSRF note: despite the name, this helper dispatches through the shared/user-supplied client rather than a Balancer HostClient, but it gets the same protection as Do — up-front host validation plus the dial-time validated-IP guard on the dispatching client when AllowPrivateIPs is false.

func Do

func Do(c fiber.Ctx, addr string, clients ...*fasthttp.Client) error

Do performs the given http request and fills the given http response. This method can be used within a fiber.Handler

SSRF note: the upstream host is validated against the active SecurityPolicy before the request is sent, and when AllowPrivateIPs is false the resolved IP is re-validated at dial time by the guard installed on the dispatching *fasthttp.Client. The connection therefore targets exactly the address that passed the blocklist, so a rebinding-capable resolver cannot slip a private IP past the check.

The guard is installed via the client's ConfigureClient hook, which only affects HostClients created after installation. The default client and WithClient clients are guarded before first use; a client supplied as a per-call variadic override is guarded on first use, so a host it had already dialed keeps a cached, pre-guard HostClient. For a full guarantee with a custom client, register it via WithClient (or pass a dedicated, unused client) before first use.

The request reaches the upstream as HTTP/1.1. As with Forward, the default client bounds the exchange at 30 seconds and the response at 100 MiB, buffered or streamed; DoTimeout and DoDeadline set the bound of their own request.

func DoDeadline

func DoDeadline(c fiber.Ctx, addr string, deadline time.Time, clients ...*fasthttp.Client) error

DoDeadline performs the given request and waits for response until the given deadline. This method can be used within a fiber.Handler

SSRF note: same protection as Do — up-front host validation plus the dial-time validated-IP guard when AllowPrivateIPs is false.

func DoRedirects

func DoRedirects(c fiber.Ctx, addr string, maxRedirectsCount int, clients ...*fasthttp.Client) error

DoRedirects performs the given http request and fills the given http response, following up to maxRedirectsCount redirects. When the redirect count exceeds maxRedirectsCount, ErrTooManyRedirects is returned. An error while following the chain resets the response, so no upstream answer goes out with it. This method can be used within a fiber.Handler

Each redirect target is re-validated against the active SecurityPolicy. Unless AllowHTTPSDowngrade is enabled, redirects from an HTTPS origin to a plaintext HTTP target are rejected with ErrRedirectDowngrade.

When a redirect changes the origin (scheme, host or port), Authorization, Proxy-Authorization, Proxy-Authenticate, WWW-Authenticate, Cookie and Cookie2 are dropped from that hop on. Other headers, such as an X-Api-Key, are forwarded unless named in SecurityPolicy.RedirectSensitiveHeaders.

SSRF note: every hop's host is validated against the policy, and when AllowPrivateIPs is false each dial is re-validated by the guard on the dispatching client — so per-hop redirects (including cross-host ones) cannot be rebound to a private IP between validation and connection.

func DoTimeout

func DoTimeout(c fiber.Ctx, addr string, timeout time.Duration, clients ...*fasthttp.Client) error

DoTimeout performs the given request and waits for response during the given timeout duration. This method can be used within a fiber.Handler

SSRF note: same protection as Do — up-front host validation plus the dial-time validated-IP guard when AllowPrivateIPs is false.

func DomainForward

func DomainForward(hostname, addr string, clients ...*fasthttp.Client) fiber.Handler

DomainForward performs an http request based on the given domain and populates the given http response. This method will return a fiber.Handler.

The upstream addr is validated at handler construction: scheme allowlist, SSRF block, and URL parsing all run once. Unlike Balancer (which defers DNS to dial time to survive transient resolver failures at startup), this construction check resolves the host, so a misconfigured or unresolvable addr panics at startup instead of failing per request. Each request also re-validates the host against the current policy before dispatch.

SSRF note: the per-request validation is an up-front host check, and when AllowPrivateIPs is false the dispatching client's dial-time guard re-validates the resolved IP at connect time — so a rebinding-capable resolver cannot reach a private address through this handler.

func Forward

func Forward(addr string, clients ...*fasthttp.Client) fiber.Handler

Forward performs the given http request and fills the given http response. This method will return a fiber.Handler

SSRF note: Forward validates the upstream host against the active SecurityPolicy up front and, when AllowPrivateIPs is false, re-validates the resolved IP at dial time via the guard installed on the dispatching client, so a rebinding-capable resolver cannot swap a public answer for a private one between validation and connection. The policy is read on every request, so keep it installed while the handler serves.

The default client gives each request 30 seconds for the whole exchange and takes at most 100 MiB of a response; WithClient replaces both bounds. A client of your own that streams response bodies is held to its MaxResponseBodySize as well, which fasthttp does not do for a stream.

func WithClient

func WithClient(cli *fasthttp.Client)

WithClient sets the global proxy client. This function should be called before Do and Forward — doing so installs the dial-time SSRF guard (via the client's ConfigureClient hook, composing with any hook it already carries) before the client dials any host, so requests dispatched through it re-validate the resolved IP at connect time, matching the default client's behavior.

Types

type Config

type Config struct {
	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c fiber.Ctx) bool

	// ModifyRequest allows you to alter the request
	//
	// Optional. Default: nil
	ModifyRequest fiber.Handler

	// ModifyResponse allows you to alter the response. It runs on the upstream's
	// response with its trailer section already dropped and, unless the policy
	// keeps them, its hop-by-hop fields stripped.
	//
	// Optional. Default: nil
	ModifyResponse fiber.Handler

	// tls config for the http client.
	TLSConfig *tls.Config

	// Client is custom client when client config is complex. Each *fasthttp.HostClient
	// among its Clients gets DisablePathNormalizing set when the balancer is built; set it
	// first on a client already in use, which is then left alone.
	// Note that Servers, Timeout, MaxConnsPerHost, ReadBufferSize, WriteBufferSize,
	// MaxResponseBodySize, TLSConfig and DialDualStack will not be used if the client is
	// set, and its dialers are yours to guard. The exception is a MaxResponseBodySize you
	// set, which holds a body the client streams to that size: fasthttp does not bound one.
	Client *fasthttp.LBClient

	// SecurityPolicy overrides the default SSRF, redirect, and
	// hop-by-hop header rules for this balancer. When nil, the
	// package-level policy set via WithSecurityPolicy is used. It is read once,
	// when the balancer is built.
	//
	// Optional. Default: nil
	SecurityPolicy *SecurityPolicy

	// Servers defines a list of <scheme>://<host> HTTP servers,
	// which are used in a round-robin manner.
	// i.e.: "https://foobar.com, http://www.foobar.com"
	//
	// An entry with a path, userinfo, query or fragment panics with ErrUpstreamNotOrigin;
	// "host:port" is read as http://host:port.
	//
	// Required unless Client is set
	Servers []string

	// Timeout is the request timeout used when calling the proxy client
	//
	// Optional. Default: 1 second
	Timeout time.Duration

	// Maximum number of connections per upstream host.
	//
	// Optional. Default: 1024
	MaxConnsPerHost int

	// Per-connection buffer size for reading upstream responses. This also limits the
	// response header size: raise it for upstreams that send multi-KB headers.
	ReadBufferSize int

	// Per-connection buffer size for writing requests to the upstream.
	WriteBufferSize int

	// MaxResponseBodySize bounds the size (in bytes) of upstream
	// responses accepted by the proxy. Responses larger than this are
	// rejected to protect the proxy from memory exhaustion. Zero takes
	// the default; a negative value removes the bound, as fasthttp's
	// unlimited default does.
	//
	// It bounds a body the proxy streams as well, which fasthttp does not: one
	// that declares more is refused before any of it is sent, and one that goes
	// past the bound without declaring its length ends the response early.
	//
	// Optional. Default: 100 MiB
	MaxResponseBodySize int

	// KeepConnectionHeader keeps the "Connection" header when set to true.
	//
	// Note: even when KeepConnectionHeader is true, other RFC 9110 §7.6.1
	// hop-by-hop headers (Keep-Alive, Proxy-Authenticate,
	// Proxy-Authorization, TE, Trailer, Transfer-Encoding, Upgrade) are
	// still stripped. To preserve every hop-by-hop header, set
	// SecurityPolicy.KeepHopByHopHeaders.
	//
	// Optional. Default: false
	KeepConnectionHeader bool

	// Attempt to connect to both ipv4 and ipv6 host addresses if set to true.
	//
	// By default client connects only to ipv4 addresses, since unfortunately ipv6
	// remains broken in many networks worldwide :)
	//
	// Optional. Default: false
	DialDualStack bool
}

Config defines the config for middleware.

type SecurityPolicy added in v3.5.0

type SecurityPolicy struct {
	// AllowedSchemes restricts the URL schemes accepted as upstream
	// targets. Empty defaults to []string{schemeHTTP, schemeHTTPS}.
	AllowedSchemes []string

	// RedirectSensitiveHeaders lists request headers, beyond the built-in set, that DoRedirects drops when
	// a redirect changes the origin (scheme, host or port), such as an X-Api-Key of your own. Names match
	// case-insensitively. Default: nil.
	RedirectSensitiveHeaders []string

	// AllowPrivateIPs allows upstream hosts to resolve to loopback, private (RFC 1918), link-local,
	// multicast, unspecified, CGNAT (RFC 6598) or other special-use addresses: 0.0.0.0/8, 192.0.0.0/24
	// (which holds Oracle Cloud's metadata address 192.0.0.192), 198.18.0.0/15, 240.0.0.0/4 (the
	// limited broadcast address included) and the deprecated IPv6 site-local range fec0::/10.
	// SECURITY: enabling this exposes the proxy to SSRF attacks against internal services such as
	// cloud metadata endpoints. Default: false.
	//
	// DNS-rebinding scope: when false, the resolved IP is re-validated at dial time, so a resolver
	// cannot answer public during validation and private at connect. Balancer guards the
	// HostClients it builds and the runtime helpers the *fasthttp.Client they dispatch through; the
	// default client and one registered with WithClient are guarded before first use. A client
	// passed per call is guarded on first use, so a host it had already dialed keeps its pre-guard
	// HostClient: register it with WithClient before its first request instead. A custom Balancer
	// Config.Client (*fasthttp.LBClient) and a *fasthttp.Client with a Transport dial through the
	// caller's own dialers, which the caller guards.
	AllowPrivateIPs bool

	// AllowHTTPSDowngrade permits proxy.DoRedirects to follow redirects
	// from HTTPS upstreams to plaintext HTTP URLs. SECURITY: enabling
	// this can leak credentials or session cookies in plaintext.
	// Default: false.
	AllowHTTPSDowngrade bool

	// KeepHopByHopHeaders disables the RFC 9110 §7.6.1 hop-by-hop header
	// stripping applied to both the outbound request and the inbound
	// response. SECURITY: enabling this can enable request smuggling
	// and proxy-auth credential forwarding. Default: false.
	KeepHopByHopHeaders bool

	// AllowAmbiguousSlashes lets Balancer, DomainForward and BalancerForward
	// forward a routed path holding an escaped slash ("%2F") or an empty
	// segment ("//"), which they otherwise answer with 400 Bad Request. An
	// upstream that keeps both as sent needs it for names such as a
	// GitLab-style "group%2Fproject" id or an object key with a doubled
	// slash. SECURITY: an upstream that decodes "%2F" into a separator or
	// merges "//" before it matches routes reads such a path as another
	// one, under a prefix whose middleware the router never ran for it;
	// enable this only when every upstream keeps them, through a client
	// that does not normalize paths. A path parameter needs
	// AllowPathParameters as well, and a forged escape, a backslash and a
	// dot segment carrying parameters are refused regardless.
	// Default: false.
	AllowAmbiguousSlashes bool

	// AllowPathParameters lets Balancer, DomainForward and BalancerForward
	// forward a routed path with a path parameter, a ";" and what follows it
	// as in "/cart;jsessionid=x", which they otherwise answer with 400 Bad
	// Request. An upstream that relies on ";jsessionid" needs it. Servlet
	// containers such as Tomcat and Jetty strip the parameters from every
	// segment before they match routes, so they read "/admin;x/secret" as
	// "/admin/secret", under a prefix whose middleware the router never ran
	// for it; enable this only when every upstream behind the handler keeps
	// the ";" as part of the name or checks access itself. A dot segment
	// carrying parameters, behind a raw slash or an escaped one, a backslash
	// and a forged escape are refused regardless, and so is a segment made of
	// parameters alone, such as "/;x/admin", unless AllowAmbiguousSlashes is
	// set as well. No effect under UnescapePath, which forwards a ";" as "%3B".
	// Default: false.
	AllowPathParameters bool
}

SecurityPolicy controls the runtime security restrictions of proxy.Do, proxy.Forward, proxy.DoRedirects, proxy.DoTimeout, proxy.DoDeadline, proxy.DomainForward and proxy.BalancerForward, and of Balancer instances without their own Config.SecurityPolicy.

Balancer reads its policy once, when it is built; the runtime helpers read the installed policy on every request and dial, so keep it installed while they serve.

func DefaultSecurityPolicy added in v3.5.0

func DefaultSecurityPolicy() SecurityPolicy

DefaultSecurityPolicy returns the secure-by-default proxy security policy. Callers can clone it, mutate selected fields, and pass it back via Config.SecurityPolicy or WithSecurityPolicy.

AllowedSchemes is a freshly allocated slice on every call: the field is exported, so returning the shared defaultAllowedSchemes backing array would let a caller doing e.g. policy.AllowedSchemes[0] = "file" silently weaken the package defaults and every policy that references them.

func WithSecurityPolicy added in v3.5.0

func WithSecurityPolicy(policy SecurityPolicy) SecurityPolicy

WithSecurityPolicy installs policy as the global default (see SecurityPolicy) and returns the previous one so callers can restore it, e.g. to relax the policy for one test.

Jump to

Keyboard shortcuts

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