carlos / platform Public

infra: pdf-host module, a fenced Gotenberg box

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a1d7d4976f28050bf3f0039f87c82cee3ee97fd6 parent a1747fd
6 files changed, +526 −0
  • infra/modules/pdf-host/main.tf +127 −0
  • infra/modules/pdf-host/outputs.tf +11 −0
  • infra/modules/pdf-host/pdf-init.sh.tftpl +143 −0
  • infra/modules/pdf-host/tests/pdf_host.tftest.hcl +188 −0
  • infra/modules/pdf-host/variables.tf +48 −0
  • infra/modules/pdf-host/versions.tf +9 −0

CI failed — run details

diff --git a/infra/modules/pdf-host/main.tf b/infra/modules/pdf-host/main.tf
new file mode 100644
index 000000000..d11191bfb
--- /dev/null
+++ b/infra/modules/pdf-host/main.tf
@@ -0,0 +1,127 @@
+data "aws_security_group" "client" {
+ id = var.client_security_group_id
+}
+
+data "aws_vpc" "client" {
+ id = data.aws_security_group.client.vpc_id
+}
+
+locals {
+ init_script = templatefile("${path.module}/pdf-init.sh.tftpl", {
+ region = var.region
+ gotenberg_image = var.gotenberg_image
+ api_timeout = var.api_timeout
+ })
+}
+
+resource "aws_security_group" "pdf" {
+ name = var.name
+ description = "pdf-host"
+ vpc_id = data.aws_security_group.client.vpc_id
+
+ # Only the console connects. Container egress is fenced in pdf-init.sh.tftpl.
+ ingress {
+ from_port = 3000
+ to_port = 3000
+ protocol = "tcp"
+ security_groups = [var.client_security_group_id]
+ }
+
+ # Packages, the image and public assets. Administration uses Session Manager.
+ egress {
+ from_port = 0
+ to_port = 0
+ protocol = "-1"
+ cidr_blocks = ["0.0.0.0/0"]
+ }
+
+ tags = { Name = var.name }
+}
+
+resource "aws_iam_role" "pdf" {
+ name = var.name
+ assume_role_policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Effect = "Allow"
+ Principal = { Service = "ec2.amazonaws.com" }
+ Action = "sts:AssumeRole"
+ }]
+ })
+}
+
+resource "aws_iam_role_policy_attachment" "pdf_ssm" {
+ role = aws_iam_role.pdf.name
+ policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
+}
+
+# AmazonSSMManagedInstanceCore grants ssm:GetParameter* on "*". Left alone,
+# this box could read the deployment's scan tag key and its release key. An
+# explicit Deny beats the managed Allow and names only the parameter-read
+# actions, so Session Manager is untouched. Same shape as region-host's
+# host_ssm_parameter_scope, with no parameter allowed at all.
+resource "aws_iam_role_policy" "no_parameters" {
+ name = "${var.name}-no-parameters"
+ role = aws_iam_role.pdf.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ {
+ Effect = "Deny"
+ Action = [
+ "ssm:GetParameter",
+ "ssm:GetParameters",
+ "ssm:GetParameterHistory",
+ "ssm:GetParametersByPath",
+ ]
+ Resource = "*"
+ },
+ ]
+ })
+}
+
+resource "aws_iam_instance_profile" "pdf" {
+ name = var.name
+ role = aws_iam_role.pdf.name
+}
+
+resource "aws_instance" "pdf" {
+ depends_on = [aws_iam_role_policy.no_parameters, aws_iam_role_policy_attachment.pdf_ssm]
+
+ ami = var.ami_id
+ instance_type = var.instance_type
+ subnet_id = var.subnet_id
+ vpc_security_group_ids = [aws_security_group.pdf.id]
+ iam_instance_profile = aws_iam_instance_profile.pdf.name
+
+ # EC2 caps user data at 16 KiB. cloud-init unpacks gzip.
+ user_data_base64 = base64gzip(local.init_script)
+ user_data_replace_on_change = false
+
+ metadata_options {
+ http_endpoint = "enabled"
+ http_tokens = "required"
+ http_put_response_hop_limit = 1
+ }
+
+ root_block_device {
+ volume_size = 20
+ volume_type = "gp3"
+ encrypted = true
+ }
+
+ tags = { Name = var.name }
+
+ # A newer image or an edited script never replaces the box by itself.
+ # Changing either is an explicit
+ # `tofu apply -replace=module.<name>.aws_instance.pdf`. A replaced box
+ # has a new private IP: update the console's CARLOS_PDF_ADDR.
+ lifecycle {
+ ignore_changes = [ami, user_data, user_data_base64]
+
+ precondition {
+ condition = var.subnet_id != null || data.aws_vpc.client.default
+ error_message = "The client security group is not in the default VPC, so the PDF host cannot use the default subnet: its security group and its instance would be in different VPCs. Pass subnet_id naming a subnet in the client group's VPC."
+ }
+ }
+}
diff --git a/infra/modules/pdf-host/outputs.tf b/infra/modules/pdf-host/outputs.tf
new file mode 100644
index 000000000..99b20f52e
--- /dev/null
+++ b/infra/modules/pdf-host/outputs.tf
@@ -0,0 +1,11 @@
+output "pdf_addr" {
+ value = "http://${aws_instance.pdf.private_ip}:3000"
+}
+
+output "instance_id" {
+ value = aws_instance.pdf.id
+}
+
+output "security_group_id" {
+ value = aws_security_group.pdf.id
+}
diff --git a/infra/modules/pdf-host/pdf-init.sh.tftpl b/infra/modules/pdf-host/pdf-init.sh.tftpl
new file mode 100644
index 000000000..080a72b18
--- /dev/null
+++ b/infra/modules/pdf-host/pdf-init.sh.tftpl
@@ -0,0 +1,143 @@
+#!/bin/bash
+# Debian arm64. The host keeps IMDS and private-network access for SSM;
+# only the default Docker bridge carries untrusted renderer traffic.
+set -Eeuo pipefail
+
+say() {
+ echo "pdf-init: $*" || true
+ { echo "pdf-init: $*" > /dev/console; } 2>/dev/null || true
+}
+fail() {
+ rm -f /usr/sbin/policy-rc.d || true
+ say "PDF-HOST FAILED: $*"
+ exit 1
+}
+trap 'fail "line $LINENO"' ERR
+export DEBIAN_FRONTEND=noninteractive
+
+say "1/4 SSM agent"
+apt-get update -q
+apt-get install -qy curl unattended-upgrades
+curl -fsSL -o /var/tmp/amazon-ssm-agent.deb \
+ "https://s3.${region}.amazonaws.com/amazon-ssm-${region}/latest/debian_arm64/amazon-ssm-agent.deb"
+dpkg -i /var/tmp/amazon-ssm-agent.deb
+rm -f /var/tmp/amazon-ssm-agent.deb
+systemctl enable --now amazon-ssm-agent unattended-upgrades
+
+say "2/4 Docker and nftables, stopped"
+# Stop package postinst and socket activation from starting Docker before
+# the fence exists. The generic nftables unit must not flush our table at boot.
+systemctl mask docker.service docker.socket nftables.service
+printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d
+chmod +x /usr/sbin/policy-rc.d
+apt-get install -qy docker.io nftables python3
+rm -f /usr/sbin/policy-rc.d
+
+say "3/4 metadata and container fence"
+tok=$(curl -fsS -X PUT http://169.254.169.254/latest/api/token \
+ -H 'X-aws-ec2-metadata-token-ttl-seconds: 300')
+imds() {
+ curl -fsS -H "X-aws-ec2-metadata-token: $tok" \
+ "http://169.254.169.254/latest/meta-data/$1"
+}
+ip=$(imds local-ipv4)
+mac=$(imds mac)
+vpc_cidr=$(imds "network/interfaces/macs/$mac/vpc-ipv4-cidr-block")
+# Parse metadata before using it in nft syntax or Docker's published address.
+# The Amazon resolver is the primary VPC CIDR's base+2, not the subnet's.
+resolver=$(python3 - "$ip" "$vpc_cidr" <<'PY'
+import ipaddress
+import sys
+ipaddress.IPv4Address(sys.argv[1])
+vpc = ipaddress.IPv4Network(sys.argv[2], strict=True)
+print(vpc.network_address + 2)
+PY
+)
+
+mkdir -p /etc/pdf-host /etc/systemd/system/docker.service.d
+cat > /etc/pdf-host/fence.nft <<EOF_NFT
+# A private table survives Docker's iptables/nft rule rebuilds. Re-loading
+# only this table is atomic: no interval with the old fence removed.
+add table inet pdf_fence
+flush table inet pdf_fence
+table inet pdf_fence {
+ chain container_egress {
+ # Replies to console requests must return to the console's private IP.
+ # Never exempt connections initiated by the renderer on conntrack state.
+ ct state established ct direction reply accept
+ ip daddr $resolver udp dport 53 accept
+ ip daddr $resolver tcp dport 53 accept
+ # Source: internal/caps/render.go, docEngineEgressDeny (all 17 entries).
+ ip daddr 0.0.0.0/8 drop
+ ip daddr 10.0.0.0/8 drop
+ ip daddr 100.64.0.0/10 drop
+ ip daddr 169.254.0.0/16 drop
+ ip daddr 169.254.169.254/32 drop
+ ip daddr 172.16.0.0/12 drop
+ ip daddr 192.0.0.0/24 drop
+ ip daddr 192.168.0.0/16 drop
+ ip daddr 198.18.0.0/15 drop
+ ip daddr 224.0.0.0/4 drop
+ ip daddr 240.0.0.0/4 drop
+ ip6 daddr 64:ff9b::/96 drop
+ ip6 daddr fc00::/7 drop
+ ip6 daddr fd00:ec2::254/128 drop
+ ip6 daddr fe80::/10 drop
+ ip6 daddr fec0::/10 drop
+ ip6 daddr ff00::/8 drop
+ }
+ chain container_host {
+ # Allow replies to host health probes, never new container-to-host calls.
+ ct state established ct direction reply accept
+ ip daddr $resolver udp dport 53 accept
+ ip daddr $resolver tcp dport 53 accept
+ drop
+ }
+ chain forward {
+ type filter hook forward priority -10; policy accept;
+ iifname "docker0" jump container_egress
+ }
+ chain input {
+ type filter hook input priority -10; policy accept;
+ iifname "docker0" jump container_host
+ }
+}
+EOF_NFT
+
+cat > /etc/systemd/system/pdf-fence.service <<'EOF_UNIT'
+[Unit]
+Description=PDF container network fence
+Before=docker.service
+
+[Service]
+Type=oneshot
+ExecStart=/usr/sbin/nft -f /etc/pdf-host/fence.nft
+RemainAfterExit=yes
+
+[Install]
+WantedBy=multi-user.target
+EOF_UNIT
+
+cat > /etc/systemd/system/docker.service.d/10-pdf-fence.conf <<'EOF_UNIT'
+[Unit]
+Requires=pdf-fence.service
+After=pdf-fence.service
+
+[Service]
+# Revalidate/reload on every Docker start, even while the oneshot is active.
+ExecStartPre=/usr/sbin/nft -f /etc/pdf-host/fence.nft
+EOF_UNIT
+systemctl daemon-reload
+systemctl unmask docker.service docker.socket
+systemctl enable pdf-fence.service docker.service
+systemctl start docker.service
+
+say "4/4 Gotenberg"
+docker run -d --name gotenberg --restart=always --network bridge \
+ -p "$ip:3000:3000" --dns "$resolver" \
+ '${gotenberg_image}' gotenberg --api-timeout='${api_timeout}' \
+ --chromium-deny-list='^file:(?!//\/tmp/).*' --webhook-deny-list='.*'
+# This probe uses the published private address, not the container loopback.
+curl --fail --silent --show-error --retry 30 --retry-connrefused --retry-delay 2 \
+ --max-time 5 "http://$ip:3000/health"
+say "PDF-HOST READY"
diff --git a/infra/modules/pdf-host/tests/pdf_host.tftest.hcl b/infra/modules/pdf-host/tests/pdf_host.tftest.hcl
new file mode 100644
index 000000000..f8ddf8c5b
--- /dev/null
+++ b/infra/modules/pdf-host/tests/pdf_host.tftest.hcl
@@ -0,0 +1,188 @@
+# Mock resources only: this suite never contacts an AWS account.
+mock_provider "aws" {}
+
+override_data {
+ target = data.aws_security_group.client
+ values = { vpc_id = "vpc-0aaaaaaaaaaaaaaaa" }
+}
+
+override_data {
+ target = data.aws_vpc.client
+ values = { default = true }
+}
+
+override_resource {
+ target = aws_instance.pdf
+ values = { private_ip = "10.0.1.23" }
+}
+
+variables {
+ name = "carlos-test-pdf"
+ ami_id = "ami-0123456789abcdef0"
+ client_security_group_id = "sg-0123456789abcdef0"
+ region = "eu-west-1"
+}
+
+run "the_fence" {
+ command = plan
+ assert {
+ condition = length(aws_security_group.pdf.ingress) == 1
+ error_message = "exactly one ingress rule"
+ }
+ assert {
+ condition = alltrue([
+ for i in aws_security_group.pdf.ingress :
+ i.from_port == 3000 && i.to_port == 3000 && i.protocol == "tcp"
+ && i.security_groups == toset([var.client_security_group_id])
+ && try(length(i.cidr_blocks), 0) == 0 && try(length(i.ipv6_cidr_blocks), 0) == 0
+ && try(length(i.prefix_list_ids), 0) == 0 && !coalesce(i.self, false)
+ ])
+ error_message = "TCP 3000 from the client group only"
+ }
+ assert {
+ condition = aws_security_group.pdf.vpc_id == "vpc-0aaaaaaaaaaaaaaaa"
+ error_message = "the group must share the client's VPC"
+ }
+}
+
+run "the_box" {
+ command = plan
+ assert {
+ condition = (
+ aws_instance.pdf.metadata_options[0].http_endpoint == "enabled"
+ && aws_instance.pdf.metadata_options[0].http_tokens == "required"
+ && aws_instance.pdf.metadata_options[0].http_put_response_hop_limit == 1
+ )
+ error_message = "IMDSv2 with one hop only"
+ }
+ assert {
+ condition = aws_instance.pdf.root_block_device[0].encrypted && aws_instance.pdf.instance_type == "t4g.medium"
+ error_message = "encrypted root and t4g.medium by default"
+ }
+ assert {
+ condition = aws_instance.pdf.user_data_base64 == base64gzip(local.init_script) && length(base64gzip(local.init_script)) < 21800
+ error_message = "compressed init must fit EC2's user data limit"
+ }
+ assert {
+ # Lifecycle is not exposed in resource values. Check the declaration too;
+ # the apply/plan pair below checks its effect on a changed init script.
+ condition = can(regex("ignore_changes\\s*=\\s*\\[ami,\\s*user_data,\\s*user_data_base64\\]", file("${path.module}/main.tf")))
+ error_message = "AMI and both user data forms require explicit replacement"
+ }
+}
+
+run "ssm_only" {
+ command = plan
+ assert {
+ condition = (
+ aws_iam_role_policy_attachment.pdf_ssm.policy_arn == "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
+ && aws_iam_role_policy_attachment.pdf_ssm.role == aws_iam_role.pdf.name
+ && aws_iam_instance_profile.pdf.role == aws_iam_role.pdf.name
+ && aws_instance.pdf.iam_instance_profile == aws_iam_instance_profile.pdf.name
+ )
+ error_message = "the instance must use the SSM role"
+ }
+ assert {
+ condition = (
+ length(jsondecode(aws_iam_role_policy.no_parameters.policy).Statement) == 1
+ && jsondecode(aws_iam_role_policy.no_parameters.policy).Statement[0].Effect == "Deny"
+ && jsondecode(aws_iam_role_policy.no_parameters.policy).Statement[0].Resource == "*"
+ && toset(jsondecode(aws_iam_role_policy.no_parameters.policy).Statement[0].Action) == toset([
+ "ssm:GetParameter", "ssm:GetParameters", "ssm:GetParameterHistory", "ssm:GetParametersByPath",
+ ])
+ )
+ error_message = "all parameter reads must be explicitly denied"
+ }
+}
+
+run "container_config" {
+ command = plan
+ assert {
+ condition = alltrue([
+ strcontains(local.init_script, "--restart=always"),
+ strcontains(local.init_script, "--network bridge"),
+ strcontains(local.init_script, "-p \"$ip:3000:3000\" --dns \"$resolver\""),
+ strcontains(local.init_script, "gotenberg --api-timeout='55s'"),
+ strcontains(local.init_script, "--chromium-deny-list='^file:(?!//\\/tmp/).*'"),
+ strcontains(local.init_script, "--webhook-deny-list='.*'"),
+ can(regex("^gotenberg/gotenberg@sha256:[0-9a-f]{64}$", var.gotenberg_image)),
+ ])
+ error_message = "private bind, explicit bridge/DNS, digest pin and checked engine flags"
+ }
+ assert {
+ condition = alltrue([
+ for cidr in [
+ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "169.254.0.0/16", "169.254.169.254/32",
+ "172.16.0.0/12", "192.0.0.0/24", "192.168.0.0/16", "198.18.0.0/15", "224.0.0.0/4", "240.0.0.0/4",
+ "64:ff9b::/96", "fc00::/7", "fd00:ec2::254/128", "fe80::/10", "fec0::/10", "ff00::/8",
+ ] : strcontains(local.init_script, "daddr ${cidr} drop")
+ ])
+ error_message = "all 17 docEngineEgressDeny destinations must be dropped"
+ }
+ assert {
+ condition = alltrue([
+ strcontains(local.init_script, "type filter hook forward priority -10; policy accept;"),
+ strcontains(local.init_script, "type filter hook input priority -10; policy accept;"),
+ strcontains(local.init_script, "iifname \"docker0\" jump container_egress"),
+ strcontains(local.init_script, "iifname \"docker0\" jump container_host"),
+ length(regexall("ip daddr \\$resolver udp dport 53 accept", local.init_script)) == 2,
+ length(regexall("ip daddr \\$resolver tcp dport 53 accept", local.init_script)) == 2,
+ !strcontains(local.init_script, "hook output"),
+ !strcontains(local.init_script, "flush ruleset"),
+ ])
+ error_message = "only container forward/input are fenced, with DNS exceptions and no global flush"
+ }
+ assert {
+ condition = alltrue([
+ can(regex("chain container_host \\{[^}]*ct state established ct direction reply accept[^}]*ip daddr \\$resolver udp dport 53 accept[^}]*ip daddr \\$resolver tcp dport 53 accept\\n drop\\n", local.init_script)),
+ can(regex("chain container_egress \\{[^}]*ip daddr \\$resolver tcp dport 53 accept[^}]*ip daddr 0\\.0\\.0\\.0/8 drop", local.init_script)),
+ !strcontains(local.init_script, "ct state established,related accept"),
+ strcontains(local.init_script, "network/interfaces/macs/$mac/vpc-ipv4-cidr-block"),
+ strcontains(local.init_script, "print(vpc.network_address + 2)"),
+ ])
+ error_message = "DNS precedes the deny list; host traffic ends in drop; only replies bypass the fence"
+ }
+ assert {
+ condition = alltrue([
+ strcontains(local.init_script, "Before=docker.service"),
+ strcontains(local.init_script, "Requires=pdf-fence.service"),
+ strcontains(local.init_script, "After=pdf-fence.service"),
+ strcontains(local.init_script, "ExecStartPre=/usr/sbin/nft -f /etc/pdf-host/fence.nft"),
+ strcontains(local.init_script, "systemctl mask docker.service docker.socket nftables.service"),
+ ])
+ error_message = "Docker must refuse startup if the fence fails, including restarts"
+ }
+}
+
+run "create_mock_box" {
+ command = apply
+ assert {
+ condition = output.pdf_addr == "http://10.0.1.23:3000"
+ error_message = "the console needs the private HTTP origin"
+ }
+ assert {
+ condition = aws_iam_role_policy.no_parameters.role == aws_iam_role.pdf.id
+ error_message = "the Deny must be attached to the instance's role"
+ }
+}
+
+run "changed_init_does_not_update_box" {
+ command = plan
+ variables {
+ api_timeout = "50s"
+ ami_id = "ami-11111111111111111"
+ }
+ assert {
+ condition = aws_instance.pdf.user_data_base64 == base64gzip(templatefile("${path.module}/pdf-init.sh.tftpl", { region = var.region, gotenberg_image = var.gotenberg_image, api_timeout = "55s" })) && aws_instance.pdf.ami == "ami-0123456789abcdef0"
+ error_message = "changing the init template or AMI must leave the existing instance alone"
+ }
+}
+
+run "another_vpc_needs_a_subnet" {
+ command = plan
+ override_data {
+ target = data.aws_vpc.client
+ values = { default = false }
+ }
+ expect_failures = [aws_instance.pdf]
+}
diff --git a/infra/modules/pdf-host/variables.tf b/infra/modules/pdf-host/variables.tf
new file mode 100644
index 000000000..19f7ec23d
--- /dev/null
+++ b/infra/modules/pdf-host/variables.tf
@@ -0,0 +1,48 @@
+variable "name" {
+ type = string
+}
+
+variable "ami_id" {
+ type = string
+}
+
+variable "client_security_group_id" {
+ type = string
+}
+
+variable "region" {
+ type = string
+ validation {
+ condition = can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]+$", var.region))
+ error_message = "region must be an AWS region name."
+ }
+}
+
+variable "instance_type" {
+ type = string
+ default = "t4g.medium"
+}
+
+variable "subnet_id" {
+ type = string
+ default = null
+}
+
+variable "gotenberg_image" {
+ type = string
+ # Gotenberg 8.39.0 multi-architecture index, including linux/arm64.
+ default = "gotenberg/gotenberg@sha256:13672f317b443c793e972b1bd2155ec62a3e7b6891b411e8196442cc053ee5f5"
+ validation {
+ condition = can(regex("^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[0-9a-f]{64}$", var.gotenberg_image))
+ error_message = "gotenberg_image must name an image pinned by sha256 digest."
+ }
+}
+
+variable "api_timeout" {
+ type = string
+ default = "55s"
+ validation {
+ condition = can(regex("^([0-9]+(\\.[0-9]+)?(ms|s|m|h))+$", var.api_timeout))
+ error_message = "api_timeout must be a duration using ms, s, m or h."
+ }
+}
diff --git a/infra/modules/pdf-host/versions.tf b/infra/modules/pdf-host/versions.tf
new file mode 100644
index 000000000..c028066c2
--- /dev/null
+++ b/infra/modules/pdf-host/versions.tf
@@ -0,0 +1,9 @@
+terraform {
+ required_version = ">= 1.10"
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = ">= 6.0"
+ }
+ }
+}