carlos / platform Public

spec: PDF service, Gotenberg for every app (approved)

One Gotenberg box per deployment from a new pdf-host module, reached
through a console door with a Service credential. Fair-use limits on
every deployment and a monthly plan cap on Carloku. Supersedes #335's
fleet-internal engines design; Tito Go moves after Carloku proves it.

Approved by Paul 2026-11-02 after an Astra builder check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a5e8d82bace7f152f4560a737a05e3bdf887ea83 parent 5394c7f
1 file changed, +361 −0
  • docs/superpowers/specs/2026-11-02-pdf-service-design.md +361 −0

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/specs/2026-11-02-pdf-service-design.md b/docs/superpowers/specs/2026-11-02-pdf-service-design.md
new file mode 100644
index 000000000..e14cff80d
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-02-pdf-service-design.md
@@ -0,0 +1,361 @@
+# PDF service: Gotenberg for every app
+
+**Date:** 2026-11-02
+**Status:** draft 2, for Paul's read. Builder check (Astra, 2026-11-02)
+raised one question, settled in §4.2: the fence covers the container,
+not the host.
+**Asked for by:** Paul, for Sporran on Carloku. Tito Go moves on to it
+after Carloku proves it.
+**Supersedes:** `2026-10-21-fleet-internal-engines-design.md` (#335) and its
+Plan 1 simulation (`internal/sim/engines`). See §9.
+**Builds on:** the virus scanner's shape: one engine box per deployment
+(`infra/modules/scanner-host`), with the console as the only client
+(`2026-10-04-scanner-host-rollout-design.md`), and `svcrole.Service`
+(`internal/svcrole/svcrole.go`), whose comment already names PDF rendering
+as the next service.
+**Review budget:** AGENTS.md "Stopping rules". At most three cross-model
+rounds on this spec, and a review stops at the first round with no P1.
+
+## 1. Intent
+
+Apps need PDFs. Sporran needs two things: an invoice the customer
+downloads, and the same invoice attached to an email. Tito Go already does
+this against a Gotenberg box that Tito's operators built by hand
+(`tito/carlos-infrastructure/svc-pdf.tf`: Gotenberg 8.21.1 in Docker
+behind Caddy basic auth, reachable from the IE fleet only). It works well.
+Carloku has nothing like it, and nothing in the platform makes one.
+
+This spec makes PDF rendering a **platform service**. The platform runs one
+Gotenberg per deployment. Every app can call it through the console with a
+Service credential, and gets back what Gotenberg returns. Gotenberg's other
+features (Office documents to PDF, merging, PDF/A and the rest) come through
+the same door.
+
+The false starts get tidied up along the way. #335's design and simulation
+go, and Tito's hand-built box is replaced by the platform module.
+
+## 2. Goals, non-goals, anti-goals
+
+**Goals**
+
+- G1. Any app on a deployment that runs the engine can render a PDF with
+ one HTTP call. No operator grant and no per-app switch are needed. The app
+ owner mints one Service credential and sets it as a secret.
+- G2. The door speaks Gotenberg's own API (same paths, same multipart form
+ fields) under a console base URL, so any Gotenberg client library works
+ once you point it at that URL and add an `Authorization` header.
+- G3. On Carloku, PDF renders are a plan limit with a monthly allowance per
+ plan, handled the way other caps are (§6.2).
+- G4. Fair use on every deployment: per-account rate and concurrency
+ limits, so one app cannot starve the others (§6.1).
+- G5. Every render is recorded per app and per account, with no price, so
+ an operator can see who uses it.
+- G6. The engine is a platform module that Carloku and Tito consume the way
+ a self-hoster would, never a hand-written root resource.
+
+**Non-goals**
+
+- An engine on every box, or in every region. There is one box per
+ deployment in the home region, as with the scanner.
+- Calling the engine directly from an instance, over a socket or private
+ network. Every call goes through the console.
+- Credentials handed to every app automatically. Paul ruled the one-time
+ `carlos services create --role service` step fine (2026-11-02).
+- Asynchronous rendering with webhooks. Gotenberg's webhook mode is refused
+ (§5.3).
+- A PDF pack (more renders for money). Possible later.
+- Tenant-run engines. `doc_engine` stays as it is for operators who want
+ their own (§9).
+
+**Anti-goals**
+
+- The engine as an SSRF foothold. Chromium inside it fetches whatever a page
+ references, so it must never reach a private address, the instance
+ metadata service or another box in the VPC (§4.2).
+- The engine reachable from anything except the console.
+- Tenant data on the engine box. It holds nothing: no bucket, no parameter
+ and no database access, same as the scanner box.
+- A free account turning the box into a render farm.
+
+## 3. Rulings (Paul, 2026-11-02)
+
+- **P1.** The platform runs Gotenberg for every app (the scanner's shape).
+ #335's tenant-run engine model is set aside.
+- **P2.** On for every app by default.
+- **P3.** Both plan limits and fair-use rate limits.
+- **P4.** #335's simulation code is deleted and its spec marked superseded.
+- **P5.** Tito Go moves on to the platform service after Carloku proves it.
+- **P6.** The one-time Service token step is fine.
+
+## 4. The engine box
+
+### 4.1 Module
+
+`infra/modules/pdf-host` is a sibling of `scanner-host`, built the same way:
+
+- One EC2 box (default `t4g.medium`: Chromium and LibreOffice need more
+ memory than clamd does, and Tito's `t4g.small` is the floor). AMI passed
+ in, the console box's own, with `ignore_changes = [ami]`. Replacement is
+ always explicit (`tofu apply -replace=...`), as with the scanner.
+- Gotenberg in Docker, pinned **by digest** (8.x, arm64), listening on the
+ box's private IP, port 3000, with `--restart=always`.
+- A security group that admits TCP 3000 only from
+ `client_security_group_id` (the console box's group), never from a CIDR.
+- An instance role with Session Manager only and an explicit Deny on SSM
+ parameter reads, copied from `scanner-host`.
+- IMDSv2 required, with a hop limit of 1, so nothing in a container can
+ reach the metadata service.
+- Outputs `pdf_addr` (`http://<private_ip>:3000`) for the console.
+
+Console to engine is plain HTTP inside the VPC, closed by the security
+group. That is the trust model Paul accepted for clamd (scanner-host D3,
+"A is fine for now"). **(my call: same model, no Caddy and no basic auth.
+Gotenberg's own basic auth could be added cheaply if the review wants it.)**
+
+### 4.2 The egress fence
+
+The security group cannot express "the internet but not the VPC", so the
+fence is on the box. It fences **the Gotenberg container's traffic only**,
+not the host's. The host's own services need private addresses: the SSM
+agent talks to the metadata service, and the host resolves names through
+the VPC resolver. Nothing on the host renders untrusted input. **(my call,
+from the builder check)**
+
+The init script installs nftables rules in Docker's `DOCKER-USER` path (the
+forward path for container traffic) that drop every destination in the
+private ranges `internal/caps/render.go` already lists for `doc_engine`
+(RFC 1918, link-local including 169.254.169.254, CGNAT, IPv6 ULA, NAT64
+and the rest). One exception is allowed: the VPC resolver's address on
+port 53, UDP and TCP, so the container can resolve public names. DNS on
+port 53 cannot carry an HTTP fetch. Container-to-host traffic (the bridge
+gateway) is dropped too, except that same DNS exception if the builder
+points the container's resolver there. The rules load before Docker
+starts. A boot where they fail to load leaves Gotenberg stopped. IMDSv2's
+hop limit of 1 (§4.1) is a second, independent block on the metadata
+service.
+
+Gotenberg's own `--chromium-deny-list` and `--webhook-deny-list` flags are
+also set, as a second layer, never the only one. Public egress (https to
+the internet) stays open, so a page can load its fonts, images and
+stylesheets from public URLs.
+
+**Acceptance check on a real box:** a render of HTML that references
+`http://169.254.169.254/`, the console's private IP, another box's
+private IP, the bridge gateway and the VPC resolver on port 80 gets none
+of them. A render that references a public image by hostname gets it.
+Session Manager still opens a session on the box.
+
+### 4.3 Console wiring
+
+| Module output | Console variable |
+|---|---|
+| `pdf_addr` | `CARLOS_PDF_ADDR` |
+
+With `CARLOS_PDF_ADDR` unset, the door answers 503 with "no PDF engine is
+configured for this deployment (CARLOS_PDF_ADDR)", following the scanner's
+`CARLOS_CLAMD_ADDR` message. That is the whole switch: there is no
+`system/pdf.json` in v1, because there is nothing for an operator to
+consent to. **(my call)**
+
+`carlos system pdf status` (Operate role, operators) reports whether an
+engine is configured, whether it answers Gotenberg's `/health`, its
+version, and the last 24 hours of renders and refusals. It sits beside
+`carlos system antivirus status`.
+
+## 5. The door
+
+### 5.1 Shape
+
+```
+POST https://<console>/api/cli/apps/{account}/{app}/pdf/<gotenberg route>
+Authorization: Bearer <service token>
+```
+
+The route registers with `svcrole.Allow(svcrole.Service)`, exactly as
+`store/scan/object` does in `internal/console/authcli.go`. An admin
+credential also passes, since Admin is a union that includes Service. The
+token must be bound to `{app}` or be account-wide in `{account}`, using the
+checks the scan door already applies through `apiAccountApp`.
+
+`<gotenberg route>` is the path Gotenberg itself serves, so
+`.../pdf/forms/chromium/convert/html` reaches Gotenberg's
+`/forms/chromium/convert/html`. The console streams the multipart body to
+the engine and streams the engine's response back, with Gotenberg's status
+code, `Content-Type`, `Content-Disposition` and `Gotenberg-Trace` headers.
+
+### 5.2 Routes allowed
+
+An allow-list, so a new Gotenberg release cannot widen the door by
+accident:
+
+- `forms/chromium/convert/html`, `.../url`, `.../markdown`
+- `forms/chromium/screenshot/html`, `.../url`, `.../markdown`
+- `forms/libreoffice/convert`
+- `forms/pdfengines/merge`, `split`, `flatten`, `convert`,
+ `metadata/read`, `metadata/write`, `encrypt`, `embed`
+
+Anything else is a 404 from the console, including `/health`, `/version`,
+`/prometheus/metrics` and `/debug`, which never reach the engine. The
+builder updates the list against the pinned Gotenberg version and records
+in the module README which version it was checked against.
+
+**URL rendering is allowed.** It is the "PDF version of a page" case for a
+public page. The fence (§4.2) is what keeps it safe. For a page behind a
+login, the docs steer apps to render the HTML themselves and send it,
+which is also the faster path, and the one an invoice uses.
+
+### 5.3 Refused inside an allowed route
+
+- Any `Gotenberg-Webhook-*` header (async mode, where the engine calls out
+ to a URL the caller names): a 400 that says webhooks are not available.
+- Any other `Gotenberg-*` request header outside a short allow-list
+ (`Gotenberg-Output-Filename`, `Gotenberg-Trace`): stripped.
+- A request body over 32 MiB: a 413. **(my call)**
+- A response over 64 MiB: the console aborts the stream and counts a
+ failure. **(my call)**
+- `downloadFrom` form fields are allowed. The fence covers them as it
+ covers URL rendering.
+
+Timeouts: the console gives the engine 60 s to respond (Gotenberg's
+`--api-timeout` is set to 55 s, so the engine gives up first and says why).
+**(my call)**
+
+### 5.4 Credentials
+
+Nothing new. The owner runs:
+
+```
+carlos services create --role service --app <app> pdf
+carlos secrets set --app <app> CARLOS_SERVICE_TOKEN=<secret>
+```
+
+The app reads `CARLOS_SERVICE_TOKEN` and `CARLOS_CONSOLE` (or its
+configured console origin) and calls the door. If an app already has a
+Service credential for scanning, the same one works.
+
+## 6. Limits
+
+All limits are per **account**, keyed on the account in the URL, so an
+owner's apps share one allowance.
+
+### 6.1 Fair use (every deployment)
+
+- **Concurrency:** at most 4 renders in flight per account. A fifth gets a
+ 429 with `Retry-After: 2`.
+- **Rate:** 60 renders per minute per account, as a token bucket with a
+ burst of 20. Over it, a 429 with `Retry-After` set to when the next token
+ is due.
+- **Deployment-wide:** at most 16 renders in flight to the engine from the
+ console, so the box is never asked for more than it can run. Over it,
+ a 503 with `Retry-After: 2`.
+
+These are console constants, set through `CARLOS_PDF_LIMITS`
+(`per_account_inflight,per_minute,burst,total_inflight`) so an operator can
+tune them without a release. The numbers are **my call**, sized for invoice
+traffic: Sporran rendering an invoice per order is far below them.
+
+The console's existing `allowWrite` limit does not apply to this door. It
+would cap PDFs at the console-wide write rate, which is a different
+budget.
+
+### 6.2 Plan limit (deployments with a plan catalog, i.e. Carloku)
+
+A new `plans.Limits` field, `PDFRendersMonth int` (`pdf_renders_month`).
+Catalog starting values: **Free 100, Personal 2,000.** These are catalog
+values, changed without a release. Zero means no limit, as with the other
+fields.
+
+It is handled like the other caps in `internal/console/plangrace.go`
+(`evaluateCap`) and Plan 4's stages, following the email cap:
+
+- At the limit: the usual warning banner, the owner email, and the
+ `X-Carlos-Plan-Warning` header.
+- At twice the limit: renders are refused with a 402 whose message comes
+ from `capCopy`, until the month resets or the plan changes. There is no
+ notice wait before the refusal, as with email's pause at 2x (Paul's
+ earlier ruling for email). **(my call to follow email's pattern)**
+- Ops accounts are exempt (`planexempt.go`), as for every other cap.
+
+With no catalog (Tito, self-hosters), only §6.1 applies.
+
+**What counts as a render:** one request that the engine answered 2xx. A
+4xx or 5xx from the engine, a refusal by the console, or an aborted stream
+does not count. **(my call)**
+
+### 6.3 Recording (G5)
+
+A console table `pdf_renders` gets one row per request with account, app,
+service credential name, route, status, bytes in and out, duration and
+time. Rows older than 90 days are pruned. The plan measure (§6.2) and
+`carlos system pdf status` read from it. The owner sees their own month's
+count on the account usage page beside the other caps.
+
+## 7. Docs
+
+A new docs page, "PDFs", walks through:
+
+1. Minting the credential.
+2. Turning an HTML invoice into a PDF with curl and Gotenberg's form
+ fields.
+3. Sending it as an email attachment (pointing at the existing email docs).
+4. Using an existing Gotenberg client library: set the base URL and the
+ header.
+5. Limits and what each refusal means.
+
+The plans page gets the new row. Every user-facing string (docs, refusal
+messages, `capCopy` entries, CLI output) goes through copy review before
+it is written.
+
+## 8. Rollout
+
+Rule 5 (no dormant feature): the code merges with the module, and the
+door is live wherever `CARLOS_PDF_ADDR` is set. Carloku switches it on in
+the release that carries it.
+
+1. **Merge** the door, limits, `carlos system pdf status`, the module and
+ docs. Release.
+2. **Carloku dev:** apply `pdf-host` in the dev root, set
+ `CARLOS_PDF_ADDR` on the dev console, and run the §4.2 acceptance checks
+ plus a real invoice render from a dev app. Production infrastructure
+ needs Paul's scoped approval (AGENTS.md), so the builder asks before
+ applying, with account, region, resources, cost and cleanup stated.
+3. **Carloku flagship:** the same in `carloku-infrastructure`, again with
+ scoped approval. Sporran mints its credential and uses it.
+4. **Tito:** once Carloku has served Sporran for a week with no engine
+ incident, apply `pdf-host` in Tito's root and set `CARLOS_PDF_ADDR` on
+ Tito's console. Then Tito Go moves from its private svc/pdf address and
+ basic auth to the door and a Service credential (a change in Tito Go,
+ which lives outside this repo). Then `svc-pdf.tf` and
+ `svc-pdf-init.sh` are destroyed and deleted. This step is its own plan,
+ with its own approval.
+
+## 9. Tidying the false starts
+
+- **#335:** a header on `2026-10-21-fleet-internal-engines-design.md`
+ saying it was superseded by this spec on 2026-11-02, and why: the
+ platform runs the engine, so the internal-route, grant and socket
+ machinery has nothing left to protect. The spec and its findings files
+ stay as history. `internal/sim/engines` (Go tests and `mutate.sh`) is
+ deleted, with a census `removed` overlay from `make census-propose`. The
+ #335 discussion is closed with a pointer to this spec.
+- **`doc_engine`:** unchanged. The README's capabilities section gains one
+ sentence pointing at the platform service as the simpler path for most
+ apps.
+- **Comments:** `svcrole.go`'s "PDF rendering is the next" and
+ `release/system.go`'s "system/pdf.json later" are updated to say what
+ was built.
+- **Tito's svc/pdf box:** retired in §8 step 4.
+
+## 10. Left to the builder
+
+- Where the door's handler lives and how it streams (an
+ `httputil.ReverseProxy` with a rewrite and a bounded body is the obvious
+ fit).
+- The `pdf_renders` schema and its index.
+- The exact nftables rules, as long as they match §4.2 and its acceptance
+ check.
+- The module's variable names, following `scanner-host`.
+- Test shape. The guards that matter: a route outside the allow-list never
+ reaches the engine; a webhook header is refused; a token for another
+ app or account is refused; the limits in §6.1 and the cap in §6.2 refuse
+ at the right count; a refused or failed render is not counted.