fix(chromium): drive Chromium over a pipe and start its workers locked out of file:// URLs

This commit is contained in:
Julien Neuhart
2026-11-21 19:14:27 +01:00
parent 1a20e3d879
commit 5777a712ae
12 changed files with 1661 additions and 118 deletions

2
go.mod
View File

@@ -9,6 +9,7 @@ require (
github.com/coreos/go-oidc/v3 v3.21.0
github.com/cucumber/godog v0.16.0
github.com/dlclark/regexp2/v2 v2.13.1
github.com/gobwas/ws v1.5.0
github.com/gomarkdown/markdown v0.0.0-20261117205700-e8c6d33a8b6c
github.com/google/uuid v1.6.0
github.com/gotenberg/litho v0.0.18
@@ -77,7 +78,6 @@ require (
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/ws v1.5.0 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/google/pprof v0.0.0-20261118010117-084b33a85f63 // indirect
github.com/gorilla/css v1.0.1 // indirect

View File

@@ -4,8 +4,11 @@ import (
"context"
"errors"
"fmt"
"io"
"log"
"log/slog"
"os"
"os/exec"
"slices"
"strings"
"sync"
@@ -32,8 +35,8 @@ import (
//
// It restates the "site-per-process,Translate,BlinkGenPropertyTrees" default
// from chromedp.DefaultExecAllocatorOptions (chromedp v0.14.2) on purpose:
// chromedp.Flag keys its flags by switch name, so a second --disable-features
// replaces chromedp's value instead of merging with it. Revisit this list when
// [chromiumSwitches] keys the switches by name, as chromedp does, so this
// value replaces chromedp's instead of merging with it. Revisit this list when
// bumping chromedp.
//
// WebUIOmniboxPopup and WebUIOmniboxAimPopup became enabled by default in
@@ -210,133 +213,115 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e
return fmt.Errorf("create symlink to hyphen-data directory: %w", err)
}
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.CombinedOutput(debug),
chromedp.ExecPath(b.arguments.binPath),
chromedp.NoSandbox,
// See:
// https://github.com/puppeteer/puppeteer/issues/661
// https://github.com/puppeteer/puppeteer/issues/2410
chromedp.Flag("font-render-hinting", "none"),
chromedp.UserDataDir(b.userProfileDirPath),
// See https://github.com/gotenberg/gotenberg/issues/831.
chromedp.Flag("disable-pdf-tagging", true),
// See https://github.com/gotenberg/gotenberg/issues/1177.
chromedp.Flag("no-zygote", true),
chromedp.Flag("disable-dev-shm-usage", true),
// See https://github.com/gotenberg/gotenberg/issues/1293.
chromedp.Flag("disable-component-update", false),
// See https://github.com/gotenberg/gotenberg/issues/1656.
chromedp.Flag("disable-features", chromiumDisableFeatures),
// See https://github.com/gotenberg/gotenberg/issues/1706.
chromedp.Flag("gaia-url", chromiumGaiaUrl),
)
if b.arguments.allowInsecureLocalhost {
// See https://github.com/gotenberg/gotenberg/issues/488.
opts = append(opts, chromedp.Flag("allow-insecure-localhost", true))
}
if b.arguments.ignoreCertificateErrors {
opts = append(opts, chromedp.IgnoreCertErrors)
}
if b.arguments.disableWebSecurity {
opts = append(opts, chromedp.Flag("disable-web-security", true))
}
if b.arguments.allowFileAccessFromFiles {
// See https://github.com/gotenberg/gotenberg/issues/356.
opts = append(opts, chromedp.Flag("allow-file-access-from-files", true))
}
if b.arguments.hostResolverRules != "" && !b.arguments.usesPinningProxy() {
// Behind the pinning proxy, Chromium resolves nothing but the proxy
// itself, and would apply a rule such as "MAP * ~NOTFOUND" to its
// 127.0.0.1 address. The pinning proxy applies the rules instead.
// See https://github.com/gotenberg/gotenberg/issues/488.
opts = append(opts, chromedp.Flag("host-resolver-rules", b.arguments.hostResolverRules))
}
if b.arguments.proxyServer != "" {
// See https://github.com/gotenberg/gotenberg/issues/376.
opts = append(opts, chromedp.ProxyServer(b.arguments.proxyServer))
}
// Default: route Chromium through the internal pinning proxy so that
// Chromium never performs its own DNS lookup for the navigation URL
// or any sub-resource. The proxy resolves and validates each URL
// once per request and dials the pinned IP, closing the DNS
// rebinding window between Gotenberg's validation and Chromium's
// connect.
//
// Skip when the operator has configured their own egress proxy: that
// proxy owns outbound safety, and routing through an internal proxy
// would override it. Custom host-resolver mappings keep the pinning
// proxy, which applies them, so that the outbound policy still covers
// WebSocket handshakes. Without it, nothing could block those.
// The pinning proxy starts first, as Chromium's switches name its address.
if b.arguments.usesPinningProxy() {
err = b.pinningProxy.Start(logger)
if err != nil {
return fmt.Errorf("start pinning proxy: %w", err)
}
opts = append(opts, chromedp.ProxyServer(b.pinningProxy.URL()))
if b.arguments.restrictsNetwork() || b.arguments.hostMapping() != nil {
// Chromium implicitly bypasses the proxy for loopback and
// link-local destinations. A WebSocket handshake is never surfaced
// as a fetch.EventRequestPaused, so listenForEventRequestPaused
// cannot filter it; the pinning proxy is the only layer that sees
// it. Left alone, a page could open a WebSocket to 127.0.0.1, ::1,
// localhost, or the link-local cloud metadata endpoint
// (169.254.169.254) and reach it unfiltered. "<-loopback>" removes
// the implicit bypass so those handshakes also traverse the
// pinning proxy and go through [gotenberg.DecideOutbound] like
// every other request.
//
// Gated on a policy that can reject a network URL: without one,
// loopback is not restricted, and routing it through the proxy
// would only turn a refused loopback sub-resource into a 502
// response instead of a loading failure. Host-resolver mappings
// also need it, since a rule may send "localhost" elsewhere and
// only the proxy applies the rules.
opts = append(opts, chromedp.Flag("proxy-bypass-list", "<-loopback>"))
}
// Tear it down on a failed start so a supervisor retry can re-bind.
// See https://github.com/gotenberg/gotenberg/issues/1559.
defer func() {
if err == nil {
return
}
stopErr := b.pinningProxy.Stop(logger)
if stopErr != nil {
logger.ErrorContext(context.Background(), fmt.Sprintf("stop pinning proxy after failed start: %s", stopErr))
}
}()
}
// --chromium-start-timeout bounds the start, from the launch to the
// DevTools handshake.
// See https://github.com/gotenberg/gotenberg/issues/524.
opts = append(opts, chromedp.WSURLReadTimeout(b.arguments.wsUrlReadTimeout))
startCtx, cancelStartTimeout := context.WithTimeout(ctx, b.arguments.wsUrlReadTimeout)
defer cancelStartTimeout()
// The browser outlives the start, so its context derives from initialCtx.
// Until the start succeeds, ctx may still abort it.
allocatorCtx, allocatorCancel := chromedp.NewExecAllocator(b.initialCtx, opts...)
var contextOpts []chromedp.ContextOption
process, err := b.launch(logger, debug)
if err != nil {
return fmt.Errorf("launch Chromium: %w", err)
}
// Until the start succeeds, its context may abort it.
abortStart := context.AfterFunc(startCtx, process.stop)
defer func() {
if err == nil {
return
}
abortStart()
process.stop()
<-process.exited
if ctx.Err() != nil {
err = fmt.Errorf("start Chromium: %w: %w", ctx.Err(), err)
return
}
err = fmt.Errorf("start Chromium: %w; if Chromium is slow to start, raise --chromium-start-timeout (CHROMIUM_START_TIMEOUT), currently %s", err, b.arguments.wsUrlReadTimeout)
}()
initialPage, err := process.pipe.initialPage()
if err != nil {
return fmt.Errorf("discover the initial page: %w", process.exitError(startCtx, err))
}
deadline, _ := startCtx.Deadline()
bridge, err := newDevToolsBridge(process.pipe, deadline)
if err != nil {
return fmt.Errorf("bridge DevTools: %w", err)
}
// Nothing listens anymore once the start is over.
defer bridge.closeListener()
// The browser outlives the start, so its context derives from the
// process's, which derives from initialCtx.
allocatorCtx, allocatorCancel := chromedp.NewRemoteAllocator(process.ctx, bridge.url(), chromedp.NoModifyURL)
contextOpts := []chromedp.ContextOption{
chromedp.WithTargetID(initialPage),
chromedp.WithErrorf(func(format string, v ...any) {
if format == "executor for %q doesn't exist" {
// The end of a session chromedp does not drive: the browser
// session auto-attaches shared and service workers, see
// lockBrowserWorkers, and chromedp drives a session of its
// own to each.
debug.Printf(format, v...)
return
}
// chromedp's default.
log.Printf("ERROR: "+format, v...)
}),
}
if b.arguments.debugProtocol {
contextOpts = append(contextOpts, chromedp.WithDebugf(debug.Printf))
}
browserCtx, cancel := chromedp.NewContext(allocatorCtx, contextOpts...)
abortStart := context.AfterFunc(ctx, func() {
// chromedp cancels browserCtx when it loses the connection, but does not
// kill a process it did not start.
stopKillOnLostConnection := context.AfterFunc(browserCtx, process.stop)
stop := func() {
// chromedp first detaches from the tab over the live connection.
stopKillOnLostConnection()
cancel()
allocatorCancel()
})
process.stop()
<-process.exited
}
err = chromedp.Run(browserCtx)
if err == nil {
err = lockBrowserWorkers(startCtx, browserCtx, logger)
}
if err == nil && !abortStart() {
// ctx was done right as Chromium came up: the browser is going down.
err = ctx.Err()
// startCtx was done right as Chromium came up: the browser is going
// down.
err = startCtx.Err()
}
if err != nil {
cancel()
allocatorCancel()
// The pinning proxy started before chromedp; tear it down so a
// supervisor retry can re-bind. Stop is a no-op when the proxy
// was never started (operator-configured --chromium-proxy-server).
// See https://github.com/gotenberg/gotenberg/issues/1559.
stopErr := b.pinningProxy.Stop(logger)
if stopErr != nil {
logger.ErrorContext(context.Background(), fmt.Sprintf("stop pinning proxy after failed start: %s", stopErr))
}
return fmt.Errorf("run exec allocator: %w; if Chromium is slow to start, raise --chromium-start-timeout (currently %s)", err, b.arguments.wsUrlReadTimeout)
stop()
return fmt.Errorf("connect to Chromium: %w", process.exitError(startCtx, err))
}
b.ctxMu.Lock()
@@ -345,20 +330,260 @@ func (b *chromiumBrowser) Start(ctx context.Context, logger *slog.Logger) (err e
// We have to keep the context around, as we need it to create new tabs
// later.
b.ctx = browserCtx
b.cancelFunc = func() {
cancel()
allocatorCancel()
}
b.pid = 0
if c := chromedp.FromContext(browserCtx); c != nil && c.Browser != nil && c.Browser.Process() != nil {
b.pid = c.Browser.Process().Pid
}
b.cancelFunc = stop
b.pid = process.cmd.Process.Pid
b.memoryExceeded.Store(0)
b.isStarted.Store(true)
return nil
}
// chromiumProcess is a Chromium process Gotenberg drives over
// --remote-debugging-pipe.
type chromiumProcess struct {
cmd *exec.Cmd
pipe *devToolsPipe
// ctx is done once the process must go: stop kills it then.
ctx context.Context
stop context.CancelFunc
// exited is closed once the process has exited, after which waitErr
// holds how.
exited chan struct{}
waitErr error
}
// launch starts Chromium with the switches of [chromiumSwitches]. Its output
// goes to the debug logs. The process lives until its stop function is
// called, or Gotenberg exits.
func (b *chromiumBrowser) launch(logger *slog.Logger, debug *debugLogger) (*chromiumProcess, error) {
proxyServer := b.arguments.proxyServer
if b.arguments.usesPinningProxy() {
proxyServer = b.pinningProxy.URL()
}
pipe, chromiumEnds, err := newDevToolsPipe()
if err != nil {
return nil, fmt.Errorf("create DevTools pipe: %w", err)
}
output, chromiumOutput, err := os.Pipe()
if err != nil {
pipe.close()
closeFiles(chromiumEnds...)
return nil, fmt.Errorf("create output pipe: %w", err)
}
cmd := exec.Command(b.arguments.binPath, chromiumSwitches(b.arguments, b.userProfileDirPath, proxyServer)...) //nolint:gosec
cmd.ExtraFiles = chromiumEnds
cmd.Stdout = chromiumOutput
cmd.Stderr = chromiumOutput
setParentDeathSignal(cmd)
logger.DebugContext(context.Background(), fmt.Sprintf("start Chromium: %s", strings.Join(cmd.Args, " ")))
err = cmd.Start()
// Chromium holds its own copies now.
closeFiles(append(chromiumEnds, chromiumOutput)...)
if err != nil {
pipe.close()
closeFiles(output)
return nil, fmt.Errorf("start Chromium: %w", err)
}
go func() {
_, _ = io.Copy(debug, output)
closeFiles(output)
}()
processCtx, stop := context.WithCancel(b.initialCtx)
process := &chromiumProcess{
cmd: cmd,
pipe: pipe,
ctx: processCtx,
stop: stop,
exited: make(chan struct{}),
}
go func() {
process.waitErr = cmd.Wait()
pipe.close()
close(process.exited)
}()
context.AfterFunc(processCtx, func() {
err := cmd.Process.Kill()
if err != nil && !errors.Is(err, os.ErrProcessDone) {
logger.ErrorContext(context.Background(), fmt.Sprintf("kill Chromium: %s", err))
}
pipe.close()
})
return process, nil
}
// exitError adds to err, an error the start ran into, its cause: the start
// ran out of time, or Chromium exited.
func (p *chromiumProcess) exitError(startCtx context.Context, err error) error {
select {
case <-p.exited:
if startCtx.Err() == nil {
return fmt.Errorf("Chromium exited (%v): %w", p.waitErr, err)
}
case <-startCtx.Done():
}
return fmt.Errorf("%w: %w", startCtx.Err(), err)
}
// chromiumSwitches returns the command line Gotenberg starts Chromium with.
// proxyServer is the address of the proxy Chromium sends its traffic to.
func chromiumSwitches(arguments browserArguments, userProfileDirPath, proxyServer string) []string {
// A string value gives --name=value, true gives --name, and false leaves
// the switch out.
switches := map[string]any{
// The switches of chromedp.DefaultExecAllocatorOptions (chromedp
// v0.14.2), which Gotenberg keeps while it starts Chromium itself.
// Revisit this list when bumping chromedp.
"no-first-run": true,
"no-default-browser-check": true,
"headless": true,
"hide-scrollbars": true,
"mute-audio": true,
"disable-background-networking": true,
"enable-features": "NetworkService,NetworkServiceInProcess",
"disable-background-timer-throttling": true,
"disable-backgrounding-occluded-windows": true,
"disable-breakpad": true,
"disable-client-side-phishing-detection": true,
"disable-default-apps": true,
"disable-dev-shm-usage": true,
"disable-extensions": true,
"disable-hang-monitor": true,
"disable-ipc-flooding-protection": true,
"disable-popup-blocking": true,
"disable-prompt-on-repost": true,
"disable-renderer-backgrounding": true,
"disable-sync": true,
"force-color-profile": "srgb",
"metrics-recording-only": true,
"safebrowsing-disable-auto-update": true,
"enable-automation": true,
"password-store": "basic",
"use-mock-keychain": true,
// Gotenberg's own.
"no-sandbox": true,
// See:
// https://github.com/puppeteer/puppeteer/issues/661
// https://github.com/puppeteer/puppeteer/issues/2410
"font-render-hinting": "none",
"user-data-dir": userProfileDirPath,
// See https://github.com/gotenberg/gotenberg/issues/831.
"disable-pdf-tagging": true,
// See https://github.com/gotenberg/gotenberg/issues/1177.
"no-zygote": true,
// See https://github.com/gotenberg/gotenberg/issues/1293.
"disable-component-update": false,
// See https://github.com/gotenberg/gotenberg/issues/1656.
"disable-features": chromiumDisableFeatures,
// See https://github.com/gotenberg/gotenberg/issues/1706.
"gaia-url": chromiumGaiaUrl,
// DevTools over file descriptors 3 and 4, and no port: see
// [devToolsPipe].
"remote-debugging-pipe": true,
}
if arguments.allowInsecureLocalhost {
// See https://github.com/gotenberg/gotenberg/issues/488.
switches["allow-insecure-localhost"] = true
}
if arguments.ignoreCertificateErrors {
switches["ignore-certificate-errors"] = true
}
if arguments.disableWebSecurity {
switches["disable-web-security"] = true
}
if arguments.allowFileAccessFromFiles {
// See https://github.com/gotenberg/gotenberg/issues/356.
switches["allow-file-access-from-files"] = true
}
if arguments.hostResolverRules != "" && !arguments.usesPinningProxy() {
// Behind the pinning proxy, Chromium resolves nothing but the proxy
// itself, and would apply a rule such as "MAP * ~NOTFOUND" to its
// 127.0.0.1 address. The pinning proxy applies the rules instead.
// See https://github.com/gotenberg/gotenberg/issues/488.
switches["host-resolver-rules"] = arguments.hostResolverRules
}
if proxyServer != "" {
// Default: route Chromium through the internal pinning proxy so that
// Chromium never performs its own DNS lookup for the navigation URL
// or any sub-resource. The proxy resolves and validates each URL
// once per request and dials the pinned IP, closing the DNS
// rebinding window between Gotenberg's validation and Chromium's
// connect.
//
// The operator's egress proxy, set with --chromium-proxy-server,
// takes its place: that proxy owns outbound safety, and routing
// through an internal proxy would override it. Custom host-resolver
// mappings keep the pinning proxy, which applies them, so that the
// outbound policy still covers WebSocket handshakes. Without it,
// nothing could block those.
// See https://github.com/gotenberg/gotenberg/issues/376.
switches["proxy-server"] = proxyServer
}
if arguments.usesPinningProxy() && (arguments.restrictsNetwork() || arguments.hostMapping() != nil) {
// Chromium implicitly bypasses the proxy for loopback and
// link-local destinations. A WebSocket handshake is never surfaced
// as a fetch.EventRequestPaused, so listenForEventRequestPaused
// cannot filter it; the pinning proxy is the only layer that sees
// it. Left alone, a page could open a WebSocket to 127.0.0.1, ::1,
// localhost, or the link-local cloud metadata endpoint
// (169.254.169.254) and reach it unfiltered. "<-loopback>" removes
// the implicit bypass so those handshakes also traverse the
// pinning proxy and go through [gotenberg.DecideOutbound] like
// every other request.
//
// Gated on a policy that can reject a network URL: without one,
// loopback is not restricted, and routing it through the proxy
// would only turn a refused loopback sub-resource into a 502
// response instead of a loading failure. Host-resolver mappings
// also need it, since a rule may send "localhost" elsewhere and
// only the proxy applies the rules.
switches["proxy-bypass-list"] = "<-loopback>"
}
args := make([]string, 0, len(switches)+1)
for name, value := range switches {
switch value := value.(type) {
case string:
args = append(args, fmt.Sprintf("--%s=%s", name, value))
case bool:
if value {
args = append(args, "--"+name)
}
}
}
slices.Sort(args)
// The first tab opens on a blank page, which --no-first-run alone does
// not ensure.
return append(args, "about:blank")
}
// closeFiles closes files, ignoring errors: callers close copies another
// process holds, or ends they no longer read.
func closeFiles(files ...*os.File) {
for _, f := range files {
_ = f.Close()
}
}
func (b *chromiumBrowser) Stop(logger *slog.Logger) error {
b.lifecycleMu.Lock()
defer b.lifecycleMu.Unlock()
@@ -489,6 +714,7 @@ func (b *chromiumBrowser) pdf(ctx context.Context, logger *slog.Logger, url, out
network.Enable(),
fetch.Enable(),
runtime.Enable(),
pauseWorkersActionFunc(logger),
clearCacheActionFunc(logger, b.arguments.clearCache),
clearCookiesActionFunc(logger, b.arguments.clearCookies),
clearStorageActionFunc(logger, b.arguments.clearStorage, url),
@@ -517,6 +743,7 @@ func (b *chromiumBrowser) screenshot(ctx context.Context, logger *slog.Logger, u
network.Enable(),
fetch.Enable(),
runtime.Enable(),
pauseWorkersActionFunc(logger),
clearCacheActionFunc(logger, b.arguments.clearCache),
clearCookiesActionFunc(logger, b.arguments.clearCookies),
clearStorageActionFunc(logger, b.arguments.clearStorage, url),
@@ -765,6 +992,11 @@ func (b *chromiumBrowser) listen(requestCtx, taskCtx context.Context, taskCancel
listenForEventWebSocketCreated(taskCtx, logger, webSocketOptions)
// Workers load what they want out of reach of the listeners above. They
// start paused, see pauseWorkersActionFunc, and stay locked out of
// file:// URLs.
listenForWorkers(taskCtx, logger)
// See:
// https://github.com/gotenberg/gotenberg/issues/613.
// https://github.com/gotenberg/gotenberg/issues/1021.

View File

@@ -67,10 +67,63 @@ func TestChromiumBrowser_Start_removesProfileOnFailure(t *testing.T) {
}
}
// fakeChromiumBinary writes an executable shell script standing for Chromium.
func fakeChromiumBinary(t *testing.T, script string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "chromium")
err := os.WriteFile(path, []byte("#!/bin/sh\n"+script+"\n"), 0o700)
if err != nil {
t.Fatalf("write fake Chromium: %v", err)
}
return path
}
// --chromium-start-timeout bounds the DevTools handshake: a Chromium that
// never answers on its pipe fails the start in time, and is killed.
func TestChromiumBrowser_Start_timesOut(t *testing.T) {
b := newChromiumBrowser(browserArguments{
binPath: fakeChromiumBinary(t, "exec sleep 30"),
hyphenDataDirPath: t.TempDir(),
wsUrlReadTimeout: 500 * time.Millisecond,
}).(*chromiumBrowser)
start := time.Now()
err := b.Start(context.Background(), slog.New(slog.DiscardHandler))
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("expected a context.DeadlineExceeded error, got %v", err)
}
if !strings.Contains(err.Error(), "--chromium-start-timeout (CHROMIUM_START_TIMEOUT)") {
t.Fatalf("expected the error to name the flag and its environment variable, got %v", err)
}
if elapsed := time.Since(start); elapsed > 10*time.Second {
t.Fatalf("expected the start to end with its timeout, took %s", elapsed)
}
if b.isStarted.Load() {
t.Fatal("expected the browser to stay not started")
}
}
// A Chromium that exits before the handshake fails the start with its exit
// status.
func TestChromiumBrowser_Start_chromiumExits(t *testing.T) {
b := newChromiumBrowser(browserArguments{
binPath: fakeChromiumBinary(t, "exit 3"),
hyphenDataDirPath: t.TempDir(),
wsUrlReadTimeout: 10 * time.Second,
}).(*chromiumBrowser)
err := b.Start(context.Background(), slog.New(slog.DiscardHandler))
if err == nil || !strings.Contains(err.Error(), "Chromium exited (exit status 3)") {
t.Fatalf("expected an error with Chromium's exit status, got %v", err)
}
}
// TestChromiumDisableFeatures guards the override described in
// https://github.com/gotenberg/gotenberg/issues/1656. Gotenberg replaces
// chromedp's --disable-features value rather than extending it, as
// chromedp.Flag keys its flags by switch name. Dropping one of chromedp's own
// chromiumSwitches keys the switches by name. Dropping one of chromedp's own
// entries while editing this list would silently re-enable it.
func TestChromiumDisableFeatures(t *testing.T) {
for _, feature := range []string{

View File

@@ -0,0 +1,304 @@
package chromium
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"sync"
"time"
"github.com/chromedp/cdproto/target"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
// devToolsPipe is Gotenberg's end of Chromium's --remote-debugging-pipe.
// Chromium reads DevTools commands from its file descriptor 3 and writes
// responses and events to its file descriptor 4, each message a JSON text
// ended by a NUL byte. No port carries the protocol, so no page Chromium
// renders can reach it.
type devToolsPipe struct {
// commands is the write end of Chromium's file descriptor 3.
commands *os.File
// messages is the read end of Chromium's file descriptor 4.
messages *os.File
reader *bufio.Reader
closeOnce sync.Once
}
// newDevToolsPipe returns the pipe, and the files Chromium inherits as its
// file descriptors 3 and 4, in that order, for [exec.Cmd.ExtraFiles]. The
// caller closes these files once Chromium has started.
func newDevToolsPipe() (*devToolsPipe, []*os.File, error) {
chromiumCommands, commands, err := os.Pipe()
if err != nil {
return nil, nil, fmt.Errorf("create commands pipe: %w", err)
}
messages, chromiumMessages, err := os.Pipe()
if err != nil {
_ = chromiumCommands.Close()
_ = commands.Close()
return nil, nil, fmt.Errorf("create messages pipe: %w", err)
}
p := &devToolsPipe{
commands: commands,
messages: messages,
reader: bufio.NewReader(messages),
}
return p, []*os.File{chromiumCommands, chromiumMessages}, nil
}
// send writes one message to Chromium. It is not safe for concurrent use.
func (p *devToolsPipe) send(message []byte) error {
_, err := p.commands.Write(append(message, 0))
if err != nil {
return fmt.Errorf("write to Chromium: %w", err)
}
return nil
}
// receive reads the next message from Chromium, without its NUL byte. It is
// not safe for concurrent use.
func (p *devToolsPipe) receive() ([]byte, error) {
message, err := p.reader.ReadBytes(0)
if err != nil {
return nil, fmt.Errorf("read from Chromium: %w", err)
}
return message[:len(message)-1], nil
}
// close closes both ends Gotenberg holds. Chromium exits once it reads the
// end of its commands, and a pending receive returns.
func (p *devToolsPipe) close() {
p.closeOnce.Do(func() {
_ = p.commands.Close()
_ = p.messages.Close()
})
}
// initialPage turns target discovery on and returns the ID of the first page
// target Chromium reports: the about:blank tab it opens at start. The browser
// context attaches to that tab, rather than opening a second one, and target
// discovery stays on for the browser session, as chromedp's own exec
// allocator leaves it. It must run before the bridge relays the pipe.
func (p *devToolsPipe) initialPage() (target.ID, error) {
const id = 1
err := p.send([]byte(fmt.Sprintf(`{"id":%d,"method":"Target.setDiscoverTargets","params":{"discover":true}}`, id)))
if err != nil {
return "", err
}
var (
acknowledged bool
page target.ID
)
for !acknowledged || page == "" {
raw, err := p.receive()
if err != nil {
return "", err
}
var message struct {
ID int64 `json:"id"`
Method string `json:"method"`
Params struct {
TargetInfo struct {
TargetID target.ID `json:"targetId"`
Type string `json:"type"`
} `json:"targetInfo"`
} `json:"params"`
Error *struct {
Code int64 `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
err = json.Unmarshal(raw, &message)
if err != nil {
return "", fmt.Errorf("decode message from Chromium: %w", err)
}
switch {
case message.ID == id && message.Error != nil:
return "", fmt.Errorf("discover targets: %s (%d)", message.Error.Message, message.Error.Code)
case message.ID == id:
acknowledged = true
case message.Method == "Target.targetCreated" && message.Params.TargetInfo.Type == "page" && page == "":
page = message.Params.TargetInfo.TargetID
}
}
return page, nil
}
// devToolsBridge serves a [devToolsPipe] to chromedp, which only speaks
// WebSocket, as a single WebSocket connection. It listens on a loopback port
// under a path of 256 random bits, accepts the first client that asks for
// that path, and closes its listener right away: once chromedp is connected,
// nothing listens anymore, and no other client ever reaches Chromium.
type devToolsBridge struct {
pipe *devToolsPipe
listener net.Listener
path string
deadline time.Time
closeListener func()
}
// newDevToolsBridge starts listening for chromedp. The upgrade of each
// connection must complete before deadline. The caller calls closeListener
// once chromedp is connected or gave up.
func newDevToolsBridge(pipe *devToolsPipe, deadline time.Time) (*devToolsBridge, error) {
secret := make([]byte, 32)
_, err := rand.Read(secret)
if err != nil {
return nil, fmt.Errorf("generate DevTools path: %w", err)
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("listen for chromedp: %w", err)
}
b := &devToolsBridge{
pipe: pipe,
listener: listener,
path: "/devtools/browser/" + hex.EncodeToString(secret),
deadline: deadline,
}
b.closeListener = sync.OnceFunc(func() { _ = listener.Close() })
go b.serve()
return b, nil
}
// url returns the WebSocket URL chromedp dials.
func (b *devToolsBridge) url() string {
return "ws://" + b.listener.Addr().String() + b.path
}
// serve accepts connections until one upgrades on the bridge's path, then
// closes the listener and relays that connection until either side ends.
func (b *devToolsBridge) serve() {
upgrader := ws.Upgrader{
OnRequest: func(uri []byte) error {
if string(uri) != b.path {
return ws.RejectConnectionError(ws.RejectionStatus(http.StatusNotFound))
}
return nil
},
OnHeader: func(key, _ []byte) error {
// chromedp sends no Origin header; a browser always does.
if bytes.EqualFold(key, []byte("Origin")) {
return ws.RejectConnectionError(ws.RejectionStatus(http.StatusForbidden))
}
return nil
},
}
for {
conn, err := b.listener.Accept()
if err != nil {
return
}
_ = conn.SetDeadline(b.deadline)
_, err = upgrader.Upgrade(conn)
if err != nil {
_ = conn.Close()
continue
}
_ = conn.SetDeadline(time.Time{})
b.closeListener()
b.relay(conn)
return
}
}
// relay copies the WebSocket text frames of conn to the pipe, and the pipe's
// messages to conn as text frames, until either side ends. It then closes
// both, so that chromedp sees a lost connection once Chromium is gone, and
// Chromium exits once chromedp is gone.
func (b *devToolsBridge) relay(conn net.Conn) {
defer b.pipe.close()
defer func() { _ = conn.Close() }()
go func() {
// Closing the connection also ends the read loop below.
defer func() { _ = conn.Close() }()
w := bufio.NewWriter(conn)
for {
message, err := b.pipe.receive()
if err != nil {
return
}
// One frame per message: chromedp does not reassemble fragments.
err = wsutil.WriteServerText(w, message)
if err == nil {
err = w.Flush()
}
if err != nil {
return
}
}
}()
// chromedp marshals with invalid UTF-8 allowed, so the reader does not
// check it. Control frames get no answer: chromedp sends no ping, and a
// close frame ends the relay.
reader := &wsutil.Reader{
Source: bufio.NewReader(conn),
State: ws.StateServerSide,
}
var message bytes.Buffer
for {
header, err := reader.NextFrame()
if err != nil {
return
}
switch {
case header.OpCode == ws.OpClose:
return
case header.OpCode != ws.OpText:
err = reader.Discard()
if err != nil {
return
}
continue
}
message.Reset()
_, err = message.ReadFrom(reader)
if err != nil && !errors.Is(err, io.EOF) {
return
}
err = b.pipe.send(message.Bytes())
if err != nil {
return
}
}
}

View File

@@ -0,0 +1,483 @@
package chromium
import (
"bufio"
"bytes"
"context"
"errors"
"log/slog"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"github.com/shirou/gopsutil/v4/process"
)
// fakeChromium is the Chromium end of a [devToolsPipe].
type fakeChromium struct {
commands *bufio.Reader
messages *os.File
files []*os.File
}
func newFakeChromium(t *testing.T) (*devToolsPipe, *fakeChromium) {
t.Helper()
pipe, chromiumEnds, err := newDevToolsPipe()
if err != nil {
t.Fatalf("newDevToolsPipe: %v", err)
}
t.Cleanup(pipe.close)
t.Cleanup(func() { closeFiles(chromiumEnds...) })
return pipe, &fakeChromium{
commands: bufio.NewReader(chromiumEnds[0]),
messages: chromiumEnds[1],
files: chromiumEnds,
}
}
func (c *fakeChromium) readCommand(t *testing.T) []byte {
t.Helper()
command, err := c.commands.ReadBytes(0)
if err != nil {
t.Fatalf("read command: %v", err)
}
return command[:len(command)-1]
}
func (c *fakeChromium) writeMessage(t *testing.T, message []byte) {
t.Helper()
_, err := c.messages.Write(append(message, 0))
if err != nil {
t.Fatalf("write message: %v", err)
}
}
func newTestBridge(t *testing.T, pipe *devToolsPipe) *devToolsBridge {
t.Helper()
bridge, err := newDevToolsBridge(pipe, time.Now().Add(10*time.Second))
if err != nil {
t.Fatalf("newDevToolsBridge: %v", err)
}
t.Cleanup(bridge.closeListener)
return bridge
}
func dialBridge(t *testing.T, url string, header http.Header) (net.Conn, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
dialer := ws.Dialer{}
if header != nil {
dialer.Header = ws.HandshakeHeaderHTTP(header)
}
conn, _, _, err := dialer.Dial(ctx, url)
if err == nil {
t.Cleanup(func() { _ = conn.Close() })
}
return conn, err
}
// readServerText reads a text message as chromedp does: without checking
// UTF-8.
func readServerText(conn net.Conn) ([]byte, error) {
reader := &wsutil.Reader{Source: conn, State: ws.StateClientSide}
header, err := reader.NextFrame()
if err != nil {
return nil, err
}
if header.OpCode != ws.OpText {
return nil, errors.New("not a text frame")
}
var message bytes.Buffer
_, err = message.ReadFrom(reader)
return message.Bytes(), err
}
func TestDevToolsBridge_relaysMessages(t *testing.T) {
pipe, chromium := newFakeChromium(t)
bridge := newTestBridge(t, pipe)
conn, err := dialBridge(t, bridge.url(), nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
large := bytes.Repeat([]byte("x"), 8<<20)
for _, message := range [][]byte{
[]byte(`{"id":1,"method":"Browser.getVersion"}`),
// chromedp marshals with invalid UTF-8 allowed.
[]byte("{\"id\":2,\"params\":{\"value\":\"\xff\"}}"),
large,
} {
err = wsutil.WriteClientText(conn, message)
if err != nil {
t.Fatalf("write client text: %v", err)
}
got := chromium.readCommand(t)
if !bytes.Equal(got, message) {
t.Fatalf("expected Chromium to read %d bytes %.40q, got %d bytes %.40q", len(message), message, len(got), got)
}
chromium.writeMessage(t, message)
got, err = readServerText(conn)
if err != nil {
t.Fatalf("read server text: %v", err)
}
if !bytes.Equal(got, message) {
t.Fatalf("expected chromedp to read %d bytes %.40q, got %d bytes %.40q", len(message), message, len(got), got)
}
}
}
func TestDevToolsBridge_singleConnection(t *testing.T) {
pipe, _ := newFakeChromium(t)
bridge := newTestBridge(t, pipe)
// The path is the secret: any other one is refused, and the bridge keeps
// waiting for chromedp.
wrongPath := bridge.url()[:strings.LastIndex(bridge.url(), "/")+1] + "guess"
_, err := dialBridge(t, wrongPath, nil)
if !errors.As(err, new(ws.StatusError)) {
t.Fatalf("expected a wrong path to be refused, got %v", err)
}
// A browser always sends an Origin header; chromedp never does.
_, err = dialBridge(t, bridge.url(), http.Header{"Origin": []string{"file://"}})
if !errors.As(err, new(ws.StatusError)) {
t.Fatalf("expected a request with an Origin header to be refused, got %v", err)
}
_, err = dialBridge(t, bridge.url(), nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
// Once chromedp is connected, nothing listens anymore.
address := strings.TrimPrefix(bridge.url(), "ws://")
address = address[:strings.Index(address, "/")]
deadline := time.Now().Add(5 * time.Second)
for {
conn, err := net.DialTimeout("tcp", address, time.Second)
if err != nil {
break
}
_ = conn.Close()
if time.Now().After(deadline) {
t.Fatal("expected the bridge to stop listening once connected")
}
time.Sleep(10 * time.Millisecond)
}
_, err = dialBridge(t, bridge.url(), nil)
if err == nil {
t.Fatal("expected a second connection to fail")
}
}
func TestDevToolsBridge_closeListenerBeforeConnection(t *testing.T) {
pipe, _ := newFakeChromium(t)
bridge := newTestBridge(t, pipe)
bridge.closeListener()
_, err := dialBridge(t, bridge.url(), nil)
if err == nil {
t.Fatal("expected no connection once the listener is closed")
}
}
func TestDevToolsBridge_endsWithChromium(t *testing.T) {
pipe, chromium := newFakeChromium(t)
bridge := newTestBridge(t, pipe)
conn, err := dialBridge(t, bridge.url(), nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
// Chromium exits: its end of the messages pipe closes.
closeFiles(chromium.files...)
_ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
_, err = readServerText(conn)
if err == nil {
t.Fatal("expected chromedp to lose the connection")
}
var netErr net.Error
if errors.As(err, &netErr) && netErr.Timeout() {
t.Fatalf("expected the connection to close, got %v", err)
}
}
func TestDevToolsBridge_endsWithChromedp(t *testing.T) {
pipe, chromium := newFakeChromium(t)
bridge := newTestBridge(t, pipe)
conn, err := dialBridge(t, bridge.url(), nil)
if err != nil {
t.Fatalf("dial: %v", err)
}
_ = conn.Close()
// Chromium reads the end of its commands, and exits.
_, err = chromium.commands.ReadBytes(0)
if err == nil {
t.Fatal("expected the commands pipe to close")
}
}
func TestDevToolsPipe_initialPage(t *testing.T) {
for _, tc := range []struct {
scenario string
messages []string
expectID string
expectErr bool
}{
{
scenario: "page reported before the response",
messages: []string{
`{"method":"Target.targetCreated","params":{"targetInfo":{"targetId":"UI","type":"browser_ui"}}}`,
`{"method":"Target.targetCreated","params":{"targetInfo":{"targetId":"PAGE","type":"page"}}}`,
`{"method":"Target.targetCreated","params":{"targetInfo":{"targetId":"OTHER","type":"page"}}}`,
`{"id":1,"result":{}}`,
},
expectID: "PAGE",
},
{
scenario: "page reported after the response",
messages: []string{
`{"id":1,"result":{}}`,
`{"method":"Target.targetCreated","params":{"targetInfo":{"targetId":"PAGE","type":"page"}}}`,
},
expectID: "PAGE",
},
{
scenario: "error response",
messages: []string{`{"id":1,"error":{"code":-32601,"message":"not found"}}`},
expectErr: true,
},
} {
t.Run(tc.scenario, func(t *testing.T) {
pipe, chromium := newFakeChromium(t)
type result struct {
id string
err error
}
done := make(chan result, 1)
go func() {
id, err := pipe.initialPage()
done <- result{string(id), err}
}()
command := chromium.readCommand(t)
if !bytes.Contains(command, []byte(`"Target.setDiscoverTargets"`)) {
t.Fatalf("expected Target.setDiscoverTargets, got %s", command)
}
for _, message := range tc.messages {
chromium.writeMessage(t, []byte(message))
}
got := <-done
if tc.expectErr {
if got.err == nil {
t.Fatal("expected an error, got nil")
}
return
}
if got.err != nil {
t.Fatalf("initialPage: %v", got.err)
}
if got.id != tc.expectID {
t.Fatalf("expected page %q, got %q", tc.expectID, got.id)
}
})
}
}
func TestDevToolsPipe_initialPageEndsWithChromium(t *testing.T) {
pipe, chromium := newFakeChromium(t)
done := make(chan error, 1)
go func() {
_, err := pipe.initialPage()
done <- err
}()
chromium.readCommand(t)
closeFiles(chromium.files...)
if err := <-done; err == nil {
t.Fatal("expected an error once Chromium is gone")
}
}
// TestChromiumSwitches pins the DevTools transport: a pipe, never a port.
func TestChromiumSwitches(t *testing.T) {
args := chromiumSwitches(browserArguments{}, "/tmp/profile", "http://127.0.0.1:1234")
for _, expect := range []string{"--remote-debugging-pipe", "--headless", "--no-sandbox", "--user-data-dir=/tmp/profile", "--proxy-server=http://127.0.0.1:1234", "--disable-features=" + chromiumDisableFeatures} {
if !strings.Contains(strings.Join(args, " "), expect) {
t.Errorf("expected %q in %v", expect, args)
}
}
for _, arg := range args {
if strings.HasPrefix(arg, "--remote-debugging-port") || strings.HasPrefix(arg, "--disable-component-update") {
t.Errorf("unexpected %q", arg)
}
}
if args[len(args)-1] != "about:blank" {
t.Errorf("expected about:blank last, got %q", args[len(args)-1])
}
}
// startLiveBrowser starts the Chromium or Chrome binary CHROMIUM_BIN_PATH
// names, or skips the test when the variable is unset.
func startLiveBrowser(t *testing.T, arguments browserArguments) *chromiumBrowser {
t.Helper()
binPath := os.Getenv("CHROMIUM_BIN_PATH")
if binPath == "" {
t.Skip("CHROMIUM_BIN_PATH is not set")
}
arguments.binPath = binPath
arguments.hyphenDataDirPath = t.TempDir()
arguments.wsUrlReadTimeout = 30 * time.Second
b := newChromiumBrowser(arguments).(*chromiumBrowser)
logger := slog.New(slog.DiscardHandler)
err := b.Start(context.Background(), logger)
if err != nil {
t.Fatalf("Start: %v", err)
}
t.Cleanup(func() {
err := b.Stop(logger)
if err != nil {
t.Errorf("Stop: %v", err)
}
})
return b
}
// TestChromiumBrowser_live_devToolsPipe starts a real Chromium and checks
// that no DevTools endpoint exists while it converts.
func TestChromiumBrowser_live_devToolsPipe(t *testing.T) {
b := startLiveBrowser(t, browserArguments{})
logger := slog.New(slog.DiscardHandler)
if !b.Healthy(logger) {
t.Fatal("expected a healthy browser")
}
if b.pid == 0 {
t.Fatal("expected the browser's pid")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
outputPath := filepath.Join(t.TempDir(), "out.png")
err := b.screenshot(ctx, logger, "data:text/html,<h1>pipe</h1>", outputPath, DefaultScreenshotOptions(), newNetworkAggregate())
if err != nil {
t.Fatalf("screenshot: %v", err)
}
info, err := os.Stat(outputPath)
if err != nil || info.Size() == 0 {
t.Fatalf("expected a screenshot, got %v", err)
}
_, err = os.Stat(filepath.Join(b.userProfileDirPath, "DevToolsActivePort"))
if !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected no DevToolsActivePort file, got %v", err)
}
p, err := process.NewProcess(int32(b.pid))
if err != nil {
t.Fatalf("find Chromium: %v", err)
}
processes := []*process.Process{p}
children, _ := p.Children()
processes = append(processes, children...)
for _, p := range processes {
connections, err := p.Connections()
if err != nil {
t.Logf("list connections of %d: %v", p.Pid, err)
continue
}
for _, c := range connections {
if c.Status == "LISTEN" {
t.Errorf("expected no listening socket, process %d listens on %s:%d", p.Pid, c.Laddr.IP, c.Laddr.Port)
}
}
}
pid := b.pid
err = b.Stop(logger)
if err != nil {
t.Fatalf("Stop: %v", err)
}
if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) {
t.Fatalf("expected Chromium to be gone after Stop, got %v", err)
}
}
// A Chromium that dies, of the memory watch or of a crash, loses chromedp's
// connection: the browser turns unhealthy, and restarts.
func TestChromiumBrowser_live_restartAfterExit(t *testing.T) {
b := startLiveBrowser(t, browserArguments{})
logger := slog.New(slog.DiscardHandler)
err := syscall.Kill(b.pid, syscall.SIGKILL)
if err != nil {
t.Fatalf("kill Chromium: %v", err)
}
deadline := time.Now().Add(10 * time.Second)
for b.ctx.Err() == nil {
if time.Now().After(deadline) {
t.Fatal("expected the browser context to end once Chromium is gone")
}
time.Sleep(10 * time.Millisecond)
}
if b.Healthy(logger) {
t.Fatal("expected an unhealthy browser once Chromium is gone")
}
err = b.Stop(logger)
if err != nil {
t.Fatalf("Stop: %v", err)
}
err = b.Start(context.Background(), logger)
if err != nil {
t.Fatalf("Start after exit: %v", err)
}
if !b.Healthy(logger) {
t.Fatal("expected a healthy browser after the restart")
}
}

View File

@@ -0,0 +1,22 @@
//go:build linux
package chromium
import (
"os"
"os/exec"
"syscall"
)
// setParentDeathSignal makes the kernel kill Chromium when Gotenberg dies, as
// chromedp's exec allocator does. AWS Lambda does not support it.
func setParentDeathSignal(cmd *exec.Cmd) {
if _, ok := os.LookupEnv("LAMBDA_TASK_ROOT"); ok {
return
}
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = new(syscall.SysProcAttr)
}
cmd.SysProcAttr.Pdeathsig = syscall.SIGKILL
}

View File

@@ -0,0 +1,8 @@
//go:build !linux
package chromium
import "os/exec"
// setParentDeathSignal does nothing: only Linux has a parent death signal.
func setParentDeathSignal(_ *exec.Cmd) {}

View File

@@ -0,0 +1,136 @@
package chromium
import (
"context"
"fmt"
"log/slog"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
)
// Web workers are targets of their own. No fetch.EventRequestPaused listener
// sees what they load, and the Fetch domain does not exist on them, so with
// --chromium-allow-file-access-from-files (CHROMIUM_ALLOW_FILE_ACCESS_FROM_FILES)
// a worker could read any file:// URL, out of reach of the per-request
// file:// prefixes. Gotenberg starts every worker paused, blocks file:// URLs
// on it, and only then lets it run. A worker never needs a file:// URL: one
// that a file:// page starts without that flag cannot read file:// URLs
// anyway, nor can one that a network page starts. So the lock applies
// whatever the flags.
// dedicatedWorkers selects the targets a page or a worker starts that run
// scripts out of reach of the page's Fetch domain: dedicated workers. Other
// child targets, such as out-of-process iframes, are not auto-attached, as
// they would wait for a debugger that never resumes them.
var dedicatedWorkers = target.Filter{{Type: "worker"}, {Exclude: true}}
// browserWorkers selects the workers no page owns: shared and service
// workers. The browser session auto-attaches them.
var browserWorkers = target.Filter{{Type: "shared_worker"}, {Type: "service_worker"}, {Exclude: true}}
// pauseWorkersOnStart makes the dedicated workers of the target ctx runs
// against start paused, so that [lockWorker] locks each before it runs. It
// replaces chromedp's auto-attach of the target, which lets them run at once.
func pauseWorkersOnStart() chromedp.Action {
return target.SetAutoAttach(true, true).WithFlatten(true).WithFilter(dedicatedWorkers)
}
// pauseWorkersActionFunc runs [pauseWorkersOnStart] on the page, before it
// navigates.
func pauseWorkersActionFunc(logger *slog.Logger) chromedp.ActionFunc {
return func(ctx context.Context) error {
logger.DebugContext(ctx, "start workers paused")
err := pauseWorkersOnStart().Do(ctx)
if err != nil {
return fmt.Errorf("start workers paused: %w", err)
}
return nil
}
}
// lockBrowserWorkers makes Chromium start shared and service workers paused,
// and locks each with [lockWorker] for as long as browserCtx lives. ctx
// bounds the command.
func lockBrowserWorkers(ctx, browserCtx context.Context, logger *slog.Logger) error {
c := chromedp.FromContext(browserCtx)
if c == nil || c.Browser == nil {
return fmt.Errorf("lock workers: %w", chromedp.ErrInvalidContext)
}
chromedp.ListenBrowser(browserCtx, func(ev any) {
if e, ok := ev.(*target.EventAttachedToTarget); ok && isPausedWorker(e) {
go lockWorker(browserCtx, logger, e.TargetInfo)
}
})
err := target.SetAutoAttach(true, true).WithFlatten(true).WithFilter(browserWorkers).Do(cdp.WithExecutor(ctx, c.Browser))
if err != nil {
return fmt.Errorf("start shared and service workers paused: %w", err)
}
return nil
}
// listenForWorkers locks with [lockWorker] every worker the target of ctx
// starts paused, see [pauseWorkersOnStart].
func listenForWorkers(ctx context.Context, logger *slog.Logger) {
chromedp.ListenTarget(ctx, func(ev any) {
if e, ok := ev.(*target.EventAttachedToTarget); ok && isPausedWorker(e) {
go lockWorker(ctx, logger, e.TargetInfo)
}
})
}
// isPausedWorker reports whether ev attaches a worker that waits for a
// debugger. A target Gotenberg attaches to itself never waits, so locking a
// worker does not lock it again.
func isPausedWorker(ev *target.EventAttachedToTarget) bool {
if !ev.WaitingForDebugger || ev.TargetInfo == nil {
return false
}
switch ev.TargetInfo.Type {
case "worker", "shared_worker", "service_worker":
return true
default:
return false
}
}
// lockWorker blocks file:// URLs on the paused worker info names, makes its
// own dedicated workers start paused, and then lets it run. The worker's
// context derives from parent, and ends with the worker or with parent. If a
// step fails, the worker stays paused: it never runs unlocked.
func lockWorker(parent context.Context, logger *slog.Logger, info *target.Info) {
workerCtx, cancel := chromedp.NewContext(parent, chromedp.WithTargetID(info.TargetID))
chromedp.ListenBrowser(workerCtx, func(ev any) {
if e, ok := ev.(*target.EventTargetDestroyed); ok && e.TargetID == info.TargetID {
// Not inline: cancel waits for commands this listener would block.
go cancel()
}
})
listenForWorkers(workerCtx, logger)
err := chromedp.Run(workerCtx,
network.SetBlockedURLs([]string{"file://*"}),
pauseWorkersOnStart(),
runtime.RunIfWaitingForDebugger(),
)
if err != nil {
if parent.Err() == nil {
logger.ErrorContext(parent, fmt.Sprintf("lock %s '%s', it stays paused: %s", info.Type, gotenberg.RedactURL(info.URL), err))
}
return
}
logger.DebugContext(parent, fmt.Sprintf("%s '%s' locked out of file:// URLs", info.Type, gotenberg.RedactURL(info.URL)))
}

View File

@@ -0,0 +1,146 @@
package chromium
import (
"context"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
)
func TestIsPausedWorker(t *testing.T) {
for _, tc := range []struct {
targetType string
waiting bool
expect bool
}{
{targetType: "worker", waiting: true, expect: true},
{targetType: "shared_worker", waiting: true, expect: true},
{targetType: "service_worker", waiting: true, expect: true},
// chromedp's own attach to a worker never waits: locking it again
// would loop.
{targetType: "worker", waiting: false, expect: false},
{targetType: "iframe", waiting: true, expect: false},
{targetType: "page", waiting: true, expect: false},
} {
t.Run(tc.targetType, func(t *testing.T) {
ev := &target.EventAttachedToTarget{
TargetInfo: &target.Info{Type: tc.targetType},
WaitingForDebugger: tc.waiting,
}
if got := isPausedWorker(ev); got != tc.expect {
t.Fatalf("isPausedWorker(%s, waiting %t) = %t, want %t", tc.targetType, tc.waiting, got, tc.expect)
}
})
}
if isPausedWorker(&target.EventAttachedToTarget{WaitingForDebugger: true}) {
t.Fatal("expected an event without target info not to be a paused worker")
}
}
// workersPage reads a file:// marker outside the page's directory from a
// dedicated, a nested, a shared and a file:// worker, reads a file of its own
// directory, and embeds a cross-site iframe. It writes what each read in its
// title.
const workersPage = `<html><body><script>
var target = location.href.replace('req/index.html', 'other/marker.txt');
var rd = "function rd(){var x=new XMLHttpRequest();try{x.open('GET','" + target + "',false);x.send();return 'READ:'+x.responseText}catch(e){return 'BLOCKED'}}";
var results = [];
var want = 6;
function done(s){results.push(s);if(results.length==want)document.title=results.join(' | ');}
onmessage = function(e){done(e.data)};
var dedicated = new Worker(URL.createObjectURL(new Blob([rd + ";postMessage('DEDICATED:'+rd())"])));
dedicated.onmessage = function(e){done(e.data)};
var inner = rd + ";postMessage('NESTED:'+rd())";
var outer = new Worker(URL.createObjectURL(new Blob([rd + ";var w=new Worker(URL.createObjectURL(new Blob([" + JSON.stringify(inner) + "])));w.onmessage=function(e){postMessage(e.data)}"])));
outer.onmessage = function(e){done(e.data)};
var shared = new SharedWorker(URL.createObjectURL(new Blob([rd + ";onconnect=function(e){e.ports[0].postMessage('SHARED:'+rd())}"])));
shared.port.onmessage = function(e){done(e.data)};
var file = new Worker('worker.js');
file.onmessage = function(e){done(e.data)};
var x = new XMLHttpRequest();
try{x.open('GET','own.txt',false);x.send();done('OWN:'+x.responseText.trim())}catch(e){done('OWN:BLOCKED')}
setTimeout(function(){for(var i=0;i<want;i++)done('TIMEOUT')},10000);
</script><iframe src="FRAME_URL"></iframe></body></html>`
// workersScript is a worker Chromium loads from a file:// URL.
const workersScript = `var x=new XMLHttpRequest();
try{x.open('GET',location.href.replace('req/worker.js','other/marker.txt'),false);x.send();postMessage('FILE:READ:'+x.responseText)}catch(e){postMessage('FILE:BLOCKED')}`
// TestChromiumBrowser_live_workersLockedOutOfFiles converts, with
// --chromium-allow-file-access-from-files, a page whose workers try to read a
// file outside the page's directory.
func TestChromiumBrowser_live_workersLockedOutOfFiles(t *testing.T) {
for _, sharedBrowserContext := range []bool{false, true} {
t.Run(fmt.Sprintf("shared browser context %t", sharedBrowserContext), func(t *testing.T) {
b := startLiveBrowser(t, browserArguments{allowFileAccessFromFiles: true, sharedBrowserContext: sharedBrowserContext})
logger := slog.New(slog.DiscardHandler)
frame := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`<script>parent.postMessage('FRAME','*')</script>`))
}))
defer frame.Close()
root, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatalf("resolve temporary directory: %v", err)
}
for name, content := range map[string]string{
"req/index.html": strings.Replace(workersPage, "FRAME_URL", frame.URL, 1),
"req/worker.js": workersScript,
"req/own.txt": "OWN-OK",
"other/marker.txt": "MARKER",
} {
path := filepath.Join(root, name)
err = os.MkdirAll(filepath.Dir(path), 0o755)
if err == nil {
err = os.WriteFile(path, []byte(content), 0o600)
}
if err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
options := DefaultOptions()
options.AllowedFilePrefixes = []string{filepath.Join(root, "req")}
var title string
err = b.do(ctx, logger, "file://"+filepath.Join(root, "req", "index.html"), options, newNetworkAggregate(), chromedp.Tasks{
network.Enable(),
fetch.Enable(),
runtime.Enable(),
pauseWorkersActionFunc(logger),
chromedp.Navigate("file://" + filepath.Join(root, "req", "index.html")),
chromedp.Poll("document.title.length > 0", nil),
chromedp.Title(&title),
})
if err != nil {
t.Fatalf("do: %v", err)
}
if strings.Contains(title, "MARKER") || strings.Contains(title, "TIMEOUT") {
t.Fatalf("expected no worker to read the marker, got %q", title)
}
for _, expect := range []string{"DEDICATED:BLOCKED", "NESTED:BLOCKED", "SHARED:BLOCKED", "FILE:BLOCKED", "OWN:OWN-OK", "FRAME"} {
if !strings.Contains(title, expect) {
t.Errorf("expected %q in %q", expect, title)
}
}
})
}
}

View File

@@ -621,6 +621,74 @@ Feature: /forms/chromium/convert/html
Then the response status code should be 400
Then the helper server should NOT have received a canary request
# Gotenberg drives Chromium over --remote-debugging-pipe: Chromium opens no
# DevTools port a page could reach.
Scenario: POST /forms/chromium/convert/html (DevTools over a pipe, without a port)
Given I have a Gotenberg container with the following environment variable(s):
| LOG_LEVEL | debug |
When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/html" endpoint with the following form data and header(s):
| files | testdata/page-1-html/index.html | file |
Then the response status code should be 200
Then the Gotenberg container should log the following entries:
| --remote-debugging-pipe |
Then the Gotenberg container should NOT log the following entries:
| --remote-debugging-port |
| DevTools listening on |
# Workers are targets of their own, out of reach of the per-request file://
# prefixes. With file access from files allowed, they stay locked out of
# file:// URLs, while the page still reads the files of its own request.
Scenario: POST /forms/chromium/convert/html (Workers cannot read files with file access from files allowed)
Given I have a Gotenberg container with the following environment variable(s):
| CHROMIUM_ALLOW_FILE_ACCESS_FROM_FILES | true |
When I make a "POST" request to Gotenberg at the "/forms/chromium/convert/html" endpoint with the following form data and header(s):
| files | testdata/file-access-worker-html/index.html | file |
| files | testdata/file-access-worker-html/own.txt | file |
| waitForExpression | window.done === true | field |
| Gotenberg-Output-Filename | foo | header |
Then the response status code should be 200
Then the response header "Content-Type" should be "application/pdf"
Then the "foo.pdf" PDF should have the following content at page 1:
"""
page own file loaded
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
dedicated parent BLOCKED
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
dedicated passwd BLOCKED
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
nested parent BLOCKED
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
nested passwd BLOCKED
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
shared parent BLOCKED
"""
Then the "foo.pdf" PDF should have the following content at page 1:
"""
shared passwd BLOCKED
"""
Then the "foo.pdf" PDF should NOT have the following content at page 1:
"""
READ
"""
Then the "foo.pdf" PDF should NOT have the following content at page 1:
"""
root:x:0:0
"""
Then the "foo.pdf" PDF should NOT have the following content at page 1:
"""
TIMEOUT
"""
# Control for the WebSocket scenario below. An ordinary fetch to a loopback
# address is surfaced as a Fetch.requestPaused event, so it is blocked by
# CHROMIUM_DENY_PRIVATE_IPS and the block is logged. The allow-list is

View File

@@ -0,0 +1,90 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Worker file access</title>
</head>
<body>
<h1>Worker file access</h1>
<div id="results"></div>
<script type="application/javascript">
// Every worker tries to read files outside the request's directory: its
// parent, which lists the directories of the other requests, and
// /etc/passwd. Each writes READ or BLOCKED. The page itself reads a file
// of its own directory.
const parent = new URL("../", location.href).href;
const read =
"function read(url) {" +
" const xhr = new XMLHttpRequest();" +
" try { xhr.open('GET', url, false); xhr.send(); return 'READ ' + xhr.responseText.slice(0, 40); }" +
" catch (e) { return 'BLOCKED'; }" +
"}" +
"function readAll(name) {" +
" return [name + ' parent ' + read(" +
JSON.stringify(parent) +
"), name + ' passwd ' + read('file:///etc/passwd')];" +
"}";
const expected = 7;
let count = 0;
function report(lines) {
for (const line of lines) {
const p = document.createElement("p");
p.textContent = line;
document.getElementById("results").appendChild(p);
count++;
}
if (count >= expected) {
window.done = true;
}
}
const worker = (source) =>
new Worker(
URL.createObjectURL(
new Blob([source], { type: "application/javascript" }),
),
);
worker(read + "postMessage(readAll('dedicated'));").onmessage = (e) =>
report(e.data);
const nested = read + "postMessage(readAll('nested'));";
worker(
"const inner = new Worker(URL.createObjectURL(new Blob([" +
JSON.stringify(nested) +
"])));" +
"inner.onmessage = (e) => postMessage(e.data);",
).onmessage = (e) => report(e.data);
const shared = new SharedWorker(
URL.createObjectURL(
new Blob(
[
read +
"onconnect = (e) => e.ports[0].postMessage(readAll('shared'));",
],
{ type: "application/javascript" },
),
),
);
shared.port.onmessage = (e) => report(e.data);
const own = new XMLHttpRequest();
try {
own.open("GET", "own.txt", false);
own.send();
report(["page " + own.responseText.trim()]);
} catch (e) {
report(["page own file BLOCKED"]);
}
setTimeout(() => {
if (!window.done) {
report(["TIMEOUT"]);
window.done = true;
}
}, 10000);
</script>
</body>
</html>

View File

@@ -0,0 +1 @@
own file loaded