commit 20b1d2a332bea3abbd01c2290fe1a2b1cc0982bb
parent 68ed63bb2af5e8f41e57db11432c73357a5caae7
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 05:05:25 +0530
parent 68ed63bb2af5e8f41e57db11432c73357a5caae7
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 05:05:25 +0530
Repair render jobs and complete sequential worker-owned release
23 files changed, 2192 insertions(+), 928 deletions(-)
A
|
141
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
112
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
122
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
|
86
++++++++++++++++++++++++++++++-------------------------------------------------
M
|
600
++++++++++++++++++++++++++++++++++++++++++-------------------------------------
A
|
236
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
133
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.scratch/roadmap/spec.md b/.scratch/roadmap/spec.md @@ -0,0 +1,141 @@ +# Feature-first implementation roadmap + +Recorded 2026-11-10 after source/documentation reconciliation. + +## Priority decision + +The owner raised authentication work as an impediment to feature implementation. +Proceed with core workflow repairs first. Signet consumes trusted forwarded +identity (`Remote-User`, with the existing configurable group/role mapping); +it does not implement or administer an authentication server. The provider, +including whether to use Authelia at all, is the deployment administrator's +choice. Provider-specific setup is outside product scope. Fail-closed identity +handling and verification of the forwarded-header trust boundary remain +mandatory before production release or exposure to untrusted users. + +Use explicit development identity headers and the existing configurable roles +for feature tests. Keep the stack isolated: current missing-header behavior +silently grants an admin identity. This roadmap does not approve that behavior +for production, introduce new auth machinery, or relax party/file authorization. +Preserve unrelated working-tree changes, including unfinished auth experiments. + +The agreed model remains in `CONTEXT.md`, `HANDOFF.md` §2 and the ADR. Source +findings are in `HANDOFF.md` §4. Historical completed tasks are not fresh evidence. +Each implementation task must extend `test/e2e.sh`, build cleanly with +`-Wall -Wextra`, and record actual results. Rendering changes also require the +edit/proof/stamped visual comparisons specified by `AGENTS.md`. + +## 1. Repair the render-job contract — ticket 10 + +Completed: evidence in `ticket-10.md`; actual release coverage added by ticket 11. +The original implementation scope follows. + +Start here. API, worker, retry logic and browser must agree on what work is +requested and how completion is tracked. + +- Define and use consistent document-job payloads containing document id, + revision, render sequence and kind; keep enrolment jobs distinct. +- Use `render_seq`/`rendered_seq` for render progress, not comparisons against + document revision. Revision still scopes submits and decisions. +- Ignore stale jobs without changing current output or database state. +- Keep `BRPOPLPUSH`/`LREM` and startup recovery. Check database update results + before acknowledging processed work; preserve jobs on database failure. +- Make retry authorization and behavior match the stored render kind. +- Ensure retry/recovery does not apply a facsimile twice. + +Acceptance: cover stamp/sign/release dispatch, stale jobs, retry, database-update +failure, processing-queue recovery and client progress/error handling. Where +release remains a placeholder, test dispatch now and defer actual release +success to ticket 11; do not claim the whole signing flow works yet. + +## 2. Complete sequential signing and worker-owned release — ticket 11 + +Completed 2026-11-12: real API/worker/browser acceptance and visual evidence in +`ticket-11.md`. Submit-time snapshots and production identity remain separate. + +Depends on ticket 10, not authentication integration. + +- Render the decision of the party that just signed, even after current-party + advancement. Read enrolled facsimiles through configured `sig_dir` in the + worker only; validate placement page, bounds and minimum dimensions. +- Support check-only parties without a facsimile overlay. +- Move final rendering out of the API. The worker overlays the last facsimile, + appends the complete event log, computes the body hash and sets `RELEASED` + only after the final artifact is ready. +- Enforce sequential file visibility, including direct file endpoints; later + parties cannot fetch early and `final.pdf` is available only after release. + Preserve drafter/signer self-service and legitimate admin access. +- Reject empty titles at submit. On correction/resubmit preserve serial and + document date, void prior sign-offs, restart at party one, and record + `RESUBMITTED` rather than `SUBMITTED`. + +Acceptance: a multi-party route with a non-final zone party, a check-only party, +first-signing enrolment and a final zone party; earlier facsimile visible to the +next party; later-party access denied until its turn; self-service; correction +and resubmit; terminal disapproval; failed sign/release and successful retry; +full audit history and final hash. Compare placements and facsimiles visually +on both pages. No API reads of `sig_dir` or synchronous API release remain. + +## 3. Freeze submit-time content — ticket 12 + +Depends on ticket 11 in this implementation sequence. + +- Resolve and persist organisation PIM text/image references at submit. +- Freeze the DAM inputs needed for that revision, including fonts and images; + storing a mutable path alone is not a snapshot. +- Produce one flattened proof per revision and derive the initial stamped copy + from that same output, rather than resolving/rendering twice. +- Sign-offs and retries use only that revision's frozen content. A correction + and resubmit creates a new revision snapshot without changing serial/date. +- Keep clients reference-only, worker-only facsimile access, existing DOM layout + state, identical browser/server text fitting, and the resource constraints. + +Acceptance: change PIM text, seal and font after submit but before worker +processing, between sign-offs and before retry. The submitted revision must +retain its frozen content throughout. A new revision may use updated inputs. +Verify proof/stamped base equality, final output and both-page visual alignment; +measure resource use against the under-60-MB Signet RSS budget. + +## 4. Harden identity handling — ticket 13 (deferred release blocker) + +Not a prerequisite for tickets 10–12. Schedule before deployment verification. + +- Remove the unconditional missing-header admin/group fallback. +- Fail closed on missing or invalid identity; define and test handling of absent + group headers so no privilege is fabricated. Keep group names config-only. +- Retain explicit isolated-dev test headers; avoid requiring Authelia just to + run feature tests. Separate production proxy integration from this small + identity-handling change. + +Acceptance: regression tests against both APIs for absent, invalid and incomplete +identity headers; explicit test users receive only configured roles. Missing +identity never yields admin access. Feature tests still run without Authelia. + +## 5. Verify production deployment — ticket 14 (release gate) + +Depends on tickets 10–13. No public/production deployment until complete. + +- Verify Signet's contract with the deployment's trusted forward-auth proxy: + forwarded identity reaches the app, client identity headers are overwritten, + and direct backend bypass is prevented. The administrator owns authentication + server choice, configuration and sessions; no provider-specific implementation + or administration belongs in Signet. +- Prove authenticated identities/roles reach both APIs. Test spoofed headers, + unauthenticated requests and authorization failures end to end. +- Settle the owner's DAM writer policy and implement it; enforce PIM writes. +- Keep unfinished provider-specific auth/dev-stack experiments separate from + core application work; their presence is not integration evidence. +- Verify native Alpine installation, OpenRC services, separate OS users, + filesystem/database permissions, Redis AOF and production lighttpd CSP. +- Run full acceptance and measure RSS on the target-class environment. + +Acceptance: recorded evidence for all checks above on bare-metal/VM Alpine with +OpenRC, not just the development container. All Signet processes stay under +60 MB RSS on the 1-vCPU/1-GB target. No prohibited production dependencies. + +## Later improvements + +Font-list validation and document-list pagination/search follow core workflow +correctness. They do not justify delaying tickets 10–12 for auth integration, +nor bypassing the production gate. Scope and acceptance criteria should be +specified separately before implementation.
diff --git a/.scratch/roadmap/ticket-10.md b/.scratch/roadmap/ticket-10.md @@ -0,0 +1,112 @@ +# Ticket 10 — render-job contract + +Implemented and targeted checks run on 2026-11-10. This is not full product +acceptance or production approval; tickets 11–14 remain open. + +## Changes + +- Document jobs carry `doc_id`, `revision`, `seq` and `kind`. Submit and + non-final zone sign-off enqueue only after the database transaction commits. + A post-commit queue outage returns 503 without undoing the committed action; + kind-aware retry can enqueue it later. +- The worker validates payloads and locks the matching pending document row + for its revision, sequence and kind. Stale, duplicate, malformed and already + failed jobs do not rerender or append outcome events. +- Output publication, completion/error update and outcome event are serialized + with API transitions. The update must return one row and the event/update + transaction must commit before the job is acknowledged. Database failures + retain work; startup and lost-acknowledgement recovery drain `:processing`. +- Sign renders read the last committed immutable `render-<seq>.pdf`, never the + possibly already-published `stamped.pdf`. Publication uses a temporary hard + link plus rename; after commit the previous immutable base is removed. Replay + after publication but before database commit therefore cannot double-stamp. + This does not add a history of cached copies; only the current base is needed + after success. Interrupted attempts can leave orphan scratch files; automatic + orphan cleanup is not implemented here. +- Retry increments render sequence without changing revision, preserves stored + kind, and is authorized for drafter/admin on stamp, current/preceding signer + or admin on sign/release. Completed work is not retryable. The API exposes + `rendered_seq`, `render_kind`, `rendering` and `can_retry`; browser polling, + errors and retry controls use those fields. +- Enrolment jobs are handled separately, without requiring a document id. Inbox + data survives a failed database transaction. Worker read permissions and + inbox ownership in the dev harness are corrected; stored facsimiles remain + worker-owned mode 0600. + +Enabling real sign dispatch required narrow prerequisite fixes: retain layout +JSON through placement validation (removing a use-after-free), select the party +that just signed, read configured `sig_dir`, supply renderer scratch directory, +and convert reference pixels to PDF points. Broader placement validation and +final-party handling remain ticket 11. + +## Verification + +Clean Alpine image build with `-Wall -Wextra`: no compiler warnings. +Targeted regression entrypoint: + +```sh +podman exec signet-ticket10-final sh /src/test/e2e.sh render-contract +``` + +Result: **`render contract: all passed`**. It verifies: + +- submit/sign payloads, outstanding-render metadata and authorization; +- completed/malformed jobs, plus stale revision/sequence/kind jobs while newer + work is still outstanding; +- missing-facsimile failure and signer retry with sequence greater than revision; +- a real PostgreSQL trigger failure on completion after PDF publication; +- retained work and recovery from the processing list after worker restart; +- no duplicate facsimile images or committed worker sign events on replay; +- release dispatch and retry produce an explicit `RELEASE_FAILED`, not false + release success while the worker release branch is unimplemented; +- Redis LPUSH denial after commit returns 503 and leaves retryable work; +- an enrol job with no document id is activated by the worker. + +Browser regression (dev-only Playwright Core, installed outside the repository): + +```sh +PLAYWRIGHT_MODULE=/tmp/signet-ticket10-browser/node_modules/playwright-core/index.mjs \ + node test/render-progress.mjs +``` + +Result: polling for a sequence greater than revision, stopping on error, +permission-controlled retry and completion **passed** in Chrome. API responses +are intercepted for this browser state test; the shell test exercises the real +API and worker. `node --check`, `sh -n` and `git diff --check` also pass. + +Two-page edit/proof/stamped visual comparison was performed using synthetic +fixtures. Both pages retain their text positions; the non-final party's +facsimile appears inside its page-2 zone and page 1 is unchanged by sign-off. +Browser screenshots temporarily expanded the scroll containers for capture; +this is not a CSS/layout acceptance pass. The draft's browser-local date and +submitted database date differed across time zones, as expected for this run; +this check does not establish timezone policy or all text-fitting cases. + +Local evidence (temporary, not committed): + +- `/tmp/signet-ticket10-build-final.log` — clean image build +- `/tmp/signet-ticket10-build-incremental.log` — subsequent renderer cleanup build +- `/tmp/signet-ticket10-tests-final.log` — targeted shell regression +- `/tmp/signet-ticket10-browser-final.log` — browser state regression +- `/tmp/signet-ticket10-visual-final.log` — visual fixture id +- `/tmp/signet-ticket10-browser/{edit,proof,stamped}-{1,2}.png` — captures + +## Limits and next work + +- The default legacy `test/e2e.sh` flow was not certified by this task. It + contains assertions incompatible with current code/model (missing-header + 401 despite the existing admin fallback, signatures already present before + sign-off, and synchronous final release). Do not report a full suite pass. + Reconcile that acceptance flow as part of ticket 11; do not weaken the model. +- API-side final release still exists. No final-party overlay/audit-history or + sequential file-visibility acceptance is claimed here (ticket 11). +- Submit-time PIM/DAM snapshotting is still missing (ticket 12). Stamp retries + still reread those mutable sources. +- This is one serial worker; concurrent workers sharing the processing list + are not supported or tested. Row locking intentionally covers rendering on + the small target machine. +- Old payloads lacking kind/sequence are rejected rather than guessed. Existing + pending documents from an older dev run require explicit retry/new payloads. +- Provider-specific authentication setup is not part of Signet. The app's + forwarded-identity trust boundary and fail-closed handling remain ticket 13; + the deployment administrator owns their authentication server.
diff --git a/.scratch/roadmap/ticket-11.md b/.scratch/roadmap/ticket-11.md @@ -0,0 +1,122 @@ +# Ticket 11 — sequential signing and worker-owned release + +Completed and verified in isolated development on 2026-11-12. No commit, +production deployment, authentication-provider integration or production +acceptance is implied. Scope/acceptance: `spec.md` §2; accepted model unchanged. + +## Implementation + +- Route access uses party order for listing, detail and files. Later parties + cannot fetch early; route access excludes drafts/corrections. Drafter-only + access does not expose `stamped.pdf`; `final.pdf` requires `RELEASED`. +- Decisions are revision/party-scoped and locked. Check-only parties advance + without a facsimile or render. Zone sign-offs require an enrolled facsimile + and typed placement: correct page, finite coordinates, positive reference + frame, positive in-zone rectangle and minimum fitted image dimensions. The + minimum check accounts for image aspect ratio and actual PDF page dimensions, + not just an arbitrarily large placement rectangle. One zone per known party; + party names are unique. External commands remain through `run_cmd()`. +- The worker selects the just-signed party for intermediate overlays, or the + current last party for release. It aspect-fits/centres the PNG and uses the + immutable committed preceding render as its input. Check-only final decisions + copy that body. No API signature-file reads or synchronous API release remain. +- Last sign-off queues `release`, leaving the document pending. The worker + overlays the final facsimile, hashes the signed body, records `RELEASED` and + renders the complete cross-revision event log with metadata and body hash. + UTF-8-safe word wrapping/pagination has no historical-event/comment truncation; + input comments are explicitly limited to 4096 bytes. `final_sha256` covers the + whole final PDF (including audit), not just the body. +- A savepoint rolls back the release event on output failure. Database failure + retains the processing job; published final files remain inaccessible before + commit. Release replay does not double-stamp or duplicate its event. Completed + job replay retries cleanup if interrupted after commit; stamped/candidate + copies are removed before acknowledgement. +- Title is mandatory before submit. Create/submit/decision events share their + state transactions; rerender state and RETRY event share one SQL statement. + Correction invalidates the old signing state and removes stamped inputs. + Resubmit keeps serial/date, starts party one again and logs `RESUBMITTED`. +- The browser retains party/minimum/reference properties through layout edits, + supports aspect-constrained pointer/keyboard placement and first-signing + enrolment, refreshes enrolment state, shows the event log and polls release. + Empty titles disable Submit. Drawing supports scaled pointer/touch coordinates. + Worker enrolment fully decodes bounded PNGs before accepting them. + +Prerequisite bugs exposed by acceptance were also fixed: `/api/pim` now merges +metadata/images under one organisation object (including duplicate SCAN hits), +`pim_image` resolves its PIM key to a DAM path, validation no longer uses a freed +Redis reply or truncates iteration at the first signature zone, and repeated +browser notifications retain the `.toast` selector. Worker DB grants now include +SELECT on `doc_events`; dev facsimile dimensions match the synthetic PNG. + +## Verification + +Clean image `signet-ticket11`, image id +`218ae9c6cba2ea6515c62771ce3cd969bac634e616b2939bc16bdd50f24ce907`; +fresh container `signet-ticket11-verify` on localhost:8080. The final test-only +malformed-PNG extension was copied into that container before rerunning the +contract suite; compiled binaries are from the clean image. Synthetic fixtures +only. Explicit forwarded identity/group headers are supplied in tests. + +- `/tmp/signet-ticket11-build-final.log`: full Alpine build/install with + `-Wall -Wextra`, no compiler warnings/errors. +- `/tmp/signet-ticket11-e2e-final.log`: `test/e2e.sh` ends **all passed**. + Covers organisation text/images, title/serial rollback, later-party + list/detail/file denial, unsigned proof, invalid/scaled placements (including + a rectangle that passes minimums but whose aspect-fitted image does not), + check-only signing, first enrolment, final-party overlay, failed release and + authorized retry, audit/body hash/final hash/cleanup, correction/resubmit with + preserved serial/date and no old facsimiles, 80 injected historical events and + a long correction sentinel on multiple audit pages, terminal disapproval, + self-service, template/series lifecycle. Also rejects unknown/duplicate zones, + integer-overflow pages, missing image references after a zone, duplicate final + decisions and unauthorized release retries. +- `/tmp/signet-ticket11-contract-final.log`: `test/e2e.sh render-contract` + ends **render contract: all passed**. Retains ticket-10 stamp/sign dispatch, + stale/malformed/mismatched jobs, database failure/startup recovery and queue + outage assertions. Adds actual release publication-before-DB-failure/replay, + pre-commit final-access denial, body/final hashes, exactly one release event, + cleanup after interrupted post-commit acknowledgement, and malformed PNG + rejection. These use real PostgreSQL triggers and real queue/worker execution. +- `/tmp/signet-ticket11-browser.log`: `test/signing-flow.mjs` passes against the + real API/worker, using externally installed Playwright Core and Chrome (dev + only). Tests edit/save and title gate, two-page proof, constrained keyboard and + pointer placement, sequential access, check-only, upload enrolment and UI + refresh, final release/event log/print control. No unhandled JS errors. + Latest visual document: `b154d5e9-0f15-4785-8af2-885b33df798a`. +- `/tmp/signet-ticket11-progress.log`: existing `test/render-progress.mjs` + polling/failure/retry-authorization/completion regression passes. Its mocked + progress cases supplement, not replace, the real worker tests. +- Visually inspected both synthetic pages in edit/proof/stamped/final screenshots + under `/tmp/signet-ticket11-browser/`, plus `audit.png`. Text and circular seal + align, unsigned proof has no facsimiles, the first facsimile survives unchanged + into final, the last appears on page two, and the audit is legible. These are + targeted fixture comparisons, not general PDF compatibility acceptance. +- `node --check` for client and browser tests, `sh -n` for all changed shell + tests/entrypoint and `git diff --check` pass. +- Observed idle app RSS including lighttpd, kfcgi, APIs/parser children and worker: + about 20 MB; worker 2836 KB, API processes up to 2680 KB. This excludes + PostgreSQL/Redis and is not a peak-load or native 1-vCPU production certificate. + +Browser commands (dependencies remain outside the repository): + +```sh +PLAYWRIGHT_MODULE=/tmp/signet-ticket10-browser/node_modules/playwright-core/index.mjs node test/signing-flow.mjs +PLAYWRIGHT_MODULE=/tmp/signet-ticket10-browser/node_modules/playwright-core/index.mjs SIGNET_EVIDENCE=/tmp/signet-ticket11-progress node test/render-progress.mjs +``` + +## Remaining scope / limits + +- Ticket 12: PIM/DAM still resolve during worker stamping, with proof/stamped + rendered separately; a submit-time frozen revision is not implemented. The + image-key/aggregation repairs above do not establish snapshot immutability. +- Tickets 13/14: fail-closed identity, trusted proxy boundary, DAM writer policy, + PIM enforcement and native Alpine/OpenRC/CSP/AOF/permissions/RSS acceptance. + The existing missing-header admin fallback remains unsafe outside isolation. +- Worker queue recovery assumes one worker. Old intermediate render files left + by interrupted non-release cleanup may need separate housekeeping. Storage + retention and full event-log growth need operational policy, not truncation. +- Nonzero CropBox/rotated/unusual PDFs, complex scripts, alternate fonts, + concurrent series allocation and memory under maximum uploads are not newly + certified here. Pending legacy development jobs need the typed-job contract. +- Unrelated authentication/dev-stack changes, skill deletions and other dirty + working-tree files were preserved. Nothing committed or deployed.
diff --git a/AGENTS.md b/AGENTS.md @@ -2,9 +2,10 @@ Read `CONTEXT.md` first (the glossary — use its words), then `HANDOFF.md` (current state, decisions and why, open work) and `docs/adr/`. `README.md` is -the user-facing description and install guide. The invariants below describe -the 2026-09-19 code after Tasks 1–8 (party model, facsimile enrolment, template lifecycle, -circular clipping). See `docs/REBUILD.md` for a task-by-task checklist. +the user-facing description and install guide. The invariants below are the +required design, not a claim that the current code satisfies every one. +See `HANDOFF.md` §4 for source-verified gaps and `docs/REBUILD.md` for the +historical implementation plan. ## Hard constraints (from the owner; do not relax without asking) @@ -39,11 +40,11 @@ circular clipping). See `docs/REBUILD.md` for a task-by-task checklist. ascent/descent). Change one, change the other, then compare edit mode against the proof visually. 4. **Clients never supply values, only references.** PIM text is resolved - server-side from Redis (`HGET <entity>:metadata <key>`); DAM refs are + server-side from Redis (`HGET <org>:metadata <key>`); DAM refs are validated relative paths; signer refs are validated usernames. 5. **Only `signetd` reads `sig_dir`.** `signet-api` must never open a - signature file. Makers never receive `stamped.pdf` (403) — only `proof.pdf` - and, after release, `final.pdf`. + signature file. Drafters receive `proof.pdf` and, after release, `final.pdf`; + `stamped.pdf` requires signer access on that document or admin access. 6. **Party-based sequential signing.** A template defines parties; the drafter assigns one signer per party at submit. Parties sign strictly one after another. Each sign-off overlays the signer's enrolled facsimile onto the @@ -79,7 +80,7 @@ circular clipping). See `docs/REBUILD.md` for a task-by-task checklist. documents in `/pim` and `/dam`. * When a statement uses the same `$n` in a `SELECT` list and a `WHERE`, cast it (`$2::varchar`) — PostgreSQL otherwise fails with "inconsistent types - deduced" and the API currently has no visible error log (see CONTEXT.md). + deduced" Log failures through the existing stderr/syslog error helpers. * JS: one file, `'use strict'`, DOM built with the `h()` helper and `textContent` only (no `innerHTML`). `parent.append()` does **not** filter `null` — only `h()` does. @@ -104,11 +105,14 @@ sleep 6 && podman exec signet /src/test/e2e.sh # must end with "all passe * Fast loop for client-only changes: `podman cp www/app.js signet:/var/www/signet/app.js` (same for `style.css`). - C changes need a rebuild of the image (the DB is recreated each run). -* Browser testing: http://localhost:8080. There is no auth proxy in dev, so - the client sends `Remote-User`/`Remote-Groups` itself from - `localStorage.signetDevIdentity` (`{"user":"asha","groups":"clerks"}`). - Dev groups: `clerks` (maker), `management` (approver), `signet-admins` + C changes need a rebuild of the image. A newly created container has fresh + data; restarting an existing one preserves its initialized database. +* Browser testing: http://localhost:8080. The current dev config does not + implement forward-auth. The client can send `Remote-User`/`Remote-Groups` + from `localStorage.signetDevIdentity` (`{"user":"asha","groups":"clerks"}`). + **Security gap:** `src/http.c` defaults missing headers to an admin identity + without checking `DEV_MODE`. Keep this stack isolated; see `TESTING-AUTH.md`. + Dev groups: `clerks` (drafter), `management` (signer), `signet-admins` (admin + pim_admin). Signature files exist for `ceo` and `manager`. * `curl` POSTs with no body get `411` from lighttpd — send `-d ''`. * All state-changing requests need `X-Requested-With: signet`. @@ -126,8 +130,9 @@ the visual check (edit mode vs. proof vs. stamped copy, both pages). ## Repository conventions -* Nothing has been committed yet (`git init` only). Commit only when the owner - asks; branch first if on the default branch once history exists. +* Git history exists (including rebuild and Authelia work). Commit only when + the owner asks; branch first if on the default branch. Preserve unrelated + working-tree changes. * `vendor/` and `www/vendor/` are third-party, fetched verbatim — do not edit. * `test/fixtures/` are generated by `test/make-fixtures.py` (dev machine only); they contain no real signatures or data. Never commit real signature images.
diff --git a/DESIGN.md b/DESIGN.md @@ -1,7 +1,7 @@ # Signet UI Design System ## Overview -Signet is a maker-checker document stamping application with a lightweight, minimal interface. The UI prioritizes clarity and efficient document workflow management. +Signet is a party-based sequential document signing application with a lightweight, minimal interface. The UI prioritizes clarity and efficient document workflow management. Domain terms follow `CONTEXT.md`; current implementation gaps are in `HANDOFF.md` §4. ## Color Palette All colors are defined in CSS custom properties (`:root`): @@ -15,11 +15,11 @@ All colors are defined in CSS custom properties (`:root`): | `--card` | `#fff` | Card/panel background | | `--accent` | `#1f5f8b` | Primary actions, links | | `--danger` | `#a8322d` | Error, destructive actions | -| `--ok` | `#2c7a4b` | Success, approved states | +| `--ok` | `#2c7a4b` | Success, released status | | `--warn` | `#9a6a00` | Warning, pending states | Imprint box colors use RGB variables: -- `--sig: 214, 48, 49` (signature boxes, reddish) +- `--sig: 214, 48, 49` (signature zones, reddish) - `--img: 9, 102, 204` (image boxes, blue) - `--txt: 34, 139, 84` (text boxes, green) @@ -72,9 +72,9 @@ Imprint box colors use RGB variables: - Border-radius: 3px - States: - Default: #e6eaef background, #3c4858 text - - `PENDING_APPROVAL`, `CORRECTED`: #fff1cf background, `--warn` text color + - `PENDING`: #fff1cf background, `--warn` text color - `CORRECTION_REQUIRED`: #ffe1d2 background, #a2461a text - - `APPROVED`: #d9f2e3 background, `--ok` text color + - `RELEASED`: #d9f2e3 background, `--ok` text color - `DISAPPROVED`: #f8d9d8 background, `--danger` text color ## Document Page Display
diff --git a/HANDOFF.md b/HANDOFF.md @@ -1,19 +1,27 @@ # HANDOFF.md — state of the code and the decisions behind it -Code as of 2026-09-19 after Tasks 1–8. Model finalized 2026-09-19. Vocabulary in `CONTEXT.md`; -working rules in `AGENTS.md`; implementation plan in `docs/REBUILD.md`. - -**Completed (Tasks 1–8):** +Documentation reconciled against source and Git history on 2026-11-10; +workflow implementation and verification updated 2026-11-12. +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`. + +**Historically reported complete (Tasks 1–9; qualifications in §4):** - Syslog logging in both FastCGI APIs (visible errors, debuggable failures) - Prefactor renaming: schema, roles, and decision names aligned with CONTEXT.md glossary (PENDING_APPROVAL→PENDING, APPROVED→RELEASED, maker→drafter, approver→signer, customer_id removed, render_seq/rendered_seq system added) - Organisation-bound PIM: documents select org, imprints resolve per-org from Redis, - image attributes stored as PIM values. PIM resolution at submit (API), rendered - from Redis by worker. DAM accessed only at submit, never at render time. + image attributes stored as PIM values. The API validates PIM references at + submit; the worker resolves them and reads DAM files at render time. This + does not yet provide the submit-time snapshot required by D18. - **Party-based sequential signing** (D18): templates name parties; drafter assigns one signer per party at submit; parties sign strictly one after another; imprints - flattened at submit and stored as JSONB placement data. + intended to be flattened once at submit. Current snapshot/queue/release + gaps are listed in §4. - **Facsimile enrolment** (D20): signers without an enrolled facsimile draw/upload in the browser at first signing; image kept and reused. Admin may also place one. - **Template and series lifecycle** (D28): templates may be retired and deleted only @@ -21,17 +29,16 @@ working rules in `AGENTS.md`; implementation plan in `docs/REBUILD.md`. rejected at submit with 409 error. - **Circular seal clipping** (D29): circles are clipped using 4-Bezier approximation (k=0.5522847498) instead of bounding-box stamping. - -**Remaining (Task 9):** acceptance sweep and documentation updates. Event log UI -(D26), AGENTS.md invariants, HANDOFF.md status updates, README.md refresh, and -full e2e test verification. +- **Acceptance sweep**: docs refreshed for the party/enrolment/PIM model; + event history is visible in the document UI and printed on the audit page; + e2e acceptance was recorded in Task 9 (`todo.txt`, commit c0b1262). ## 1. Status -**Working and verified on Alpine 3.22 (podman):** +**Historical Alpine 3.22 (Podman) verification reports — not rerun in this reconciliation:** -* Clean build with `-Wall -Wextra` after prefactor renaming (commit 5641808). -* Test suite passes (count and assertions updated for new names). +* Clean build with `-Wall -Wextra` after the rebuild acceptance sweep. +* Test suite pass recorded for Task 9 (`todo.txt`, commit c0b1262). * Browser check done by hand: dashboard, edit mode (drag moves the `<area>`, property panel, palette), submit, preview mode as signer (overlays sit exactly on the stamped text; seal alpha correct; signature under red box). @@ -40,14 +47,24 @@ full e2e test verification. * Error logging: all API errors visible in `podman logs signet` (both syslog and stderr, allowing debugging without external syslog setup in dev). +**Fresh isolated-development verification (2026-11-12, ticket 11):** clean +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. + **Not verified / never run:** OpenRC scripts, `etc/lighttpd-signet.conf` (production config incl. WebDAV + CSP), real Authelia in front, `make install` on a real host, JPEG embedding, TTF fonts other than DejaVuSans, rotated or -CropBox-offset source PDFs, `poly` areas, template with different page counts, -concurrent submits on one series. +CropBox-offset source PDFs, template with different page counts, concurrent +submits on one series. -**Code committed as of 2026-09-19** (commit 5641808 fixes spec bugs from prefactor; -commits 3f77fed and 847eac9 implement Tasks 1–2). Untracked: `.mcp.json`, `CLAUDE.md`. +**Git history inspected on 2026-11-10:** rebuild tasks are committed through +c0b1262; later commits on `main` add Authelia/test-container work through +68ed63b. The working tree currently has uncommitted Authelia/dev-stack edits +plus documentation changes and removal of project-local skills. Preserve +unrelated changes; inspect `git status` for the live inventory. ## 2. Decisions and their reasons @@ -55,7 +72,7 @@ commits 3f77fed and 847eac9 implement Tasks 1–2). Untracked: `.mcp.json`, `CLA | :-- | :-- | :-- | | D1 | **No groff.** Overlay PDF is written by `src/pdfw.c`; `qpdf --overlay` merges | `groff -Tpdf` = `gropdf` = Perl; `.PDFPIC` only embeds PDFs (PNG would need ImageMagick, alpha doubtful); spec's sample used `.h` which is not a request. Owner accepted ("others use recommended"). Owner's motive for troff was dynamic content → covered by `serial`/`date` imprints + series + templates | | D2 | *Superseded by D18.* Stamping at submit; approval = sign-off | Owner, mid-build: "stamping is done immediately… checkers only then send a signal that the stamped document is okay, that is essentially the signing". Hence two files: `proof.pdf` (no signatures → maker) and `stamped.pdf` (with signatures → checkers) | -| D3 | **No `STAMPING`/`FAILED` status** | Owner rejected it. Async gap is expressed by `rendered_revision < revision`; failure by `render_error` + "Retry stamping" (`POST …/rerender`) | +| D3 | **No `STAMPING`/`FAILED` status** | Owner rejected it. Async gap was originally `rendered_revision < revision`; the agreed render gate is now `rendered_seq < render_seq` (§4 records implementation gaps); failure by `render_error` + "Retry stamping" (`POST …/rerender`) | | D4 | *Superseded by D27.* Statuses `DRAFT, PENDING_APPROVAL, CORRECTION_REQUIRED, CORRECTED, DISAPPROVED, APPROVED` | Owner prefers these over an umbrella REJECTED. `CORRECTED` behaves exactly like `PENDING_APPROVAL` (both in `PENDING` macro); it only flags a resubmission. Correction resets `current_level` to 1 and bumps `revision` | | D5 | *Superseded by D18.* Multi-level routes: `{"levels":[{"approvers":[…],"mode":"any"|"all"}]}` per document | Owner: many approvers, same level or through levels, several per level | | D6 | *Superseded by D18.* Signature ref = explicit username that must appear in the route; `level:N` refs dropped | With D2 the image is stamped before anyone approves, so "whoever approves level N" is unknowable | @@ -72,7 +89,7 @@ commits 3f77fed and 847eac9 implement Tasks 1–2). Untracked: `.mcp.json`, `CLA | D17 | A correction request voids **all** sign-offs of that revision; after resubmit every party signs again from the first | A sign-off attests one specific stamped copy; the copy changed. Owner confirmed 2026-09-19 | | D18 | **Party model, DocuSeal-style** (`docs/adr/0001`): a template names parties; the drafter assigns one signer per party at submit; parties sign strictly one after another; the drafter reserves a signature zone, the signer fills it at sign-off with their own facsimile; release is rendered by the worker after the last sign-off. **Imprints are flattened once, at submit**; each sign-off overlays the facsimile onto the previous stamped copy, so the DAM is read only at submit and a mid-route seal/font change cannot reach a pending document | Owner 2026-09-19: "a document requires a signature of a signatory. Anyone [holding the post] can sign that box"; then "compare with DocuSeal and copy them". Replaces D2/D5/D6/D7. `any`/`all` and multi-approver levels are gone; "any partner" = the drafter picks which partner | | D19 | At most **one zone per party**; check-only parties (no zone) exist; per-page names or initials are ordinary text imprints, not signatures | Owner 2026-09-19: initials-on-every-page is not an obvious case; "put [the] name … or place a partner text there" | -| D20 | **Enrolment at first signing**: a signer without an enrolled facsimile signs in the browser (draw/upload, as DocuSeal); the image is kept and reused; an admin may also place one | Owner 2026-09-19. Replaces the hand-copied `sig_dir` files of §4.4; the worker remains the sole reader of stored facsimiles (D14) | +| D20 | **Enrolment at first signing**: a signer without an enrolled facsimile signs in the browser (draw/upload, as DocuSeal); the image is kept and reused; an admin may also place one | Owner 2026-09-19. Replaces the original hand-copied `sig_dir` workflow; the worker remains the sole reader of stored facsimiles (D14) | | D21 | **No "customer" concept.** `customer_id` (free text on documents, a dashboard column, a side-panel field) is to be removed in the rebuild | Owner 2026-09-19: "I don't know how a customer got here, delete it" | | D22 | **Title is mandatory**; the drafter must set it before submit. Replaces today's "blank → serial" default | Owner 2026-09-19 | | D23 | **PIM is a deliberately reduced, local key/value mirror** (Redis) of the organisation's full PIM, which is too heavy to run beside Signet. **A document is bound to one organisation**, chosen by the drafter; PIM imprints reference an attribute *key* and resolve against that organisation at submit. Replaces today's literal `org:key` refs baked into the template | Owner 2026-09-19: "select an org and fetch all the gstin and bank account in the right places automatically" | @@ -100,9 +117,10 @@ src/render.[ch] pdfinfo page sizes (+rot swap), bbox per shape, px→pt, pim_lookup src/http.[ch] kcgi helpers: identity/roles, fields, CSRF check, path split, send_json/err/file -src/signet-api.c all endpoints (list at top of file), validation, - submit / decide transactions, release() -src/signetd.c BRPOPLPUSH loop → proof.pdf + stamped.pdf → PG update +src/signet-api.c endpoints, placement/party visibility validation, + submit / decide transactions and typed-job dispatch +src/signetd.c BRPOPLPUSH loop; stamp/sign/enrol/release branches; + full audit, body/final hashes, replay-safe release/cleanup pim/pim-api.c GET/POST /attrs, POST /resync (PG → Redis mirror) pim/www/index.html one-page PIM editor www/app.js whole client; sections: helpers, fonts, geometry, imprint @@ -115,22 +133,33 @@ test/ dev-up.sh (container entrypoint), lighttpd-dev.conf, e2e.sh, make-fixtures.py, fixtures/ ``` -Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf`, -`<data_dir>/templates/<uuid>.pdf`, `<dam_dir>/…`, `<sig_dir>/<user>.png`. - -Request flow for a submit: `save` (layout+route JSON validated, stored as -JSONB) → `submit` (tx: lock row, `check_submittable` — PIM refs resolvable, -DAM files exist, signers ∈ route, series present if `serial` imprint — allocate -serial, status/revision update, commit) → `LPUSH {"doc_id","revision"}` → -signetd renders both files → `rendered_revision = revision` → client polls -`GET /docs/<id>` every 1.2 s until then. +Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf` plus +immutable `render-<seq>.pdf` inputs; `<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 → +`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. +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. +Zone sign-offs queue `sign` for the just-signed party; check-only parties advance +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. Layout JSON (what `collectLayout()` emits, what `render.c` reads): ```json {"reference_width":1000,"reference_height":1414,"imprints":[ - {"page":1,"shape":"rect","type":"pim_text","ref":"org:gstin","prefix":"GSTIN: ", - "coords":[120,150,520,180],"ref_w":1000,"ref_h":1414,"font":"fonts/X.ttf","align":"left"}]} + {"page":1,"shape":"rect","type":"pim_text","ref":"gstin","prefix":"GSTIN: ", + "coords":[120,150,520,180],"ref_w":1000,"ref_h":1414,"font":"fonts/X.ttf","align":"left"}, + {"page":1,"shape":"rect","type":"signature_zone","party":"Manager","min_w":120,"min_h":45, + "coords":[120,650,340,740],"ref_w":1000,"ref_h":1414}]} ``` `ref_w/ref_h` per imprint override the top-level reference size (pages can @@ -138,7 +167,7 @@ differ). The client rasterises every page to 1000 px natural width. ## 4. Known problems and gaps -**✓ FIXED (Tasks 1–8):** +**Historically reported fixes (Tasks 1–9; see source-verified qualifications below):** 1. API errors are now logged to syslog (LOCAL0) and stderr; visible in dev (`podman logs signet`). 2. Facsimile management: signers now enrol at first signing (draw/upload browser UI); enrollment data stored in facsimiles table with dimensions and timestamp. @@ -150,16 +179,49 @@ differ). The client rasterises every page to 1000 px natural width. unlinking all documents; series are retired, never deleted. Retired items rejected at submit with 409 error. -**Remaining:** -6. **Authelia ↔ lighttpd is unproven.** lighttpd has no native forward-auth; +**Source-verified gaps/repairs (2026-11-10 review; updated 2026-11-12):** + +- **Authentication is unsafe outside an isolated dev environment.** + `ident_read()` in `src/http.c` assigns `admin` and hardcoded groups when + headers are absent, without checking `DEV_MODE`. This violates config-only + group mapping and fail-closed authentication. +- **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. +- **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. + Ticket 11 adds real release output/failure/replay tests; the placeholder is + gone. See both ticket notes for evidence and limits. Full native production + acceptance is not yet established. +- **Worker release completed in ticket 11.** Last-party overlay, aspect-fitted + placement validation, check-only routes, complete paginated cross-revision + audit, body/final hashes and transactional release now have API/worker/browser + coverage. Only the worker reads stored facsimiles. Release output failures + stay pending/retryable; DB failures retain work without a release event. +- **Submit/correction semantics repaired in ticket 11.** Empty titles are + rejected before serial allocation. Resubmit logs `RESUBMITTED`, preserves + serial/date and restarts party one with no old facsimiles/active decisions. +- **Sequential visibility repaired in ticket 11.** List/detail/file access is + party-order-aware; `final` requires `RELEASED`; drafter-only access never + exposes the pending stamped copy. Self-service remains supported. +- **Acceptance prerequisites repaired in ticket 11.** Organisation PIM JSON is + grouped correctly and image keys resolve through Redis before DAM access. + Browser zone/minimum metadata survives save; pointer/keyboard placement, + first enrolment refresh and repeated notifications pass real browser tests. + +**Other remaining / unverified work:** +6. **The forwarded-identity trust boundary is unproven.** lighttpd has no native forward-auth; the assumption is a proxy in front that sets and *overwrites* `Remote-User`/`Remote-Groups`. If identity only arrives as CGI `REMOTE_USER`, kcgi cannot see it → needs a lighttpd `setenv`/mod_magnet 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 what future submits stamp. There is no DAM - upload UI — by design it's a network drive. + 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 + 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. 9. No complex-script shaping (Tamil etc.). Latin + symbols (₹ if the font has @@ -173,14 +235,14 @@ differ). The client rasterises every page to 1000 px natural width. 12. Redis AOF must be enabled in production (`appendonly yes`); not enforced. If `LPUSH` fails after the submit commit the doc sits un-stamped until someone presses "Retry stamping" (no automatic sweep in signetd). -13. Event log UI: `doc_events` is written but there is no UI for it (D26 prints - it on the audit page — to be added in Task 9). -14. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker, +13. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker, `blob:` images, inline `style` attributes set via `h()`). -## 5. Completed tasks (Tasks 1–8) +## 5. Completed tasks (Tasks 1–9) -All behavioral changes from the 2026-09-19 model are now implemented: +Tracker completion records are reproduced below. They do not establish that +all behavior in the 2026-09-19 model is implemented; §4 records contradictions +found in the current source. | Task | Changes | Status | |------|---------|--------| @@ -192,56 +254,59 @@ All behavioral changes from the 2026-09-19 model are now implemented: | 6 | Sign-off overlays; worker release | ✓ 2026-09-19 | | 7 | Template/series lifecycle; retire/delete/unlink | ✓ 2026-09-19 | | 8 | Circular seal clipping with Bezier paths | ✓ 2026-09-19 | - -## 6. Remaining: Task 9 (acceptance sweep) - -**Task 9** updates documentation and verification for full acceptance: - -| Item | Status | -|------|--------| -| Event log UI (D26): audit page with full event history | pending | -| README.md: refresh for new party model and features | pending | -| CONTEXT.md: domain terminology updates | pending | -| AGENTS.md: invariants for party model + enrolment | ✓ updated 2026-09-19 | -| HANDOFF.md: status updates and known issues | ✓ updated 2026-09-19 | -| Full e2e test suite verification | pending | +| 9 | Docs, invariants and acceptance sweep | ✓ 2026-09-19 | ## 6. Open questions for the owner -* Who may write to the DAM (operational only: with D18 a change affects - future submits, never a pending or signed document; no versioning needed). +* 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. * 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.) -## 6. Next steps - -**✓ DONE:** -1. Syslog logging (Task 1, commit 847eac9). -2. Prefactor rename to glossary (Task 2, commit 3f77fed + 5641808). -3. First commit of Tasks 1–2 (commit 5641808, live as of 2026-09-19 03:43 UTC). - -**TODO (Tasks 3–9):** Implement the 2026-09-19 behavioral model per `docs/REBUILD.md`. -- Task 3: Organisation-bound PIM imprints (blocks 8, 9) -- Task 4: Parties, signature zones, sequential decisions (core model; blocks 5, 6, 7, 9) -- Task 5: Facsimile enrolment (blocks 6, 9) -- Task 6: Overlay + release in worker (blocks 9) -- Task 7: Template/series lifecycle (retire, unlink, delete; blocks 9) -- Task 8: Clip circular seals (blocks 9) -- Task 9: Docs, invariants, acceptance sweep (all tests pass) - -## 7. Next steps (revised) - -**After rebuild (Tasks 3–9 complete):** -1. Bring up on a real Alpine VM with OpenRC + Authelia; fix what §1 lists as - never run; settle §4.2 and §4.3. -2. Font list validation, pagination. +## 7. Next steps + +**Feature-first priority (2026-11-10):** Signet supports trusted forwarded +identity (`Remote-User` plus the existing configured group/role mapping), not +an authentication-server implementation. The deployment administrator chooses +and manages the provider; Authelia-specific work is outside product scope. +Fail-closed identity handling and the forwarded-header trust boundary remain +production gates, not prerequisites for isolated feature development. Current +missing-header admin behavior is unsafe; this sequencing does not approve it +for production. + +The implementation scopes and acceptance criteria are in +`.scratch/roadmap/spec.md`, indexed by tickets 10–14 in `todo.txt`/`done.txt`: + +1. **Ticket 10:** render-job payloads, sequence gates, retry and database + acknowledgement, including client progress handling, now have targeted + implementation/tests; see `.scratch/roadmap/ticket-10.md`. +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. +4. **Ticket 13 (deferred release blocker):** fail-closed identity handling, + config-only role mapping and tests for both APIs. Explicit isolated-dev + identities must keep feature tests independent of Authelia. +5. **Ticket 14 (production gate):** verify trusted proxy identity enforcement, + DAM write policy, OpenRC, permissions, Redis AOF, CSP and RSS on Alpine. + Keep provider-specific auth experiments separate from application work. +6. Later: font-list validation and document-list pagination/search. + +Add regression coverage and rerun acceptance for implementation changes; the +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. * 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 (DB is re-initialised per run). + be running on :8080 with throw-away data. `test/dev-up.sh` initialises the DB + only when absent; restarting an existing container does not reset it. * Alpine 3.22 packages used: `kcgi-dev`, `hiredis-dev`, `libpq-dev` (headers in `/usr/include/postgresql`, found via `pkg-config`), `postgresql16`, `redis` 8, `lighttpd` 1.4.85 + `lighttpd-mod_webdav`,
diff --git a/README.md b/README.md @@ -4,6 +4,12 @@ Party-based sequential document signing for a 1 vCPU / 1 GB Alpine box. Native C (kcgi + libpq + hiredis + libpng), lighttpd, PostgreSQL, Redis, `qpdf`, `pdfinfo`. 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`. Submit-time PIM/DAM snapshots and fail-closed +identity remain open (`HANDOFF.md` §4). It is not ready for production deployment; +these checks do not certify the native deployment or production trust boundary. + ``` browser (vanilla JS, pdf.js) lighttpd ── /dam/ WebDAV (seals, fonts) <img usemap> + <map>/<area> ──► │ @@ -24,8 +30,9 @@ browser (vanilla JS, pdf.js) lighttpd ── /dam/ WebDAV (seals, fon | `DISAPPROVED` | Terminal; sent back by a signing party | preview | | `RELEASED` | Last party signed. Worker rendered final copy + audit page with full event history → `final.pdf`, SHA-256 stored | preview | -Parties sign strictly one after another. Each sign-off overlays the signer's -enrolled facsimile (drawn or uploaded in the browser) onto the stamped copy. +Parties sign strictly one after another. A party with a signature zone overlays +the signer's enrolled facsimile (drawn or uploaded in the browser) onto the +stamped copy; a check-only party signs off without adding an image. The worker renders `final.pdf` only after the last sign-off. At submit, the drafter assigns one signer per party from the organisation. Signature imprints create zones where signers place their facsimiles. @@ -45,11 +52,11 @@ repeatable. `<area shape coords data-type data-ref …>` in the page's `<map>` is the state. `data-coords` keeps natural-pixel coordinates; `coords` is rescaled on resize. -| type | ref | rendered from | +| type | ref / property | rendered from | | :-- | :-- | :-- | -| `pim_text` | `entity:key` | `HGET entity:metadata key` in Redis, never from the client | -| `dam_image` | path under the DAM | `/var/www/dam/<ref>` (PNG with alpha, JPEG) | -| `signature` | username | `/var/lib/signatures/<user>.png`, worker only | +| `pim_text` | PIM attribute key | `HGET <org>:metadata <key>` in Redis, never from the client | +| `pim_image` | PIM image key | `HGET <org>:images <key>` → DAM path (PNG with alpha, JPEG) | +| `signature_zone` | party name | signer places an enrolled facsimile at sign-off | | `date` | – | document date, `format` = strftime | | `serial` | – | allocated serial number | @@ -66,6 +73,10 @@ merged with `qpdf --overlay`. ## Install (Alpine) +The following is an unverified deployment outline, not a production-ready +runbook. Resolve the gaps in `HANDOFF.md` §4 first; in particular the current +missing-header admin fallback must not be exposed to untrusted requests. + ```sh apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev \ lighttpd lighttpd-mod_webdav postgresql16 redis qpdf poppler-utils @@ -80,15 +91,18 @@ install -d -o signetd -m 0700 /var/lib/signatures # <username>.png, 0600 createuser signet; createuser signetd; createdb -O signet signet psql -U signet -d signet -f sql/schema.sql psql -U signet -d signet -c "GRANT SELECT, UPDATE ON documents TO signetd; - GRANT INSERT ON doc_events TO signetd; GRANT USAGE ON SEQUENCE doc_events_id_seq TO signetd;" + GRANT SELECT, INSERT ON doc_events TO signetd; GRANT USAGE ON SEQUENCE doc_events_id_seq TO signetd; + GRANT SELECT ON doc_decisions TO signetd; GRANT SELECT, UPDATE ON facsimiles TO signetd;" cp etc/init.d/* /etc/init.d/ && rc-update add signet-api && rc-update add signet-pim && rc-update add signetd cp etc/lighttpd-signet.conf /etc/lighttpd/ # and include it $EDITOR /etc/signet/signet.conf # groups → roles, paths, fonts ``` -Enable Redis AOF (`appendonly yes`). The auth proxy must overwrite -`Remote-User` / `Remote-Groups` on every request. +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 +identity and maps configured groups to roles. ## Develop / test @@ -96,9 +110,22 @@ Enable Redis AOF (`appendonly yes`). The auth proxy must overwrite podman build -t signet-dev . podman run --rm -d --name signet -p 8080:8080 signet-dev podman exec signet /src/test/e2e.sh # API + worker end to end -open http://localhost:8080 # asks for a dev username + groups +podman exec signet /src/test/e2e.sh render-contract # failure/replay/queue regression +open http://localhost:8080 # isolated dev only; may default to admin ``` +Optional browser regressions use externally installed Playwright Core and Chrome +on the development machine only (no production or runtime JS dependency): + +```sh +PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/signing-flow.mjs +PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/render-progress.mjs +``` + +Set `CHROME_PATH` for a non-default Chrome location and `SIGNET_URL` for a server +other than localhost:8080. Tests create synthetic documents and use explicit dev +identity headers; never run them against production. + ## Limits (v1) * Fonts must be TrueType with `glyf` outlines. No complex-script shaping @@ -108,9 +135,13 @@ open http://localhost:8080 # asks for a dev username + groups evidence is the audit page plus `doc_events`. No cryptographic PDF signature (PAdES). * **At most one signature zone per party.** Multiple signings per party - (countersigning, witness) are not supported. -* **Imprints are organisation-bound:** PIM attributes are resolved per-organisation - from a local Redis mirror at submit time. Changes to PIM after submit do not - reach a pending document. + (countersigning, witness) are not supported. Placement stays within the zone, + 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. * 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 @@ -1,142 +1,81 @@ -# Testing Authentication & Authorization +# Testing authentication and authorization -## Dev Mode (Default — No Auth) +## Application boundary -The test container uses **dev mode** — no Authelia needed: +Signet consumes identity from a trusted forward-auth proxy (`Remote-User` and +the existing configurable group header for role mapping). Authentication-server +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. -```bash -test/dev-up.sh -# Access http://localhost:8080 -# Type any username/groups in localStorage (dev-only): -localStorage.setItem('signetDevIdentity', JSON.stringify({ - user: 'admin', - groups: 'drafters,pim_admin,signet_admin' -})) -location.reload() -``` - -**Available groups in dev mode:** `drafters`, `management`, `pim_admin`, `signet_admin` - -## Production Testing with Authelia (Real Auth) - -Test with real authentication using Authelia + YAML backend: - -### 1. Start Authelia - -```bash -# Start Authelia with YAML backend -docker run -d --name authelia \ - -p 9091:9091 \ - -v $(pwd)/etc/authelia.yml:/etc/authelia/authelia.yml \ - -v $(pwd)/etc/authelia-users.yml:/etc/authelia/users.yml \ - -v authelia-storage:/var/lib/authelia \ - authelia/authelia:latest - -# Verify Authelia is running -curl -i http://localhost:9091/api/verify -``` - -### 2. Start Signet Test Container with Auth - -```bash -# Edit test/lighttpd-dev.conf to enable Authelia proxy: -# Uncomment: proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => 9091 )) ) - -test/dev-up.sh -# Now access http://localhost:8080/ - -# Signet will forward requests to Authelia on port 9091 -# Authelia will authenticate and set Remote-User/Remote-Groups headers -# Signet backend reads these headers and grants access -``` - -### 3. Access Signet & PIM with Auth - -**Signet** (Document Signing): -- URL: http://localhost:8080/ -- Login: Use any test user (admin/admin, ceo/ceo, etc.) -- Create/sign documents - -**PIM** (Attribute Management): -- URL: http://localhost:8080/pim/ -- Login: Requires `pim_admin` role -- Manage organization attributes - -### 4. Login with Test Users - -**admin/admin** (all permissions): -- Groups: `pim_admin`, `signet_admin`, `drafters` -- Can create organizations and attributes in PIM -- Can sign documents -- Can manage DAM (fonts/seals) +## Current status (source inspected 2026-11-10) -**ceo/ceo** (drafter): -- Groups: `management`, `drafters` -- Can create and sign documents -- Cannot access PIM +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. -**manager/manager** (drafter): -- Groups: `drafters` -- Can create and sign documents +**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. -**viewer/viewer** (no permissions): -- No groups -- Can only read (if allowed by policy) +## Isolated development tests -## Users & Roles +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. -### Roles +The browser can send explicit test headers using its dev identity setting: -- **pim_admin** — Manage organization attributes (PIM portal at `/pim/`) -- **signet_admin** — Administer Signet (users, groups, templates) -- **drafters** — Create and sign documents -- **management** — Higher-level approval (future) -- **dam_admins** — Upload fonts and seals - -### Password Hashes - -All passwords use bcrypt (12 rounds). To generate new ones: - -```bash -htpasswd -B -C 12 -n username -# Enter password twice -# Copy the hash (everything after username:) -``` - -Or use Python: - -```python -import bcrypt -hashed = bcrypt.hashpw(b'password', bcrypt.gensalt(12)) -print(hashed.decode()) -``` - -## Files - -- `etc/authelia.yml` — Authelia configuration -- `etc/authelia-users.yml` — YAML user database with roles -- `TESTING-AUTH.md` — This guide - -## Troubleshooting - -### "Remote-User header not set" - -Authelia is not running or not proxying requests. Check: - -```bash -curl -i http://localhost:9091/api/verify -# Should return 401 (no auth) or 200 (authenticated) +```js +localStorage.setItem('signetDevIdentity', JSON.stringify({ + user: 'asha', + groups: 'clerks' +})); +location.reload(); ``` -### Users can't access PIM - -Check user's groups in `authelia-users.yml` — must include `pim_admin`. - -### Passwords not working - -Verify bcrypt hashes are correct. Test locally: - -```bash -echo -n 'admin' | htpasswd -Bib /dev/stdin admin -# Compare output with authelia-users.yml -``` +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. + +Roles are mapped in `etc/signet.conf.example`, copied into the dev container's +`/etc/signet/signet.conf`: + +| Role | Example dev group | Purpose | +| --- | --- | --- | +| `drafter` | `clerks` | Prepare and submit documents | +| `signer` | `management` | Record decisions for assigned parties | +| `admin` | `signet-admins` | Administer templates, series and facsimiles | +| `pim_admin` | `signet-admins` | Write PIM attributes | + +These are example mappings, not fixed production group names. Holding the +signer role does not replace assignment to a party. Authenticated users may +read PIM; writes require `pim_admin`. DAM write authorization remains unresolved. +The test suite sends explicit `Remote-User` and `Remote-Groups` headers; this +tests application authorization, not proxy authentication or spoof prevention. + +## Authelia work is incomplete + +`etc/authelia.yml`, `etc/authelia-users.yml`, `docker-compose.yml` and +`test/Dockerfile` contain development experiments. Their presence, or a 200/401 +from an Authelia endpoint, does not establish end-to-end authentication. +Passwords and group mappings must be checked against the actual configuration; +this guide makes no claim that example username/password pairs work. +Containers are development-only; production targets bare-metal Alpine/OpenRC. + +For a deployment, the administrator should verify the forwarded-identity trust +boundary with their chosen provider: + +- Unauthenticated requests are denied or redirected before reaching the APIs. +- Direct backend access is blocked, and missing identity fails closed. +- Spoofed `Remote-User`/`Remote-Groups` headers are overwritten by the proxy. +- Authenticated identity reaches both Signet and PIM with the configured roles. +- PIM writes and DAM writes follow their explicit authorization policies. +- API requests cannot bypass the proxy. Provider session/logout policy is owned + and tested by the deployment administrator. + +None of these production checks was run during the documentation reconciliation.
diff --git a/docs/REBUILD.md b/docs/REBUILD.md @@ -1,5 +1,11 @@ # Rebuild plan: from the 2026-09-18 code to the 2026-09-19 model +**Historical plan, not a current implementation report.** Task completion was +recorded in `todo.txt`, but source inspection on 2026-11-10 found material +acceptance gaps. Use `HANDOFF.md` §4 for those findings. The steps, old line +references and test scenarios below preserve the original intent; they are not +proof that the current code meets it. + Written for whoever (or whichever model) does the code change. It assumes no memory of the design session. Read, in this order: `CONTEXT.md` (vocabulary — use those words in code, comments, UI and tests), `HANDOFF.md` §2 (decisions
diff --git a/docs/adr/0001-signers-sign-at-sign-off.md b/docs/adr/0001-signers-sign-at-sign-off.md @@ -19,6 +19,11 @@ browser, which enrols it); imprints are flattened once at submit, each 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). + ## Considered options - **Keep stamp-at-submit and add `any`/`all` levels with holders** (the @@ -32,8 +37,9 @@ renders the release after the last one. ## Consequences - Release is asynchronous (the worker, sole reader of stored facsimiles, must - draw the last one); `APPROVED` reuses the `rendered_revision`/`render_error` - gap and "Retry" of D3. + draw the last one); the document remains `PENDING` until the worker sets + `RELEASED`. Rendering is tracked by `rendered_seq < render_seq`, failures by + `render_error`, with retry following D3. - A party never sees a later party's facsimile, because it does not exist yet. - The DAM (fonts, seals) is read only at submit, so a file replaced on the network drive mid-route cannot change what a pending document shows; the
diff --git a/done.txt b/done.txt @@ -0,0 +1,2 @@ +x 2026-11-10 2026-11-10 Repair render-job payloads, sequence gates, retry and acknowledgement +api +worker +client +test status:completed id:10 spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-10.md +x 2026-11-12 2026-11-10 Complete sequential signing, file visibility and worker-owned release +api +worker +render +client +test status:completed id:11 blockedby:10 spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-11.md
diff --git a/etc/signet.conf.example b/etc/signet.conf.example @@ -15,7 +15,8 @@ sig_inbox = /var/lib/signet/sig-inbox # temporary location for enrolled fac default_font = fonts/DejaVuSans.ttf date_format = %d-%m-%Y -# Identity headers set by the auth proxy (Authelia). lighttpd must never let +# Identity headers set by the deployment's trusted forward-auth proxy. +# The administrator chooses the auth provider. lighttpd must never let # a client-supplied copy of these headers through. auth.user_header = Remote-User auth.groups_header = Remote-Groups
diff --git a/pim/www/README.md b/pim/www/README.md @@ -1,69 +1,49 @@ -# Signet PIM Portal +# Signet PIM editor -Multi-tenant Personally Identifiable Information (PIM) management for Signet document signing. - -## What is PIM? - -PIM stores organization-bound attributes (company name, contact info, logos, etc.) that can be populated into Signet documents via imprints. +PIM is Signet's deliberately reduced local product-information mirror: text +and image attributes belonging to an organisation. See `CONTEXT.md` for the +glossary. It does not mean “Personally Identifiable Information”. ## Access -- **Auth:** Same as Signet — Authelia + lighttpd passes `Remote-User` and `Remote-Groups` headers -- **Role:** `pim_admin` required -- **URL:** `/pim/` (configured in lighttpd as alias to `/var/www/pim/`) +- URL: `/pim/`, aliased to `/var/www/pim/` by lighttpd. +- API reads are available to authenticated users; writes require `pim_admin`. +- The current browser editor requires `pim_admin` even to display its UI. +- Identity comes from configured request headers. Authelia integration is + unverified, and the shared API code currently defaults missing headers to + admin. Keep development isolated; see `TESTING-AUTH.md`. -## Features +The PIM client uses plain `fetch` and does not read Signet's +`localStorage.signetDevIdentity`. Setting that value does not change the PIM +client's request headers. -1. **Multi-tenant org selector** — Each organization is a separate namespace -2. **Attribute management** — Add/edit/delete attributes per org -3. **Type support** — text, date, number, image -4. **Simple UI** — No complex forms, just org → key/type/value +## Attributes -## Usage Flow +Select or create an organisation, then add/edit/delete key/type/value rows. +Supported types are **text** and **image**, not separate date or number types. +Dates and numbers can be stored as text. Image values are validated +DAM-relative paths, such as `seals/agency_seal.png`. -1. Login to Signet with `pim_admin` role -2. Navigate to `/pim/` -3. Select organization from dropdown -4. Add attributes: - - Key: `company_name`, Type: `text` - - Key: `logo`, Type: `image` - - Key: `founded`, Type: `date` -5. Values can be edited via API or future admin UI -6. Signet documents automatically populate from PIM data +Documents reference attribute keys, so a template can be used for different +organisations. The design requires values to be frozen at submit; current code +still reads Redis and DAM during worker rendering. See `HANDOFF.md` §4. ## API -``` -GET /pim-api/me → {user, roles} -GET /pim-api/attrs → [{org_code, attr_key, attr_type, attr_value}] -POST /pim-api/attrs → upsert/delete (pim_admin only) -POST /pim-api/resync → rebuild Redis from PostgreSQL -``` - -## Testing - -### Local Development - -Set fake identity in localStorage: - -```javascript -localStorage.setItem('signetDevIdentity', JSON.stringify({ - user: 'testuser', - groups: 'pim_admin' -})); -location.reload(); -``` - -### Docker - -```bash -docker exec signet-test /var/www/pim/pim.js # runs in browser, not CLI +```text +GET /pim-api/me → {user, roles:{pim_admin}} +GET /pim-api/attrs → [{org_code, attr_key, attr_type, attr_value}] +POST /pim-api/attrs → org, key, type, value (empty value deletes) +POST /pim-api/resync → rebuild Redis mirror from PostgreSQL ``` -The portal runs entirely in the browser. Auth is via lighttpd headers in production. +Both POST endpoints require `pim_admin` and `X-Requested-With: signet`. +Use explicit test identity headers for API authorization tests in the isolated +dev container; this does not test proxy authentication. ## Files -- `index.html` — Portal UI -- `pim.js` — Auth, org/attribute management logic -- `README.md` — This file +- `index.html` — editor markup +- `pim.js` — browser authentication checks and attribute management + +The client runs in the browser, not through a container shell or a JS CLI.
diff --git a/src/render.c b/src/render.c @@ -74,6 +74,22 @@ page_sizes(const char *pdf, struct page_size **out) return n; } +int +render_page_size(const char *pdf, int page, double *w, double *h) +{ + struct page_size *ps = NULL; + int n = page_sizes(pdf, &ps); + + if (n < 1 || page < 1 || page > n) { + free(ps); + return -1; + } + *w = ps[page - 1].w; + *h = ps[page - 1].h; + free(ps); + return 0; +} + /* --- value resolution ------------------------------------------------------ */ int @@ -300,10 +316,26 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, draw_text(pw, cx, imp, text, x, top, w, h, pg->h); } else if (strcmp(type, "pim_image") == 0 || strcmp(type, "dam_image") == 0) { const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape")); - if (!is_safe_relpath(ref)) - return fail(err, errsz, "bad DAM path: %s", ref ? ref : "?"); + 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); /* Apply circular clipping if shape is "circle" */ if (shape != NULL && strcmp(shape, "circle") == 0) { @@ -314,7 +346,7 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout, } if (draw_image(pw, path, x, top, w, h, pg->h) == -1) - return fail(err, errsz, "cannot embed image: %s", ref); + return fail(err, errsz, "cannot embed image: %s", path); /* End clipping if it was applied */ if (shape != NULL && strcmp(shape, "circle") == 0) @@ -384,12 +416,23 @@ out: return rc; } +static void +audit_line(pdfw *pw, int font, double *y, const char *line) +{ + if (*y < 56) { + pdfw_page(pw, 595.28, 841.89); + *y = 841.89 - 72; + } + pdfw_text(pw, font, 9.5, 56, *y, line); + *y -= 15; +} + 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); - char audit[1024], fpath[1024] = ""; + char audit[1024], fpath[1024] = "", line[1024]; char *argv[] = { "qpdf", "--warning-exit-0", "--empty", "--pages", (char *)body, audit, "--", (char *)out, NULL }; double y = 841.89 - 72; @@ -404,14 +447,55 @@ render_release(const struct render_ctx *cx, const char *body, const char *out, conf_get(cx->cf, "dam_dir", "/var/www/dam"), fref); font = pdfw_font(pw, fpath); pdfw_page(pw, 595.28, 841.89); - pdfw_text(pw, font, 16, 56, y, "Approval audit record"); + pdfw_text(pw, font, 16, 56, y, "Document audit record"); y -= 30; - for (i = 0; i < nlines; i++, y -= 15) { - if (y < 56) { - pdfw_page(pw, 595.28, 841.89); - y = 841.89 - 72; + for (i = 0; i < nlines; i++) { + const char *p = lines[i]; + size_t used = 0; + + /* Wrap complete UTF-8 text instead of dropping comments or event rows. */ + while (*p) { + const char *next = p; + size_t bytes; + + utf8_next(&next); + bytes = (size_t)(next - p); + if (*p == '\n' || *p == '\r') { + line[used] = '\0'; + audit_line(pw, font, &y, line); + used = 0; + p = next; + continue; + } + if (used + bytes + 1 >= sizeof(line)) { + line[used] = '\0'; + audit_line(pw, font, &y, line); + used = 0; + } + memcpy(line + used, p, bytes); + line[used + bytes] = '\0'; + if (used > 0 && pdfw_text_width(pw, font, line, 9.5) > 483) { + char *space; + + line[used] = '\0'; + space = strrchr(line, ' '); + if (space != NULL && space != line) { + size_t rest = used - (size_t)(space - line) - 1; + *space = '\0'; + audit_line(pw, font, &y, line); + memmove(line, space + 1, rest); + used = rest; + } else { + audit_line(pw, font, &y, line); + used = 0; + } + continue; + } + used += bytes; + p = next; } - pdfw_text(pw, font, 9.5, 56, y, lines[i]); + line[used] = '\0'; + audit_line(pw, font, &y, line); } if (pdfw_close(pw) == -1) { unlink(audit); @@ -427,7 +511,7 @@ render_release(const struct render_ctx *cx, const char *body, const char *out, int render_sign(const struct render_ctx *cx, const char *body, const char *out, const char *png, int page, double x, double y, double w, double h, - char *err, size_t errsz) + double ref_w, double ref_h, char *err, size_t errsz) { struct page_size *ps = NULL; char overlay[1024]; @@ -435,26 +519,48 @@ render_sign(const struct render_ctx *cx, const char *body, const char *out, char *argv[] = { "qpdf", "--warning-exit-0", (char *)body, "--overlay", overlay, page_spec, from_spec, "--", (char *)out, NULL }; pdfw *pw; - int n, rc = -1; + int n, iw, ih; + double fit_w, fit_h; if ((n = page_sizes(body, &ps)) == -1) return fail(err, errsz, "pdfinfo could not read the body PDF%s", ""); - if (page < 1 || page > n) { + if (page < 1 || page > n || ref_w <= 0 || ref_h <= 0) { free(ps); - return fail(err, errsz, "page %d out of range", ""); + return fail(err, errsz, "invalid signature page or reference size%s", ""); } - + x = x / ref_w * ps[page - 1].w; + y = y / ref_h * ps[page - 1].h; + w = w / ref_w * ps[page - 1].w; + h = h / ref_h * ps[page - 1].h; + snprintf(overlay, sizeof(overlay), "%s/sign-%ld.pdf", cx->tmpdir, (long)getpid()); if ((pw = pdfw_open(overlay)) == NULL) { free(ps); return fail(err, errsz, "cannot write %s", overlay); } + if (pdfw_image_size(pw, png, &iw, &ih) == -1 || iw <= 0 || ih <= 0) { + pdfw_close(pw); + free(ps); + unlink(overlay); + return fail(err, errsz, "cannot read facsimile %s", png); + } + fit_w = w; + fit_h = w * ih / iw; + if (fit_h > h) { + fit_h = h; + fit_w = h * iw / ih; + } + x += (w - fit_w) / 2; + y += (h - fit_h) / 2; + w = fit_w; + h = fit_h; pdfw_page(pw, ps[page - 1].w, ps[page - 1].h); /* PDF origin is bottom-left; convert placement y from top-left to bottom-left */ if (pdfw_image(pw, png, x, ps[page - 1].h - y - h, w, h) == -1) { pdfw_close(pw); free(ps); + unlink(overlay); return fail(err, errsz, "cannot draw image %s", png); }
diff --git a/src/render.h b/src/render.h @@ -19,6 +19,9 @@ struct render_ctx { const char *tmpdir; /* scratch space, same filesystem as `out` */ }; +/* Displayed page dimensions in points; validates that the page exists. */ +int render_page_size(const char *pdf, int page, double *w, double *h); + /* Expand a series pattern: {date:<strftime>} and {seq:<min digits>}. */ int series_expand(const char *pattern, const char *ymd, int seq, char *out, size_t outsz); @@ -36,9 +39,9 @@ int render_release(const struct render_ctx *, const char *body, const char *out, const char *const *lines, int nlines, char *err, size_t errsz); -/* Overlay a facsimile image at placement coords on a PDF page. */ +/* Overlay a facsimile at natural-pixel coords in the supplied reference frame. */ int render_sign(const struct render_ctx *, const char *body, const char *out, const char *png, int page, double x, double y, - double w, double h, char *err, size_t errsz); + double w, double h, double ref_w, double ref_h, char *err, size_t errsz); #endif
diff --git a/src/signet-api.c b/src/signet-api.c @@ -17,12 +17,13 @@ * GET /series POST /series code, pattern * GET /pim GET /dam * - * Identity comes from the auth proxy (Authelia) as request headers; roles are + * Identity comes from the deployment's trusted auth proxy as headers; roles are * mapped from groups in signet.conf. Nothing here ever reads sig_dir. */ #include <sys/stat.h> #include <dirent.h> +#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -40,6 +41,10 @@ static struct conf cf; #define PENDING "('PENDING')" #define IN_ROUTE(u) "EXISTS (SELECT 1 FROM jsonb_array_elements(d.route_json->'parties') p " \ "WHERE p->>'signer' = " u ")" +#define ROUTE_ACCESS(u) "(d.status NOT IN ('DRAFT','CORRECTION_REQUIRED') AND " \ + "EXISTS (SELECT 1 FROM jsonb_array_elements(d.route_json->'parties') " \ + "WITH ORDINALITY p(party, n) WHERE p.party->>'signer' = " u \ + " AND p.n <= d.current_party))" #define CAN_DECIDE(u) "(d.status IN " PENDING " AND d.rendered_seq = d.render_seq " \ "AND d.render_error IS NULL " \ "AND (d.route_json->'parties'->(d.current_party - 1)->>'signer') = " u \ @@ -53,13 +58,13 @@ doc_path(char *buf, size_t sz, const char *id, const char *name) "/var/lib/signet"), id, name ? "/" : "", name ? name : ""); } -static void +static int log_event(PGconn *pg, const char *id, const char *actor, const char *action, const char *detail) { const char *p[] = { id, actor, action, detail }; - db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) " + return db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) " "VALUES ($1, $2, $3, $4)", 4, p); } @@ -81,17 +86,17 @@ send_sql_json(struct kreq *r, PGconn *pg, const char *sql, int n, } static int -enqueue(const char *id, const char *revision) +enqueue(const char *id, const char *revision, const char *seq, const char *kind) { redisContext *rc = redis_get(&cf); redisReply *rep; - char job[128]; + char job[192]; int ok; if (rc == NULL) return -1; - snprintf(job, sizeof(job), "{\"doc_id\":\"%s\",\"revision\":%d}", id, - atoi(revision)); + snprintf(job, sizeof(job), "{\"doc_id\":\"%s\",\"revision\":%d," + "\"seq\":%d,\"kind\":\"%s\"}", id, atoi(revision), atoi(seq), kind); rep = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue", "queue:stamping"), job); ok = rep != NULL && rep->type == REDIS_REPLY_INTEGER; @@ -155,14 +160,27 @@ check_layout(yyjson_val *layout) y = yyjson_get_num(yyjson_arr_get(v, 1)); w = yyjson_get_num(yyjson_arr_get(v, 2)) - x; h = yyjson_get_num(yyjson_arr_get(v, 3)) - y; - if (w <= 0 || h <= 0) - return "signature_zone coords must be valid rectangle"; + double rw = yyjson_get_num(yyjson_obj_get(imp, "ref_w")); + double rh = yyjson_get_num(yyjson_obj_get(imp, "ref_h")); + if (yyjson_obj_get(imp, "ref_w") == NULL) + rw = yyjson_get_num(yyjson_obj_get(layout, "reference_width")); + if (yyjson_obj_get(imp, "ref_h") == NULL) + rh = yyjson_get_num(yyjson_obj_get(layout, "reference_height")); + v = yyjson_obj_get(imp, "page"); + const char *shape = yyjson_get_str(yyjson_obj_get(imp, "shape")); + if (!yyjson_is_int(v) || yyjson_get_sint(v) < 1 || yyjson_get_sint(v) > 500 || + (shape != NULL && strcmp(shape, "rect") != 0) || + !isfinite(rw) || !isfinite(rh) || rw <= 0 || rh <= 0 || + !isfinite(x) || !isfinite(y) || !isfinite(w) || !isfinite(h) || + x < 0 || y < 0 || w <= 0 || h <= 0 || x + w > rw || y + h > rh) + return "signature_zone needs a valid page, reference size and rectangle"; v = yyjson_obj_get(imp, "min_w"); min_w = yyjson_is_num(v) ? yyjson_get_num(v) : 0; v = yyjson_obj_get(imp, "min_h"); min_h = yyjson_is_num(v) ? yyjson_get_num(v) : 0; - if (min_w > w || min_h > h) - return "signature_zone min dimensions exceed zone size"; + if (!isfinite(min_w) || !isfinite(min_h) || min_w <= 0 || min_h <= 0 || + min_w > w || min_h > h) + return "signature_zone minimum dimensions must be positive and fit the zone"; } if (font != NULL && *font && !is_safe_relpath(font)) return "bad font reference"; @@ -188,6 +206,32 @@ check_route(yyjson_val *route) signer = yyjson_get_str(yyjson_obj_get(p, "signer")); if (signer != NULL && (!*signer || !is_safe_name(signer))) return "party signer must be a safe name"; + for (size_t j = 0; j < i; j++) + if (strcmp(name, yyjson_get_str(yyjson_obj_get(yyjson_arr_get(parties, j), "name"))) == 0) + return "party names must be unique"; + } + return NULL; +} + +static const char * +check_zones(yyjson_val *layout, yyjson_val *route) +{ + yyjson_val *imp, *party, *parties = yyjson_obj_get(route, "parties"); + size_t i, n, j, count; + char seen[20] = {0}; + + yyjson_arr_foreach(yyjson_obj_get(layout, "imprints"), i, n, imp) { + const char *type = yyjson_get_str(yyjson_obj_get(imp, "type")); + if (strcmp(type, "signature_zone") != 0) + continue; + const char *name = yyjson_get_str(yyjson_obj_get(imp, "party")); + yyjson_arr_foreach(parties, j, count, party) + if (strcmp(name, yyjson_get_str(yyjson_obj_get(party, "name"))) == 0) + break; + if (j == yyjson_arr_size(parties)) + return "signature zone references an unknown party"; + if (seen[j]++) + return "a party can have only one signature zone"; } return NULL; } @@ -204,7 +248,8 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, redisContext *rc; redisReply *r; - if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL) { + if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL || + (msg = check_zones(layout, route)) != NULL) { snprintf(err, errsz, "%s", msg); return -1; } @@ -224,7 +269,6 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, /* validate imprints */ yyjson_val *imprints = yyjson_obj_get(layout, "imprints"); - char seen_zones[20] = {0}; 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")); @@ -236,7 +280,7 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, return -1; } rc = redis_get(&cf); - r = redisCommand(rc, "HGET %s:metadata %s", org_code, ref); + 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); @@ -249,7 +293,7 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, return -1; } rc = redis_get(&cf); - r = redisCommand(rc, "HGET %s:images %s", org_code, ref); + 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); @@ -258,32 +302,13 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, const char *dam_path = r->str; snprintf(path, sizeof(path), "%s/%s", conf_get(&cf, "dam_dir", "/var/www/dam"), dam_path); - int exists = file_exists(path); - freeReplyObject(r); - if (!is_safe_relpath(dam_path) || !exists) { + 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; } - } else if (strcmp(type, "signature_zone") == 0) { - const char *party_name = yyjson_get_str(yyjson_obj_get(imp, "party")); - int found_party = 0; - size_t party_idx; - yyjson_val *p; - yyjson_arr_foreach(parties, party_idx, max, p) { - const char *pname = yyjson_get_str(yyjson_obj_get(p, "name")); - if (pname != NULL && strcmp(pname, party_name) == 0) { - found_party = 1; - if (seen_zones[party_idx]++) { - snprintf(err, errsz, "Party '%s' has multiple signature zones — each party can only sign once", party_name); - return -1; - } - break; - } - } - if (!found_party) { - snprintf(err, errsz, "Signature zone references party '%s', which is not defined in the route", party_name ? party_name : "(unknown)"); - return -1; - } + freeReplyObject(r); } else 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; @@ -334,7 +359,7 @@ h_docs_list(struct kreq *r, PGconn *pg, const struct ident *id) if (strcmp(scope, "pending") == 0) where = CAN_DECIDE("$1"); else if (strcmp(scope, "involved") == 0) - where = "d.status <> 'DRAFT' AND " IN_ROUTE("$1"); + where = ROUTE_ACCESS("$1"); else if (strcmp(scope, "all") == 0 && ident_has_role(id, &cf, "admin")) where = "$1 <> ''"; else @@ -363,8 +388,13 @@ h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) send_err(r, KHTTP_403, "drafter role required"); return; } + if (db_do(pg, "BEGIN", 0, NULL) == -1) { + send_err(r, KHTTP_500, "database error"); + return; + } if (tpl != NULL && *tpl) { if (!is_uuid(tpl)) { + db_do(pg, "ROLLBACK", 0, NULL); send_err(r, KHTTP_400, "bad template_id"); return; } @@ -377,10 +407,12 @@ h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) res = db_q(pg, "INSERT INTO documents (drafter_user) VALUES ($1) " "RETURNING id", 1, p); } else { + db_do(pg, "ROLLBACK", 0, NULL); send_err(r, KHTTP_400, "upload a PDF (max 32 MB) or pick a template"); return; } if (res == NULL || PQntuples(res) != 1) { + db_do(pg, "ROLLBACK", 0, NULL); send_err(r, KHTTP_400, "could not create document"); if (res != NULL) PQclear(res); @@ -394,17 +426,31 @@ h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) if (mkdir_p(dir, 0770) == -1 || (tpl != NULL && *tpl ? copy_file(src, path) : write_file(path, file->val, file->valsz, 0640)) == -1) { - p[0] = docid; - db_do(pg, "DELETE FROM documents WHERE id = $1", 1, p); + db_do(pg, "ROLLBACK", 0, NULL); + unlink(path); + rmdir(dir); send_err(r, KHTTP_500, "could not store the PDF"); + } else if (log_event(pg, docid, id->user, "CREATED", "") == -1 || + db_do(pg, "COMMIT", 0, NULL) == -1) { + db_do(pg, "ROLLBACK", 0, NULL); + unlink(path); + rmdir(dir); + send_err(r, KHTTP_500, "could not record document creation"); } else { - log_event(pg, docid, id->user, "CREATED", ""); snprintf(body, sizeof(body), "{\"id\":\"%s\"}", docid); send_json(r, KHTTP_201, body); } PQclear(res); } +#define RETRY_ACTOR "($3::boolean OR " \ + "(d.render_kind = 'stamp' AND d.drafter_user = $2) OR " \ + "(d.render_kind = 'sign' AND (" \ + "d.route_json->'parties'->(d.current_party - 1)->>'signer' = $2 OR " \ + "d.route_json->'parties'->(d.current_party - 2)->>'signer' = $2)) OR " \ + "(d.render_kind = 'release' AND " \ + "d.route_json->'parties'->(d.current_party - 1)->>'signer' = $2))" + static void h_doc_get(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid) { @@ -414,19 +460,24 @@ h_doc_get(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid) send_sql_json(r, pg, "SELECT row_to_json(t)::text FROM (SELECT d.id, d.status, d.title, " - "d.drafter_user, d.series_code, d.serial, d.doc_date, " + "d.drafter_user, d.series_code, d.serial, d.doc_date, d.org_code, " "d.layout_json AS layout, d.route_json AS route, d.revision, " - "d.current_party, d.render_seq, d.render_error, d.final_sha256, " + "d.current_party, d.render_seq, d.rendered_seq, d.render_kind, " + "(d.rendered_seq < d.render_seq) AS rendering, " + "(d.status = 'PENDING' AND d.rendered_seq < d.render_seq AND " + RETRY_ACTOR ") AS can_retry, d.render_error, d.final_sha256, " "d.created_at, d.submitted_at, d.released_at, " "(SELECT s.pattern FROM series s WHERE s.code = d.series_code) AS series_pattern, " "(d.drafter_user = $2 AND d.status IN ('DRAFT','CORRECTION_REQUIRED')) AS can_edit, " "($4::boolean AND " CAN_DECIDE("$2") ") AS can_decide, " - "($3::boolean OR " IN_ROUTE("$2") ") AS can_see_stamped, " + "($3::boolean OR " ROUTE_ACCESS("$2") ") AS can_see_stamped, " + "(SELECT coalesce(json_agg(e ORDER BY e.id), '[]') FROM (" + "SELECT id, actor, action, detail, at FROM doc_events WHERE doc_id = d.id) e) AS events, " "(SELECT coalesce(json_agg(x ORDER BY x.decided_at), '[]') FROM (" "SELECT revision, party, signer, decision, comment, decided_at " "FROM doc_decisions WHERE doc_id = d.id) x) AS decisions " "FROM documents d WHERE d.id = $1 AND (d.drafter_user = $2 OR $3::boolean " - "OR (d.status <> 'DRAFT' AND " IN_ROUTE("$2") "))) t", 4, p); + "OR " ROUTE_ACCESS("$2") ")) t", 4, p); } static void @@ -445,7 +496,8 @@ h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid root = yyjson_doc_get_root(doc); layout = yyjson_obj_get(root, "layout"); route = yyjson_obj_get(root, "route"); - if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL) { + if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL || + (msg = check_zones(layout, route)) != NULL) { send_err(r, KHTTP_400, msg); goto out; } @@ -497,18 +549,25 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc yyjson_doc *ldoc = NULL, *rdoc = NULL; char err[512] = "", serial[256], body[64], *rev = NULL; int has_serial, has_series; + const char *submit_action; if (db_do(pg, "BEGIN", 0, NULL) == -1) { send_err(r, KHTTP_500, "database error"); return; } res = db_q(pg, "SELECT layout_json::text, route_json::text, series_code, " - "serial, org_code FROM documents WHERE id = $1 AND drafter_user = $2 " + "serial, org_code, status::text, title 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"); goto fail; } + submit_action = strcmp(PQgetvalue(res, 0, 5), "CORRECTION_REQUIRED") == 0 + ? "RESUBMITTED" : "SUBMITTED"; + if (strspn(PQgetvalue(res, 0, 6), " \t\r\n") == strlen(PQgetvalue(res, 0, 6))) { + snprintf(err, sizeof(err), "document title is required"); + goto fail; + } const char *org_code = PQgetisnull(res, 0, 4) ? NULL : PQgetvalue(res, 0, 4); if (org_code == NULL || !*org_code) { snprintf(err, sizeof(err), "document must have an organisation selected"); @@ -526,6 +585,12 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc 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); + if (sres == NULL || PQntuples(sres) != 1) { + if (sres != NULL) + PQclear(sres); + snprintf(err, sizeof(err), "could not read series"); + goto fail; + } if (sres != NULL) { if (!PQgetisnull(sres, 0, 0)) { snprintf(err, sizeof(err), "this series has been retired"); @@ -559,19 +624,16 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc "render_kind = 'stamp', current_party = 1, " "serial = COALESCE(serial, $3), " "doc_date = COALESCE(doc_date, CURRENT_DATE), " - "title = CASE WHEN title = '' THEN COALESCE(serial, $3, 'Untitled') " - "ELSE title END, submitted_at = CURRENT_TIMESTAMP, render_error = NULL " + "submitted_at = CURRENT_TIMESTAMP, render_error = NULL " "WHERE id = $1 AND drafter_user = $2 " - "RETURNING revision::text, " - "CASE WHEN status = 'CORRECTION_REQUIRED'::doc_status THEN 'RESUBMITTED' " - "ELSE 'SUBMITTED' END AS event_action", 3, p); + "RETURNING revision::text, render_seq::text", 3, 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) { snprintf(err, sizeof(err), "submit failed"); goto fail; } - log_event(pg, docid, id->user, PQgetvalue(r2, 0, 1), rev); - if (enqueue(docid, rev) == -1) + 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"); else { @@ -599,79 +661,88 @@ h_doc_rerender(struct kreq *r, PGconn *pg, const struct ident *id, const char *d ident_has_role(id, &cf, "admin") ? "t" : "f" }; PGresult *res; - res = db_q(pg, "UPDATE documents d SET render_error = NULL WHERE id = $1 " - "AND (drafter_user = $2 OR $3::boolean) AND status IN " PENDING - " AND render_seq < revision RETURNING revision::text", 3, p); - if (res == NULL || PQntuples(res) != 1) + res = db_q(pg, "SELECT " RETRY_ACTOR " FROM documents d WHERE id = $1", 3, p); + if (res == NULL) { + send_err(r, KHTTP_500, "database error"); + return; + } + if (PQntuples(res) != 1 || PQgetvalue(res, 0, 0)[0] != 't') { + PQclear(res); + send_err(r, KHTTP_403, "not permitted to retry this render"); + return; + } + PQclear(res); + res = db_q(pg, "WITH work AS (UPDATE documents d SET render_error = NULL, " + "render_seq = render_seq + 1 WHERE id = $1 AND " RETRY_ACTOR + " AND status IN " PENDING " AND rendered_seq < render_seq " + "AND render_kind IN ('stamp','sign','release') " + "RETURNING id, revision, render_seq, render_kind), event AS (" + "INSERT INTO doc_events(doc_id,actor,action,detail) " + "SELECT id, $2::varchar, 'RETRY', render_kind FROM work) " + "SELECT revision::text, render_seq::text, render_kind FROM work", 3, p); + if (res == NULL) + send_err(r, KHTTP_500, "database error"); + else if (PQntuples(res) != 1) send_err(r, KHTTP_409, "nothing to re-render"); - else if (enqueue(docid, PQgetvalue(res, 0, 0)) == -1) - send_err(r, KHTTP_503, "stamping queue is down"); - else - send_json(r, KHTTP_200, "{\"ok\":true}"); + else { + if (enqueue(docid, PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 1), + PQgetvalue(res, 0, 2)) == -1) + send_err(r, KHTTP_503, "render queue is down; retry rendering once it is back"); + else + send_json(r, KHTTP_200, "{\"ok\":true}"); + } if (res != NULL) PQclear(res); } -/* Last sign-off: stamped.pdf + audit page -> final.pdf, hash recorded. */ -static int -release(PGconn *pg, const char *docid, char *sha, char *err, size_t errsz) +static double +json_number(yyjson_val *obj, const char *key, double fallback) { - struct render_ctx cx; - const char *p[] = { docid }, *lines[64]; - char dir[600], stamped[700], tmp[700], final[700], body_sha[65]; - char hashline[128]; - PGresult *res; - int i, n = 0, rc = -1; + yyjson_val *v = yyjson_obj_get(obj, key); - doc_path(dir, sizeof(dir), docid, NULL); - doc_path(stamped, sizeof(stamped), docid, "stamped.pdf"); - doc_path(tmp, sizeof(tmp), docid, "final.pdf.tmp"); - doc_path(final, sizeof(final), docid, "final.pdf"); - if (sha256_file(stamped, body_sha) == -1) { - snprintf(err, errsz, "stamped copy is missing"); - return -1; - } - res = db_q(pg, - "SELECT * FROM (SELECT 0 AS o, 'Document ID: ' || d.id FROM documents d WHERE d.id = $1 " - "UNION ALL SELECT 1, 'Serial: ' || coalesce(d.serial, '-') FROM documents d WHERE d.id = $1 " - "UNION ALL SELECT 2, 'Title: ' || d.title FROM documents d WHERE d.id = $1 " - "UNION ALL SELECT 3, 'Prepared by: ' || d.drafter_user || ' submitted ' || " - "to_char(d.submitted_at, 'YYYY-MM-DD HH24:MI:SS TZ') || ' revision ' || d.revision " - "FROM documents d WHERE d.id = $1 " - "UNION ALL SELECT 4, '' " - "UNION ALL SELECT 5, 'Sign-offs:' " - "UNION ALL (SELECT 6, ' Party ' || x.party || ': ' || x.signer || ' signed off ' || " - "to_char(x.decided_at, 'YYYY-MM-DD HH24:MI:SS TZ') || " - "CASE WHEN x.comment <> '' THEN ' \"' || left(x.comment, 60) || '\"' ELSE '' END " - "FROM doc_decisions x JOIN documents d ON d.id = x.doc_id " - "WHERE x.doc_id = $1 AND x.revision = d.revision AND x.decision = 'SIGNOFF' " - "ORDER BY x.party, x.decided_at LIMIT 50)) q ORDER BY o", 1, p); - if (res == NULL) { - snprintf(err, errsz, "database error"); - return -1; - } - for (i = 0; i < PQntuples(res) && n < 58; i++) - lines[n++] = PQgetvalue(res, i, 1); - snprintf(hashline, sizeof(hashline), "SHA-256 of the preceding pages as signed off:"); - lines[n++] = ""; - lines[n++] = hashline; - lines[n++] = body_sha; - lines[n++] = ""; - lines[n++] = "Signature images in this document are facsimiles placed by the system. The"; - lines[n++] = "sign-offs listed above, authenticated by the organisation's directory, are the approval record."; - - memset(&cx, 0, sizeof(cx)); - cx.cf = &cf; - cx.tmpdir = dir; - if (render_release(&cx, stamped, tmp, lines, n, err, errsz) == 0) { - if (sha256_file(tmp, sha) == 0 && rename(tmp, final) == 0) { - chmod(final, 0640); - rc = 0; - } else - snprintf(err, errsz, "could not finalise the released PDF"); - } - PQclear(res); - return rc; + return yyjson_is_num(v) ? yyjson_get_num(v) : fallback; +} + +static const char * +check_placement(yyjson_val *layout, yyjson_val *zone, yyjson_val *pl, + double aspect, double page_w, double page_h) +{ + yyjson_val *coords = yyjson_obj_get(pl, "coords"); + yyjson_val *zc = yyjson_obj_get(zone, "coords"); + yyjson_val *page = yyjson_obj_get(pl, "page"); + double c[4], zw, zh, rw, rh, w, h, fit_w, fit_h; + int i; + + if (!yyjson_is_obj(pl) || !yyjson_is_int(page) || + yyjson_get_sint(page) != yyjson_get_sint(yyjson_obj_get(zone, "page")) || + !yyjson_is_arr(coords) || yyjson_arr_size(coords) != 4) + return "placement needs the zone page and four numeric coordinates"; + zw = json_number(zone, "ref_w", json_number(layout, "reference_width", 0)); + zh = json_number(zone, "ref_h", json_number(layout, "reference_height", 0)); + rw = json_number(pl, "ref_w", 0); + rh = json_number(pl, "ref_h", 0); + if (!isfinite(rw) || !isfinite(rh) || rw <= 0 || rh <= 0 || zw <= 0 || zh <= 0) + return "placement needs positive reference dimensions"; + for (i = 0; i < 4; i++) { + if (!yyjson_is_num(yyjson_arr_get(coords, i))) + return "placement coordinates must be finite numbers"; + c[i] = yyjson_get_num(yyjson_arr_get(coords, i)) * (i % 2 ? zh / rh : zw / rw); + if (!isfinite(c[i])) + return "placement coordinates must be finite numbers"; + } + w = c[2] - c[0]; + h = c[3] - c[1]; + if (w <= 0 || h <= 0 || c[0] < yyjson_get_num(yyjson_arr_get(zc, 0)) || + c[1] < yyjson_get_num(yyjson_arr_get(zc, 1)) || + c[2] > yyjson_get_num(yyjson_arr_get(zc, 2)) || + c[3] > yyjson_get_num(yyjson_arr_get(zc, 3))) + return "placement outside zone bounds or not a positive rectangle"; + fit_w = fmin(w / zw * page_w, h / zh * page_h * aspect); + fit_h = fit_w / aspect; + if (fit_w + 1e-7 < json_number(zone, "min_w", 0) / zw * page_w || + fit_h + 1e-7 < json_number(zone, "min_h", 0) / zh * page_h) + return "placement too small for the zone minimum dimensions"; + return NULL; } static void @@ -681,25 +752,29 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc const char *comment = http_field_str(r, "comment"); const char *placement_json = http_field_str(r, "placement"); const char *p[5], *code, *action; - char err[512] = ""; - PGresult *res = NULL; + char err[512] = "", detail[4608]; + PGresult *res = NULL, *job_res = NULL; int party, parties, is_last_party, has_zone; yyjson_val *layout, *imprints, *imp; - yyjson_doc *layout_doc = NULL; + yyjson_doc *layout_doc = NULL, *placement_doc = NULL; char party_name[50] = ""; size_t i, max; const char *type, *pname; if (comment == NULL) comment = ""; - if (decision != NULL && strcmp(decision, "approve") == 0) + if (strlen(comment) > 4096) { + send_err(r, KHTTP_400, "comment must be at most 4096 bytes"); + return; + } + if (decision != NULL && (strcmp(decision, "signoff") == 0 || strcmp(decision, "approve") == 0)) code = "SIGNOFF"; else if (decision != NULL && strcmp(decision, "correction") == 0) code = "CORRECTION"; else if (decision != NULL && strcmp(decision, "disapprove") == 0) code = "DISAPPROVE"; else { - send_err(r, KHTTP_400, "decision must be approve, correction or disapprove"); + send_err(r, KHTTP_400, "decision must be signoff, correction or disapprove"); return; } if (code[0] != 'S' && *comment == '\0') { @@ -718,7 +793,7 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc p[1] = id->user; res = db_q(pg, "SELECT d.current_party, jsonb_array_length(d.route_json->'parties'), " "d.route_json->'parties'->(d.current_party - 1)->>'name', " - "d.revision::text, d.render_seq::text FROM documents d WHERE d.id = $1 AND " + "d.revision::text, d.render_seq::text, d.layout_json::text FROM documents d WHERE d.id = $1 AND " CAN_DECIDE("$2") " FOR UPDATE", 2, p); if (res == NULL || PQntuples(res) != 1) { snprintf(err, sizeof(err), "this document is not waiting for your decision"); @@ -731,108 +806,59 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc p[3] = PQgetvalue(res, 0, 4); is_last_party = (party >= parties); - /* For SIGNOFF, check if this party has a signature_zone and validate placement */ has_zone = 0; if (code[0] == 'S') { - const char *lp[] = { docid }; - PGresult *lres = db_q(pg, "SELECT layout_json FROM documents WHERE id = $1", 1, lp); - if (lres != NULL && PQntuples(lres) == 1) { - const char *layout_str = PQgetvalue(lres, 0, 0); - layout_doc = yyjson_read(layout_str, strlen(layout_str), 0); - if (layout_doc != NULL) { - layout = yyjson_doc_get_root(layout_doc); - imprints = yyjson_obj_get(layout, "imprints"); - yyjson_arr_foreach(imprints, i, max, imp) { - type = yyjson_get_str(yyjson_obj_get(imp, "type")); - pname = yyjson_get_str(yyjson_obj_get(imp, "party")); - if (type != NULL && strcmp(type, "signature_zone") == 0 && - pname != NULL && strcmp(pname, party_name) == 0) { - has_zone = 1; - break; - } - } - yyjson_doc_free(layout_doc); - layout_doc = NULL; - } - PQclear(lres); - } + const char *layout_str = PQgetvalue(res, 0, 5), *msg; + yyjson_val *zone = NULL; + layout_doc = yyjson_read(layout_str, strlen(layout_str), 0); + if (layout_doc == NULL) { + snprintf(err, sizeof(err), "invalid stored layout"); + goto fail; + } + layout = yyjson_doc_get_root(layout_doc); + imprints = yyjson_obj_get(layout, "imprints"); + yyjson_arr_foreach(imprints, i, max, imp) { + type = yyjson_get_str(yyjson_obj_get(imp, "type")); + pname = yyjson_get_str(yyjson_obj_get(imp, "party")); + if (type != NULL && strcmp(type, "signature_zone") == 0 && + pname != NULL && strcmp(pname, party_name) == 0) + zone = imp; + } + has_zone = zone != NULL; if (has_zone) { - /* Check facsimile is enrolled for this signer */ - PGresult *fres = db_q(pg, "SELECT 1 FROM facsimiles WHERE username = $1 AND enrolled_at IS NOT NULL", - 1, (const char *[]){ id->user }); - int enrolled = (fres != NULL && PQntuples(fres) == 1); + PGresult *fres = db_q(pg, "SELECT width, height FROM facsimiles WHERE username = $1 " + "AND enrolled_at IS NOT NULL AND width > 0 AND height > 0", 1, (const char *[]){ id->user }); + int enrolled = fres != NULL && PQntuples(fres) == 1; + double aspect = enrolled ? atof(PQgetvalue(fres, 0, 0)) / atof(PQgetvalue(fres, 0, 1)) : 0; + double page_w, page_h; + char source[700]; + if (fres != NULL) PQclear(fres); if (!enrolled) { snprintf(err, sizeof(err), "enrol your signature first"); goto fail; } - - /* Validate placement JSONB */ - if (placement_json == NULL || !*placement_json) { - snprintf(err, sizeof(err), "placement required for signature zones"); + doc_path(source, sizeof(source), docid, "source.pdf"); + if (render_page_size(source, yyjson_get_int(yyjson_obj_get(zone, "page")), &page_w, &page_h) == -1) { + snprintf(err, sizeof(err), "signature zone page does not exist"); goto fail; } - - /* Parse placement and validate against zone */ - yyjson_doc *plj = yyjson_read(placement_json, strlen(placement_json), 0); - if (plj == NULL) { - snprintf(err, sizeof(err), "invalid placement JSON"); + placement_doc = placement_json == NULL ? NULL : + yyjson_read(placement_json, strlen(placement_json), 0); + msg = placement_doc == NULL ? "placement required for signature zones" : + check_placement(layout, zone, yyjson_doc_get_root(placement_doc), aspect, page_w, page_h); + if (msg != NULL) { + snprintf(err, sizeof(err), "%s", msg); goto fail; } - yyjson_val *pl_root = yyjson_doc_get_root(plj); - yyjson_val *pl_coords = yyjson_obj_get(pl_root, "coords"); - double pl_x1 = 0, pl_y1 = 0, pl_x2 = 0, pl_y2 = 0; - double zone_x1 = 0, zone_y1 = 0, zone_x2 = 0, zone_y2 = 0; - double min_w = 0, min_h = 0; - - /* Extract placement coords */ - if (yyjson_is_arr(pl_coords) && yyjson_arr_size(pl_coords) == 4) { - pl_x1 = yyjson_get_num(yyjson_arr_get(pl_coords, 0)); - pl_y1 = yyjson_get_num(yyjson_arr_get(pl_coords, 1)); - pl_x2 = yyjson_get_num(yyjson_arr_get(pl_coords, 2)); - pl_y2 = yyjson_get_num(yyjson_arr_get(pl_coords, 3)); - } - - /* Find zone in layout and extract bounds */ - yyjson_arr_foreach(imprints, i, max, imp) { - const char *z_type = yyjson_get_str(yyjson_obj_get(imp, "type")); - const char *z_party = yyjson_get_str(yyjson_obj_get(imp, "party")); - if (z_type != NULL && strcmp(z_type, "signature_zone") == 0 && - z_party != NULL && strcmp(z_party, party_name) == 0) { - yyjson_val *z_coords = yyjson_obj_get(imp, "coords"); - if (yyjson_is_arr(z_coords) && yyjson_arr_size(z_coords) == 4) { - zone_x1 = yyjson_get_num(yyjson_arr_get(z_coords, 0)); - zone_y1 = yyjson_get_num(yyjson_arr_get(z_coords, 1)); - zone_x2 = yyjson_get_num(yyjson_arr_get(z_coords, 2)); - zone_y2 = yyjson_get_num(yyjson_arr_get(z_coords, 3)); - yyjson_val *min_w_val = yyjson_obj_get(imp, "min_w"); - yyjson_val *min_h_val = yyjson_obj_get(imp, "min_h"); - min_w = yyjson_is_num(min_w_val) ? yyjson_get_num(min_w_val) : 0; - min_h = yyjson_is_num(min_h_val) ? yyjson_get_num(min_h_val) : 0; - } - break; - } - } - - /* Validate placement inside zone with min dimensions */ - double pl_w = pl_x2 - pl_x1; - double pl_h = pl_y2 - pl_y1; - if (pl_x1 < zone_x1 || pl_x2 > zone_x2 || - pl_y1 < zone_y1 || pl_y2 > zone_y2) { - snprintf(err, sizeof(err), "placement outside zone bounds"); - yyjson_doc_free(plj); - goto fail; - } - if (pl_w < min_w || pl_h < min_h) { - snprintf(err, sizeof(err), "placement too small (min %gx%g, got %gx%g)", min_w, min_h, pl_w, pl_h); - yyjson_doc_free(plj); - goto fail; - } - yyjson_doc_free(plj); } } + if (!has_zone && placement_json != NULL) { + snprintf(err, sizeof(err), "placement is only allowed for a zone sign-off"); + goto fail; + } /* Record the decision */ { @@ -860,49 +886,19 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc action = NULL; if (code[0] == 'S') { - if (is_last_party) { - /* Last party signing: build and release final PDF */ - char sha[65]; - if (release(pg, docid, sha, err, sizeof(err)) == -1) - goto fail; - if (db_do(pg, "UPDATE documents SET status = 'RELEASED', " - "final_sha256 = $2, released_at = CURRENT_TIMESTAMP " - "WHERE id = $1", 2, (const char*[]){ docid, sha }) == -1) { - snprintf(err, sizeof(err), "could not update release status"); - goto fail; - } - action = "RELEASED"; - } else { - /* Move to next party, optionally enqueue sign job if has zone */ - if (db_do(pg, "UPDATE documents SET current_party = current_party + 1 WHERE id = $1", - 1, p) == -1) { - snprintf(err, sizeof(err), "could not advance party"); + if (!is_last_party && db_do(pg, "UPDATE documents SET " + "current_party = current_party + 1 WHERE id = $1", 1, p) == -1) + goto fail; + if (has_zone || is_last_party) { + const char *jp[] = { docid, is_last_party ? "release" : "sign" }; + + job_res = db_q(pg, "UPDATE documents SET render_seq = render_seq + 1, " + "render_kind = $2, render_error = NULL WHERE id = $1 " + "RETURNING revision::text, render_seq::text, render_kind", 2, jp); + if (job_res == NULL || PQntuples(job_res) != 1) goto fail; - } - if (has_zone) { - PGresult *res_seq; - const char *render_seq; - - if (db_do(pg, "UPDATE documents SET render_seq = render_seq + 1, " - "render_kind = 'sign' WHERE id = $1", 1, p) == -1) { - snprintf(err, sizeof(err), "could not update render sequence"); - goto fail; - } - res_seq = db_q(pg, "SELECT render_seq FROM documents WHERE id = $1", 1, p); - if (res_seq == NULL) { - snprintf(err, sizeof(err), "could not read render sequence"); - goto fail; - } - render_seq = PQgetvalue(res_seq, 0, 0); - if (enqueue(docid, render_seq) == -1) { - snprintf(err, sizeof(err), "could not enqueue sign job"); - PQclear(res_seq); - goto fail; - } - PQclear(res_seq); - } - action = "SIGNED"; } + action = "SIGNOFF"; } else { if (db_do(pg, code[0] == 'C' ? "UPDATE documents SET status = 'CORRECTION_REQUIRED' WHERE id = $1" @@ -911,10 +907,26 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc action = code[0] == 'C' ? "CORRECTION_REQUIRED" : "DISAPPROVED"; } - if (db_do(pg, "COMMIT", 0, NULL) == -1) + snprintf(detail, sizeof(detail), "revision %s, party %d (%s): %s", + p[2], party, party_name, comment); + if (log_event(pg, docid, id->user, action, detail) == -1 || + db_do(pg, "COMMIT", 0, NULL) == -1) goto fail; - log_event(pg, docid, id->user, action ? action : "DECISION", comment); - send_json(r, KHTTP_200, "{\"ok\":true}"); + if (code[0] != 'S') { + char path[700]; + + doc_path(path, sizeof(path), docid, "stamped.pdf"); + unlink(path); + snprintf(path, sizeof(path), "%s/docs/%s/render-%s.pdf", + conf_get(&cf, "data_dir", "/var/lib/signet"), docid, p[3]); + unlink(path); + } + /* Publish only committed work; a queue outage can be retried by the signer. */ + if (job_res != NULL && enqueue(docid, PQgetvalue(job_res, 0, 0), + PQgetvalue(job_res, 0, 1), PQgetvalue(job_res, 0, 2)) == -1) + send_err(r, KHTTP_503, "decision recorded, but the render queue is down; retry rendering"); + else + send_json(r, KHTTP_200, "{\"ok\":true}"); goto done; fail: db_do(pg, "ROLLBACK", 0, NULL); @@ -924,6 +936,9 @@ done: PQclear(res); if (layout_doc != NULL) yyjson_doc_free(layout_doc); + if (job_res != NULL) + PQclear(job_res); + yyjson_doc_free(placement_doc); } static void @@ -959,8 +974,9 @@ h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid int is_drafter, in_route, admin = p[2][0] == 't'; const char *status; - res = db_q(pg, "SELECT d.drafter_user = $2, " IN_ROUTE("$2") ", d.status::text " - "FROM documents d WHERE d.id = $1 AND $3 <> ''", 3, p); + res = db_q(pg, "SELECT d.drafter_user = $2, " ROUTE_ACCESS("$2") ", d.status::text " + "FROM documents d WHERE d.id = $1 AND (d.drafter_user = $2 " + "OR $3::boolean OR " ROUTE_ACCESS("$2") ")", 3, p); if (res == NULL || PQntuples(res) != 1) { send_err(r, KHTTP_404, "not found"); goto out; @@ -975,7 +991,12 @@ h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid send_err(r, KHTTP_404, "not found"); goto out; } - /* the stamped copy carries signature facsimiles: checkers only */ + if ((strcmp(kind, "final") == 0 && strcmp(status, "RELEASED") != 0) || + (strcmp(kind, "stamped") == 0 && strcmp(status, "PENDING") != 0)) { + send_err(r, KHTTP_404, "file not available"); + goto out; + } + /* Only a party whose turn has arrived (or an admin) sees facsimiles. */ if (!(admin || in_route || (is_drafter && strcmp(kind, "stamped") != 0))) { send_err(r, KHTTP_403, "forbidden"); goto out; @@ -1073,13 +1094,35 @@ h_series(struct kreq *r, PGconn *pg, const struct ident *id) send_json(r, KHTTP_200, "{\"ok\":true}"); } +static yyjson_mut_val * +pim_org(yyjson_mut_doc *doc, yyjson_mut_val *root, const char *key, size_t len) +{ + char org[65]; + yyjson_mut_val *ent; + + if (len == 0 || len >= sizeof(org)) + return NULL; + memcpy(org, key, len); + org[len] = '\0'; + if (!is_safe_name(org)) + return NULL; + ent = yyjson_mut_obj_get(root, org); + if (ent == NULL) { + ent = yyjson_mut_obj(doc); + yyjson_mut_obj_add(root, yyjson_mut_strcpy(doc, org), ent); + yyjson_mut_obj_add(ent, yyjson_mut_str(doc, "text"), yyjson_mut_obj(doc)); + yyjson_mut_obj_add(ent, yyjson_mut_str(doc, "images"), yyjson_mut_obj(doc)); + } + return ent; +} + static void h_pim(struct kreq *r) { redisContext *rc = redis_get(&cf); redisReply *scan = NULL, *h; yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); - yyjson_mut_val *root = yyjson_mut_obj(doc), *ent, *attr; + yyjson_mut_val *root = yyjson_mut_obj(doc), *ent; char cursor[32] = "0", *out; size_t i, j, klen; @@ -1096,19 +1139,19 @@ h_pim(struct kreq *r) klen = strlen(key) - strlen(":metadata"); if ((h = redisCommand(rc, "HGETALL %s", key)) == NULL) break; - ent = yyjson_mut_obj(doc); - for (j = 0; h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2) - yyjson_mut_obj_add(ent, + ent = pim_org(doc, root, key, klen); + ent = yyjson_mut_obj_get(ent, "text"); + for (j = 0; ent != NULL && h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2) + yyjson_mut_obj_put(ent, yyjson_mut_strcpy(doc, h->element[j]->str), yyjson_mut_strcpy(doc, h->element[j + 1]->str)); - yyjson_mut_obj_add(root, yyjson_mut_strncpy(doc, key, klen), ent); freeReplyObject(h); } freeReplyObject(scan); scan = NULL; } while (strcmp(cursor, "0") != 0); - /* Now scan for image attributes and add them as objects with type field */ + /* Merge both hashes under one organisation, as the editor expects. */ snprintf(cursor, sizeof(cursor), "%s", "0"); do { if (rc == NULL || (scan = redisCommand(rc, "SCAN %s MATCH *:images " @@ -1122,21 +1165,12 @@ h_pim(struct kreq *r) klen = strlen(key) - strlen(":images"); if ((h = redisCommand(rc, "HGETALL %s", key)) == NULL) break; - ent = (yyjson_mut_val *)yyjson_mut_obj_get(root, key); - if (ent == NULL) { - ent = yyjson_mut_obj(doc); - yyjson_mut_obj_add(root, yyjson_mut_strncpy(doc, key, klen), ent); - } - for (j = 0; h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2) { - const char *attr_key = h->element[j]->str; - const char *attr_val = h->element[j + 1]->str; - attr = yyjson_mut_obj(doc); - yyjson_mut_obj_add(attr, yyjson_mut_str(doc, "value"), - yyjson_mut_strcpy(doc, attr_val)); - yyjson_mut_obj_add(attr, yyjson_mut_str(doc, "type"), - yyjson_mut_str(doc, "image")); - yyjson_mut_obj_add(ent, yyjson_mut_strcpy(doc, attr_key), attr); - } + ent = pim_org(doc, root, key, klen); + ent = yyjson_mut_obj_get(ent, "images"); + for (j = 0; ent != NULL && h->type == REDIS_REPLY_ARRAY && j + 1 < h->elements; j += 2) + yyjson_mut_obj_put(ent, + yyjson_mut_strcpy(doc, h->element[j]->str), + yyjson_mut_strcpy(doc, h->element[j + 1]->str)); freeReplyObject(h); } freeReplyObject(scan); @@ -1298,7 +1332,7 @@ h_me_facsimile(struct kreq *r, PGconn *pg, const struct ident *id) snprintf(inbox_path, sizeof(inbox_path), "%s/%s.png", conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), id->user); - if (write_file(inbox_path, file->val, file->valsz, 0600) == -1) { + if (write_file(inbox_path, file->val, file->valsz, 0640) == -1) { send_err(r, KHTTP_500, "could not store facsimile"); return; } @@ -1354,7 +1388,7 @@ h_facsimiles(struct kreq *r, PGconn *pg, const struct ident *id) snprintf(inbox_path, sizeof(inbox_path), "%s/%s.png", conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), user); - if (write_file(inbox_path, file->val, file->valsz, 0600) == -1) { + if (write_file(inbox_path, file->val, file->valsz, 0640) == -1) { send_err(r, KHTTP_500, "could not store facsimile"); return; }
diff --git a/src/signetd.c b/src/signetd.c @@ -1,28 +1,24 @@ /* - * signetd: stamping worker. - * - * Blocks on BRPOPLPUSH <queue> <queue>:processing. For every submitted - * document it renders two files next to source.pdf: - * proof.pdf PIM text, seals, date, serial (what the maker sees) - * stamped.pdf proof + signature facsimiles (what checkers sign off) - * It is the only process allowed to read sig_dir. A job is removed from the - * processing list only after PostgreSQL has been updated, so a crash at any - * point just replays the job on the next start. + * signetd: serial render worker. Jobs stay in :processing until the database + * outcome is committed. A locked document row serialises rendering with API + * transitions; immutable render inputs make replay safe after a failed commit. */ #include <sys/stat.h> +#include <errno.h> +#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> +#include <png.h> + #include "conf.h" #include "db.h" #include "render.h" #include "util.h" -#include <png.h> - static struct conf cf; static char queue[128], processing[160]; @@ -33,53 +29,109 @@ doc_path(char *buf, size_t sz, const char *id, const char *name) "/var/lib/signet"), id, name ? "/" : "", name ? name : ""); } -static void +static int log_event(PGconn *pg, const char *id, const char *action, const char *detail) { const char *p[] = { id, action, detail }; - db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) " + return db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) " "VALUES ($1, 'signetd', $2, $3)", 3, p); } -static void -log_enrol(PGconn *pg, const char *user) -{ - const char *p[] = { NULL, "ENROLLED", user }; - db_do(pg, "INSERT INTO doc_events (doc_id, actor, action, detail) " - "VALUES ($1, 'signetd', $2, $3)", 3, p); -} - -/* Validate PNG and extract width/height. Returns 0 on success. */ static int png_get_dimensions(const char *path, int *width, int *height) { png_image png; + void *pixels; + int rv = -1; memset(&png, 0, sizeof(png)); png.version = PNG_IMAGE_VERSION; if (!png_image_begin_read_from_file(&png, path)) return -1; - *width = png.width; - *height = png.height; + png.format = PNG_FORMAT_RGBA; + if (png.width == 0 || png.height == 0 || (uint64_t)png.width * png.height > 4000000) { + png_image_free(&png); + return -1; + } + pixels = malloc(PNG_IMAGE_SIZE(png)); + if (pixels != NULL && png_image_finish_read(&png, NULL, pixels, 0, NULL)) { + *width = png.width; + *height = png.height; + rv = 0; + } + free(pixels); png_image_free(&png); - return 0; + return rv; +} + +/* Enrol jobs have no document id or render sequence. */ +static int +process_enrol(PGconn *pg, const char *user) +{ + char inbox[1024], sig[1024], tmp[1040], w[16], h[16]; + const char *p[] = { user, w, h }; + PGresult *res; + int width, height, rv = -1; + + if (db_do(pg, "BEGIN", 0, NULL) == -1) + return -1; + res = db_q(pg, "SELECT enrolled_at FROM facsimiles WHERE username = $1 " + "FOR UPDATE", 1, p); + if (res == NULL) + goto out; + if (PQntuples(res) == 0 || !PQgetisnull(res, 0, 0)) { + PQclear(res); + rv = db_do(pg, "COMMIT", 0, NULL); + goto out; + } + PQclear(res); + snprintf(inbox, sizeof(inbox), "%s/%s.png", + conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), user); + snprintf(sig, sizeof(sig), "%s/%s.png", + conf_get(&cf, "sig_dir", "/var/lib/signatures"), user); + snprintf(tmp, sizeof(tmp), "%s.tmp", sig); + /* Keep the inbox until commit, so a failed database update is replayable. */ + if (png_get_dimensions(inbox, &width, &height) == -1) { + if (access(inbox, F_OK) == -1 && errno != ENOENT) + goto out; + if (log_event(pg, NULL, "ENROL_FAILED", user) == -1 || + db_do(pg, "COMMIT", 0, NULL) == -1) + goto out; + unlink(inbox); + return 0; + } + if (copy_file(inbox, tmp) == -1 || chmod(tmp, 0600) == -1 || + rename(tmp, sig) == -1) + goto out; + snprintf(w, sizeof(w), "%d", width); + snprintf(h, sizeof(h), "%d", height); + if (db_do(pg, "UPDATE facsimiles SET enrolled_at = CURRENT_TIMESTAMP, " + "width = $2::int, height = $3::int WHERE username = $1", 3, p) == -1 || + log_event(pg, NULL, "ENROLLED", user) == -1 || + db_do(pg, "COMMIT", 0, NULL) == -1) + goto out; + unlink(inbox); + rv = 0; +out: + if (rv == -1) + db_do(pg, "ROLLBACK", 0, NULL); + return rv; } static int render_pair(redisContext *rc, const char *id, const char *layout_txt, - const char *serial, const char *date, const char *org_code, char *err, - size_t errsz) + const char *serial, const char *date, const char *org_code, + const char *candidate, char *err, size_t errsz) { struct render_ctx cx; - char dir[512], src[600], tmp[600], dst[600]; - const char *names[] = { "proof", "stamped" }; + char dir[512], src[600], tmp[700], proof[600]; yyjson_doc *doc; int i, rv = -1; - snprintf(dir, sizeof(dir), "%s/docs/%s", - conf_get(&cf, "data_dir", "/var/lib/signet"), id); - snprintf(src, sizeof(src), "%s/source.pdf", dir); + 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"); return -1; @@ -92,19 +144,17 @@ render_pair(redisContext *rc, const char *id, const char *layout_txt, 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/%s.pdf.tmp", dir, names[i]); - snprintf(dst, sizeof(dst), "%s/%s.pdf", dir, names[i]); + snprintf(tmp, sizeof(tmp), "%s.tmp", dst); if (render_stamp(&cx, yyjson_doc_get_root(doc), src, tmp, err, - errsz) == -1) { + errsz) == -1 || chmod(tmp, 0640) == -1 || rename(tmp, dst) == -1) { + if (!*err) + snprintf(err, errsz, "could not publish render output"); unlink(tmp); goto out; } - chmod(tmp, 0640); - if (rename(tmp, dst) == -1) { - snprintf(err, errsz, "rename to %s failed", dst); - goto out; - } } rv = 0; out: @@ -112,187 +162,317 @@ out: return rv; } -/* Returns 0 when the job is finished (successfully or not), -1 to retry. */ +static int +render_decision(PGconn *pg, const char *id, const char *revision, + const char *base, const char *candidate, char *err, size_t errsz) +{ + const char *p[] = { id, revision }; + PGresult *res; + yyjson_doc *doc = NULL; + yyjson_val *pl, *coords; + struct render_ctx cx; + char png[1024], dir[600], tmp[700]; + double x, y, w, h, rw, rh; + int page, rv = -1; + + /* Sign jobs follow advancement; release keeps the final party current. */ + res = db_q(pg, "SELECT x.signer, x.placement::text, f.enrolled_at FROM doc_decisions x " + "JOIN documents d ON d.id = x.doc_id LEFT JOIN facsimiles f ON f.username = x.signer " + "WHERE x.doc_id = $1 AND x.revision = $2::int " + "AND x.party = CASE WHEN d.render_kind = 'release' THEN d.current_party " + "ELSE d.current_party - 1 END AND x.decision = 'SIGNOFF'", 2, p); + if (res == NULL) + return -2; + if (PQntuples(res) != 1 || !is_safe_name(PQgetvalue(res, 0, 0))) { + snprintf(err, errsz, "signed party has no enrolled facsimile or placement"); + goto out; + } + if (PQgetisnull(res, 0, 1)) { + snprintf(tmp, sizeof(tmp), "%s.tmp", candidate); + if (copy_file(base, tmp) == 0 && rename(tmp, candidate) == 0) + rv = 0; + else + snprintf(err, errsz, "could not copy check-only body"); + unlink(tmp); + goto out; + } + if (PQgetisnull(res, 0, 2)) { + snprintf(err, errsz, "facsimile is not enrolled"); + goto out; + } + doc = yyjson_read(PQgetvalue(res, 0, 1), strlen(PQgetvalue(res, 0, 1)), 0); + if (doc == NULL) { + snprintf(err, errsz, "invalid signature placement"); + goto out; + } + pl = yyjson_doc_get_root(doc); + coords = yyjson_obj_get(pl, "coords"); + page = yyjson_get_int(yyjson_obj_get(pl, "page")); + rw = yyjson_get_num(yyjson_obj_get(pl, "ref_w")); + rh = yyjson_get_num(yyjson_obj_get(pl, "ref_h")); + x = yyjson_get_num(yyjson_arr_get(coords, 0)); + y = yyjson_get_num(yyjson_arr_get(coords, 1)); + w = yyjson_get_num(yyjson_arr_get(coords, 2)) - x; + h = yyjson_get_num(yyjson_arr_get(coords, 3)) - y; + if (rw <= 0 || rh <= 0 || x < 0 || y < 0 || w <= 0 || h <= 0 || + x + w > rw || y + h > rh || page < 1) { + snprintf(err, errsz, "invalid signature page or coordinates"); + goto out; + } + snprintf(png, sizeof(png), "%s/%s.png", + conf_get(&cf, "sig_dir", "/var/lib/signatures"), PQgetvalue(res, 0, 0)); + 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)) { + snprintf(err, errsz, "could not publish signature output"); + rv = -1; + } + unlink(tmp); +out: + yyjson_doc_free(doc); + PQclear(res); + return rv; +} + +static int +release_document(PGconn *pg, const char *id, const char *body, char sha[65], + 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]; + int i, n, rv = -1; + + if (sha256_file(body, body_sha) == -1) { + snprintf(err, errsz, "could not hash the signed body"); + return -1; + } + /* Included in the audit only if the same completion transaction commits. */ + if (log_event(pg, id, "RELEASED", body_sha) == -1) + return -2; + res = db_q(pg, "SELECT line FROM (" + "SELECT 0 AS bucket, 0::bigint AS event_id, 'Document ID: ' || id AS line FROM documents WHERE id=$1 " + "UNION ALL SELECT 1, 0, 'Serial: ' || coalesce(serial, '-') FROM documents WHERE id=$1 " + "UNION ALL SELECT 2, 0, 'Title: ' || title FROM documents WHERE id=$1 " + "UNION ALL SELECT 3, 0, 'Organisation: ' || coalesce(org_code, '-') FROM documents WHERE id=$1 " + "UNION ALL SELECT 4, 0, 'Drafter: ' || drafter_user FROM documents WHERE id=$1 " + "UNION ALL SELECT 5, 0, 'Full event log (all revisions):' " + "UNION ALL SELECT 6, id, to_char(at, 'YYYY-MM-DD HH24:MI:SS TZ') || ' | ' || " + "actor || ' | ' || action || ' | ' || detail FROM doc_events WHERE doc_id=$1 " + ") audit ORDER BY bucket, event_id", 1, p); + if (res == NULL) + return -2; + n = PQntuples(res); + lines = malloc(((size_t)n + 3) * sizeof(*lines)); + if (lines == NULL) { + snprintf(err, errsz, "could not allocate audit lines"); + PQclear(res); + return -1; + } + for (i = 0; i < n; i++) + lines[i] = PQgetvalue(res, i, 0); + lines[n++] = "SHA-256 of the signed body before the audit pages:"; + lines[n++] = body_sha; + lines[n++] = "Signature images are facsimiles, not cryptographic signatures."; + 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; + 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) + rv = 0; + else + snprintf(err, errsz, "could not publish final copy"); + } + unlink(tmp); + free(lines); + PQclear(res); + return rv; +} + +/* A committed render file is never overwritten, even when its job is replayed. */ +static int +publish_stamped(const char *id, const char *candidate) +{ + char tmp[700], dst[700]; + + doc_path(tmp, sizeof(tmp), id, "stamped.pdf.tmp"); + doc_path(dst, sizeof(dst), id, "stamped.pdf"); + unlink(tmp); + return link(candidate, tmp) == 0 && rename(tmp, dst) == 0 ? 0 : -1; +} + +static int +cleanup_release(const char *id, int seq) +{ + char path[700], name[64]; + + doc_path(path, sizeof(path), id, "stamped.pdf"); + if (unlink(path) == -1 && errno != ENOENT) + return -1; + snprintf(name, sizeof(name), "render-%d.pdf", seq); + doc_path(path, sizeof(path), id, name); + return unlink(path) == 0 || errno == ENOENT ? 0 : -1; +} + +/* 0 acknowledges an invalid/stale job or a committed outcome; -1 retries. */ static int process(redisContext *rc, const char *payload) { PGconn *pg; - PGresult *res; + PGresult *res = NULL, *updated = NULL; yyjson_doc *job; - yyjson_val *root; - const char *id, *kind, *p[3]; - char revbuf[16], seqbuf[16], err[512] = ""; - int rev, seq; + yyjson_val *root, *revision, *sequence; + const char *id, *kind, *user, *action, *p[5]; + char revbuf[16], seqbuf[16], err[512] = "", sha[65] = ""; + char name[64], base[700], candidate[700]; + int seq, previous = 0, rv = -1, rendered; - if ((job = yyjson_read(payload, strlen(payload), 0)) == NULL) { - fprintf(stderr, "signetd: dropping malformed job\n"); + if ((job = yyjson_read(payload, strlen(payload), 0)) == NULL) return 0; - } root = yyjson_doc_get_root(job); - id = yyjson_get_str(yyjson_obj_get(root, "doc_id")); - rev = yyjson_get_int(yyjson_obj_get(root, "revision")); - seq = yyjson_get_int(yyjson_obj_get(root, "seq")); kind = yyjson_get_str(yyjson_obj_get(root, "kind")); - if (!is_uuid(id)) { - yyjson_doc_free(job); - return 0; - } - if (kind == NULL) - kind = "stamp"; - if ((pg = db_get(&cf)) == NULL) { - yyjson_doc_free(job); - return -1; + id = yyjson_get_str(yyjson_obj_get(root, "doc_id")); + user = yyjson_get_str(yyjson_obj_get(root, "user")); + revision = yyjson_obj_get(root, "revision"); + sequence = yyjson_obj_get(root, "seq"); + if (kind != NULL && strcmp(kind, "enrol") == 0) { + if (user == NULL || !is_safe_name(user)) + goto invalid; + pg = db_get(&cf); + rv = pg == NULL ? -1 : process_enrol(pg, user); + goto done; } - snprintf(revbuf, sizeof(revbuf), "%d", rev); + if (kind == NULL || (strcmp(kind, "stamp") != 0 && strcmp(kind, "sign") != 0 && + strcmp(kind, "release") != 0) || !is_uuid(id) || + !yyjson_is_int(revision) || yyjson_get_sint(revision) < 1 || + yyjson_get_sint(revision) > INT_MAX || !yyjson_is_int(sequence) || + yyjson_get_sint(sequence) < 1 || yyjson_get_sint(sequence) > INT_MAX) + goto invalid; + seq = yyjson_get_int(sequence); + snprintf(revbuf, sizeof(revbuf), "%d", yyjson_get_int(revision)); snprintf(seqbuf, sizeof(seqbuf), "%d", seq); p[0] = id; p[1] = revbuf; - - if (strcmp(kind, "stamp") == 0) { - res = db_q(pg, "SELECT layout_json::text, serial, doc_date::text, org_code " - "FROM documents WHERE id = $1 AND revision = $2 " - "AND status IN ('PENDING')", 2, p); - if (res == NULL) { - yyjson_doc_free(job); - return -1; + p[2] = seqbuf; + p[3] = kind; + 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, " + "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); + if (res == NULL) + goto rollback; + if (PQntuples(res) == 0) { + /* A crash after release commit can precede filesystem cleanup/LREM. */ + if (strcmp(kind, "release") == 0) { + updated = db_q(pg, "SELECT id FROM documents WHERE id=$1 AND revision=$2::int " + "AND rendered_seq=$3::int AND render_seq=$3::int AND status='RELEASED'", 3, p); + if (updated == NULL) + goto rollback; } - if (PQntuples(res) == 1) { - if (render_pair(rc, id, PQgetvalue(res, 0, 0), - PQgetisnull(res, 0, 1) ? NULL : PQgetvalue(res, 0, 1), - PQgetvalue(res, 0, 2), - PQgetisnull(res, 0, 3) ? NULL : PQgetvalue(res, 0, 3), - err, sizeof(err)) == 0) { - const char *up[] = { id, seqbuf }; - db_do(pg, "UPDATE documents SET rendered_seq = $2::int, " - "render_error = NULL WHERE id = $1", 2, up); - log_event(pg, id, "STAMPED", ""); - } else { - fprintf(stderr, "signetd: %s: %s\n", id, err); - p[2] = err; - db_do(pg, "UPDATE documents SET render_error = $3 " - "WHERE id = $1 AND revision = $2", 3, p); - log_event(pg, id, "STAMP_FAILED", err); - } - } - PQclear(res); + rv = db_do(pg, "COMMIT", 0, NULL); + if (rv == 0 && updated != NULL && PQntuples(updated) == 1) + rv = cleanup_release(id, seq); + goto rollback; + } + previous = atoi(PQgetvalue(res, 0, 4)); + snprintf(name, sizeof(name), "render-%d.pdf", previous); + doc_path(base, sizeof(base), id, name); + 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), + PQgetisnull(res, 0, 1) ? NULL : PQgetvalue(res, 0, 1), + PQgetvalue(res, 0, 2), PQgetvalue(res, 0, 3), candidate, err, sizeof(err)); + action = rendered == 0 ? "STAMPED" : "STAMP_FAILED"; } else if (strcmp(kind, "sign") == 0) { - /* Fetch placement and signer for current party's decision */ - PGresult *sres = db_q(pg, - "SELECT d.current_party, (d.route_json->'parties'->(d.current_party - 1)->>'signer') as signer, " - "x.placement, d.org_code FROM documents d " - "LEFT JOIN doc_decisions x ON (x.doc_id = d.id AND x.revision = d.revision AND " - " x.party = d.current_party AND x.decision = 'SIGNOFF') " - "WHERE d.id = $1 AND d.revision = $2", 2, p); - if (sres != NULL && PQntuples(sres) == 1) { - const char *signer = PQgetvalue(sres, 0, 1); - const char *placement_str = PQgetisnull(sres, 0, 2) ? NULL : PQgetvalue(sres, 0, 2); - if (signer != NULL && *signer && placement_str != NULL) { - /* Parse placement JSON and overlay facsimile */ - yyjson_doc *pldoc = yyjson_read(placement_str, strlen(placement_str), 0); - if (pldoc != NULL) { - yyjson_val *pl = yyjson_doc_get_root(pldoc); - int page = (int)yyjson_get_num(yyjson_obj_get(pl, "page")) || 1; - yyjson_val *coords = yyjson_obj_get(pl, "coords"); - double x = yyjson_is_arr(coords) ? yyjson_get_num(yyjson_arr_get(coords, 0)) : 0; - double y = yyjson_is_arr(coords) ? yyjson_get_num(yyjson_arr_get(coords, 1)) : 0; - double x2 = yyjson_is_arr(coords) ? yyjson_get_num(yyjson_arr_get(coords, 2)) : 0; - double y2 = yyjson_is_arr(coords) ? yyjson_get_num(yyjson_arr_get(coords, 3)) : 0; - - char png_path[1024], stamped[700], tmp[700], final[700]; - struct render_ctx cx; - /* Verify facsimile is enrolled for this signer */ - PGresult *fres = db_q(pg, "SELECT 1 FROM facsimiles WHERE username = $1 AND enrolled_at IS NOT NULL", - 1, (const char*[]){ signer }); - int facsimile_ok = (fres != NULL && PQntuples(fres) == 1); - if (fres) PQclear(fres); - if (!facsimile_ok) { - snprintf(err, sizeof(err), "facsimile not enrolled for %s", signer); - fprintf(stderr, "signetd: %s: sign failed: %s\n", id, err); - p[2] = err; - db_do(pg, "UPDATE documents SET render_error = $3 WHERE id = $1 AND revision = $2", 3, p); - yyjson_doc_free(pldoc); - PQclear(sres); - return 0; - } - snprintf(png_path, sizeof(png_path), "%s/sig_dir/%s.png", - conf_get(&cf, "data_dir", "/var/lib/signet"), signer); - doc_path(stamped, sizeof(stamped), id, "stamped.pdf"); - doc_path(tmp, sizeof(tmp), id, "stamped.pdf.tmp"); - - memset(&cx, 0, sizeof(cx)); - cx.cf = &cf; - if (render_sign(&cx, stamped, tmp, png_path, page, x, y, x2 - x, y2 - y, - err, sizeof(err)) == 0) { - if (rename(tmp, stamped) == 0) { - chmod(stamped, 0640); - const char *up[] = { id, seqbuf }; - db_do(pg, "UPDATE documents SET rendered_seq = $2::int, " - "render_error = NULL WHERE id = $1", 2, up); - log_event(pg, id, "SIGNED", ""); - } else { - snprintf(err, sizeof(err), "rename failed"); - p[2] = err; - db_do(pg, "UPDATE documents SET render_error = $3 " - "WHERE id = $1 AND revision = $2", 3, p); - } - } else { - fprintf(stderr, "signetd: %s: sign failed: %s\n", id, err); - p[2] = err; - db_do(pg, "UPDATE documents SET render_error = $3 " - "WHERE id = $1 AND revision = $2", 3, p); - } - yyjson_doc_free(pldoc); - } - } - PQclear(sres); - } - } else if (strcmp(kind, "release") == 0) { - /* Release is now synchronous in API - this is a no-op placeholder */ - /* Log completion for audit trail */ - log_event(pg, id, "RELEASED", ""); - } else if (strcmp(kind, "enrol") == 0) { - const char *user = yyjson_get_str(yyjson_obj_get(root, "user")); - if (user != NULL && is_safe_name(user)) { - char inbox_path[1024], sig_path[1024], tmp_path[1024]; - int width, height; + rendered = render_decision(pg, id, revbuf, base, candidate, err, sizeof(err)); + if (rendered == -2) + goto rollback; + action = rendered == 0 ? "SIGNED" : "SIGN_FAILED"; + } else { + if (db_do(pg, "SAVEPOINT release_output", 0, NULL) == -1) + 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)); + if (rendered == -2) + goto rollback; + if (rendered != 0 && db_do(pg, "ROLLBACK TO SAVEPOINT release_output", 0, NULL) == -1) + goto rollback; + action = rendered == 0 ? NULL : "RELEASE_FAILED"; + } + if (rendered == 0 && strcmp(kind, "release") != 0 && publish_stamped(id, candidate) == -1) { + rendered = -1; + snprintf(err, sizeof(err), "could not publish stamped copy"); + action = strcmp(kind, "stamp") == 0 ? "STAMP_FAILED" : "SIGN_FAILED"; + } + p[4] = rendered == 0 && strcmp(kind, "release") == 0 ? sha : err; + updated = db_q(pg, rendered == 0 && strcmp(kind, "release") == 0 + ? "UPDATE documents SET status='RELEASED', rendered_seq=$3::int, render_error=NULL, " + "final_sha256=$5, released_at=CURRENT_TIMESTAMP WHERE id=$1 " + "AND revision=$2::int AND render_kind=$4 RETURNING id" + : rendered == 0 + ? "UPDATE documents SET rendered_seq = $3::int, render_error = NULL " + "WHERE id = $1 AND revision = $2::int AND render_kind = $4 RETURNING id" + : "UPDATE documents SET render_error = $5 WHERE id = $1 " + "AND revision = $2::int AND render_seq = $3::int AND render_kind = $4 RETURNING id", + rendered == 0 && strcmp(kind, "release") != 0 ? 4 : 5, p); + if (updated == NULL || PQntuples(updated) != 1 || + (action != NULL && log_event(pg, id, action, err) == -1) || db_do(pg, "COMMIT", 0, NULL) == -1) + goto rollback; + /* Only the current immutable base is needed after a committed outcome. */ + if (rendered == 0 && previous > 0) + unlink(base); + if (rendered == 0 && strcmp(kind, "release") == 0 && cleanup_release(id, seq) == -1) + goto rollback; + if (rendered != 0) { + unlink(candidate); + fprintf(stderr, "signetd: %s: %s\n", id, err); + } + rv = 0; +rollback: + if (rv == -1) + db_do(pg, "ROLLBACK", 0, NULL); +done: + if (res != NULL) + PQclear(res); + if (updated != NULL) + PQclear(updated); + yyjson_doc_free(job); + return rv; +invalid: + fprintf(stderr, "signetd: dropping invalid render job\n"); + rv = 0; + goto done; +} - snprintf(inbox_path, sizeof(inbox_path), "%s/%s.png", - conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), user); - snprintf(sig_path, sizeof(sig_path), "%s/%s.png", - conf_get(&cf, "sig_dir", "/var/lib/signet"), user); - snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", sig_path); +static int +recover(redisContext *rc) +{ + redisReply *r; + int more; - /* Validate PNG and get dimensions */ - if (png_get_dimensions(inbox_path, &width, &height) == 0) { - /* Copy inbox file to sig_dir atomically */ - if (rename(inbox_path, tmp_path) == 0) { - if (chmod(tmp_path, 0600) == 0 && rename(tmp_path, sig_path) == 0) { - /* Update facsimiles table */ - char width_buf[16], height_buf[16]; - snprintf(width_buf, sizeof(width_buf), "%d", width); - snprintf(height_buf, sizeof(height_buf), "%d", height); - const char *up[] = { user, width_buf, height_buf }; - db_do(pg, "INSERT INTO facsimiles (username, enrolled_by, width, height, enrolled_at) " - "VALUES ($1, $1, $2::int, $3::int, NOW()) " - "ON CONFLICT (username) DO UPDATE SET " - "enrolled_at = NOW(), width = $2::int, height = $3::int, enrolled_by = $1", - 3, up); - log_enrol(pg, user); - } else { - unlink(tmp_path); - fprintf(stderr, "signetd: enrol %s: failed to move to sig_dir\n", user); - } - } else { - fprintf(stderr, "signetd: enrol %s: failed to move from inbox\n", user); - } - } else { - /* Bad PNG file - remove it and leave unenrolled */ - unlink(inbox_path); - fprintf(stderr, "signetd: enrol %s: invalid PNG\n", user); - } + do { + r = redisCommand(rc, "RPOPLPUSH %s %s", processing, queue); + if (r == NULL || (r->type != REDIS_REPLY_STRING && r->type != REDIS_REPLY_NIL)) { + if (r != NULL) + freeReplyObject(r); + return -1; } - } - yyjson_doc_free(job); + more = r->type == REDIS_REPLY_STRING; + freeReplyObject(r); + } while (more); return 0; } @@ -301,8 +481,8 @@ main(int argc, char *argv[]) { const char *path = CONF_PATH_DEFAULT; redisContext *rc; - redisReply *r; - int c; + redisReply *r, *d; + int c, ready = 0; while ((c = getopt(argc, argv, "c:")) != -1) if (c == 'c') @@ -314,45 +494,40 @@ main(int argc, char *argv[]) snprintf(queue, sizeof(queue), "%s", conf_get(&cf, "queue", "queue:stamping")); snprintf(processing, sizeof(processing), "%s:processing", queue); umask(027); - - /* crash recovery: whatever was in flight goes back on the queue */ - while ((rc = redis_get(&cf)) == NULL) - sleep(2); - for (;;) { - r = redisCommand(rc, "RPOPLPUSH %s %s", processing, queue); - c = r != NULL && r->type == REDIS_REPLY_STRING; - if (r != NULL) - freeReplyObject(r); - if (!c) - break; - } - for (;;) { if ((rc = redis_get(&cf)) == NULL) { + ready = 0; + sleep(2); + continue; + } + /* Also recover after a lost acknowledgement or Redis reconnection. */ + if (!ready && recover(rc) == -1) { + redis_drop(); sleep(2); continue; } + ready = 1; r = redisCommand(rc, "BRPOPLPUSH %s %s 30", queue, processing); - if (r == NULL) { + if (r == NULL || r->type == REDIS_REPLY_ERROR) { + if (r != NULL) + freeReplyObject(r); redis_drop(); + ready = 0; continue; } if (r->type == REDIS_REPLY_STRING) { if (process(rc, r->str) == 0) { - redisReply *d = redisCommand(rc, "LREM %s 1 %b", - processing, r->str, r->len); - - if (d != NULL) - freeReplyObject(d); + 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; } else { - /* infrastructure down: put it back and wait */ - redisReply *d = redisCommand(rc, "RPOPLPUSH %s %s", - processing, queue); - - if (d != NULL) - freeReplyObject(d); + d = redisCommand(rc, "RPOPLPUSH %s %s", processing, queue); + if (d == NULL || d->type != REDIS_REPLY_STRING) + ready = 0; sleep(5); } + if (d != NULL) + freeReplyObject(d); } freeReplyObject(r); }
diff --git a/test/dev-up.sh b/test/dev-up.sh @@ -20,9 +20,9 @@ if ! su-exec postgres psql -lqt | grep -qw signet; then su-exec postgres createdb -O signet signet su-exec signet psql -q -d signet -f /src/sql/schema.sql su-exec signet psql -q -d signet -c \ - "GRANT SELECT, UPDATE ON documents TO signetd; GRANT INSERT ON doc_events TO signetd; GRANT USAGE ON SEQUENCE doc_events_id_seq TO signetd; GRANT INSERT, UPDATE ON facsimiles TO signetd;" + "GRANT SELECT, UPDATE ON documents TO signetd; GRANT SELECT, INSERT ON doc_events TO signetd; GRANT USAGE ON SEQUENCE doc_events_id_seq TO signetd; GRANT SELECT, INSERT, UPDATE ON facsimiles TO signetd; GRANT SELECT ON doc_decisions TO signetd;" su-exec signet psql -q -d signet -c \ - "INSERT INTO facsimiles (username, enrolled_by, enrolled_at, width, height) VALUES ('ceo', 'admin', NOW(), 200, 80); INSERT INTO facsimiles (username, enrolled_by, enrolled_at, width, height) VALUES ('manager', 'admin', NOW(), 200, 80);" + "INSERT INTO facsimiles (username, enrolled_by, enrolled_at, width, height) VALUES ('ceo', 'admin', NOW(), 300, 80); INSERT INTO facsimiles (username, enrolled_by, enrolled_at, width, height) VALUES ('manager', 'admin', NOW(), 300, 80);" fi mkdir -p /var/lib/signet/sig-inbox @@ -30,7 +30,8 @@ cp /usr/share/fonts/dejavu/DejaVuSans.ttf /var/www/dam/fonts/ cp /src/test/fixtures/seal.png /var/www/dam/seals/agency_seal.png cp /src/test/fixtures/sig.png /var/lib/signatures/ceo.png cp /src/test/fixtures/sig.png /var/lib/signatures/manager.png -chown -R signet:signet /var/lib/signet && chmod 2770 /var/lib/signet && chmod 1730 /var/lib/signet/sig-inbox +chown -R signet:signet /var/lib/signet && chmod 2770 /var/lib/signet +chown signetd:signet /var/lib/signet/sig-inbox && chmod 1730 /var/lib/signet/sig-inbox chown -R signetd /var/lib/signatures && chmod 0700 /var/lib/signatures && chmod 0600 /var/lib/signatures/* chown -R lighttpd /var/www/dam
diff --git a/test/e2e.sh b/test/e2e.sh @@ -1,103 +1,211 @@ #!/bin/sh -# End-to-end check against the dev stack (run inside the container). +# API/worker acceptance against an isolated dev container (run as root). set -eu +if [ "${1-}" = render-contract ]; then + exec sh /src/test/render-contract.sh +fi B=http://localhost:8080 X='X-Requested-With: signet' -as() { u=$1; g=$2; shift 2; curl -sS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } +as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } clerk() { as asha clerks "$@"; } admin() { as root signet-admins "$@"; } -ok() { echo "ok - $1"; } -die() { echo "FAIL - $1"; exit 1; } -expect() { echo "$2" | grep -q "$3" && ok "$1" || die "$1: got $2"; } - -expect "unauthenticated is 401" "$(curl -sS $B/api/me)" 'no authenticated user' -expect "roles from groups" "$(clerk $B/api/me)" '"drafter":true,"signer":false' -expect "POST needs CSRF header" "$(clerk -d '' $B/api/series)" 'X-Requested-With' -expect "clerk cannot create series" "$(clerk -H "$X" -F code=T -F 'pattern={seq}' $B/api/series)" 'admin role' - -admin -H "$X" -F code=SCNREPLY -F 'pattern=SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}' $B/api/series >/dev/null -admin -H "$X" -F org=SKGA -F key=gstin -F type=text -F value=33AAAAA0000A1Z5 $B/pim-api/attrs >/dev/null -admin -H "$X" -F org=SKGA -F key=seal -F type=image -F value=seals/agency_seal.png $B/pim-api/attrs >/dev/null -admin $B/pim-api/resync >/dev/null -expect "PIM visible through signet (text)" "$(clerk $B/api/pim)" 'SKGA.*gstin' -expect "PIM has image type" "$(clerk $B/api/pim)" 'seal.*image' -expect "DAM listing" "$(clerk $B/api/dam)" 'seals/agency_seal.png' - -ID=$(clerk -H "$X" -F file=@/src/test/fixtures/letter.pdf $B/api/docs | jq -r .id) -[ ${#ID} -eq 36 ] && ok "draft created $ID" || die "create" - -LAYOUT='{"title":"","org_code":"SKGA","series_code":"SCNREPLY", - "route":{"parties":[{"name":"Manager","signer":"manager"},{"name":"CEO","signer":"ceo"}]}, - "layout":{"reference_width":1000,"reference_height":1414,"imprints":[ - {"page":1,"type":"pim_text","ref":"gstin","prefix":"GSTIN: ","coords":[120,150,520,180]}, - {"page":1,"type":"serial","coords":[120,200,620,228],"font":"fonts/DejaVuSans.ttf"}, - {"page":1,"type":"date","coords":[700,150,900,178],"align":"right"}, - {"page":2,"type":"pim_image","shape":"circle","ref":"seal","coords":[300,1100,90]}, - {"page":2,"type":"signature_zone","party":"CEO","coords":[600,1050,850,1150],"min_w":50,"min_h":50}]}}' -expect "save layout" "$(clerk -H "$X" -F "json=$LAYOUT" $B/api/docs/$ID/save)" '"ok":true' -expect "other clerk cannot see draft" "$(as ravi clerks $B/api/docs/$ID)" 'not found' - -BAD=$(echo "$LAYOUT" | sed 's/"name":"CEO"/"name":"Unknown"/') -clerk -H "$X" -F "json=$BAD" $B/api/docs/$ID/save >/dev/null -expect "party name must match route" "$(clerk -H "$X" -d '' $B/api/docs/$ID/submit)" 'unknown party' -clerk -H "$X" -F "json=$LAYOUT" $B/api/docs/$ID/save >/dev/null - -expect "submit" "$(clerk -H "$X" -d '' $B/api/docs/$ID/submit)" '"revision":1' -for i in 1 2 3 4 5 6 7 8 9 10; do - D=$(clerk $B/api/docs/$ID) - [ "$(echo "$D" | jq -r .render_seq)" = 1 ] && break - sleep 1 -done -expect "stamped by worker" "$D" '"render_seq":1' +sql() { su-exec postgres psql -X -At -v ON_ERROR_STOP=1 -d signet "$@"; } +ok() { echo "ok - $*"; } +die() { echo "FAIL - $*"; exit 1; } +check() { echo "$2" | jq -e "$3" >/dev/null || die "$1: $2"; ok "$1"; } +code() { u=$1; g=$2; shift 2; curl -sS -o /tmp/signet-e2e-response -w '%{http_code}' -H "Remote-User: $u" -H "Remote-Groups: $g" -H "$X" "$@"; } +status() { want=$1; shift; got=$(code "$@"); [ "$got" = "$want" ] || die "HTTP $got, expected $want: $(head -c 500 /tmp/signet-e2e-response)"; } +get() { clerk "$B/api/docs/$ID"; } +save() { clerk -H "$X" --form-string "json=$1" "$B/api/docs/$ID/save"; } +submit() { clerk -H "$X" -d '' "$B/api/docs/$ID/submit"; } +decide() { u=$1; decision=$2; shift 2; as "$u" management -H "$X" -F "decision=$decision" "$@" "$B/api/docs/$ID/decide"; } +wait_ready() { + for i in $(seq 1 100); do + D=$(get) + [ "$(echo "$D" | jq -r .render_error)" = null ] || die "$D" + [ "$(echo "$D" | jq -r .rendering)" = false ] && return 0 + sleep .1 + done + die 'render timeout' +} +wait_error() { + for i in $(seq 1 100); do D=$(get); [ "$(echo "$D" | jq -r .render_error)" != null ] && return 0; sleep .1; done + die 'expected render failure' +} +stop_worker() { pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true; sleep 1; } +start_worker() { su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/signet-e2e-worker.log 2>&1 & } +cleanup() { + for f in /var/lib/signatures/*.e2e-saved; do [ ! -e "$f" ] || mv "$f" "${f%.e2e-saved}"; done + stop_worker + start_worker +} +trap cleanup EXIT +pgrep -f '^/usr/local/sbin/signetd$' >/dev/null || start_worker +images() { pdfimages -list "$1" | awk '$3 == "image" {n++} END {print n+0}'; } +new_doc() { + ID=$(clerk -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -r .id) + [ ${#ID} = 36 ] || die create + save "$LAYOUT" >/dev/null +} +# Auth-provider setup and the pre-existing missing-header fallback are ticket 13, +# not prerequisites for these tests; every request supplies an explicit identity. +check 'configured drafter role' "$(clerk "$B/api/me")" '.roles.drafter and (.roles.signer | not)' +status 403 asha clerks -F code=DENIED -F 'pattern={seq}' "$B/api/series" +SERIES=T11_$(date +%s) +admin -H "$X" -F "code=$SERIES" -F "pattern=$SERIES/{date:%Y%m%d}/{seq:02}" "$B/api/series" >/dev/null +admin -H "$X" -F org=ORG11 -F key=gstin -F type=text -F value=33AAAAA0000A1Z5 "$B/pim-api/attrs" >/dev/null +admin -H "$X" -F org=ORG11 -F key=seal -F type=image -F value=seals/agency_seal.png "$B/pim-api/attrs" >/dev/null +check 'PIM text/image references' "$(clerk "$B/api/pim")" '.ORG11.text.gstin == "33AAAAA0000A1Z5" and .ORG11.images.seal == "seals/agency_seal.png"' +LAST=fresh_$(date +%s) +LAYOUT=$(jq -nc --arg series "$SERIES" --arg last "$LAST" '{title:"Acceptance letter",org_code:"ORG11",series_code:$series,route:{parties:[{name:"Manager",signer:"manager"},{name:"Audit",signer:"auditor"},{name:"Partner",signer:$last}]},layout:{reference_width:1000,reference_height:1414,imprints:[{page:1,type:"pim_text",ref:"gstin",prefix:"GSTIN: ",font:"fonts/DejaVuSans.ttf",coords:[120,150,520,180]},{page:1,type:"serial",coords:[120,200,620,228]},{page:1,type:"signature_zone",party:"Manager",coords:[120,550,500,700],min_w:50,min_h:20},{page:2,type:"pim_image",shape:"circle",ref:"seal",coords:[300,1100,90]},{page:2,type:"signature_zone",party:"Partner",coords:[400,1000,850,1200],min_w:70,min_h:25}]}}') +PM='{"page":1,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' +PL='{"page":2,"coords":[400,1000,850,1200],"ref_w":1000,"ref_h":1414}' +new_doc +save "$(echo "$LAYOUT" | jq '.title=" "')" >/dev/null +status 409 asha clerks -d '' "$B/api/docs/$ID/submit" +check 'empty title does not allocate a serial' "$(get)" '.serial == null and .revision == 0' +save "$LAYOUT" >/dev/null +status 400 asha clerks --form-string "json=$(echo "$LAYOUT" | jq '.route.parties[1].name="Manager"')" "$B/api/docs/$ID/save" +status 400 asha clerks --form-string "json=$(echo "$LAYOUT" | jq '.layout.imprints[2].min_w=0')" "$B/api/docs/$ID/save" +status 400 asha clerks --form-string "json=$(echo "$LAYOUT" | jq '.layout.imprints[4].party="Unknown"')" "$B/api/docs/$ID/save" +status 400 asha clerks --form-string "json=$(echo "$LAYOUT" | jq '.layout.imprints += [.layout.imprints[2]]')" "$B/api/docs/$ID/save" +status 400 asha clerks --form-string "json=$(echo "$LAYOUT" | jq '.layout.imprints[2].page=4294967297')" "$B/api/docs/$ID/save" +save "$(echo "$LAYOUT" | jq '.layout.imprints[3].ref="missing_image"')" >/dev/null +status 409 asha clerks -d '' "$B/api/docs/$ID/submit" +save "$LAYOUT" >/dev/null +status 404 ravi clerks "$B/api/docs/$ID" +submit >/dev/null +wait_ready SERIAL=$(echo "$D" | jq -r .serial) -expect "serial allocated" "$SERIAL" "^SKGA/SCNREPLY/$(date +%Y%m%d)/01$" -expect "title defaults to serial" "$(echo "$D" | jq -r .title)" "$SERIAL" - -clerk -o /tmp/proof.pdf $B/api/docs/$ID/file/proof -TXT=$(pdftotext /tmp/proof.pdf -) -expect "proof has PIM text" "$TXT" 'GSTIN: 33AAAAA0000A1Z5' -expect "proof has serial" "$TXT" "$SERIAL" -expect "proof has date" "$TXT" "$(date +%d-%m-%Y)" -expect "maker cannot fetch stamped copy" "$(clerk $B/api/docs/$ID/file/stamped)" 'forbidden' -P=$(pdfimages -list /tmp/proof.pdf | grep -c image || true) -as ceo management -o /tmp/stamped.pdf $B/api/docs/$ID/file/stamped -S=$(pdfimages -list /tmp/stamped.pdf | grep -c image || true) -[ "$S" -gt "$P" ] && ok "stamped copy has the signature, proof does not ($P vs $S images)" || die "signature images $P vs $S" +DATE=$(echo "$D" | jq -r .doc_date) +check 'stamp is ready with organisation and serial' "$D" '.render_seq == .rendered_seq and .revision == 1 and .org_code == "ORG11" and (.events | map(.action) | index("SUBMITTED")) != null' +[ "$SERIAL" = "$SERIES/$(date +%Y%m%d)/01" ] || die serial +for kind in source proof stamped final; do status 404 "$LAST" management "$B/api/docs/$ID/file/$kind"; done +status 404 "$LAST" management "$B/api/docs/$ID" +check 'later party is absent from involved list' "$(as "$LAST" management "$B/api/docs?scope=involved")" "all(.[]; .id != \"$ID\")" +status 403 asha clerks "$B/api/docs/$ID/file/stamped" +status 404 manager management "$B/api/docs/$ID/file/final" +clerk -o /tmp/t11-proof.pdf "$B/api/docs/$ID/file/proof" +pdftotext /tmp/t11-proof.pdf - | grep -q 'GSTIN: 33AAAAA0000A1Z5' || die 'PIM text absent' +P=$(images /tmp/t11-proof.pdf) +as manager management -o /tmp/t11-stamped.pdf "$B/api/docs/$ID/file/stamped" +[ "$(images /tmp/t11-stamped.pdf)" = "$P" ] || die 'facsimiles present before sign-off' +ok 'sequential metadata/list/file visibility and unsigned proof' +for placement in \ + '{"page":2,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":[0,0,500,700],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":[120,550,130,560],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":[120,550,180,650],"ref_w":1000,"ref_h":1414}' \ + '{"page":4294967297,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":[500,700,120,550],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":["120",550,500,700],"ref_w":1000,"ref_h":1414}' \ + '{"page":1,"coords":[120,550,500,700],"ref_w":0,"ref_h":1414}' \ + '{"page":1,"coords":[120,550,500],"ref_w":1000,"ref_h":1414}'; do + status 409 manager management -F decision=signoff --form-string "placement=$placement" "$B/api/docs/$ID/decide" +done +check 'invalid placements do not record a decision' "$(as manager management "$B/api/docs/$ID")" '.can_decide and (.decisions | length) == 0' +# Equivalent smaller reference frame must normalize to the same zone rectangle. +decide manager signoff --form-string 'placement={"page":1,"coords":[60,275,250,350],"ref_w":500,"ref_h":707}' >/dev/null +wait_ready +as auditor management -o /tmp/t11-stamped.pdf "$B/api/docs/$ID/file/stamped" +[ "$(images /tmp/t11-stamped.pdf)" = "$((P+1))" ] || die 'non-final overlay missing' +SEQ=$(echo "$D" | jq .render_seq) +status 409 auditor management -F decision=signoff --form-string "placement=$PM" "$B/api/docs/$ID/decide" +decide auditor signoff >/dev/null +check 'check-only sign-off advances without a render' "$(get)" ".current_party == 3 and .render_seq == $SEQ and (.rendering | not)" +status 409 "$LAST" management -F decision=signoff --form-string "placement=$PL" "$B/api/docs/$ID/decide" +as "$LAST" management -H "$X" -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" >/dev/null +for i in $(seq 1 100); do [ "$(as "$LAST" management "$B/api/me" | jq -r .enrolled)" = true ] && break; sleep .1; done +check 'first-signing enrolment activates' "$(as "$LAST" management "$B/api/me")" '.enrolled and .facsimile.width > 0' +stop_worker +decide "$LAST" signoff --form-string "placement=$PL" -F 'comment=Final party attestation' >/dev/null +check 'last decision queues release, not synchronous success' "$(get)" '.status == "PENDING" and .render_kind == "release" and .rendering and (.can_decide | not)' +status 409 "$LAST" management -F decision=signoff --form-string "placement=$PL" "$B/api/docs/$ID/decide" +status 403 auditor management -d '' "$B/api/docs/$ID/rerender" +status 404 "$LAST" management "$B/api/docs/$ID/file/final" +mv "/var/lib/signatures/$LAST.png" "/var/lib/signatures/$LAST.png.e2e-saved" +start_worker +wait_error +check 'release failure remains pending without a release event' "$D" '.status == "PENDING" and (.events | map(.action) | index("RELEASE_FAILED")) != null and (.events | map(.action) | index("RELEASED")) == null' +status 403 asha clerks -d '' "$B/api/docs/$ID/rerender" +stop_worker +mv "/var/lib/signatures/$LAST.png.e2e-saved" "/var/lib/signatures/$LAST.png" +as "$LAST" management -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null +start_worker +wait_ready +check 'worker releases with final SHA-256 and event' "$D" '.status == "RELEASED" and (.final_sha256 | length) == 64 and (.events | map(.action) | index("RELEASED")) != null' +clerk -o /tmp/t11-final.pdf "$B/api/docs/$ID/file/final" +[ "$(images /tmp/t11-final.pdf)" = "$((P+2))" ] || die 'last facsimile missing or duplicated' +[ "$(sha256sum /tmp/t11-final.pdf | cut -d ' ' -f 1)" = "$(echo "$D" | jq -r .final_sha256)" ] || die 'final hash mismatch' +pdftotext -f 3 /tmp/t11-final.pdf - | tr '\n' ' ' | tr -s '[:space:]' ' ' > /tmp/t11-audit.txt +for term in CREATED SUBMITTED SIGNOFF RELEASE_FAILED RETRY RELEASED ORG11 'Final party attestation' 'SHA-256'; do grep -q "$term" /tmp/t11-audit.txt || die "missing audit term $term"; done +[ ! -e "/var/lib/signet/docs/$ID/stamped.pdf" ] || die 'stamped copy retained after release' +ok 'final overlay, full audit, release retry and cleanup' -expect "ceo cannot sign yet" "$(as ceo management -H "$X" -F decision=approve $B/api/docs/$ID/decide)" 'not waiting' -expect "pending list for manager" "$(as manager management $B/api/docs?scope=pending)" "$ID" -expect "correction needs comment" "$(as manager management -H "$X" -F decision=correction $B/api/docs/$ID/decide)" 'comment is required' -expect "manager asks for correction" "$(as manager management -H "$X" -F decision=correction -F comment='fix date' $B/api/docs/$ID/decide)" '"ok":true' -expect "status CORRECTION_REQUIRED, editable" "$(clerk $B/api/docs/$ID)" '"status":"CORRECTION_REQUIRED".*"can_edit":true' -expect "resubmit" "$(clerk -H "$X" -d '' $B/api/docs/$ID/submit)" '"revision":2' -sleep 2 -D=$(clerk $B/api/docs/$ID) -expect "status PENDING, serial unchanged" "$D" "\"status\":\"PENDING\".*\"serial\":\"$SERIAL\"" +new_doc +submit >/dev/null +wait_ready +SERIAL2=$(echo "$D" | jq -r .serial) +DATE2=$(echo "$D" | jq -r .doc_date) +decide manager signoff --form-string "placement=$PM" >/dev/null +wait_ready +REASON=$(printf 'Correct this document\n'; printf 'full history retained %.0s' $(seq 1 90); printf ' END_OF_LONG_CORRECTION') +decide auditor correction --form-string "comment=$REASON" >/dev/null +check 'correction returns to drafter' "$(get)" '.status == "CORRECTION_REQUIRED" and .can_edit' +[ ! -e "/var/lib/signet/docs/$ID/stamped.pdf" ] || die 'stamped copy retained after correction' +status 404 auditor management "$B/api/docs/$ID/file/stamped" +save "$LAYOUT" >/dev/null +submit >/dev/null +wait_ready +check 'resubmit restarts route and voids old decisions' "$D" '.revision == 2 and .current_party == 1 and (.events | map(.action) | index("RESUBMITTED")) != null' +[ "$(echo "$D" | jq -r .serial)" = "$SERIAL2" ] && [ "$(echo "$D" | jq -r .doc_date)" = "$DATE2" ] || die 'serial/date changed on correction' +status 404 auditor management "$B/api/docs/$ID" +check 'first party must sign again' "$(as manager management "$B/api/docs/$ID")" '.can_decide' +as manager management -o /tmp/t11-resubmitted.pdf "$B/api/docs/$ID/file/stamped" +[ "$(images /tmp/t11-resubmitted.pdf)" = "$P" ] || die 'old facsimile survived resubmit' +decide manager signoff --form-string "placement=$PM" >/dev/null +wait_ready +decide auditor signoff >/dev/null +# More than the old 64-line audit cap, with a sentinel at the end. +sql -c "INSERT INTO doc_events(doc_id,actor,action,detail) SELECT '$ID','test-fixture','HISTORICAL','History entry ' || n FROM generate_series(1,80) n" >/dev/null +decide "$LAST" signoff --form-string "placement=$PL" >/dev/null +wait_ready +clerk -o /tmp/t11-corrected.pdf "$B/api/docs/$ID/file/final" +pdftotext -f 3 /tmp/t11-corrected.pdf - | tr '\n' ' ' | tr -s '[:space:]' ' ' > /tmp/t11-corrected-audit.txt +for term in CORRECTION_REQUIRED RESUBMITTED END_OF_LONG_CORRECTION 'History entry 80'; do grep -q "$term" /tmp/t11-corrected-audit.txt || die "audit truncated: $term"; done +[ "$(pdfinfo /tmp/t11-corrected.pdf | awk '/^Pages:/ {print $2}')" -gt 3 ] || die 'audit did not paginate' +ok 'correction/resubmit keeps serial/date; full multi-page history is not truncated' -expect "manager sign-off (no zone)" "$(as manager management -H "$X" -F decision=approve $B/api/docs/$ID/decide)" '"ok":true' -expect "now party 2" "$(clerk $B/api/docs/$ID | jq .current_party)" '^2$' -expect "ceo not enrolled yet" "$(as ceo management $B/api/me)" '"enrolled":false' -expect "ceo cannot sign without enrollment" "$(as ceo management -H "$X" -F decision=approve $B/api/docs/$ID/decide)" 'enrol your signature' -as ceo management -H "$X" -F file=@/src/test/fixtures/sig.png $B/api/me/facsimile >/dev/null -for i in 1 2 3 4 5 6; do - ME=$(as ceo management $B/api/me) - [ "$(echo "$ME" | jq -r .enrolled)" = true ] && break - sleep 1 -done -expect "ceo enrolled after upload" "$ME" '"enrolled":true' -PLACEMENT='{"page":2,"coords":[600,1050,850,1150],"ref_w":1000,"ref_h":1414}' -expect "ceo signs with placement" "$(as ceo management -H "$X" -F decision=approve -F placement='$PLACEMENT' $B/api/docs/$ID/decide)" '"ok":true' -D=$(clerk $B/api/docs/$ID) -expect "RELEASED" "$D" '"status":"RELEASED"' -clerk -o /tmp/final.pdf $B/api/docs/$ID/file/final -expect "final = 2 pages + audit page" "$(pdfinfo /tmp/final.pdf)" 'Pages: *3' -expect "sha256 recorded matches file" "$(sha256sum /tmp/final.pdf)" "$(echo "$D" | jq -r .final_sha256)" -expect "audit page lists sign-offs" "$(pdftotext -f 3 /tmp/final.pdf -)" 'ceo' -[ ! -e /var/lib/signet/docs/$ID/stamped.pdf ] && ok "stamped copy removed after release" || die "stamped copy left behind" +new_doc +submit >/dev/null +wait_ready +SERIAL3=$(echo "$D" | jq -r .serial) +decide manager disapprove -F 'comment=Terminal decision' >/dev/null +check 'disapproval is terminal and keeps serial' "$(get)" '.status == "DISAPPROVED" and (.serial | endswith("/03"))' +status 409 asha clerks -d '' "$B/api/docs/$ID/delete" +status 409 asha clerks -d '' "$B/api/docs/$ID/submit" +status 409 asha clerks --form-string "json=$LAYOUT" "$B/api/docs/$ID/save" +[ ! -e "/var/lib/signet/docs/$ID/stamped.pdf" ] || die 'stamped copy retained after disapproval' +ok 'terminal disapproval retains the allocated serial' -expect "template from document" "$(clerk -H "$X" -F doc_id=$ID -F name='Reply letter' $B/api/templates)" '"id"' -TID=$(clerk $B/api/templates | jq -r '.[0].id') -ID2=$(clerk -H "$X" -F template_id=$TID $B/api/docs | jq -r .id) -clerk -H "$X" -d '' $B/api/docs/$ID2/submit >/dev/null -expect "second doc from template gets /02" "$(clerk $B/api/docs/$ID2 | jq -r .serial)" '/02$' -echo "all passed" +# Self-service is explicitly allowed, including a one-party final zone. +ID=$(as asha clerks,management -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -r .id) +SELF=$(echo "$LAYOUT" | jq '.title="Self service" | .route.parties=[{name:"Manager",signer:"asha"}] | .layout.imprints=[.layout.imprints[2]]') +as asha clerks,management -H "$X" --form-string "json=$SELF" "$B/api/docs/$ID/save" >/dev/null +submit >/dev/null +wait_ready +as asha clerks,management -H "$X" -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" >/dev/null +for i in $(seq 1 100); do [ "$(as asha management "$B/api/me" | jq -r .enrolled)" = true ] && break; sleep .1; done +decide asha signoff --form-string "placement=$PM" >/dev/null +wait_ready +check 'self-service release' "$D" '.status == "RELEASED" and (.serial | endswith("/04"))' +TID=$(clerk -H "$X" -F "doc_id=$ID" -F name='Self service template' "$B/api/templates" | jq -r .id) +CHILD=$(clerk -H "$X" -F "template_id=$TID" "$B/api/docs" | jq -r .id) +check 'template copies parties and zones' "$(clerk "$B/api/docs/$CHILD")" '.route.parties[0].name == "Manager" and .layout.imprints[0].type == "signature_zone"' +admin -H "$X" -d '' "$B/api/templates/$TID/retire" >/dev/null +status 400 asha clerks -F "template_id=$TID" "$B/api/docs" +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' +echo 'all passed'
diff --git a/test/render-contract.sh b/test/render-contract.sh @@ -0,0 +1,236 @@ +#!/bin/sh +# Isolated, destructive queue/database regression checks; run as root in dev. +set -eu +B=http://localhost:8080 +X='X-Requested-With: signet' +Q=queue:stamping +sql() { su-exec postgres psql -X -At -v ON_ERROR_STOP=1 -d signet "$@"; } +as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } +post() { as "$1" "$2" -H "$X" -d '' "$B/api/docs/$ID/$3"; } +fail() { echo "FAIL - $*"; exit 1; } +ok() { echo "ok - $*"; } +stop_worker() { pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true; sleep 1; } +start_worker() { su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/render-contract-worker.log 2>&1 & } +cleanup() { + redis-cli ACL SETUSER default +lpush >/dev/null + sql -c 'DROP TRIGGER IF EXISTS ticket10_fail ON documents; DROP FUNCTION IF EXISTS ticket10_fail();' >/dev/null + [ ! -e /var/lib/signatures/manager.png.saved ] || mv /var/lib/signatures/manager.png.saved /var/lib/signatures/manager.png + stop_worker + start_worker +} +trap cleanup EXIT +wait_done() { + for i in $(seq 1 80); do + D=$(as asha clerks "$B/api/docs/$ID") + [ "$(echo "$D" | jq -r .render_error)" = null ] || fail "render error: $D" + if [ "$(echo "$D" | jq -r .rendering)" = false ]; then return; fi + sleep .1 + done + fail 'render did not finish' +} +wait_error() { + for i in $(seq 1 80); do + D=$(as asha clerks "$B/api/docs/$ID") + [ "$(echo "$D" | jq -r .render_error)" = null ] || return 0 + sleep .1 + done + fail 'expected render error' +} +wait_empty() { + for i in $(seq 1 80); do + [ "$(redis-cli LLEN "$Q")$(redis-cli LLEN "$Q:processing")" = 00 ] && return + sleep .1 + done + fail 'queues did not drain' +} +assert_job() { + redis-cli --raw LINDEX "$Q" 0 | jq -e --arg id "$ID" --arg kind "$1" --argjson seq "$2" \ + '.doc_id == $id and .revision == 1 and .seq == $seq and .kind == $kind' >/dev/null || fail 'wrong job payload' +} +http_code() { + u=$1; g=$2; shift 2 + curl -sS -o /tmp/render-contract-response -w '%{http_code}' -H "Remote-User: $u" -H "Remote-Groups: $g" -H "$X" "$@" +} +new_doc() { + ID=$(as asha clerks -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -r .id) + [ ${#ID} = 36 ] || fail 'create document' + as asha clerks -H "$X" --form-string "json=$LAYOUT" "$B/api/docs/$ID/save" | jq -e .ok >/dev/null +} +images() { pdfimages -list "$1" | awk '$3 == "image" {n++} END {print n+0}'; } + +stop_worker +: >/tmp/render-contract-worker.log +redis-cli DEL "$Q" "$Q:processing" >/dev/null +as root signet-admins -H "$X" -F org=TICKET10 -F key=gstin -F type=text -F value=FROZEN-LATER "$B/pim-api/attrs" >/dev/null +LAYOUT='{"title":"Render contract","org_code":"TICKET10","route":{"parties":[{"name":"Manager","signer":"manager"},{"name":"CEO","signer":"ceo"}]},"layout":{"reference_width":1000,"reference_height":1414,"imprints":[{"page":1,"type":"pim_text","ref":"gstin","coords":[120,150,520,180]},{"page":2,"type":"signature_zone","party":"Manager","coords":[500,900,900,1100],"min_w":50,"min_h":50}]}}' +new_doc +post asha clerks submit >/dev/null +assert_job stamp 1 +D=$(as asha clerks "$B/api/docs/$ID") +echo "$D" | jq -e '.rendering and .can_retry and .rendered_seq == 0 and .render_seq == 1 and .render_kind == "stamp"' >/dev/null || fail 'initial progress' +[ "$(http_code ravi clerks -d '' "$B/api/docs/$ID/rerender")" = 403 ] || fail 'unrelated retry allowed' +ok 'submit payload and outstanding-render metadata' +start_worker +wait_done +wait_empty +BASE=/var/lib/signet/docs/$ID +HASH=$(sha256sum "$BASE/stamped.pdf") +EVENTS=$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='STAMPED'") +for job in \ + "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":1,\"kind\":\"stamp\"}" \ + "{\"doc_id\":\"$ID\",\"revision\":2,\"seq\":1,\"kind\":\"stamp\"}" \ + "{\"doc_id\":\"$ID\",\"revision\":1}" \ + "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":1,\"kind\":\"bogus\"}"; do + redis-cli LPUSH "$Q" "$job" >/dev/null +done +wait_empty +[ "$(sha256sum "$BASE/stamped.pdf")" = "$HASH" ] || fail 'stale job changed PDF' +[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='STAMPED'")" = "$EVENTS" ] || fail 'duplicate completion event' +[ "$(http_code asha clerks -d '' "$B/api/docs/$ID/rerender")" = 409 ] || fail 'completed render retried' +ok 'completed, stale and malformed jobs do not change output or history' + +stop_worker +PLACEMENT='{"page":2,"coords":[500,900,900,1100],"ref_w":1000,"ref_h":1414}' +as manager management -H "$X" -F decision=approve --form-string "placement=$PLACEMENT" "$B/api/docs/$ID/decide" | jq -e .ok >/dev/null +assert_job sign 2 +[ "$(as ceo management "$B/api/docs/$ID" | jq -r .can_decide)" = false ] || fail 'next party can decide before sign render' +[ "$(http_code asha clerks -d '' "$B/api/docs/$ID/rerender")" = 403 ] || fail 'drafter can retry sign' +[ "$(as manager management "$B/api/docs/$ID" | jq -r .can_retry)" = true ] || fail 'previous signer cannot retry' +mv /var/lib/signatures/manager.png /var/lib/signatures/manager.png.saved +start_worker +wait_error +wait_empty +echo "$D" | jq -e '.rendered_seq == 1 and .render_seq == 2 and .rendering and .render_kind == "sign"' >/dev/null || fail 'failed-sign metadata' +ok 'sign dispatch and signer-specific retry permissions' +stop_worker +mv /var/lib/signatures/manager.png.saved /var/lib/signatures/manager.png +post manager management rerender >/dev/null +assert_job sign 3 +JOB=$(redis-cli --raw RPOP "$Q") +HASH=$(sha256sum "$BASE/stamped.pdf") +for job in \ + "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":1,\"kind\":\"stamp\"}" \ + "{\"doc_id\":\"$ID\",\"revision\":2,\"seq\":3,\"kind\":\"sign\"}" \ + "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":3,\"kind\":\"stamp\"}"; do + redis-cli LPUSH "$Q" "$job" >/dev/null +done +start_worker +wait_empty +stop_worker +[ "$(sha256sum "$BASE/stamped.pdf")" = "$HASH" ] || fail 'stale job changed an outstanding render' +[ "$(sql -c "SELECT render_seq || ':' || rendered_seq FROM documents WHERE id='$ID'")" = 3:1 ] || fail 'stale job completed outstanding work' +redis-cli LPUSH "$Q" "$JOB" >/dev/null +ok 'sequence, revision and kind mismatches are ignored while current work is outstanding' +# Force failure after output publication but before the completion transaction commits. +sql <<'SQL' >/dev/null +CREATE FUNCTION ticket10_fail() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.rendered_seq > OLD.rendered_seq THEN + RAISE EXCEPTION 'ticket10 completion update failure'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER ticket10_fail BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION ticket10_fail(); +SQL +start_worker +for i in $(seq 1 80); do + grep -q 'ticket10 completion update failure' /tmp/render-contract-worker.log && break + sleep .1 +done +grep -q 'ticket10 completion update failure' /tmp/render-contract-worker.log || fail 'database failure not exercised' +stop_worker +[ "$(sql -c "SELECT rendered_seq FROM documents WHERE id='$ID'")" = 1 ] || fail 'failed update was committed' +[ "$(redis-cli LLEN "$Q")$(redis-cli LLEN "$Q:processing")" != 00 ] || fail 'job lost after database failure' +P=$(images "$BASE/proof.pdf") +[ "$(images "$BASE/stamped.pdf")" = "$((P+1))" ] || fail 'sign output was not published before database failure' +sql -c 'DROP TRIGGER ticket10_fail ON documents; DROP FUNCTION ticket10_fail();' >/dev/null +# Leave the retained job in :processing to exercise startup recovery. +redis-cli RPOPLPUSH "$Q" "$Q:processing" >/dev/null +start_worker +wait_done +wait_empty +[ "$(images "$BASE/stamped.pdf")" = "$((P+1))" ] || fail 'replay applied signature twice' +[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND actor='signetd' AND action='SIGNED'")" = 1 ] || fail 'wrong number of committed sign events' +echo "$D" | jq -e '.revision == 1 and .render_seq == 3 and .rendered_seq == 3 and (.rendering | not)' >/dev/null || fail 'retry confused sequence with revision' +HASH=$(sha256sum "$BASE/stamped.pdf") +redis-cli LPUSH "$Q" "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":2,\"kind\":\"sign\"}" >/dev/null +redis-cli LPUSH "$Q" "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":3,\"kind\":\"sign\"}" >/dev/null +wait_empty +[ "$(sha256sum "$BASE/stamped.pdf")" = "$HASH" ] || fail 'sign replay changed PDF' +ok 'database failure retains work; startup recovery and duplicates never double-stamp' + +# The final check-only party releases asynchronously. Crash after publication +# must leave final.pdf inaccessible until the same database outcome commits. +stop_worker +as ceo management -H "$X" -F decision=signoff "$B/api/docs/$ID/decide" >/dev/null +assert_job release 4 +sql <<'SQL' >/dev/null +CREATE FUNCTION ticket10_fail() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.status = 'RELEASED' THEN + RAISE EXCEPTION 'release completion update failure'; + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER ticket10_fail BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION ticket10_fail(); +SQL +start_worker +for i in $(seq 1 80); do + grep -q 'release completion update failure' /tmp/render-contract-worker.log && break + sleep .1 +done +grep -q 'release completion update failure' /tmp/render-contract-worker.log || fail 'release database failure not exercised' +stop_worker +[ -f "$BASE/final.pdf" ] || fail 'final was not published before database failure' +BODY_HASH=$(sha256sum "$BASE/render-4.pdf" | cut -d ' ' -f 1) +[ "$(http_code ceo management "$B/api/docs/$ID/file/final")" = 404 ] || fail 'uncommitted final was served' +[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='RELEASED'")" = 0 ] || fail 'uncommitted release event survived rollback' +sql -c 'DROP TRIGGER ticket10_fail ON documents; DROP FUNCTION ticket10_fail();' >/dev/null +redis-cli RPOPLPUSH "$Q" "$Q:processing" >/dev/null +start_worker +wait_done +wait_empty +echo "$D" | jq -e '.status == "RELEASED" and .rendered_seq == 4' >/dev/null || fail 'release did not recover' +[ "$(images "$BASE/final.pdf")" = "$((P+1))" ] || fail 'release replay double-stamped' +pdftotext "$BASE/final.pdf" - | grep -q "$BODY_HASH" || fail 'audit body hash mismatch' +[ "$(sha256sum "$BASE/final.pdf" | cut -d ' ' -f 1)" = "$(echo "$D" | jq -r .final_sha256)" ] || fail 'final download hash mismatch' +[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='RELEASED'")" = 1 ] || fail 'duplicate release event' +[ ! -e "$BASE/stamped.pdf" ] || fail 'stamped copy retained after release' +# Simulate interrupted post-commit cleanup, then replay the already-finished job. +cp "$BASE/proof.pdf" "$BASE/stamped.pdf" +redis-cli LPUSH "$Q" "{\"doc_id\":\"$ID\",\"revision\":1,\"seq\":4,\"kind\":\"release\"}" >/dev/null +wait_empty +[ ! -e "$BASE/stamped.pdf" ] || fail 'post-commit cleanup did not recover' +ok 'release replay commits exactly once, hashes the body and gates final access until commit' + +# A queue outage after submit commits leaves a retryable render, even without an error string. +stop_worker +new_doc +redis-cli ACL SETUSER default -lpush >/dev/null +[ "$(http_code asha clerks -d '' "$B/api/docs/$ID/submit")" = 503 ] || fail 'queue outage not returned' +redis-cli ACL SETUSER default +lpush >/dev/null +D=$(as asha clerks "$B/api/docs/$ID") +echo "$D" | jq -e '.status == "PENDING" and .rendering and .can_retry and .render_error == null' >/dev/null || fail 'queue outage not retryable' +post asha clerks rerender >/dev/null +assert_job stamp 2 +start_worker +wait_done +wait_empty +ok 'post-commit queue outage can retry with the original render kind' + +as freshsigner management -H "$X" -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" >/dev/null +for i in $(seq 1 80); do + [ "$(as freshsigner management "$B/api/me" | jq -r .enrolled)" = true ] && break + sleep .1 +done +[ "$(as freshsigner management "$B/api/me" | jq -r .enrolled)" = true ] || fail 'enrol job without document id was dropped' +wait_empty +ok 'enrol payload is processed separately from document jobs' +head -c 33 /src/test/fixtures/sig.png > /tmp/truncated-sig.png +as corruptsigner management -H "$X" -F file=@/tmp/truncated-sig.png "$B/api/me/facsimile" >/dev/null +wait_empty +[ "$(as corruptsigner management "$B/api/me" | jq -r .enrolled)" = false ] || fail 'truncated PNG enrolled' +[ ! -e /var/lib/signatures/corruptsigner.png ] || fail 'truncated PNG published' +[ ! -e /var/lib/signet/sig-inbox/corruptsigner.png ] || fail 'invalid enrolment inbox retained' +ok 'enrolment fully decodes PNG before publishing a facsimile' +echo 'render contract: all passed'
diff --git a/test/render-progress.mjs b/test/render-progress.mjs @@ -0,0 +1,55 @@ +// Dev-only: PLAYWRIGHT_MODULE=/path/to/playwright-core/index.mjs node test/render-progress.mjs +import assert from 'node:assert/strict'; +import { mkdir } from 'node:fs/promises'; +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright-core'); +const base = process.env.SIGNET_URL || 'http://localhost:8080'; +const output = process.env.SIGNET_EVIDENCE || '/tmp/signet-ticket10-browser'; +await mkdir(output, { recursive: true }); +const browser = await chromium.launch({ + executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + headless: true, +}); +try { + const context = await browser.newContext({ + viewport: { width: 1440, height: 1000 }, + extraHTTPHeaders: { 'Remote-User': 'asha', 'Remote-Groups': 'clerks', 'X-Requested-With': 'signet' }, + }); + const page = await context.newPage(); + const docs = await (await context.request.get(base + '/api/docs?scope=mine')).json(); + const id = docs.find((d) => d.title === 'Render contract' && d.status === 'PENDING').id; + const original = await (await context.request.get(base + '/api/docs/' + id)).json(); + let state = { ...original, revision: 1, render_seq: 7, rendered_seq: 6, + rendering: true, render_error: null, can_retry: true, can_decide: false }; + let requests = 0; + await page.route('**/api/docs/' + id, async (route) => { + requests++; + await route.fulfill({ json: state }); + }); + await page.route('**/api/docs/' + id + '/rerender', async (route) => { + state = { ...state, rendering: false, rendered_seq: 8, render_seq: 8, render_error: null, can_retry: false }; + await route.fulfill({ json: { ok: true } }); + }); + await page.goto(base + '/#/doc/' + id); + await page.getByText('Rendering in progress…', { exact: true }).waitFor(); + await page.waitForTimeout(1450); + assert(requests >= 2, 'poll even when render sequence is greater than revision'); + await page.getByRole('button', { name: 'Retry rendering', exact: true }).waitFor(); + state = { ...state, render_error: 'Injected rendering failure', can_retry: false }; + await page.waitForTimeout(1450); + await page.getByText('Rendering failed: Injected rendering failure', { exact: true }).waitFor(); + assert.equal(await page.getByRole('button', { name: 'Retry rendering', exact: true }).count(), 0); + const stopped = requests; + await page.waitForTimeout(1450); + assert.equal(requests, stopped, 'stop polling after an error'); + state = { ...state, can_retry: true }; + await page.reload(); + await page.getByRole('button', { name: 'Retry rendering', exact: true }).click(); + await page.waitForTimeout(1450); + assert.equal(await page.getByText('Rendering in progress…', { exact: true }).count(), 0); + assert.equal(await page.getByRole('button', { name: 'Retry rendering', exact: true }).count(), 0); + assert.equal(await page.getByText('Rendering failed: Injected rendering failure', { exact: true }).count(), 0); + await page.screenshot({ path: output + '/render-progress.png', fullPage: true }); + console.log('render progress: polling, failure, retry authorization and completion passed'); +} finally { + await browser.close(); +}
diff --git a/test/signing-flow.mjs b/test/signing-flow.mjs @@ -0,0 +1,133 @@ +// Real browser/API/worker regression; run against the isolated Alpine dev stack. +// PLAYWRIGHT_MODULE=/path/to/playwright-core/index.mjs node test/signing-flow.mjs +import assert from 'node:assert/strict'; +import { mkdir, readFile } from 'node:fs/promises'; +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright-core'); +const base = process.env.SIGNET_URL || 'http://localhost:8080'; +const output = process.env.SIGNET_EVIDENCE || '/tmp/signet-ticket11-browser'; +await mkdir(output, { recursive: true }); +const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true }); +let page; +const errors = []; +try { + const context = await browser.newContext({ viewport: { width: 1440, height: 1700 } }); + page = await context.newPage(); + page.on('pageerror', (e) => errors.push(e.message)); + async function identity(user, groups) { + await context.setExtraHTTPHeaders({ 'Remote-User': user, 'Remote-Groups': groups, 'X-Requested-With': 'signet' }); + } + await identity('root', 'signet-admins'); + for (const [key, type, value] of [['gstin', 'text', '33AAAAA0000A1Z5'], ['seal', 'image', 'seals/agency_seal.png']]) { + assert((await context.request.post(base + '/pim-api/attrs', { multipart: { org: 'BROWSER11', key, type, value } })).ok()); + } + await identity('asha', 'clerks'); + const upload = await context.request.post(base + '/api/docs', { multipart: { file: { name: 'letter.pdf', mimeType: 'application/pdf', buffer: await readFile(new URL('fixtures/letter.pdf', import.meta.url)) } } }); + const { id } = await upload.json(); + const finalSigner = 'browser_' + Date.now(); + const layout = { title: 'Browser sequential signing', org_code: 'BROWSER11', route: { parties: [{ name: 'Manager', signer: 'manager' }, { name: 'Audit', signer: 'auditor' }, { name: 'Partner', signer: finalSigner }] }, layout: { reference_width: 1000, reference_height: 1414, imprints: [ + { type: 'pim_text', page: 1, ref: 'gstin', prefix: 'GSTIN: ', coords: [120, 150, 520, 180], font: 'fonts/DejaVuSans.ttf' }, + { type: 'signature_zone', page: 1, party: 'Manager', coords: [120, 550, 500, 700], min_w: 50, min_h: 20 }, + { type: 'pim_image', page: 2, ref: 'seal', shape: 'circle', coords: [300, 1100, 90] }, + { type: 'signature_zone', page: 2, party: 'Partner', coords: [400, 1000, 850, 1200], min_w: 70, min_h: 25 }, + ] } }; + assert((await context.request.post(base + `/api/docs/${id}/save`, { multipart: { json: JSON.stringify(layout) } })).ok()); + async function open() { + await page.goto(base + '/#/doc/' + id); + await page.reload(); + await page.locator('.page').nth(1).waitFor(); + await page.waitForFunction(() => [...document.querySelectorAll('.page img')].every((i) => i.complete && i.naturalWidth)); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(200); + } + async function capture(label) { + for (let i = 0; i < 2; i++) await page.locator('.page').nth(i).screenshot({ path: `${output}/${label}-${i + 1}.png` }); + } + async function signOff() { + const [response] = await Promise.all([page.waitForResponse((r) => r.url().endsWith('/decide') && r.request().method() === 'POST'), page.getByRole('button', { name: 'Sign off', exact: true }).click()]); + assert(response.ok(), await response.text()); + } + async function ready() { + for (let i = 0; i < 120; i++) { + const r = await context.request.get(base + '/api/docs/' + id), d = await r.json(); + assert(r.ok(), JSON.stringify(d)); + assert.equal(d.render_error, null); + if (!d.rendering) return d; + await page.waitForTimeout(100); + } + throw Error('worker timeout'); + } + await open(); + await page.locator('#f-title').fill(''); + assert(await page.getByRole('button', { name: 'Submit', exact: true }).isDisabled()); + await page.locator('#f-title').fill(layout.title); + await page.getByRole('button', { name: 'Save draft', exact: true }).click(); + await page.getByText('Saved', { exact: true }).waitFor(); + const saved = await (await context.request.get(base + '/api/docs/' + id)).json(); + assert.equal(saved.org_code, 'BROWSER11'); + assert.equal(saved.layout.imprints.find((i) => i.party === 'Manager').min_w, 50); + assert.equal(saved.layout.imprints.find((i) => i.party === 'Partner').min_h, 25); + await capture('edit'); + await Promise.all([page.waitForResponse((r) => r.url().endsWith('/submit') && r.request().method() === 'POST'), page.getByRole('button', { name: 'Submit', exact: true }).click()]); + await ready(); + await open(); + await capture('proof'); + + await identity(finalSigner, 'management'); + assert.equal((await context.request.get(base + `/api/docs/${id}`)).status(), 404); + await identity('manager', 'management'); + await open(); + let placement = page.locator('.placement'); + await placement.waitFor(); + let coords = await page.locator('area[data-placement]').getAttribute('data-coords'); + await placement.focus(); + await placement.press('Shift+ArrowLeft'); + assert.notEqual(await page.locator('area[data-placement]').getAttribute('data-coords'), coords); + coords = await page.locator('area[data-placement]').getAttribute('data-coords'); + await placement.press('ArrowRight'); + assert.notEqual(await page.locator('area[data-placement]').getAttribute('data-coords'), coords); + const grip = await page.locator('.placement .grip').boundingBox(); + await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2); + await page.mouse.down(); + await page.mouse.move(grip.x - 40, grip.y - 15, { steps: 5 }); + await page.mouse.up(); + const chosen = JSON.parse(await page.locator('area[data-placement]').evaluate((a) => JSON.stringify(a.dataset.coords.split(',').map(Number)))); + assert(chosen[0] >= 120 && chosen[1] >= 550 && chosen[2] <= 500 && chosen[3] <= 700); + assert(chosen[2] - chosen[0] >= 50 && chosen[3] - chosen[1] >= 20); + await signOff(); + await ready(); + await open(); + await capture('stamped'); + await identity('auditor', 'management'); + await open(); + assert.equal(await page.locator('.placement').count(), 0, 'check-only party needs no placement'); + await signOff(); + await identity(finalSigner, 'management'); + await open(); + await page.getByRole('heading', { name: 'Enrol your signature', exact: true }).waitFor(); + await page.locator('input[type=file]').setInputFiles(new URL('fixtures/sig.png', import.meta.url).pathname); + await page.getByRole('button', { name: 'Enrol signature', exact: true }).click(); + await page.locator('.placement').waitFor({ timeout: 15000 }); + await page.locator('textarea').fill('Browser final sign-off'); + await signOff(); + const released = await ready(); + assert.equal(released.status, 'RELEASED'); + assert.equal(released.decisions.length, 3); + assert(released.events.some((e) => e.action === 'RELEASED')); + await open(); + await page.getByRole('button', { name: 'Open print copy (PDF)', exact: true }).waitFor(); + await page.getByRole('heading', { name: 'Event log', exact: true }).waitFor(); + await capture('final'); + await page.locator('.page').nth(2).screenshot({ path: output + '/audit.png' }); + assert.equal((await context.request.get(base + `/api/docs/${id}/file/stamped`)).status(), 404); + assert.deepEqual(errors, []); + console.log('signing flow: edit/save, two-page proof, constrained keyboard/pointer placement, check-only, enrolment, final release and event log passed; id=' + id); +} catch (error) { + console.error('Browser errors:', errors); + if (page) { + console.error(await page.locator('#view').innerText()); + await page.screenshot({ path: output + '/failure.png', fullPage: true }); + } + throw error; +} finally { + await browser.close(); +}
diff --git a/todo.txt b/todo.txt @@ -7,3 +7,6 @@ x 2026-09-19 Facsimile overlay at sign-off, release in the worker with the full x 2026-09-19 Template and series lifecycle: retire, unlink, delete +api +client +schema +test status:completed id:7 blockedby:4 commit:833cb63,84cbc5f,1fc24fb spec:docs/REBUILD.md note:.scratch/rebuild/issues/07-template-series-lifecycle.md completed:2026-09-19 x 2026-09-19 Clip circular seals +render +test status:completed id:8 blockedby:3 spec:docs/REBUILD.md note:.scratch/rebuild/issues/08-clip-circular-seals.md commit:c7b2ef8 completed:2026-09-19 x 2026-09-19 Docs, invariants and acceptance sweep +docs +test +ops status:completed id:9 blockedby:3,6,7,8 spec:docs/REBUILD.md note:.scratch/rebuild/issues/09-docs-and-acceptance.md completed:2026-09-19 commit:c0b1262 +2026-11-10 Freeze PIM and DAM inputs at submit and derive stamped copy from proof +api +worker +render +schema +test status:ready-for-agent id:12 blockedby:11 spec:.scratch/roadmap/spec.md +2026-11-10 Make identity fail closed without blocking isolated feature tests +api +pim +test +ops status:ready-for-agent id:13 @before-production spec:.scratch/roadmap/spec.md +2026-11-10 Verify forwarded-identity boundary, DAM policy and native Alpine deployment +ops +dam +test status:needs-info id:14 blockedby:10,11,12,13 @before-production @owner-question spec:.scratch/roadmap/spec.md
: asapien/signet