mirror of
https://github.com/gotenberg/gotenberg.git
synced 2026-12-06 16:22:15 +00:00
209 lines
7.4 KiB
Go
209 lines
7.4 KiB
Go
package scenario
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/moby/moby/api/types/container"
|
|
"github.com/moby/moby/client"
|
|
"github.com/testcontainers/testcontainers-go"
|
|
"github.com/testcontainers/testcontainers-go/wait"
|
|
)
|
|
|
|
// testcontainersLabel is the label testcontainers-go stamps on every
|
|
// container and network it creates. Pruning on this label only ever touches
|
|
// resources owned by the test suite.
|
|
const testcontainersLabel = "org.testcontainers"
|
|
|
|
// PruneOrphanedNetworks removes dangling networks created by the test suite.
|
|
// Scenarios no longer create one: the Gotenberg container is reached over its
|
|
// mapped port and the host-side helper over host.docker.internal, so the
|
|
// default bridge suffices. This stays as cheap insurance against networks
|
|
// leaked by an older suite version or an interrupted run, which consume
|
|
// Docker's predefined address pools until none remain and every later
|
|
// scenario fails with "all predefined address pools have been fully
|
|
// subnetted".
|
|
//
|
|
// Only unused networks bearing the testcontainers label are removed, so
|
|
// running containers and operator networks are never affected.
|
|
func PruneOrphanedNetworks(ctx context.Context) (int, error) {
|
|
cli, err := client.New(client.FromEnv)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("create Docker client: %w", err)
|
|
}
|
|
defer cli.Close()
|
|
|
|
filters := client.Filters{}.Add("label", testcontainersLabel+"=true")
|
|
|
|
report, err := cli.NetworkPrune(ctx, client.NetworkPruneOptions{Filters: filters})
|
|
if err != nil {
|
|
return 0, fmt.Errorf("prune networks: %w", err)
|
|
}
|
|
|
|
return len(report.Report.NetworksDeleted), nil
|
|
}
|
|
|
|
var (
|
|
// GotenbergDockerRepository is the repository of the image, such as
|
|
// "gotenberg/gotenberg".
|
|
GotenbergDockerRepository string
|
|
// GotenbergVersion is the version the image reports, such as in the
|
|
// Gotenberg-Version header.
|
|
GotenbergVersion string
|
|
// GotenbergVariant selects a variant image, such as "chromium", tagged
|
|
// <version>-<variant>. Empty selects the full image, tagged <version>.
|
|
GotenbergVariant string
|
|
// GotenbergContainerPlatform is the platform of the image, such as
|
|
// "linux/amd64".
|
|
GotenbergContainerPlatform string
|
|
)
|
|
|
|
// gotenbergImage returns the image the containers run.
|
|
func gotenbergImage() string {
|
|
tag := GotenbergVersion
|
|
if GotenbergVariant != "" {
|
|
tag += "-" + GotenbergVariant
|
|
}
|
|
|
|
return fmt.Sprintf("gotenberg/%s:%s", GotenbergDockerRepository, tag)
|
|
}
|
|
|
|
type noopLogger struct{}
|
|
|
|
func (n *noopLogger) Printf(format string, v ...any) {
|
|
// NOOP
|
|
}
|
|
|
|
// integrationAllowList is the default allow-list pattern injected into
|
|
// every Gotenberg container started by the integration tests. The outbound
|
|
// URL guard introduced for SSRF protection rejects URLs whose host
|
|
// resolves to a non-public IP, which would block:
|
|
//
|
|
// - host.docker.internal (Docker host gateway, RFC1918)
|
|
// - The static helper server running inside the test network
|
|
// - file:// URIs created in /tmp by the API context
|
|
//
|
|
// Setting the allow-list to a permissive pattern flips the URL guard into
|
|
// "allow-list match bypasses the IP check" mode for every URL the tests
|
|
// touch. Operator-supplied deny-lists still apply, so deny-list scenarios
|
|
// keep working. Test scenarios that exercise allow-list semantics
|
|
// explicitly override this default in their environment table.
|
|
//
|
|
// Production operators wanting a similar bypass for trusted internal
|
|
// destinations should set their own --*-allow-list with a tighter regex
|
|
// (for example ^https?://internal\.svc(:|/|$)).
|
|
const integrationAllowList = `.+`
|
|
|
|
// applyDefaultEnv merges baseline environment variables that the
|
|
// integration tests rely on into env, without overwriting values supplied
|
|
// by the test scenario itself. Tests can clear a default by setting it to
|
|
// the empty string in their scenario table.
|
|
func applyDefaultEnv(env map[string]string) map[string]string {
|
|
if env == nil {
|
|
env = make(map[string]string)
|
|
}
|
|
defaults := map[string]string{
|
|
"CHROMIUM_ALLOW_LIST": integrationAllowList,
|
|
"API_DOWNLOAD_FROM_ALLOW_LIST": integrationAllowList,
|
|
"WEBHOOK_ALLOW_LIST": integrationAllowList,
|
|
}
|
|
for k, v := range defaults {
|
|
if _, ok := env[k]; !ok {
|
|
env[k] = v
|
|
}
|
|
}
|
|
return env
|
|
}
|
|
|
|
// startGotenbergContainer starts a Gotenberg container on Docker's default
|
|
// bridge. No dedicated network is created: the suite addresses the container
|
|
// through container.Host plus its mapped port, and the container reaches the
|
|
// host-side webhook and static file server through the host.docker.internal
|
|
// alias below, so a per-scenario network would carry no traffic while still
|
|
// consuming one of Docker's predefined subnets.
|
|
func startGotenbergContainer(ctx context.Context, env map[string]string) (testcontainers.Container, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
|
defer cancel()
|
|
|
|
env = applyDefaultEnv(env)
|
|
|
|
healthPath := "/health"
|
|
if env["API_ROOT_PATH"] != "" {
|
|
healthPath = fmt.Sprintf("%shealth", env["API_ROOT_PATH"])
|
|
}
|
|
|
|
req := testcontainers.ContainerRequest{
|
|
Image: gotenbergImage(),
|
|
ImagePlatform: GotenbergContainerPlatform,
|
|
ExposedPorts: []string{"3000/tcp"},
|
|
HostConfigModifier: func(hostConfig *container.HostConfig) {
|
|
hostConfig.ExtraHosts = []string{"host.docker.internal:host-gateway"}
|
|
// Docker 29.4 and later deny socketcall on i386 in their default
|
|
// seccomp profile, to block the AF_ALG sockets of CVE-2026-31431, and
|
|
// Go's linux/386 port opens every socket through it: Gotenberg would
|
|
// fail to listen. Users of the 386 image need the same option.
|
|
// See https://github.com/moby/moby/pull/52494.
|
|
if GotenbergContainerPlatform == "linux/386" {
|
|
hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, "seccomp=unconfined")
|
|
}
|
|
},
|
|
WaitingFor: wait.ForHTTP(healthPath),
|
|
Env: env,
|
|
}
|
|
|
|
c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
|
ContainerRequest: req,
|
|
Started: true,
|
|
Logger: &noopLogger{},
|
|
})
|
|
if err != nil {
|
|
err = fmt.Errorf("start new Gotenberg container: %w", err)
|
|
|
|
// A failed start (for example the process exiting before the health
|
|
// check passes) only reports an opaque exit code. testcontainers
|
|
// still returns the container on this path, so attach its logs to
|
|
// surface the actual crash reason in CI.
|
|
if c != nil {
|
|
if logs, errLogs := containerLogEntries(ctx, c); errLogs == nil && logs != "" {
|
|
err = fmt.Errorf("%w\ncontainer logs:\n%s", err, logs)
|
|
}
|
|
if errTerminate := c.Terminate(ctx, testcontainers.StopTimeout(0)); errTerminate != nil {
|
|
err = fmt.Errorf("%w (also failed to terminate container: %v)", err, errTerminate)
|
|
}
|
|
}
|
|
|
|
return nil, err
|
|
}
|
|
|
|
return c, nil
|
|
}
|
|
|
|
func containerHttpEndpoint(ctx context.Context, container testcontainers.Container, port string) (string, error) {
|
|
ip, err := container.Host(ctx)
|
|
if err != nil {
|
|
return "", fmt.Errorf("get container IP: %w", err)
|
|
}
|
|
mapped, err := container.MappedPort(ctx, port)
|
|
if err != nil {
|
|
return "", fmt.Errorf("get container port: %w", err)
|
|
}
|
|
return fmt.Sprintf("http://%s:%s", ip, mapped.Port()), nil
|
|
}
|
|
|
|
func containerLogEntries(ctx context.Context, container testcontainers.Container) (string, error) {
|
|
logReader, err := container.Logs(ctx)
|
|
if err != nil {
|
|
return "", fmt.Errorf("get container log entries: %w", err)
|
|
}
|
|
defer logReader.Close()
|
|
|
|
logsBytes, err := io.ReadAll(logReader)
|
|
if err != nil {
|
|
return "", fmt.Errorf("read container log entries: %w", err)
|
|
}
|
|
|
|
return string(logsBytes), nil
|
|
}
|