console: PDF door to a platform Gotenberg
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+824
−0
cmd/console/main.go+18 −0cmd/console/pdf_test.go+25 −0internal/console/apipdf.go+314 −0internal/console/apipdf_test.go+424 −0internal/console/authcli.go+1 −0internal/console/claim_invariant_fixtures_test.go+15 −0internal/console/pdf_copy.go+18 −0internal/console/server.go+8 −0internal/console/testdata/claim-routes.txt+1 −0
CI failed — run details
diff --git a/cmd/console/main.go b/cmd/console/main.go| index a4d133646..95040e3b2 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -132,6 +132,7 @@ import ( |
| "log" |
| "math/rand/v2" |
| "net" |
| + "net/url" |
| "os" |
| "os/signal" |
| "path/filepath" |
| @@ -368,6 +369,10 @@ func serve() { |
| rec := new(perf.Recorder) |
| storeProvisioner, storeDeployment := storeBackend(rec) |
| storeScanner, seedAntivirus := storeScannerFor(storeDeployment) |
| + pdfAddr, err := pdfEngine(os.Getenv) |
| + if err != nil { |
| + log.Fatalf("console: %v", err) |
| + } |
| catalog, err := planCatalog() |
| if err != nil { |
| // A broken catalog must never quietly mean "no limits". |
| @@ -539,6 +544,7 @@ func serve() { |
| DomainCatalog: domainCatalog, |
| StoreProvisioner: storeProvisioner, |
| StoreScanner: storeScanner, |
| + PDFEngine: pdfAddr, |
| ScanSeedFromDeprecatedEnv: seedAntivirus, |
| ScanBudget: envDuration("CARLOS_STORE_SCAN_BUDGET", time.Minute), |
| ScanInterval: envDuration("CARLOS_STORE_SCAN_INTERVAL", 24*time.Hour), |
| @@ -2011,3 +2017,15 @@ func planCatalog() (*plans.Catalog, error) { |
| func regionIngress(getenv func(string) string) ([]string, error) { |
| return console.ParseRegionIngress(getenv("CONSOLE_REGION_INGRESS")) |
| } |
| + |
| +func pdfEngine(getenv func(string) string) (string, error) { |
| + addr := strings.TrimSpace(getenv("CARLOS_PDF_ADDR")) |
| + if addr == "" { |
| + return "", nil |
| + } |
| + u, err := url.Parse(addr) |
| + if err != nil || u.Scheme != "http" || u.Hostname() == "" { |
| + return "", fmt.Errorf("CARLOS_PDF_ADDR must be an http:// URL with a host") |
| + } |
| + return addr, nil |
| +} |
diff --git a/cmd/console/pdf_test.go b/cmd/console/pdf_test.go| new file mode 100644 |
| index 000000000..8d56b6a39 |
| --- /dev/null |
| +++ b/cmd/console/pdf_test.go |
| @@ -0,0 +1,25 @@ |
| +package main |
| + |
| +import "testing" |
| + |
| +func TestPDFEngineWiring(t *testing.T) { |
| + for _, tc := range []struct { |
| + value, want string |
| + invalid bool |
| + }{ |
| + {"", "", false}, {" ", "", false}, {" http://127.0.0.1:3000 ", "http://127.0.0.1:3000", false}, |
| + {"https://example.com", "", true}, {"http:///missing", "", true}, {"127.0.0.1:3000", "", true}, {"http://:3000", "", true}, |
| + } { |
| + t.Run(tc.value, func(t *testing.T) { |
| + got, err := pdfEngine(func(key string) string { |
| + if key != "CARLOS_PDF_ADDR" { |
| + t.Fatalf("unexpected env key %q", key) |
| + } |
| + return tc.value |
| + }) |
| + if (err != nil) != tc.invalid || got != tc.want { |
| + t.Fatalf("pdfEngine(%q) = %q, %v", tc.value, got, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/apipdf.go b/internal/console/apipdf.go| new file mode 100644 |
| index 000000000..bfa529847 |
| --- /dev/null |
| +++ b/internal/console/apipdf.go |
| @@ -0,0 +1,314 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/http/httputil" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "sync/atomic" |
| + "time" |
| +) |
| + |
| +var pdfRoutes = map[string]bool{ |
| + "forms/chromium/convert/html": true, |
| + "forms/chromium/convert/url": true, |
| + "forms/chromium/convert/markdown": true, |
| + "forms/chromium/screenshot/html": true, |
| + "forms/chromium/screenshot/url": true, |
| + "forms/chromium/screenshot/markdown": true, |
| + "forms/libreoffice/convert": true, |
| + "forms/pdfengines/merge": true, |
| + "forms/pdfengines/split": true, |
| + "forms/pdfengines/flatten": true, |
| + "forms/pdfengines/convert": true, |
| + "forms/pdfengines/metadata/read": true, |
| + "forms/pdfengines/metadata/write": true, |
| + "forms/pdfengines/encrypt": true, |
| + "forms/pdfengines/embed": true, |
| +} |
| + |
| +func pdfRoute(wild string) (string, bool) { |
| + if !pdfRoutes[wild] { |
| + return "", false |
| + } |
| + return wild, true |
| +} |
| + |
| +type pdfOutcome string |
| + |
| +const ( |
| + pdfRendered pdfOutcome = "rendered" |
| + pdfEngineError pdfOutcome = "engine_error" |
| + pdfRefused pdfOutcome = "refused" |
| + pdfAborted pdfOutcome = "aborted" |
| + pdfFailed pdfOutcome = "failed" |
| +) |
| + |
| +type pdfRenderRow struct { |
| + Account, App, Credential, Route string |
| + Outcome pdfOutcome |
| + Status int |
| + BytesIn, BytesOut int64 |
| + Duration time.Duration |
| + At time.Time |
| +} |
| + |
| +// Tasks 2 and 4 replace these admission stubs. |
| +type pdfLimiter struct{} |
| +type pdfRefusal struct { |
| + Status int |
| + RetryAfter int |
| + Msg string |
| +} |
| + |
| +func (*pdfLimiter) acquire(string, time.Time) (func(), *pdfRefusal) { return func() {}, nil } |
| +func (*Server) pdfPlanCheck(context.Context, *Account, time.Time) error { return nil } |
| + |
| +func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request) { |
| + _, acct, app, ok := s.apiAccountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + now := time.Now() |
| + clientCtx := r.Context() |
| + principal, _ := principalFrom(r.Context()) |
| + row := pdfRenderRow{Account: acct.Sqid, App: app, Credential: principal.Name, Route: r.PathValue("route"), Outcome: pdfRefused, At: now} |
| + out := &pdfResponseWriter{ResponseWriter: w} |
| + var input *pdfRequestBody |
| + defer func() { |
| + interrupted := recover() |
| + if interrupted != nil || clientCtx.Err() != nil { |
| + row.Outcome = pdfAborted |
| + } |
| + row.Status, row.BytesOut = out.status, out.bytes |
| + if input != nil { |
| + row.BytesIn = input.bytes.Load() |
| + } |
| + row.Duration = time.Since(now) |
| + // Recording must remain possible after the caller disconnects. |
| + s.recordPDF(context.WithoutCancel(clientCtx), row) |
| + if interrupted != nil { |
| + panic(interrupted) |
| + } |
| + }() |
| + if err := s.pdfPlanCheck(r.Context(), acct, now); err != nil { |
| + jsonError(out, http.StatusPaymentRequired, err.Error()) |
| + return |
| + } |
| + release, refusal := s.pdfLimiter.acquire(acct.Sqid, now) |
| + if refusal != nil { |
| + out.Header().Set("Retry-After", strconv.Itoa(refusal.RetryAfter)) |
| + jsonError(out, refusal.Status, refusal.Msg) |
| + return |
| + } |
| + defer release() |
| + |
| + // The mux decodes PathValue. Split the escaped path at the fixed route |
| + // prefix instead, so an escaped slash can never become an allowed route. |
| + parts := strings.SplitN(r.URL.EscapedPath(), "/", 8) |
| + raw := "" |
| + if len(parts) == 8 { |
| + raw = parts[7] |
| + } |
| + row.Route = raw |
| + route, ok := pdfRoute(raw) |
| + if !ok { |
| + jsonError(out, http.StatusNotFound, pdfText("pdf.unknown_route")) |
| + return |
| + } |
| + for name := range r.Header { |
| + if strings.HasPrefix(strings.ToLower(name), "gotenberg-webhook-") { |
| + jsonError(out, http.StatusBadRequest, pdfText("pdf.webhook")) |
| + return |
| + } |
| + } |
| + if s.cfg.PDFEngine == "" { |
| + jsonError(out, http.StatusServiceUnavailable, pdfText("pdf.unconfigured")) |
| + return |
| + } |
| + if r.ContentLength > 32<<20 { |
| + jsonError(out, http.StatusRequestEntityTooLarge, pdfText("pdf.too_large")) |
| + return |
| + } |
| + engine, err := url.Parse(s.cfg.PDFEngine) |
| + if err != nil || engine.Scheme != "http" || engine.Hostname() == "" { |
| + log.Printf("console: invalid PDF engine address") |
| + row.Outcome = pdfFailed |
| + jsonError(out, http.StatusBadGateway, pdfText("pdf.engine_down")) |
| + return |
| + } |
| + timeout := s.pdfTimeout |
| + if timeout <= 0 { |
| + timeout = 60 * time.Second |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), timeout) |
| + defer cancel() |
| + input = &pdfRequestBody{ReadCloser: http.MaxBytesReader(out, r.Body, 32<<20)} |
| + r = r.Clone(ctx) |
| + r.Body = input |
| + transport := http.DefaultTransport.(*http.Transport).Clone() |
| + transport.Proxy = nil |
| + transport.DisableCompression = true |
| + transport.ResponseHeaderTimeout = timeout |
| + defer transport.CloseIdleConnections() |
| + gateRefused := false |
| + proxy := &httputil.ReverseProxy{ |
| + Rewrite: func(pr *httputil.ProxyRequest) { |
| + pr.Out.URL = &url.URL{Scheme: engine.Scheme, Host: engine.Host, Path: "/" + route} |
| + pr.Out.Host = engine.Host |
| + pr.Out.Header = make(http.Header) |
| + for _, key := range []string{"Content-Type", "Content-Length", "Gotenberg-Output-Filename", "Gotenberg-Trace"} { |
| + if values := pr.In.Header.Values(key); len(values) != 0 { |
| + pr.Out.Header[key] = append([]string(nil), values...) |
| + } |
| + } |
| + // An absent User-Agent would make Transport add its own. |
| + pr.Out.Header["User-Agent"] = nil |
| + pr.Out.Trailer = nil |
| + pr.Out.Close = false |
| + }, |
| + Transport: pdfRoundTripper(func(req *http.Request) (*http.Response, error) { |
| + var resp *http.Response |
| + var engineErr error |
| + // A render is an outbound app operation. Settle the admission after |
| + // sending; streaming the answer makes no further engine requests. |
| + gateErr := s.claimAppMutation(req.Context(), acct, app, "pdf.render", func(ctx context.Context) error { |
| + resp, engineErr = transport.RoundTrip(req.WithContext(ctx)) |
| + return nil |
| + }) |
| + if gateErr != nil { |
| + gateRefused = true |
| + if resp != nil { |
| + resp.Body.Close() |
| + } |
| + return nil, gateErr |
| + } |
| + if resp != nil { |
| + // Transport fills trailers on its response at EOF. Give the |
| + // proxy a separate response so those headers stay private. |
| + filtered := *resp |
| + filtered.Trailer = nil |
| + resp = &filtered |
| + } |
| + return resp, engineErr |
| + }), |
| + ModifyResponse: func(resp *http.Response) error { |
| + pdfFilterResponseHeaders(resp.Header) |
| + resp.Trailer = nil |
| + resp.Body = &pdfResponseBody{ReadCloser: resp.Body, remaining: 64 << 20} |
| + row.Outcome = pdfEngineError |
| + if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| + row.Outcome = pdfRendered |
| + } |
| + return nil |
| + }, |
| + ErrorHandler: func(w http.ResponseWriter, req *http.Request, err error) { |
| + var tooLarge *http.MaxBytesError |
| + var network net.Error |
| + switch { |
| + case input.tooLarge.Load() || errors.As(err, &tooLarge): |
| + row.Outcome = pdfRefused |
| + jsonError(w, http.StatusRequestEntityTooLarge, pdfText("pdf.too_large")) |
| + case gateRefused: |
| + row.Outcome = pdfRefused |
| + jsonError(w, http.StatusBadGateway, pdfText("pdf.engine_down")) |
| + case r.Context().Err() == context.Canceled: |
| + row.Outcome = pdfAborted |
| + case errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &network) && network.Timeout()): |
| + row.Outcome = pdfFailed |
| + jsonError(w, http.StatusGatewayTimeout, pdfText("pdf.engine_timeout")) |
| + default: |
| + row.Outcome = pdfFailed |
| + jsonError(w, http.StatusBadGateway, pdfText("pdf.engine_down")) |
| + } |
| + }, |
| + } |
| + proxy.ServeHTTP(out, r) |
| +} |
| + |
| +type pdfRoundTripper func(*http.Request) (*http.Response, error) |
| + |
| +func (f pdfRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +type pdfRequestBody struct { |
| + io.ReadCloser |
| + bytes atomic.Int64 |
| + tooLarge atomic.Bool |
| +} |
| + |
| +func (b *pdfRequestBody) Read(p []byte) (int, error) { |
| + n, err := b.ReadCloser.Read(p) |
| + b.bytes.Add(int64(n)) |
| + var limit *http.MaxBytesError |
| + if errors.As(err, &limit) { |
| + b.tooLarge.Store(true) |
| + } |
| + return n, err |
| +} |
| + |
| +type pdfResponseBody struct { |
| + io.ReadCloser |
| + remaining int64 |
| +} |
| + |
| +func (b *pdfResponseBody) Read(p []byte) (int, error) { |
| + if len(p) == 0 { |
| + return 0, nil |
| + } |
| + if b.remaining == 0 { |
| + var probe [1]byte |
| + n, err := b.ReadCloser.Read(probe[:]) |
| + if n != 0 { |
| + return 0, errors.New("console: PDF response exceeds 64 MiB") |
| + } |
| + return 0, err |
| + } |
| + if int64(len(p)) > b.remaining { |
| + p = p[:b.remaining] |
| + } |
| + n, err := b.ReadCloser.Read(p) |
| + b.remaining -= int64(n) |
| + return n, err |
| +} |
| + |
| +type pdfResponseWriter struct { |
| + http.ResponseWriter |
| + status int |
| + bytes int64 |
| +} |
| + |
| +func (w *pdfResponseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| +func (w *pdfResponseWriter) WriteHeader(status int) { |
| + // ReverseProxy forwards informational responses before ModifyResponse. |
| + if status < 200 { |
| + pdfFilterResponseHeaders(w.Header()) |
| + } |
| + if status >= 200 && w.status == 0 { |
| + w.status = status |
| + } |
| + w.ResponseWriter.WriteHeader(status) |
| +} |
| +func (w *pdfResponseWriter) Write(p []byte) (int, error) { |
| + if w.status == 0 { |
| + w.WriteHeader(http.StatusOK) |
| + } |
| + n, err := w.ResponseWriter.Write(p) |
| + w.bytes += int64(n) |
| + return n, err |
| +} |
| + |
| +func pdfFilterResponseHeaders(header http.Header) { |
| + for key := range header { |
| + switch http.CanonicalHeaderKey(key) { |
| + case "Content-Type", "Content-Disposition", "Gotenberg-Trace": |
| + default: |
| + delete(header, key) |
| + } |
| + } |
| +} |
diff --git a/internal/console/apipdf_test.go b/internal/console/apipdf_test.go| new file mode 100644 |
| index 000000000..173f265be |
| --- /dev/null |
| +++ b/internal/console/apipdf_test.go |
| @@ -0,0 +1,424 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "mime/multipart" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httptrace" |
| + "net/textproto" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +const pdfHTMLRoute = "forms/chromium/convert/html" |
| + |
| +type pdfDoorFixture struct { |
| + *consoleFixture |
| + token string |
| + rows chan pdfRenderRow |
| +} |
| + |
| +func newPDFDoorFixture(t *testing.T, engine http.HandlerFunc) *pdfDoorFixture { |
| + t.Helper() |
| + addr := "" |
| + if engine != nil { |
| + ts := httptest.NewServer(engine) |
| + t.Cleanup(ts.Close) |
| + addr = ts.URL |
| + } |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{Tweak: func(cfg *Config) { cfg.PDFEngine = addr }}) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", serviceMinter, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows := make(chan pdfRenderRow, 32) |
| + fx.srv.recordPDF = func(_ context.Context, row pdfRenderRow) { rows <- row } |
| + return &pdfDoorFixture{fx, serviceToken(t, fx.st, OpsAccountID, "pdf", "shop", svcrole.Service), rows} |
| +} |
| + |
| +func (fx *pdfDoorFixture) request(t *testing.T, route string, body io.Reader, headers http.Header) *http.Response { |
| + t.Helper() |
| + return fx.requestAs(t, fx.sqid, "shop", fx.token, route, body, headers) |
| +} |
| + |
| +func (fx *pdfDoorFixture) requestAs(t *testing.T, account, app, token, route string, body io.Reader, headers http.Header) *http.Response { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/api/cli/apps/"+account+"/"+app+"/pdf/"+route, body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if headers != nil { |
| + req.Header = headers.Clone() |
| + } |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + client := &http.Client{Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { resp.Body.Close() }) |
| + return resp |
| +} |
| + |
| +func pdfWantError(t *testing.T, resp *http.Response, status int, key string) { |
| + t.Helper() |
| + data, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out map[string]string |
| + if err := json.Unmarshal(data, &out); err != nil { |
| + t.Fatalf("status %d body %q: %v", resp.StatusCode, data, err) |
| + } |
| + if resp.StatusCode != status || out["error"] != pdfCopy[key] { |
| + t.Fatalf("got %d %s, want %d %q", resp.StatusCode, data, status, pdfCopy[key]) |
| + } |
| +} |
| + |
| +func (fx *pdfDoorFixture) row(t *testing.T, outcome pdfOutcome, status int) pdfRenderRow { |
| + t.Helper() |
| + select { |
| + case row := <-fx.rows: |
| + if row.Outcome != outcome || row.Status != status { |
| + t.Fatalf("row = %+v, want %s/%d", row, outcome, status) |
| + } |
| + if row.Account != fx.sqid || row.App != "shop" || row.Credential != "pdf" || row.At.IsZero() || row.Duration <= 0 { |
| + t.Fatalf("incomplete row: %+v", row) |
| + } |
| + return row |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("no render row") |
| + return pdfRenderRow{} |
| + } |
| +} |
| + |
| +func TestPDFDoorForwardsAllowedRoute(t *testing.T) { |
| + var body bytes.Buffer |
| + form := multipart.NewWriter(&body) |
| + part, err := form.CreateFormFile("files", "index.html") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + io.WriteString(part, "<html><body>invoice</body></html>") |
| + if err := form.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantBody := append([]byte(nil), body.Bytes()...) |
| + type received struct { |
| + path, query, contentType string |
| + body []byte |
| + } |
| + got := make(chan received, 1) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + data, _ := io.ReadAll(r.Body) |
| + got <- received{r.URL.EscapedPath(), r.URL.RawQuery, r.Header.Get("Content-Type"), data} |
| + w.Header().Set("Content-Type", "application/pdf") |
| + w.Header().Set("Content-Disposition", `attachment; filename="invoice.pdf"`) |
| + w.Header().Set("Gotenberg-Trace", "render-trace") |
| + w.Header().Set("Set-Cookie", "engine-secret=yes") |
| + w.Header().Set("X-Engine-Internal", "secret") |
| + w.Header().Set("Trailer", "X-Engine-Trailer") |
| + io.WriteString(w, "%PDF-invoice") |
| + w.Header().Set("X-Engine-Trailer", "secret") |
| + }) |
| + resp := fx.request(t, pdfHTMLRoute+"?secret=drop", &body, http.Header{"Content-Type": {form.FormDataContentType()}}) |
| + data, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp.StatusCode != 200 || string(data) != "%PDF-invoice" || resp.Header.Get("Content-Type") != "application/pdf" || resp.Header.Get("Content-Disposition") != `attachment; filename="invoice.pdf"` || resp.Header.Get("Gotenberg-Trace") != "render-trace" { |
| + t.Fatalf("response = %d %v %q", resp.StatusCode, resp.Header, data) |
| + } |
| + if resp.Header.Get("Set-Cookie") != "" || resp.Header.Get("X-Engine-Internal") != "" || len(resp.Trailer) != 0 { |
| + t.Fatalf("engine headers leaked: %v / %v", resp.Header, resp.Trailer) |
| + } |
| + seen := <-got |
| + if seen.path != "/"+pdfHTMLRoute || seen.query != "" || seen.contentType != form.FormDataContentType() || !bytes.Equal(seen.body, wantBody) { |
| + t.Fatalf("engine request = %+v", seen) |
| + } |
| + row := fx.row(t, pdfOutcome("rendered"), 200) |
| + if row.Route != pdfHTMLRoute || row.BytesIn != int64(len(wantBody)) || row.BytesOut != int64(len(data)) { |
| + t.Fatalf("row = %+v", row) |
| + } |
| +} |
| + |
| +func TestPDFDoorRefusesUnlistedRoutes(t *testing.T) { |
| + var calls atomic.Int64 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + for _, route := range []string{"health", "version", "prometheus/metrics", "debug", "forms/chromium/convert/html/../../../health", "forms%2Fchromium%2Fconvert%2Fhtml", pdfHTMLRoute + "/", "forms//chromium/convert/html", "forms/chromium/convert/%68tml"} { |
| + t.Run(route, func(t *testing.T) { |
| + resp := fx.request(t, route, nil, nil) |
| + if strings.Contains(route, "..") || strings.Contains(route, "//") { |
| + if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| + t.Fatalf("unclean path returned %d", resp.StatusCode) |
| + } |
| + } else { |
| + pdfWantError(t, resp, 404, "pdf.unknown_route") |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatal("unlisted route reached engine") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPDFDoorRefusesWebhooks(t *testing.T) { |
| + var calls atomic.Int64 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + for _, name := range []string{"Gotenberg-Webhook-Url", "Gotenberg-Webhook-Error-Url", "gotenberg-webhook-method"} { |
| + pdfWantError(t, fx.request(t, pdfHTMLRoute, nil, http.Header{name: {"https://example.com/x"}}), 400, "pdf.webhook") |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatal("webhook reached engine") |
| + } |
| +} |
| + |
| +func TestPDFDoorStripsOtherGotenbergHeaders(t *testing.T) { |
| + got := make(chan http.Header, 1) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { got <- r.Header.Clone() }) |
| + headers := http.Header{"Gotenberg-Output-Filename": {"invoice"}, "Gotenberg-Trace": {"trace"}, "Gotenberg-Foo": {"drop"}, "Cookie": {"session=secret"}, "X-Forwarded-For": {"10.0.0.1"}, "Forwarded": {"for=secret"}, "Accept-Encoding": {"gzip"}, "User-Agent": {"caller"}} |
| + resp := fx.request(t, pdfHTMLRoute, nil, headers) |
| + io.Copy(io.Discard, resp.Body) |
| + seen := <-got |
| + if seen.Get("Gotenberg-Output-Filename") != "invoice" || seen.Get("Gotenberg-Trace") != "trace" { |
| + t.Fatalf("allowed headers lost: %v", seen) |
| + } |
| + for _, key := range []string{"Gotenberg-Foo", "Authorization", "Cookie", "X-Forwarded-For", "Forwarded", "Accept-Encoding", "User-Agent"} { |
| + if seen.Get(key) != "" { |
| + t.Errorf("%s leaked: %v", key, seen) |
| + } |
| + } |
| +} |
| + |
| +type pdfGeneratedBytes struct{} |
| + |
| +func (pdfGeneratedBytes) Read(p []byte) (int, error) { |
| + for i := range p { |
| + p[i] = 'x' |
| + } |
| + return len(p), nil |
| +} |
| + |
| +func TestPDFDoorBodyLimit(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) }) |
| + resp := fx.request(t, pdfHTMLRoute, io.LimitReader(pdfGeneratedBytes{}, 33<<20), nil) |
| + pdfWantError(t, resp, 413, "pdf.too_large") |
| + fx.row(t, pdfOutcome("refused"), 413) |
| +} |
| + |
| +func TestPDFDoorUnconfigured(t *testing.T) { |
| + fx := newPDFDoorFixture(t, nil) |
| + pdfWantError(t, fx.request(t, pdfHTMLRoute, nil, nil), 503, "pdf.unconfigured") |
| + fx.row(t, pdfOutcome("refused"), 503) |
| +} |
| + |
| +func TestPDFDoorEngineDown(t *testing.T) { |
| + engine := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) |
| + engine.Close() |
| + fx := newPDFDoorFixture(t, nil) |
| + fx.srv.cfg.PDFEngine = engine.URL |
| + pdfWantError(t, fx.request(t, pdfHTMLRoute, nil, nil), 502, "pdf.engine_down") |
| + fx.row(t, pdfOutcome("failed"), 502) |
| +} |
| + |
| +func TestPDFDoorEngineTimeout(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { time.Sleep(150 * time.Millisecond) }) |
| + fx.srv.pdfTimeout = 50 * time.Millisecond |
| + pdfWantError(t, fx.request(t, pdfHTMLRoute, nil, nil), 504, "pdf.engine_timeout") |
| + fx.row(t, pdfOutcome("failed"), 504) |
| +} |
| + |
| +func TestPDFDoorOtherAppOrAccount(t *testing.T) { |
| + var calls atomic.Int64 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "blog", serviceMinter, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := theirAccount(t, fx.consoleFixture) |
| + foreign := serviceToken(t, fx.st, other.ID, "foreign", "", svcrole.Admin) |
| + for _, tc := range []struct{ app, token string }{{"blog", fx.token}, {"shop", foreign}} { |
| + resp := fx.requestAs(t, fx.sqid, tc.app, tc.token, pdfHTMLRoute, nil, nil) |
| + data, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 404 || string(data) != "404 page not found\n" { |
| + t.Fatalf("scope refusal = %d %q", resp.StatusCode, data) |
| + } |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatal("foreign token reached engine") |
| + } |
| +} |
| + |
| +func TestPDFDoorResponseLimit(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/pdf") |
| + io.CopyN(w, pdfGeneratedBytes{}, 65<<20) |
| + }) |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + n, err := io.Copy(io.Discard, resp.Body) |
| + if err == nil || n != 64<<20 { |
| + t.Fatalf("output = %d bytes, err %v; want 64 MiB then abort", n, err) |
| + } |
| + row := fx.row(t, pdfOutcome("aborted"), 200) |
| + if row.BytesOut != n { |
| + t.Fatalf("row bytes = %d, sent %d", row.BytesOut, n) |
| + } |
| +} |
| + |
| +func TestPDFDoorEngineErrorPassesThrough(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(400) |
| + io.WriteString(w, "engine rejected fixture") |
| + }) |
| + resp := fx.request(t, pdfHTMLRoute, nil, nil) |
| + data, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != 400 || string(data) != "engine rejected fixture" { |
| + t.Fatalf("engine error = %d %q", resp.StatusCode, data) |
| + } |
| + fx.row(t, pdfOutcome("engine_error"), 400) |
| +} |
| + |
| +func TestPDFDoorAllowedRoutes(t *testing.T) { |
| + for _, route := range []string{ |
| + "forms/chromium/convert/html", "forms/chromium/convert/url", "forms/chromium/convert/markdown", |
| + "forms/chromium/screenshot/html", "forms/chromium/screenshot/url", "forms/chromium/screenshot/markdown", |
| + "forms/libreoffice/convert", "forms/pdfengines/merge", "forms/pdfengines/split", "forms/pdfengines/flatten", |
| + "forms/pdfengines/convert", "forms/pdfengines/metadata/read", "forms/pdfengines/metadata/write", "forms/pdfengines/encrypt", "forms/pdfengines/embed", |
| + } { |
| + if got, ok := pdfRoute(route); !ok || got != route { |
| + t.Errorf("pdfRoute(%q) = %q, %v", route, got, ok) |
| + } |
| + } |
| + if len(pdfRoutes) != 15 { |
| + t.Fatalf("route count = %d", len(pdfRoutes)) |
| + } |
| +} |
| + |
| +func TestPDFDoorExactLimits(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + n, err := io.Copy(io.Discard, r.Body) |
| + if err != nil || n != 32<<20 { |
| + t.Errorf("engine body = %d, %v", n, err) |
| + } |
| + w.Header().Set("Content-Type", "application/pdf") |
| + io.CopyN(w, pdfGeneratedBytes{}, 64<<20) |
| + }) |
| + resp := fx.request(t, pdfHTMLRoute, io.LimitReader(pdfGeneratedBytes{}, 32<<20), nil) |
| + n, err := io.Copy(io.Discard, resp.Body) |
| + if resp.StatusCode != 200 || err != nil || n != 64<<20 { |
| + t.Fatalf("boundary response = %d, %d bytes, %v", resp.StatusCode, n, err) |
| + } |
| + row := fx.row(t, pdfOutcome("rendered"), 200) |
| + if row.BytesIn != 32<<20 || row.BytesOut != 64<<20 { |
| + t.Fatalf("boundary row = %+v", row) |
| + } |
| +} |
| + |
| +func TestPDFDoorClientGone(t *testing.T) { |
| + started := make(chan struct{}) |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + close(started) |
| + <-r.Context().Done() |
| + }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/pdf/"+pdfHTMLRoute, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+fx.token) |
| + finished := make(chan error, 1) |
| + go func() { |
| + resp, err := http.DefaultClient.Do(req) |
| + if resp != nil { |
| + resp.Body.Close() |
| + } |
| + finished <- err |
| + }() |
| + select { |
| + case <-started: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("engine never started") |
| + } |
| + cancel() |
| + select { |
| + case err := <-finished: |
| + if err == nil { |
| + t.Fatal("cancelled request succeeded") |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("client did not stop") |
| + } |
| + fx.row(t, pdfOutcome("aborted"), 0) |
| +} |
| + |
| +func TestPDFDoorRoleGate(t *testing.T) { |
| + var calls atomic.Int64 |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) }) |
| + instance := serviceToken(t, fx.st, OpsAccountID, "instance", "shop", svcrole.Instance) |
| + admin := serviceToken(t, fx.st, OpsAccountID, "admin", "shop", svcrole.Admin) |
| + for _, tc := range []struct { |
| + token string |
| + status int |
| + }{{"", 401}, {instance, 403}, {admin, 200}} { |
| + resp := fx.requestAs(t, fx.sqid, "shop", tc.token, pdfHTMLRoute, nil, nil) |
| + io.Copy(io.Discard, resp.Body) |
| + if resp.StatusCode != tc.status { |
| + t.Fatalf("role gate = %d, want %d", resp.StatusCode, tc.status) |
| + } |
| + } |
| + if calls.Load() != 1 { |
| + t.Fatalf("engine calls = %d, want only admin", calls.Load()) |
| + } |
| +} |
| + |
| +func TestPDFDoorFiltersInformationalHeaders(t *testing.T) { |
| + fx := newPDFDoorFixture(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Set-Cookie", "engine-secret=yes") |
| + w.Header().Set("Gotenberg-Trace", "trace") |
| + w.WriteHeader(http.StatusEarlyHints) |
| + w.WriteHeader(http.StatusOK) |
| + }) |
| + hints := make(chan http.Header, 1) |
| + ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{ |
| + Got1xxResponse: func(code int, h textproto.MIMEHeader) error { |
| + if code == http.StatusEarlyHints { |
| + hints <- http.Header(h).Clone() |
| + } |
| + return nil |
| + }, |
| + }) |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/shop/pdf/"+pdfHTMLRoute, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+fx.token) |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + io.Copy(io.Discard, resp.Body) |
| + select { |
| + case h := <-hints: |
| + if h.Get("Set-Cookie") != "" { |
| + t.Fatalf("informational headers leaked: %v", h) |
| + } |
| + case <-time.After(time.Second): |
| + t.Fatal("missing informational response") |
| + } |
| +} |
| + |
| +func TestPDFDoorClaimGate(t *testing.T) { |
| + door := claimFixtures["route POST /api/cli/apps/{account}/{app}/pdf/{route...}"].door |
| + problems, _ := runClaimDoor(t, door) |
| + for _, problem := range problems { |
| + t.Error(problem) |
| + } |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index 6c4607db8..a60d22049 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1089,6 +1089,7 @@ func (s *Server) registerCLIRoutes() { |
| // And reading the answer back (spec §5.2), same role and same reasoning: |
| // an app asking about its own object. |
| s.cliRoute("GET /api/cli/apps/{account}/{app}/store/scan/object", svcrole.Allow(svcrole.Service), s.handleAPIScanObject) |
| + s.cliRoute("POST /api/cli/apps/{account}/{app}/pdf/{route...}", svcrole.Allow(svcrole.Service), s.handleAPIPDF) |
| // The relay family (internal/console/apirelay.go, relay spec §5): the |
| // platform STUN/TURN relay's app-facing doors. enable/status/disable are |
| // the member's own verbs — declaring, inspecting and ending the app's own |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index ae025c3d4..aff05656e 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -24,6 +24,7 @@ import ( |
| "errors" |
| "fmt" |
| "net/http" |
| + "net/http/httptest" |
| "net/url" |
| "strconv" |
| "strings" |
| @@ -2107,6 +2108,20 @@ var claimFixtures = map[string]claimFixture{ |
| setup: func(t *testing.T, cx *claimCase) { cx.scanGranted(t) }, |
| do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/store/scan/sweep", `{}`), |
| }}, |
| + "route POST /api/cli/apps/{account}/{app}/pdf/{route...}": {door: &claimDoor{ |
| + apps: claimRefs("bab/shop"), |
| + setup: func(t *testing.T, cx *claimCase) { |
| + cx.enroll(t, "bab", "shop") |
| + engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cx.rec.add(claimRawEvent{Surface: "http", Method: r.Method, Key: r.URL.String(), Unscoped: true}) |
| + w.Header().Set("Content-Type", "application/pdf") |
| + _, _ = w.Write([]byte("%PDF-fixture")) |
| + })) |
| + t.Cleanup(engine.Close) |
| + cx.srv.cfg.PDFEngine = engine.URL |
| + }, |
| + do: claimAPI(http.MethodPost, "/api/cli/apps/bab/shop/pdf/forms/chromium/convert/html", "fixture"), |
| + }}, |
| "route POST /api/cli/apps/{account}/{app}/store/scan/object": {door: &claimDoor{ |
| apps: claimRefs("bab/titogo"), |
| setup: func(t *testing.T, cx *claimCase) { cx.scanGranted(t) }, |
diff --git a/internal/console/pdf_copy.go b/internal/console/pdf_copy.go| new file mode 100644 |
| index 000000000..fdc091612 |
| --- /dev/null |
| +++ b/internal/console/pdf_copy.go |
| @@ -0,0 +1,18 @@ |
| +package console |
| + |
| +import "fmt" |
| + |
| +// Approved in docs/superpowers/notes/pdf-service-copy-deck.md. |
| +var pdfCopy = map[string]string{ |
| + "pdf.unconfigured": "no PDF engine is configured for this deployment (CARLOS_PDF_ADDR)", |
| + "pdf.unknown_route": "that is not a PDF route. the PDFs docs page lists the routes this door carries", |
| + "pdf.webhook": "webhooks are not available here. send the PDF request without a webhook header", |
| + "pdf.too_large": "the request is over 32 MiB. send a smaller request", |
| + "pdf.busy_account": "this account already has %d PDFs rendering. wait for one to finish and try again", |
| + "pdf.rate": "this account has asked for more than %d PDFs in a minute. try again in %d seconds", |
| + "pdf.busy_engine": "the PDF engine is busy. try again in a few seconds", |
| + "pdf.engine_down": "the PDF engine did not answer. try again shortly", |
| + "pdf.engine_timeout": "the PDF engine took more than 60 seconds and was stopped. try again", |
| +} |
| + |
| +func pdfText(key string, args ...any) string { return fmt.Sprintf(pdfCopy[key], args...) } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 1883966c3..a2caab8aa 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -777,6 +777,8 @@ type Config struct { |
| // engine released before its bucket goes, so a nil scanner over an enabled |
| // record is a refusal rather than a skip. |
| StoreScanner objstore.Scanner |
| + // PDFEngine is the Gotenberg base URL; empty disables the PDF door. |
| + PDFEngine string |
| // ScanSeedFromDeprecatedEnv says the retired CARLOS_STORE_SCANNER supplied |
| // this deployment's clamd address. The first scan-pass tick then seeds |
| // system/antivirus.json enabled, once, carrying forward an intent the |
| @@ -980,6 +982,9 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| + pdfTimeout time.Duration |
| + pdfLimiter *pdfLimiter |
| + recordPDF func(context.Context, pdfRenderRow) |
| purchaseWake chan struct{} |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| @@ -1750,6 +1755,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| } |
| km.SetSigningKey(key) |
| s := &Server{ |
| + pdfTimeout: 60 * time.Second, |
| + pdfLimiter: &pdfLimiter{}, |
| + recordPDF: func(context.Context, pdfRenderRow) {}, |
| purchaseWake: make(chan struct{}, 1), |
| jobs: newJobRegistry(time.Now), |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 46cfd744c..5bafac76a 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -279,6 +279,7 @@ route POST /api/cli/apps/{account}/{app}/keep |
| route POST /api/cli/apps/{account}/{app}/ledgers/publish |
| route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/append |
| route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/blobs |
| +route POST /api/cli/apps/{account}/{app}/pdf/{route...} |
| route POST /api/cli/apps/{account}/{app}/place |
| route POST /api/cli/apps/{account}/{app}/promote |
| route POST /api/cli/apps/{account}/{app}/regions/guess |