mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
refactor(gotenberg): share the Chromium pinning proxy as the outbound proxy
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
package chromium
|
||||
package gotenberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -17,27 +17,27 @@ import (
|
||||
|
||||
"github.com/dlclark/regexp2/v2"
|
||||
"golang.org/x/net/http/httpproxy"
|
||||
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
|
||||
)
|
||||
|
||||
// pinningProxy is a loopback-bound HTTP/1.1 forward and CONNECT proxy
|
||||
// placed between Chromium and the outbound network. It runs the same
|
||||
// allow/deny/IP-public validation as [gotenberg.FilterOutboundURL] on
|
||||
// every request and dials the destination using the IPs resolved at that
|
||||
// moment. Routing Chromium through this proxy eliminates the Chromium-side
|
||||
// DNS lookup that otherwise opens a DNS rebinding window between
|
||||
// Gotenberg's validation and Chromium's TCP connect.
|
||||
// OutboundProxy is a loopback-bound HTTP/1.1 forward and CONNECT proxy placed
|
||||
// between a converter, such as Chromium or LibreOffice, and the outbound
|
||||
// network. It runs [DecideOutbound] on every request and dials the destination
|
||||
// using the IPs resolved at that moment. Routing a converter through this
|
||||
// proxy eliminates the converter-side DNS lookup that otherwise opens a DNS
|
||||
// rebinding window between Gotenberg's validation and the converter's TCP
|
||||
// connect.
|
||||
//
|
||||
// The proxy is transparent to the caller. HTTPS sub-resources tunnel
|
||||
// through CONNECT with Chromium performing its own TLS handshake using
|
||||
// the original hostname, preserving SNI and certificate validation.
|
||||
type pinningProxy struct {
|
||||
// The proxy is transparent to the caller. HTTPS requests tunnel through
|
||||
// CONNECT with the converter performing its own TLS handshake using the
|
||||
// original hostname, preserving SNI and certificate validation. A tunnel only
|
||||
// exposes its host and port, so the filters see the root URL of the tunnel,
|
||||
// never its path. See [OutboundProxy.DecideTunnel].
|
||||
type OutboundProxy struct {
|
||||
allowList []*regexp2.Regexp
|
||||
denyList []*regexp2.Regexp
|
||||
|
||||
// decide resolves and validates a URL. Tests may override it.
|
||||
decide func(ctx context.Context, rawURL string, allowList, denyList []*regexp2.Regexp, deadline time.Time) (gotenberg.OutboundDecision, error)
|
||||
decide func(ctx context.Context, rawURL string, allowList, denyList []*regexp2.Regexp, deadline time.Time) (OutboundDecision, error)
|
||||
|
||||
// dialPinned dials the pinned IPs for a decision. Tests may override
|
||||
// it to connect to a stub upstream regardless of decision.
|
||||
@@ -50,11 +50,14 @@ type pinningProxy struct {
|
||||
// upstreamProxy resolves the upstream (corporate) proxy for a
|
||||
// destination URL from the standard proxy environment variables, or
|
||||
// returns a nil URL to connect directly. It is nil unless the operator
|
||||
// opted into proxy-environment honoring. When set, the pinning proxy
|
||||
// performs the authenticated proxy handshake that Chromium cannot. See
|
||||
// opted into proxy-environment honoring. When set, the proxy performs
|
||||
// the authenticated proxy handshake that the converter cannot. See
|
||||
// https://github.com/gotenberg/gotenberg/issues/1592.
|
||||
upstreamProxy func(*url.URL) (*url.URL, error)
|
||||
|
||||
// logRefusal records a request the filters refused.
|
||||
logRefusal func(ctx context.Context, rawURL string, err error)
|
||||
|
||||
listener net.Listener
|
||||
server *http.Server
|
||||
wg sync.WaitGroup
|
||||
@@ -78,32 +81,58 @@ type pinningProxy struct {
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// newPinningProxy returns a pinning proxy configured with the given
|
||||
// allow/deny lists, IP-class policy, and host mapping, which may be nil. They
|
||||
// are applied via [gotenberg.DecideOutbound] on every request the proxy sees,
|
||||
// so Chromium inherits whatever posture the operator selected, and connects
|
||||
// where the mapping sends it. The returned proxy is not yet listening; call
|
||||
// Start.
|
||||
func newPinningProxy(allowList, denyList []*regexp2.Regexp, denyPrivateIPs, denyPublicIPs, enableEnvironmentProxy bool, hostMapping gotenberg.HostMapping) *pinningProxy {
|
||||
p := &pinningProxy{
|
||||
allowList: allowList,
|
||||
denyList: denyList,
|
||||
decide: func(ctx context.Context, rawURL string, allow, deny []*regexp2.Regexp, deadline time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.DecideOutbound(ctx, rawURL, allow, deny, deadline,
|
||||
gotenberg.WithDenyPrivateIPs(denyPrivateIPs),
|
||||
gotenberg.WithDenyPublicIPs(denyPublicIPs),
|
||||
gotenberg.WithHostMapping(hostMapping),
|
||||
// OutboundProxyOptions configures an [OutboundProxy].
|
||||
type OutboundProxyOptions struct {
|
||||
// AllowList and DenyList are the operator's outbound lists, matched as
|
||||
// [DecideOutbound] matches them.
|
||||
AllowList []*regexp2.Regexp
|
||||
DenyList []*regexp2.Regexp
|
||||
|
||||
// DenyPrivateIPs and DenyPublicIPs refuse destinations of that IP class.
|
||||
// See [WithDenyPrivateIPs] and [WithDenyPublicIPs].
|
||||
DenyPrivateIPs bool
|
||||
DenyPublicIPs bool
|
||||
|
||||
// EnableEnvironmentProxy sends the requests the filters allow through the
|
||||
// proxy the standard proxy environment variables name, credentials
|
||||
// included.
|
||||
EnableEnvironmentProxy bool
|
||||
|
||||
// HostMapping sends a host where the operator's rules map it. It may be
|
||||
// nil. See [WithHostMapping].
|
||||
HostMapping HostMapping
|
||||
|
||||
// LogRefusal records a request the filters refused, with the URL the
|
||||
// filters saw. When nil, the proxy logs it through [LogOutboundRefusal]
|
||||
// with its own logger.
|
||||
LogRefusal func(ctx context.Context, rawURL string, err error)
|
||||
}
|
||||
|
||||
// NewOutboundProxy returns a proxy that applies opts to every request it
|
||||
// sees, so the converter behind it inherits whatever posture the operator
|
||||
// selected, and connects where the host mapping sends it. The returned proxy
|
||||
// is not yet listening; call [OutboundProxy.Start].
|
||||
func NewOutboundProxy(opts OutboundProxyOptions) *OutboundProxy {
|
||||
p := &OutboundProxy{
|
||||
allowList: opts.AllowList,
|
||||
denyList: opts.DenyList,
|
||||
decide: func(ctx context.Context, rawURL string, allow, deny []*regexp2.Regexp, deadline time.Time) (OutboundDecision, error) {
|
||||
return DecideOutbound(ctx, rawURL, allow, deny, deadline,
|
||||
WithDenyPrivateIPs(opts.DenyPrivateIPs),
|
||||
WithDenyPublicIPs(opts.DenyPublicIPs),
|
||||
WithHostMapping(opts.HostMapping),
|
||||
)
|
||||
},
|
||||
dialPinned: gotenberg.DialPinned,
|
||||
dialPinned: DialPinned,
|
||||
dialBypass: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
||||
return dialer.DialContext(ctx, network, addr)
|
||||
},
|
||||
logRefusal: opts.LogRefusal,
|
||||
maxTunnels: maxConcurrentTunnels,
|
||||
}
|
||||
|
||||
if enableEnvironmentProxy {
|
||||
if opts.EnableEnvironmentProxy {
|
||||
// Honor the standard proxy environment variables, credentials
|
||||
// included. httpproxy reads the environment now and applies NO_PROXY.
|
||||
p.upstreamProxy = httpproxy.FromEnvironment().ProxyFunc()
|
||||
@@ -113,26 +142,26 @@ func newPinningProxy(allowList, denyList []*regexp2.Regexp, denyPrivateIPs, deny
|
||||
}
|
||||
|
||||
// Start binds the proxy to 127.0.0.1 on an ephemeral port and serves in a
|
||||
// background goroutine. Bind failures return an error; the caller must
|
||||
// not proceed to start Chromium with --proxy-server.
|
||||
func (p *pinningProxy) Start(logger *slog.Logger) error {
|
||||
// background goroutine, logging with logger. Bind failures return an error;
|
||||
// the caller must not point the converter at the proxy then.
|
||||
func (p *OutboundProxy) Start(logger *slog.Logger) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
|
||||
if p.started {
|
||||
return errors.New("pinning proxy already started")
|
||||
return errors.New("outbound proxy already started")
|
||||
}
|
||||
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return fmt.Errorf("bind pinning proxy: %w", err)
|
||||
return fmt.Errorf("bind outbound proxy: %w", err)
|
||||
}
|
||||
|
||||
baseCtx, cancelRequests := context.WithCancel(context.Background())
|
||||
|
||||
p.listener = l
|
||||
p.cancelRequests = cancelRequests
|
||||
p.logger = logger.With(slog.String("logger", "pinning-proxy"))
|
||||
p.logger = logger
|
||||
p.server = &http.Server{
|
||||
Handler: http.HandlerFunc(p.serveHTTP),
|
||||
BaseContext: func(net.Listener) context.Context { return baseCtx },
|
||||
@@ -145,18 +174,18 @@ func (p *pinningProxy) Start(logger *slog.Logger) error {
|
||||
p.wg.Go(func() {
|
||||
serveErr := p.server.Serve(l)
|
||||
if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
|
||||
p.logger.ErrorContext(context.Background(), fmt.Sprintf("pinning proxy serve: %s", serveErr))
|
||||
p.logger.ErrorContext(context.Background(), fmt.Sprintf("outbound proxy serve: %s", serveErr))
|
||||
}
|
||||
})
|
||||
|
||||
p.started = true
|
||||
p.logger.DebugContext(context.Background(), fmt.Sprintf("pinning proxy listening on %s", l.Addr()))
|
||||
p.logger.DebugContext(context.Background(), fmt.Sprintf("outbound proxy listening on %s", l.Addr()))
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop shuts the proxy down and waits for in-flight handlers to complete.
|
||||
// Safe to call on a non-started proxy.
|
||||
func (p *pinningProxy) Stop(logger *slog.Logger) error {
|
||||
// Stop shuts the proxy down and waits for in-flight handlers to complete,
|
||||
// until ctx ends. Safe to call on a non-started proxy.
|
||||
func (p *OutboundProxy) Stop(ctx context.Context) error {
|
||||
p.mu.Lock()
|
||||
if !p.started {
|
||||
p.mu.Unlock()
|
||||
@@ -170,34 +199,31 @@ func (p *pinningProxy) Stop(logger *slog.Logger) error {
|
||||
|
||||
// Force in-flight tunnels shut before draining the server. Shutdown does
|
||||
// not reach them, so a tunnel whose upstream never answers would otherwise
|
||||
// survive the proxy, and with it every Chromium restart.
|
||||
// survive the proxy, and with it every converter restart.
|
||||
cancelRequests()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
shutdownErr := srv.Shutdown(ctx)
|
||||
p.wg.Wait()
|
||||
|
||||
if shutdownErr != nil {
|
||||
return fmt.Errorf("shutdown pinning proxy: %w", shutdownErr)
|
||||
return fmt.Errorf("shutdown outbound proxy: %w", shutdownErr)
|
||||
}
|
||||
logger.DebugContext(context.Background(), "pinning proxy stopped")
|
||||
p.logger.DebugContext(ctx, "outbound proxy stopped")
|
||||
return nil
|
||||
}
|
||||
|
||||
// URL returns the proxy URL suitable for Chromium's --proxy-server flag.
|
||||
// Returns an empty string when the proxy is not listening.
|
||||
func (p *pinningProxy) URL() string {
|
||||
// Addr returns the host:port the proxy listens on, or an empty string when
|
||||
// the proxy has never listened.
|
||||
func (p *OutboundProxy) Addr() string {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.listener == nil {
|
||||
return ""
|
||||
}
|
||||
return "http://" + p.listener.Addr().String()
|
||||
return p.listener.Addr().String()
|
||||
}
|
||||
|
||||
func (p *pinningProxy) serveHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
func (p *OutboundProxy) serveHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
if req.Method == http.MethodConnect {
|
||||
p.handleConnect(w, req)
|
||||
return
|
||||
@@ -205,23 +231,23 @@ func (p *pinningProxy) serveHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
p.handleForward(w, req)
|
||||
}
|
||||
|
||||
// handleConnect handles HTTPS (and any other CONNECT) tunnels. Chromium
|
||||
// issues CONNECT host:port; the proxy validates the host, dials the
|
||||
// pinned IP, and splices the client socket with the upstream socket.
|
||||
// Chromium then negotiates TLS end-to-end with the original hostname in
|
||||
// SNI.
|
||||
func (p *pinningProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
// handleConnect handles HTTPS (and any other CONNECT) tunnels. The converter
|
||||
// issues CONNECT host:port; the proxy validates the host, dials the pinned
|
||||
// IP, and splices the client socket with the upstream socket. The converter
|
||||
// then negotiates TLS end-to-end with the original hostname in SNI.
|
||||
func (p *OutboundProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
// A ceiling, not a tuning knob: it bounds what a tunnel that refuses to end
|
||||
// can accumulate, whatever keeps it alive. [spliceIdleTimeout] ends a silent
|
||||
// tunnel, but a peer trickling a byte just under it stays "active" forever,
|
||||
// and a compromised renderer can hold the client side open to match.
|
||||
//
|
||||
// Chromium caps itself well below this. Its socket pool manager allows 128
|
||||
// sockets per proxy chain for normal traffic plus 128 for WebSocket
|
||||
// traffic, and every request Gotenberg's Chromium makes traverses this one
|
||||
// proxy chain, so an honest browser cannot exceed 256 tunnels here. At
|
||||
// double that, a real page never meets the ceiling and a hostile one stops
|
||||
// at it.
|
||||
// Chromium, the most demanding converter, caps itself well below this. Its
|
||||
// socket pool manager allows 128 sockets per proxy chain for normal traffic
|
||||
// plus 128 for WebSocket traffic, and every request Gotenberg's Chromium
|
||||
// makes traverses this one proxy chain, so an honest browser cannot exceed
|
||||
// 256 tunnels here. At double that, a real page never meets the ceiling and
|
||||
// a hostile one stops at it. LibreOffice converts one document at a time
|
||||
// and fetches far less.
|
||||
if !p.acquireTunnel() {
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("CONNECT to '%s' refused: %d tunnels already in flight", req.Host, p.maxTunnels))
|
||||
http.Error(w, "too many tunnels", http.StatusServiceUnavailable)
|
||||
@@ -241,11 +267,14 @@ func (p *pinningProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
deadline = time.Now().Add(30 * time.Second)
|
||||
}
|
||||
|
||||
decision, err := p.decideTunnel(req.Context(), req.Host, deadline)
|
||||
decision, err := p.DecideTunnel(req.Context(), req.Host, deadline)
|
||||
if err != nil {
|
||||
if isClientCancellation(req.Context(), err) {
|
||||
switch {
|
||||
case isClientCancellation(req.Context(), err):
|
||||
p.logger.DebugContext(req.Context(), fmt.Sprintf("CONNECT abandoned by client for '%s': %s", req.Host, err))
|
||||
} else {
|
||||
case p.logRefusal != nil && FilterRule(err) != "":
|
||||
p.logRefusal(req.Context(), "https://"+req.Host, err)
|
||||
default:
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("CONNECT blocked for '%s': %s", req.Host, err))
|
||||
}
|
||||
http.Error(w, "CONNECT blocked", http.StatusForbidden)
|
||||
@@ -253,7 +282,7 @@ func (p *pinningProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
}
|
||||
|
||||
// When the operator routes egress through an authenticated proxy,
|
||||
// Chromium cannot supply the credentials itself, so the pinning proxy
|
||||
// the converter cannot supply the credentials itself, so this proxy
|
||||
// performs the CONNECT (and authentication) upstream. The decision above
|
||||
// still gated the destination through the allow/deny and IP-class rules.
|
||||
var proxyURL *url.URL
|
||||
@@ -267,7 +296,7 @@ func (p *pinningProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
}
|
||||
|
||||
// A host-resolver rule may send the tunnel to another host and port. An
|
||||
// upstream proxy still receives the original host, as Chromium itself
|
||||
// upstream proxy still receives the original host, as a browser itself
|
||||
// leaves name resolution to the proxy it talks to.
|
||||
target := req.Host
|
||||
if decision.Target != "" {
|
||||
@@ -326,7 +355,7 @@ func (p *pinningProxy) handleConnect(w http.ResponseWriter, req *http.Request) {
|
||||
spliceTunnel(client, upstream, req.Context().Done(), spliceIdleTimeout)
|
||||
}
|
||||
|
||||
// tunnelSchemes lists the schemes Chromium sends through a CONNECT tunnel and
|
||||
// tunnelSchemes lists the schemes a converter sends through a CONNECT tunnel and
|
||||
// their default ports: HTTPS sub-resources and WebSocket handshakes, secure or
|
||||
// not. Plain http:// requests use the forward path instead.
|
||||
var tunnelSchemes = []struct {
|
||||
@@ -338,7 +367,7 @@ var tunnelSchemes = []struct {
|
||||
{"ws", "80"},
|
||||
}
|
||||
|
||||
// decideTunnel validates the destination of a CONNECT tunnel to hostport.
|
||||
// DecideTunnel validates the destination of a CONNECT tunnel to hostport.
|
||||
//
|
||||
// A tunnel is opaque: the proxy sees the host and port, never the scheme or
|
||||
// the path of what travels through it. The deny-list is therefore matched
|
||||
@@ -346,16 +375,15 @@ var tunnelSchemes = []struct {
|
||||
// "https://host/" and "wss://host/", so that a rule anchored on a scheme or on
|
||||
// "host/" refuses the tunnel exactly as it refuses the ordinary request. Such a
|
||||
// rule refuses every tunnel to that host and port, whatever travels through
|
||||
// it. Rules that name a path cannot match here; for WebSocket handshakes,
|
||||
// [listenForEventWebSocketCreated] covers them.
|
||||
// it. Rules that name a path cannot match here: only a layer that sees the
|
||||
// full URL, such as Chromium's request interception, can apply them.
|
||||
//
|
||||
// The allow-list and the IP-class checks then run through decide on the
|
||||
// https:// form, as before. The scheme does not influence the CONNECT handling
|
||||
// beyond filtering.
|
||||
func (p *pinningProxy) decideTunnel(ctx context.Context, hostport string, deadline time.Time) (gotenberg.OutboundDecision, error) {
|
||||
// The allow-list and the IP-class checks then run on the https:// form. The
|
||||
// scheme does not influence the CONNECT handling beyond filtering.
|
||||
func (p *OutboundProxy) DecideTunnel(ctx context.Context, hostport string, deadline time.Time) (OutboundDecision, error) {
|
||||
host, port, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("split CONNECT target %q: %v: %w", hostport, err, gotenberg.ErrFiltered)
|
||||
return OutboundDecision{}, fmt.Errorf("split CONNECT target %q: %v: %w", hostport, err, ErrFiltered)
|
||||
}
|
||||
|
||||
for _, ts := range tunnelSchemes {
|
||||
@@ -367,24 +395,24 @@ func (p *pinningProxy) decideTunnel(ctx context.Context, hostport string, deadli
|
||||
}
|
||||
}
|
||||
|
||||
err = gotenberg.FilterDenyList(ts.scheme+"://"+authority+"/", p.denyList, deadline)
|
||||
err = FilterDenyList(ts.scheme+"://"+authority+"/", p.denyList, deadline)
|
||||
if err != nil {
|
||||
return gotenberg.OutboundDecision{}, err
|
||||
return OutboundDecision{}, err
|
||||
}
|
||||
}
|
||||
|
||||
return p.decide(ctx, "https://"+hostport, p.allowList, p.denyList, deadline)
|
||||
}
|
||||
|
||||
// maxConcurrentTunnels is the default for [pinningProxy.maxTunnels]. See
|
||||
// [pinningProxy.handleConnect] for how the value is derived.
|
||||
// maxConcurrentTunnels is the default for [OutboundProxy.maxTunnels]. See
|
||||
// [OutboundProxy.handleConnect] for how the value is derived.
|
||||
const maxConcurrentTunnels = 512
|
||||
|
||||
// acquireTunnel reserves a slot for one CONNECT handler, reporting false when
|
||||
// the proxy is already at [pinningProxy.maxTunnels]. The compare-and-swap loop
|
||||
// the proxy is already at [OutboundProxy.maxTunnels]. The compare-and-swap loop
|
||||
// keeps the check and the increment atomic, so concurrent handlers cannot
|
||||
// overshoot the ceiling between them.
|
||||
func (p *pinningProxy) acquireTunnel() bool {
|
||||
func (p *OutboundProxy) acquireTunnel() bool {
|
||||
for {
|
||||
current := p.tunnels.Load()
|
||||
if current >= p.maxTunnels {
|
||||
@@ -396,8 +424,8 @@ func (p *pinningProxy) acquireTunnel() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// releaseTunnel returns a slot taken by [pinningProxy.acquireTunnel].
|
||||
func (p *pinningProxy) releaseTunnel() {
|
||||
// releaseTunnel returns a slot taken by [OutboundProxy.acquireTunnel].
|
||||
func (p *OutboundProxy) releaseTunnel() {
|
||||
p.tunnels.Add(-1)
|
||||
}
|
||||
|
||||
@@ -407,7 +435,7 @@ func (p *pinningProxy) releaseTunnel() {
|
||||
// Nothing else bounds one. The hijacked connections carry no deadline: the
|
||||
// server clears the header read deadline once the request line is in, and
|
||||
// net.Dialer.Timeout only covers the connect. net/http also untracks a
|
||||
// connection once it is hijacked, so neither Server.Shutdown nor a Chromium
|
||||
// connection once it is hijacked, so neither Server.Shutdown nor a converter
|
||||
// restart reaps it. Left alone, an upstream that accepts the tunnel and then
|
||||
// answers nothing holds two goroutines and two sockets until the process dies.
|
||||
//
|
||||
@@ -510,7 +538,7 @@ func copyTracking(dst, src net.Conn, lastActivity *atomic.Int64, writeTimeout ti
|
||||
// handleForward handles plain HTTP requests sent to the proxy as absolute
|
||||
// URIs (GET http://host/path). The proxy revalidates the URL, then
|
||||
// forwards the request via a transport that dials the pinned IP.
|
||||
func (p *pinningProxy) handleForward(w http.ResponseWriter, req *http.Request) {
|
||||
func (p *OutboundProxy) handleForward(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL == nil || req.URL.Scheme == "" || req.URL.Host == "" {
|
||||
http.Error(w, "absolute URL required", http.StatusBadRequest)
|
||||
return
|
||||
@@ -523,10 +551,13 @@ func (p *pinningProxy) handleForward(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
decision, err := p.decide(req.Context(), req.URL.String(), p.allowList, p.denyList, deadline)
|
||||
if err != nil {
|
||||
if isClientCancellation(req.Context(), err) {
|
||||
p.logger.DebugContext(req.Context(), fmt.Sprintf("forward abandoned by client for '%s': %s", gotenberg.RedactURL(req.URL.String()), err))
|
||||
} else {
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("forward blocked for '%s': %s", gotenberg.RedactURL(req.URL.String()), err))
|
||||
switch {
|
||||
case isClientCancellation(req.Context(), err):
|
||||
p.logger.DebugContext(req.Context(), fmt.Sprintf("forward abandoned by client for '%s': %s", RedactURL(req.URL.String()), err))
|
||||
case p.logRefusal != nil && FilterRule(err) != "":
|
||||
p.logRefusal(req.Context(), req.URL.String(), err)
|
||||
default:
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("forward blocked for '%s': %s", RedactURL(req.URL.String()), err))
|
||||
}
|
||||
http.Error(w, "request blocked", http.StatusForbidden)
|
||||
return
|
||||
@@ -536,7 +567,7 @@ func (p *pinningProxy) handleForward(w http.ResponseWriter, req *http.Request) {
|
||||
if p.upstreamProxy != nil {
|
||||
proxyURL, err = p.upstreamProxy(req.URL)
|
||||
if err != nil {
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("resolve upstream proxy for '%s': %s", gotenberg.RedactURL(req.URL.String()), err))
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("resolve upstream proxy for '%s': %s", RedactURL(req.URL.String()), err))
|
||||
http.Error(w, "upstream proxy error", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
@@ -585,9 +616,9 @@ func (p *pinningProxy) handleForward(w http.ResponseWriter, req *http.Request) {
|
||||
resp, err := transport.RoundTrip(outReq)
|
||||
if err != nil {
|
||||
if isClientCancellation(req.Context(), err) {
|
||||
p.logger.DebugContext(req.Context(), fmt.Sprintf("forward RoundTrip abandoned by client for '%s': %s", gotenberg.RedactURL(req.URL.String()), err))
|
||||
p.logger.DebugContext(req.Context(), fmt.Sprintf("forward RoundTrip abandoned by client for '%s': %s", RedactURL(req.URL.String()), err))
|
||||
} else {
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("forward RoundTrip failed for '%s': %s", gotenberg.RedactURL(req.URL.String()), err))
|
||||
p.logger.WarnContext(req.Context(), fmt.Sprintf("forward RoundTrip failed for '%s': %s", RedactURL(req.URL.String()), err))
|
||||
}
|
||||
resetClient(w)
|
||||
return
|
||||
@@ -634,7 +665,7 @@ func copyHeaders(dst, src http.Header) {
|
||||
// rule decision. Callers downgrade these to debug to avoid alarming
|
||||
// operators with noise from speculative or aborted browser requests. The
|
||||
// canonical case is a Chromium DNS prefetch that the browser drops before
|
||||
// the proxy's [outbound.resolveHost] call returns. The [net.DNSError]
|
||||
// the proxy's [resolveHost] call returns. The [net.DNSError]
|
||||
// returned by [net.Resolver.LookupNetIP] unwraps to [context.Canceled] or
|
||||
// [context.DeadlineExceeded] in that case, so an [errors.Is] walk catches
|
||||
// it.
|
||||
@@ -646,16 +677,16 @@ func isClientCancellation(ctx context.Context, err error) bool {
|
||||
}
|
||||
|
||||
// dialThroughUpstreamProxy tunnels to target through the upstream proxy,
|
||||
// letting [gotenberg.DialThroughProxy] perform the authenticated CONNECT that
|
||||
// Chromium cannot. dialBypass dials the proxy itself and is overridable in
|
||||
// letting [DialThroughProxy] perform the authenticated CONNECT that
|
||||
// the converter cannot. dialBypass dials the proxy itself and is overridable in
|
||||
// tests. See https://github.com/gotenberg/gotenberg/issues/1592.
|
||||
func (p *pinningProxy) dialThroughUpstreamProxy(ctx context.Context, proxyURL *url.URL, target string) (net.Conn, error) {
|
||||
return gotenberg.DialThroughProxy(ctx, proxyURL, target, p.dialBypass)
|
||||
func (p *OutboundProxy) dialThroughUpstreamProxy(ctx context.Context, proxyURL *url.URL, target string) (net.Conn, error) {
|
||||
return DialThroughProxy(ctx, proxyURL, target, p.dialBypass)
|
||||
}
|
||||
|
||||
// resetClient aborts the client connection with a TCP reset instead of
|
||||
// answering. Chromium treats a proxy response as the origin's own, so a 502
|
||||
// would reach the page as an ordinary HTTP error; a reset surfaces as a
|
||||
// answering. A converter treats a proxy response as the origin's own, so a
|
||||
// 502 would reach the document as an ordinary HTTP error; a reset surfaces as a
|
||||
// network failure, as it would without the proxy.
|
||||
func resetClient(w http.ResponseWriter) {
|
||||
hj, ok := w.(http.Hijacker)
|
||||
@@ -1,4 +1,4 @@
|
||||
package chromium
|
||||
package gotenberg
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
@@ -20,30 +20,28 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dlclark/regexp2/v2"
|
||||
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
|
||||
)
|
||||
|
||||
// recordingHandler is a slog.Handler that captures every record emitted
|
||||
// proxyLogRecorder is a slog.Handler that captures every record emitted
|
||||
// through it so tests can assert on the level and message of proxy logs.
|
||||
type recordingHandler struct {
|
||||
type proxyLogRecorder struct {
|
||||
mu sync.Mutex
|
||||
records []slog.Record
|
||||
}
|
||||
|
||||
func (h *recordingHandler) Enabled(_ context.Context, _ slog.Level) bool { return true }
|
||||
func (h *proxyLogRecorder) Enabled(_ context.Context, _ slog.Level) bool { return true }
|
||||
|
||||
func (h *recordingHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
func (h *proxyLogRecorder) Handle(_ context.Context, r slog.Record) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.records = append(h.records, r.Clone())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *recordingHandler) WithAttrs(_ []slog.Attr) slog.Handler { return h }
|
||||
func (h *recordingHandler) WithGroup(_ string) slog.Handler { return h }
|
||||
func (h *proxyLogRecorder) WithAttrs(_ []slog.Attr) slog.Handler { return h }
|
||||
func (h *proxyLogRecorder) WithGroup(_ string) slog.Handler { return h }
|
||||
|
||||
func (h *recordingHandler) snapshot() []slog.Record {
|
||||
func (h *proxyLogRecorder) snapshot() []slog.Record {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
out := make([]slog.Record, len(h.records))
|
||||
@@ -87,22 +85,22 @@ func newRawTCPServer(t *testing.T, handle func(net.Conn)) (string, func()) {
|
||||
return l.Addr().String(), func() { _ = l.Close() }
|
||||
}
|
||||
|
||||
// newProxyForTest returns a pinning proxy whose decide and dial functions
|
||||
// newProxyForTest returns an outbound proxy whose decide and dial functions
|
||||
// are set to test stubs. The proxy is started on a loopback ephemeral
|
||||
// port and stopped during test cleanup.
|
||||
func newProxyForTest(t *testing.T, p *pinningProxy) string {
|
||||
func newProxyForTest(t *testing.T, p *OutboundProxy) string {
|
||||
t.Helper()
|
||||
err := p.Start(testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = p.Stop(testLogger())
|
||||
_ = p.Stop(context.Background())
|
||||
})
|
||||
return p.URL()
|
||||
return "http://" + p.Addr()
|
||||
}
|
||||
|
||||
func TestPinningProxy_Forward_Pinned_Success(t *testing.T) {
|
||||
func TestOutboundProxy_Forward_Pinned_Success(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Host != "example.com" {
|
||||
t.Errorf("upstream expected Host=example.com, got %q", r.Host)
|
||||
@@ -113,10 +111,10 @@ func TestPinningProxy_Forward_Pinned_Success(t *testing.T) {
|
||||
upstreamURL := mustParseURL(t, upstream.URL)
|
||||
|
||||
var decideCalls atomic.Int32
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
decideCalls.Add(1)
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(ctx context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamURL.Host)
|
||||
@@ -151,10 +149,10 @@ func TestPinningProxy_Forward_Pinned_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_Forward_BlockedByDecide(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("nope: %w", gotenberg.ErrFiltered)
|
||||
func TestOutboundProxy_Forward_BlockedByDecide(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{}, fmt.Errorf("nope: %w", ErrFiltered)
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
t.Fatal("dialPinned must not be called when decide returns an error")
|
||||
@@ -180,7 +178,7 @@ func TestPinningProxy_Forward_BlockedByDecide(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_Forward_Bypass(t *testing.T) {
|
||||
func TestOutboundProxy_Forward_Bypass(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprint(w, "bypassed")
|
||||
}))
|
||||
@@ -188,9 +186,9 @@ func TestPinningProxy_Forward_Bypass(t *testing.T) {
|
||||
upstreamURL := mustParseURL(t, upstream.URL)
|
||||
|
||||
var bypassCalls atomic.Int32
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Bypass: true}, nil
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Bypass: true}, nil
|
||||
}
|
||||
p.dialBypass = func(_ context.Context, network, _ string) (net.Conn, error) {
|
||||
bypassCalls.Add(1)
|
||||
@@ -223,7 +221,7 @@ func TestPinningProxy_Forward_Bypass(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_Forward_StripsHopByHopHeaders(t *testing.T) {
|
||||
func TestOutboundProxy_Forward_StripsHopByHopHeaders(t *testing.T) {
|
||||
var upstreamSawProxyAuth bool
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Proxy-Authorization") != "" {
|
||||
@@ -237,9 +235,9 @@ func TestPinningProxy_Forward_StripsHopByHopHeaders(t *testing.T) {
|
||||
t.Cleanup(upstream.Close)
|
||||
upstreamURL := mustParseURL(t, upstream.URL)
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(ctx context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamURL.Host)
|
||||
@@ -276,11 +274,11 @@ func TestPinningProxy_Forward_StripsHopByHopHeaders(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_Forward_RejectsNonAbsoluteURL(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
func TestOutboundProxy_Forward_RejectsNonAbsoluteURL(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
t.Fatal("decide must not be called for malformed proxy request")
|
||||
return gotenberg.OutboundDecision{}, nil
|
||||
return OutboundDecision{}, nil
|
||||
}
|
||||
proxyURL := newProxyForTest(t, p)
|
||||
|
||||
@@ -306,7 +304,7 @@ func TestPinningProxy_Forward_RejectsNonAbsoluteURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_CONNECT_Pinned_Success(t *testing.T) {
|
||||
func TestOutboundProxy_CONNECT_Pinned_Success(t *testing.T) {
|
||||
upstreamAddr, stop := newRawTCPServer(t, func(c net.Conn) {
|
||||
defer c.Close()
|
||||
_, _ = c.Write([]byte("HI"))
|
||||
@@ -317,10 +315,10 @@ func TestPinningProxy_CONNECT_Pinned_Success(t *testing.T) {
|
||||
t.Cleanup(stop)
|
||||
|
||||
var decideCalls atomic.Int32
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
decideCalls.Add(1)
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamAddr)
|
||||
@@ -386,10 +384,10 @@ func TestPinningProxy_CONNECT_Pinned_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_CONNECT_BlockedByDecide(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("nope: %w", gotenberg.ErrFiltered)
|
||||
func TestOutboundProxy_CONNECT_BlockedByDecide(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{}, fmt.Errorf("nope: %w", ErrFiltered)
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
t.Fatal("dialPinned must not be called when decide returns an error")
|
||||
@@ -419,13 +417,13 @@ func TestPinningProxy_CONNECT_BlockedByDecide(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_DNSRebind_SingleResolution is the regression test for
|
||||
// TestOutboundProxy_DNSRebind_SingleResolution is the regression test for
|
||||
// the DNS rebinding window. It simulates a DNS authority that returns a
|
||||
// public IP on the first lookup and a loopback IP on subsequent lookups.
|
||||
// The proxy must resolve the host exactly once per request and dial the
|
||||
// IP validated at that moment, so that a second resolution by any later
|
||||
// layer cannot pivot the connection to an internal target.
|
||||
func TestPinningProxy_DNSRebind_SingleResolution(t *testing.T) {
|
||||
func TestOutboundProxy_DNSRebind_SingleResolution(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = fmt.Fprint(w, "public-upstream")
|
||||
}))
|
||||
@@ -433,20 +431,20 @@ func TestPinningProxy_DNSRebind_SingleResolution(t *testing.T) {
|
||||
upstreamURL := mustParseURL(t, upstream.URL)
|
||||
|
||||
var lookupCount atomic.Int32
|
||||
stubDecide := func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
stubDecide := func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
n := lookupCount.Add(1)
|
||||
if n == 1 {
|
||||
// First lookup: returns a public IP, validation passes, the
|
||||
// proxy pins it for the dial.
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("93.184.216.34")}}, nil
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("93.184.216.34")}}, nil
|
||||
}
|
||||
// Any subsequent lookup for the same host would return a
|
||||
// loopback IP. This return value must not influence the dial
|
||||
// because the proxy must not call decide again for this request.
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("rebind lookup: %w", gotenberg.ErrFiltered)
|
||||
return OutboundDecision{}, fmt.Errorf("rebind lookup: %w", ErrFiltered)
|
||||
}
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = stubDecide
|
||||
p.dialPinned = func(_ context.Context, network string, addrs []netip.Addr, _ string) (net.Conn, error) {
|
||||
if len(addrs) != 1 || addrs[0].String() != "93.184.216.34" {
|
||||
@@ -481,27 +479,27 @@ func TestPinningProxy_DNSRebind_SingleResolution(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_CONNECT_ClientCancellation_LoggedAtDebug verifies that
|
||||
// TestOutboundProxy_CONNECT_ClientCancellation_LoggedAtDebug verifies that
|
||||
// when decide fails because the request context was canceled or its
|
||||
// deadline expired (the canonical case is Chromium dropping a speculative
|
||||
// CONNECT before the proxy finishes resolving the host), the proxy logs
|
||||
// at debug and not at warn. Policy refusals must still warn; see
|
||||
// [TestPinningProxy_CONNECT_BlockedByDecide].
|
||||
func TestPinningProxy_CONNECT_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
// [TestOutboundProxy_CONNECT_BlockedByDecide].
|
||||
func TestOutboundProxy_CONNECT_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
// Mimic the wrap chain produced by outbound.resolveHost when the
|
||||
// DNS lookup is canceled mid-flight by Chromium hanging up.
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("validate '%s' host: resolve %q: lookup %s: %w", "https://www.google.com:443", "www.google.com", "www.google.com", context.Canceled)
|
||||
return OutboundDecision{}, fmt.Errorf("validate '%s' host: resolve %q: lookup %s: %w", "https://www.google.com:443", "www.google.com", "www.google.com", context.Canceled)
|
||||
}
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(proxyURL, "http://"))
|
||||
if err != nil {
|
||||
@@ -542,23 +540,23 @@ func TestPinningProxy_CONNECT_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_Forward_ClientCancellation_LoggedAtDebug is the
|
||||
// TestOutboundProxy_Forward_ClientCancellation_LoggedAtDebug is the
|
||||
// handleForward equivalent of
|
||||
// [TestPinningProxy_CONNECT_ClientCancellation_LoggedAtDebug]. Plain
|
||||
// [TestOutboundProxy_CONNECT_ClientCancellation_LoggedAtDebug]. Plain
|
||||
// HTTP forward requests aborted by the client must also log at debug.
|
||||
func TestPinningProxy_Forward_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("validate host: %w", context.DeadlineExceeded)
|
||||
func TestOutboundProxy_Forward_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{}, fmt.Errorf("validate host: %w", context.DeadlineExceeded)
|
||||
}
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(mustParseURL(t, proxyURL))},
|
||||
@@ -592,22 +590,22 @@ func TestPinningProxy_Forward_ClientCancellation_LoggedAtDebug(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_PolicyDenial_LoggedAtWarn protects the existing
|
||||
// TestOutboundProxy_PolicyDenial_LoggedAtWarn protects the existing
|
||||
// behavior: a deny-list match (or any non-cancellation decide error) must
|
||||
// still surface at warn level so operators see real refusals.
|
||||
func TestPinningProxy_PolicyDenial_LoggedAtWarn(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("denied: %w", gotenberg.ErrFiltered)
|
||||
func TestOutboundProxy_PolicyDenial_LoggedAtWarn(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{}, fmt.Errorf("denied: %w", ErrFiltered)
|
||||
}
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(proxyURL, "http://"))
|
||||
if err != nil {
|
||||
@@ -645,17 +643,17 @@ func TestPinningProxy_PolicyDenial_LoggedAtWarn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_CONNECT_DialCancellation_LoggedAtDebug verifies that
|
||||
// TestOutboundProxy_CONNECT_DialCancellation_LoggedAtDebug verifies that
|
||||
// when the upstream dial fails because the request context was canceled
|
||||
// (typically Chromium dropping a speculative CONNECT before a slow IPv6
|
||||
// dial completes), the proxy logs at debug rather than warn. Genuine
|
||||
// dial failures must still warn; see
|
||||
// [TestPinningProxy_CONNECT_DialFailure_LoggedAtWarn].
|
||||
func TestPinningProxy_CONNECT_DialCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
// [TestOutboundProxy_CONNECT_DialFailure_LoggedAtWarn].
|
||||
func TestOutboundProxy_CONNECT_DialCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
// Mimic a dial canceled mid-flight by the client hanging up,
|
||||
@@ -665,10 +663,10 @@ func TestPinningProxy_CONNECT_DialCancellation_LoggedAtDebug(t *testing.T) {
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(proxyURL, "http://"))
|
||||
if err != nil {
|
||||
@@ -709,14 +707,14 @@ func TestPinningProxy_CONNECT_DialCancellation_LoggedAtDebug(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_CONNECT_DialFailure_LoggedAtWarn guards the existing
|
||||
// TestOutboundProxy_CONNECT_DialFailure_LoggedAtWarn guards the existing
|
||||
// behavior: a genuine dial failure (host unreachable, refused, etc.)
|
||||
// must still warn so operators see real problems.
|
||||
func TestPinningProxy_CONNECT_DialFailure_LoggedAtWarn(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
func TestOutboundProxy_CONNECT_DialFailure_LoggedAtWarn(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return nil, errors.New("connection refused")
|
||||
@@ -724,10 +722,10 @@ func TestPinningProxy_CONNECT_DialFailure_LoggedAtWarn(t *testing.T) {
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(proxyURL, "http://"))
|
||||
if err != nil {
|
||||
@@ -769,10 +767,10 @@ func TestPinningProxy_CONNECT_DialFailure_LoggedAtWarn(t *testing.T) {
|
||||
// connection rather than answering 502. Chromium treats a proxy response as
|
||||
// the origin's own, so a 502 would hide the failure from
|
||||
// failOnResourceLoadingFailed.
|
||||
func TestPinningProxy_Forward_DialFailure_ResetsClient(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
func TestOutboundProxy_Forward_DialFailure_ResetsClient(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return nil, errors.New("connection refused")
|
||||
@@ -781,11 +779,11 @@ func TestPinningProxy_Forward_DialFailure_ResetsClient(t *testing.T) {
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
err := p.Start(logger)
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(logger) })
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(p.URL(), "http://"))
|
||||
conn, err := net.Dial("tcp", p.Addr())
|
||||
if err != nil {
|
||||
t.Fatalf("dial proxy: %v", err)
|
||||
}
|
||||
@@ -806,15 +804,15 @@ func TestPinningProxy_Forward_DialFailure_ResetsClient(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_Forward_RoundTripCancellation_LoggedAtDebug verifies
|
||||
// TestOutboundProxy_Forward_RoundTripCancellation_LoggedAtDebug verifies
|
||||
// the handleForward dial-cancellation path: when the inner Transport's
|
||||
// dial returns a canceled error (client hung up mid-dial), the proxy
|
||||
// logs at debug, not warn. Genuine RoundTrip failures still warn.
|
||||
func TestPinningProxy_Forward_RoundTripCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
func TestOutboundProxy_Forward_RoundTripCancellation_LoggedAtDebug(t *testing.T) {
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return nil, fmt.Errorf("dial tcp [2001:4860::]:80: %w", context.Canceled)
|
||||
@@ -822,10 +820,10 @@ func TestPinningProxy_Forward_RoundTripCancellation_LoggedAtDebug(t *testing.T)
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
proxyURL := p.URL()
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
proxyURL := "http://" + p.Addr()
|
||||
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(mustParseURL(t, proxyURL))},
|
||||
@@ -887,7 +885,7 @@ func TestIsClientCancellation(t *testing.T) {
|
||||
{
|
||||
name: "policy denial",
|
||||
ctx: context.Background(),
|
||||
err: fmt.Errorf("denied: %w", gotenberg.ErrFiltered),
|
||||
err: fmt.Errorf("denied: %w", ErrFiltered),
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
@@ -906,13 +904,13 @@ func TestIsClientCancellation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_StartTwice(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
func TestOutboundProxy_StartTwice(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
err := p.Start(testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("first Start: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(testLogger()) })
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
err = p.Start(testLogger())
|
||||
if err == nil {
|
||||
@@ -920,20 +918,20 @@ func TestPinningProxy_StartTwice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinningProxy_StopIdempotent(t *testing.T) {
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
func TestOutboundProxy_StopIdempotent(t *testing.T) {
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
// Stop on a never-started proxy is a no-op.
|
||||
if err := p.Stop(testLogger()); err != nil {
|
||||
if err := p.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("Stop on never-started proxy: %v", err)
|
||||
}
|
||||
|
||||
if err := p.Start(testLogger()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
if err := p.Stop(testLogger()); err != nil {
|
||||
if err := p.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("first Stop: %v", err)
|
||||
}
|
||||
if err := p.Stop(testLogger()); err != nil {
|
||||
if err := p.Stop(context.Background()); err != nil {
|
||||
t.Fatalf("second Stop on stopped proxy: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1084,20 +1082,20 @@ func TestSpliceTunnel_ActiveTransferOutlivesIdleTimeout(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_CONNECT_TunnelCeiling verifies the ceiling that bounds what
|
||||
// TestOutboundProxy_CONNECT_TunnelCeiling verifies the ceiling that bounds what
|
||||
// tunnels refusing to end can accumulate. The idle bound cannot cover a peer
|
||||
// that trickles just under it, so the count is what stops the growth.
|
||||
func TestPinningProxy_CONNECT_TunnelCeiling(t *testing.T) {
|
||||
func TestOutboundProxy_CONNECT_TunnelCeiling(t *testing.T) {
|
||||
// An upstream that accepts and then says nothing: the tunnel stays open.
|
||||
upstreamAddr, stop := newRawTCPServer(t, func(c net.Conn) {
|
||||
<-make(chan struct{})
|
||||
})
|
||||
t.Cleanup(stop)
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.maxTunnels = 1
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamAddr)
|
||||
@@ -1153,19 +1151,19 @@ func TestPinningProxy_CONNECT_TunnelCeiling(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_TunnelSlotIsReleased verifies a completed tunnel gives its
|
||||
// TestOutboundProxy_TunnelSlotIsReleased verifies a completed tunnel gives its
|
||||
// slot back, so the ceiling bounds concurrency rather than lifetime totals.
|
||||
func TestPinningProxy_TunnelSlotIsReleased(t *testing.T) {
|
||||
func TestOutboundProxy_TunnelSlotIsReleased(t *testing.T) {
|
||||
upstreamAddr, stop := newRawTCPServer(t, func(c net.Conn) {
|
||||
defer c.Close()
|
||||
_, _ = c.Write([]byte("HI"))
|
||||
})
|
||||
t.Cleanup(stop)
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.maxTunnels = 1
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamAddr)
|
||||
@@ -1215,10 +1213,10 @@ func TestPinningProxy_TunnelSlotIsReleased(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_DecideTunnel_DenyRuleShapes pins which deny-list rule
|
||||
// TestOutboundProxy_DecideTunnel_DenyRuleShapes pins which deny-list rule
|
||||
// shapes refuse a CONNECT tunnel. The proxy only sees host:port, so the rules
|
||||
// are matched against the root URL of every scheme a tunnel may carry.
|
||||
func TestPinningProxy_DecideTunnel_DenyRuleShapes(t *testing.T) {
|
||||
func TestOutboundProxy_DecideTunnel_DenyRuleShapes(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rule string
|
||||
@@ -1236,17 +1234,17 @@ func TestPinningProxy_DecideTunnel_DenyRuleShapes(t *testing.T) {
|
||||
{"path rule cannot match a tunnel", `^wss://denied\.example/ws`, "denied.example:443", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
p := newPinningProxy(nil, []*regexp2.Regexp{regexp2.MustCompile(tc.rule, regexp2.None)}, false, false, false, nil)
|
||||
p.decide = func(context.Context, string, []*regexp2.Regexp, []*regexp2.Regexp, time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Bypass: true}, nil
|
||||
p := NewOutboundProxy(OutboundProxyOptions{DenyList: []*regexp2.Regexp{regexp2.MustCompile(tc.rule, regexp2.None)}})
|
||||
p.decide = func(context.Context, string, []*regexp2.Regexp, []*regexp2.Regexp, time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Bypass: true}, nil
|
||||
}
|
||||
|
||||
_, err := p.decideTunnel(context.Background(), tc.hostport, time.Now().Add(time.Minute))
|
||||
_, err := p.DecideTunnel(context.Background(), tc.hostport, time.Now().Add(time.Minute))
|
||||
if tc.denied != (err != nil) {
|
||||
t.Fatalf("decideTunnel(%q) with rule %q: error = %v, want denied: %t", tc.hostport, tc.rule, err, tc.denied)
|
||||
}
|
||||
if err != nil && !errors.Is(err, gotenberg.ErrFiltered) {
|
||||
t.Errorf("error %v does not wrap gotenberg.ErrFiltered", err)
|
||||
if err != nil && !errors.Is(err, ErrFiltered) {
|
||||
t.Errorf("error %v does not wrap ErrFiltered", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1255,16 +1253,16 @@ func TestPinningProxy_DecideTunnel_DenyRuleShapes(t *testing.T) {
|
||||
// A tunnel whose upstream never answers must end with the proxy that accepted
|
||||
// it, including across a restart: Shutdown does not reach hijacked
|
||||
// connections.
|
||||
func TestPinningProxy_StopClosesTunnels(t *testing.T) {
|
||||
func TestOutboundProxy_StopClosesTunnels(t *testing.T) {
|
||||
upstreamAddr, stop := newRawTCPServer(t, func(c net.Conn) {
|
||||
defer c.Close()
|
||||
_, _ = io.Copy(io.Discard, c)
|
||||
})
|
||||
t.Cleanup(stop)
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, network string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
return net.Dial(network, upstreamAddr)
|
||||
@@ -1273,10 +1271,10 @@ func TestPinningProxy_StopClosesTunnels(t *testing.T) {
|
||||
for attempt := range 2 {
|
||||
err := p.Start(testLogger())
|
||||
if err != nil {
|
||||
t.Fatalf("attempt %d start pinning proxy: %v", attempt, err)
|
||||
t.Fatalf("attempt %d start outbound proxy: %v", attempt, err)
|
||||
}
|
||||
|
||||
conn, err := net.Dial("tcp", strings.TrimPrefix(p.URL(), "http://"))
|
||||
conn, err := net.Dial("tcp", p.Addr())
|
||||
if err != nil {
|
||||
t.Fatalf("attempt %d dial proxy: %v", attempt, err)
|
||||
}
|
||||
@@ -1293,9 +1291,9 @@ func TestPinningProxy_StopClosesTunnels(t *testing.T) {
|
||||
}
|
||||
_, _ = br.ReadString('\n')
|
||||
|
||||
err = p.Stop(testLogger())
|
||||
err = p.Stop(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("attempt %d stop pinning proxy: %v", attempt, err)
|
||||
t.Fatalf("attempt %d stop outbound proxy: %v", attempt, err)
|
||||
}
|
||||
|
||||
err = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
@@ -1311,33 +1309,33 @@ func TestPinningProxy_StopClosesTunnels(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_Forward_RedactsURLInLogs pins that the logs of a forward
|
||||
// TestOutboundProxy_Forward_RedactsURLInLogs pins that the logs of a forward
|
||||
// the policy blocks, or that fails, name the URL without its query, which may
|
||||
// hold a token.
|
||||
func TestPinningProxy_Forward_RedactsURLInLogs(t *testing.T) {
|
||||
func TestOutboundProxy_Forward_RedactsURLInLogs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
decide func(context.Context, string, []*regexp2.Regexp, []*regexp2.Regexp, time.Time) (gotenberg.OutboundDecision, error)
|
||||
decide func(context.Context, string, []*regexp2.Regexp, []*regexp2.Regexp, time.Time) (OutboundDecision, error)
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "blocked",
|
||||
decide: func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{}, fmt.Errorf("nope: %w", gotenberg.ErrFiltered)
|
||||
decide: func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{}, fmt.Errorf("nope: %w", ErrFiltered)
|
||||
},
|
||||
want: "forward blocked for 'http://blocked.example/report'",
|
||||
},
|
||||
{
|
||||
name: "failed",
|
||||
decide: func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Bypass: true}, nil
|
||||
decide: func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Bypass: true}, nil
|
||||
},
|
||||
want: "forward RoundTrip failed for 'http://blocked.example/report'",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec := &recordingHandler{}
|
||||
p := newPinningProxy(nil, nil, false, false, false, nil)
|
||||
rec := &proxyLogRecorder{}
|
||||
p := NewOutboundProxy(OutboundProxyOptions{})
|
||||
p.decide = tc.decide
|
||||
p.dialBypass = func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, errors.New("connection refused")
|
||||
@@ -1345,12 +1343,12 @@ func TestPinningProxy_Forward_RedactsURLInLogs(t *testing.T) {
|
||||
|
||||
err := p.Start(slog.New(rec))
|
||||
if err != nil {
|
||||
t.Fatalf("start pinning proxy: %v", err)
|
||||
t.Fatalf("start outbound proxy: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = p.Stop(slog.New(rec)) })
|
||||
t.Cleanup(func() { _ = p.Stop(context.Background()) })
|
||||
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(mustParseURL(t, p.URL()))},
|
||||
Transport: &http.Transport{Proxy: http.ProxyURL(mustParseURL(t, "http://"+p.Addr()))},
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
resp, err := client.Get("http://blocked.example/report?token=secret")
|
||||
@@ -1374,15 +1372,21 @@ func TestPinningProxy_Forward_RedactsURLInLogs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPinningProxy_HostMapping runs the real outbound decision with a
|
||||
// TestOutboundProxy_HostMapping runs the real outbound decision with a
|
||||
// --chromium-host-resolver-rules mapping: the proxy dials where the rules send
|
||||
// a request, and the IP-class policy judges that address. Before the proxy
|
||||
// applied the rules, any rule turned it off, and with it the only layer that
|
||||
// can refuse a WebSocket handshake.
|
||||
func TestPinningProxy_HostMapping(t *testing.T) {
|
||||
rules, err := parseHostResolverRules("MAP mapped.test 1.1.1.1:8443, MAP private.test 10.0.0.5, MAP unrelated.invalid 127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("parse rules: %v", err)
|
||||
func TestOutboundProxy_HostMapping(t *testing.T) {
|
||||
mapping := func(host, port string) (string, string, error) {
|
||||
switch host {
|
||||
case "mapped.test":
|
||||
return "1.1.1.1", "8443", nil
|
||||
case "private.test":
|
||||
return "10.0.0.5", port, nil
|
||||
default:
|
||||
return host, port, nil
|
||||
}
|
||||
}
|
||||
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -1399,7 +1403,7 @@ func TestPinningProxy_HostMapping(t *testing.T) {
|
||||
dialedAddrs []netip.Addr
|
||||
dialedPort string
|
||||
)
|
||||
p := newPinningProxy(nil, nil, true, false, false, rules.rewrite)
|
||||
p := NewOutboundProxy(OutboundProxyOptions{DenyPrivateIPs: true, HostMapping: mapping})
|
||||
p.dialPinned = func(_ context.Context, network string, addrs []netip.Addr, port string) (net.Conn, error) {
|
||||
dialedMu.Lock()
|
||||
dialedAddrs, dialedPort = addrs, port
|
||||
@@ -1,4 +1,4 @@
|
||||
package chromium
|
||||
package gotenberg
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -15,15 +15,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dlclark/regexp2/v2"
|
||||
|
||||
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
|
||||
)
|
||||
|
||||
// TestPinningProxy_Forward_ThroughUpstreamProxy verifies that when the
|
||||
// TestOutboundProxy_Forward_ThroughUpstreamProxy verifies that when the
|
||||
// operator opts into proxy-environment honoring, a plain HTTP request is
|
||||
// forwarded through the upstream (corporate) proxy with the credentials
|
||||
// Chromium cannot supply. See https://github.com/gotenberg/gotenberg/issues/1592.
|
||||
func TestPinningProxy_Forward_ThroughUpstreamProxy(t *testing.T) {
|
||||
func TestOutboundProxy_Forward_ThroughUpstreamProxy(t *testing.T) {
|
||||
var gotAuth atomic.Value
|
||||
gotAuth.Store("")
|
||||
|
||||
@@ -38,11 +36,11 @@ func TestPinningProxy_Forward_ThroughUpstreamProxy(t *testing.T) {
|
||||
upstreamURL := mustParseURL(t, upstream.URL)
|
||||
upstreamURL.User = url.UserPassword("bob", "pw")
|
||||
|
||||
p := newPinningProxy(nil, nil, false, false, true, nil)
|
||||
p := NewOutboundProxy(OutboundProxyOptions{EnableEnvironmentProxy: true})
|
||||
// Force every destination through our stub upstream proxy.
|
||||
p.upstreamProxy = func(_ *url.URL) (*url.URL, error) { return upstreamURL, nil }
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (gotenberg.OutboundDecision, error) {
|
||||
return gotenberg.OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
p.decide = func(_ context.Context, _ string, _, _ []*regexp2.Regexp, _ time.Time) (OutboundDecision, error) {
|
||||
return OutboundDecision{Pinned: []netip.Addr{netip.MustParseAddr("127.0.0.1")}}, nil
|
||||
}
|
||||
p.dialPinned = func(_ context.Context, _ string, _ []netip.Addr, _ string) (net.Conn, error) {
|
||||
t.Fatal("dialPinned must not be called when routing through an upstream proxy")
|
||||
@@ -145,7 +145,7 @@ type chromiumBrowser struct {
|
||||
|
||||
arguments browserArguments
|
||||
fs *gotenberg.FileSystem
|
||||
pinningProxy *pinningProxy
|
||||
pinningProxy *gotenberg.OutboundProxy
|
||||
|
||||
// pid is the browser process, which the memory watch reads with its
|
||||
// descendants, the renderers. Set by Start, under ctxMu.
|
||||
@@ -162,10 +162,17 @@ type chromiumBrowser struct {
|
||||
|
||||
func newChromiumBrowser(arguments browserArguments) browser {
|
||||
b := &chromiumBrowser{
|
||||
initialCtx: context.Background(),
|
||||
arguments: arguments,
|
||||
fs: gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll)),
|
||||
pinningProxy: newPinningProxy(arguments.allowList, arguments.denyList, arguments.denyPrivateIPs, arguments.denyPublicIPs, arguments.enableEnvironmentProxy, arguments.hostMapping()),
|
||||
initialCtx: context.Background(),
|
||||
arguments: arguments,
|
||||
fs: gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll)),
|
||||
pinningProxy: gotenberg.NewOutboundProxy(gotenberg.OutboundProxyOptions{
|
||||
AllowList: arguments.allowList,
|
||||
DenyList: arguments.denyList,
|
||||
DenyPrivateIPs: arguments.denyPrivateIPs,
|
||||
DenyPublicIPs: arguments.denyPublicIPs,
|
||||
EnableEnvironmentProxy: arguments.enableEnvironmentProxy,
|
||||
HostMapping: arguments.hostMapping(),
|
||||
}),
|
||||
}
|
||||
b.isStarted.Store(false)
|
||||
|
||||
@@ -215,7 +222,7 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e
|
||||
|
||||
// The pinning proxy starts first, as Chromium's switches name its address.
|
||||
if b.arguments.usesPinningProxy() {
|
||||
err = b.pinningProxy.Start(logger)
|
||||
err = b.pinningProxy.Start(logger.With(slog.String("logger", "pinning-proxy")))
|
||||
if err != nil {
|
||||
return fmt.Errorf("start pinning proxy: %w", err)
|
||||
}
|
||||
@@ -227,7 +234,7 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e
|
||||
return
|
||||
}
|
||||
|
||||
stopErr := b.pinningProxy.Stop(logger)
|
||||
stopErr := b.stopPinningProxy()
|
||||
if stopErr != nil {
|
||||
logger.ErrorContext(context.Background(), fmt.Sprintf("stop pinning proxy after failed start: %s", stopErr))
|
||||
}
|
||||
@@ -358,7 +365,7 @@ type chromiumProcess struct {
|
||||
func (b *chromiumBrowser) launch(logger *slog.Logger, debug *debugLogger) (*chromiumProcess, error) {
|
||||
proxyServer := b.arguments.proxyServer
|
||||
if b.arguments.usesPinningProxy() {
|
||||
proxyServer = b.pinningProxy.URL()
|
||||
proxyServer = "http://" + b.pinningProxy.Addr()
|
||||
}
|
||||
|
||||
pipe, chromiumEnds, err := newDevToolsPipe()
|
||||
@@ -665,7 +672,7 @@ func (b *chromiumBrowser) Stop(logger *slog.Logger) error {
|
||||
// in-flight requests Chromium issues during teardown complete. The
|
||||
// Stop call is a no-op when the proxy was not started (operator
|
||||
// configured --chromium-proxy-server or --chromium-host-resolver-rules).
|
||||
err := b.pinningProxy.Stop(logger)
|
||||
err := b.stopPinningProxy()
|
||||
if err != nil {
|
||||
logger.ErrorContext(context.Background(), fmt.Sprintf("stop pinning proxy: %s", err))
|
||||
}
|
||||
@@ -673,6 +680,15 @@ func (b *chromiumBrowser) Stop(logger *slog.Logger) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// stopPinningProxy stops the pinning proxy, giving its in-flight handlers a
|
||||
// few seconds to complete.
|
||||
func (b *chromiumBrowser) stopPinningProxy() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
return b.pinningProxy.Stop(ctx)
|
||||
}
|
||||
|
||||
func (b *chromiumBrowser) Healthy(logger *slog.Logger) bool {
|
||||
// Good to know: the supervisor does not call this method if no first start
|
||||
// or if the process is restarting.
|
||||
@@ -987,7 +1003,7 @@ func (b *chromiumBrowser) listen(requestCtx, taskCtx context.Context, taskCancel
|
||||
cancel: taskCancel,
|
||||
}
|
||||
if b.arguments.usesPinningProxy() {
|
||||
webSocketOptions.decideTunnel = b.pinningProxy.decideTunnel
|
||||
webSocketOptions.decideTunnel = b.pinningProxy.DecideTunnel
|
||||
}
|
||||
|
||||
listenForEventWebSocketCreated(taskCtx, logger, webSocketOptions)
|
||||
|
||||
34
pkg/modules/chromium/logging_test.go
Normal file
34
pkg/modules/chromium/logging_test.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package chromium
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// recordingHandler is a slog.Handler that captures every record emitted
|
||||
// through it so tests can assert on the level and message of logs.
|
||||
type recordingHandler struct {
|
||||
mu sync.Mutex
|
||||
records []slog.Record
|
||||
}
|
||||
|
||||
func (h *recordingHandler) Enabled(_ context.Context, _ slog.Level) bool { return true }
|
||||
|
||||
func (h *recordingHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.records = append(h.records, r.Clone())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *recordingHandler) WithAttrs(_ []slog.Attr) slog.Handler { return h }
|
||||
func (h *recordingHandler) WithGroup(_ string) slog.Handler { return h }
|
||||
|
||||
func (h *recordingHandler) snapshot() []slog.Record {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
out := make([]slog.Record, len(h.records))
|
||||
copy(out, h.records)
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user