PDF Generation in a Distroless Go Monolith with Typst
Our backend was a lightweight Go monolith running in a distroless container. Then we needed server-side PDF generation for healthcare documents. We tried WeasyPrint and could not get it working within our deployment con
Our backend was a lightweight Go monolith running in a distroless container. Then we needed server-side PDF generation for healthcare documents.
We tried WeasyPrint and could not get it working within our deployment constraints. Another service was an option, but in our experience each additional service brought more cost, deployment work, and failure points.
We bundled Typst with the Go backend and invoked it as a local child process. AI-assisted coding made writing and iterating on its templates much more approachable.
Why the deployment mattered
Jinja2 and WeasyPrint fit naturally in Python applications. Our Go deployment would also need Python and native text-layout dependencies such as Pango, as described in the installation documentation.
Playwright with Chromium can reuse existing web layouts, but adds a browser runtime and system dependencies. Its Docker guidance also explains the user and sandbox configuration needed for untrusted content.
In healthcare, sensitive patient information and HIPAA requirements shape operational decisions. Adding a rendering service meant another deployment, service identity, network transfer, and failure boundary for our team to manage.
The security boundary starts before the renderer
Consider this common pipeline:
Application data -> Jinja template -> HTML and CSS -> WeasyPrint -> PDF
Two questions matter: can submitted content become template code, and can it cause the renderer to load a resource?
Keep Jinja templates developer-controlled, enable HTML autoescaping, and avoid applying |safe to submitted text. Rich text needs sanitization. Values used as resource URLs need separate validation; HTML escaping does not authorize their destinations. See Jinja configuration.
WeasyPrint renders HTML and CSS without browser JavaScript. Supported resource references can still trigger network requests or local file reads. Its security documentation covers file disclosure, attachments, long renderings, and memory use.
Recent advisories illustrate these boundaries:
| Advisory | Relevant condition | Fixed in |
|---|---|---|
| Jinja CVE-2025-27516 | Attacker-controlled templates escape sandbox attribute checks through the attr filter and permit arbitrary Python code execution. | 3.1.6 |
| WeasyPrint CVE-2025-68616 | Redirects bypass custom destination validation. | 68.0 |
| WeasyPrint CVE-2026-49452 | Untrusted HTML injects CSS when presentational hints are enabled. | 69.0 |
| WeasyPrint CVE-2026-55073 | Attacker-influenced metadata or stylesheet parameters bypass the document's restrictive fetcher. | 70.0 |
These versions fix the listed issues. Patching, resource policies, and process limits remain necessary, including when rendering runs behind an internal endpoint.
A local renderer inside the Go deployment
Our runtime image uses a nonroot distroless Debian base. Alongside the Go server, it contains the musl Typst binary, selected fonts, and developer-owned templates. The Go application starts the compiler directly. Bundling fonts explicitly also makes the rendering environment easier to reproduce when developing locally and deploying new revisions.
One deployed container
Go API
-> prepare JSON and required assets in a work directory
-> invoke the local Typst executable
-> read PDF bytes
-> remove temporary files
For this rendering path, we avoided another endpoint and network hop while retaining one deployment.
The compiler shares the container's resource budget. Its operating-system access depends on the account, mounts, environment, and runtime policy it receives.
Keep submitted content as data
Our narrative-document path passes JSON into a fixed Typst template. Other paths generate Typst source; this example focuses on the data-driven approach.
A synthetic input might look like this:
{
"name": "Example Patient",
"notes": "Literal input: #read(\"../outside.txt\")\n<img src=\"https://example.invalid/a.png\">\n$42 [demo] {{ 7 * 7 }}"
}
The developer-owned template reads those values as strings:
#let data = json(sys.inputs.data)
#set page(paper: "us-letter", margin: 0.75in)
#set text(size: 11pt)
= Synthetic report
*Name:* #data.name
*Notes*
#data.notes
The template inserts data.notes as text. Avoid eval, which turns strings into Typst code. This keeps submitted content on the data side of the boundary.
Fields used to select images or other assets still need validation. JSON does not make every use of its values safe.
In this Go example, imports are omitted. trustedTemplate embeds the report.typ above; Report contains string fields Name and Notes, tagged name and notes for JSON.
func renderPDF(parent context.Context, report Report) ([]byte, error) {
typstPath, err := exec.LookPath("typst")
if err != nil {
return nil, err
}
root, err := os.MkdirTemp("", "report-*")
if err != nil {
return nil, err
}
defer os.RemoveAll(root)
payload, err := json.Marshal(report)
if err != nil {
return nil, err
}
for name, body := range map[string][]byte{
"report.typ": trustedTemplate,
"data.json": payload,
} {
if err := os.WriteFile(filepath.Join(root, name), body, 0600); err != nil {
return nil, err
}
}
ctx, cancel := context.WithTimeout(parent, 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, typstPath,
"compile", "--root", root,
"--input", "data=data.json", "report.typ", "output.pdf")
cmd.Dir = root
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("compile PDF: %w", err)
}
return os.ReadFile(filepath.Join(root, "output.pdf"))
}
exec.CommandContext receives an argument list. Filenames are fixed, submitted values go into JSON, and os.MkdirTemp creates a private work directory.
With Typst 0.14.2, extracted PDF text retained the literal #read(...), HTML tag, punctuation, and Jinja-looking expression. A separate template that directly tried reading outside the project root failed with access denied.
Endpoint authorization, admission limits, memory budgets, and output-size limits belong around this example.
What Typst changes and what still needs controls
The standard compiler confines document file access to the project root. Document code cannot launch applications; network access is restricted to official-registry package downloads. See Typst's security explanation.
We stage only required document assets. For offline compilation, bundle packages and enforce egress restrictions. Asset downloads performed by the application need their own validation.
A production rendering path still needs operational controls:
Keep tenant authorization in the application before selecting document data.
Bound admitted jobs and concurrent renders across requests; a limiter created separately for each request cannot impose a service-wide ceiling.
Enforce deadlines and CPU/memory budgets; a timeout does not limit peak memory.
Keep paths application-controlled and restrict the subprocess environment and filesystem access.
Bound input and output sizes and handle compiler failures.
Keep sensitive content and compiler diagnostics out of general-purpose logs and client errors.
Patch dependencies and rerun synthetic rendering fixtures when they change.
Distroless packaging and nonroot execution reduce deployment exposure. The child process still shares container resources and may access readable mounted secrets.
AI coding reduced the template work
AI-assisted coding reduced the effort of learning Typst and building templates. We could describe a layout, generate a first version, and iterate against the rendered PDF.
A reusable agent skill can preserve conventions between documents. A starting instruction block:
Build a Typst document from a developer-owned template and a JSON schema.
Use synthetic fixtures for development.
Keep submitted strings as data; do not evaluate them as template code.
Use fixed asset mappings and the project's approved fonts.
Test long answers, empty sections, punctuation, and page breaks.
Compile the PDF, render every page, and inspect the images.
Check extracted text for missing answers and clipped content.
Repeat the checks after changes.
Compilation success can hide missing sections, overlapping headings, or unreadable text. Our narrative-template tests check text positions for heading overlap; rendered-page inspection complements those checks. A skill makes those checks repeatable across new templates and revisions, with a person reviewing the final document.
When I would use a separate renderer
A separate worker becomes attractive when jobs need a queue, independent scaling, or stronger resource and credential isolation. Customer-authored templates or arbitrary HTML also change the isolation requirements. That separation works only when the worker's permissions and resource policies enforce the intended boundary.
For this PDF path, Typst preserved our deployment shape. We accepted another template language and shared container resources in exchange for fewer moving parts.
Disclosure: I work on EasyDocForms (company blog), where these document-generation requirements come from. AI assistance was used in preparing this article and checking its synthetic code example.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.