commit 78bca55c0c7e1d39c6a52418558fb81971581a28
parent b820eccad501830294647373b77d5faf9c36c366
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 06:37:51 +0530
parent b820eccad501830294647373b77d5faf9c36c366
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 06:37:51 +0530
Integrate frozen revision inputs and replay-stable proofs
23 files changed, 1138 insertions(+), 256 deletions(-)
A
|
112
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
221
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.gitattributes b/.gitattributes @@ -0,0 +1,4 @@ +# Keep generated fixtures and font assets byte-identical on every checkout. +*.png -text +*.pdf -text +*.ttf -text
diff --git a/.scratch/roadmap/spec.md b/.scratch/roadmap/spec.md @@ -2,6 +2,11 @@ Recorded 2026-11-10 after source/documentation reconciliation. +Integration status2026-11-12: tickets10–13 have isolated application evidence; +ticket14 remains an incomplete native/trust/resource release gate. Baseline +missing-header descriptions below are historical; ticket13 now fails closed. +Owner customer-signing considerations do not expand this approved scope. + ## Priority decision The owner raised authentication work as an impediment to feature implementation. @@ -78,6 +83,10 @@ on both pages. No API reads of `sig_dir` or synchronous API release remain. ## 3. Freeze submit-time content — ticket 12 +Completed2026-11-12: implementation, mutation/replay/browser/visual evidence and +resource-measurement limits in `ticket-12.md`. Native production acceptance is +not implied. The original scope follows. + Depends on ticket 11 in this implementation sequence. - Resolve and persist organisation PIM text/image references at submit. @@ -98,6 +107,9 @@ measure resource use against the under-60-MB Signet RSS budget. ## 4. Harden identity handling — ticket 13 (deferred release blocker) +Completed2026-11-12 on the integration branch; both-API/role/header remapping +and environment-backdoor evidence in `ticket-13.md`. Proxy trust remains ticket14. + Not a prerequisite for tickets 10–12. Schedule before deployment verification. - Remove the unconditional missing-header admin/group fallback.
diff --git a/.scratch/roadmap/ticket-12.md b/.scratch/roadmap/ticket-12.md @@ -0,0 +1,112 @@ +# Ticket 12 — frozen submit-time revision content + +Implemented in feat/signet-ticket12, integrating independently completed +fail-closed identity (ticket13). Accepted domain model unchanged. No production +or maa-1 access/service changes. Owner's CONSIDERATIONS.md was read in full; +customer signing remains a discussion handoff, not new implementation scope. + +## Implementation + +- The submit transaction locks the editable document, validates layout/route, + obtains a new server UUID and freezes inputs before accepting the revision. + One bounded atomic Redis EVAL reads only referenced organisation attributes. + Clients still provide references; client-supplied values are overwritten. +- Private snapshot-<UUID>/ directories hold copied DAM bytes (not hard links to + mutable assets), asset hashes and an immutable manifest.json for every revision. + Current snapshot_id/snapshot_json are stored in PostgreSQL. Corrections point + at a new snapshot; previous resolved metadata/assets remain available privately. +- Fonts, including the audit/default font, images and date format are frozen. + Every DAM path component is opened without following symlinks; only regular + files are accepted. Copying streams through16KB, rejects concurrent in-place + modification and limits aggregate copied assets to16MiB. Referenced PIM strings + are bounded to1023bytes, reject embedded NULs, and text plus prefix must fit the + existing1024-byte render buffer rather than silently truncate. +- Files and containing directories are synced before commit, with final read-only + modes set before fsync: assets/manifests0440, directories0550, shared-group read. + Regression tests assert the actual permissions. Known transaction rollback + removes newly created inputs. An ambiguous COMMIT retains files: deleting + potentially committed inputs would be data loss. Orphan inventory/retention + remains an explicit operational responsibility. +- Renderer context has no Redis connection, organisation lookup, live DAM path + or config font lookup. It consumes only server-resolved text and frozen asset + names. The worker verifies hashes; missing/damaged inputs fail closed, never + falling back to current PIM/DAM values. +- One successful flatten is cached privately as proof-<UUID>.pdf. Public proof + links it; initial stamped input is byte-identical. Database completion failure + and recovery reuse the cache without running the flatten again. Subsequent + sign-offs only overlay facsimiles on the committed body; release reads the + revision's frozen audit font. Only signetd reads sig_dir. +- Additive migration001 and upgrade/backup/recovery notes live under + sql/migrations/. Legacy pending revisions are not silently backfilled from + current values: drain them before upgrade or arrange authorised correction/ + recreation and new sign-offs. New workers refuse unfrozen legacy inputs. + +Clean-worktree verification also found packaging issues: the verified ticket11 +JS/CSS had not reached the initial baseline commit; commit b97f77a restores those +exact tested bytes without modifying the original checkout. PIM's external JS +was missing from clean installs; the Makefile installs it and e2e checks HTTP200. +.gitattributes prevents global text/EOL rules from corrupting binary fixtures. + +The visual comparison exposed an existing overlay-border bug: borders reduced +clientHeight/Width, making edit text/seals smaller than server output. Decorative +inset outlines preserve the complete imprint geometry. fitText/draw_text maths +are unchanged; a browser geometry/font-size assertion fails on the old CSS and +passes on the corrected CSS. No UI redesign or customer features were introduced. + +## Verification + +All data/images synthetic; tests run in isolated Alpine development containers. +Source/image verification is recorded in /tmp/signet-roadmap-build-final.log and +/tmp/signet-roadmap-image.txt. Latest stack: signet-roadmap-review :8082. + +- Full clean build/install -Wall -Wextra, no warnings/errors. +- /tmp/signet-ticket12-e2e-final.log: identity + complete API/worker acceptance + + snapshot contract end with `all passed`. +- test/snapshot-contract.sh is a retained regression, dispatched through e2e: + - Rejects symlink/oversized assets, oversized/binary text and forged values; + forced submit DB rollback removes snapshots and does not burn a serial. + - Changes PIM text, seal and font after submit but before worker execution; + forces real qpdf failure, removes live inputs and retries successfully. + - Verifies raw proof/initial stamped equality, unchanged content at sign-off + and actual embedded font-stream hashes (not merely PDF font labels). + - Correction/resubmit preserves serial/date, creates distinct frozen inputs, + retains previous resolved metadata and releases with live inputs removed. + - Damaged frozen bytes fail closed; restoring exact bytes/permissions permits + retry. PostgreSQL-triggered completion failure/recovery preserves proof + bytes and does not execute qpdf flatten a second time. +- /tmp/signet-ticket12-render-final.log: existing render/release contract passes, + retaining typed/stale jobs, sign/release failure/replay, queue and enrol checks. +- /tmp/signet-ticket12-browser.log: real signing UI/API/worker/enrolment/release + pass with no unhandled JS errors; geometry/70%-size assertions included. + /tmp/signet-ticket12-progress.log: existing progress/error/retry regression pass. +- /tmp/signet-ticket12-border-red.log: the geometry regression fails as expected + against old borders, before changing CSS. +- Both pages visually compared in edit/proof/stamped/final, plus audit, under + /tmp/signet-ticket12-browser/. Text and circular seal align; only the proper + parties' facsimiles appear; first facsimile persists into final; audit legible. +- /tmp/signet-ticket12-migration.log: migration idempotence on current schema. + /tmp/signet-ticket12-legacy-migration.log: apply/idempotence on an isolated DB + built from original68ed63b schema. No shared or production DB was changed. +- Node/shell syntax and git diff --check pass. + +## Resource evidence and remaining gates + +/tmp/signet-ticket12-rss-samples.log samples the isolated app UID processes +(lighttpd, kfcgi, API/parser children, signetd and same-UID qpdf/pdfinfo children) +at roughly50ms during the fixture suites/browser run. The final sample maximum +is29,576KB across691samples, recorded in /tmp/signet-ticket12-rss-summary.txt. +This excludes PostgreSQL, +Redis, browser/client RAM, and sampling can miss short peaks. It is NOT a native +1-vCPU benchmark, maximum concurrent-upload test or production capacity claim. + +The16MiB frozen-input cap/streaming limits this new submit work, not the entire +runtime. Existing32MiB buffered uploads, oversized JSON parse/clone amplification, +child timeouts/limits, aggregate decoded images/fonts, shared DB/Redis impact, +backup/restore and native OpenRC/proxy/CSP +verification remain ticket14 release gates. Do not expose/deploy until addressed; +maa-1's mission-critical services must not be used as an uncontrolled test bed. + +Invalid original PDF/DAM content cannot be repaired by silently taking today's +live inputs; use explicit authorised correction/recreation or exact verified +backup restoration. No speculative retention, administrative lifecycle shortcut, +shared-service reconfiguration or customer-signing model is introduced here.
diff --git a/.scratch/roadmap/ticket-14.md b/.scratch/roadmap/ticket-14.md @@ -0,0 +1,55 @@ +# Ticket 14 — release gate, incomplete / needs owner information + +Spec: spec.md §5. Tickets10–13 have isolated application evidence; none of it +certifies production. CONSIDERATIONS.md in the original checkout was read in +full on2026-11-12. It is a discussion handoff, not approval for customer features. + +## Required owner/deployment inputs + +- Who may write seals/fonts through DAM/WebDAV? Provide the allowed writers or + decide writes should be disabled. Do not infer a policy from the dev admin role. +- Which isolated native Alpine/OpenRC target may be used, and what trusted proxy + topology/identity header contract/backend isolation will the administrator use? + No maa-1 or shared-service changes have been authorised/performed by this work. +- What database/Redis allocation and namespace/roles are reserved for Signet? + Dev uses private disposable services; generic dev keys/default DB are not a + safe shared-service deployment policy. Do not reconfigure existing services + speculatively. +- What representative PDF/upload/image sizes and concurrent workload should the + native resource tests support? The historical maa-1 sample is not capacity. +- Repository remote and hosted spec/ticket URLs are needed to publish the draft + PR and use correct closing links. No Git remote/gh currently exists here. + +## Unfinished technical acceptance (must not be checked off) + +- Real trusted-header overwrite/spoof prevention, missing identity, authenticated + roles for both APIs and blocked direct-backend access. +- Approved DAM writer enforcement; production PIM authorization. +- Concurrent buffered upload containment (current API cap32MiB), bounded rendering + children/deadlines and timeout/crash recovery. run_cmd currently has no child + timeout/resource limits. The new streamed frozen-input cap alone does not bound + decoded image/font memory, upload concurrency or total child RSS. +- Bound/prune JSON metadata before parsing/cloning/serializing. Save currently + accepts arbitrary unused JSON members up to the buffered request limit; + snapshot_create clones the layout, so oversized ignored/client-value fields can + amplify heap use. The referenced-text/asset caps are not a whole-JSON cap. + This needs local resource hardening as well as native measurement; owner/proxy + questions are not the only unfinished work. +- Measure complete application cohort including qpdf/pdfinfo, incremental shared + PostgreSQL/Redis impact, CPU/I/O and recovery, on target-class native Alpine. + Sampling sequential synthetic fixtures is not a hard peak bound. +- Native install/OpenRC lifecycle, filesystem/database privileges, Redis AOF, + production CSP, backup/restore (including private snapshots and facsimiles), + and full acceptance under the actual chosen deployment topology. + +maa-1 hosts mission-critical services. Do not use it for uncontrolled stress or +package/config experiments; no production Docker, authentication-server setup, +shared database tuning or customer/OpenSign feature expansion is implied. + +## Local implementation/PR state + +Integration branch feat/feature-first-roadmap is kept in +/tmp/signet-roadmap-20261112/integration. Original working tree is preserved on +wip/preserved-local-state-20261112, including auth experiments and skill removals. +No branch was pushed and no PR was created or marked ready. Final whole-spec +review/readiness must remain open while this ticket is incomplete.
diff --git a/HANDOFF.md b/HANDOFF.md @@ -6,8 +6,9 @@ Model finalized 2026-09-19. Vocabulary in `CONTEXT.md`; working rules in `AGENTS.md`; historical implementation plan in `docs/REBUILD.md`. The original completed-task records below are historical reports, not fresh verification. Source inspection found material gaps against the agreed model; -see §4. Fresh ticket-10 and ticket-11 verification is recorded separately in -`.scratch/roadmap/ticket-10.md` and `.scratch/roadmap/ticket-11.md`. +see §4. Fresh verification is recorded separately in +`.scratch/roadmap/ticket-{10,11,12,13}.md`. The authoritative integration branch is +`feat/feature-first-roadmap`; the original dirty checkout is preserved separately. **Historically reported complete (Tasks 1–9; qualifications in §4):** - Syslog logging in both FastCGI APIs (visible errors, debuggable failures) @@ -52,7 +53,9 @@ Alpine build with no warnings, full `test/e2e.sh` and `render-contract` pass; real browser signing/enrolment/release and progress regressions pass. Both-page edit/proof/stamped/final comparisons and audit-page inspection completed using synthetic fixtures. See `.scratch/roadmap/ticket-11.md` for logs, scope and limits. -This is not native production acceptance; snapshot/identity gaps below remain. +Tickets12/13 now add frozen revision content and fail-closed identity tests; +see their notes. This is not native production acceptance: proxy/resource/native +verification below remains mandatory. **Not verified / never run:** OpenRC scripts, `etc/lighttpd-signet.conf` (production config incl. WebDAV + CSP), real Authelia in front, `make install` @@ -113,8 +116,9 @@ src/pdfw.[ch] PDF writer: pages, Helvetica fallback, embedded TTF simplified API, ≤4 MP), JPEG passthrough src/render.[ch] pdfinfo page sizes (+rot swap), bbox per shape, px→pt, draw_text/draw_image, render_stamp (overlay + qpdf), - render_release (audit page + qpdf --pages), series_expand, - pim_lookup + render_release (audit page + qpdf --pages), series_expand +src/snapshot.[ch] bounded atomic PIM resolution, streamed/symlink-safe DAM + snapshots, per-revision manifests/hashes and rollback cleanup src/http.[ch] kcgi helpers: identity/roles, fields, CSRF check, path split, send_json/err/file src/signet-api.c endpoints, placement/party visibility validation, @@ -134,15 +138,18 @@ test/ dev-up.sh (container entrypoint), lighttpd-dev.conf, ``` Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf` plus -immutable `render-<seq>.pdf` inputs; `<data_dir>/templates/<uuid>.pdf`, +immutable `render-<seq>.pdf` inputs, `proof-<snapshot UUID>.pdf` caches and +`snapshot-<UUID>/` assets/manifests; `<data_dir>/templates/<uuid>.pdf`, `<dam_dir>/…`, `<sig_dir>/<user>.png`. -Current submit flow: `save` stores layout/route JSONB → `submit` validates -references, allocates the first serial/date in a transaction, updates -status/revision/render sequence and commits → +Current submit flow: `save` stores reference-only layout/route JSONB → `submit` +locks the document, resolves referenced organisation attributes atomically and +freezes DAM bytes into private hashed revision inputs, allocates the first +serial/date, updates status/revision/render sequence and commits → `LPUSH {"doc_id","revision","seq","kind":"stamp"}` → worker locks the matching -pending document, resolves PIM and renders proof/stamped copies, publishes the -output, and commits `rendered_seq` plus the outcome event before acknowledging. +pending document and renders one cached proof from frozen inputs; public proof +and initial stamped body are byte-identical. It commits `rendered_seq` and the +outcome event before acknowledging. A successful flatten survives DB failure. The API exposes `rendering`, `rendered_seq`, `render_kind` and `can_retry`; the client polls outstanding work and stops on error. Immutable per-sequence render inputs prevent signature replay from overlaying a facsimile twice. @@ -150,7 +157,7 @@ Zone sign-offs queue `sign` for the just-signed party; check-only parties advanc without rendering. Last sign-off queues `release`, which applies its optional facsimile and appends the full cross-revision event log with body hash. Only after final publication does the worker commit `RELEASED`/`final_sha256`, clean -stamped inputs and acknowledge. Submit-time PIM/DAM snapshotting remains ticket 12. +stamped inputs and acknowledge. Snapshot/retry/mutation evidence is in ticket12. Layout JSON (what `collectLayout()` emits, what `render.c` reads): @@ -187,10 +194,14 @@ differ). The client rasterises every page to 1000 px natural width. regressions pass. The original checkout's unrelated uncommitted admin fallback was not included; do not deploy that dirty checkout. The trusted production proxy boundary remains unverified (ticket 14). See ticket-13 evidence. -- **D18 snapshotting is incomplete.** `check_submittable()` validates references; - `render_pair()` renders proof and stamped copies separately, resolving Redis - PIM values and DAM files during each render. Submit-time immutability is not - guaranteed, nor is identical content across those two reads. +- **D18 snapshotting implemented in ticket12.** Submit persists resolved text, + copied/hash-verified images and fonts (including audit), date format and a + private per-revision manifest. One proof flatten/cache supplies identical + initial stamped bytes. Retries/sign-offs/release never reread live PIM/DAM; + correction creates a new snapshot, preserving serial/date. Both-page visual + and real mutation/rollback/replay tests pass; see ticket12 evidence. Upgrade + requires the additive migration and draining legacy pending revisions; never + manufacture historical snapshots from current values. - **Queue/render contract repaired in ticket 10.** Typed payloads, locked sequence/revision/kind matching, stale/duplicate rejection, database-checked acknowledgement, startup recovery and kind-aware retry have targeted tests. @@ -221,8 +232,8 @@ differ). The client rasterises every page to 1000 px natural width. shim or a patch. Header spoofing must be impossible in production. 7. **DAM WebDAV write access** is not restricted in `lighttpd-signet.conf` (comment says "restrict at the proxy"). Decide and implement; anyone who - can PUT a seal or font changes future renders, including queued/retried - renders until snapshotting is fixed. There is no DAM upload UI — by design + can PUT a seal or font changes future submits; pending revisions now retain + their frozen bytes. There is no DAM upload UI — by design it is a network drive. 8. Rotated pages: handled only by swapping w/h from `pdfinfo`; untested. Non-zero MediaBox origin / CropBox: relies on qpdf's overlay fitting. @@ -260,9 +271,11 @@ found in the current source. ## 6. Open questions for the owner -* Who may write to the DAM? Under the intended D18 snapshot model, changes - affect only future submits; current render-time reads do not provide that - guarantee. +* Who may write to the DAM? Snapshots protect pending revisions; writer policy + still determines who may alter future submitted content. +* Which isolated native Alpine/OpenRC target and shared-service allocations may + be used for ticket14? Upload/child/decoded-image peak resources, containment, + backup/restore and coexistence need measurement before touching maa-1. * Is a cryptographic PDF signature (PAdES) wanted later? Would need a new allowed dependency. * Fix `~/.ssh/known_hosts` line 47 so host `podman` works? (Not touched.) @@ -287,8 +300,9 @@ The implementation scopes and acceptance criteria are in 2. **Ticket 11 completed:** sequential facsimile overlays, worker-owned release, party/file visibility, correction/resubmit events and title validation pass targeted acceptance; see `.scratch/roadmap/ticket-11.md`. -3. **Ticket 12 next:** freeze PIM/DAM inputs at submit and derive the initial stamped - copy from the same flattened proof. Prove retries retain frozen content. +3. **Ticket12 completed:** frozen PIM/DAM bytes and one immutable proof per + revision; mutation, retry, correction and visual checks pass. See + `.scratch/roadmap/ticket-12.md`. 4. **Ticket 13 completed:** fail-closed identity handling, config-only role/header mapping and both-API tests pass without an authentication-server dependency. See `.scratch/roadmap/ticket-13.md`. Proxy trust remains ticket 14. @@ -302,9 +316,10 @@ historical completed tickets do not substitute for fresh evidence. ## 8. Dev environment facts -* Latest isolated verification: image `signet-ticket11`, container - `signet-ticket11-verify` on :8080; throw-away DB and explicit test identities. - Earlier ticket-11 containers were stopped. No production services changed. +* Latest isolated roadmap verification: image `signet-roadmap`, container + `signet-roadmap-review` on :8082; throw-away DB and explicit test identities. + Original ticket11 evidence stack remains on :8080. No production/maa-1 services + changed. Fixture RSS samples do not certify native peak resource safety. * Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created for this project; image `signet-dev`; a container named `signet` may still be running on :8080 with throw-away data. `test/dev-up.sh` initialises the DB
diff --git a/Makefile b/Makefile @@ -13,7 +13,7 @@ LIBS_PDF = -lpng -lz -lm LIBS_CGI = -lkcgi -lz COMMON = build/conf.o build/util.o build/db.o build/yyjson.o build/sha256.o -PDF = build/pdfw.o build/ttf.o build/render.o +PDF = build/pdfw.o build/ttf.o build/render.o build/snapshot.o all: build/signet-api build/signetd build/pim-api @@ -50,7 +50,7 @@ install: all install -m 0755 build/signetd $(DESTDIR)$(PREFIX)/sbin/ install -m 0644 www/index.html www/app.js www/style.css $(DESTDIR)$(WWWDIR)/ install -m 0644 www/vendor/*.js $(DESTDIR)$(WWWDIR)/vendor/ - install -m 0644 pim/www/index.html $(DESTDIR)$(PIMWWW)/ + install -m 0644 pim/www/*.html pim/www/*.js $(DESTDIR)$(PIMWWW)/ test -f $(DESTDIR)/etc/signet/signet.conf || \ install -m 0640 etc/signet.conf.example $(DESTDIR)/etc/signet/signet.conf
diff --git a/README.md b/README.md @@ -7,7 +7,8 @@ No containers or language runtimes in production. **Development status:** sequential signing, worker-owned release and render-job recovery have fresh isolated-development tests; see `.scratch/roadmap/ticket-11.md`. Fail-closed identity is covered by -`.scratch/roadmap/ticket-13.md`; submit-time PIM/DAM snapshots remain open. +`.scratch/roadmap/ticket-13.md`; frozen PIM/DAM revision inputs and immutable +proof caching are verified in `.scratch/roadmap/ticket-12.md`. It is not ready for production deployment; these checks do not certify the native deployment or production trust boundary. @@ -101,6 +102,9 @@ cp etc/lighttpd-signet.conf /etc/lighttpd/ # and include it $EDITOR /etc/signet/signet.conf # groups → roles, paths, fonts ``` +For an existing database, read `sql/migrations/README.md` before upgrading; +legacy pending documents must not be backfilled from current PIM/DAM data. + Enable Redis AOF (`appendonly yes`). The deployment's trusted forward-auth proxy must overwrite `Remote-User` / `Remote-Groups` on every request. The deployment administrator chooses and manages the authentication provider; Signet only consumes forwarded @@ -154,9 +158,16 @@ identity headers; never run them against production. preserves the facsimile's aspect ratio and must meet the fitted image's minimum dimensions. Decision comments are limited to 4096 UTF-8 bytes; all accepted comments/events appear in the paginated audit without history truncation. -* **Imprints are organisation-bound.** The design requires a submit-time - snapshot. Current code validates references at submit but resolves values - from Redis and reads DAM assets during worker rendering; changes between - submit and render (or a retry) can affect the copy. +* **Imprints are organisation-bound and frozen at submit.** The server resolves + referenced PIM text/image attributes and copies image/font bytes (including + the audit font). Worker retries and sign-offs use only that revision's content; + correction/resubmit creates a new snapshot while retaining serial/date. + Frozen assets total at most16MiB per revision; imprint text including prefix + is limited to1023 UTF-8 bytes. Missing/damaged inputs fail closed; restore exact + verified bytes/permissions rather than replacing them from the live DAM. +* **Resource/deployment acceptance remains open.** Fixture RSS is not a native + peak-load certificate. Concurrent buffered uploads, rendering children, + image/font decoding and shared database impact require containment/measurement + before production or coexistence with other mission-critical services. * Rotated source pages are handled by swapping the page size; unusual CropBox offsets are left to qpdf's overlay fitting.
diff --git a/TESTING-AUTH.md b/TESTING-AUTH.md @@ -8,25 +8,27 @@ choice and administration belong to the deployment administrator. Authelia is only an optional deployment provider, not a product dependency or implementation task. The tests below concern Signet's forwarded-identity contract. -## Current status (source inspected 2026-11-10) +## Current integration status (2026-11-12) -The development stack does **not** establish a working Authelia forward-auth -integration. `test/lighttpd-dev.conf` has a commented proxy example; forwarding -application requests to Authelia is not a forward-auth implementation. Do not -uncomment that example and assume identity headers are trusted. +Ticket13 verifies fail-closed identity on the roadmap integration branch: +missing/invalid usernames return401 in both APIs; missing groups grant no roles. +The configured header names and group/role mappings are exercised with remapping; +DEV_MODE/DEV_REMOTE_* cannot create credentials. See ticket13 evidence. -**Security blocker:** `ident_read()` in `src/http.c` defaults missing identity -headers to user `admin` and groups `signet-admins,clerks,management`. This is -unconditional: exporting or unsetting `DEV_MODE` does not gate it. Keep this -stack isolated from untrusted users. Production requires fail-closed identity -handling and a trusted proxy that overwrites client-supplied identity headers. -See `HANDOFF.md` §4 for other implementation gaps. +The unrelated original dirty checkout's unconditional admin fallback was excluded +from the integration branch; do not deploy that checkout. The development stack +has no authentication-server dependency and does **not** prove a production +forward-auth integration. Keep it isolated from untrusted users: clients can +supply identity headers. A trusted production proxy must overwrite them and +prevent backend bypass; ticket14 remains open. ## Isolated development tests Use the Alpine dev container described in `README.md`; `test/dev-up.sh` is its -entrypoint, not a script to run directly on the host. It currently exports -`DEV_MODE=1`, but the API fallback above does not consult that variable. +entrypoint, not a script to run directly on the host. It requires explicit test +identities and does not install or start an authentication server. +`test/e2e.sh identity-contract` temporarily remaps the isolated config/restarts +APIs and restores them on exit; never run that contract test on production. The browser can send explicit test headers using its dev identity setting: @@ -39,8 +41,8 @@ location.reload(); ``` Clear it after testing with `localStorage.removeItem('signetDevIdentity')`. -A missing setting may silently use the server's admin fallback rather than -prompting for an identity. A successful page load is not evidence of auth. +A missing setting no longer receives an implicit server identity. A successful +page load with dev-supplied headers is still not evidence of proxy authentication. Roles are mapped in `etc/signet.conf.example`, copied into the dev container's `/etc/signet/signet.conf`:
diff --git a/docs/adr/0001-signers-sign-at-sign-off.md b/docs/adr/0001-signers-sign-at-sign-off.md @@ -20,9 +20,9 @@ sign-off overlays one facsimile onto the previous stamped copy, and the worker renders the release after the last one. This ADR records the accepted design, not implementation verification. See -`HANDOFF.md` §4 for current gaps, including render-time PIM/DAM reads and -fail-closed identity. Worker release verification is recorded in -`.scratch/roadmap/ticket-11.md` (path relative to the repository root). +`HANDOFF.md` §4 for remaining production trust/resource/native deployment gates. +Worker release, frozen submit inputs and fail-closed identity verification are +recorded in `.scratch/roadmap/ticket-{11,12,13}.md` (repository-root paths). ## Considered options
diff --git a/sql/migrations/001-submit-snapshots.sql b/sql/migrations/001-submit-snapshots.sql @@ -0,0 +1,5 @@ +-- Apply before starting the new API/worker. See sql/migrations/README.md. +BEGIN; +ALTER TABLE documents ADD COLUMN IF NOT EXISTS snapshot_id UUID; +ALTER TABLE documents ADD COLUMN IF NOT EXISTS snapshot_json JSONB; +COMMIT;
diff --git a/sql/migrations/README.md b/sql/migrations/README.md @@ -0,0 +1,38 @@ +# Schema upgrades + +Run upgrades as the database owner, with the API and worker stopped and a tested +backup. Do not run against a shared/production service without administrator +approval. Test on an isolated database first; fresh installs use schema.sql. + +## 001 — submit-time snapshots + +Apply `001-submit-snapshots.sql` before installing the snapshot-aware API/worker. +The two nullable columns preserve drafts, completed documents and old history. +The script is additive/idempotent; it does not manufacture old snapshots from +current PIM/DAM values or silently alter a document's attested content. + +Before upgrading, drain all pending documents with the old application, or +arrange an explicitly authorised correction/recreation and fresh sign-offs. +Already-pending legacy revisions have no authentic submit-time snapshot. New +workers fail closed rather than rebuilding them from today's attributes/assets. +Do not auto-backfill them or label a current-value backfill historically frozen. +New submits (including authorised corrections) create fresh revision snapshots. + +Snapshot storage is private under the document directory: snapshot-<UUID>/ holds +flat asset-N files and the database holds the server-only resolved layout and +asset hashes. The worker also keeps proof-<UUID>.pdf as the revision's immutable +flattened cache; public proof.pdf is a hard link, and initial stamped input is a +byte-identical copy. Retain referenced snapshots/proofs with the database and +source/artifact backups. Restoring files must preserve group signet read access +(directory0550, assets0440) and hashes; do not repair missing inputs with mutable +live assets. Exact bytes can be restored from a verified backup before retry. + +Rollback before COMMIT removes a newly created snapshot. If COMMIT's outcome is +ambiguous, retain its files: deleting them could destroy committed inputs. A +crash can leave an unreferenced snapshot/proof; inventory against snapshot_id and +retained revision policy before any administrative removal. No automatic sweep +or destructive retention policy is introduced here. + +This upgrade is not native deployment/resource certification. In particular, +concurrent upload buffering and external-command deadlines remain release-gate +work; never infer safe coexistence with maa-1's other services from dev tests.
diff --git a/sql/schema.sql b/sql/schema.sql @@ -49,6 +49,8 @@ CREATE TABLE documents ( doc_date DATE, -- fixed on first submit org_code VARCHAR(50), -- organisation (D23); NOT NULL at submit layout_json JSONB NOT NULL DEFAULT '{}', + snapshot_id UUID, -- private snapshot-<id> directory + snapshot_json JSONB, -- server-frozen layout/assets for this revision -- {"parties":[{"name":"Manager","signer":"manager"},{"name":"Partner","signer":"ceo"}]} route_json JSONB NOT NULL DEFAULT '{"parties":[]}', revision INTEGER NOT NULL DEFAULT 0, -- bumped on every submit
diff --git a/src/render.c b/src/render.c @@ -142,22 +142,6 @@ series_expand(const char *pat, const char *ymd, int seq, char *out, size_t outsz return 0; } -char * -pim_lookup(redisContext *rc, const char *org, const char *key) -{ - redisReply *r; - char *val = NULL; - - if (rc == NULL || org == NULL || key == NULL) - return NULL; - r = redisCommand(rc, "HGET %s:metadata %s", org, key); - if (r != NULL && r->type == REDIS_REPLY_STRING) - val = strdup(r->str); - if (r != NULL) - freeReplyObject(r); - return val; -} - /* --- geometry -------------------------------------------------------------- */ static int @@ -223,10 +207,9 @@ draw_text(pdfw *pw, const struct render_ctx *cx, yyjson_val *imp, int font; if (fref == NULL || *fref == '\0') - fref = conf_get(cx->cf, "default_font", NULL); - if (fref != NULL && is_safe_relpath(fref)) - snprintf(fpath, sizeof(fpath), "%s/%s", - conf_get(cx->cf, "dam_dir", "/var/www/dam"), fref); + fref = cx->default_font; + if (fref != NULL && is_safe_name(fref)) + snprintf(fpath, sizeof(fpath), "%s/%s", cx->asset_dir, fref); font = pdfw_font(pw, fpath); /* Same fitting rule as www/app.js fitText(): 70% of the box height, @@ -272,7 +255,8 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, const char *prefix = yyjson_get_str(yyjson_obj_get(imp, "prefix")); const char *fmt; double b[4], rw, rh, x, top, w, h; - char text[1024], path[1024], *val; + char text[1024], path[1024]; + const char *val; if (type == NULL || bbox(imp, b) == -1) return fail(err, errsz, "imprint with bad type or coords%s", ""); @@ -289,14 +273,10 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, if (prefix == NULL) prefix = ""; - if (strcmp(type, "pim_text") == 0) { - if ((val = pim_lookup(cx->redis, cx->org_code, ref)) == NULL) { - snprintf(err, errsz, "PIM value not found: %s in %s", ref ? ref : "?", - cx->org_code ? cx->org_code : "?"); - return -1; - } + if (strcmp(type, "resolved_text") == 0) { + if ((val = yyjson_get_str(yyjson_obj_get(imp, "value"))) == NULL) + return fail(err, errsz, "missing frozen text%s", ""); snprintf(text, sizeof(text), "%s%s", prefix, val); - free(val); draw_text(pw, cx, imp, text, x, top, w, h, pg->h); } else if (strcmp(type, "serial") == 0) { if (cx->serial == NULL) @@ -308,34 +288,18 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, fmt = yyjson_get_str(yyjson_obj_get(imp, "format")); if (fmt == NULL || *fmt == '\0' || strlen(fmt) > 64) - fmt = conf_get(cx->cf, "date_format", "%d-%m-%Y"); + fmt = cx->date_format; snprintf(pat, sizeof(pat), "{date:%s}", fmt); if (series_expand(pat, cx->doc_date, 0, d, sizeof(d)) == -1) return fail(err, errsz, "bad date format: %s", fmt); snprintf(text, sizeof(text), "%s%s", prefix, d); draw_text(pw, cx, imp, text, x, top, w, h, pg->h); - } else if (strcmp(type, "pim_image") == 0 || strcmp(type, "dam_image") == 0) { + } else if (strcmp(type, "frozen_image") == 0) { const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape")); - redisReply *image = NULL; - if (strcmp(type, "pim_image") == 0) { - if (cx->redis != NULL && is_safe_name(cx->org_code) && is_safe_name(ref)) - image = redisCommand(cx->redis, "HGET %s:images %s", cx->org_code, ref); - if (image == NULL || image->type != REDIS_REPLY_STRING) { - if (image != NULL) - freeReplyObject(image); - return fail(err, errsz, "PIM image not found: %s", ref ? ref : "?"); - } - ref = image->str; - } - if (!is_safe_relpath(ref)) { - if (image != NULL) - freeReplyObject(image); - return fail(err, errsz, "bad DAM image reference%s", ""); - } - snprintf(path, sizeof(path), "%s/%s", - conf_get(cx->cf, "dam_dir", "/var/www/dam"), ref); - if (image != NULL) - freeReplyObject(image); + + if (!is_safe_name(ref)) + return fail(err, errsz, "bad frozen image reference%s", ""); + snprintf(path, sizeof(path), "%s/%s", cx->asset_dir, ref); /* Apply circular clipping if shape is "circle" */ if (shape != NULL && strcmp(shape, "circle") == 0) { @@ -351,15 +315,6 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, /* End clipping if it was applied */ if (shape != NULL && strcmp(shape, "circle") == 0) pdfw_clip_end(pw); - } else if (strcmp(type, "signature") == 0) { - if (!cx->with_signatures) - return 0; - if (!is_safe_name(ref)) - return fail(err, errsz, "bad signer: %s", ref ? ref : "?"); - snprintf(path, sizeof(path), "%s/%s.png", - conf_get(cx->cf, "sig_dir", "/var/lib/signatures"), ref); - if (draw_image(pw, path, x, top, w, h, pg->h) == -1) - return fail(err, errsz, "no usable signature on file for: %s", ref); } else if (strcmp(type, "signature_zone") == 0) { /* Signature zones are metadata for the signing flow; skip during rendering */ return 0; @@ -431,7 +386,7 @@ int render_release(const struct render_ctx *cx, const char *body, const char *out, const char *const *lines, int nlines, char *err, size_t errsz) { - const char *fref = conf_get(cx->cf, "default_font", NULL); + const char *fref = cx->default_font; char audit[1024], fpath[1024] = "", line[1024]; char *argv[] = { "qpdf", "--warning-exit-0", "--empty", "--pages", (char *)body, audit, "--", (char *)out, NULL }; @@ -442,9 +397,8 @@ render_release(const struct render_ctx *cx, const char *body, const char *out, snprintf(audit, sizeof(audit), "%s/audit-%ld.pdf", cx->tmpdir, (long)getpid()); if ((pw = pdfw_open(audit)) == NULL) return fail(err, errsz, "cannot write %s", audit); - if (fref != NULL && is_safe_relpath(fref)) - snprintf(fpath, sizeof(fpath), "%s/%s", - conf_get(cx->cf, "dam_dir", "/var/www/dam"), fref); + if (fref != NULL && is_safe_name(fref)) + snprintf(fpath, sizeof(fpath), "%s/%s", cx->asset_dir, fref); font = pdfw_font(pw, fpath); pdfw_page(pw, 595.28, 841.89); pdfw_text(pw, font, 16, 56, y, "Document audit record");
diff --git a/src/render.h b/src/render.h @@ -4,18 +4,14 @@ #include <stddef.h> -#include <hiredis/hiredis.h> - -#include "conf.h" #include "yyjson.h" struct render_ctx { - const struct conf *cf; - redisContext *redis; + const char *asset_dir; + const char *default_font; + const char *date_format; const char *serial; /* NULL if the document has no series */ const char *doc_date; /* YYYY-MM-DD */ - const char *org_code; /* organisation for PIM lookup */ - int with_signatures; /* 0: proof, 1: stamped copy */ const char *tmpdir; /* scratch space, same filesystem as `out` */ }; @@ -26,13 +22,10 @@ int render_page_size(const char *pdf, int page, double *w, double *h); int series_expand(const char *pattern, const char *ymd, int seq, char *out, size_t outsz); -/* PIM lookup: resolve org/entity/key -> HGET <entity>:metadata <key>. */ -char *pim_lookup(redisContext *, const char *org, const char *ref); - int render_stamp(const struct render_ctx *, yyjson_val *layout, const char *src_pdf, const char *out_pdf, char *err, size_t errsz); -/* render_stamp variants: org_code required for D23 PIM resolution */ +/* Stamp consumes only server-frozen layout/asset references. */ /* `body`: stamped copy; `out` = body + one audit page listing `lines`. */ int render_release(const struct render_ctx *, const char *body,
diff --git a/src/signet-api.c b/src/signet-api.c @@ -34,6 +34,7 @@ #include "db.h" #include "http.h" #include "render.h" +#include "snapshot.h" #include "util.h" static struct conf cf; @@ -243,10 +244,7 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, { yyjson_val *imp; size_t i, max; - const char *type, *ref, *msg; - char path[1024]; - redisContext *rc; - redisReply *r; + const char *type, *msg; if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL || (msg = check_zones(layout, route)) != NULL) { @@ -271,45 +269,13 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, yyjson_val *imprints = yyjson_obj_get(layout, "imprints"); yyjson_arr_foreach(imprints, i, max, imp) { type = yyjson_get_str(yyjson_obj_get(imp, "type")); - ref = yyjson_get_str(yyjson_obj_get(imp, "ref")); - if (ref == NULL) - ref = ""; - if (strcmp(type, "pim_text") == 0) { - if (org_code == NULL || !*org_code) { - snprintf(err, errsz, "Select an organisation to populate organisation-bound fields"); - return -1; - } - rc = redis_get(&cf); - r = rc == NULL ? NULL : redisCommand(rc, "HGET %s:metadata %s", org_code, ref); - if (r == NULL || r->type != REDIS_REPLY_STRING) { - snprintf(err, errsz, "Organisation '%s' does not have a '%s' attribute — check PIM settings", org_code, ref); - if (r != NULL) freeReplyObject(r); - return -1; - } - freeReplyObject(r); - } else if (strcmp(type, "pim_image") == 0) { - if (org_code == NULL || !*org_code) { - snprintf(err, errsz, "Select an organisation to populate organisation-bound image fields"); - return -1; - } - rc = redis_get(&cf); - r = rc == NULL ? NULL : redisCommand(rc, "HGET %s:images %s", org_code, ref); - if (r == NULL || r->type != REDIS_REPLY_STRING) { - snprintf(err, errsz, "Organisation '%s' does not have an image attribute '%s' — check PIM settings", org_code, ref); - if (r != NULL) freeReplyObject(r); - return -1; - } - const char *dam_path = r->str; - snprintf(path, sizeof(path), "%s/%s", conf_get(&cf, "dam_dir", - "/var/www/dam"), dam_path); - int exists = is_safe_relpath(dam_path) && file_exists(path); - if (!exists) { - snprintf(err, errsz, "Image file '%s' not found in the DAM — ensure the file exists and the path is correct", dam_path); - freeReplyObject(r); - return -1; - } - freeReplyObject(r); - } else if (strcmp(type, "serial") == 0 && !has_series) { + if ((strcmp(type, "pim_text") == 0 || strcmp(type, "pim_image") == 0) && + (org_code == NULL || !*org_code)) { + snprintf(err, errsz, "Select an organisation for PIM imprints"); + return -1; + } + /* Attribute existence and bytes are checked once, by snapshot_create. */ + if (strcmp(type, "serial") == 0 && !has_series) { snprintf(err, errsz, "Serial number field is used, but no series is selected — choose a series or remove the serial field"); return -1; } @@ -544,11 +510,12 @@ out: static void h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid) { - const char *p[3] = { docid, id->user, NULL }; + const char *p[5] = { docid, id->user, NULL, NULL, NULL }; PGresult *res = NULL, *r2 = NULL; yyjson_doc *ldoc = NULL, *rdoc = NULL; char err[512] = "", serial[256], body[64], *rev = NULL; - int has_serial, has_series; + char key[37], name[64], frozen_dir[1024] = "", *frozen = NULL; + int has_serial, has_series, commit_attempted = 0; const char *submit_action; if (db_do(pg, "BEGIN", 0, NULL) == -1) { @@ -556,7 +523,7 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc return; } res = db_q(pg, "SELECT layout_json::text, route_json::text, series_code, " - "serial, org_code, status::text, title FROM documents WHERE id = $1 AND drafter_user = $2 " + "serial, org_code, status::text, title, revision + 1 FROM documents WHERE id = $1 AND drafter_user = $2 " "AND status IN ('DRAFT','CORRECTION_REQUIRED') FOR UPDATE", 2, p); if (res == NULL || PQntuples(res) != 1) { snprintf(err, sizeof(err), "document is not submittable by you"); @@ -582,6 +549,25 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc org_code, has_series, err, sizeof(err)) == -1) goto fail; + r2 = db_q(pg, "SELECT gen_random_uuid()::text", 0, NULL); + if (r2 == NULL || PQntuples(r2) != 1) { + snprintf(err, sizeof(err), "could not allocate revision snapshot"); + goto fail; + } + snprintf(key, sizeof(key), "%s", PQgetvalue(r2, 0, 0)); + PQclear(r2); + r2 = NULL; + snprintf(name, sizeof(name), "snapshot-%s", key); + doc_path(frozen_dir, sizeof(frozen_dir), docid, name); + frozen = snapshot_create(&cf, redis_get(&cf), org_code, + atoi(PQgetvalue(res, 0, 7)), yyjson_doc_get_root(ldoc), frozen_dir, err, sizeof(err)); + if (frozen == NULL) { + frozen_dir[0] = '\0'; /* snapshot_create cleans only a directory it created. */ + goto fail; + } + p[3] = frozen; + p[4] = key; + if (has_series) { const char *sp[] = { PQgetvalue(res, 0, 2) }; PGresult *sres = db_q(pg, "SELECT retired_at FROM series WHERE code = $1", 1, sp); @@ -622,17 +608,23 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc r2 = db_q(pg, "UPDATE documents SET status = 'PENDING'::doc_status, " "revision = revision + 1, render_seq = render_seq + 1, " "render_kind = 'stamp', current_party = 1, " + "snapshot_json = $4::jsonb, snapshot_id = $5::uuid, " "serial = COALESCE(serial, $3), " "doc_date = COALESCE(doc_date, CURRENT_DATE), " "submitted_at = CURRENT_TIMESTAMP, render_error = NULL " "WHERE id = $1 AND drafter_user = $2 " - "RETURNING revision::text, render_seq::text", 3, p); + "RETURNING revision::text, render_seq::text", 5, p); if (r2 == NULL || PQntuples(r2) != 1 || (rev = strdup(PQgetvalue(r2, 0, 0))) == NULL || - log_event(pg, docid, id->user, submit_action, rev) == -1 || - db_do(pg, "COMMIT", 0, NULL) == -1) { + log_event(pg, docid, id->user, submit_action, rev) == -1) { snprintf(err, sizeof(err), "submit failed"); goto fail; } + /* An ambiguous COMMIT must never delete potentially committed inputs. */ + commit_attempted = 1; + if (db_do(pg, "COMMIT", 0, NULL) == -1) { + snprintf(err, sizeof(err), "submit commit outcome unknown; reload document before retrying"); + goto fail; + } if (enqueue(docid, rev, PQgetvalue(r2, 0, 1), "stamp") == -1) send_err(r, KHTTP_503, "submitted, but the stamping queue is down; " "use 'Retry stamping' once it is back"); @@ -643,8 +635,11 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc goto done; fail: db_do(pg, "ROLLBACK", 0, NULL); + if (!commit_attempted) + snapshot_remove(frozen_dir); send_err(r, KHTTP_409, err); done: + free(frozen); free(rev); if (res != NULL) PQclear(res);
diff --git a/src/signetd.c b/src/signetd.c @@ -17,6 +17,7 @@ #include "conf.h" #include "db.h" #include "render.h" +#include "snapshot.h" #include "util.h" static struct conf cf; @@ -119,45 +120,79 @@ out: return rv; } +static yyjson_doc * +load_snapshot(const char *id, const char *key, const char *json, + struct render_ctx *cx, char assets[1024], char *err, size_t errsz) +{ + yyjson_doc *doc; + yyjson_val *root; + char name[64]; + + if (!is_uuid(key) || (doc = yyjson_read(json, strlen(json), 0)) == NULL) { + snprintf(err, errsz, "revision has no submit-time snapshot; never rebuild from live inputs"); + return NULL; + } + root = yyjson_doc_get_root(doc); + snprintf(name, sizeof(name), "snapshot-%s", key); + doc_path(assets, 1024, id, name); + if (snapshot_verify(root, assets, err, errsz) == -1 || + !yyjson_is_obj(yyjson_obj_get(root, "layout")) || + !yyjson_is_str(yyjson_obj_get(root, "default_font")) || + !yyjson_is_str(yyjson_obj_get(root, "date_format"))) { + yyjson_doc_free(doc); + return NULL; + } + memset(cx, 0, sizeof(*cx)); + cx->asset_dir = assets; + cx->default_font = yyjson_get_str(yyjson_obj_get(root, "default_font")); + cx->date_format = yyjson_get_str(yyjson_obj_get(root, "date_format")); + return doc; +} + static int -render_pair(redisContext *rc, const char *id, const char *layout_txt, - const char *serial, const char *date, const char *org_code, - const char *candidate, char *err, size_t errsz) +render_pair(const char *id, const char *snapshot_txt, const char *key, + const char *serial, const char *date, const char *candidate, + char *err, size_t errsz) { struct render_ctx cx; - char dir[512], src[600], tmp[700], proof[600]; + char dir[512], src[600], tmp[740], proof[600], copy[740], assets[1024]; + char name[64], cached[700]; yyjson_doc *doc; - int i, rv = -1; + int rv = -1; doc_path(dir, sizeof(dir), id, NULL); doc_path(src, sizeof(src), id, "source.pdf"); doc_path(proof, sizeof(proof), id, "proof.pdf"); - if ((doc = yyjson_read(layout_txt, strlen(layout_txt), 0)) == NULL) { - snprintf(err, errsz, "layout is not valid JSON"); + doc = load_snapshot(id, key, snapshot_txt, &cx, assets, err, errsz); + if (doc == NULL) return -1; - } - memset(&cx, 0, sizeof(cx)); - cx.cf = &cf; - cx.redis = rc; cx.serial = serial; cx.doc_date = date; - cx.org_code = org_code; cx.tmpdir = dir; - for (i = 0; i < 2; i++) { - const char *dst = i ? candidate : proof; - - cx.with_signatures = i; - snprintf(tmp, sizeof(tmp), "%s.tmp", dst); - if (render_stamp(&cx, yyjson_doc_get_root(doc), src, tmp, err, - errsz) == -1 || chmod(tmp, 0640) == -1 || rename(tmp, dst) == -1) { - if (!*err) - snprintf(err, errsz, "could not publish render output"); - unlink(tmp); + snprintf(name, sizeof(name), "proof-%s.pdf", key); + doc_path(cached, sizeof(cached), id, name); + snprintf(tmp, sizeof(tmp), "%s.tmp", cached); + /* A successful flatten survives database failure and stamp retries. */ + if (!file_exists(cached)) { + if (render_stamp(&cx, yyjson_obj_get(yyjson_doc_get_root(doc), "layout"), + src, tmp, err, errsz) == -1 || chmod(tmp, 0440) == -1 || rename(tmp, cached) == -1) goto out; - } } - rv = 0; + snprintf(tmp, sizeof(tmp), "%s.tmp", proof); + snprintf(copy, sizeof(copy), "%s.tmp", candidate); + unlink(tmp); + /* Public proof links the revision cache; stamped input is byte-identical. */ + if (link(cached, tmp) == 0 && copy_file(cached, copy) == 0 && + rename(tmp, proof) == 0 && rename(copy, candidate) == 0) + rv = 0; out: + if (rv == -1 && !*err) + snprintf(err, errsz, "could not publish render output"); + unlink(tmp); + if (rv == -1) { + snprintf(copy, sizeof(copy), "%s.tmp", candidate); + unlink(copy); + } yyjson_doc_free(doc); return rv; } @@ -224,7 +259,6 @@ render_decision(PGconn *pg, const char *id, const char *revision, doc_path(dir, sizeof(dir), id, NULL); snprintf(tmp, sizeof(tmp), "%s.tmp", candidate); memset(&cx, 0, sizeof(cx)); - cx.cf = &cf; cx.tmpdir = dir; rv = render_sign(&cx, base, tmp, png, page, x, y, w, h, rw, rh, err, errsz); if (rv == 0 && (chmod(tmp, 0640) == -1 || rename(tmp, candidate) == -1)) { @@ -240,12 +274,13 @@ out: static int release_document(PGconn *pg, const char *id, const char *body, char sha[65], - char *err, size_t errsz) + const char *snapshot_txt, const char *key, char *err, size_t errsz) { const char *p[] = { id }, **lines; struct render_ctx cx; PGresult *res; - char dir[600], tmp[700], final[700], body_sha[65]; + char dir[600], tmp[700], final[700], body_sha[65], assets[1024]; + yyjson_doc *snapshot; int i, n, rv = -1; if (sha256_file(body, body_sha) == -1) { @@ -282,8 +317,12 @@ release_document(PGconn *pg, const char *id, const char *body, char sha[65], doc_path(dir, sizeof(dir), id, NULL); doc_path(tmp, sizeof(tmp), id, "final.pdf.tmp"); doc_path(final, sizeof(final), id, "final.pdf"); - memset(&cx, 0, sizeof(cx)); - cx.cf = &cf; + snapshot = load_snapshot(id, key, snapshot_txt, &cx, assets, err, errsz); + if (snapshot == NULL) { + free(lines); + PQclear(res); + return -1; + } cx.tmpdir = dir; if (render_release(&cx, body, tmp, lines, n, err, errsz) == 0) { if (sha256_file(tmp, sha) == 0 && chmod(tmp, 0640) == 0 && rename(tmp, final) == 0) @@ -292,6 +331,7 @@ release_document(PGconn *pg, const char *id, const char *body, char sha[65], snprintf(err, errsz, "could not publish final copy"); } unlink(tmp); + yyjson_doc_free(snapshot); free(lines); PQclear(res); return rv; @@ -324,7 +364,7 @@ cleanup_release(const char *id, int seq) /* 0 acknowledges an invalid/stale job or a committed outcome; -1 retries. */ static int -process(redisContext *rc, const char *payload) +process(const char *payload) { PGconn *pg; PGresult *res = NULL, *updated = NULL; @@ -366,7 +406,7 @@ process(redisContext *rc, const char *payload) if ((pg = db_get(&cf)) == NULL || db_do(pg, "BEGIN", 0, NULL) == -1) goto done; /* Hold the row through filesystem publication and database completion. */ - res = db_q(pg, "SELECT layout_json::text, serial, doc_date::text, org_code, " + res = db_q(pg, "SELECT snapshot_json::text, serial, doc_date::text, snapshot_id::text, " "rendered_seq FROM documents WHERE id = $1 AND revision = $2::int " "AND render_seq = $3::int AND render_kind = $4 AND status = 'PENDING' " "AND rendered_seq < render_seq AND render_error IS NULL FOR UPDATE", 4, p); @@ -391,9 +431,9 @@ process(redisContext *rc, const char *payload) snprintf(name, sizeof(name), "render-%d.pdf", seq); doc_path(candidate, sizeof(candidate), id, name); if (strcmp(kind, "stamp") == 0) { - rendered = render_pair(rc, id, PQgetvalue(res, 0, 0), + rendered = render_pair(id, PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 3), PQgetisnull(res, 0, 1) ? NULL : PQgetvalue(res, 0, 1), - PQgetvalue(res, 0, 2), PQgetvalue(res, 0, 3), candidate, err, sizeof(err)); + PQgetvalue(res, 0, 2), candidate, err, sizeof(err)); action = rendered == 0 ? "STAMPED" : "STAMP_FAILED"; } else if (strcmp(kind, "sign") == 0) { rendered = render_decision(pg, id, revbuf, base, candidate, err, sizeof(err)); @@ -405,7 +445,8 @@ process(redisContext *rc, const char *payload) goto rollback; rendered = render_decision(pg, id, revbuf, base, candidate, err, sizeof(err)); if (rendered == 0) - rendered = release_document(pg, id, candidate, sha, err, sizeof(err)); + rendered = release_document(pg, id, candidate, sha, + PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 3), err, sizeof(err)); if (rendered == -2) goto rollback; if (rendered != 0 && db_do(pg, "ROLLBACK TO SAVEPOINT release_output", 0, NULL) == -1) @@ -516,7 +557,7 @@ main(int argc, char *argv[]) continue; } if (r->type == REDIS_REPLY_STRING) { - if (process(rc, r->str) == 0) { + if (process(r->str) == 0) { d = redisCommand(rc, "LREM %s 1 %b", processing, r->str, r->len); if (d == NULL || d->type != REDIS_REPLY_INTEGER || d->integer != 1) ready = 0;
diff --git a/src/snapshot.c b/src/snapshot.c @@ -0,0 +1,325 @@ +#include <sys/stat.h> + +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "snapshot.h" +#include "util.h" + +#define MAX_ASSETS 201 /* 200 imprints plus the audit font. */ +#define MAX_ASSET_BYTES (16u * 1024 * 1024) /* Aggregate frozen inputs, streamed. */ + +struct asset { + char ref[1024], name[32]; +}; + +/* Open every DAM component without following symlinks, including directories. */ +static int +open_asset(const char *dam, const char *ref) +{ + char path[1024], *part, *next; + int dir, fd; + + if (!is_safe_relpath(ref) || strlen(ref) >= sizeof(path)) + return -1; + strcpy(path, ref); + if ((dir = open(dam, O_RDONLY | O_DIRECTORY)) == -1) + return -1; + for (part = path; (next = strchr(part, '/')) != NULL; part = next + 1) { + *next = '\0'; + fd = openat(dir, part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW); + close(dir); + if (fd == -1) + return -1; + dir = fd; + } + fd = openat(dir, part, O_RDONLY | O_NOFOLLOW | O_NONBLOCK); + close(dir); + return fd; +} + +static int +freeze_asset(const struct conf *cf, const char *ref, const char *dir, + struct asset assets[MAX_ASSETS], int *count, size_t *total, yyjson_mut_doc *doc, + yyjson_mut_val *files, char name[32]) +{ + char dest[1200], buf[16384], hash[65]; + struct stat before, after; + yyjson_mut_val *file; + ssize_t n, written; + int i, in, out = -1, rv = -1; + size_t copied = 0; + + for (i = 0; i < *count; i++) + if (strcmp(assets[i].ref, ref) == 0) { + strcpy(name, assets[i].name); + return 0; + } + if (*count == MAX_ASSETS || strlen(ref) >= sizeof(assets[0].ref)) + return -1; + in = open_asset(conf_get(cf, "dam_dir", "/var/www/dam"), ref); + if (in == -1) + return -1; + if (fstat(in, &before) == -1 || !S_ISREG(before.st_mode) || + before.st_size < 1 || (uint64_t)before.st_size > MAX_ASSET_BYTES - *total) + goto out; + snprintf(name, 32, "asset-%d", *count); + snprintf(dest, sizeof(dest), "%s/%s", dir, name); + if ((out = open(dest, O_WRONLY | O_CREAT | O_EXCL, 0640)) == -1) + goto out; + while ((n = read(in, buf, sizeof(buf))) != 0) { + if (n == -1) { + if (errno == EINTR) + continue; + goto out; + } + if ((size_t)n > (size_t)before.st_size - copied) + goto out; + copied += (size_t)n; + for (written = 0; written < n;) { + ssize_t step = write(out, buf + written, (size_t)(n - written)); + if (step == -1 && errno == EINTR) + continue; + if (step <= 0) + goto out; + written += step; + } + } + /* Reject in-place edits during the copy; atomic replacement keeps this fd stable. */ + if (fstat(in, &after) == -1 || copied != (size_t)before.st_size || before.st_size != after.st_size || + before.st_mtim.tv_sec != after.st_mtim.tv_sec || + before.st_mtim.tv_nsec != after.st_mtim.tv_nsec || + before.st_ctim.tv_sec != after.st_ctim.tv_sec || + before.st_ctim.tv_nsec != after.st_ctim.tv_nsec || + fchmod(out, 0440) == -1 || fsync(out) == -1) + goto out; + if (close(out) == -1) { + out = -1; + goto out; + } + out = -1; + if (sha256_file(dest, hash) == -1) + goto out; + file = yyjson_mut_obj(doc); + if (file == NULL || !yyjson_mut_obj_add_strcpy(doc, file, "name", name) || + !yyjson_mut_obj_add_strcpy(doc, file, "sha256", hash) || + !yyjson_mut_arr_append(files, file)) + goto out; + strcpy(assets[*count].ref, ref); + strcpy(assets[*count].name, name); + (*count)++; + *total += copied; + rv = 0; +out: + if (out != -1) + close(out); + close(in); + return rv; +} + +/* One bounded, atomic Redis read of just the referenced organisation attributes. */ +static redisReply * +read_attributes(redisContext *rc, const char *org, yyjson_val *layout) +{ + static const char script[] = + "local t,i={},{}; for n=1,#ARGV,2 do " + "local a,k; if ARGV[n]=='t' then a=t; k=KEYS[1] else a=i; k=KEYS[2] end; " + "local v=redis.call('HGET',k,ARGV[n+1]); " + "if not v or #v>1023 or string.find(v,string.char(0),1,true) then " + "return redis.error_reply('missing or invalid snapshot attribute') end; " + "a[#a+1]=ARGV[n+1]; a[#a+1]=v; end; return {t,i}"; + const char *argv[405] = { "EVAL", script, "2" }; + char metadata[128], images[128]; + yyjson_val *imp; + const char *type; + size_t i, max; + int argc = 5; + + if (rc == NULL) + return NULL; + snprintf(metadata, sizeof(metadata), "%s:metadata", org); + snprintf(images, sizeof(images), "%s:images", org); + argv[3] = metadata; + argv[4] = images; + yyjson_arr_foreach(yyjson_obj_get(layout, "imprints"), i, max, imp) { + type = yyjson_get_str(yyjson_obj_get(imp, "type")); + if (strcmp(type, "pim_text") != 0 && strcmp(type, "pim_image") != 0) + continue; + if (argc + 2 > (int)(sizeof(argv) / sizeof(argv[0]))) + return NULL; + argv[argc++] = strcmp(type, "pim_text") == 0 ? "t" : "i"; + argv[argc++] = yyjson_get_str(yyjson_obj_get(imp, "ref")); + } + return argc == 5 ? NULL : redisCommandArgv(rc, argc, argv, NULL); +} + +static const char * +attribute(redisReply *hash, const char *ref) +{ + size_t i; + + if (hash == NULL || hash->type != REDIS_REPLY_ARRAY || ref == NULL) + return NULL; + for (i = 0; i + 1 < hash->elements; i += 2) + if (hash->element[i]->type == REDIS_REPLY_STRING && + hash->element[i + 1]->type == REDIS_REPLY_STRING && + strcmp(hash->element[i]->str, ref) == 0) + return hash->element[i + 1]->str; + return NULL; +} + +char * +snapshot_create(const struct conf *cf, redisContext *rc, const char *org, + int revision, yyjson_val *layout, const char *dir, char *err, size_t errsz) +{ + struct asset assets[MAX_ASSETS]; + yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); + yyjson_mut_val *root, *frozen, *imps, *imp, *files; + redisReply *pim = NULL, *text = NULL, *images = NULL; + const char *type, *ref, *value, *font, *prefix; + char name[32], manifest[1200], *result = NULL; + size_t i, max, total = 0; + int count = 0, created = 0, fd, parent, complete = 0; + + if (doc == NULL) + goto out; + root = yyjson_mut_obj(doc); + frozen = yyjson_val_mut_copy(doc, layout); + files = yyjson_mut_arr(doc); + if (root == NULL || frozen == NULL || files == NULL || mkdir(dir, 0750) == -1) + goto out; + created = 1; + yyjson_mut_doc_set_root(doc, root); + if (!yyjson_mut_obj_add_int(doc, root, "version", 1) || + !yyjson_mut_obj_add_int(doc, root, "revision", revision) || + !yyjson_mut_obj_add_strcpy(doc, root, "org_code", org) || + !yyjson_mut_obj_add_val(doc, root, "layout", frozen) || + !yyjson_mut_obj_add_val(doc, root, "files", files) || + !yyjson_mut_obj_add_strcpy(doc, root, "date_format", conf_get(cf, "date_format", "%d-%m-%Y"))) + goto out; + font = conf_get(cf, "default_font", ""); + name[0] = '\0'; + if (*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1) + goto out; + if (!yyjson_mut_obj_add_strcpy(doc, root, "default_font", name)) + goto out; + pim = read_attributes(rc, org, layout); + if (pim != NULL && pim->type == REDIS_REPLY_ARRAY && pim->elements == 2) { + text = pim->element[0]; + images = pim->element[1]; + } + imps = yyjson_mut_obj_get(frozen, "imprints"); + yyjson_mut_arr_foreach(imps, i, max, imp) { + type = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "type")); + ref = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "ref")); + if (strcmp(type, "pim_text") == 0) { + value = attribute(text, ref); + prefix = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "prefix")); + if (value == NULL || strlen(value) + (prefix ? strlen(prefix) : 0) > 1023 || !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "resolved_text")) || + !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "value"), yyjson_mut_strcpy(doc, value))) + goto out; + } else if (strcmp(type, "pim_image") == 0) { + value = attribute(images, ref); + if (value == NULL || freeze_asset(cf, value, dir, assets, &count, &total, doc, files, name) == -1 || + !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "frozen_image")) || + !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "ref"), yyjson_mut_strcpy(doc, name))) + goto out; + } + if (strcmp(type, "pim_text") == 0 || strcmp(type, "date") == 0 || strcmp(type, "serial") == 0) { + font = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "font")); + if (font == NULL || !*font) + font = conf_get(cf, "default_font", ""); + name[0] = '\0'; + if ((*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1) || + !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "font"), yyjson_mut_strcpy(doc, name))) + goto out; + } + } + /* Keep every revision's resolved metadata, even after the DB points at a correction. */ + result = yyjson_mut_write(doc, 0, NULL); + snprintf(manifest, sizeof(manifest), "%s/manifest.json", dir); + if (result == NULL || write_file(manifest, result, strlen(result), 0440) == -1 || + (fd = open(manifest, O_RDONLY)) == -1) + goto out; + if (fchmod(fd, 0440) == -1 || fsync(fd) == -1) { + close(fd); + goto out; + } + close(fd); + if (chmod(dir, 0550) == -1 || (fd = open(dir, O_RDONLY | O_DIRECTORY)) == -1) + goto out; + if (fsync(fd) == -1) { + close(fd); + goto out; + } + parent = openat(fd, "..", O_RDONLY | O_DIRECTORY); + close(fd); + if (parent == -1) + goto out; + if (fsync(parent) == -1) { + close(parent); + goto out; + } + close(parent); + complete = 1; +out: + if (!complete) { + free(result); + result = NULL; + if (created) + snapshot_remove(dir); + snprintf(err, errsz, "could not freeze submit inputs (missing, unsafe, changing, text over 1023 bytes or assets over 16 MB)"); + } + if (pim != NULL) + freeReplyObject(pim); + yyjson_mut_doc_free(doc); + return result; +} + +void +snapshot_remove(const char *dir) +{ + DIR *d; + struct dirent *entry; + + if (dir == NULL || !*dir || chmod(dir, 0750) == -1 || (d = opendir(dir)) == NULL) + return; + while ((entry = readdir(d)) != NULL) + if ((strncmp(entry->d_name, "asset-", 6) == 0 && is_safe_name(entry->d_name)) || + strcmp(entry->d_name, "manifest.json") == 0) + unlinkat(dirfd(d), entry->d_name, 0); + closedir(d); + rmdir(dir); +} + +int +snapshot_verify(yyjson_val *root, const char *dir, char *err, size_t errsz) +{ + yyjson_val *files = yyjson_obj_get(root, "files"), *file; + const char *name, *expected; + char path[1200], hash[65]; + size_t i, max; + + if (yyjson_get_sint(yyjson_obj_get(root, "version")) != 1 || !yyjson_is_arr(files) || + yyjson_arr_size(files) > MAX_ASSETS) + goto fail; + yyjson_arr_foreach(files, i, max, file) { + name = yyjson_get_str(yyjson_obj_get(file, "name")); + expected = yyjson_get_str(yyjson_obj_get(file, "sha256")); + if (!is_safe_name(name) || expected == NULL) + goto fail; + snprintf(path, sizeof(path), "%s/%s", dir, name); + if (sha256_file(path, hash) == -1 || strcmp(hash, expected) != 0) + goto fail; + } + return 0; +fail: + snprintf(err, errsz, "frozen revision inputs missing or damaged; live PIM/DAM fallback is forbidden"); + return -1; +}
diff --git a/src/snapshot.h b/src/snapshot.h @@ -0,0 +1,18 @@ +/* Server-owned revision inputs. No client values or mutable DAM paths. */ +#ifndef SIGNET_SNAPSHOT_H +#define SIGNET_SNAPSHOT_H + +#include <stddef.h> + +#include <hiredis/hiredis.h> + +#include "conf.h" +#include "yyjson.h" + +/* Creates a new flat directory; caller removes it if its submit rolls back. */ +char *snapshot_create(const struct conf *, redisContext *, const char *org, + int revision, yyjson_val *layout, const char *dir, char *err, size_t errsz); +void snapshot_remove(const char *dir); +int snapshot_verify(yyjson_val *, const char *dir, char *err, size_t errsz); + +#endif
diff --git a/test/e2e.sh b/test/e2e.sh @@ -4,11 +4,15 @@ set -eu if [ "${1-}" = render-contract ]; then exec sh /src/test/render-contract.sh fi +if [ "${1-}" = snapshot-contract ]; then + exec sh /src/test/snapshot-contract.sh +fi if [ "${1-}" = identity-contract ]; then exec sh /src/test/identity-contract.sh fi sh /src/test/identity-contract.sh B=http://localhost:8080 +curl -fsS "$B/pim/pim.js" >/dev/null # Clean installs must include the PIM client. X='X-Requested-With: signet' as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } clerk() { as asha clerks "$@"; } @@ -212,4 +216,5 @@ status 409 root signet-admins -d '' "$B/api/templates/$TID/delete" admin -H "$X" -d '' "$B/api/docs/$CHILD/unlink" >/dev/null admin -H "$X" -d '' "$B/api/templates/$TID/delete" >/dev/null ok 'template retire/unlink/delete regression' +sh /src/test/snapshot-contract.sh echo 'all passed'
diff --git a/test/signing-flow.mjs b/test/signing-flow.mjs @@ -57,6 +57,13 @@ try { throw Error('worker timeout'); } await open(); + const textBox = await page.locator('.overlay .box.t-pim_text').evaluate((b) => ({ + height: b.getBoundingClientRect().height, + content: b.clientHeight, + size: parseFloat(getComputedStyle(b).fontSize), + })); + assert(Math.abs(textBox.height - textBox.content) < 1, 'overlay decoration must not consume the renderer box'); + assert(Math.abs(textBox.size - textBox.height * .7) < .75, 'editor text must use 70% of the full imprint height'); await page.locator('#f-title').fill(''); assert(await page.getByRole('button', { name: 'Submit', exact: true }).isDisabled()); await page.locator('#f-title').fill(layout.title);
diff --git a/test/snapshot-contract.sh b/test/snapshot-contract.sh @@ -0,0 +1,221 @@ +#!/bin/sh +# Isolated root-run Alpine dev regression: real API, Redis, worker and PDFs. +set -eu +B=http://localhost:8080 +X='X-Requested-With: signet' +Q=queue:stamping +ORG=SNAPSHOT12 +SERIES=S12_$(date +%s) +FONT=/var/www/dam/fonts/DejaVuSans.ttf +EXPLICIT=/var/www/dam/fonts/snapshot12.ttf +SEAL=/var/www/dam/seals/snapshot12.png +TMP=$(mktemp -d /tmp/snapshot-contract.XXXXXX) +chmod 0755 "$TMP" +cp "$FONT" "$TMP/font.ttf" +cp /src/test/fixtures/seal.png "$SEAL" +cp "$FONT" "$EXPLICIT" +mkdir "$TMP/bin" +touch "$TMP/qpdf-calls" +chown signetd:signet "$TMP/qpdf-calls" +cat > "$TMP/bin/qpdf" <<EOF +#!/bin/sh +[ ! -e '$TMP/fail-qpdf' ] || exit 17 +echo "\$*" >> '$TMP/qpdf-calls' +exec /usr/bin/qpdf "\$@" +EOF +chmod 0755 "$TMP/bin/qpdf" +as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } +sql() { su-exec postgres psql -X -At -v ON_ERROR_STOP=1 -d signet "$@"; } +stop() { pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true; sleep 1; } +start() { PATH="$TMP/bin:$PATH" su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/snapshot-worker.log 2>&1 & } +cleanup() { + sql -c 'DROP TRIGGER IF EXISTS snapshot_fail ON documents; DROP FUNCTION IF EXISTS snapshot_fail(); DROP TRIGGER IF EXISTS snapshot_complete ON documents; DROP FUNCTION IF EXISTS snapshot_complete();' >/dev/null 2>&1 || true + cp "$TMP/font.ttf" "$FONT" + rm -f "$TMP/fail-qpdf" "$EXPLICIT" "$SEAL" /var/www/dam/seals/snapshot12-link.png /var/www/dam/seals/snapshot12-large.png + stop + su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/snapshot-worker.log 2>&1 & +} +trap cleanup EXIT +fail() { echo "FAIL - $*"; exit 1; } +status() { + want=$1; shift + got=$(curl -sS -o "$TMP/response" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H "$X" "$@") + [ "$got" = "$want" ] || fail "HTTP $got expected $want: $(head -c 400 "$TMP/response")" +} +get() { as asha clerks "$B/api/docs/$ID"; } +save() { as asha clerks -H "$X" --form-string "json=$1" "$B/api/docs/$ID/save"; } +submit() { as asha clerks -H "$X" -d '' "$B/api/docs/$ID/submit"; } +decide() { u=$1; d=$2; shift 2; as "$u" management -H "$X" -F "decision=$d" "$@" "$B/api/docs/$ID/decide"; } +wait_ready() { + for i in $(seq 1 120); do + D=$(get) + [ "$(echo "$D" | jq -r .render_error)" = null ] || fail "$D" + [ "$(echo "$D" | jq -r .rendering)" = false ] && return + sleep .1 + done + fail timeout +} +wait_error() { + for i in $(seq 1 120); do D=$(get); [ "$(echo "$D" | jq -r .render_error)" != null ] && return; sleep .1; done + fail 'expected frozen-input render failure' +} +body_has() { pdftotext -f 1 -l 2 "$1" - | grep -q "$2" || fail "body missing $2"; } +fonts_match() { + pdf=$1; expected=$(sha256sum "$2" | cut -d ' ' -f 1) + objects=$(qpdf --json "$pdf" | jq -r '.. | objects | .["/FontFile2"]? // empty' | cut -d ' ' -f 1) + [ -n "$objects" ] || fail 'no embedded TrueType font' + for object in $objects; do + got=$(qpdf --show-object="$object" --filtered-stream-data "$pdf" | sha256sum | cut -d ' ' -f 1) + [ "$got" = "$expected" ] || fail 'embedded font bytes differ from frozen input' + done +} +new_doc() { + ID=$(as asha clerks -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -r .id) + BASE=/var/lib/signet/docs/$ID + save "$LAYOUT" >/dev/null +} +stop +redis-cli DEL "$Q" "$Q:processing" >/dev/null +redis-cli HSET "$ORG:metadata" gstin BEFORE_SUBMIT >/dev/null +redis-cli HSET "$ORG:images" seal seals/snapshot12.png >/dev/null +as root signet-admins -H "$X" -F "code=$SERIES" --form-string "pattern=$SERIES/{seq:02}" "$B/api/series" >/dev/null +LAYOUT=$(jq -nc --arg org "$ORG" --arg series "$SERIES" '{title:"Frozen revision",org_code:$org,series_code:$series,route:{parties:[{name:"Manager",signer:"manager"},{name:"Audit",signer:"auditor"},{name:"Partner",signer:"ceo"}]},layout:{reference_width:1000,reference_height:1414,imprints:[{type:"pim_text",page:1,ref:"gstin",value:"FORGED_CLIENT_VALUE",font:"fonts/snapshot12.ttf",coords:[120,150,600,180]},{type:"pim_image",page:2,ref:"seal",shape:"circle",coords:[250,1050,90]},{type:"signature_zone",page:1,party:"Manager",coords:[120,550,500,700],min_w:50,min_h:20},{type:"signature_zone",page:2,party:"Partner",coords:[400,1000,850,1200],min_w:70,min_h:25}]}}') +PL1='{"page":1,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' +PL2='{"page":2,"coords":[400,1000,850,1200],"ref_w":1000,"ref_h":1414}' +new_doc +# Invalid assets fail before serial allocation; never follow a symlink out of DAM. +ln -s /src/test/fixtures/seal.png /var/www/dam/seals/snapshot12-link.png +redis-cli HSET "$ORG:images" seal seals/snapshot12-link.png >/dev/null +status 409 -d '' "$B/api/docs/$ID/submit" +truncate -s 16777217 /var/www/dam/seals/snapshot12-large.png +redis-cli HSET "$ORG:images" seal seals/snapshot12-large.png >/dev/null +status 409 -d '' "$B/api/docs/$ID/submit" +redis-cli HSET "$ORG:images" seal seals/snapshot12.png >/dev/null +redis-cli HSET "$ORG:metadata" gstin "$(head -c 1024 /dev/zero | tr '\000' x)" >/dev/null +status 409 -d '' "$B/api/docs/$ID/submit" +printf 'embedded\000null' | redis-cli -x HSET "$ORG:metadata" gstin >/dev/null +status 409 -d '' "$B/api/docs/$ID/submit" +redis-cli HSET "$ORG:metadata" gstin BEFORE_SUBMIT >/dev/null +sql <<SQL >/dev/null +CREATE FUNCTION snapshot_fail() RETURNS trigger LANGUAGE plpgsql AS \$\$ +BEGIN IF NEW.id='$ID' AND NEW.status='PENDING' THEN RAISE EXCEPTION 'snapshot rollback probe'; END IF; RETURN NEW; END \$\$; +CREATE TRIGGER snapshot_fail BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION snapshot_fail(); +SQL +status 409 -d '' "$B/api/docs/$ID/submit" +[ "$(find "$BASE" -maxdepth 1 -name 'snapshot-*' | wc -l)" = 0 ] || fail 'rollback left a private snapshot' +echo "$(get)" | jq -e '.status=="DRAFT" and .serial==null and .revision==0' >/dev/null || fail 'failed freeze allocated serial' +sql -c 'DROP TRIGGER snapshot_fail ON documents; DROP FUNCTION snapshot_fail();' >/dev/null +submit >/dev/null +SERIAL=$(get | jq -r .serial) +[ "${SERIAL##*/}" = 01 ] || fail 'failed submits consumed a serial' +DATE=$(get | jq -r .doc_date) +KEY=$(sql -c "SELECT snapshot_id FROM documents WHERE id='$ID'") +SNAP=$BASE/snapshot-$KEY +[ "$(stat -c %a "$SNAP")" = 550 ] || fail 'snapshot directory is not read-only' +for file in "$SNAP"/asset-* "$SNAP/manifest.json"; do + [ "$(stat -c %a "$file")" = 440 ] || fail 'frozen file permissions are not read-only' +done +MANIFEST=$(sql -c "SELECT snapshot_json FROM documents WHERE id='$ID'") +echo "$MANIFEST" | jq -e '.layout.imprints[0].type=="resolved_text" and .layout.imprints[0].value=="BEFORE_SUBMIT"' >/dev/null || fail 'client values used in frozen layout' +get | jq -e 'has("snapshot_json")|not' >/dev/null || fail 'private render manifest exposed' +SEAL_NAME=$(echo "$MANIFEST" | jq -r '.layout.imprints[1].ref') +[ "$(sha256sum "$SEAL" | cut -d ' ' -f 1)" = "$(sha256sum "$SNAP/$SEAL_NAME" | cut -d ' ' -f 1)" ] || fail 'seal not frozen' +echo 'ok - submit freezes server-only text/assets; unsafe/oversized inputs and DB rollback allocate no serial' + +# Change all live inputs before the worker runs, then force a real render failure. +redis-cli HSET "$ORG:metadata" gstin AFTER_SUBMIT >/dev/null +cp /src/test/fixtures/sig.png "$SEAL" +cp /usr/share/fonts/dejavu/DejaVuSansMono.ttf "$EXPLICIT" +cp /usr/share/fonts/dejavu/DejaVuSansMono.ttf "$FONT" +touch "$TMP/fail-qpdf" +start +wait_error +echo "$D" | jq -e '.render_error|contains("qpdf")' >/dev/null || fail 'failure did not use frozen inputs' +rm "$TMP/fail-qpdf" "$SEAL" "$EXPLICIT" "$FONT" +redis-cli HSET "$ORG:images" seal seals/missing-live-image.png >/dev/null +redis-cli HSET "$ORG:metadata" gstin BEFORE_RETRY >/dev/null +as asha clerks -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null +wait_ready +cmp "$BASE/proof.pdf" "$BASE/stamped.pdf" || fail 'proof and initial stamped body differ' +body_has "$BASE/proof.pdf" BEFORE_SUBMIT +pdftotext "$BASE/proof.pdf" - | grep -q FORGED_CLIENT_VALUE && fail 'client forged content' || true +fonts_match "$BASE/proof.pdf" "$TMP/font.ttf" +decide manager signoff --form-string "placement=$PL1" >/dev/null +wait_ready +body_has "$BASE/stamped.pdf" BEFORE_SUBMIT +echo 'ok - stamp failure/retry and sign-off ignore changed/deleted live PIM, seal and fonts; proof equals initial stamped bytes' + +# Correction must use a fresh snapshot while retaining the original serial/date. +decide auditor correction --form-string 'comment=Snapshot correction' >/dev/null +cp /usr/share/fonts/dejavu/DejaVuSansMono.ttf "$FONT" +cp "$FONT" "$EXPLICIT" +cp /src/test/fixtures/sig.png "$SEAL" +redis-cli HSET "$ORG:metadata" gstin NEW_REVISION >/dev/null +redis-cli HSET "$ORG:images" seal seals/snapshot12.png >/dev/null +stop +submit >/dev/null +NEWKEY=$(sql -c "SELECT snapshot_id FROM documents WHERE id='$ID'") +[ "$KEY" != "$NEWKEY" ] && [ -d "$SNAP" ] || fail 'revision snapshot not isolated/retained' +jq -e '.revision==1 and .org_code=="SNAPSHOT12" and .layout.imprints[0].value=="BEFORE_SUBMIT"' "$SNAP/manifest.json" >/dev/null || fail 'previous revision resolved metadata was lost' +get | jq -e --arg serial "$SERIAL" --arg date "$DATE" '.revision==2 and .serial==$serial and .doc_date==$date and .current_party==1' >/dev/null || fail 'revision changed numbering' +rm "$FONT" "$EXPLICIT" "$SEAL" +redis-cli HSET "$ORG:metadata" gstin CHANGED_AFTER_RESUBMIT >/dev/null +start +wait_ready +cmp "$BASE/proof.pdf" "$BASE/stamped.pdf" || fail 'revision2 proof/stamped differ' +body_has "$BASE/proof.pdf" NEW_REVISION +decide manager signoff --form-string "placement=$PL1" >/dev/null +wait_ready +decide auditor signoff >/dev/null +stop +decide ceo signoff --form-string "placement=$PL2" >/dev/null +redis-cli DEL "$ORG:metadata" "$ORG:images" >/dev/null +start +wait_ready +echo "$D" | jq -e '.status=="RELEASED"' >/dev/null || fail 'release did not use frozen audit font' +body_has "$BASE/final.pdf" NEW_REVISION +fonts_match "$BASE/final.pdf" /usr/share/fonts/dejavu/DejaVuSansMono.ttf +pdftotext "$BASE/final.pdf" - | grep -q RESUBMITTED || fail 'resubmit history missing' +echo 'ok - correction creates fresh frozen inputs with stable serial/date; release/audit succeed with live PIM/DAM removed' + +# Damaged private inputs must fail closed, never silently fall back to live assets. +cp "$TMP/font.ttf" "$FONT" +cp "$FONT" "$EXPLICIT" +cp /src/test/fixtures/seal.png "$SEAL" +redis-cli HSET "$ORG:metadata" gstin DAMAGE_TEST >/dev/null +redis-cli HSET "$ORG:images" seal seals/snapshot12.png >/dev/null +stop +new_doc +submit >/dev/null +KEY=$(sql -c "SELECT snapshot_id FROM documents WHERE id='$ID'") +SNAP=$BASE/snapshot-$KEY +cp "$SNAP/asset-0" "$TMP/frozen-original" +chmod u+w "$SNAP/asset-0" +printf damaged > "$SNAP/asset-0" +start +wait_error +echo "$D" | jq -e '.render_error|contains("live PIM/DAM fallback is forbidden")' >/dev/null || fail 'damaged snapshot did not fail closed' +cp "$TMP/frozen-original" "$SNAP/asset-0" +chown signet:signet "$SNAP/asset-0" +chmod 0440 "$SNAP/asset-0" +rm "$FONT" "$EXPLICIT" "$SEAL" +sql <<SQL >/dev/null +CREATE FUNCTION snapshot_complete() RETURNS trigger LANGUAGE plpgsql AS \$\$ +BEGIN IF NEW.id='$ID' AND NEW.rendered_seq>OLD.rendered_seq THEN RAISE EXCEPTION 'snapshot completion replay $ID'; END IF; RETURN NEW; END \$\$; +CREATE TRIGGER snapshot_complete BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION snapshot_complete(); +SQL +as asha clerks -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null +for i in $(seq 1 100); do grep -q "snapshot completion replay $ID" /tmp/snapshot-worker.log && break; sleep .1; done +grep -q "snapshot completion replay $ID" /tmp/snapshot-worker.log || fail 'stamp completion database failure not exercised' +stop +CACHE_HASH=$(sha256sum "$BASE/proof-$KEY.pdf" | cut -d ' ' -f 1) +CALLS=$(wc -l < "$TMP/qpdf-calls") +sql -c 'DROP TRIGGER snapshot_complete ON documents; DROP FUNCTION snapshot_complete();' >/dev/null +start +wait_ready +[ "$(wc -l < "$TMP/qpdf-calls")" = "$CALLS" ] || fail 'replay flattened the same revision twice' +[ "$(sha256sum "$BASE/proof.pdf" | cut -d ' ' -f 1)" = "$CACHE_HASH" ] || fail 'replay changed cached proof bytes' +body_has "$BASE/proof.pdf" DAMAGE_TEST +echo 'ok - hash-verified frozen assets fail closed; exact-input restoration permits retry without live assets' +echo 'ok - database failure/recovery reuses the byte-identical revision proof without another flatten' +echo 'snapshot contract: all passed'
diff --git a/www/app.js b/www/app.js @@ -46,14 +46,14 @@ function h(tag, attrs, ...kids) { function toast(msg, isError) { const t = document.querySelector('.toast'); t.textContent = msg; - t.className = isError ? 'error' : ''; + t.className = isError ? 'toast error' : 'toast'; t.hidden = false; clearTimeout(toast.timer); toast.timer = setTimeout(() => { t.hidden = true; }, isError ? 7000 : 3000); } /* Local development without the auth proxy: identity headers come from - * localStorage. Behind Authelia/lighttpd these are overwritten upstream. */ + * localStorage. The deployment's trusted proxy overwrites these upstream. */ function devHeaders() { try { const dev = JSON.parse(localStorage.getItem('signetDevIdentity') || 'null'); @@ -223,6 +223,24 @@ function syncOverlay(page) { }); area.title = describe(area); overlay.append(box); + if (area.dataset.placement) { + box.classList.add('placement'); + if (area === selected) box.classList.add('selected'); + box.tabIndex = 0; + box.setAttribute('aria-label', 'Signature placement: arrow keys move, Shift and arrows resize'); + box.append(h('span', { class: 'grip' })); + box.addEventListener('pointerdown', (e) => startDrag(e, area, box, page)); + box.addEventListener('keydown', (e) => { + if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return; + e.preventDefault(); + const b = bboxOf(area), dx = e.key === 'ArrowLeft' ? -5 : e.key === 'ArrowRight' ? 5 : 0; + const dy = e.key === 'ArrowUp' ? -5 : e.key === 'ArrowDown' ? 5 : 0; + constrainPlacement(area, e.shiftKey ? [b[0], b[1], b[2] + dx + dy, b[3]] : b.map((v, i) => v + (i % 2 ? dy : dx)), e.shiftKey); + syncOverlay(page); + page.querySelector('.placement').focus(); + }); + return; + } if (!editing) return; /* edit mode: the box is the layer itself */ @@ -240,8 +258,8 @@ function syncOverlay(page) { } else { box.append(h('span', { class: 'ph' }, '[PIM image not found]')); } - } else if (type === 'signature') { - box.append(h('span', { class: 'ph' }, 'Signature' + (area.dataset.ref ? ': ' + area.dataset.ref : ''))); + } else if (type === 'signature_zone') { + box.append(h('span', { class: 'ph' }, 'Signature zone: ' + (area.dataset.party || '(choose party)'))); } else { box.append(h('span', { class: 'ph' }, 'choose an image')); } @@ -251,6 +269,35 @@ function syncOverlay(page) { }); } +function constrainPlacement(area, bounds, resizing) { + const zone = [...area.closest('.page').querySelectorAll('area:not([data-placement])')].find((a) => a.dataset.type === 'signature_zone' && a.dataset.party === area.dataset.party); + const z = bboxOf(zone), ratio = app.me.facsimile.width / app.me.facsimile.height; + let [x, y, x2, y2] = bounds, w = x2 - x, height = y2 - y; + if (resizing) { + w = Math.min(z[2] - x, (z[3] - y) * ratio, Math.max(+zone.dataset.min_w, +zone.dataset.min_h * ratio, w)); + height = w / ratio; + } + x = Math.max(z[0], Math.min(z[2] - w, x)); + y = Math.max(z[1], Math.min(z[3] - height, y)); + setBbox(area, [x, y, x + w, y + height]); +} + +function setupPlacement() { + const party = doc.route.parties[doc.current_party - 1]; + const zone = [...document.querySelectorAll('area[data-type="signature_zone"]')].find((a) => a.dataset.party === party.name); + if (!zone) return; + const page = zone.closest('.page'), z = bboxOf(zone); + const ratio = app.me.facsimile.width / app.me.facsimile.height; + let w = z[2] - z[0], height = w / ratio; + if (height > z[3] - z[1]) { height = z[3] - z[1]; w = height * ratio; } + const x = z[0] + (z[2] - z[0] - w) / 2, y = z[1] + (z[3] - z[1] - height) / 2; + addArea(page, { type: 'signature_zone', party: party.name, placement: true, coords: [x, y, x + w, y + height] }); + if (w < +zone.dataset.min_w || height < +zone.dataset.min_h) { + document.querySelector('.side').append(h('p', { class: 'notice error' }, 'Your facsimile cannot fit this zone at its minimum size. Request a correction to enlarge the zone.')); + } + syncOverlay(page); +} + function startDrag(e, area, box, page) { e.preventDefault(); select(area); @@ -273,7 +320,14 @@ function startDrag(e, area, box, page) { x1 = Math.min(W - w, Math.max(0, x1 + dx)); y1 = Math.min(H - hh, Math.max(0, y1 + dy)); x2 = x1 + w; y2 = y1 + hh; } - setBbox(area, [x1, y1, x2, y2]); + if (area.dataset.placement) { + if (resizing) { + const ratio = app.me.facsimile.width / app.me.facsimile.height; + x2 = x1 + start[2] - start[0] + (Math.abs(dx) >= Math.abs(dy * ratio) ? dx : dy * ratio); + } + constrainPlacement(area, [x1, y1, x2, y2], resizing); + [x1, y1, x2, y2] = bboxOf(area); + } else setBbox(area, [x1, y1, x2, y2]); Object.assign(live.style, { left: (x1 / W) * 100 + '%', top: (y1 / H) * 100 + '%', width: ((x2 - x1) / W) * 100 + '%', height: ((y2 - y1) / H) * 100 + '%', @@ -305,7 +359,7 @@ function addArea(page, imp) { const d = area.dataset; d.type = imp.type; d.coords = imp.coords.join(','); - for (const k of ['ref', 'font', 'prefix', 'format', 'align']) if (imp[k]) d[k] = imp[k]; + for (const k of ['ref', 'font', 'prefix', 'format', 'align', 'party', 'min_w', 'min_h', 'placement']) if (imp[k]) d[k] = imp[k]; map.append(area); scaleArea(area); return area; @@ -319,20 +373,23 @@ function loadLayout(layout) { if (!page || !TYPES[imp.type]) continue; const img = page.querySelector('img'); const k = img.naturalWidth / (imp.ref_w || layout.reference_width || img.naturalWidth); - addArea(page, { ...imp, coords: imp.coords.map((v) => v * k) }); + const ky = img.naturalHeight / (imp.ref_h || layout.reference_height || img.naturalHeight); + addArea(page, { ...imp, min_w: imp.min_w * k, min_h: imp.min_h * ky, + coords: imp.coords.map((v, i) => v * (imp.shape === 'circle' || i % 2 === 0 ? k : ky)) }); } refitAll(); } function collectLayout() { const first = document.querySelector('.page img'); - const imprints = [...document.querySelectorAll('.page area')].map((area) => { + const imprints = [...document.querySelectorAll('.page area:not([data-placement])')].map((area) => { const img = area.closest('.page').querySelector('img'), d = area.dataset; const imp = { page: +area.closest('.page').dataset.page, shape: area.shape || 'rect', type: d.type, ref: d.ref || '', coords: getCoords(area), ref_w: img.naturalWidth, ref_h: img.naturalHeight, }; - for (const k of ['font', 'prefix', 'format', 'align']) if (d[k]) imp[k] = d[k]; + for (const k of ['font', 'prefix', 'format', 'align', 'party']) if (d[k]) imp[k] = d[k]; + for (const k of ['min_w', 'min_h']) if (d[k]) imp[k] = +d[k]; return imp; }); return { reference_width: first.naturalWidth, reference_height: first.naturalHeight, imprints }; @@ -388,7 +445,7 @@ function placeNew(page, type, cx, cy) { const x1 = Math.max(0, Math.min(img.naturalWidth - t.w, cx - t.w / 2)); const y1 = Math.max(0, Math.min(img.naturalHeight - t.h, cy - t.h / 2)); const imp = { type, coords: [x1, y1, x1 + t.w, y1 + t.h] }; - if (type === 'signature_zone') imp.party = collectRoute().parties[0]?.name || ''; + if (type === 'signature_zone') Object.assign(imp, { party: collectRoute().parties[0]?.name || '', min_w: 50, min_h: 30 }); select(addArea(page, imp)); } @@ -490,11 +547,10 @@ function collectRoute() { } function historyList() { - if (!doc.decisions.length) return null; - const words = { SIGNOFF: 'signed off', CORRECTION: 'asked for correction', DISAPPROVE: 'disapproved' }; - return [h('h2', {}, 'History'), h('ul', { class: 'history' }, doc.decisions.map((x) => - h('li', {}, h('strong', {}, x.signer), ` ${words[x.decision]} · party ${x.party} · rev ${x.revision}`, - h('span', { class: 'c' }, fmtTime(x.decided_at) + (x.comment ? ' · “' + x.comment + '”' : '')))))]; + if (!doc.events?.length) return []; + return [h('h2', {}, 'Event log'), h('ul', { class: 'history' }, doc.events.map((x) => + h('li', {}, h('strong', {}, x.actor), ' · ' + x.action.replace(/_/g, ' '), + h('span', { class: 'c' }, fmtTime(x.at) + (x.detail ? ' · ' + x.detail : '')))))]; } /* ---------- document view ---------- */ @@ -529,9 +585,10 @@ async function showDoc(id) { view.replaceChildren(h('p', { class: 'notice error' }, e.message)); return; } + if (doc.can_decide) app.me = await api('/me'); doc.mode = doc.can_edit ? 'edit' : 'preview'; const pending = ['PENDING'].includes(doc.status); - const stamping = pending && doc.render_seq < doc.revision && !doc.render_error; + const rendering = pending && doc.rendering && !doc.render_error; /* which flattened copy is the base image */ let kind = 'source'; @@ -553,11 +610,13 @@ async function showDoc(id) { notices.append(h('p', { class: 'notice' }, `Correction requested by ${last ? last.signer : 'a checker'}: “${last ? last.comment : ''}”`)); } if (doc.render_error) { - notices.append(h('p', { class: 'notice error' }, 'Stamping failed: ' + doc.render_error + ' ', - h('button', { onclick: () => act(() => api(`/docs/${id}/rerender`, { method: 'POST' }), 'Queued again') }, 'Retry stamping'))); + notices.append(h('p', { class: 'notice error' }, 'Rendering failed: ' + doc.render_error)); + } + if (doc.can_retry) { + notices.append(h('button', { onclick: () => act(() => api(`/docs/${id}/rerender`, { method: 'POST' }), 'Queued again') }, 'Retry rendering')); } - if (stamping) { - notices.append(h('p', { class: 'notice' }, 'Stamping in progress…')); + if (rendering) { + notices.append(h('p', { class: 'notice' }, 'Rendering in progress…')); pollTimer = setTimeout(() => showDoc(id), 1200); kind = 'source'; } @@ -567,9 +626,9 @@ async function showDoc(id) { if (doc.mode === 'edit') { const orgs = Object.keys(app.pim || {}).sort(); side.append( - ...field('Title (blank = use the serial number)', h('input', { id: 'f-title', value: doc.title, maxlength: 200 })), + ...field('Title (required)', h('input', { id: 'f-title', value: doc.title, maxlength: 200, required: true, oninput: (e) => { document.getElementById('submit-doc').disabled = !e.target.value.trim(); } })), h('p', { style: 'margin: 0.5rem 0; font-size: 12px' }, h('span', { class: 'status ' + doc.status }, doc.status.replace(/_/g, ' '))), - ...field('Organisation (required)', selectEl([['', '(choose)'], ...orgs.map((org) => [org, org])], doc.org_code, refitAll, { id: 'f-org' })), + ...field('Organisation (required)', selectEl([['', '(choose)'], ...orgs.map((org) => [org, org])], doc.org_code, (value) => { doc.org_code = value; refitAll(); renderProps(); }, { id: 'f-org' })), ...field('Series', selectEl([['', '(none)'], ...app.series.map((s) => [s.code, `${s.code} · ${s.pattern}`])], doc.series_code, refitAll, { id: 'f-series', disabled: !!doc.serial })), doc.serial ? h('p', { class: 'mono' }, doc.serial) : null, h('h2', {}, 'Imprints'), @@ -579,10 +638,10 @@ async function showDoc(id) { ondblclick: () => { const p = document.querySelector('.page'); const i = p.querySelector('img'); placeNew(p, type, i.naturalWidth / 2, i.naturalHeight / 2); }, }, t.label))), h('div', { id: 'props' }), - h('h2', {}, 'Approval route'), routeEditor(doc.route, true), + h('h2', {}, 'Signing route'), routeEditor(doc.route, true), h('div', { class: 'actions' }, h('button', { onclick: () => act(saveDoc, 'Saved', false) }, 'Save draft'), - h('button', { class: 'primary', onclick: () => act(async () => { await saveDoc(); await api(`/docs/${id}/submit`, { method: 'POST' }); }, 'Submitted for approval') }, doc.status === 'CORRECTION_REQUIRED' ? 'Resubmit' : 'Submit for approval'), + h('button', { id: 'submit-doc', class: 'primary', disabled: !doc.title.trim(), onclick: () => act(async () => { await saveDoc(); await api(`/docs/${id}/submit`, { method: 'POST' }); }, 'Submitted') }, doc.status === 'CORRECTION_REQUIRED' ? 'Resubmit' : 'Submit'), h('button', { onclick: () => { const name = prompt('Template name'); if (name) act(async () => { await saveDoc(); await api('/templates', { method: 'POST', fields: { doc_id: id, name } }); app.templates = await api('/templates'); }, 'Template saved', false); } }, 'Save as template'), doc.status === 'DRAFT' && !doc.serial ? h('button', { class: 'danger', onclick: () => { if (confirm('Delete this draft?')) act(async () => { await api(`/docs/${id}/delete`, { method: 'POST' }); location.hash = '#/'; }, 'Deleted', false); } }, 'Delete draft') : null)); } else { @@ -593,7 +652,7 @@ async function showDoc(id) { h('p', {}, h('span', { class: 'mono' }, doc.serial || '(no serial)'), h('br'), `Prepared by ${doc.drafter_user}`, h('br'), `Submitted ${fmtTime(doc.submitted_at)} · revision ${doc.revision}`), doc.status === 'RELEASED' ? h('p', {}, `Released ${fmtTime(doc.released_at)}`, h('br'), h('span', { class: 'mono' }, 'sha256 ' + doc.final_sha256), h('br'), h('button', { class: 'primary', onclick: () => act(async () => { const buf = await api(`/docs/${id}/file/final`, { raw: true }); window.open(URL.createObjectURL(new Blob([buf], { type: 'application/pdf' }))); }, null, false) }, 'Open print copy (PDF)')) : null, - h('h2', {}, 'Approval route'), routeEditor(doc.route, false)); + h('h2', {}, 'Signing route'), routeEditor(doc.route, false)); if (doc.can_decide) { const comment = h('textarea', { rows: 3, placeholder: 'Comment (required unless signing off)' }); const currentParty = doc.current_party > 0 && doc.route.parties ? doc.route.parties[doc.current_party - 1] : null; @@ -602,7 +661,7 @@ async function showDoc(id) { if (needsEnrolment) { /* Show enrolment dialog */ - const canvas = h('canvas', { width: 400, height: 200, style: 'border: 1px solid #ccc; display: block; margin: 1rem 0' }); + const canvas = h('canvas', { width: 400, height: 200, class: 'enrol-canvas' }); const fileInput = h('input', { type: 'file', accept: 'image/png', style: 'margin: 1rem 0' }); let isDrawing = false; let ctx = canvas.getContext('2d'); @@ -611,13 +670,14 @@ async function showDoc(id) { ctx.strokeStyle = '#000'; ctx.lineWidth = 2; - const drawStart = (e) => { isDrawing = true; const rect = canvas.getBoundingClientRect(); ctx.beginPath(); ctx.moveTo(e.clientX - rect.left, e.clientY - rect.top); }; - const drawMove = (e) => { if (!isDrawing) return; const rect = canvas.getBoundingClientRect(); ctx.lineTo(e.clientX - rect.left, e.clientY - rect.top); ctx.stroke(); }; + const point = (e) => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * canvas.width / r.width, (e.clientY - r.top) * canvas.height / r.height]; }; + const drawStart = (e) => { isDrawing = true; canvas.setPointerCapture(e.pointerId); ctx.beginPath(); ctx.moveTo(...point(e)); }; + const drawMove = (e) => { if (isDrawing) { ctx.lineTo(...point(e)); ctx.stroke(); } }; const drawEnd = () => { isDrawing = false; }; - canvas.addEventListener('mousedown', drawStart); - canvas.addEventListener('mousemove', drawMove); - canvas.addEventListener('mouseup', drawEnd); - canvas.addEventListener('mouseout', drawEnd); + canvas.addEventListener('pointerdown', drawStart); + canvas.addEventListener('pointermove', drawMove); + canvas.addEventListener('pointerup', drawEnd); + canvas.addEventListener('pointercancel', drawEnd); const enrol = async () => { let blob; @@ -634,7 +694,8 @@ async function showDoc(id) { const me = await api('/me'); if (me.enrolled) { toast('Ready to sign!'); - location.hash = '#/doc/' + id; /* Reload the page */ + app.me = me; + await showDoc(id); return; } } @@ -650,18 +711,19 @@ async function showDoc(id) { const placementInput = hasZone ? h('input', { type: 'hidden', id: 'f-placement', value: '' }) : null; const decide = (decision) => act(async () => { const fields = { decision, comment: comment.value }; - if (hasZone && decision === 'approve') { - const pl = document.getElementById('f-placement').value; - if (!pl) throw new Error('Placement required for signature zones'); - fields.placement = pl; + if (hasZone && decision === 'signoff') { + const area = document.querySelector('area[data-placement]'); + if (!area) throw new Error('Placement required for signature zones'); + const img = area.closest('.page').querySelector('img'); + fields.placement = JSON.stringify({ page: +area.closest('.page').dataset.page, coords: getCoords(area), ref_w: img.naturalWidth, ref_h: img.naturalHeight }); } return api(`/docs/${id}/decide`, { method: 'POST', fields }); }, 'Recorded'); side.append(h('h2', {}, 'Your decision'), comment); - if (placementInput) side.append(h('p', { class: 'notice' }, 'Draw your signature placement in the zone on the page')); + if (placementInput) side.append(h('p', { class: 'notice' }, 'Position your facsimile inside the signature zone. Drag the placement or use arrow keys; Shift and arrows resize.')); if (placementInput) side.append(placementInput); side.append(h('div', { class: 'actions' }, - h('button', { class: 'primary', onclick: () => decide('approve') }, 'Sign off'), + h('button', { class: 'primary', onclick: () => decide('signoff') }, 'Sign off'), h('button', { onclick: () => decide('correction') }, 'Correction required'), h('button', { class: 'danger', onclick: () => { if (confirm('Disapprove this document? This is final.')) decide('disapprove'); } }, 'Disapprove'))); } @@ -673,6 +735,7 @@ async function showDoc(id) { try { await renderPdf(pages, await api(`/docs/${id}/file/${kind}`, { raw: true })); loadLayout(doc.layout); + if (doc.can_decide && app.me.enrolled) setupPlacement(); renderProps(); } catch (e) { pages.replaceChildren(h('p', { class: 'notice error' }, 'Could not load the PDF: ' + e.message));
diff --git a/www/style.css b/www/style.css @@ -49,16 +49,17 @@ tr.click:hover td { background: #f6f9fc; } .side { flex: 0 0 25%; padding: 1.2rem; background: var(--bg); border-left: 1px solid var(--line); overflow-y: auto; } @media (max-width: 900px) { .workspace { flex-direction: column; } .pages { flex: 0 0 auto; overflow-y: visible; } .side { flex: 0 0 auto; background: transparent; border-left: none; overflow-y: visible; } } .pages { display: flex; flex-direction: column; gap: 1rem; align-items: center; } -.page { position: relative; width: 100%; max-width: 1000px; background: #fff; box-shadow: 0 1px 4px rgba(20, 30, 45, .25); line-height: 0; } +.page { position: relative; flex-shrink: 0; width: 100%; max-width: 1000px; background: #fff; box-shadow: 0 1px 4px rgba(20, 30, 45, .25); line-height: 0; } .page > img { width: 100%; height: auto; display: block; user-select: none; -webkit-user-drag: none; } .page .overlay { position: absolute; inset: 0; line-height: normal; } .page .pageno { position: absolute; top: 4px; right: -2.2rem; font-size: 11px; color: var(--muted); line-height: 1; } .notice { padding: .6rem .8rem; border-radius: 4px; background: #fff1cf; color: #6b4b00; margin-bottom: .8rem; } .notice.error { background: #f8d9d8; color: #7a201c; } -.box { position: absolute; border: 1.5px solid rgb(var(--c)); background: rgba(var(--c), .10); overflow: hidden; white-space: nowrap; color: #000; } -.box.t-signature { --c: var(--sig); } -.box.t-dam_image { --c: var(--img); } +/* Decoration must not shrink the imprint geometry used by fitText/object-fit. */ +.box { position: absolute; outline: 1.5px solid rgb(var(--c)); outline-offset: -1.5px; background: rgba(var(--c), .10); overflow: hidden; white-space: nowrap; color: #000; } +.box.t-signature_zone { --c: var(--sig); } +.box.t-pim_image { --c: var(--img); } .box.t-pim_text, .box.t-date, .box.t-serial { --c: var(--txt); } .box.circle { border-radius: 50%; } .box img { width: 100%; height: 100%; object-fit: contain; pointer-events: none; display: block; } @@ -67,19 +68,21 @@ tr.click:hover td { background: #f6f9fc; } /* preview mode: translucent shapes above the flattened copy; the <area>s underneath keep their native tooltips */ .preview .overlay { pointer-events: none; } -.preview .box { background: rgba(var(--c), .16); border-style: dashed; } +.preview .box { background: rgba(var(--c), .16); outline-style: dashed; } .hide-overlays .overlay { display: none; } /* edit mode */ -.edit .box { cursor: move; touch-action: none; } +.edit .box, .preview .placement { cursor: move; touch-action: none; } +.preview .placement { pointer-events: auto; outline-style: solid; } +.preview .placement:focus { outline: 2px solid rgb(var(--sig)); outline-offset: 2px; } .edit .box.selected { outline: 2px solid rgb(var(--c)); outline-offset: 1px; background: rgba(var(--c), .18); } -.edit .box .grip { position: absolute; right: 0; bottom: 0; width: 9px; height: 9px; background: rgb(var(--c)); opacity: .55; cursor: nwse-resize; clip-path: polygon(100% 0, 100% 100%, 0 100%); } +.edit .box .grip, .preview .placement .grip { position: absolute; right: 0; bottom: 0; width: 9px; height: 9px; background: rgb(var(--c)); opacity: .55; cursor: nwse-resize; clip-path: polygon(100% 0, 100% 100%, 0 100%); } .edit .box.circle .grip { right: 12%; bottom: 12%; border-radius: 50%; } .page.dragover { outline: 3px dashed var(--accent); } .palette { display: grid; grid-template-columns: 1fr 1fr; gap: .4rem; } .palette .chip { border: 1.5px solid rgb(var(--c)); background: rgba(var(--c), .1); border-radius: 4px; padding: .35rem .5rem; cursor: grab; font-size: 13px; text-align: center; user-select: none; } -.chip.t-signature { --c: var(--sig); } .chip.t-dam_image { --c: var(--img); } +.chip.t-signature_zone { --c: var(--sig); } .chip.t-pim_image { --c: var(--img); } .chip.t-pim_text, .chip.t-date, .chip.t-serial { --c: var(--txt); } .level { border: 1px solid var(--line); border-radius: 4px; padding: .5rem; margin-bottom: .4rem; } @@ -88,6 +91,7 @@ tr.click:hover td { background: #f6f9fc; } .history { font-size: 13px; margin: 0; padding: 0; list-style: none; } .history li { padding: .35rem 0; border-bottom: 1px solid var(--line); } .history .c { color: var(--muted); display: block; } +.enrol-canvas { display: block; max-width: 100%; touch-action: none; border: 1px solid var(--line); margin: 1rem 0; } .actions { display: flex; gap: .4rem; flex-wrap: wrap; margin-top: .8rem; } .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; word-break: break-all; } .legend { display: flex; gap: .8rem; font-size: 12px; color: var(--muted); flex-wrap: wrap; }
: asapien/signet