Code review · pdf-signoff 0.1.0

PDF Signoff Code Review

A disciplined codebase. Twelve findings, all at its edges — the CLI contract, profile reuse, and what the tool tells you when something goes wrong.

Reviewed 2026-09-07 Branch master at cf961c0 739 statements · ~1.2k lines frontend
pytest
213 passed
coverage
100.00%
ruff check
clean
ruff format
24 files ok
mypy
10 files ok

What this review found

The gate checks above all pass on the current tree, and that is a fair summary of the code itself. Module boundaries are real rather than nominal: coordinate conversion lives in exactly one place, the output commit is genuinely transactional, the review server refuses to bind off-loopback, and the L0 stamping path validates the physical aspect ratio of every rectangle against the PNG rather than silently distorting it. The security posture documented in the README is the posture the code actually implements.

So the findings below are not about the core. Eleven of the twelve sit at the boundary between the tool and the person or agent driving it: an option that is ignored instead of refused, a config key that validates but does nothing, an error message that tells you nothing, a Save button that goes dead without saying why. For a utility whose stated product API is its command line and whose stated audience is unattended agents, that boundary is the product.

One finding (PS‑01) is worth acting on before the next release. Each finding is filed as a Backlog task; the ID is on the right of every row.

Findings

Ordered by severity. Nine were reproduced against the working tree; three are read from the source and marked accordingly.

PS-01 High ● Reproduced TASK-002

A mistyped option is discarded, and --auto quietly becomes review mode

pdf_signoff/cli.py:72–77 · context_settings

The command sets ignore_unknown_options and allow_extra_args so Onacol can consume nested config options like --general--log-level. The side effect is that any token Onacol does not recognise is thrown away without a diagnostic.

Because --autoo never sets automatic, the run falls through to interactive review, opens a loopback server, and blocks in session.wait_for_result() until killed. In the unattended agent workflow this tool is built for, one mistyped character turns a headless signing run into a process that hangs forever.

$ pdf-signoff t.pdf --signature sig.png \
      --autoo --no-such-flag --open-browser false --output o1.pdf

(no error, no warning; process blocks in review mode
 until SIGTERM at 120s)
Fix

Check leftover ctx.args against the Onacol schema before any PDF inspection runs, and raise UsageError naming the offending token. Keep nested options working; refuse everything else.

PS-02 Medium ● Reproduced TASK-003

Profile matching only checks the pages the profile chose to list

pdf_signoff/inspection.py:184 · pdf_signoff/profile.py:69

validate_profile_match iterates profile.match.pages. Nothing requires that list to cover every page, to be free of duplicates, or to include the pages the placements actually reference. A profile can declare page_count: 2, describe page 1, and place its signature on page 2 — whose CropBox size and rotation are then never compared to the document.

Profiles the tool emits always list every page, so this only reaches hand-edited or truncated input. But rotation changes how a normalized placement maps onto the page, and the README promises the profile is checked against the PDF before reuse.

Document: page 1 = 595 x 842 pt, page 2 = 842 x 595 pt

Profile: page_count 2, match.pages = [page 1 only]
         placements  = [{ "page": 2, ... }]

  -> page 2 geometry NEVER validated -> accepted
  -> duplicate page-1 entries        -> accepted
Fix

In MatchSpec.validate_page_references, require match.pages to describe pages 1…page_count exactly once — or, at minimum, require every placement's page to appear in the list.

PS-03 Medium ● Reproduced TASK-004

general.log_level validates, changes the config, and does nothing

pdf_signoff/default_config.yaml:1–7 · spec §21 · README §Configuration

The specification requires Python logging directed to stderr. The bundled config exposes general.log_level with a DEBUG…CRITICAL schema, and the README documents --general--log-level DEBUG as a worked example. No code reads the value.

Every diagnostic goes through click.echo(..., err=True) at fixed verbosity, and the only logging call in the package is one hard-coded error in ReviewServer.stop. This is worse than not offering the knob, because it is the first thing an operator reaches for when a signing run fails.

$ grep -rn "log_level" pdf_signoff/
pdf_signoff/default_config.yaml:2:  log_level:

# no basicConfig, no setLevel, no read of
# config["general"]["log_level"] anywhere in the package
Fix

Decide one way. Either wire the level into a real logging setup — never emitting the session token or the PKCS#12 password at DEBUG, and never touching stdout — or drop the option from the schema, README, and spec.

PS-04 Medium ○ From source TASK-005

An expired certificate and a full disk produce the same message

pdf_signoff/crypto.py:56–57 · pdf_signoff/cli.py:203–216

L1Signer.sign catches every exception from pyHanko and re-raises L1SigningError("Cryptographic PDF signing failed."). main renders only str(exc) through ClickException, so that one sentence is the entire operator-facing account of the failure.

The secret-safety instinct is right and should be kept — pyHanko messages can name credential paths and signer details. But exception types are not secrets, and without them a failed L1 run cannot be diagnosed from the terminal at all.

except Exception as exc:
    raise L1SigningError("Cryptographic PDF signing failed.") from exc

# cause is chained, but ClickException prints str(exc) only,
# so the chain never reaches the operator
Fix

Report the cause category — credential, certificate, PDF structure, I/O — while keeping the password and key material out of every stream. The chained cause pairs naturally with whatever PS‑03 settles for verbosity.

PS-05 Medium ○ From source TASK-006

Reviewing a profile made with a different signature leaves Save permanently dead

frontend/src/placement.ts:192 · frontend/src/placement.ts:49 · frontend/src/App.vue:40

isPlacementStateValid requires every placement to sit within 5% of the current PNG aspect ratio, and applies that to placements preloaded from --coords exactly as to freshly drawn ones. initializePlacements copies the stored width and height verbatim rather than re-deriving the height from the current image.

Load a profile whose signature had a different shape and canSave is false forever. Nothing on screen says so: the status line shows no message, and the user is looking at a rendered document with visible signatures on it and a button that does nothing.

Fix

Either re-derive preloaded heights from the current PNG on load, or keep the strict check and name the inconsistent pages on screen. Save should never be disabled without a visible reason.

PS-06 Low ○ From source TASK-007

The review UI reports the wrong error, and sometimes hides it

frontend/src/App.vue:53 · frontend/src/App.vue:181–186

reportError discards its argument and always sets “Unable to load the review session.” It is wired to the error event from PdfDocument and PdfPage, so a mid-session canvas render failure reports a misleading load error.

Separately, the status line branches saved, then saving, then placeMode, and only then errorMessage. Any error raised while place mode is active is rendered invisible by the earlier branch.

Fix

Distinguish load, per-page render, and save failures, and give the error its own slot so place mode cannot suppress it.

PS-07 Low ● Reproduced TASK-008

Published PDFs inherit mkstemp's 0600, not the umask

pdf_signoff/output.py:71–91

write_output_atomically stages through tempfile.mkstemp, which creates at 0600. Neither os.replace nor os.link changes the mode, so the signed PDF keeps 0600 and ignores the process umask.

Restrictive permissions on a signed document are defensible and may be the intent — but nothing in the code, README, or spec records the choice, so it currently reads as an artifact of mkstemp. It is a surprise when the output feeds a shared directory or another service account, which is a realistic shape for these workflows.

write_output_atomically(out, lambda p: p.write_bytes(b"%PDF-1.4\n"))

expected under default umask: 0644
actual mode:                  0o600
Fix

Choose the permission model deliberately, apply it explicitly in the staging path, and state it in the README where the output commit is described.

PS-08 Low ● Reproduced TASK-009

Route handlers read the session's private attributes

pdf_signoff/server.py:335 · pdf_signoff/server.py:339

/api/document and /api/signature read session._input_pdf and session._signature_png directly. ReviewSession otherwise keeps a deliberate private boundary, offering token, is_active, and metadata as its public surface; these two reads are the only crossings.

A small change — but those private names are precisely the state deciding which files the server will hand to a browser, so the contract is worth keeping inside the class.

Fix

Add read-only properties for the two paths and use them from the routes.

PS-09 Low ● Reproduced TASK-010

A published CLI with no way to ask which version it is

pdf_signoff/cli.py:72–138 · pdf_signoff/__init__.py:6

The console script has no --version. __version__ exists and the package is on PyPI, but an installed binary cannot report itself.

Every emitted placement profile and every signed PDF is the output of a specific build, and the stated audience is agents capturing that output into a workflow. Recording provenance currently means inspecting the Python environment instead of asking the tool.

Fix

Add an eager --version that reads installed package metadata — not a second hard-coded literal — and exits before the required arguments are enforced.

PS-10 Low ● Reproduced TASK-011

Hardening gap: no CSP, no framing policy, no Host allowlist

pdf_signoff/server.py:501–504 · _harden

_harden sets Cache-Control: no-store and X-Content-Type-Options: nosniff and nothing else. There is no Content-Security-Policy, no framing restriction, and the middleware never compares the Host header to the address it bound to.

To be clear about severity: the 256-bit session token is what actually stops unrelated pages and DNS-rebinding attempts, and it does that job — a rebound origin carries no cookie for 127.0.0.1. This is defence in depth, not a live hole. But the page renders an arbitrary user-supplied PDF through PDF.js, every asset is first-party and bundled, and the app loads nothing from the network, so a strict policy costs nothing and matches the posture the README already claims.

Fix

Send a same-origin-only policy with frame-ancestors 'none', and reject requests whose Host is not the bound address. Confirm PDF.js, its worker module, and the signature image still load under the Playwright end-to-end run.

PS-11 Low ● Reproduced TASK-012

Every page decodes and rasterises at mount, with no ceiling

frontend/src/components/PdfDocument.vue:59 · frontend/src/components/PdfPage.vue:148

PdfDocument renders v-for="page in pageCount", and each PdfPage calls getPage on mount and rasterises to a canvas at up to twice the device pixel ratio. There is no virtualisation and no page-count ceiling.

For the short forms the spec targets this is fine and arguably preferable. At a few hundred pages it allocates a few hundred full-resolution canvases during mount, and nothing warns, degrades, or refuses.

Fix

Render lazily — but note the coupling: isPlacementStateValid needs a page size for every placement page, so any lazy scheme must still supply sizes for pages never rasterised, or Save silently stops working.

PS-12 Low ● Reproduced TASK-013

An unrelated npm advisory can block a tagged release

.github/workflows/release.yml · .github/workflows/ci.yml

Both workflows run bare npm audit, which exits non-zero on an advisory of any severity anywhere in the transitive dev tree.

In the release workflow this sits ahead of the build, publish, and GitHub Release jobs. A newly published low-severity advisory in a build-time dependency fails a tagged release with no change to this codebase — and recovery then needs a new version and a new tag, because the release guide correctly forbids reusing a failed one.

Fix

Pass an explicit --audit-level in both workflows and record the threshold, plus the handling of a real breach, in release_guide.md.

Checked and found sound

Areas examined in detail that produced no finding. Recorded so the next review does not repeat the work.

Atomic output commit

Same-directory staging, os.replace under --overwrite and os.link without it, so a destination created by another process mid-signing is not clobbered. Temp file cleaned on every path.

Session token handling

256-bit token_urlsafe, compare_digest comparison, bootstrap redirect that strips the token from the address bar, HttpOnly + SameSite=Strict cookie, access log disabled.

Coordinate conversion

One module, one function. Displayed CropBox to PDF rect via derotation_matrix, honouring non-zero page-box origins. No duplicate transform logic in the stamping path.

Aspect-ratio enforcement

Physical rectangle ratio checked against PNG ratio within 5% on both sides of the wire, before stamping and in the browser. Hand-edited profiles are refused rather than distorted.

Save-state machine

active → saving → saved under a lock, reverting to active on failure so a rejected save is retryable. finish_save runs as a background task, after the response is flushed.

Dependency provenance

httpx2 in the dev group reads like a typosquat; it is not. It is the Pydantic-maintained httpx successor, correctly pinned and hash-locked in uv.lock.

Blocking work off the event loop

POST /api/save is a sync def, so Starlette runs the stamping and pyHanko signing in the threadpool rather than stalling the loop.

Release workflow shape

Tag/version equality enforced, PyPI via OIDC Trusted Publishing with no long-lived token, committed web_dist verified against a fresh build, wheel smoke-tested before publish.

Where to start

Take PS‑01 first and alone — it is small, it is the only finding that can hang an agent workflow indefinitely, and it changes the CLI contract, so it wants its own release note.

Then PS‑03 and PS‑04 together: deciding what happens to general.log_level settles where L1's chained cause should surface, and doing them separately means doing the second one twice. PS‑02 is independent and self-contained. PS‑05 and PS‑06 are both frontend and both about telling the user what is wrong, so they pair naturally.

The remaining six are genuine housekeeping and can ride along with whatever else touches those files — with one caveat: PS‑11 and PS‑05 touch the same validity rule, so whichever lands second should re-check the other's tests.

Reviewed against master at cf961c0 with the working tree's uncommitted changes to docs/pdf-sign-implementation-spec.md and backlog/tasks/task-001.13 in place. Findings marked Reproduced were confirmed by running the code or a probe against it; those marked From source are read from the code and not executed. Filed as Backlog tasks TASK-002 through TASK-013, all To Do, labelled code-review.