ZDDC/zddc/internal/handler/converthandler.go
ZDDC b5aab81d31 feat(zddc): MD→{docx,html,pdf} server-side conversion via stock pandoc + chromium containers
New endpoint GET /<path>/foo.md?convert=docx|html|pdf renders a markdown
source on demand. Surfaced as the Download buttons in browse's markdown
editor (separate commit).

Execution model — two upstream container images, lazy-pulled:

  • docker.io/pandoc/latex:latest  — MD→DOCX, MD→HTML (entrypoint pandoc)
  • docker.io/zenika/alpine-chrome — HTML→PDF (entrypoint chromium-browser)

No custom image build. The runner passes --pull=missing on every podman/
docker invocation so the operator only needs the runtime installed —
first request pulls the image, subsequent requests use the local cache.
Overrides: --convert-pandoc-image / --convert-chromium-image (and the
matching ZDDC_CONVERT_* env vars). Engine: --convert-engine (podman
preferred, docker fallback). Resource caps: --convert-mem-mib (512),
--convert-cpus (2), --convert-pids (100), --convert-timeout (30s).

PDF flow is two-stage: pandoc renders the markdown through the embedded
viewer-template.html to standalone HTML, then chromium prints that HTML
via --print-to-pdf. Preserves the print-media CSS already authored in
viewer-template.html rather than going through pandoc's LaTeX template.

Each conversion runs in a throw-away container with --rm --network=none
--read-only --tmpfs=/tmp --cap-drop=ALL --security-opt=no-new-privileges
--env=HOME=/tmp plus a bind-mounted scratch dir for I/O. Pandoc reads
markdown from stdin / writes to stdout; the viewer template lives at
/tpl (ro). Chromium reads HTML from a read-write bind mount at /pdf
and writes the PDF to the same mount; the host reads it back. No shell
wrappers, no shell quoting — argv flows straight into each image's
entrypoint.

On-disk cache at <dir>/.converted/<base>.<ext> with mtime synced to the
source. Fast path is a stat-and-serve with no exec; slow path
singleflights concurrent requests for the same target. PUT/DELETE/MOVE
on the source .md purges the .converted/ sidecars.

Per-project template variables (client/project/contractor/project_number)
come from a new .zddc `convert:` cascade block, walked leaf→root with
per-key latest-wins. Filename-derived variables (title, tracking_number,
revision, status, is_draft) come from a new zddc.ParseFilename helper.

If neither podman nor docker is on PATH, the endpoint serves 503 with
a clear Retry-After. The rest of the server keeps working.

This is the first os/exec site in the codebase. The hardening in
internal/convert/runner.go — context.CancelFunc → process kill,
cmd.WaitDelay, platform-specific SysProcAttr (Setpgid + Pdeathsig on
Linux), minimal env, stdout cap via limitWriter, stderr ring buffer —
sets the pattern for any future shell-outs.

Public surface:
  convert.ToDocx(ctx, source, meta) / .ToHTML / .ToPDF
  convert.Probe(ctx, engineOverride) → install Runner if engine present
  convert.SetImages(pandoc, chromium)
  convert.ConfigureLimits(memMiB, cpus, pids, timeout)
  convert.Available()

Container handler at internal/handler/converthandler.go; dispatcher
branch in cmd/zddc-server/main.go inserts the convert lookup after the
existing ACL gate, reusing the source file's read policy verbatim.
2026-05-13 10:33:56 -05:00

297 lines
9.7 KiB
Go

package handler
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/convert"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// On-demand MD→{docx,html,pdf} conversion endpoint.
//
// GET /<path>/foo.md?convert=docx|html|pdf
//
// The source file's read policy (already enforced by the dispatcher
// before this handler runs) gates the response. The converted bytes
// are cached at <dir>/.converted/<base>.<ext>, with mtime synced to the
// source — so a fast-path GET that finds a fresh cache hit serves the
// disk file via http.ServeContent without invoking pandoc at all.
//
// When the cache is stale (or absent) the handler:
// 1. Reads source bytes.
// 2. Walks the .zddc cascade to assemble the convert.Metadata.
// 3. Calls convert.ToDocx / ToHTML / ToPDF (containerised pandoc).
// 4. Atomically writes the result to .converted/ and syncs mtime.
// 5. Serves it.
//
// Concurrent requests for the same URL share a single conversion via
// the singleflightGroup keyed by the cached-file absolute path.
var convertSF singleflightGroup
// convertTimeout bounds the slow-path conversion + write + serve. The
// runner itself enforces a finer-grained timeout on the container.
const convertTimeout = 90 * time.Second
// ServeConverted is the entry point. format is the requested target
// extension; chain is the already-resolved ACL chain (re-used here
// only to extract the convert: cascade metadata).
func ServeConverted(cfg config.Config, w http.ResponseWriter, r *http.Request, srcAbs, format string, chain zddc.PolicyChain) {
format = strings.ToLower(strings.TrimSpace(format))
switch format {
case "docx", "html", "pdf":
default:
http.Error(w, "Bad Request — convert must be docx, html, or pdf", http.StatusBadRequest)
return
}
caps, ok := convert.Available()
if !ok {
// One re-probe attempt — gives the operator a way to recover
// after building the image without restarting the server.
caps = convert.Reprobe(r.Context(), os.Getenv("ZDDC_CONVERT_ENGINE"))
if !caps.Ready() {
w.Header().Set("Retry-After", "60")
http.Error(w, "Service Unavailable — "+caps.Reason(), http.StatusServiceUnavailable)
return
}
}
srcInfo, err := os.Stat(srcAbs)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
http.Error(w, "Not Found", http.StatusNotFound)
} else {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
return
}
if srcInfo.IsDir() {
http.Error(w, "Bad Request — convert applies to files", http.StatusBadRequest)
return
}
base := strings.TrimSuffix(filepath.Base(srcAbs), filepath.Ext(srcAbs))
dir := filepath.Dir(srcAbs)
cacheDir := filepath.Join(dir, ".converted")
cacheAbs := filepath.Join(cacheDir, base+"."+format)
// Fast path: cached file present and mtime-equal to source.
if cacheInfo, err := os.Stat(cacheAbs); err == nil && cacheInfo.Mode().IsRegular() {
if cacheInfo.ModTime().Equal(srcInfo.ModTime()) {
serveCached(w, r, cacheAbs, format, base)
return
}
}
// Slow path: convert, cache, serve. Singleflight collapses
// concurrent requests for the same target.
_, err = convertSF.Do(cacheAbs, func() (any, error) {
return nil, buildAndStore(r.Context(), srcAbs, srcInfo, cacheDir, cacheAbs, format, base, chain)
})
if err != nil {
mapConvertError(w, err, format)
return
}
serveCached(w, r, cacheAbs, format, base)
}
// buildAndStore reads the source, runs the conversion, atomically
// writes the result, and syncs the cached mtime to the source mtime.
// Returns the cached file's absolute path on success.
func buildAndStore(ctx context.Context, srcAbs string, srcInfo os.FileInfo, cacheDir, cacheAbs, format, base string, chain zddc.PolicyChain) error {
source, err := os.ReadFile(srcAbs)
if err != nil {
return fmt.Errorf("read source: %w", err)
}
meta := buildMetadata(srcAbs, chain)
ctx, cancel := context.WithTimeout(ctx, convertTimeout)
defer cancel()
var out []byte
switch format {
case "docx":
out, err = convert.ToDocx(ctx, source, meta)
case "html":
out, err = convert.ToHTML(ctx, source, meta)
case "pdf":
out, err = convert.ToPDF(ctx, source, meta)
default:
return fmt.Errorf("unsupported format %q", format)
}
if err != nil {
return err
}
if err := os.MkdirAll(cacheDir, 0o755); err != nil {
return fmt.Errorf("mkdir cache: %w", err)
}
if err := zddc.WriteAtomic(cacheAbs, out); err != nil {
return fmt.Errorf("write cache: %w", err)
}
// Sync mtime to source so the fast-path predicate works on the
// next request. Both atime and mtime get the source's mtime —
// http.ServeContent honors mtime for Last-Modified / ETag.
srcMT := srcInfo.ModTime()
if err := os.Chtimes(cacheAbs, srcMT, srcMT); err != nil {
slog.Warn("convert: chtimes failed (continuing)", "path", cacheAbs, "err", err)
}
return nil
}
// buildMetadata assembles the Metadata used by pandoc -V flags. The
// filename-derived fields (title, tracking_number, revision, status,
// is_draft) come from zddc.ParseFilename; the project-wide fields
// (client/project/contractor/project_number) come from the cascade.
//
// chain.Levels is walked from leaf (last index, most specific) toward
// root, then Embedded as the final fallback. The first non-empty value
// per field wins.
func buildMetadata(srcAbs string, chain zddc.PolicyChain) convert.Metadata {
meta := convert.Metadata{
GenerationTime: time.Now(),
}
name := filepath.Base(srcAbs)
parsed := zddc.ParseFilename(name)
if parsed.Valid {
meta.Title = parsed.Title
meta.TrackingNumber = parsed.TrackingNumber
meta.Revision = parsed.Revision
meta.Status = parsed.Status
meta.IsDraft = strings.Contains(parsed.Revision, "~")
} else {
// Strip extension as a last-resort title.
stem := strings.TrimSuffix(name, filepath.Ext(name))
meta.Title = stem
}
apply := func(zf zddc.ZddcFile) {
if zf.Convert == nil {
return
}
if meta.Client == "" {
meta.Client = zf.Convert.Client
}
if meta.Project == "" {
meta.Project = zf.Convert.Project
}
if meta.Contractor == "" {
meta.Contractor = zf.Convert.Contractor
}
if meta.ProjectNumber == "" {
meta.ProjectNumber = zf.Convert.ProjectNumber
}
}
// Leaf → root.
for i := len(chain.Levels) - 1; i >= 0; i-- {
apply(chain.Levels[i])
}
apply(chain.Embedded)
return meta
}
// serveCached writes the cached file with the correct headers. ETag is
// derived from the source's mtime so a refresh changes it cleanly.
func serveCached(w http.ResponseWriter, r *http.Request, cacheAbs, format, base string) {
f, err := os.Open(cacheAbs)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer f.Close()
info, err := f.Stat()
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", contentTypeFor(format))
w.Header().Set("Content-Disposition", contentDispositionFor(format, base))
w.Header().Set("X-ZDDC-Source", "convert:"+format)
// http.ServeContent handles If-Modified-Since / Range / etc. and
// emits Last-Modified from info.ModTime(). The clients we ship
// don't issue conditional GETs for conversions today, but other
// callers might.
http.ServeContent(w, r, filepath.Base(cacheAbs), info.ModTime(), f)
}
func contentTypeFor(format string) string {
switch format {
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
case "html":
return "text/html; charset=utf-8"
case "pdf":
return "application/pdf"
}
return "application/octet-stream"
}
// contentDispositionFor returns the disposition header. HTML is served
// inline (so the browser renders the rich viewer template directly);
// DOCX and PDF are inline too but the browse client adds the anchor's
// `download` attribute, which forces save-as. Filename is the source
// stem + the target extension so the user gets `foo.docx`, not
// `foo.md.docx`.
func contentDispositionFor(format, base string) string {
return fmt.Sprintf(`inline; filename="%s.%s"`, base, format)
}
// purgeConverted removes the cached .converted/<base>.{docx,html,pdf}
// sidecars for an .md source. Called from the file API after a
// successful PUT/DELETE/MOVE so the next GET ?convert= regenerates.
// Best-effort: errors (including "directory doesn't exist") are
// swallowed. Non-.md sources are a no-op so this is safe to call
// unconditionally after any write.
func purgeConverted(srcAbs string) {
if !strings.HasSuffix(strings.ToLower(srcAbs), ".md") {
return
}
dir := filepath.Dir(srcAbs)
base := strings.TrimSuffix(filepath.Base(srcAbs), filepath.Ext(srcAbs))
for _, ext := range []string{".docx", ".html", ".pdf"} {
_ = os.Remove(filepath.Join(dir, ".converted", base+ext))
}
}
func mapConvertError(w http.ResponseWriter, err error, format string) {
if errors.Is(err, convert.ErrUnavailable) {
w.Header().Set("Retry-After", "60")
http.Error(w, "Service Unavailable — conversion runtime not available", http.StatusServiceUnavailable)
return
}
var ce *convert.ConvertError
if errors.As(err, &ce) {
// Timeout → 504. Non-zero exit with stderr → 422 with the
// stderr excerpt so the client can show a real message.
if ce.Cause != nil && errors.Is(ce.Cause, context.DeadlineExceeded) {
http.Error(w, "Gateway Timeout — conversion timed out", http.StatusGatewayTimeout)
return
}
msg := strings.TrimSpace(ce.Stderr)
if msg == "" {
msg = ce.Error()
}
if len(msg) > 1024 {
msg = msg[:1024]
}
http.Error(w, "Unprocessable Entity — "+msg, http.StatusUnprocessableEntity)
return
}
slog.Warn("convert: unexpected error", "format", format, "err", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}