commit 64e43d2265b96fad8e1bfaa8a9f1c21d860c6e36
parent 9876b79a6404702b192ba6a862dcc7d0cfd36ba6
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 19 Nov 2026 23:06:51 +0530
parent 9876b79a6404702b192ba6a862dcc7d0cfd36ba6
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 19 Nov 2026 23:06:51 +0530
Integrate verified signing, bounded transport, and detached timestamps Checkpoint immutable signature collections, bounded upload/parser retention, PDF writer allocation handling, API failure logging, and representative A5 regressions alongside optional libcurl/libcrypto RFC3161 evidence. Disposable Alpine warning-clean builds and full E2E passed; product/test/config hashes match the tested r5 checkpoint. Timestamp failures never gate release; four attempts stop within one release-anchored hour. Native/aggregate resource acceptance, ticket 20 child-buffering overlap, live TSA and browser acceptance remain open. This commit authorizes no deployment or preview upgrade.
98 files changed, 7504 insertions(+), 436 deletions(-)
A
|
102
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
146
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
100
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
150
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
100
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
136
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
112
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
148
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
220
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
100
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
100
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
75
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
77
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
124
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
149
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
258
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
91
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
158
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
M
|
75
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
M
|
570
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
A
|
152
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
98
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
141
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
231
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
149
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
113
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
332
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
84
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
101
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
101
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
154
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
277
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
249
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
84
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
A
|
92
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
diff --git a/.scratch/a5-workload.md b/.scratch/a5-workload.md @@ -0,0 +1,102 @@ +# Ticket20: representative A5 workload (2026-11-18) + +The owner says most documents will resemble those under +`~/Projects/salaryprocess/out/a5/`. That is workload evidence, not permission to +lower admitted limits or waive `.scratch/parser-window.md` / +`.scratch/parser-coordination.md` counterexamples. No product source changed. + +## Read-only structural inventory + +Existing host Poppler utilities inspected32 local PDFs without extracting text +or copying real files into the repository, container or evidence archives: + +-3913–4210 bytes each;131337 bytes total. +-All one page,420×595 points (A5), rotation0, PDF1.7. +-No encryption, forms, JavaScript or raster image objects. +-Helvetica and Helvetica-Bold, Type1 Custom encoding, unembedded. + +Reports and fixtures contain no employee names, pay amounts or other real +payroll content. No source file was modified. Structural similarity is not +proof that arbitrary PDFs/fonts or future scanned inputs have the same cost. + +## Retained synthetic probe + +`test/resource-a5.c` generates a4108-byte, one-page420×595-point PDF using the +existing native writer: base14 unembedded Helvetica,29 synthetic tabular rows, +no source images or real data. It intentionally does NOT reproduce the exact +producer/font-pair/encoding/bytes of the private inputs. It is a comparable +small text-only workload, not a visual replica or PDF parser compatibility +certificate for every real file. + +`test/resource-a5-probe.sh` is opt-in, destructive disposable-stack only: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes sh /src/test/resource-a5-probe.sh +``` + +Run after normal dev-stack initialization, never on preserved/shared services. +The script refuses without explicit opt-in. It compiles the generator against +current native writer source, creates only synthetic organisation/document +records, and sequentially creates/submits/signs/releases32 documents. It adds a +small PIM text imprint using the ordinary DejaVuSans font, a fixture seal, and +the seeded manager's synthetic facsimile. This includes actual PDF overlay and +release/audit work, not just copying32 small source files. + +For every document it checks exact uploaded/downloaded source SHA256, one-page +A5 proof, seal presence, released status/event, final SHA256, qpdf validity, +two-page final (one A5 body plus audit), all29 source rows, the PIM text, +exactly two final image objects (seal/facsimile), and audit SIGNOFF text. +It does not claim rasterized edit/proof visual acceptance or exact image bytes; +those remain covered separately by existing image/render/fidelity contracts. + +The RSS sampler includes signet/signetd/lighttpd UID cohorts, including kcgi +helpers and external tools. It excludes root test clients/compiler/sampler, +PostgreSQL and Redis; shared DB/cache service allocation remains a native gate. +Polling is1ms plus non-atomic /proc scan time, NOT certified instantaneous peak. +The batch is sequential, not concurrent users, burst admission or a throughput +benchmark. Synthetic records remain only inside the owned disposable stack; +private temporary files/sampler are cleaned on exit. + +## Results + +Baseline image `signet-logging-final-r2`, new unpublished disposable container +`signet-a5-resource-20261118`, no host ports. Product binaries/47 product inputs +are unchanged. Only generator/probe/sampler test sources were copied in. + +-Initial exploratory4438-byte/32-row fixture:33460KiB. It was reduced to29 rows + to match the observed4KiB profile, not to change product capacity. +-Final4108-byte fixture: sampled33424KiB. +-Full normal `test/e2e.sh` after the representative batch ends **all passed**. +-Warmed repeat after full E2E:33952KiB (34766848 bytes). +-Final strengthened assertions (all rows and seal/facsimile counts):33528KiB + (34332672 bytes), all32 releases verified. + +The final result is `within_for_representative_fixture`, NOT whole-runtime +acceptance. The actual admitted-input failure63112KiB and rejected gate's +warm child-buffering failures59136/59296KiB remain unresolved. No maximum +capacity/admission/worker concurrency was reduced. No new dependency, build +framework, browser run, commit/publication or preview upgrade. + +## Evidence and cleanup + +Private source/evidence directory: +`~/.local/var/signet-work/a5-resource-20261118/`. +Logs include initial, final, warm, strengthened and full E2E runs. Initial setup +attempt ran before web startup and failed connection; it is not a resource result. +Host sh syntax, actual Alpine warning-clean native compilation, opt-in refusal +and `git diff --check` pass. Source hashes match copied test sources; all47 +product hashes match the existing final22 manifest on host and tested image. +Owned fixture checks show normal pools, empty queues, no lock holders/stopped +processes/preload/temporary resource directories; container stopped/retained +exit0. No preserved services were changed. These source/evidence archives are +not runtime user-data backups. + +## Consequence for next work + +The expected small text-based documents have substantial observed headroom in +this sequential fixture. Keep this test as the normal-workload baseline while +continuing20's adversarial child-buffering/metadata/catalogue/history/native +work. Do not add an admission framework merely because a large artificial +fixture fails, but do not turn typical-case samples into an unsupported global +60MB promise either. Any supported-input/production-resource policy change is +an owner decision, not an inference from this folder.
diff --git a/.scratch/api-logging.md b/.scratch/api-logging.md @@ -0,0 +1,146 @@ +# API failure logging and development capture — ticket22 (2026-11-16) + +**Repaired and verified source-only.** Owner priority is22 →20 →remaining work. +Authoritative source remains `/tmp/signet-roadmap-20261112/integration`, branch +`feat/feature-first-roadmap`, HEAD9876b79 plus uncommitted integrated changes. +Original checkout, preserved previews and production are unchanged. + +## Reproduced gaps + +Disposable `signet-logging-red`, from the preceding request-retention image: +real400 responses from `/api/docs` and `/pim-api/attrs`, and a404 through a +manually logged dispatch branch, produced no corresponding container output. +Shared `send_err()` never logged; kfcgi's default daemon mode disconnected worker +stderr. The first native LOCAL0 regression failed on the missing docs400 record. +Raw `PQerrorMessage()` and Redis error replies also allowed backend text/DETAIL +(which can repeat private parameters) into application diagnostics. + +## Retained implementation + +- Existing callers still use `send_err()`. A C99 source-site macro invokes the + shared `send_err_at()` with `__func__`/`__LINE__`; HTTP response bodies/statuses + remain unchanged. It emits one request summary before building the response. + Redundant manual dispatch log calls are removed, including auth/not-found. +- API main loops lend their loaded configuration through `r.arg` after parsing; + the logger uses the same configurable identity-header reader/validation as + dispatch, also on pre-dispatch allocation errors. These unmapped + `khttp_fcgi_init()` calls register no user argument/free callback; inspection + of kcgi0.13.4 confirms the borrowed request pointer is not freed by request + destruction. Invalid/missing identity + becomes `anonymous`, not the original header contents. +- `log_request()` emits method, normalized route, validated actor, HTTP status, + and source `site=function:line`. Known route words are retained, UUIDs become + `:id`, all other components become `:other`; query data is omitted and depth + is bounded. The source site identifies the exact branch without logging its + possibly private error message. Use the matching source/build when resolving + line numbers. Method/site are code-owned, not request strings. +- LOCAL0.warning carries4xx; LOCAL0.err carries5xx. stderr includes program and + PID, matching syslog identity/PID for correlation. Successes are not logged. + Low-level diagnostics use one bounded512-byte formatted message in both sinks. +- `db.c` logs only operation and SQLSTATE, not SQL/parameters/server message, + DETAIL, CONTEXT or connection error text. Redis connection/mirror/resync + diagnostics identify the failed operation without copying reply text. +- Both APIs report configuration/init/parse failures safely. Before a parsed + request exists, these are process diagnostics, not fabricated actor/HTTP data. +- Dev startup uses documented `kfcgi -d` in background: the shell still owns the + foreground supervisors, their stderr remains connected, readiness is checked, + and shutdown stops them. Identity/PIM test restarts preserve that mode and + route output to PID1's stderr; they wait for supervisors/sockets appropriately. + Production OpenRC configuration is not changed. + +Example stderr (identities below are synthetic): + +``` +signet-api[123]: request method=POST route=/docs actor=asha status=400 site=h_doc_create:402 +pim-api[456]: request method=POST route=/attrs actor=admin status=500 site=h_upsert:149 +pim-api[456]: database query failed (SQLSTATE P0001) +``` + +Sites in this illustration are explanatory, not a promise of fixed line numbers. +No bodies, labels, resolved PIM attributes, raw URLs, query strings, cookies, +authorization tokens, groups or signature data enter the request summary. +Validated actor names intentionally remain visible. Header trust is still a +production boundary requiring ticket14 acceptance. + +## Runnable checks + +On an explicitly disposable dev container: + +``` +SIGNET_LOGGING_TEST_DISPOSABLE=yes sh /src/test/e2e.sh logging-contract +``` + +For the actual container-capture assertion, run where the existing Podman CLI +works (on this Mac, inside `podman machine ssh` with the mounted project path): + +``` +SIGNET_LOGGING_TEST_DISPOSABLE=yes sh test/logging-dev.sh disposable-container +``` + +The host-side check invokes real API requests and reads `podman logs`, rather +than trusting that writing stderr implies capture. It checks only newly appended +records, exact per-component summary counts, and private-marker/success absence. + +`test/logging-contract.sh` exercises: +- Both APIs' validation400, missing/invalid identity401, CSRF/role403, Signet + unknown/file404, both APIs' injected database500, and PIM Redis503. +- A temporary existing-BusyBox syslog receiver selecting only LOCAL0.warning + and above. Other facilities and LOCAL0.info markers must stay out. The test + refuses to replace an existing `/dev/log`, stops its receiver and removes its + own socket. Final requests prove stderr still works with no receiver. +- Private sentinel values in bodies/PIM values, raw paths/queries, cookies, + Authorization, invalid identity, config paths and backend message/DETAIL. +- Native `test/log-request.c`: control characters, invalid actors,4096-byte path, + query/UUID redaction, bounded output and success silence. +- Both APIs' missing-configuration diagnostics without leaking its path. + +The full E2E includes the native logging check. The existing snapshot/render +failure tests formerly depended on leaking PostgreSQL message text; they now +inject distinct SQLSTATE P2210/P2211/P2212 and retain all transaction, cached +proof, queue, hash and replay assertions. This is not a weakened failure test. + +## Verified final checkpoint + +Image/container `signet-logging-final-r2`, no host port or implicit preview. +Clean build/install has no compiler/make warnings. Full E2E ends `all passed`; +standalone render/hang/retry/replay/DB contracts pass. Real `podman logs` +assertions pass both after the full suite's API-pool replacements and after a +full graceful container restart. Each run checks13 representative HTTP errors; +startup/low-level diagnostics are additional, not duplicate request summaries. +All91 source/build/UI/schema/config/vendor/test files hash-match the final image; +installed API/PIM/worker binaries match their build outputs. Eight changed shell +scripts each pass `sh -n`; runtime checks cover Alpine scripts and the host +Podman-capture wrapper. Fixtures intentionally use Alpine/Linux facilities, +not a cross-platform runtime promise. Modified portable +C also passes the Mac syntax/warning check; `git diff --check` passes. + +All four owned logging stacks were checked for zero logging SQL fixtures/saved +Redis keys, restored registry shape and no temporary syslog/socket, then stopped +with exit0. Preserved18087/18090 return200. Preserved8080 is still the old +`signet-ticket11-verify` (started2026-11-12, PID1 lighttpd); both host and internal +HTTP checks timed out. No restart/repair was attempted there. Do not claim that +stack healthy or infer a new cause from this logging work. + +Private backup: +`/Users/saikrupa/.local/var/signet-feature-backups/api-logging-20261116T170748Z`. +Logs `/tmp/signet-logging-{red,green,contract-green,final-tests,final-retest,final-r2}.log`. +The first full test run correctly failed its old raw-server-message assertion; +that historical failure is retained alongside the successful updated contracts. +No Python, new dependency, persistent logging service, schema/config migration, +commit, push, original-checkout edit, shared-service change or deployment. + +## Scope and remaining gates + +This verifies errors emitted by the parsed APIs and generic startup/parse +failure diagnostics. Rejections generated before API dispatch by lighttpd, +kcgi or a proxy are not fabricated as API responses. Client disconnects or +failures after a200 stream starts are not turned into retrospective HTTP500s. +Do not claim all web/proxy/server/backend diagnostics are sanitized by this work. +PostgreSQL's own protected server log is separately administered. + +Persistent native LOCAL0 capture, log permissions/rotation/retention, disk +pressure and deployed OpenRC/proxy behavior still require owner-approved +native acceptance (ticket14). Production needs its existing system logger; +application stderr cannot substitute for verified persistent storage. No per-app +daemon/rate limiter was added. Ticket20 resource/cardinality/overlap/native gates +remain OPEN and are next; no production RSS or logging-delivery certificate.
diff --git a/.scratch/bounded-parsers.md b/.scratch/bounded-parsers.md @@ -0,0 +1,100 @@ +# Dense parser admission — follow-up23 of20 (2026-11-15) + +## Verified local repair, not a native certificate + +Two900000-byte URL-encoded POSTs to a nonexistent route reached122884KiB +aggregate application RSS; two text/plain requests reached92252KiB. They all +returned404: handler validation/route rejection is too late. An earlier30000-byte +URL-encoded control peaked27876KiB, and a1004507-byte multipart control36920KiB. +Idle residency returned to about25MiB: the dominant issue is transient per-field +allocation, not retained upload files. kcgi0.13.4 sends each parsed field to its +parent, which reconstructs a kpair and strings; validators do not discard these +allocations. No upstream/vendor file is modified. + +Evidence: `/tmp/signet-parser-{red,small,text,multipart,nested}.log` and +`/tmp/signet-parser-contract-red.log` (HTTP404 expected413 at16385 bytes). +Experiments/signals affect only owned disposable stacks, not preserved18087 or +other shared/production services. Worktree `/tmp/signet-roadmap-20261112/parsers`, +`fix/bounded-parsers`, base9876b79 plus the complete uncommitted integration. + +## Minimal fix + +Both lighttpd configs match every API/PIM FastCGI prefix, including unknown or +normalised suffixes. Before kcgi runs: + +- Non-multipart request bodies: **16384 bytes (16KiB)** maximum. +- `multipart/form-data; ...`: existing **1100KiB** maximum, case-insensitive. +- DAM/WebDAV transport remains34000KiB; no writer or organisation ACL is added. + +This explicitly changes transport compatibility for large URL-encoded/plain/ +unknown bodies. Send large logical fields using multipart. It does NOT lower +1MiB JSON/PNG field limits or32MiB complete PDF capacity; frontend FormData and +PDF application chunks already use the supported encoding. The former large +URL-encoded snapshot test now sends the exact same JSON bytes via multipart; +exact-limit acceptance and one-byte-over API400 are retained. Small forms and +empty POSTs still work. No schema/API-role/signing/rendering changes or runtime +dependencies are introduced. + +The admission decision must be retained at the actual backend web server. +Socket isolation/proxy overwrite/native config are still release gates. This is +not a claim that request-byte limits bound every parser/JSON/SQL/catalog/codec +allocation, or that multipart alone certifies mixed rendering below60MB. + +## Tests and final source + +Final candidate `signet-parser-final-r2`, container +`7dbc0b55d5246e89ba816c25ca645235c9a11c8ab6eae59c25dfbb98709cad85`, +loopback18103 during verification. Logs `/tmp/signet-parser-final-{build,e2e,render,rss,upload-rss}.log`. + +- Clean native build, no compiler warnings; E2E ends **all passed**, full renderer + contracts/hang/recovery/replay pass. +- `test/parser-contract.sh` covers exact16384/16385 dense body boundaries, + URL-encoded/plain/unknown content types, spoofed multipart-prefix rejection, + encoded/unknown API and PIM paths, unknown-length chunked transfer, ambiguous + duplicate Content-Type rejection, case-insensitive real multipart admission, + and the retained1100KiB multipart cap. +- Opt-in `test/resource-parser-probe.sh` runs two API workers plus one PIM worker + concurrently. Large dense bodies are rejected413; exact16KiB dense bodies are + admitted to the unknown route. A1120092-byte nested multipart contains35000 + very short parts inheriting one outer name, plus1000 query and1000 cookie + pairs per request. Baseline23848KiB, sampled peak **50052KiB (51253248bytes)**. + Includes signet/signetd/lighttpd UID cohorts and kcgi helpers; excludes root + clients/sampler/PostgreSQL/Redis. Sample interval is1ms sleep PLUS /proc scan, + not an absolute atomic peak certificate. Probe fails for zero/exceeded samples. +- Original two32MiB upload probe still completes and independently verifies both + source hashes, near-cap ignored fields and raw/HTTP-chunked oversized request + rejection: sampled peak **28964KiB**. Existing1MiB metadata/signature contracts + still pass. Whole file capacity is preserved. +- Real browser exact32MiB valid two-page PDF/hash/progress/conflict/delete and + full edit/proof/placement/check-only/enrolment/release/event signing flow pass: + `/tmp/signet-parser-{browser,signing-browser}{.log,/}`. Standalone real client + helper tests pass too. External dev-only Playwright reused read-only from + `/private/tmp/minci-browser-check/node_modules/playwright-core/index.mjs`; + previous temporary module path had disappeared. No package install/runtime + dependency was added. +- Test RSS helper now emits readiness only after installing signal handlers AND + its first scan. New probe waits for it, avoiding a false startup SIGTERM/143 + when immediate413 responses finish before the sampler starts. One-shot output + remains unchanged. Diagnostic prototypes live outside product source in + `/tmp/signet-upload-investigation/`; no debug production instrumentation. + +Product and test source SHA256 matches the final image exactly: +`/tmp/signet-parser-{host,image}.sha256`. Source integration is selective and +uncommitted; private0700 backup (files0600) +`/Users/saikrupa/.local/var/signet-feature-backups/bounded-parsers-20261114T191422Z` +retains pre/post integration source, patch/status and synthetic test/image/ +browser evidence. It is not a runtime user-data backup. + +## Remaining work + +Tracker23 is the verified parser-density slice. Parent20 remains OPEN for +metadata/catalog amplification, aggregate image/font/render and native/mixed/ +coexistence certification. PDF writer allocation-failure21 and actual failure +logging/capture22 remain open. Native target/workload/DAM/proxy/namespace and +coordinated rollback gates remain; no production readiness is implied. + +No preserved-preview upgrade, commit or push. Old18087 PIM Resync still uses +FLUSHDB and must not be invoked. Any later installation must coordinate the web +caps with the previously integrated chunk API/browser/migration003; no old API +rollback over incomplete uploads. Source/test evidence backups are separate +from actual runtime user DB/files/queue/config backups.
diff --git a/.scratch/bounded-uploads.md b/.scratch/bounded-uploads.md @@ -0,0 +1,150 @@ +# Aggregate upload buffering — tracker20 progress (2026-11-14) + +**Subsequent parser repair (23):** the current API/PIM pre-parser cap is16KiB +for non-multipart bodies; multipart/form-data retains1100KiB. Large logical +fields must use multipart. This note's earlier uniform-cap measurements remain +historical evidence; see `.scratch/bounded-parsers.md` for the dense-field +counterexample and final regression/resource results. + +## Scope and state + +The measured whole-body PDF-upload counterexample is repaired and dev-verified. +Tracker20 remains OPEN: aggregate image/font/render/parser amplification and +native/representative/coexistence acceptance are not certified. No production +or preserved18087 installation is authorised/implied. Source integration is +uncommitted; original dirty checkout, :8080, :18087, signature preview and PHP +service are not altered. Metadata18 and PIM19 remain source-only too; never use +old PIM Resync on preserved18087. + +Worktree: `/tmp/signet-roadmap-20261112/uploads`, `fix/bounded-uploads`, base9876b79 +with the complete uncommitted integration overlay. No third-party code was +changed. Matching Alpine kcgi0.13.4 source confirms complete FastCGI-body buffers +and reconstructed parent fields; its public options do not provide streaming +uploads. Source archive SHA512: +`53acccc5ad59958c359f1c46a5e08a66926d06f6adb9096226a197ed7334c556de9a4af8e0c292090884747cc42762ef1d810e2824daaa0041ba5568a153aea9`. + +## Retained policy, changed transport + +- PDFs still accept up to **33,554,432 bytes (32 MiB)**. The browser uses256KiB + application-level chunks, not HTTP Transfer-Encoding as a streaming workaround. +- lighttpd caps every `/api` and `/pim-api` FastCGI prefix at1100KiB **before** + kcgi parses a body, including unknown suffixes and normalised/encoded paths. + Native configuration must retain this cap and backend isolation. DAM/WebDAV's + existing34000KiB cap is unchanged; no organisation ACL/writer policy is added. +- Existing small multipart PDF uploads and templates still work. A large legacy + single multipart body now returns413; non-browser clients must adopt chunks. + This is an explicit transport change, not a silent reduction of file capacity. + Multipart JSON/signature fields at the existing1MiB limit still pass; encoded + request overhead also counts toward the1100KiB transport cap. +- `POST /docs` accepts `total_size` and the first PDF chunk, responds201 with + `id`, `upload_offset`, `upload_total`. First bytes retain `%PDF-` validation. + `POST /docs/:id/upload` accepts `offset` and `file`, responds200 with the + acknowledged offset/total. PostgreSQL builds the new JSON acknowledgements; + duplicate chunks do not perform another counter update. No new document status or independent upload + session/cleanup service is introduced. +- Additive migration003 stores nullable `source_total`/`source_received`. + NULL/NULL preserves every legacy/template source; matching counters mean + complete. A partial upload is an ordinary private DRAFT. It cannot be edited, + submitted, made into a template or downloaded (including by admin). +- Current drafter role plus exact creator ownership and a PostgreSQL row lock + guard chunks. Acknowledged prefixes cannot be replaced: retries compare actual + bytes. Out-of-order/conflicting bodies fail409. Completed sources cannot be + overwritten. File/counter ordering is file fsync, final rename when complete, + directory fsync, SQL update/COMMIT. Unknown commit outcomes retain files. + A retry reconciles a final filename with an older SQL counter under the same + row lock; publication alone never grants download/readiness. +- Browser disables duplicate creation and shows native accessible progress. + Only identified chunks get one transient retry; creation is not blindly + retried. Failure navigates to a safe incomplete-draft view; deletion removes + the partial file. UI restart/resume is intentionally not added: discard and + upload again. Private signatures/organisation references/routing are unchanged. + +## Evidence + +Baseline repeated probe:18,572→85,804KiB held; a second run19,532→85,684KiB +held and **182,624KiB sampled transient aggregate peak**. Logs: +`/tmp/signet-upload-{baseline,transient-baseline,transient-samples}.log`. +The original stable held excess independently proves the budget failure; samples +are not an absolute instantaneous maximum. + +Protocol red: `/tmp/signet-upload-contract-red.log`, +`FAIL - bounded upload initial offset missing` against the unchanged PIM19 image. + +Latest clean product image/container `signet-upload-final-r3`, loopback18100, +container `d40b2794e49057019cbb9dd5acbef27144542a76e2b2215288b8be5c1000fd7e`. +All five owned PIM/upload investigation containers were subsequently stopped +gracefully and retained. Preserved18087 still responds200; no fixture is left +running as an implicit replacement preview. + +- Clean `-Wall -Wextra` build, full E2E ends **all passed**, renderer contracts + including hangs/recovery/replay pass. Logs `/tmp/signet-upload-final-r3-{build,e2e,render}.log`. +- Migration fixture preserves original fields/NULL source meaning, applies003 + twice, rejects invalid counter pairs/ranges in its own temporary database. +- HTTP contract covers roles/ownership, no partial source access/admin bypass, + save/template/submit gates, chunk limits, concurrent exact retries, discarded + uncommitted suffix, deferred COMMIT failure **after final rename**, private + incomplete state, recovery, exact assembled bytes, cancellation, small legacy + compatibility and encoded/unknown prefix pre-parser413 responses. +- Harder two-file probe accepts **two complete32MiB files**, hashes downloaded + source bytes independently, adds ignored fields bringing initial multipart + bodies near the1100KiB cap, and rejects both32MiB Content-Length and unknown- + length HTTP chunked legacy bodies before kcgi. Aggregate signet/signetd/ + lighttpd cohorts include kcgi helpers. Excludes root fixture/curl/sampler, + PostgreSQL and Redis (not an assertion about their shared-service footprint). + Baseline **24,180KiB**, held **26,388KiB**, sampled peak **29,660KiB** + (30,371,840 bytes). `/tmp/signet-upload-final-r3-rss.log` explicitly reports + `budget_result=within_for_fixture; native/resource gate remains OPEN`. + Nominal1ms sleep plus /proc scanning, not a certified1kHz atomic sample. +- `node test/upload-client.mjs`: real helper accepts exact32MiB in128 bounded + slices; over-limit rejected before creation, tail, exact transient retry, + no conflict/initial-creation retry and stalled progress checks pass. +- `test/upload-browser.mjs`: real Chrome, first chunk gated to inspect disabled + duplicate button/progress/private incomplete state; valid exact32MiB two-page + PDF uploaded and source hash verified; forced chunk conflict shows safe + incomplete view and deletion succeeds, no page errors. SHA256 + `bf5434eb60f750d2dc282330542d9e2f21eca5525a49fd6bc9d8e3cc38a0afb7`, + document `aff88622-7256-4631-b91e-9acc73154d27` (synthetic disposable only). + `/tmp/signet-upload-final-browser{.log,/}`; progress/complete/incomplete images reviewed. + Native qpdf check and pdfinfo confirm valid two-page33554432-byte PDF: + `/tmp/signet-upload-max-pdf-check.log`. +- Retained full browser signing flow passes edit/save, both-page proof, + keyboard/pointer placement, check-only, enrolment, final release and events. + `/tmp/signet-upload-final-signing-browser{.log,/}`, synthetic document + `12f35dec-9003-463c-8d3d-33ba32bb776c`. + +Tested product source (all native C/headers, UI, schema/migrations, Makefile and +configs) SHA256 matches the worktree exactly; manifests +`/tmp/signet-upload-product-{host,image}.sha256`. The stronger HTTP contract is +included in the final-r3 image/full E2E. Intermediate-r2 contract strengthening +also passed separately (`/tmp/signet-upload-strengthened-contract.log`); its +harder upload fixture peaked27,164KiB. Earlier evidence is retained, not an +absolute peak guarantee or a claim that different runs have identical residency. +Owned probe/commit triggers and holder activity were checked absent after tests. + +Private0700 backup: +`/Users/saikrupa/.local/var/signet-feature-backups/bounded-uploads-20261114T181856Z`. +Contains pre/post integration source, patch/status, exact source manifests and +synthetic test/browser/image evidence. No runtime user backup or preview upgrade +is implied. Skill-link loops were excluded from directory comparison, not changed; +tar retains symlinks without following them. Selective integration copies only +the24 documented changed/new paths; all prior signature/restart/metadata/PIM +changes remain present. No commit/push. + +## Remaining gates / rollout precautions + +Request-byte caps are NOT whole-parser heap bounds: field cardinality, yyjson/ +libpq expansion, PIM catalogs/replies, simultaneous image/font codecs, complex +PDF subprocesses and representative mixed workload still require accounting and +containment. No CPU/RSS/cgroup/native certification follows from this fixture. +Allocation-failure work21 and actual error logging/capture22 remain open. + +A future approved installation must coordinate migration003, API, browser and +both lighttpd configs. Stop writers/take verified coordinated DB/files/queue/ +config backups first. Do not roll back to an old API while incomplete uploads +exist: it ignores the new readiness guards. Complete or explicitly discard them +under the new API with owner approval, or reconcile a paired DB/files restore +with all newer activity. Never blindly restore a pre-activity backup. Retain +partial files/counters together in backups; interrupted initial creation can +leave an unreferenced private directory, not an automatically deletable record. +No automatic sweep, replacement API, production namespace/capacity decision or +native service reconfiguration is introduced.
diff --git a/.scratch/detached-timestamps.md b/.scratch/detached-timestamps.md @@ -0,0 +1,100 @@ +# Optional detached timestamps — source checkpoint 2026-11-19 + +## Scope and decision + +Owner approved existing generic Signet sign-offs/facsimiles plus optional +validated detached RFC3161 evidence for the unchanged released PDF, **not +PAdES B-T**, certificate-based PDF signing, personal-key custody or a payroll +workflow. Approved dependencies are **libcurl + OpenSSL libcrypto**; the owner +specifically chose the HTTPS library over launching curl. No production/native +installation, preserved-preview upgrade, commit, publication or deployment. +See `docs/adr/0003-detached-release-timestamps.md`, `docs/timestamps.md` and +research `.scratch/{pdf-signatures,india-pades-key-custody}.md`. + +## Implemented + +- `src/timestamp.{c,h}`: SHA-256 imprint, fresh 128-bit nonce, HTTPS-only libcurl, + no redirects/proxy, TLS peer/hostname checks, bounded response/timeouts; + OpenSSL verifies full DER, nonce/imprint/version, signer/chain/validity/EKU + against explicit TSA trust. CMS digest must be SHA-256/384/512; no SHA-1. +- `src/signet-timestamp.c`: short-lived system-cron runner, no HTTPS in render + worker, one database-wide session advisory lock, four durable attempt slots + consumed before I/O. Deadline is release +1h, approximate slots 0/5/20/55m; + missed slots have at least1m spacing, never a reset window. A newly acquired + lock waits1s too, covering a predecessor crashing before its final rate delay. + No document row is held over HTTPS; hash/revision/released state guard storage. +- Fresh schema/migration004/grants, Makefile/install wiring, disabled config and + cron example. Dependencies added only to the development Containerfile. +- API exposes separate server `signed_at`/`released_at` and validated + `timestamped_at`/status/attempts. Authorized full RFC3161-response download + uses `/api/docs/<id>/file/timestamp`, `application/timestamp-reply`, `.tsr`. + Missing evidence404, backend failure503; original PDF access is unchanged. +- UI labels times separately, offers explicit pending-status refresh and evidence + download; no hour-long polling, PDF rewriting or new document status. + +## Verification and evidence + +Private evidence/checkpoints: +`~/.local/var/signet-work/timestamp-implementation-20261119/`. +`before/` preserves the already-dirty pre-timestamp tree; do not confuse its +contents with Git HEAD or restore unrelated work away. + +Final owned image `signet-timestamp-r5` and disposable stack of the same name: +warning-clean full rebuild plus real `make install` in the container. A later +incremental header rebuild/staged DESTDIR install also passed and reproduced +the installed timestamp binary. **101 product/config/fixture/test/build-input +hashes** match the authoritative worktree (`sources.sha256`, `final-checks.log`). +libcurl8.14.1 / OpenSSL libcrypto3.5.8; linkage inspected. +Final image ID `5b7095868485a9318a7b3fc853ef7f9dd5bfb476e39b4b7546c4866bf1106426`; +base remains verified `0e7b09eb561705af9d5b20ebc116865977ec85e5c5364f9f17779382ea67ea14`. +All five owned timestamp stacks are now **stopped, exit0** (`stopped.log`); +private :18095 is no longer served. The three preserved stacks remain running +unchanged on their existing :8080/:18087/:18090 ports. `sh -n` passes for all +new/modified shell files and the private check script; `node --check www/app.js` +passes. Tests are POSIX-sh syntax using existing Alpine-specific facilities, +not a claim of cross-platform utility portability. + +`final-r5.log` ends full E2E **all passed**, then passes the32-document synthetic +A5 probe. Timestamp coverage includes valid SHA-256/384/512 evidence, wrong +nonce/imprint, damaged signature, expired/untrusted signer, untrusted HTTPS, +SHA-1 rejection, rejected/malformed/oversized/HTTP-error replies, HTTP refusal, +timeout, four attempts, actual SIGKILL/restart slot consumption, deadline expiry, +concurrent-runner exclusion, real disposable cron, preservation of old migration +fields/decisions/grants, all four status labels, revision/hash binding, +owner/party/admin download and unrelated-user denial, backend503, unchanged +final PDF/sign-off time, and another document releasing during a held TSA request. +The scheduler was drained before removing its fixture, with no live fixture +worker/cron/TSA, temporary TSA directory, migration database, held advisory lock, +DB holder or stamping queue job after final checks. + +- Timestamp/release fixture sampled **39,784KiB /40,738,816bytes** aggregate app + RSS; includes the actual short-lived timestamp worker and concurrent small + document release, excludes root test client/compiler/TSA, PostgreSQL and Redis. +- Subsequent synthetic32-document A5 batch sampled **33,660KiB /34,467,840bytes**, + source4108bytes,29 rows each, exact source/final hashes, seal/facsimile and audit. + Timestamp scheduler is off during this A5-only batch; these are separate + representative fixtures, **not** a worst-case simultaneous A5/TSA/native proof. +- Sampler is a non-atomic1ms Linux `/proc` scan. Ticket20's existing warm parser + overlap counterexamples and native/aggregate gates remain OPEN. + +Earlier logs are retained honestly: r1 had a deprecated OpenSSL store setter +warning, fixed with the3.4+ API/older-version fallback; `weak-digest-red.log` +reproduced that libcrypto accepted a SHA-1 CMS signature before the explicit +policy fix. Initial r3 E2E/trace failed a new test because API configuration uses +`SIGNET_CONF`, not a `-c` argument; only the test was corrected. The standalone +r3 fix, full r4, and final r5 passed. Do not report those earlier failures as passes. + +## Limits / next authorization + +No live TSA/provider trust has been configured or contacted; local synthetic +HTTPS verification is not provider or legal qualification. No online revocation +fetch/check, archival renewal or long-term-validation system is implemented. +The optional existing browser regression was **not run**: its old +`/tmp/signet-ticket10-browser/node_modules/playwright-core` directory has been +pruned and lacks `index.mjs`; no dependency reinstall/alternative automation was +introduced. JS syntax/source review and native/API checks are not browser UX +acceptance. Native/OpenRC, deployment trust/permissions/cron and aggregate memory +acceptance still require separate authorized work. Preserved previews, original +checkout, private A5 files, host clock/known_hosts and third-party/vendor code are +untouched. This timestamp checkpoint intentionally changes product files AFTER +the restored final22 parser baseline; it does not repair or supersede ticket20.
diff --git a/.scratch/image-memory.md b/.scratch/image-memory.md @@ -0,0 +1,136 @@ +# Writer memory reduction and unresolved mixed-load gate — ticket20 (2026-11-15) + +**Historical writer-only checkpoint: mixed probe failed60MB. Parent20 stays OPEN.** +Superseded for the retained-request fixture by `.scratch/request-retention.md`: +API field/cookie compaction plus large libpq-cache recycling now pass seven +final mixed samples (maximum57020KiB), unchanged pixels/qpdf/capacity. Other +resource overlaps/cardinality/native gates remain open. The failures below are +retained historical evidence, not the latest candidate's measured result. +Earlier source-only transport/parser work: `.scratch/bounded-uploads.md` and +`.scratch/bounded-parsers.md`. +The native writer reduction below is verified; it is not a whole-renderer or +whole-runtime memory certificate. Source-only, uncommitted integration work; +no original checkout, preserved preview, shared-service or production changes. + +## Verified native writer improvement + +`src/pdfw.c` now uses existing zlib streaming compression into the PDF with +16KiB output chunks and standard indirect stream lengths. PNG colour/alpha and +embedded font data no longer need a whole compressed output buffer next to the +decoded image/loaded font. PNGs without a source alpha channel decode directly +to RGB rather than expanding to RGBA first. RGBA still preserves every alpha +sample, with no separate alpha-plane allocation for an entirely opaque image. +No file/pixel limits, snapshot capacity, render geometry, font fitting, schema, +public interface or dependencies change. Transparency and JPEG passthrough remain. + +Retained native regression `sh test/image-memory.sh` creates an actual max4MP +(2048x2048) high-entropy RGB PNG and a valid DejaVuSans with2MiB trailing padding. +The font remains loaded while the image is embedded through the real writer API. +Linux `getrusage(RUSAGE_SELF)` reports native process peak RSS: + +- Unmodified ticket21 source: **32728KiB**, fails the fixture's24MiB ceiling. + `/tmp/signet-image-memory-red.log`. +- Repaired source: **16216KiB**, passes. Same result inside the final full E2E. + `/tmp/signet-image-memory-green.log` and final E2E log below. + +The24MiB ceiling is ONLY a reproducible Linux fixture regression assertion, +not a new product per-process policy or proof for every supported input. It +leaves headroom above the fixture's12MiB RGB +2.85MB font + codec/runtime costs +and catches the old image-sized output overlap. Native writer output is checked +by qpdf; decoded RGB and embedded TTF stream bytes exactly match their inputs; +Unicode text extracts correctly. `/dev/full` output failure is rejected. + +`test/image-contract.{c,sh}` also verifies exact decoded pixels/alpha for RGB, +gray, opaque RGBA, transparent RGBA and palette transparency, and that opaque +variants have no soft mask. Existing JPEG and alpha interpolation checks remain. +The native memory regression runs in full E2E and its `image-memory` mode. +The ticket21 fault sweep adapts to16 allocation positions after removing three +compressed-buffer allocations: transient/persistent failures and all targeted +cleanup cases pass. Codec-internal fault injection is still not established. + +## Actual mixed-load counterexample — still failing + +Retained opt-in **destructive disposable-only** probe: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes sh /src/test/resource-image-probe.sh +``` + +Never run it on a preserved/shared/production stack. It creates private synthetic +records/assets, temporarily stops/restarts ONLY the disposable worker and holds +TWO admitted HTTP document uploads at their INSERTs using an owned PG advisory +lock/trigger. Each body1120212 bytes has a tiny PDF file plus35000 nested ignored +MIME parts. They are admitted sequentially, retained concurrently, then the +worker renders a queued real document independently. This deliberately separates +retained parsed bodies + rendering from simultaneous parser startup. Cleanup +releases the owned holder, removes its trigger/function and temporary DAM assets, +and leaves synthetic records only inside the disposable stack. Proof image/font +bytes are checked independently after qpdf overlay. + +The pending document freezes12607295 PNG bytes +2854228 font bytes +757076 audit +font bytes = **16218599 bytes**, within the existing16MiB aggregate snapshot cap. +There are4194304 pixels, within the existing PNG cap. No over-policy input is +needed for this budget counterexample. + +Summed `/proc/*/status` VmRSS includes all signet/signetd/lighttpd UID processes, +kfcgi/kcgi helpers and external tools under those UIDs. Root curl/compiler/test/ +sampler, PostgreSQL and Redis are excluded. The helper scans at1ms sleep PLUS +scan time: sampled maxima are not absolute/atomic peak certificates. + +- Image-only initial baseline:53736KiB, within for that fixture; did not prove + mixed safety. The first fixture run had a test identity403 and a corrected + generator compiler warning before any valid budget conclusion. +- Initial simultaneous-body mixed baseline:68364KiB (old writer). +- Retained-body phased baseline (old writer):**66576KiB**, gate fails. + `/tmp/signet-image-budget-phased-red.log`. +- Early writer-only streaming prototypes still failed (65608KiB,68064KiB), + and one warm sample58580KiB barely fell below60MB. This was NOT accepted as + safety evidence. Subsequent phased samples62704/68904KiB still fail. +- Final exact tested candidate, after full E2E/browser work: held bodies35600KiB, + parser phase37788KiB, render phase **72240KiB (73973760 bytes)**. Proof RGB/TTF + byte checks pass; resource probe deliberately exits1 with `budget_result=exceeded`. + `/tmp/signet-image-memory-final-mixed.log`. No mixed-resource gate is completed. + +Existing qpdf facilities were checked before changing product orchestration. +Direct actual overlay of the fixture proof onto the two-page base under BusyBox +`time -v` uses **34028KiB** peak by itself; `--stream-data=preserve` still uses +33752KiB. It is NOT a proven repair, so no qpdf command option was changed. +`/tmp/signet-image-budget-qpdf-options.log`. This is a separate-process peak, +not an exact decomposition of the simultaneous cohort; further process/subphase +correlation, admission/containment and native acceptance remain necessary. + +## Final functional verification and safety + +Image/container **signet-image-memory-final**, temporary loopback18106; +image/container metadata in the private backup identifies the exact candidate. + +- Clean Alpine build (`make clean`, `make -j2`, `make install`), no warnings; + full `sh /src/test/e2e.sh` ends **all passed** (includes native memory/byte, + format, allocation, snapshot, signature, PIM, upload and parser regressions). + `/tmp/signet-image-memory-final-e2e.log`. +- Separate renderer/hang/retry/replay/DB contracts all pass: + `/tmp/signet-image-memory-final-render.log`. +- Existing Chrome signing flow passes using preinstalled read-only external + Playwright Core, no package install or new JS automation. Both-page edit, + proof, stamped and final screenshots plus audit reviewed: fitting, clipping, + alpha and JPEG placement match; facsimiles appear at the appropriate sign-offs. + `/tmp/signet-image-memory-browser{.log,/}`; synthetic document + `f959d7d2-d5ad-4573-b501-65e7f3c36100`. +- `sh -n` on all four added/modified shell scripts, manual POSIX review and + `git diff --check` pass; actual scripts executed with sh. No production runtime + or build dependency changes, no ABI/API/install/config change. +- Full native/UI/schema/config/vendor/test source and Makefile/Containerfile + SHA256 manifests exactly match the tested candidate: + `/tmp/signet-image-memory-{host,image}.sha256`. +- Owned trigger/holder backend counts are both0 after the mixed probe. All four + owned investigation containers stopped gracefully/retained; preserved18087 + still responds HTTP200. `/tmp/signet-image-memory-{cleanup,stopped}.log`. + +Latest native writer gains must NOT hide the final failing mixed probe. +Remaining20 includes qpdf/API overlap, other metadata/catalog/codec amplification, +resource containment and native representative/coexistence certification. Actual +logging22 and native/proxy/DAM/namespace/backup14 gates are unchanged. No commit, +push or installation on preserved18087; old PIM Resync there remains FLUSHDB. + +Private before/after source/evidence backup (not runtime user data): +`/Users/saikrupa/.local/var/signet-feature-backups/image-compression-20261115T014846Z`.
diff --git a/.scratch/india-pades-key-custody.md b/.scratch/india-pades-key-custody.md @@ -0,0 +1,112 @@ +# India, employee key custody and FreeTSA — research, 2026-11-18 + +Research only: no key generation, LDAP changes, service integration, document +uploads or product requirement changes. Complements `.scratch/pdf-signatures.md`. + +## Key custody recommendation + +PAdES uses CMS/X.509 certificate-based signatures, not OpenPGP/GPG signature +packets. Reusing a cryptographic algorithm does not make GPG keys/certification +or an OpenPGP signature directly interoperable with PAdES. An X.509 issuing and +trust process is needed for the proposed interoperable PDF signature design. + +LDAP can publish the employee's PUBLIC X.509 certificate using the standard +`userCertificate;binary` attribute (RFC4523 section4.1), plus nonsecret IDs or +key handles. LDAP ACLs/TLS and disk encryption do not by themselves make it an +employee-controlled private-key signing device: directory admins, backups and +server credentials may expose/use the key; if Signet can decrypt/use a key +without the employee, it can sign without them. Encrypted software key stores +exist but must not be conflated with hardware non-exportability or legal key +control requirements. Do not introduce private key blobs into LDAP as a +security shortcut. + +For an Indian employee DSC workflow, investigate a CCA-licensed CA-issued +certificate with the required token/key-storage policy, or a CCA-framework +remote eSign provider providing signer authentication/consent. HSM storage is +not sufficient on its own: identity verification, per-signature authorization, +key control, revocation/renewal and audit also matter. A single organisational +signing key has a different meaning than a personal employee signature. + +## India: format vs legal status + +PAdES is a PDF signature format, not an Indian CA licence or blanket legal +approval. The CCA guidance identifies licensed CAs for DSC issuance and a +rooted India PKI; eSign guidance describes licensed providers, signer consent, +e-KYC, certificate issuance and signatures under the IT Act. Merely generating +keys/self-issued certificates and producing a conforming PAdES-B-T file does +not establish compliance with that recognised DSC/eSign framework. + +No source reviewed here declares all PAdES-B-T documents accepted for every +Indian transaction or mandates PAdES-B-T for this payroll acknowledgement. +Use it as an interoperable engineering target with the appropriate licensed +DSC/eSign process if recognised Indian digital signatures are required. Check +specific accepting-system/document and employment-record requirements. Internal +self-issued signatures may provide integrity/evidence but must not be advertised +as equivalent to the regulated DSC route; admissibility/presumptions are not +settled by a format choice. This is technical research, not a legal opinion. + +## FreeTSA suitability + +The service advertises RFC3161 timestamps and publishes its own TSA/CA +certificates. Its first-party usage policy explicitly says: + +- Public endpoint: maximum ONE timestamp request/second/IP. +- Commercial use permitted without a separate commercial licence. +- Best effort, NO availability/uptime/response/restoration guarantee or SLA. +- Even dedicated instances are described as best effort without formal SLA. + +A timestamp binds a trusted time to a hash; it does not establish employee +identity/consent or upgrade a self-issued employee certificate to an Indian +licensed-CA DSC. For PAdES B-T the signature timestamp must be incorporated in +the required structure (normally a timestamp of the signature value), not just +an arbitrary whole-file `.tsr` stored alongside the PDF. + +Timestamp trust depends on certificate chain, policy, algorithms and verifier +trust configuration. Publishing a root certificate is not proof that ordinary +PDF viewers or Indian recipients trust it. No AATL/EUTL/India-PKI recognition +for FreeTSA was established in this research; do not claim it is absent from +all trust programs merely because these sources do not establish it. + +CCA's time-stamping guidance points subscribers to CA time-stamping services, +notes these services are mandated for CAs, and specifies NPLI time sourcing for +reliability. FreeTSA was not established as equivalent to that framework. +For production Indian regulated signatures, prefer a licensed CA/provider's +appropriate timestamp service and confirm recipient requirements; FreeTSA is a +reasonable RFC3161 interoperability/prototype candidate, not an unqualified +compliance/availability dependency. + +A production B-T requirement introduces a network dependency. Validate timestamp +responses and expected hash/nonce/policy/chain, retain evidence and historical +trust material, obey rate limits, and make unavailable timestamps retryable. +Never silently release a B-B signature labelled B-T. Do not send the real PDF +or private key to a TSA; RFC3161 uses a hash imprint. Hash-only submission still +reveals request timing/network metadata and may enable correlation of known +content; avoid claiming it reveals nothing. + +## Primary sources consulted + +- LDAP X.509 public certificate attribute: RFC4523 section4.1: + https://www.rfc-editor.org/rfc/rfc4523 +- Timestamp protocol, hash-only service and verification requirements: + https://www.rfc-editor.org/rfc/rfc3161 +- CCA DSC issuance and key-storage policy references: + https://cca.gov.in/digital_signature.html +- CCA India PKI explanation: + https://cca.gov.in/india_pki.html +- CCA eSign explanation (consent/e-KYC/licensed providers/HSM one-use keys): + https://cca.gov.in/eSign.html +- CCA licensed CA list (consulted, not reproduced as a frozen list): + https://cca.gov.in/licensed_ca.html +- CCA time-stamping guidance: + https://cca.gov.in/time_stamping_service.html +- FreeTSA service/protocol and certificates: + https://freetsa.org/index_en.php +- FreeTSA published usage/availability/commercial policy: + https://freetsa.org/freetsa.html + +These primary pages were retrieved this session; public copies are outside the +repository in `~/.local/var/signet-work/`. The normative current India CP and all +applicable legal/rule texts were NOT exhaustively reviewed. Before selecting a +provider, confirm current CCA policy, licence scope, certificate/key-storage +requirements, TSA policy and intended recipient validation. No signing component +was selected, installed, benchmarked or certified against Signet's60MB target.
diff --git a/.scratch/parser-coordination.md b/.scratch/parser-coordination.md @@ -0,0 +1,148 @@ +# Ticket20: parent admission gate rejected (2026-11-18) + +**No product repair retained. Ticket20 is OPEN.** Work remains in the durable +integration worktree named by `~/.local/var/signet-work/current-integration`. +All47 product inputs again match `parser-window-product.sha256` (final22). +Only diagnostic test changes and these notes survive this session. Do not +recover/install the rejected gate merely because its first fixture passed. + +## Reproduction and rejected candidate + +Baseline replay of `.scratch/parser-window.md` reached61812KiB (63295488 bytes), +with35001 held fields, resumed404, live qpdf and exact RGB/font bytes. The +restored baseline repeat reached63112KiB (64626688 bytes), again with every +content/admission assertion passing. This is still an actual red diagnostic. + +A candidate used a persistent `.workload.lock` inode in `data_dir`, shared +POSIX record locks for API parent parse/prune and exclusive locks before worker +jobs/DB transactions. Public kcgi control-fd readiness was checked with pselect +before taking admission, never holding it during idle FastCGI or handler SQL +waits. A two-byte turnstile prevented new readers bypassing a queued worker. +Private native regressions covered group-write mode despite umask077, shared +readers, exclusion, turnstile ordering, SIGKILL release, idle/contended SIGTERM, +parse-error cleanup and symlink refusal. Prune allocation failure kept admission +until the request was freed. No dependency/config/capacity/renderer change. + +The held-parent diagnostic was adapted to require an actual worker kernel lock +wait in `/proc/locks`, verify that rendering remained pending while the parser +was stopped, resume the parser, then REQUIRE observed qpdf and exact output. +This passed48868KiB on r2 and51224KiB on r3. The r3 matched preload control +passed55352KiB, original retained-upload fixture55600KiB, full E2E all passed. +These passes did NOT establish that admission began early enough. + +## Reverse order exposes the missing coverage + +The worker-first diagnostic starts the owned worker with a private PATH qpdf +wrapper, holding it immediately before real qpdf while it owns admission. It +then sends the SAME1120212-byte/35001-field PIM request. A test-only preload +pselect observer records that the ready API parent is retrying admission; +`/proc/locks` confirms the worker owns WRITE, and no parent parse-complete +marker exists yet. The fixture releases the wrapper to exec unchanged real +`/usr/bin/qpdf`, requires proof completion and live-qpdf sampling, resumes the +later completed PIM parse, requires404 and exact RGB/font bytes. No root test +helper is counted in app RSS; the worker's wrapper/helpers ARE counted. + +Both warm reverse samples FAIL:59136KiB (60555264 bytes), then59296KiB (60719104 +bytes). Optional per-process sampler output in the second run shows live qpdf +33816KiB, PIM child3368KiB, PIM parent2148KiB and worker2804KiB, along with +normal warm API/lighttpd/kcgi cohorts. This is not merely two unrelated peaks +added by hand, nor a green timeout/unobserved-qpdf result. A final reverse +replay after full container restart, also exercising the final wrapper-free +worker restoration, sampled58036KiB (59428864 bytes) and passed. That colder +sample does NOT invalidate the two warm failures or make this candidate safe. +See phase `final-cleanup-replay.log`. + +kcgi0.13.4 `child.c:kworker_fcgi_child()` reads the FastCGI body into its own +buffers BEFORE it notifies the control process of readiness. Its child then +transcribes fields over IPC and can block behind a parent that has not entered +parse. Polling `khttp_fcgi_getfd()` and delaying the parent cannot prevent those +child allocations. Inspect the preserved upstream child.c around1999–2273 and +fcgi.c around250–300/636–706; evidence paths are in `parser-window.md`. + +**Decision:** reject the parent-only gate. Its complete candidate, native tests +and build staging are preserved privately, but this session's product edits +and E2E additions were restored selectively from the pre-session archive. +All prior dirty work is preserved. No reset/checkout/commit or whole-tree diff +application was used. Native test files for the rejected gate were removed +from the live tree after being archived; production needs no new lock file. + +## Retained diagnostic interfaces + +Original modes are unchanged. Inside an explicitly owned disposable stack: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes SIGNET_RESOURCE_PARSE_WINDOW=yes \ + sh /src/test/resource-image-probe.sh +``` + +Still red on current baseline. The original retained-upload/default and matched +`preload` control remain available. + +Two candidate-specific modes require the rejected gate or an equivalent future +candidate; they are NOT expected to pass on the restored baseline: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes SIGNET_RESOURCE_PARSE_WINDOW=yes \ + SIGNET_RESOURCE_PARSE_EXCLUSION=yes sh /src/test/resource-image-probe.sh +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes SIGNET_RESOURCE_PARSE_WINDOW=worker-first \ + sh /src/test/resource-image-probe.sh +``` + +The first requires the actual kernel lock wait on `.workload.lock`; the second +requires the admission retry pselect observer and worker WRITE lock. Adapt these +checks deliberately if a future mechanism differs. Missing markers/timeout is +an invalid test, NEVER a budget pass. `SIGNET_RSS_DETAIL=yes` optionally emits +PID/name/RSS cohorts for new qpdf-phase maxima to stderr; ordinary/default +sampler output stays compatible. Tests remain Linux disposable-stack only. + +The worker-first wrapper never replaces `/usr/bin/qpdf`; its private PATH +wrapper and gate are removed on exit, the temporary PIM preload pool is restored, +and the owned worker is restarted without that PATH. Fixture flags are not +production configuration. + +## Next repair boundary and permissions + +A successful design must account for **already buffering kcgi children as well +as parent materialization**, in both request-first and worker-first order. Do +not lower admitted capacities, qpdf fidelity or concurrency merely to pass a +number. Parent-only locking plus another post-parse free is disproven here. +A web-server/transport admission solution or a narrowly scoped upstream kcgi +change needs further design. No third-party modification, replacement protocol +front end, dependency installation, native deployment or production service +change is authorized by this experiment. Ask before any required exception. +The existing public poll API is not a hook before child-body buffering. +Other20 catalogue/metadata/Redis/history/codecs/arbitrary-PDF/native gates remain +open regardless of this particular counterexample. + +## Evidence and verification + +Private phase directory (0700, private source/evidence): +`/Users/saikrupa/.local/var/signet-work/parser-repair-20261118/`. +`before/source.tar` plus status/diff preserve the starting tree; +`rejected-candidate.tar` preserves the gate and native tests; `build/` is its +private experimental build staging, NOT authoritative source. Rejected images +`signet-parser-repair-r2`/`-r3` are NOT previews and must not be installed. +Image r1 failed startup due private staging SQL file read permissions; r2 fixed +only image `/src` readability. Existing baseline image was reused for builds; +no package installation, host/VM clock or known_hosts change. + +Logs alongside the phase directory are `parser-repair-{red-20261118, +exclusion-red-20261118,build-r1,build-r2,build-r3,window-r2,window-r3, +control-r3,retained-r3,worker-first-r3,worker-first-detail-r3,e2e-r3, +restored-e2e,restored-red}.log`. The phase archive contains the copies as well. +Original candidate-specific red first failed because the baseline has no gate; +only the ordinary baseline diagnostic's `budget_result=exceeded` establishes RSS. + +Full E2E on the RESTORED baseline ends `all passed`; all47 current and baseline +image product hashes match the previous manifest. Shell syntax and diff checks +pass; sampler/preload compile cleanly under Alpine `-Wall -Wextra` during probes. +No product renderer/fitting change survives; no new browser/visual/native +acceptance is claimed. Candidate E2E pass is evidence about the rejected +experiment only, not a retained repair. + +Owned cleanup checks verify trigger/function/holder counts0, both queue lengths0, +normal API/PIM process counts, no stopped processes, no fixture directories or +PIM preload environment. All session-owned service stacks were then stopped and +retained, exit0; failed startup r1 already exited1. See phase cleanup/stopped logs. +No preserved preview/shared/production service was changed or restarted. No +commit/push/PR. Source/evidence archives are not runtime user-data backups.
diff --git a/.scratch/parser-window.md b/.scratch/parser-window.md @@ -0,0 +1,220 @@ +# Ticket20: unpruned request delivery overlaps qpdf (2026-11-17) + +**2026-11-18 follow-up:** parent parse/prune admission was experimentally +implemented, then REJECTED and selectively reverted. Request-first exclusion +passed, but reverse worker-first order still reached59136/59296KiB because kcgi +children buffer before parent readiness. Current47 product inputs still match +final22; baseline replay remains red63112KiB. Read `.scratch/parser-coordination.md` +before retrying a gate; it records both schedules and the private candidate. + +**New reproducible budget counterexample; NOT repaired. Ticket20 stays OPEN.** +Production source remains byte-identical to the final ticket22 checkpoint. +This slice adds only opt-in diagnostic instrumentation and sampler reporting. +No admission limit, role, render geometry, data format or signing behavior changed. + +## Source recovery first + +The old `/tmp/signet-roadmap-20261112/integration` lost `.git` and source files. +The authoritative worktree is now: +`/Users/saikrupa/.local/var/signet-work/integration-recovery-nQvIoiCL`. +Branch `feat/feature-first-roadmap`, HEAD9876b79 plus uncommitted work. + +Recovered final22 `after/source.tar` into a NEW durable directory, preserving the +old partial tree. All105 surviving product/doc files and61 tool files matched; +all91 runtime-input hashes and the complete Git status matched the saved final22 +checkpoint before new work. All19 surviving symlink targets and surviving-file +executable bits also match. Excluded clean tool metadata was recovered from the +same Git revision and compared with surviving files. Native `git worktree repair` +reconnected registration, without checkout/reset/commit. Durable pointer: +`~/.local/var/signet-work/current-integration`. Partial-source/registration +archives and recovery comparisons are in that parent. Do not reuse the old +incomplete `/tmp` tree or replace this source with an older feature worktree. + +## Replay setup from the host + +Use `podman machine ssh` for native VM-side Podman operations; the host CLI's +known_hosts error is not repaired. Create a NEW, unused, unpublished container +from existing image `signet-logging-final-r2` (no `-p`); stop on any setup error. +The old three measurement stacks remain stopped evidence, not candidate builds. +Wait for normal development initialization (the tested loop used six seconds). +Copy these THREE files from the durable worktree into its `/src/test/`: + +- `test/resource-image-probe.sh` +- `test/resource-rss.c` +- `test/resource-parse-gate.c` + +Use `podman cp` inside the VM; `/Users` is mounted there. Example for one file, +with `name` set to the newly created owned container and `root` read from the +durable pointer on the HOST: + +```sh +podman machine ssh "podman cp '$root/test/resource-parse-gate.c' '$name:/src/test/'" </dev/null +``` + +The `/dev/null` redirection matters when SSH is invoked from a shell heredoc: +otherwise it can consume later commands from the caller's stdin. The baseline +image's47 product inputs are unchanged in this diagnostic slice. Copying these +tests does NOT update product binaries; any future C repair needs a rebuild +from the canonical tree/private staging and a fresh candidate source manifest. + +## Tight loop + +Only inside that explicitly disposable Alpine development stack with these tests: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes SIGNET_RESOURCE_PARSE_WINDOW=yes \ + sh /src/test/resource-image-probe.sh +``` + +The test retains the existing4MP high-entropy PNG, padded loaded font and exact +proof RGB/font validation. It admits one1120212-byte multipart PIM request with +35001 parsed fields. There are NO retained document-upload requests, dense query +or cookies in the minimized case. Its eventual response is the expected404 for +an unknown route, not a pre-parser413 or forced input rejection. + +`test/resource-parse-gate.c` is a disposable LD_PRELOAD library, compiled only by +this opt-in mode, never linked/installed into the product. It calls the real +`khttp_fcgi_parse()`, publishes only PID/field count atomically in a private gate +directory and stops its own PIM parent before the application can prune fields. +The root fixture verifies that process is stopped before starting the worker, +keeps it stopped through proof completion, then resumes it and verifies404. +It holds the real library allocations without copying the request. This models +an otherwise permitted scheduling pause at that call boundary; it is NOT a +claim that ordinary traffic naturally holds that window this long, nor a +measurement of every earlier child-parser phase. + +The sampler's opt-in `--qpdf` additionally records maximum aggregate app RSS on +scans containing a live, nonzero-RSS qpdf process of a Signet cohort UID. Default +sampler/`--once` output stays compatible. Since the PIM parent is verified stopped +through the render, this establishes coexistence with its unpruned allocations, +not just separate peaks added by hand. Scans remain non-atomic and1ms plus scan +time; successful samples still cannot certify a universal/native ceiling. + +Matched preload control (same library/pool replacement but no large PIM request): + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes SIGNET_RESOURCE_PARSE_WINDOW=preload \ + sh /src/test/resource-image-probe.sh +``` + +Omit `SIGNET_RESOURCE_PARSE_WINDOW` for the ORIGINAL retained-upload fixture: +two densely populated admitted document uploads held at INSERTs after pruning. +That existing case was not replaced or waived. + +## Measurements + +| Scenario | Sampled app peak KiB | Bytes | Verdict | +| --- | ---: | ---: | --- | +| First exploratory window, two retained uploads plus query/cookies |63028|64540672|exceeded| +| Minimized window, no retained uploads/query/cookies |62716|64221184|exceeded| +| Fresh minimized repeat |62352|63848448|exceeded| +| Fresh preload-only control |53688|54976512|within for fixture| +| Original retained-upload fixture |56404|57757696|within for fixture| +| Final hardened probe, preload-only control after restart |54252|55554048|within for fixture| +| Final hardened probe, minimized window after restart |60992|62455808|exceeded| + +Every row validates exact decoded RGB and loaded font bytes. Window rows require +35001 fields held and an admitted404 after resume (first exploratory row36001). +The final hardened probe atomically publishes readiness and includes scoped +cleanup for an interrupted/stopped PIM process. Budget is strictly less than +60000000 bytes; exit1 with `budget_result=exceeded` is an actual diagnostic red, +not a build/HTTP/check failure. Root test clients, compiler, PostgreSQL and Redis +are excluded from app RSS; Signet/lighttpd UIDs and their helpers are included. + +The approximately6.6–8.5MiB contrast with matched preload controls supports actual +parsed request storage as the cause, not the tiny hook/library itself. Repeats also +separate this from one ordinary qpdf peak crossing the budget: both controls and +the existing retained fixture pass, while every measured unpruned window fails. +Neither controls nor these forced schedules certify other traffic or native +coexistence on the target1vCPU/1GB machine. + +## Why the earlier repair is insufficient + +`http_keep_fields()` correctly discards unnecessary fields immediately AFTER +`khttp_fcgi_parse()` returns. It cannot eliminate the library's earlier peak or +prevent a scheduler from pausing at that boundary. In kcgi0.13.4 `parent.c`, +`kpair_expand()` grows storage for every received field before mapping known +keys. Supplying a key registry alone does not skip unknown fields. The previous +retained-request/libpq repair is still valid; `.scratch/request-retention.md`. +This is a DIFFERENT live-memory window, not a reverted allocation repair. + +Next repair should address overlap before materialization, not add another +post-parse free or lower accepted capacities. A native coordination/admission +approach must be checked against kcgi's public polling API, already-buffering +child processes, idle waits, database/queue lock ordering, interruption/crash +cleanup, permissions and starvation. `khttp_fcgi_getfd()` permits polling only; +do not manipulate its control protocol. A lock held while an idle FastCGI call +waits forever would block useful worker progress. No such gate has been shipped +or claimed correct here; no third-party fork/filter was introduced. + +The diagnostic intentionally waits for proof completion while holding the +window. A real admission repair may instead block the worker: adapt the gate +handshake to verify that exclusion and release the parser safely, retaining the +same request/assets and RSS/content assertions. A timeout or an unobserved qpdf +phase is NOT a green result. Do not silently disable the window to obtain a pass. + +## Upstream source used for the diagnosis + +Selected surviving kcgi0.13.4 investigation sources/manuals are copied verbatim +into the private phase archive under `evidence/kcgi-0.13.4/`, with `SHA256`: +`parent.c`, `child.c`, `fcgi.c`, `kcgi.c`, `extern.h`, `kcgi.h`, `man/kfcgi.8` +and `man/khttp_fcgi_getfd.3`. Read `parent.c` around182/321 for field growth, +`fcgi.c` around636/642 for the poll-only control descriptor and parse entry, +and the getfd manual for supported readiness use. This is selected read-only +evidence, not a new vendored dependency, buildable checkout or claim that every +upstream file remains present. The old `/tmp` investigation cannot be relied on +for recovery (its previously referenced `man/kreq.3` is now absent). + +## Checks, safety and evidence + +- 47 non-test source/build/UI/schema/config/vendor inputs hash-match final22; + product binaries are unchanged. Three test files form this slice. +- Full E2E after the hardened window/cleanup ends `all passed`, including actual + logging contracts and pool replacement. Earlier full E2E plus standalone + parser probe also pass; parser-only sampled peak47612KiB is limited evidence. +- `sh -n` on the changed shell fixture, host portable-C sampler syntax/warnings, + Alpine `-Wall -Wextra` compilation of sampler/hook and `git diff --check` pass. + No new dependency, Python/Node helper, container/image publication, commit, + deployment or preserved-preview replacement. +- Dedicated stacks: `signet-parser-window`, `signet-parser-window-control`, + `signet-parser-window-repeat`, all based on `signet-logging-final-r2`, no host + port. Only the diagnostic files were copied into these owned containers. + PIM replacement is restored to normal foreground capture on all exits; the + temporary preload/gate files are removed. SQL triggers/holders in default mode + remain owned and cleaned. These are destructive disposable tests, never for + preserved18087 (old PIM Resync still FLUSHDB),18090,8080 or production. + +Logs and recovery evidence are initially under `~/.local/var/signet-work/`: +`parser-window-{first,minimized,fresh-repeat,preload-control,original-fixture, +regressions,final-control,final-red,final-e2e}.log` and product SHA checks. +Restricted source/evidence archive (UTC timestamp): +`/Users/saikrupa/.local/var/signet-feature-backups/parser-window-20261116T193934Z`. +All three owned stacks are instrumentation/holder-free, queues empty, normal +PIM pool restored, no stopped processes or temporary syslog left; then stopped +exit0. Preserved18087/18090 return200; other preserved services are untouched. +For a new replay, retain output before cleanup. The fixture restores its scoped +PIM replacement on exit; independently verify owned trigger/function/holder +counts, normal PIM process count, stopped processes and queue lengths, then stop +ONLY that owned container and record its exit status. The private +`evidence/parser-window-cleanup.sh` shows the actual read-only checks for the +three historical names; adapt the name deliberately rather than checking old +stacks as evidence for a new candidate. Do not run whole-container logging or +resync tests against preserved services. + +Latest evidence mapping: + +| File in private `evidence/` | Meaning | +| --- | --- | +| `parser-window-final-red.log` | Hardened final window, expected exit1/exceeded | +| `parser-window-final-control.log` | Same loaded hook, no held request | +| `parser-window-original-fixture.log` | Original two retained uploads still exercised | +| `parser-window-final-e2e.log` | Full suite after hardened window, all passed | +| `parser-window-regressions.log` | Earlier full suite and standalone parser probe | +| `parser-window-product.sha256`, `product-unchanged-final.log` |47 final22 non-test inputs unchanged | +| `parser-window-cleanup.log`, `parser-window-stopped.log` | All three owned stacks clean, then exit0 | +| `signet-parser-window*-capture.log`, `*-inspect.json` | Original container logs and identities | + +A replay is red ONLY when it reaches the held-field/RGB/font/resumed404/qpdf +checks AND reports `budget_result=exceeded`; a generic exit1 is insufficient. +Native trust/DAM/OpenRC/backups and other ticket20 metadata/catalogue/codec/ +history/arbitrary-PDF resource gates remain open. Do not deploy this integration.
diff --git a/.scratch/pdf-signatures.md b/.scratch/pdf-signatures.md @@ -0,0 +1,100 @@ +# Cryptographic PDF signatures — research, 2026-11-18 + +Research only, not an approved product requirement or implementation plan. +No audit-page decision, dependency exception or production change is implied. + +## Viable formats before recommendation + +1. **Embedded PDF approval signatures:** ISO32000, section12.8 (PDF1.7 edition + consulted), defines signature fields/dictionaries, `/ByteRange`, `/Contents` + and incremental-revision preservation. CMS detached SignedData (RFC5652) is + the standard cryptographic envelope used for common interoperable PDF + signatures. Basic legacy CMS-in-PDF support is a viable compatibility target, + but does not automatically satisfy PAdES Baseline requirements. +2. **PAdES Baseline:** ETSI EN319142-1 profiles PDF signatures. B-B is the basic + baseline; B-T adds trusted time evidence; B-LT embeds validation material; + B-LTA adds archival timestamp protection/renewal. The European Commission's + maintained DSS documentation describes these profiles and notes that not + every CMS or even CAdES Baseline signature is suitable for PAdES Baseline. +3. **Detached CMS sidecar:** RFC5652 SignedData can authenticate an external + file. This is technically simpler than inserting a PDF signature but creates + another artifact, not an embedded PDF signature/reader signature-panel entry. + It is therefore not the answer when the requirement is a self-contained + digitally signed PDF. + +**Recommendation:** for interoperable embedded signatures, target PAdES B-B +as the minimum baseline, consider B-T where future proof of signing time +matters. Use an established signing component and crypto implementation, not +custom crypto/PDF parsing. Long-term document retention may justify LT/LTA, +which add certificate/revocation/timestamp operations and maintenance; they +are not the simplest initial scope. Format conformance alone establishes +neither certificate trust nor jurisdiction-specific legal effect. + +## Embedding mechanism + +Prepare the document revision, including its optional visible signature +appearance and a signature field/dictionary. Reserve a sufficiently sized +`/Contents` hex-string region; finalize `/ByteRange` offsets to cover the signed +revision except that region. Hash those ranges, build/sign the required CMS +signed attributes with the signing key, and insert the CMS bytes in the reserved +region without moving offsets/changing signed bytes. Include the signing +certificate and appropriate chain material/profile attributes. Test signature, +coverage, structure/profile and trust in independent validators; a hash alone +or an image is not a signature. + +A signature can have an invisible appearance and needs no extra PDF page. +PAdES B-B does not require contacting a timestamp authority to sign; certificate +issuance, trust provisioning and revocation checking still need operational +planning. A local asserted signing date is not a trusted timestamp. Later +signatures must preserve prior revisions using incremental updates; preserving +old signed bytes does not imply every appended modification is permitted. +Ordinary whole-file rewriting/re-overlay after signing is incompatible with +preserving existing embedded signatures. + +## Identity and Signet-specific implications + +An employee signature needs a key/certificate attributed to that employee and +a defensible authorization/control mechanism (e.g. token or remote signing +service). One organisation-held key signs as the organisation, not separately +as every employee. A server certificate can seal the released artifact and +attest application records, but must not be represented as an employee-held +cryptographic signature. Self-signed certificates can support cryptographic +integrity; recipient trust requires provisioning and does not appear by magic. + +Current Signet sequential sign-off uses qpdf overlays and release rewriting. +Adding employee cryptographic signatures at each party would need a +signature-preserving revision pipeline, not simply signing each existing +intermediate file. Applying one organisational signature AFTER all current +rendering is a smaller integration boundary but has the different meaning +above. This is an architectural observation, not approval to implement it. + +No native signing component has been selected or benchmarked for the60MB +aggregate target. Current dependency/vendor constraints require explicit owner +approval for any additional crypto/PDF-signing dependency or third-party fork. +A certificate/key lifecycle (issuance, storage/token access, renewal, revocation, +backup/recovery and verification) is part of the feature, not merely an API call. +The DSS Java implementation is a documentation/validation reference here, NOT +a proposed production dependency (Java is prohibited). + +## Sources and verification limits + +- ISO32000-1:2008 section12.8 and Table252, hosted by Adobe: + https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf + Retrieved and relevant signature/byte-range/incremental-update text read. +- RFC5652, especially section5 SignedData: + https://www.rfc-editor.org/rfc/rfc5652 + Text retrieved and SignedData/detached-content structure inspected. +- European Commission DSS documentation, signature levels, PAdES and external + CMS signing sections: + https://ec.europa.eu/digital-building-blocks/DSS/webapp-demo/doc/dss-documentation.html + Retrieved; profiles, byte-range digest preparation and CMS-vs-PAdES caveat read. +- Normative PAdES reference, linked by that official implementation guide: + https://www.etsi.org/deliver/etsi_en/319100_319199/31914201/01.02.01_60/en_31914201v010201p.pdf + Direct access returned403 this session. Profile recommendation is supported + by the retrieved Commission documentation, NOT a claimed fresh clause-by-clause + review of the normative ETSI PDF. No implementation conformance certified. + +No tools/packages installed, no code changes, no remote PDF uploads or private +key operations. Downloaded public source documents are outside the repository +under `~/.local/var/signet-work/`. Background subagents are unavailable in this +session, so source research was performed directly.
diff --git a/.scratch/pdfw-allocation.md b/.scratch/pdfw-allocation.md @@ -0,0 +1,100 @@ +# PDF writer allocation failures — tracker21 (2026-11-15) + +## Scope + +Source-only, uncommitted repair in `/tmp/signet-roadmap-20261112/integration`, +`feat/feature-first-roadmap`. Original dirty checkout and preserved previews +(:18087, :18090, :8080), unrelated services and production are untouched. +No dependencies, schema, installation, runtime configuration or ABI changes. +Aggregate resource/native acceptance20 and actual API logging22 remain open. + +## Deterministic red → green + +`sh test/pdfw-alloc.sh` compiles the actual `pdfw.c` and `ttf.c` with test-only +allocator substitution. A bounded pointer registry checks their allocations, +including loaded TTF bytes, glyph bookkeeping, strings and realloc ownership. +Libc/codec internals are NOT interposed. Separate child processes have a3s alarm +so persistent allocation failure cannot hang the suite indefinitely. + +The healthy public-API path loads real DejaVuSans and synthetic PNG bytes, grows +page content multiple times, clips an image and writes two pages. It traverses +19 allocation positions in this fixture (not19 unique allocation call sites). +Every position is failed once and then persistently in +separate cases. Four additional targeted cases isolate open, existing-buffer +growth, font glyph bookkeeping and font path allocation. Assertions reject leaks, +crashes/timeouts and incorrect success for the targeted fatal writer errors. +Existing unusable-font fallback and caller-visible image failures are preserved. +Healthy output is independently checked by qpdf and pdfinfo (two pages). + +Red invocation on the unchanged `signet-parser-final-r2` product source: + +``` +podman exec signet-pdfw-alloc-check sh /src/test/pdfw-alloc.sh +``` + +(The host uses `podman machine ssh` to avoid the known host known_hosts issue.) +Red log `/tmp/signet-pdfw-red.log`:17 failed cases, including growth/font leaks +and SIGALRM on persistent initial object-table allocation failure. A preliminary +wrong installed-font path was corrected before obtaining this reproduction. + +The source audit's attribution of the spin to `cprintf()` was imprecise: +`cprintf()` returns after realloc failure but loses the old buffer and later +calls try allocating again. The deterministic infinite retry is the +`pdfw_open()` object-reservation loop, which ignored `new_obj()` failure. + +Minimal repair: + +- Content realloc uses a temporary pointer and updates capacity only on success; + an already failed writer does not format/reallocate more content. Negative + formatting results and capacity overflow fail rather than retrying forever. + Initial sizing uses a null buffer without undefined null-pointer arithmetic. +- Font bookkeeping failure frees all unpublished slot resources immediately. +- Open stops on object allocation failure, closes its file and frees ownership. +- Close skips finalisation once failure is known, always releases owned memory + and returns failure. Normal rendering/layout/font fitting is unchanged. + +Green `/tmp/signet-pdfw-green.log`:19 points, transient/persistent failures, +**0 failed cases**, healthy two-page PDF passes. The retained test is run by +normal `test/e2e.sh` and its standalone `pdfw-alloc` mode. + +## Fresh acceptance + +Candidate image/container `signet-pdfw-final`, disposable loopback18104 during +verification. Original parser candidate remains unchanged. + +- Clean image build executes `make clean`, `make -j2`, `make install`; no compiler + warnings. `/tmp/signet-pdfw-build.log`. +- Full `sh /src/test/e2e.sh` ends **all passed**, including the new allocation + test and retained image/command/identity/snapshot/signature/metadata/PIM/upload/ + parser contracts. `/tmp/signet-pdfw-e2e.log`. +- Separate `sh /src/test/e2e.sh render-contract`: all pass, including failed + release, hung-command cleanup, queue retry, replay and database commit gates. + `/tmp/signet-pdfw-render.log`. +- Existing real Chrome signing flow passes against18104, using the preinstalled + external Playwright Core read-only (no package install or new automation JS). + `/tmp/signet-pdfw-browser.log`, screenshots `/tmp/signet-pdfw-browser/`. + Both-page edit/proof/stamped/final screenshots reviewed: matching text fitting, + circular seal and JPEG placement; facsimiles only appear after the appropriate + sign-offs. Audit page reviewed. Synthetic document + `30d37762-c1bb-4bc8-a6ac-bc66e5185332` only in this disposable stack. +- `sh -n test/pdfw-alloc.sh test/e2e.sh`, manual POSIX shell review and + `git diff --check` pass. Tests run with `sh`, not just syntax checked. +- Native source, UI, schema, configs, vendor and tests plus Makefile/Containerfile + SHA256 manifests exactly match the tested image: + `/tmp/signet-pdfw-{host,image}.sha256`. A separate final standalone allocation + rerun also passes: `/tmp/signet-pdfw-repeat.log`. +- Both owned containers stopped/retained after verification; preserved18087 + still responds HTTP200. The service-bearing final stack stopped gracefully; + the native-test-only shell/sleep container needed Podman's SIGKILL fallback + after20s (no services or user state). `/tmp/signet-pdfw-stopped.log`. + +Allocation injection is at the native writer seam, not an OOM experiment on the +live worker. Codec-internal allocation failure, other render inputs and a whole +system memory/RSS certificate are not established. Native/proxy/DAM/shared-service +and backup gates remain ticket14; no deployment is authorised by this result. + +Private source/evidence backup (not runtime user-data backup): +`/Users/saikrupa/.local/var/signet-feature-backups/pdfw-allocation-20261115T013439Z`. +Before/after source, patches/status, source/image checksums and synthetic evidence +are retained privately. Only owned disposable21 containers are stopped/retained; +no preserved stack is upgraded. Old18087 PIM Resync remains unsafe (FLUSHDB).
diff --git a/.scratch/pim-resync.md b/.scratch/pim-resync.md @@ -0,0 +1,75 @@ +# PIM resync safety repair — tracker19 (2026-11-14) + +Implemented and verified in isolated source/stacks, not installed on preserved +:18087. Do NOT invoke Resync in that existing preview until it is upgraded: +its old PIM binary still uses FLUSHDB. No production/shared service changed. + +## Root cause and change + +`h_resync()` used FLUSHDB before rebuilding PIM hashes. An authenticated PIM +administrator could silently erase waiting/processing sign/enrol jobs and every +unrelated Redis key in that database. A disposable red regression fails with +`FAIL - resync deleted unrelated Redis key` against the old verified image. + +The replacement uses existing PostgreSQL/Redis capabilities, no new dependency: + +- PostgreSQL constructs the canonical attribute array. +- A Redis Lua script validates all input/registry names/types before mutation, + atomically reconciles only `<organisation>:metadata`/`:images` for organisations + present in the canonical table or existing `pim:orgs` registry, and records + those organisations. It does not scan/delete arbitrary similarly named keys. +- Upserts atomically remove the old key from both type hashes before publishing + the canonical current type. Empty value deletes both types, matching the + database's org/key deletion semantics. Every write tracks its organisation. +- A component-level PostgreSQL session advisory lock orders committed SQL updates + and their Redis mirror publication against resync across PIM workers. Keeping + it across SQL commit prevents an older mirror write overwriting a newer resync. + Every acquired lock has an explicit unlock attempt on success/error response + paths; the fixture verifies release after cache errors. +- Missing/invalid Redis replies produce503, including an empty canonical table; + NULL replies drop the cached Redis connection. A committed SQL change with a + failed cache write retains the existing 'saved, Redis down; resync later' + contract. Cache reconstruction is retryable, not a distributed transaction. + +Redis scripts prevent interleaved partial publication; they do NOT provide +rollback after arbitrary runtime/OOM failure or atomic commitment with PostgreSQL. +Direct out-of-band SQL writers must coordinate/quiesce or use the same lock; +normal PIM API writers participate. Native lifecycle/limits remain unverified. + +## Namespace and migration boundary + +The PIM-owned namespace remains `pim:orgs` plus known organisation hashes. This +must be reserved separately from configured signing queues and other services +before production. No allocation/ACL policy is invented here. A hash whose +organisation has neither a canonical row nor a registry entry is NOT safe to +infer as PIM-owned and delete. Historical manually orphaned/unregistered keys +need an owner-reviewed inventory/reconciliation, not a broad SCAN/DEL fallback. +Catalog size, Redis script/shared-service resource limits, and native containment +remain open with ticket14/20; this is not production acceptance. + +## Retained evidence + +`test/pim-contract.sh` runs in full E2E, only inside a disposable dev stack. It +pauses its worker, plants waiting/processing markers and unrelated keys, and +checks exact list contents/order, foreign values/TTL, and an unowned `:metadata` +hash. It verifies: + +- Resync preserves signing/enrol waiting/processing and foreign Redis state. +- Text-to-image changes and deletion with a differing supplied type leave no + stale opposite-type field; stale attributes/types are reconciled from SQL; + historical empty-value rows retain their uncached/deleted semantics. +- A previously managed organisation with no SQL rows is cleaned. +- Wrong-type/invalid-name registry returns503 before cache mutation; failed upsert still + commits its SQL value and reports503, then resync recovers it. +- Two real PIM workers wait on an independently owned mirror lock. No SQL write + slips past it; after release, concurrent upsert/resync succeed and keep the + newest canonical value, with no advisory locks left behind. The fixture + restores the one-worker PIM pool and resumes the worker on exit. + +Logs `/tmp/signet-pim-{red,green,build,e2e,render}.log`; image identity +`/tmp/signet-pim-image.txt`. Fresh clean Alpine build has no warning/error matches; +full E2E (identity, snapshots, signatures, metadata and PIM) and render/hang/replay +contracts pass. Renderer/JS geometry are unchanged. Redis failures call `log_err`, but actual +both-API/dev log capture needs follow-up22; current runtime stdout did not expose +those fixture diagnostics, so no logging-transport pass is claimed. API/worker/UI on preserved +:18087 were NOT replaced during this work. Source is uncommitted integration.
diff --git a/.scratch/preview-upgrade.md b/.scratch/preview-upgrade.md @@ -0,0 +1,77 @@ +# Signature collection integration and preserved-preview upgrade + +Completed 2026-11-14 UTC, with the owner's approval to proceed. Integration is +uncommitted in `feat/feature-first-roadmap` at +`/tmp/signet-roadmap-20261112/integration` (base `9876b79`). The feature source +also remains in `feat/signature-collections`; no commit or remote publication. +The original dirty checkout, its auth experiments and skill deletions were not +changed. + +## Review and integration + +Reviewed the uncommitted feature against `9876b79`, AGENTS, CONTEXT, ADRs 0001/2 +and the owner's collection requirements. No blocking correctness/spec mismatch +found: typed owned/enrolled references, immutable queued decisions, legacy +NULL-reference behaviour, worker-only original reads, and configured roles are +retained. The verified feature files were copied into the previously clean +integration worktree, without unrelated original-checkout changes. Existing full +build/E2E/render/browser/migration evidence is in `signature-collections.md`. +Subagents were unavailable; review was performed directly, not delegated. + +## Backup and rehearsal + +Private durable backup (0700 directory, sensitive files 0600): +`/Users/saikrupa/.local/var/signet-preview-upgrades/20261114T045733Z/`. +It contains pre/post database dumps, pre/post installed runtime archives, private +signature/document/DAM/config backup, Redis RDB/AOF, container metadata, +original-field row fingerprints for every public table, all application asset +hashes, package comparisons, installed-product hashes, private browser evidence +and rehearsal logs. Never commit these private backup contents. + +The actual backup was restored into `signet-signatures-upgrade-rehearsal`. +Migration 002 applied twice preserved every original column in every table and +all asset bytes. The restored data booted and survived three graceful restarts +in the same no-`--init` topology as the user's container. Rollback was also +rehearsed there: restored old-schema dump plus original runtime booted, and all +original records/assets matched. The rehearsal is stopped; its localhost:18091 +is no longer serving a second copy of the user's data. + +## In-place upgrade + +The existing `signet-jpeg-loopback` container was not recreated or reinitialised. +Its web process was frozen and APIs/worker stopped before the consistent dump +and filesystem backup. Applied migration as DB owner with writers stopped; +original-column fingerprints matched immediately. PostgreSQL and Redis were +cleanly shut down before the container was stopped and runtime replaced. + +Installed API/worker and three UI files matched the previously verified product +image `6009232559c7ca6082c66bff36aa70086e4d5c135021c9c7c298f005e91865f2` +byte-for-byte; package inventories matched. Updated source/startup scripts were +staged too. Booted initially on an internal-only maintenance port, verified all +original data/config/file hashes and Redis logical contents (including key types +and expiration times), then restored the exact original web config and reopened +http://127.0.0.1:18087. The container's original image ID is unchanged because +this is an in-place filesystem upgrade, not a newly committed user-data image. + +Read-only browser checks on :18087 passed for manager/management: signer nav, +My signatures, existing pending inbox/document, default signature picker and DOM +placement. No sign-off, upload, default change or other mutation was performed +on user records. No page errors. Three graceful restarts and a full controlled +same-container restart passed. After browser and restart checks, all original +public-table fields, all document/signature/DAM/config bytes, all new collection +IDs/metadata and complete Redis logical data still matched their baselines. +Only the intended new schema/metadata was added; no old decision was backfilled. + +## Scope and remaining gates + +:18087 is now the upgraded preserved preview; :18090 remains the clean synthetic +preview. The :8080 stack, unrelated PHP :8087, maa-1 and shared services were not +modified. No host/VM clock or sysctl was changed. Native OpenRC, proxy trust/DAM +writer policy, resource/concurrency/coexistence and production backup acceptance +remain ticket14 / tracker9. This local restore rehearsal is not a production +certificate. Publication/commits remain pending. + +Rollback snapshots are point-in-time. Once the user resumes editing/signing, +never blindly restore the pre-upgrade dump: doing so would lose subsequent +entries. Preserve current state and reconcile any later changes first. Removing +or recreating the container is not persistence; retain its data and backups.
diff --git a/.scratch/request-retention.md b/.scratch/request-retention.md @@ -0,0 +1,124 @@ +# API request retention and mixed render fixture — ticket20 (2026-11-15) + +**Source-only repair of the retained-request counterexample. Parent20 remains +OPEN for other resource combinations and native representative acceptance.** +Authoritative integration remains `/tmp/signet-roadmap-20261112/integration`, +HEAD9876b79 plus uncommitted work. No preserved-preview installation, deployment, +commit, dependency, input-capacity, schema or configuration change. + +## Reproduction and rejected approach + +The unchanged opt-in `test/resource-image-probe.sh` reproduced68428KiB on the +pre-repair writer image in disposable `signet-qpdf-investigate`. It queues an +actual max4MP high-entropy PNG/loaded-font render while two admitted1120212-byte +multipart document uploads are retained at INSERTs. Snapshot assets16218599 +bytes remain within16MiB. Exact decoded RGB and font bytes pass even when RSS +fails. Previous checkpoint reached72240KiB; neither that failure nor these +sampled peaks is discarded from the evidence. + +Upstream qpdf12.2.0 source reads a whole stream in `QPDF::pipeStreamData()` and +buffers writer stream data in `QPDFWriter::willFilterStream()`. Its standalone +~34MiB overlay cost was already measured. Stream-preserve is not a repair. +A prototype splitting PNGs into64 internally positioned strips passed the RSS +fixture (50304KiB) and exact decoded-pixel checks, but changed rasterization and +showed strip-boundary banding. It was REJECTED: writer/test changes are reverted +byte-for-byte to the preceding checkpoint. No tiling helper remains in product +source. qpdf itself, geometry, interpolation, alpha and image samples are unchanged. + +## Retained repair + +1. `src/http.c:http_keep_fields()` runs immediately after parsing in BOTH APIs, + before a handler can block on PostgreSQL. It discards unused fields/cookies, + keeps the first occurrence of supported names (existing `http_field()` + semantics), preserves binary file/metadata ownership and shrinks the pair + array. The component's supported-name list is beside its FastCGI main loop; + adding a future input requires updating that list as well as its handler. + Unknown fields were already ignored. No accepted body/field/file limit is + lowered, and the original35000-part requests still succeed. + + kcgi0.13.4's destructor frees key/val/file/ctype/xcode per pair. The helper + releases exactly these owned pointers; parsed values alias val. It only + operates on unmapped requests (`keysz==0`, matching both init calls), clears + retained next pointers and refuses mapped storage. On failed shrink, the + reduced logical count remains valid for ordinary kcgi cleanup and the API + returns503 instead of dispatching with the original large allocation. + +2. Repeated warm tests showed that compaction alone was insufficient:59100KiB + still exceeded60000000 bytes. libpq caches its grown input/output buffers + after `PQclear()`. `src/db.c` now marks the cached connection for recycling + when a query's aggregate text parameters or `PQresultMemorySize()` reach + 256KiB. `db_request_done()` releases that connection only at the API request + boundary. Ordinary small requests retain connection reuse; large requests + reconnect lazily on the next DB operation.256KiB is a recycling trigger, + NOT an input limit or exact heap bound. It uses existing libpq16 APIs. + + Query results, active transactions and worker connection lifetimes are not + interrupted. Only API main loops call the boundary operation. The worker's + PostgreSQL commit-before-queue-ack contract is unchanged. Operational cost: + an API request after large DB I/O may need a fresh DB connection; no added + service, file, install permission, config switch or migration is needed. + +## Verification + +Final image/container: `signet-request-retention-final-r2`, temporary loopback +18110, disposable only. Fresh build has no compiler/make warnings. The host +clock was ~15 minutes ahead of the VM: no clock was changed; only private build +staging file timestamps were normalized in the VM before the build. + +- Full E2E ends `all passed`, including metadata/PIM/signature/chunked-upload, + parser admission, allocation and exact image/font contracts. +- `test/http-fields.c` covers10000 distinct unknown names, known duplicates, + first empty/NUL/binary values, file metadata, cookies, mapped-request refusal, + idempotence, zero retained fields, failed realloc and real kcgi destruction. +- `test/db-cache.c` verifies backend PID reuse for small queries; fresh backend + after large result/parameter/aggregate-parameter/error cases; SQL NULL params; + and preservation of an active transaction until its explicit commit/boundary. +- Real HTTP tests cover both APIs' first-duplicate semantics and byte-exact PDF + upload/source retrieval. Full E2E includes `request-fields`; standalone mode: + `sh /src/test/e2e.sh request-fields`. +- Seven final mixed runs, including after renderer/browser tests:54212,52776, + 53064,57020,49748,55736,55896KiB. All retain the original probe/capacity and + compare decoded RGB/font bytes. Maximum57020KiB =58388480 bytes, below60M + FOR THESE SAMPLED FIXTURES, with limited headroom. No universal bound claimed. +- Separate render/hang/retry/replay/DB contracts pass. Chrome signing flow + passes with two-page output and audit reviewed; synthetic document + `123a1527-faad-448b-8d33-cb7393485856`. +- Separate three-request parser/query/cookie fixture:48132KiB. This is NOT + proof that active dense parsing and qpdf can overlap safely. +- ASan/UBSan runtimes are absent from the existing image; no dependency was + installed. Real destructor/failure tests are not exhaustive allocator proof. + +The resource sampler sums RSS of Signet/lighttpd UIDs, including helpers and +external tools, not PostgreSQL/Redis or root test tools. Sampling is non-atomic, +with1ms sleep PLUS scan time. Successful samples do not certify peak worst case, +other colours/codecs, catalogue/history/metadata cardinality, simultaneous active +parsing/qpdf, arbitrary PDFs or a native1vCPU/1GB shared deployment. Continue20 +after22 (owner reordered on2026-11-16; `.scratch/api-logging.md` records its +source-only completion); owner14 trust/DAM/namespace/backup/OpenRC gates remain separate. + +## Evidence and recovery + +Restricted source/evidence backup: +`/Users/saikrupa/.local/var/signet-feature-backups/qpdf-image-strips-20261115T031645Z`. +The directory name reflects the rejected first experiment, not the retained +implementation. Before source/status/diff, rejected candidate, final-r2 source, +logs, manifests, image metadata and synthetic browser evidence are retained. +It is a source backup, not a runtime DB/files/queues backup. + +Logs `/tmp/signet-qpdf-{red,stream-red,strips-first,strips-green,pixel-compare}.log`, +`/tmp/signet-request-retention-{green,final-e2e,final-mixed,repeat}.log`, +`/tmp/signet-request-retention-r2-{e2e,mixed,post-browser}.log`, +`/tmp/signet-request-retention-browser.log`; screenshots under +`/tmp/signet-request-retention-browser/`. Earlier retention-only overrun59100KiB +and original72240KiB evidence are historical failures, not final candidate passes. + +Host/image SHA256 manifests match all88 native/UI/schema/config/vendor/test +files plus build descriptors in the manifest. Installed binaries match the build. +`sh -n`, manual POSIX/ownership review and `git diff --check` pass. Owned trigger +and holder-backend counts are both0. All five owned investigation stacks are +stopped/retained, exit0: `signet-qpdf-investigate`, `signet-qpdf-strips-check`, +`signet-request-retention-check`, `signet-request-retention-final`, and final-r2. +No implicit replacement preview remains. Preserved18087 remains HTTP200; +18090/8080 and PHP8087 were not modified. Never invoke old PIM Resync on18087 +(still FLUSHDB). No native installation or preserved-preview replacement is +implied. Source manifests and cleanup/stopped logs accompany the private backup.
diff --git a/.scratch/resource-audit.md b/.scratch/resource-audit.md @@ -0,0 +1,149 @@ +# Ticket 14 follow-up — local resource audit (2026-11-14) + +Scope: integration source plus disposable Alpine stacks only. The preserved +:18087 preview, clean signature preview :18090, ticket11 :8080, unrelated PHP +:8087 and all production/shared services were not modified. No native resource +certificate, production deployment, upload-policy change or commit is implied. + +## Implemented: remaining decision metadata guards (tracker 18) + +`h_doc_decide()` now applies the existing 1 MiB byte policy to supplied placement +text before yyjson parsing. Embedded NULs are rejected, not treated as an absent +placement. Its SQL query bounds a legacy pending layout before transferring it +through libpq; oversized stored layout blocks sign-off with409, but a correction +request remains possible without parsing it. No signature/route access is widened. + +Retained `test/metadata-contract.sh`, invoked by the full E2E suite, verifies: + +- 1,048,577-byte placement rejected400 with no decision; exact1,048,576 accepted. +- Embedded-NUL placement rejected400. +- Pending legacy layout padded with350,000 multibyte characters (>1 MiB bytes, + fewer than1 MiB characters) rejected409 with no decision; correction succeeds. + +The old verified signature image accepted oversized placement (200, expected400) +and the oversized pending layout (200, expected409). Red logs: +`/tmp/signet-resource-{metadata,legacy}-red.log`. +Green: `/tmp/signet-resource-metadata-green.log`. +Full build/E2E/render logs: `/tmp/signet-resource-{build,e2e,render}.log`. +Final image identity is captured in `/tmp/signet-resource-image.txt`. +Renderer/geometry/font fitting are unchanged; no renderer visual change is claimed. + +## Measured release blocker: concurrent buffered uploads (tracker 20) + +**Subsequent source repair:** `.scratch/bounded-uploads.md` records chunked PDF +transport retaining32MiB capacity and a pre-kcgi1100KiB API/PIM body cap. The +latest harder repaired fixture peaks29,660KiB with both max source hashes verified. +The evidence below is the historical counterexample; the current probe now +uses the chunk protocol. Tracker23 subsequently fixes dense form amplification: +16KiB non-multipart cap,1100KiB multipart retained, with exact logical field/PDF +capacity tests. See `.scratch/bounded-parsers.md`. Tracker20/native aggregate +acceptance stays open. + +`test/resource-upload-probe.sh` is an explicitly opted-in, destructive disposable +fixture diagnostic, NOT part of normal E2E and NEVER for preserved/shared stacks. +Run only inside a dedicated dev stack: + +``` +SIGNET_RESOURCE_PROBE_DISPOSABLE=yes sh /src/test/resource-upload-probe.sh +``` + +Two actual32 MiB multipart PDF-header uploads enter the existing two-handler API. +An owned PostgreSQL advisory lock/trigger holds their document INSERTs so both +already-parsed request bodies remain live. The probe sums `/proc/*/status` VmRSS, not virtual allocation estimates. +The actual cohort is all `signet`, `signetd`, and `lighttpd` UID processes, +including kfcgi/kcgi children; root curl/probe, PostgreSQL and Redis are excluded. + +Observed on isolated `signet-resource-audit`: + +- Baseline22,896 KiB; both handlers held88,888 KiB (~91.0 MB decimal). +- Budget60,000,000 bytes. This is an actual local budget counterexample, not + merely a missing native measurement. Parse-time peaks may be higher. +- Both HTTP uploads completed201 after releasing the owned gate. Upload currently + checks size/header, not full PDF validity; invalid admitted input must also be + resource-bounded. The two synthetic DRAFTs remain only in the disposable stack. +- No global memory limit, clock, host/VM setting or shared service changed. +- Trigger/function and owned lock-holder session removed on exit. Original + pdfinfo SHA verified unchanged after an initial unsuccessful wrapper-based probe + (uploads do not call pdfinfo). That initial diagnostic did not establish RSS. + +Evidence: `/tmp/signet-resource-upload-probe.log`. Exit0 means the diagnostic ran, +NOT that the budget passed: its explicit `budget_result=exceeded` is a blocker. + +Do not silently lower the accepted32 MiB PDF policy or certify the current +concurrency. Implement streaming/admission/runtime controls and measure the entire +cohort, including transient parser copies, in follow-up20; native target and +representative workload acceptance still require owner inputs. + +## Allocation/parse path audit and limitations + +| Path | Existing bound / live allocation | What this does NOT establish | +| --- | --- | --- | +| HTTP transport | API/PIM16KiB non-multipart,1100KiB multipart before kcgi; PDF32MiB via256KiB chunks, PNG/JSON fields1MiB; DAM/WebDAV34000KiB unchanged | concrete PDF and dense-form counterexamples repaired in source; remaining JSON/catalog/codec/mixed/native workloads not certified | +| save/submit/decide metadata | save request1 MiB; submit stored layout/route each1 MiB before libpq; decision placement/stored layout now bounded | yyjson nodes/mutable clones amplify input bytes; this is not a1 MiB heap or whole-request bound | +| PIM writes | value500 bytes, org/key50, checked after request parsing | oversized request is buffered first; resync/attrs read the full unpaginated SQL table; catalog count is not bounded | +| Redis PIM discovery | SCAN/HKEYS and reference reads | SCAN COUNT is a hint; reply buffers/cardinality and foreign colliding keys need namespace/resource policy | +| snapshots | <=201 streamed assets, <=16 MiB aggregate,16 KiB copy buffer; text<=1023 bytes | worker reads/parses stored manifest/layout JSON; no blanket pre-transfer bound on every legacy DB/queue JSON path | +| proof fonts | <=8 cached fonts; each TTF<=16 MiB; glyph-use array<=256 KiB/font | for normal verified frozen proof inputs, aggregate font FILE bytes are within the SAME16 MiB snapshot budget, NOT8x16 MiB; font compression and metadata add live memory | +| PNG proof embedding | <=4*1024*1024 pixels; RGB3P or RGBA4P, optional alphaP; compression streams in16KiB output chunks plus codec state | native maxRGB+font fixture now16216KiB vs32728KiB; one image freed before the next, metadata cache does NOT retain64 decoded images. prior qpdf/API mixed failure72240KiB is repaired for the retained-request fixture (seven samples <=57020KiB) by API field/cache cleanup; other overlaps/native still open; `.scratch/request-retention.md` | +| facsimile enrolment | <=4,000,000 pixels; one decoded RGBA buffer; uploaded bytes<=1 MiB | compressed input size is not decoded size; separate API and worker allocations can overlap | +| JPEG embedding | encoded file<16 MiB, direct DCT stream, freed per image | does not server-decode pixels; arbitrary colour spaces/unusual PDFs remain unverified | +| audit release | full SQL event history plus line pointers, streamed per-page PDF output | event count and total audit pages/history are unbounded;500-page source limit is not an audit-history bound | +| external tools | 30s wall deadline, owned group cleanup, direct-child parent-death | not CPU/RSS/I/O containment or a deadline around C parsing/rendering; escaped descendants/native lifecycle still open | + +### Independent safety findings + +- **Tracker19, source fix completed after this audit:** the old + `pim/pim-api.c:h_resync()` used `FLUSHDB`, deleting signing/enrolment queues and + unrelated Redis state. Scoped reconciliation and ordered mirror writes now + pass queue/foreign-key/type/deletion/error/two-worker regressions and full + E2E/render suites. See `.scratch/pim-resync.md`. Do not invoke old Resync in + preserved :18087: the source-only fix is NOT installed there. Production + namespace ownership must still be agreed, not inferred from dev default keys. +- **Tracker21, repaired/dev-verified2026-11-15:** deterministic injection + reproduced content realloc and unpublished font leaks. Correction to the + original source hypothesis: `cprintf()` returns after failure; the infinite + retry is `pdfw_open()` ignoring failed object reservation. All three paths + now have minimal cleanup/failure repairs.19 allocation points under transient/ + persistent faults, full E2E/render and both-page browser visual comparisons + pass. Source-only; `.scratch/pdfw-allocation.md` records evidence and limits. + +- **Tracker22, repaired/dev-verified2026-11-16:** shared API failure summaries + now log normalized route/actor/status/source site, with private message/path + data omitted; DB diagnostics retain only SQLSTATE. Foreground dev kfcgi and + pool-restarter fixes retain stderr. Real container capture, LOCAL0 filtering, + privacy/success-silence tests and restart/full E2E/render checks pass. See + `.scratch/api-logging.md`. Pre-dispatch web/proxy failures and persistent + native LOCAL0 capture/rotation remain separate administrator gates. + +### Subsequent writer slice and actual mixed-load blocker (2026-11-15) + +Streaming image/font compression and direct RGB decoding halve the native writer +fixture peak32728→16216KiB without reducing capacity. Exact RGB/alpha/font bytes, +Unicode, fault tests and full E2E/render/browser visuals pass. That writer-only +checkpoint still failed aggregate20 at72240KiB. Subsequent request compaction +and libpq large-I/O cache recycling repair the retained-body fixture without +changing pixels/qpdf/capacity: seven final samples <=57020KiB. Compaction alone +still failed59100KiB; the strip-rendering prototype changed visuals and was +rejected/reverted. The unchanged opt-in probe is retained, not waived. See +`.scratch/request-retention.md` for final evidence and operational implications; +`.scratch/image-memory.md` preserves the earlier failure. Active dense parsing +plus qpdf and other metadata/catalog/codec/native combinations remain unverified. +No production/preserved stack is changed. + +### New scheduling-window counterexample (2026-11-17) + +The post-parse cleanup does not bound the earlier live array: one admitted +35001-field PIM request paused after real kcgi parsing but before pruning, with +NO retained API uploads/query/cookies, overlaps qpdf at60992–62716KiB, exceeding +60000000 bytes. Matched loaded-hook/no-request controls peak53688/54252KiB; +the original retained-upload probe still passes56404KiB. Exact decoded RGB/font +bytes and eventual PIM404 pass. All47 non-test inputs remain final22-identical; +only disposable diagnostic tests changed. Full E2E after cleanup passes. +This forced scheduling diagnostic is a new technical blocker, NOT a repair or +proof of every running-parser phase. `.scratch/parser-window.md` gives exact +invocations, limits and next admission-repair requirements. Do not lower caps +or treat an unobserved/blocked qpdf phase as a green budget result. + +The native/proxy/DAM/shared-service/backup gates in ticket14 remain open. Local +technical work20 is unfinished;22 is source-only complete. Owner questions +are not the sole remaining blocker.
diff --git a/.scratch/roadmap/ticket-14.md b/.scratch/roadmap/ticket-14.md @@ -159,3 +159,36 @@ Integration branch feat/feature-first-roadmap is kept in wip/preserved-local-state-20261112, including auth experiments and skill removals. No branch was pushed and no PR was created or marked ready. Final whole-spec review/readiness must remain open while this ticket is incomplete. + +## 2026-11-14 local follow-up: known technical blockers, not just owner inputs + +See `.scratch/resource-audit.md`. Decision placement and pending legacy-layout +parsing now use the existing1 MiB byte guard, with red/green/full E2E/render +coverage. This source-only change has not been installed on preserved :18087. + +An explicitly disposable probe held two admitted32 MiB upload requests at their +owned SQL INSERT gate and measured88,888 KiB aggregate application RSS. Budget +failure is demonstrated locally; previous small-fixture samples do not establish +resource safety. Follow-up20 must address buffering/admission without silently +changing the accepted32 MiB policy, then obtain aggregate/native acceptance. + +Follow-up19 subsequently repaired PIM's FLUSHDB in integration source, with +scoped reconciliation, ordered mirror writes, queue/foreign-state preservation, +cache-error recovery and two-worker tests; full E2E/render pass. See +`.scratch/pim-resync.md`. NOT installed on preserved :18087; do not invoke its +old Resync action. PDF writer allocation failures still need injected tests/ +repair (21). Follow-up20 subsequently repaired the concrete upload counterexample +in source:256KiB application chunks retain32MiB PDF capacity and API/PIM bodies +are capped before kcgi. Two max files with near-cap ignored fields/hash checks +peak29,660KiB versus182,624KiB before repair. Full E2E/render, ownership/retry/ +commit-recovery/migration and browser tests pass; `.scratch/bounded-uploads.md`. +NOT installed :18087. Tracker20 remains open for parser/image/font/render +aggregation and native acceptance. Normal frozen-input font bytes share the aggregate +16 MiB snapshot budget; PNGs are decoded sequentially, not64 retained buffers. +Those facts still do not bound the complete concurrently active process cohort. +Tracker23 then repairs dense form parsing before kcgi: non-multipart16KiB, +otherwise multipart1100KiB; logical1MiB fields/32MiB files remain supported. +Three near-cap nested multipart requests with query/cookies peak50052KiB; +full E2E/render/browser pass. `.scratch/bounded-parsers.md`. Mixed renderer and +other metadata/catalog/native gates remain, as do21/22. No production/shared +service or preserved preview changed during this follow-up.
diff --git a/.scratch/session-handoff.md b/.scratch/session-handoff.md @@ -0,0 +1,258 @@ +# Session handoff — 2026-11-17 + +## Latest source checkpoint — 2026-11-19 + +Optional detached RFC3161 timestamp task10 is implemented/source-dev verified; +read `.scratch/detached-timestamps.md`, `docs/timestamps.md` and ADR0003 first. +Owner approved libcurl + OpenSSL libcrypto (not curl subprocesses). Unchanged +released PDF and existing facsimile/sign-off/audit behavior; separate server +and validated TSA times; four total attempts within1h, short-lived cron runner, +explicit trust, no release gate. Disabled by default; no live TSA configured. +Final disposable r5 warning-clean build/full E2E, actual cron/crash/concurrency/ +release-independence/access/hash/migration checks and101 source hashes passed. +Timestamp representative sample39784KiB; subsequent32-document A5-only33660KiB. +No browser acceptance: existing optional Playwright cache is pruned; no reinstall. +No commits/publication/deployment/native install/preserved-preview changes. +Ticket20 and its native/aggregate gates remain OPEN. **Product files now include +intentional timestamp edits after the restored47-file final22 parser baseline**; +do not restore them away trying to enforce the older checkpoint's hashes. +Private evidence: `~/.local/var/signet-work/timestamp-implementation-20261119/`. +All five owned timestamp stacks are stopped exit0; fixture queues/locks/processes +clean, :18095 closed. Preserved :8080/:18087/:18090 stacks remain unchanged. + +## Representative workload update — 2026-11-18 + +Owner says most PDFs resemble `~/Projects/salaryprocess/out/a5/`: read-only scan +found32 one-page A5 PDFs,3913–4210bytes, base14 Helvetica/Helvetica-Bold, no +images/forms/JS/encryption. No real payroll contents/files copied to fixtures +or containers. `.scratch/a5-workload.md` records a new synthetic4108-byte A5 +32-document create/submit/sign/release probe, with source/final hashes, all29 +text rows, A5 body dimensions, seal/facsimile and audit checks. Final sampled +peak33528KiB; warm sample33952KiB; full E2E all passed. Two test files added, +no product change or capacity reduction. Representative sequential evidence +only: all ticket20 failures/native gates below remain OPEN. Owned +`signet-a5-resource-20261118` cleaned/stopped exit0; evidence in private +`~/.local/var/signet-work/a5-resource-20261118/`. Preserve user's source PDFs. + +## Latest parser update — 2026-11-18 + +Ticket20 still OPEN; read `.scratch/parser-coordination.md` next. A parent-only +parse/prune versus worker admission gate was implemented/tested, then REJECTED +and selectively reverted: held-parent exclusion passed51224KiB, but reverse +worker-first order still failed59136/59296KiB with an already-buffering kcgi +child. At that restored checkpoint (before the later timestamp work above), +all47 product inputs were final22-identical; full E2E on restored baseline ended all passed, and baseline red reproduces63112KiB. Only diagnostic +tests/notes survive this session. No normal E2E additions or new product locks +remain. Candidate/native test source and evidence are private under +`~/.local/var/signet-work/parser-repair-20261118/`; do not install its r2/r3 images. +Three owned service stacks (red, r2, r3) cleaned/stopped exit0; r1 failed startup +and remains exited1. No preview/shared/production changes, commits, dependencies, +clock/known_hosts changes or browser/native acceptance. Next design must cover +child buffering BEFORE parent readiness in both orders, not repeat parent-only +locking. Existing no-publication/no-third-party-edit limits still apply. + +## Resume here + +Authoritative integration (recovered2026-11-17): +`/Users/saikrupa/.local/var/signet-work/integration-recovery-nQvIoiCL`, branch +`feat/feature-first-roadmap`, HEAD9876b79 plus substantial UNCOMMITTED changes. +The old `/tmp/signet-roadmap-20261112/integration` lost its `.git` and source +files. It is preserved as partial evidence, NOT a usable working tree. Recovery +used the final ticket22 `after/source.tar` into this new durable directory: +all105 surviving product/doc files and61 surviving tool files match; all91 +runtime-input hashes and the complete Git status match the saved checkpoint. +Native Git worktree repair reconnects the existing branch, without checkout, +reset or commit. Durable pointer: `~/.local/var/signet-work/current-integration`. +Recovery evidence/partial-tree and registration archives are in that parent. +Original `/Users/saikrupa/Projects/signet` dirty checkout is preserved; do not +replace it, commit its unrelated changes or copy its unsafe identity fallback. + +Read CONTEXT.md, HANDOFF.md, docs/adr/, .scratch/bounded-parsers.md, +.scratch/bounded-uploads.md and .scratch/resource-audit.md before coding. +Latest verified source adds tracker22 privacy-safe API logging/capture, +image `signet-logging-final-r2`. Clean full E2E/render and actual container-log +checks pass, including after pool replacement and full container restart. +See `.scratch/api-logging.md`. Owner priority22 →20 →rest;22 is source-only +complete,20 is NEXT/OPEN. Prior mixed fixture's seven samples (max57020KiB) +remain limited evidence, not rerun as native acceptance during22. No new RSS +certificate. Latest test-only20 work reproduces a DIFFERENT unpruned request +window: one admitted35001-field PIM parse held before pruning plus qpdf peaks +60992–62716KiB (>60M bytes), while matched preload controls and the original +retained-upload fixture pass. Product-source47-file hashes remain unchanged. +Full E2E after the final probe passes; this blocker is NOT repaired. See +`.scratch/parser-window.md` before choosing an admission/coordination repair. +Read `.scratch/request-retention.md`, `.scratch/image-memory.md`, +`.scratch/pdfw-allocation.md`; strip-rendering prototype remains rejected. +The earlier `/tmp/signet-roadmap-20261112/parsers`, `fix/bounded-parsers`, predates +tracker21. The older `uploads` worktree also predates the final parser cap; +do not copy either over current integration. + +## Next session: start here, in order + +1. Enter the durable worktree, not the original checkout or partial `/tmp` copy: + + ```sh + root=$(head -n 1 "$HOME/.local/var/signet-work/current-integration") + cd "$root" + git status --short + git rev-parse --abbrev-ref HEAD + git rev-parse --short HEAD + ``` + + Expected branch `feat/feature-first-roadmap`, base9876b79 and a substantial + dirty tree. Preserve ALL existing changes. Do not reset, checkout old source, + apply a whole backup diff, prune worktrees or commit/push without approval. +2. Read this file, CONTEXT.md, HANDOFF.md, AGENTS.md and both ADRs; then + `.scratch/parser-window.md` for the current red loop, controls and limitations. + Ticket22 is completed SOURCE-ONLY; ticket20 is the active task, not finished. +3. Use the host replay in that note to create a NEW unpublished disposable stack. + Host `podman` still needs the existing `podman machine ssh` workaround; do not + edit `~/.ssh/known_hosts`. The current baseline image exists as + `signet-logging-final-r2`. It contains the previous product code, not a future + repair: copy the three current diagnostic files when replaying it. Product C + changes require a fresh image build from THIS worktree/private staging, never + the original checkout. Preserve the host and VM clocks. +4. Repair the pre-prune overlap without lowering admitted capacities. No + coordination/admission fix has been implemented or approved as correct yet. + Existing key registries do not filter kcgi's accumulated unknown fields; + another post-parse free cannot fix this window. Check idle FastCGI waits, + child buffers, file/DB/queue lock ordering, permissions and signal/crash + cleanup before choosing a gate. A repair that blocks the worker needs a + revised diagnostic release handshake: timeout/unobserved qpdf is NOT a pass. +5. Verify the red input, preload control, ORIGINAL retained-upload case, exact + RGB/font bytes and full E2E against the candidate; check all owned fixture + teardown and source/binary identities. Sampling is not native certification. + Other20 metadata/catalogue/Redis/history/codec/arbitrary-PDF cases and owner14 + native/proxy/DAM/backup gates remain open after this particular repair. + +### Permissions and non-goals + +Source/test work on disposable development stacks is authorised. Commit, push, +publication, dependency installation, production/native-target work and preserved +preview upgrades are NOT authorised. No Python or replacement JS/Perl/etc. +assistance scripts; use POSIX sh/existing utilities and the established C tests. +Keep32MiB PDF,1MiB JSON/PNG,1100KiB multipart and16KiB non-multipart admission; +keep reference-only inputs, sequential access and edit/proof/stamped fidelity. +Do not resurrect the rejected PNG-strip approach or change qpdf/dependencies to +obtain a passing number without a separately agreed change and fidelity checks. + +## Completed, source-only + +Signature collections/restart repairs, metadata18, scoped PIM19, chunked PDF20, +dense parser23 and PDF writer allocation21 are integrated uncommitted. Only the earlier authorised +signature/restart upgrade was installed on preserved18087. No commit/push or +production/shared-service deployment happened. + +Latest parser23 fix: API/PIM bodies16KiB non-multipart,1100KiB multipart before +kcgi. Large logical fields must use multipart;1MiB JSON/PNG and32MiB PDF files +remain supported. PDFs use authenticated256KiB chunks, migration003 counters, +creator row locks, byte-checked retries and durable guarded publication. + +Earlier parser23 tested candidate `signet-parser-final-r2` container +`7dbc0b55d5246e89ba816c25ca645235c9a11c8ab6eae59c25dfbb98709cad85`. +Product/test source SHA matched image and integration at that checkpoint. Clean build/no warnings, +full E2E ends all passed, renderer/hang/replay, exact admission limits, ambiguous +MIME/unknown-length/encoded-prefix checks, browser32MiB two-page/hash/progress/ +failure/delete, full signing flow and standalone client all pass. + +Original two900KB dense forms:122884KiB RSS; now rejected before parsing. +Three admitted near-cap nested multipart requests plus dense query/cookies: +50052KiB sampled aggregate. Two complete32MiB PDFs:28964KiB, both source hashes +verified. These are fixture samples, NOT mixed renderer/native certification. + +## Pending / next action + +1. Repo21 completed source-only: deterministic injection reproduced17 failures; + 19 allocation points now pass transient/persistent faults, full E2E/render and + real browser both-page visual checks. `.scratch/pdfw-allocation.md`. +2. Repo20 remains open; the retained-body counterexample is repaired source-only + (seven final max4MP/font +two original admitted requests samples <=57020KiB). + New pre-prune scheduling-window diagnostic now FAILS60992–62716KiB with + just one PIM request plus qpdf. Fix before claiming20 acceptance; use + `.scratch/parser-window.md`, not another post-parse free/capacity reduction. + Request compaction alone still failed59100KiB; large libpq I/O-cache recycling + at API request end was also needed. Do not reintroduce PNG strips or waive + the unchanged opt-in probe. Next: active dense parsing/qpdf overlap, other + metadata/catalog/codec amplification and native representative acceptance. + `.scratch/request-retention.md`; passing samples are NOT a global certificate. +3. Repo22 complete source-only: both APIs' shared summaries, source sites, + normalized routes/actors, SQLSTATE-only DB diagnostics and real dev capture. + Native LOCAL0 persistence/rotation and pre-API server failures are separate; + `.scratch/api-logging.md`. Continue remaining20, not historical logging work. +4. Tool13: actual affected manager browser identity/groups/list scope unknown; + no proven route defect. Never widen sequential access to hide the symptom. +5. Tool9 / repo14: owner-approved native Alpine/OpenRC target, proxy overwrite/ + backend isolation, DAM writer policy, DB/Redis allocations and coordinated + backup/restore/coexistence remain release gates. No maa-1 changes authorised. +6. Tool10 final review/publication blocked by9. No remote/PR URL invented. + +## Runtime safety + +Last verified runtime state (2026-11-17; recheck read-only if needed): + +- `signet-jpeg-loopback`:18087 and `signet-signatures-preview`:18090 return200. +- Old `signet-ticket11-verify`:8080 remains running, but host AND internal HTTP + checks timed out during ticket22. It started2026-11-12 with lighttpd PID1. + No cause or repair was established; it was left untouched. Do not describe it + as healthy, restart it incidentally or infer that the new diagnostics caused it. +- All three `signet-parser-window`, `-control`, `-repeat` stacks are stopped exit0; + instrumentation/holders/queues=0, no stopped processes, ordinary PIM restored. +- All four earlier `signet-logging-{red,check,final,final-r2}` stacks are stopped + exit0; logging SQL/Redis/syslog fixtures were cleaned. Images remain available. +- No test stack is an implicit replacement preview. PHP:8087 remains unrelated. + +Preserved `signet-jpeg-loopback` at127.0.0.1:18087 remains unchanged/HTTP200. +DO NOT invoke its PIM Resync: installed version STILL uses FLUSHDB. Metadata18, +PIM19, upload20, parser23, PDF-allocation21, writer-memory20, API-retention20 +and API-logging22 are NOT installed there. Any later upgrade needs +separate approval and coordinated API/browser/web-config/migration003 deployment +with verified DB/files/queues/config backups. Do not roll an old API over an +incomplete upload, or restore stale backups over newer user activity. + +Owned upload/PIM/parser investigation containers were stopped gracefully and +retained, not deleted. PDF-allocation21 containers are also stopped/retained: +final service stack graceful, idle native-test shell required SIGKILL fallback. +All four owned image-memory20 investigation containers are also stopped/retained +(gracefully). All five qpdf/retention investigation stacks also stopped/retained +with exit0; latest `signet-request-retention-final-r2` (temporary18110) is NOT a +replacement preview. Trigger/holder counts0; source/image manifests match88 files. +All three newer parser-window stacks also stopped exit0 after zero +instrumentation/holders, empty queues, normal PIM pools and no stopped processes +were verified. Preserved18087/18090 still return200. Preserve ticket11:8080, +signature preview18090 and the unrelated PHP:8087. Destructive fixture tests only on explicitly disposable +stacks, never preserved/shared services. Do not change host clock/known_hosts. + +## Durable evidence + +Private0700 directories, files0600; never commit/publish backups: +- `/Users/saikrupa/.local/var/signet-feature-backups/bounded-parsers-20261114T191422Z` +- `/Users/saikrupa/.local/var/signet-feature-backups/bounded-uploads-20261114T181856Z` +- `/Users/saikrupa/.local/var/signet-feature-backups/qpdf-image-strips-20261115T031645Z` + (name reflects rejected prototype; retained repair is API request/cache cleanup) +- `/Users/saikrupa/.local/var/signet-feature-backups/api-logging-20261116T170748Z` +- `/Users/saikrupa/.local/var/signet-feature-backups/parser-window-20261116T193934Z` + (UTC label; local work2026-11-17, unrepaired pre-prune window counterexample) + +Contain pre/post source/patch/status, source/image manifests, logs and synthetic +browser evidence. They are source backups, not runtime user-data backups. +Latest durable live evidence is under `~/.local/var/signet-work/`: +`parser-window-*.log`, `parser-window-product.sha256`, `parser-window-cleanup.sh`, +recovery comparisons, `partial-integration.tar` and `integration-registration.tar`. +`parser-window-backup-path` points at the latest private phase archive. Its +`after/source.tar` is refreshed for this handoff; `after/status` and full diff +include earlier dirty work, while `after/probe-only.diff` isolates the three +current diagnostic test files. Consult its private README before selective recovery. + +Old `/tmp` logs/screenshots are expendable and may disappear. Prefer the private +archives over `/tmp/signet-parser-final-*.log` or old browser evidence paths. +The recovery cause was not diagnosed; do not assume that moving/reading an old +`/tmp` path makes its missing files safe again. + +Host browser tests can reuse read-only Playwright Core at +`/private/tmp/minci-browser-check/node_modules/playwright-core/index.mjs` and +Chrome `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`. +These were earlier development facilities, not reverified in the latest +parser-window phase. Check availability and policy/approval before invoking; +no browser run or visual change is claimed for this diagnostic-only slice. +Old `/tmp/signet-ticket10-browser/node_modules/...` disappeared. No production +Node/browser dependency was added. Native packages/tooling remain unchanged.
diff --git a/.scratch/signature-collections.md b/.scratch/signature-collections.md @@ -0,0 +1,91 @@ +# Private signature collections — isolated implementation evidence + +Status: implemented and dev-verified, uncommitted on `feat/signature-collections` +in `/tmp/signet-roadmap-20261112/signatures` (base `9876b79`). The owner-approved +2026-11-14 follow-up integrated this into `feat/feature-first-roadmap` and upgraded +the preserved :18087 preview in place; see `preview-upgrade.md`. No production +rollout or remote publication. The evidence below records the initial isolated +implementation before that follow-up. + +## Model and implementation + +D30 / `docs/adr/0002-private-signature-collections.md`: organisation seals/logos +remain PIM image references into DAM. User originals are private immutable +labelled facsimiles, not DAM assets. One ready default; the signer chooses at +sign-off. An owned/enrolled UUID is recorded with the decision, including when +an old client omits the optional choice. Default changes never reinterpret it. + +Migration 002 keeps legacy username filenames/metadata and NULL-reference +historical decisions. New variants use UUID files, worker PNG decoding, byte +hashes, durable publication, and exact-reference validation before stamping. +Self/admin uploads share one helper. Metadata is bounded (32 ready/pending +variants, latest failed attempts within a 64-row response); originals are never +served by an API. Activation retry requeues the same ID and is idempotent. + +## Verified + +* Clean Alpine build, no compiler warning/error matches; JS/shell syntax and + `git diff --check` clean. +* Old-image collection red: `FAIL - enrolment must return an immutable variant reference`. +* Full E2E ends `all passed`: command/image/configurable-identity contracts, + sequential privacy, snapshots/corrections and collection/migration contracts. +* Migration repeated in temporary PostgreSQL DB: original metadata fingerprint + unchanged, legacy decision still NULL, multiple variants insert successfully. +* Collection contracts: owner/role/UUID/NUL/label validation; private 0600 files + unreadable by API UID; queued explicit/default choices remain fixed; damaged + chosen bytes fail closed and exact restoration/retry succeeds; old NULL + decisions retain legacy meaning after default changes; failed PNGs preserve + defaults; Redis LPUSH denial rolls back; quota, lost activation and duplicate + retry activate 32 variants with exactly one default. +* Retained render contract passes, including 30-second command hang, missing + original, queue failure and replay; browser progress failure/retry passes. +* Real-browser collection upload/default/picker/recorded-ID regression passes; + 32-row collection with an 80-byte unbroken label scrolls without horizontal + overflow. Both-page edit/proof/stamped/final plus audit/picker reviewed visually. + Latest browser document: `83fd5722-3cc8-4e39-bb29-2b4dbda83473`. + +## Dev restart investigation (tracker 15) + +Reproduced with SIGUSR1, without changing any host/VM clock. Even `--init` alone +fails: the shell exec'd lighttpd while its background signetd remained a direct +child. The stopped web server waits for that worker; terminating the worker +unblocked restart. Keep the startup shell as parent, with web and worker as +siblings, and trap shutdown for Redis save/PostgreSQL fast stop. Repeated +three-restart contracts pass while preserving the worker. Bootstrap copies +seeds nonoverwriting and retains existing config. + +A controlled same-container restart with custom signature/organisation PNG and +config sentinels preserved every document/signature/DAM/config file hash and +complete documents/doc_decisions/facsimiles/doc_events row fingerprints. +Sentinels were restored to their original synthetic bytes and another restart +passed. This was only the disposable test stack, not the user's container. + +## Artifacts and preview + +Product image: `6009232559c7ca6082c66bff36aa70086e4d5c135021c9c7c298f005e91865f2`. +Product C/UI/schema/bootstrap file hashes matched the built container; see +`/tmp/signet-signatures-final-source-hashes.txt`. + +Logs `/tmp/signet-signatures-final-{build,e2e,render,browser,progress}.log`; +visuals `/tmp/signet-signatures-final-browser/`; restart red +`/tmp/signet-signature-restart-red.log`; collection red +`/tmp/signet-collections-baseline-red.log`; persistence log/helper/fingerprints +`/tmp/signet-signatures-persistence*`. Retained fixture RSS sampling during +render/browser/progress peaked at 34632 KB, 263 samples; excludes PG/Redis and +is not production/native/aggregate-resource certification. + +Clean preview: `signet-signatures-preview`, http://127.0.0.1:18090, same verified +product image, fresh synthetic data. Manager/management has one legacy default; +My signatures and the three-restart health contract work. Verification stack +`signet-signatures-final` (:18089) and early stack `signet-signatures-test` +(:18088) are stopped/retained. Latest browser harness has identity reload and +32-row UI checks; it runs from the worktree and was also copied into the +verification container after the product image build. + +During this initial implementation the user's :18087 preview was not modified. +The later owner-approved upgrade of that same container, with all original data +preserved and real-backup restore/rollback rehearsed, is in `preview-upgrade.md`. +The preserved :8080 stack, unrelated PHP :8087, original dirty checkout, shared +services and maa-1 remain untouched. Native OpenRC/proxy/DAM-writer/production +backup/concurrency/resource gates remain tracker 9 / ticket 14; do not infer +production readiness from either local verification.
diff --git a/AGENTS.md b/AGENTS.md @@ -16,7 +16,9 @@ historical implementation plan. Podman is used **only** on the dev machine for testing. * Allowed: native C, `qpdf`, `pdfinfo`/poppler-utils, `lighttpd` (+`mod_webdav`, `mod_fastcgi`), PostgreSQL 16+, Redis, `kcgi`/`kfcgi`, - `hiredis`, `libpq`, `libpng`, `zlib`. JSON is **yyjson** (vendored, owner's + `hiredis`, `libpq`, `libpng`, `zlib`, **libcurl + OpenSSL libcrypto** + (owner-approved for optional detached RFC3161 evidence, 2026-11-19; + `docs/timestamps.md`). JSON is **yyjson** (vendored, owner's choice). `php-fpm`, `imagemagick`, `groff` are permitted by the original spec but deliberately unused — do not add them back without a reason. * Frontend: vanilla HTML/JS, no framework, no jQuery, no build step. Only @@ -41,7 +43,8 @@ historical implementation plan. against the proof visually. 4. **Clients never supply values, only references.** PIM text is resolved server-side from Redis (`HGET <org>:metadata <key>`); DAM refs are - validated relative paths; signer refs are validated usernames. + validated relative paths; signer refs are validated usernames. Facsimile + UUIDs must resolve to an enrolled variant owned by the deciding signer. 5. **Only `signetd` reads `sig_dir`.** `signet-api` must never open a signature file. Drafters receive `proof.pdf` and, after release, `final.pdf`; `stamped.pdf` requires signer access on that document or admin access. @@ -49,11 +52,12 @@ historical implementation plan. assigns one signer per party at submit. Parties sign strictly one after another. Each sign-off overlays the signer's enrolled facsimile onto the previous stamped copy. Release happens in the worker after the last sign-off. -7. **Facsimiles are enrolled at first signing.** A signer without an enrolled - facsimile draws or uploads one in the browser; it is stored and reused. The - worker is the sole reader of enrolled facsimiles (`sig_dir`). An admin may - also place a facsimile for a signer (file at `/var/lib/signatures/<user>.png`, - mode 0600). +7. **Facsimiles are private, immutable user-owned variants (D30).** A signer + enrols before or at first signing and chooses an enrolled variant at sign-off. + Record its ID in the decision; defaults affect future choices only. The + worker alone reads originals (`sig_dir`); admin enrolment adds a variant + rather than replacing one. Preserve legacy user-named files/history during + migration. See `docs/adr/0002-private-signature-collections.md`. 8. **Stamping produces only one cached copy per revision.** At submit, imprints are flattened once and stored as JSONB placement data. Each sign-off reads this placement and overlays a facsimile. PIM is read only at submit; a @@ -119,10 +123,12 @@ sleep 6 && podman exec signet /src/test/e2e.sh # must end with "all passe * Portable files can be syntax-checked on macOS: `cc -std=c99 -D_DARWIN_C_SOURCE -Isrc -fsyntax-only src/{conf,util,ttf}.c`, `node --check www/app.js`. -* **Error logging:** All API failures (database errors, validation failures, - 4xx/5xx responses) are logged to stderr and syslog (facility LOCAL0). - In dev, all errors appear in `podman logs signet`. In production, configure - syslog to capture `LOCAL0.warning` and above for persistent logs. +* **Error logging:** API-emitted 4xx/5xx use shared `send_err()`; its summary + logs normalized route, validated actor, status and source site to stderr and + LOCAL0 (warning for 4xx, error for 5xx). Keep private values/raw backend errors + out of diagnostics; use SQLSTATE. Dev kfcgi must retain stderr (`-d`). For + capture regressions/native logging boundaries, read `.scratch/api-logging.md`. + Persistent native LOCAL0.warning capture/rotation remains an admin gate. Extend `test/e2e.sh` with every API behaviour change; it is the regression suite. After any change to `render.c`, `pdfw.c`, `ttf.c` or `fitText`, also do
diff --git a/CONTEXT.md b/CONTEXT.md @@ -54,7 +54,9 @@ is in `HANDOFF.md`. **Placement**: the rectangle a signer's facsimile occupies inside its zone. Automatic (largest fit that keeps the image's proportions) when the signer has an enrolled facsimile; chosen by hand otherwise. -**Signature facsimile**: the image of a person's signature. Not a cryptographic signature. **Enrolled** once a user has signed for the first time or an admin has placed it; reused on later documents. _Avoid_: signature (alone), e-signature +**Signature facsimile**: a labelled image of a person's signature, owned by that user. Not a cryptographic signature; once **enrolled**, it is reused without replacing its original image. _Avoid_: signature (alone), e-signature + +**Signature collection**: a user's enrolled facsimiles, with one **default facsimile** when any are ready. The signer chooses a facsimile at sign-off; changing the default affects future choices, never an already recorded sign-off. **Proof**: the drafter's flattened copy: imprints, no facsimiles. @@ -68,6 +70,8 @@ is in `HANDOFF.md`. **Document date**: the date of first submit. Fixed with the serial; the `date` imprint and the serial's date part both come from it, so a resubmit on a later day changes neither. +**External timestamp**: optional, validated detached RFC3161 evidence that the unchanged released PDF existed by a timestamp authority's stated time. It is separate from Signet's server-recorded sign-off/release times and never controls release. _Avoid_: PAdES B-T, certificate signature, independently verified sign-off time + **Event log**: the complete history of a document — created, each submit and resubmit, every decision with its reason — across all revisions. Printed in full on the audit page. _Avoid_: timeline, activity **Audit page**: the page(s) appended at release: document id, serial, title, organisation, the full event log, and the SHA-256 of the pages before it. The body pages carry no trace of corrections; the audit page is where the history shows (D26). _Avoid_: certificate, audit log (DocuSeal's word)
diff --git a/Containerfile b/Containerfile @@ -1,6 +1,6 @@ # Dev/test image only: production is bare-metal Alpine + OpenRC (see README). FROM alpine:3.22 -RUN apk add --no-cache build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev \ +RUN apk add --no-cache build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev curl-dev openssl-dev \ postgresql16 postgresql16-contrib redis lighttpd lighttpd-mod_webdav \ qpdf poppler-utils font-dejavu curl jq su-exec WORKDIR /src
diff --git a/HANDOFF.md b/HANDOFF.md @@ -1,7 +1,8 @@ # HANDOFF.md — state of the code and the decisions behind it Documentation reconciled against source and Git history on 2026-11-10; -workflow implementation and verification updated 2026-11-12. +workflow implementation and verification updated 2026-11-12; +optional detached timestamp source checkpoint verified 2026-11-19. 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 @@ -57,6 +58,21 @@ Tickets12/13 now add frozen revision content and fail-closed identity tests; see their notes. This is not native production acceptance: proxy/resource/native verification below remains mandatory. +**Detached timestamp checkpoint (2026-11-19, source/test only):** optional +libcurl/libcrypto RFC3161 evidence over unchanged `final.pdf`, with separate +server sign-off/release and validated TSA time; four total release-anchored +attempts within one hour, never gating release. Disabled without explicit HTTPS +endpoint/trust and operator-installed system-cron scheduling. Final disposable +r5 warning-clean build, full E2E (including local HTTPS negatives, actual crash, +concurrent-runner exclusion, real cron, independent release, migration/access/ +hash checks), incremental/staged install and101 source hashes passed. Timestamp +fixture sampled39784KiB; subsequent32-document A5-only probe33660KiB. These are +representative samples, not native/global resource acceptance. No live TSA, +browser acceptance, preview upgrade or deployment; the optional existing browser +cache is missing, and no dependency was reinstalled. See +`.scratch/detached-timestamps.md` and `docs/timestamps.md`. Ticket20 remains OPEN; +timestamp product edits are later than its restored final22 baseline. + **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 variants beyond the RGB fixture, TTF fonts other than DejaVuSans, rotated or @@ -102,6 +118,8 @@ unrelated changes; inspect `git status` for the live inventory. | D27 | Statuses renamed to match the vocabulary: `DRAFT, PENDING, CORRECTION_REQUIRED, DISAPPROVED, RELEASED`. `CORRECTED` becomes a `RESUBMITTED` event, not a status | Owner 2026-09-19, on recommendation. Replaces D4 | | D28 | **Templates are edited and retired, never silently deleted**; an admin may delete a template only after every document has been **unlinked** from it. **Series are retired, never deleted or re-patterned** once a serial has been issued | Owner 2026-09-19. Documents are self-contained copies, so unlinking loses nothing but the back-reference | | D29 | **Latin script only** for now (no shaping). Imprint shapes: **rectangle and circle** (circle clips a round seal); `poly` dropped | Owner 2026-09-19 | +| D30 | **Private signature collections** (`docs/adr/0002`): labelled immutable facsimiles per user, one ready default, signer chooses at sign-off; the decision pins its exact owned/enrolled ID. Organisation seals remain PIM/DAM assets. Legacy files and NULL-reference decisions retain their meaning | Owner requested multiple signatures per user and organisation-owned stamps/assets, 2026-11-13; extends D20, avoids mutable-default/replacement races | +| D31 | **Detached external timestamps** (`docs/adr/0003`): optional validated RFC3161 evidence over the unchanged released PDF, separate TSA time, four total attempts within one release-anchored hour; failures never control release. libcurl + OpenSSL libcrypto, short-lived system-cron runner; explicit TSA trust, no PDF signing/key custody | Owner approved timestamp-only cushion and both libraries, 2026-11-19; not PAdES B-T, independently verified sign-off time, identity or legal qualification. Existing D18/D20/D26 behavior unchanged | ## 3. Map of the code (2026-09-19 model) @@ -243,14 +261,56 @@ differ). The client rasterises every page to 1000 px natural width. *browser* would still show the OTF, so edit ≠ proof in that case. Consider filtering `/api/dam` fonts through `ttf_load`. 10. `GET /docs` caps at 200 rows, no pagination/search. -11. Uploads are held in memory by kcgi (limit 32 MB in code, 34 MB in - lighttpd). With 2–4 API workers this is the main threat to the RAM budget; - consider lowering the cap. +11. Source-only upload/parser repairs retain32MiB PDF capacity via256KiB + application chunks. API/PIM bodies are capped before kcgi at16KiB except + multipart/form-data at1100KiB. Two900000-byte dense-form requests had + exceeded120MiB aggregate RSS despite404 responses; tracker23 repairs this + pre-parser gap. Large logical fields use multipart. Three near-cap nested + multipart requests plus dense query/cookies peak50052KiB in the fixture; + this is NOT mixed renderer/native certification. Native writer compression + now uses16KiB output chunks, reducing maxRGB+font fixture32728→16216KiB. + The72240KiB retained-request counterexample is now repaired source-only: + both APIs discard unused/repeated fields and recycle large libpq I/O caches + at request end. Seven final mixed samples peak57020KiB with exact pixels/font + bytes.20 remains OPEN for other overlaps/cardinality/native acceptance; this + is not a whole-runtime certificate. See `.scratch/request-retention.md`, + `.scratch/image-memory.md` and `.scratch/bounded-parsers.md`. + New2026-11-17 test-only diagnostic reproduces60992–62716KiB with just one + unpruned PIM request overlapping qpdf. This DIFFERENT budget blocker is NOT + repaired; `.scratch/parser-window.md`. Product source remains final22; + parent20 requires a pre-materialization/coordination repair, not lower caps. + A2026-11-18 parent-only admission experiment was rejected/reverted: reverse + worker-first order still failed59136/59296KiB with a buffered kcgi child. + Product source remains final22. Read `.scratch/parser-coordination.md` before + another gate; request-first success alone is insufficient. + Owner-provided typical profile is small single-page A5 text PDFs. A synthetic + 32-document signing/release batch samples33528KiB (warm33952KiB), full E2E + passes; `.scratch/a5-workload.md`. This is representative sequential evidence, + not a waiver of the above failures or native acceptance. 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. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker, `blob:` images, inline `style` attributes set via `h()`). +14. PIM resync no longer uses `FLUSHDB` in integration source (tracker19). + Scoped atomic reconciliation, canonical type/deletion mirroring, queue/ + foreign-key preservation, cache-error recovery and two-worker ordering pass + disposable/full E2E/render tests. See `.scratch/pim-resync.md`. This fix is + NOT installed on preserved :18087: do not invoke its old Resync action. + Shared namespace allocation/native acceptance remain open. +15. PDF writer allocation failures repaired/dev-verified in tracker21: + deterministic tests reproduced content/font leaks and persistent allocation + retry in PDF open (not cprintf). Temporary realloc ownership, unpublished + font cleanup, failed-open cleanup and failed-close finalisation guards now + pass19-point transient/persistent injection, full E2E/render and both-page + browser visual checks. Source-only; `.scratch/pdfw-allocation.md`. +16. Tracker22 repaired/dev-verified source-only2026-11-16: shared `send_err()` + logs every API-emitted4xx/5xx with normalized route, validated actor, status + and source site; backend diagnostics use SQLSTATE/operation, not raw values. + Dev foreground kfcgi preserves stderr, including after pool/container restarts. + Actual container capture and temporary LOCAL0/privacy regressions pass. + `.scratch/api-logging.md`; pre-API errors and persistent native capture remain + separate deployment gates. No preserved preview was upgraded. ## 5. Completed tasks (Tasks 1–9) @@ -283,6 +343,12 @@ found in the current source. ## 7. Next steps +Latest session resume/safety checklist: `.scratch/session-handoff.md` (2026-11-17). +The integration worktree was recovered from final22 into a durable directory; +use the path in that checklist, not the now-incomplete historical `/tmp` tree. +Owner reordered remaining work22 →20 →rest;22 is now source-only complete. +Continue20's remaining overlap/cardinality/native gates before production work. + **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 @@ -312,8 +378,38 @@ The implementation scopes and acceptance criteria are in Local guards limit save/submit JSON before parse/clone and bound external commands to30s with group cleanup/Linux direct-child parent-death protection; unit, actual hang/retry, fixture suites and browser checks pass. HTTP buffering, - other parse paths, decoded assets and aggregate/service-level resources remain - unbounded by those guards and require further work. + decoded assets and aggregate/service-level resources remain unbounded by + those guards and require further work. Follow-up18 now bounds decision + placement and stored-layout parsing using the same1 MiB byte policy; exact + limits, multibyte legacy rejection and correction recovery pass full E2E/ + render tests. This source-only change is NOT installed on preserved :18087. + Resource audit and remaining technical blockers20/22: + `.scratch/resource-audit.md`. Tracker21 allocation-failure repair now passes + deterministic fault injection and renderer/browser acceptance in source; + `.scratch/pdfw-allocation.md`. NOT installed on preserved previews. Follow-up19 also repairs global PIM Redis + flushing and ordered mirror publication in source, with full regression + evidence in `.scratch/pim-resync.md`. Neither fix is installed on :18087. + Follow-up20 now repairs the concrete upload counterexample in source:32MiB + PDF files use256KiB application chunks; all API/PIM prefixes have a pre-kcgi + 1100KiB request cap. Two max files plus near-cap ignored fields/hash checks + give29,660KiB sampled peak versus182,624KiB before repair. Migration003, + owner/readiness/retry/failed-commit recovery, full E2E/render and browser + regressions pass. See `.scratch/bounded-uploads.md`. NOT installed :18087; + API/browser/config/migration must move together on a separately approved + upgrade. Tracker20 remains open for parser/image/font/render aggregation + and native acceptance; this is not a whole-runtime RSS certificate. + Tracker23 additionally repairs dense form amplification (122884KiB for two + 900000-byte requests): non-multipart bodies now have a16KiB pre-kcgi cap, + multipart keeps1100KiB/1MiB logical fields. Three heavily populated multipart + API/PIM requests with query/cookies peak50052KiB; both32MiB uploads, full + E2E/render and real browser signing/upload tests still pass. Source-only, + NOT installed :18087. `.scratch/bounded-parsers.md`; other20/22 work stays open. + Native writer image/font compression now streams with exact decoded-byte, + fault and two-page visual tests; fixture32728→16216KiB. Subsequent API request + compaction and large libpq-cache recycling repair the retained-request mixed + case (seven final samples <=57020KiB). The strip-rendering prototype was + rejected/reverted.20 stays open for other overlaps/cardinality/native gates. + Latest source/evidence: `.scratch/request-retention.md`; no preview install. Owner inputs, remaining work and evidence: `.scratch/roadmap/ticket-14.md`. Image-reader review also repaired opaque JPEG snapshots and matched image interpolation to the browser; RGB byte-preservation and both-page visual @@ -326,11 +422,24 @@ historical completed tickets do not substitute for fresh evidence. ## 8. Dev environment facts -* Latest isolated verification: image `signet-jpeg-final`, container - `signet-jpeg-loopback` at `http://127.0.0.1:18087`. Earlier :8087 conflicted - across IPv4/IPv6 with another local service; that service was not touched. - Our older test stacks are retained stopped, except preserved ticket11 :8080. - Throw-away DBs and explicit identities; no production/maa-1 services changed. +* Preserve the user's `signet-jpeg-loopback` at `http://127.0.0.1:18087` + (image `signet-jpeg-final`), its documents and the ticket11 :8080 stack. + Earlier :8087 conflicted with an unrelated service; that service is untouched. + Owner-approved in-place signature-collection upgrade completed 2026-11-14; + original records/files/config/Redis preserved, backup/restore rehearsed. + See `.scratch/preview-upgrade.md`. Do not run destructive contracts or + reinitialise the user's preview. +* Signature collections (D30) are implemented/dev-verified and integrated, + uncommitted in `feat/feature-first-roadmap` and `feat/signature-collections`. Clean synthetic preview: + `signet-signatures-preview` at `http://127.0.0.1:18090`. Verification stack + :18089 and early :18088 are stopped/retained. Full evidence, source/image + hashes and scope: `.scratch/signature-collections.md`. No production/maa-1 + services or the original checkout changed; commits/publication are pending. +* Dev startup now keeps worker and lighttpd as siblings, not an exec'd web + server inheriting the worker. Three graceful restarts and nonoverwriting + seed/config persistence pass in disposable stacks. The fix is now installed + in :18087 too; graceful and full-container restart/preservation checks pass. + `--init` alone was insufficient. Fixture RSS samples do not certify native peak resource safety. * Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created for this project; image `signet-dev`; a container named `signet` may still
diff --git a/Makefile b/Makefile @@ -1,5 +1,5 @@ # signet: builds on Alpine with -# apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev +# apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev curl-dev openssl-dev CC ?= cc CFLAGS ?= -O2 -pipe CFLAGS += -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra -Isrc -Ivendor @@ -15,9 +15,9 @@ LIBS_CGI = -lkcgi -lz COMMON = build/conf.o build/util.o build/db.o build/yyjson.o build/sha256.o PDF = build/pdfw.o build/ttf.o build/render.o build/snapshot.o -all: build/signet-api build/signetd build/pim-api +all: build/signet-api build/signetd build/pim-api build/signet-timestamp -build/signet-api: build/signet-api.o build/http.o $(COMMON) $(PDF) +build/signet-api: build/signet-api.o build/http.o build/upload.o $(COMMON) $(PDF) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS_CGI) $(LIBS_DB) $(LIBS_PDF) build/signetd: build/signetd.o $(COMMON) $(PDF) @@ -26,6 +26,14 @@ build/signetd: build/signetd.o $(COMMON) $(PDF) build/pim-api: build/pim-api.o build/http.o $(COMMON) $(CC) $(LDFLAGS) -o $@ $^ $(LIBS_CGI) $(LIBS_DB) -lm +build/signet-timestamp: build/signet-timestamp.o build/timestamp.o build/conf.o build/util.o build/db.o build/sha256.o + $(CC) $(LDFLAGS) -o $@ $^ $(LIBS_DB) $(shell pkg-config --libs libcurl libcrypto) + +build/signet-timestamp.o: src/signet-timestamp.c src/timestamp.h + +build/timestamp.o: src/timestamp.c src/timestamp.h | build + $(CC) $(CFLAGS) $(shell pkg-config --cflags libcurl libcrypto) -c -o $@ $< + build/%.o: src/%.c | build $(CC) $(CFLAGS) -c -o $@ $< @@ -46,7 +54,8 @@ build: install: all install -d $(DESTDIR)$(PREFIX)/libexec $(DESTDIR)$(PREFIX)/sbin \ $(DESTDIR)$(WWWDIR)/vendor $(DESTDIR)$(PIMWWW) $(DESTDIR)/etc/signet - install -m 0755 build/signet-api build/pim-api $(DESTDIR)$(PREFIX)/libexec/ + install -m 0755 build/signet-api build/pim-api build/signet-timestamp $(DESTDIR)$(PREFIX)/libexec/ + install -m 0644 etc/timestamp.cron.example $(DESTDIR)/etc/signet/ install -m 0755 build/signetd $(DESTDIR)$(PREFIX)/sbin/ install -m 0644 www/index.html www/app.js www/style.css $(DESTDIR)$(WWWDIR)/ install -m 0644 www/vendor/*.js $(DESTDIR)$(WWWDIR)/vendor/
diff --git a/README.md b/README.md @@ -2,7 +2,8 @@ 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. +Optional detached timestamps use libcurl + OpenSSL libcrypto. No containers or +language runtimes in production. **Development status:** sequential signing, worker-owned release and render-job recovery have fresh isolated-development tests; see @@ -39,9 +40,27 @@ 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. -**Facsimile enrolment:** A signer without an enrolled facsimile completes -enrolment at first signing (draw in browser, or upload a PNG). The facsimile -is kept and reused. An admin may also place one directly in `/var/lib/signatures/<user>.png`. +**Signature collections:** Signers can draw/upload labelled PNG facsimiles in +**My signatures**, or enrol their first one when signing. The first ready image +becomes the default; adding another never replaces it. Choose the signature in +the document's **Signature to use** picker, or use **Use as default** for future +sign-offs. Each decision records its chosen ID, so later default changes cannot +alter queued work. Uploads are at most 1 MiB; up to 32 ready/pending variants per +user. Invalid PNGs are reported without displacing an existing default. If an +activation is pending after a queue interruption, **Retry activation** requeues +the same immutable reference (`POST /api/me/facsimile/retry`); it does not upload +or replace an image. + +Originals live at `/var/lib/signatures/<UUID>.png` (0600, worker only). Existing +`<username>.png` files and enrolled metadata remain supported by migration; +never overwrite them once enrolled. An admin can add a labelled variant for a +user with `POST /api/facsimiles` (`user`, `label`, `file`). No API serves original +signature images. Enrolled variants cannot be replaced/deleted; add a new one. + +Organisation seals, stamps and logos remain separate PIM image attributes +(`seal`, `accounts_stamp`, `logo`, etc.) referencing DAM-relative files. Nested +paths such as `organisations/ACME/seals/company.png` are supported; folder names +organise files; they do not provide access control. Signature originals must not go in DAM. Serial numbers come from a **series** (`SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}`, counter restarts daily). The number is allocated on first submit and never @@ -49,6 +68,18 @@ changes across corrections. `serial` and `date` imprints print it anywhere on the page; a **template** (base PDF + layout + route + series) makes that repeatable. +## Optional external timestamps + +Released documents can obtain detached, validated RFC3161 evidence without +changing the PDF or blocking release: four total attempts within one hour. +**Signed at** remains Signet's server-recorded sign-off time; **Externally +timestamped at** is the separately verified TSA time. A later timestamp proves +existence by its issuance, not the earlier sign-off, identity or consent. +This is **not PAdES B-T** or a certificate-based PDF signature. It is disabled +without a configured HTTPS endpoint and explicit TSA trust; scheduling uses the +existing system cron facility, not another resident Signet daemon. +See [setup, evidence download, limits and checks](docs/timestamps.md). + ## Imprints `<area shape coords data-type data-ref …>` in the page's `<map>` is the state. @@ -81,7 +112,7 @@ but the trusted proxy boundary, DAM writer policy and native resource safety still require deployment verification. ```sh -apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev \ +apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev curl-dev openssl-dev \ lighttpd lighttpd-mod_webdav postgresql16 redis qpdf poppler-utils make && make install @@ -89,13 +120,14 @@ addgroup -S signet adduser -S -G signet -H signet # API adduser -S -G signet -H signetd # worker install -d -o signet -g signet -m 2770 /var/lib/signet -install -d -o signetd -m 0700 /var/lib/signatures # <username>.png, 0600 +install -d -o signetd -m 0700 /var/lib/signatures # <UUID>.png (legacy <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 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;" + GRANT SELECT ON doc_decisions TO signetd; GRANT SELECT, UPDATE ON facsimiles TO signetd; + GRANT SELECT, INSERT, UPDATE ON document_timestamps 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 @@ -114,12 +146,18 @@ identity and maps configured groups to roles. ```sh podman build -t signet-dev . -podman run --rm -d --name signet -p 8080:8080 signet-dev +podman run -d --init --name signet -p 127.0.0.1:8080:8080 signet-dev podman exec signet /src/test/e2e.sh # API + worker end to end podman exec signet /src/test/e2e.sh render-contract # failure/replay/queue regression open http://localhost:8080 # isolated dev only; explicit identity required ``` +Use `--init` for this multi-process dev stack to reap orphan processes. The +startup shell keeps worker and lighttpd as siblings: lighttpd must not inherit +the long-lived worker as its child and wait for it during graceful restart. Existing +containers retain their data on restart; demo seeds/config do not overwrite +existing files. Removing a container still requires a backup/persistence plan. + Development has no implicit admin identity or authentication-server dependency. For browser testing, set an explicit identity in the browser console and reload: @@ -133,12 +171,39 @@ configurable identities/roles. It restarts test API processes and must run only in the isolated dev container. Production must overwrite forwarded headers and prevent direct backend access; the browser dev selector is not authentication. +### Failure logs + +API-emitted 4xx/5xx write a failure summary to stderr and syslog LOCAL0: method, +normalized route, validated actor, status, and `site=function:line`. UUIDs and +unknown path components are redacted; bodies, tokens, raw URLs and backend error +text are omitted. Database diagnostics retain SQLSTATE. Resolve a site against +the matching source/build. Successful requests are quiet. + +Development uses foreground kfcgi supervisors (`-d`), so `podman logs signet` +actually captures API stderr, including without `/dev/log`. On an explicitly +disposable stack, run the real capture regression where the Podman CLI works: + +```sh +SIGNET_LOGGING_TEST_DISPOSABLE=yes sh test/logging-dev.sh disposable-container +``` + +The test temporarily installs a syslog receiver and isolated failure fixtures; +it refuses to replace an existing `/dev/log`. The full E2E includes its native +API/syslog checks. See `.scratch/api-logging.md` for scope and evidence. +Production must configure and verify persistent LOCAL0.warning-and-above capture, +permissions and rotation. Web-server/proxy rejections before API dispatch and +PostgreSQL's own logs are separate; native/OpenRC acceptance remains open. + +### Browser regressions + 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 +PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/upload-browser.mjs +node test/upload-client.mjs # standalone browser-helper contract; development only ``` Set `CHROME_PATH` for a non-default Chrome location and `SIGNET_URL` for a server @@ -165,19 +230,33 @@ identity headers; never run them against production. Frozen assets total at most16MiB per revision; imprint text including prefix is limited to1023 UTF-8 bytes. Missing/damaged inputs fail closed; restore exact verified bytes/permissions rather than replacing them from the live DAM. +* **PDF files still accept up to32MiB.** The browser uses authenticated256KiB + application-level chunks; incomplete drafts cannot be read, edited or submitted. + Exact retries never replace acknowledged bytes. Before kcgi buffering, API/PIM + bodies are capped at16KiB, except multipart/form-data at1100KiB. Large JSON/PNG + fields must use multipart (for curl: `--form 'json=<layout.json'`); large PDF + clients must use the chunk protocol in `.scratch/bounded-uploads.md`. This + prevents dense URL-encoded/plain-text forms amplifying per-field allocations; + tests/evidence are in `.scratch/bounded-parsers.md`. Small multipart uploads and + template creation remain supported; DAM/WebDAV's transport limit is unchanged. + Install migration003, API/browser and lighttpd changes together; see the upgrade + precautions in `sql/migrations/README.md`. This source change is not installed + on the preserved development preview. * **Layout metadata is bounded.** Document-save JSON accepts at most1MiB; submit also rejects stored layout/route exceeding1MiB before snapshot cloning. - This is independent of the32MiB PDF-upload limit and is not a whole-runtime - memory bound. + Multipart transport overhead counts toward the separate HTTP cap. These are + not whole-runtime memory bounds. * **External commands have a deadline.** pdfinfo/qpdf must finish within30s; timeout kills the command group. Worker jobs record a retryable render failure; - API PDF validation fails without accepting the upload. + callers fail closed when a required command does not complete successfully. + PDF creation checks its header; it does not run pdfinfo on the uploaded body. Linux also kills the direct command child when its API/worker caller dies. This is not a memory/CPU quota or whole-service crash-containment guarantee. `sh test/command-contract.sh` runs the standalone development regression. -* **Resource/deployment acceptance remains open.** Fixture RSS is not a native - peak-load certificate. Concurrent buffered uploads, rendering children, - image/font decoding and shared database impact require containment/measurement - before production or coexistence with other mission-critical services. +* **Resource/deployment acceptance remains open.** The two-max-file upload + counterexample is locally repaired, not a native peak-load certificate. Parser + amplification, rendering children, simultaneous image/font decoding and shared + database impact still require containment/measurement before production or + coexistence with other mission-critical services. * Rotated source pages are handled by swapping the page size; unusual CropBox offsets are left to qpdf's overlay fitting.
diff --git a/docs/adr/0002-private-signature-collections.md b/docs/adr/0002-private-signature-collections.md @@ -0,0 +1,24 @@ +--- +status: accepted +date: 2026-11-13 +--- + +# Private user facsimiles are immutable variants, not a replaceable image + +The owner requested organisation-owned seals/assets and multiple signatures per +user. Organisation image attributes remain PIM references into the DAM; a user's +signature collection remains private to the signing worker, never in the DAM. + +An enrolled facsimile has a stable ID, label and immutable image. One ready +facsimile is the default; the signer can choose another at sign-off. The API +records that exact owned/enrolled ID with the decision, rather than asking the +worker to look up whichever image is the default later. Changing the default +or adding a variant must not change queued work or any previously signed copy. +The drafter assigns a signer to a party, not a signature image to a document. + +Legacy user-named files/metadata remain readable, and decisions without an ID +retain their legacy meaning even after the user changes defaults. New files +use private UUID names; PNG decoding, byte hashing and publication belong only +to the worker. Replacing/deleting enrolled variants is deliberately not exposed: +add a new variant instead. This extends D20 without changing the sequential +route or submit-time organisation snapshot model.
diff --git a/docs/adr/0003-detached-release-timestamps.md b/docs/adr/0003-detached-release-timestamps.md @@ -0,0 +1,5 @@ +# Detached evidence never controls document release + +Keep Signet's existing sign-offs, facsimiles and released PDF unchanged; optionally obtain a validated RFC3161 response over that final PDF's SHA-256. The owner chose timestamp-only evidence rather than certificate-based PDF signing/PAdES or personal-key custody: an external timestamp proves existence by the TSA's time, not identity, consent or an earlier server sign-off time. + +A short-lived system-cron job uses the approved libcurl and OpenSSL libcrypto libraries, explicit TSA trust and a durable four-attempt budget anchored to release, ending after one hour. No HTTPS runs in the signing/rendering worker; failures never undo sign-offs or gate release. The detached response and separately labelled time are available only to users authorized for the released document. No new resident service, automatic provider enrollment, PDF modification, indefinite retry, or online revocation/long-term archival system is introduced.
diff --git a/docs/timestamps.md b/docs/timestamps.md @@ -0,0 +1,158 @@ +# Optional external timestamps + +Signet still records server-authenticated sign-offs and facsimiles, not +certificate-based PDF signatures. Optional detached RFC3161 evidence confirms +that the **unchanged released PDF** existed by a timestamp authority's time. +It does not independently establish an earlier sign-off time, signer identity, +consent, Indian DSC/eSign recognition or any other legal qualification. +It is **not PAdES B-T**; PDF readers will not show a PDF digital-signature panel. +The original release/audit behavior is unchanged. + +## Enable deliberately + +This is source/disposable-development verified, not production deployment +acceptance. Do not upgrade a production or preserved preview without approval. + +1. Back up coordinated database, document files, configuration and trust bundles. + Stop writers and apply `sql/migrations/004-detached-timestamps.sql` as database + owner **before installing the new API**, even if timestamps will be disabled. + Fresh installs use `sql/schema.sql`; grant `signetd` SELECT/INSERT/UPDATE on + `document_timestamps` as shown in the install guide. No old PDF/sign-off is + rewritten or backdated by the migration. +2. Build with `curl-dev` and `openssl-dev`. The timestamp executable uses + **libcurl and OpenSSL libcrypto**; it does not launch curl/openssl or require + either command-line executable in production. Keep the platform's HTTPS CA + bundle available. Other Signet binaries do not link the timestamp module. +3. Independently choose an HTTPS RFC3161 endpoint and provision its approved TSA + signing trust anchors in a local PEM file readable by `signetd`. Neither the + endpoint nor trust is selected/downloaded automatically. Configure: + + ```ini + timestamp.url = https://your-selected-authority.example/timestamp + timestamp.ca_file = /etc/signet/tsa-trust.pem + timestamp.tls_ca_file = + ``` + + The first two values enable attempts. The last is normally empty: HTTPS uses + platform trust, independently of the TSA signing trust file. A private test + endpoint can use a separate explicit HTTPS trust bundle there. Keep trust + files/configuration administrator-owned and non-writable by service users; + do not put private keys or signature images in them. No provider account or + private signing key is required by this feature. +4. Install `etc/timestamp.cron.example` in **signetd's user crontab**, using the + established system cron service and the actual installation prefix. Preserve + existing user-crontab entries; do not blindly replace the whole crontab. + Confirm system cron runs and captures worker stderr/syslog. Example entry: + + ```cron + * * * * * /usr/local/libexec/signet-timestamp + ``` + + A supervised manual invocation of that executable (with optional `-c PATH`) + uses the same persistent budget, not a new retry window. There is no new + resident Signet service. Installing the example file alone does not schedule + anything. Leave the endpoint/trust unset and do not schedule it to stay off. + +Only the SHA-256 imprint, fresh random nonce and protocol fields go to the TSA, +not PDF contents, names or facsimiles. Network timing and the digest can still +be correlated; timestamping is an explicit external network dependency. +HTTPS certificate/hostname verification is required; redirects and proxies are +disabled. Replies are limited to 65,536 bytes. Each HTTPS operation has at most +10 seconds (or the remaining window), with at most 3 seconds for connection. + +## Four attempts, one release-anchored hour + +The cron runner discovers recent released documents without changing release. +Attempt slots are approximately the first scheduled run after release, then +release +5, +20 and +55 minutes. Late runs keep the original deadline; at least +one minute separates rescheduled attempts when a slot was missed. There are +**four total attempts**, not four retries, and no attempt after release +1 hour. +An offline/overloaded scheduler can make fewer attempts; there is no guarantee +that all four occur. Old releases are never put into a fresh one-hour window. + +The database records/consumes each attempt before hashing/network I/O, so a +crash also consumes its slot. A session advisory lock serializes overlapping +runners; no document row remains locked during HTTPS. The runner spaces its +requests by at least one second, processes at most 20 jobs per invocation and +stops starting jobs after approximately 20 seconds. A current bounded operation +can finish after that invocation budget. One-hour eligibility is independently +checked before HTTP and when storing successful evidence. + +The on-disk final PDF must still hash to the released revision's recorded hash. +A response succeeds only after full DER parsing and OpenSSL verification of +requested SHA-256 imprint, nonce/version, signature, certificate chain/validity +and timestamping EKU against the explicitly configured trust. The CMS signer +must use SHA-256, SHA-384 or SHA-512; legacy SHA-1 evidence is rejected even if +the library can verify it cryptographically. Unverified, +malformed, rejected or late evidence is not advertised or downloadable. +There is no online OCSP/CRL fetching, revocation-status guarantee, archival +renewal or long-term-validation claim; trust provisioning/updates and later +independent assessment remain operator responsibilities. + +## What users see and download + +Document details keep status `RELEASED` regardless of timestamp outcomes: + +- **Signed at**: last sign-off of the current revision, from Signet's server. + Individual parties' decision times remain in the existing route/history. +- **Released**: the existing server release time. +- **Externally timestamped at**: the validated TSA time, never copied from a + server time or displayed before verification. +- **Pending**, **unavailable**, or **not requested**: separate timestamp state, + never a replacement signing/release status. Pending expires at the release + deadline; enabling the scheduler later cannot revive an expired window. + Without a stored record, a configured recent release is pending, a configured + expired release is unavailable, and a disabled feature is not requested. + Previously stored outcomes remain visible even if configuration is disabled. + +The pending view has an explicit status-refresh button, not an hour-long poll. +Authorized users can download `GET /api/docs/<UUID>/file/timestamp` as +`timestamp.tsr`, MIME `application/timestamp-reply`. Authorization is the same +as for that document's final PDF. This is the **complete RFC3161 response**, +not a raw CMS token; it is bound to the current released revision and PDF hash. +No original facsimile endpoint or new access grant is introduced. + +Keep `final.pdf`, the response and the relevant public trust/chain material +with ordinary coordinated backups. The evidence bytes live in PostgreSQL; +`GET /api/docs/<UUID>` exposes `signed_at`, `timestamp_status`, +`timestamp_attempts` and `timestamped_at`, not a replacement PDF or retry API. +On a separate verification machine with the OpenSSL command-line tools already +available, a full-response check can use: + +```sh +openssl ts -verify -in timestamp.tsr -data final.pdf -CAfile tsa-trust.pem +``` + +Independent verification needs the appropriate trust/chain and a deliberate +validation policy. Do not silently treat any certificate embedded in a response +as a trust anchor. Changing PDF bytes breaks this evidence. Keep its original +hash and bytes; do not append the token/audit note to the released PDF. + +## Development checks + +Only explicitly disposable stacks; these create synthetic documents/decisions +and isolate synthetic released-document evidence from other fixture jobs: + +```sh +podman exec signet sh /src/test/e2e.sh timestamp-contract +podman exec signet env SIGNET_TIMESTAMP_TEST_CRON=yes SIGNET_TIMESTAMP_TEST_RSS=yes \ + sh /src/test/e2e.sh timestamp-contract +``` + +The first is also part of full E2E. A local native HTTPS TSA creates ephemeral +keys in memory; only public CA certificates and synthetic protocol replies +are temporary files. Tests cover valid evidence; wrong imprint/nonce/signature; +expired/untrusted signer and HTTPS trust; SHA-1 refusal and SHA-2 support; +malformed/oversized/rejected/HTTP-failure replies; +HTTP refusal/timeouts; four attempts; crash-slot consumption/restarts; missed deadline; overlapping +runners; migration preservation/repeatability/grants; authorized download; original +PDF hash and sign-off preservation; and another document releasing while a TSA +request is held. The optional scheduler check uses real disposable cron without +changing host/VM time. Optional RSS sampling is a non-atomic Linux `/proc` cohort +sample, not native aggregate/adversarial resource certification. + +No live TSA, preserved preview, native deployment or browser acceptance is +implied by these fixture checks. Ticket20's parser-overlap/native resource gates +remain open independently of timestamping. Disable the cron entry to stop future +work; retain existing evidence/database rows and original PDFs. Do not delete +history or blindly restore an old database after newer document activity.
diff --git a/done.txt b/done.txt @@ -2,3 +2,11 @@ x 2026-11-10 2026-11-10 Repair render-job payloads, sequence gates, retry and ac 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 x 2026-11-12 2026-11-10 Make identity fail closed without blocking isolated feature tests +api +pim +test +ops status:completed id:13 spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-13.md commit:6c96811 x 2026-11-12 2026-11-10 Freeze PIM and DAM inputs at submit and derive stamped copy from proof +api +worker +render +schema +test status:completed id:12 blockedby:11 spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-12.md commit:456b95b +x 2026-11-13 2026-11-12 Diagnose and fix dev graceful restart child ownership; preserve custom seeds/config +ops +test status:completed id:15 note:.scratch/signature-collections.md +x 2026-11-13 2026-11-13 Add private labelled user signature collections, one default and immutable signer choice +api +worker +client +schema +test status:completed id:16 note:.scratch/signature-collections.md +x 2026-11-14 2026-11-14 Integrate collections and upgrade preserved preview in place with real-backup restore and rollback rehearsal +ops +api +worker +client +schema +test status:completed id:17 note:.scratch/preview-upgrade.md +x 2026-11-14 2026-11-14 Audit resource paths and bound decision placement plus legacy pending-layout metadata +api +test status:completed id:18 note:.scratch/resource-audit.md +x 2026-11-14 2026-11-14 Replace global PIM Redis flush with scoped reconciliation and ordered mirror writes +pim +api +worker +test status:completed id:19 note:.scratch/pim-resync.md +x 2026-11-15 2026-11-15 Bound dense request encodings before kcgi while retaining multipart field and PDF capacities +api +pim +ops +test status:completed id:23 note:.scratch/bounded-parsers.md +x 2026-11-15 2026-11-14 Reproduce and repair PDF writer realloc/font allocation failure leaks and retry spin +render +worker +test status:completed id:21 note:.scratch/pdfw-allocation.md +x 2026-11-16 2026-11-14 Verify shared API failure logging and actual dev log capture rather than historical claims +api +pim +ops +test status:completed id:22 note:.scratch/api-logging.md
diff --git a/etc/lighttpd-signet.conf b/etc/lighttpd-signet.conf @@ -4,7 +4,16 @@ server.modules += ( "mod_alias", "mod_fastcgi", "mod_webdav", "mod_setenv" ) -server.max-request-size = 34000 # KB; PDFs up to 32 MB +server.max-request-size = 34000 # KiB; DAM/WebDAV policy is unchanged +# kcgi buffers whole requests: 32 MiB PDFs travel as authenticated 256 KiB chunks. +# Match all FastCGI prefixes, including unknown suffixes that still reach kcgi. +# Dense encodings allocate a kpair per few bytes; retain large fields via multipart. +$HTTP["url"] =~ "^/(api|pim-api)" { + server.max-request-size = 16 + $REQUEST_HEADER["Content-Type"] =~ "(?i)^multipart/form-data[ \\t]*;" { + server.max-request-size = 1100 + } +} alias.url += ( "/dam/" => "/var/www/dam/",
diff --git a/etc/signet.conf.example b/etc/signet.conf.example @@ -5,9 +5,17 @@ redis.host = 127.0.0.1 redis.port = 6379 queue = queue:stamping +# Optional detached RFC3161 evidence. Both fields must be set to enable. +# HTTPS endpoint and locally provisioned TSA trust anchors (never auto-download). +# Install timestamp.cron.example in signetd's crontab; signing/release never wait. +timestamp.url = +timestamp.ca_file = +# Usually empty: HTTPS uses system trust, independently of the TSA signing CA. +timestamp.tls_ca_file = + data_dir = /var/lib/signet # docs/<uuid>/*.pdf, templates/<uuid>.pdf dam_dir = /var/www/dam # public DAM (lighttpd mod_webdav) -sig_dir = /var/lib/signatures # <username>.png, readable by signetd only +sig_dir = /var/lib/signatures # <UUID>.png (legacy <username>.png), signetd only sig_inbox = /var/lib/signet/sig-inbox # temporary location for enrolled facsimiles # Fonts are DAM assets: the browser loads /dam/<path>, the worker embeds the
diff --git a/etc/timestamp.cron.example b/etc/timestamp.cron.example @@ -0,0 +1,3 @@ +# Optional: install in signetd's user crontab using the system's cron facility. +# Configure timestamp.url and timestamp.ca_file first. No new resident worker. +* * * * * /usr/local/libexec/signet-timestamp
diff --git a/pim/pim-api.c b/pim/pim-api.c @@ -20,58 +20,94 @@ static struct conf cf; +/* Keep the tiny catalog's post-commit mirror writes ordered across workers. */ +static int +mirror_lock(PGconn *pg, int acquire) +{ + return db_do(pg, acquire ? + "SELECT pg_advisory_lock(hashtextextended('signet:pim-mirror',0))" : + "SELECT pg_advisory_unlock(hashtextextended('signet:pim-mirror',0))", 0, NULL); +} + static int mirror(const char *org, const char *key, const char *type, const char *value) { + static const char script[] = + "for _,k in ipairs(KEYS) do " + "local t=redis.call('TYPE',k).ok; " + "if t~='none' and t~=(k==KEYS[1] and 'set' or 'hash') then " + "return redis.error_reply('invalid PIM mirror type') end end; " + "redis.call('HDEL',KEYS[2],ARGV[1]); redis.call('HDEL',KEYS[3],ARGV[1]); " + "if ARGV[3]~='' then redis.call('HSET'," + "ARGV[2]=='image' and KEYS[3] or KEYS[2],ARGV[1],ARGV[3]) end; " + "redis.call('SADD',KEYS[1],ARGV[4]); return 1"; redisContext *rc = redis_get(&cf); redisReply *rep; - const char *hash; int ok; if (rc == NULL) return -1; - hash = strcmp(type, "image") == 0 ? "images" : "metadata"; - if (value != NULL && *value) - rep = redisCommand(rc, "HSET %s:%s %s %s", org, hash, key, value); - else - rep = redisCommand(rc, "HDEL %s:%s %s", org, hash, key); - ok = rep != NULL && rep->type != REDIS_REPLY_ERROR; + rep = redisCommand(rc, "EVAL %s 3 pim:orgs %s:metadata %s:images %s %s %s %s", + script, org, org, key, type, value ? value : "", org); + ok = rep != NULL && rep->type == REDIS_REPLY_INTEGER && rep->integer == 1; + if (!ok) + log_err("PIM mirror command failed"); if (rep != NULL) freeReplyObject(rep); - /* Also track org in the set for listing */ - if (ok && (value == NULL || !*value)) { - rep = redisCommand(rc, "SADD pim:orgs %s", org); - if (rep != NULL) - freeReplyObject(rep); - } + else + redis_drop(); return ok ? 0 : -1; } static void h_resync(struct kreq *r, PGconn *pg) { - PGresult *res = db_q(pg, "SELECT org_code, attr_key, attr_type, attr_value " - "FROM pim_attributes", 0, NULL); + static const char script[] = + "local rows=cjson.decode(ARGV[1]); local owned={}; " + "local function safe(s) return type(s)=='string' and #s<=50 " + "and string.sub(s,1,1)~='.' and string.match(s,'^[A-Za-z0-9._-]+$') end; " + "for _,org in ipairs(redis.call('SMEMBERS',KEYS[1])) do " + "if not safe(org) then return redis.error_reply('invalid PIM organisation') end; " + "owned[org]=true end; " + "for _,row in ipairs(rows) do " + "if not safe(row[1]) or not safe(row[2]) or type(row[4])~='string' " + "or (row[3]~='text' and row[3]~='image') then " + "return redis.error_reply('invalid PIM attribute') end; owned[row[1]]=true end; " + /* Validate everything before removing only this component's owned hashes. */ + "for org in pairs(owned) do redis.call('DEL',org..':metadata',org..':images') end; " + "for _,row in ipairs(rows) do if row[4]~='' then redis.call('HSET',row[1].." + "(row[3]=='image' and ':images' or ':metadata'),row[2],row[4]) end end; " + "for org in pairs(owned) do redis.call('SADD',KEYS[1],org) end; return 1"; + PGresult *res; redisContext *rc; - redisReply *rep; - int i, bad = 0; + redisReply *rep = NULL; + int bad = 1; + if (mirror_lock(pg, 1) == -1) { + send_err(r, KHTTP_500, "database error"); + return; + } + res = db_q(pg, "SELECT coalesce(json_agg(json_build_array(org_code, attr_key, " + "attr_type, attr_value)), '[]')::text FROM pim_attributes", 0, NULL); if (res == NULL) { + mirror_lock(pg, 0); send_err(r, KHTTP_500, "database error"); return; } - /* Clear existing data and rebuild from PostgreSQL */ - rc = redis_get(&cf); - if (rc != NULL) { - rep = redisCommand(rc, "FLUSHDB"); /* caution: dev only, shares Redis */ + if ((rc = redis_get(&cf)) != NULL) { + rep = redisCommand(rc, "EVAL %s 1 pim:orgs %s", script, PQgetvalue(res, 0, 0)); + bad = rep == NULL || rep->type != REDIS_REPLY_INTEGER || rep->integer != 1; + if (bad) + log_err("PIM resync command failed"); if (rep != NULL) freeReplyObject(rep); + else + redis_drop(); } - for (i = 0; i < PQntuples(res); i++) - bad |= mirror(PQgetvalue(res, i, 0), PQgetvalue(res, i, 1), - PQgetvalue(res, i, 2), PQgetvalue(res, i, 3)); PQclear(res); - if (bad) + if (mirror_lock(pg, 0) == -1) + send_err(r, KHTTP_500, "database error"); + else if (bad) send_err(r, KHTTP_503, "redis unavailable"); else send_json(r, KHTTP_200, "{\"ok\":true}"); @@ -94,6 +130,10 @@ h_upsert(struct kreq *r, PGconn *pg) send_err(r, KHTTP_400, "org/key must be [A-Za-z0-9._-], type text|image"); return; } + if (mirror_lock(pg, 1) == -1) { + send_err(r, KHTTP_500, "database error"); + return; + } if (*p[3]) rc = db_do(pg, "INSERT INTO pim_attributes (org_code, attr_key, attr_type, " "attr_value) VALUES ($1, $2, $3, $4) ON CONFLICT (org_code, attr_key) " @@ -101,9 +141,13 @@ h_upsert(struct kreq *r, PGconn *pg) else rc = db_do(pg, "DELETE FROM pim_attributes WHERE org_code = $1 " "AND attr_key = $2", 2, p); + if (rc != -1) + rc = mirror(p[0], p[1], p[2], p[3]) == -1 ? 1 : 0; + if (mirror_lock(pg, 0) == -1) + rc = -1; if (rc == -1) send_err(r, KHTTP_500, "database error"); - else if (mirror(p[0], p[1], p[2], p[3]) == -1) + else if (rc == 1) send_err(r, KHTTP_503, "saved, but Redis is down: run resync later"); else send_json(r, KHTTP_200, "{\"ok\":true}"); @@ -117,17 +161,14 @@ dispatch(struct kreq *r) PGconn *pg; PGresult *res; int n; - const char *method = http_method_str(r->method); ident_read(r, &cf, &id); if (id.user == NULL) { send_err(r, KHTTP_401, "no authenticated user"); - log_request(method, r->fullpath, id.user, 401, "no authenticated user"); return; } if ((pg = db_get(&cf)) == NULL) { send_err(r, KHTTP_503, "database unavailable"); - log_request(method, r->fullpath, id.user, 503, "database unavailable"); return; } n = http_path(r, buf, sizeof(buf), seg, 2); @@ -143,7 +184,6 @@ dispatch(struct kreq *r) "ORDER BY org_code, attr_key) t", 0, NULL); if (res == NULL) { send_err(r, KHTTP_500, "database error"); - log_request(method, r->fullpath, id.user, 500, "database error"); } else { send_json(r, KHTTP_200, PQgetvalue(res, 0, 0)); PQclear(res); @@ -152,7 +192,6 @@ dispatch(struct kreq *r) } if (!http_post_ok(r) || !ident_has_role(&id, &cf, "pim_admin")) { send_err(r, KHTTP_403, "pim_admin role required"); - log_request(method, r->fullpath, id.user, 403, "pim_admin role required"); return; } if (n == 1 && strcmp(seg[0], "attrs") == 0) @@ -161,7 +200,6 @@ dispatch(struct kreq *r) h_resync(r, pg); else { send_err(r, KHTTP_404, "not found"); - log_request(method, r->fullpath, id.user, 404, "not found"); } } @@ -169,19 +207,32 @@ int main(void) { static const char *const pages[] = { "index" }; + static const char *const fields[] = { "org", "key", "type", "value" }; const char *path = getenv("SIGNET_CONF"); struct kfcgi *fcgi; struct kreq r; + enum kcgi_err er; - if (conf_load(&cf, path ? path : CONF_PATH_DEFAULT) == -1) - return 1; log_open("pim-api"); - if (khttp_fcgi_init(&fcgi, NULL, 0, pages, 1, 0) != KCGI_OK) + if (conf_load(&cf, path ? path : CONF_PATH_DEFAULT) == -1) { + log_err("cannot read configuration"); return 1; - while (khttp_fcgi_parse(fcgi, &r) == KCGI_OK) { - dispatch(&r); + } + if (khttp_fcgi_init(&fcgi, NULL, 0, pages, 1, 0) != KCGI_OK) { + log_err("FastCGI initialization failed"); + return 1; + } + while ((er = khttp_fcgi_parse(fcgi, &r)) == KCGI_OK) { + r.arg = &cf; + if (http_keep_fields(&r, fields, sizeof(fields) / sizeof(fields[0])) == -1) + send_err(&r, KHTTP_503, "request allocation failed"); + else + dispatch(&r); khttp_free(&r); + db_request_done(); } + if (er != KCGI_EXIT) + log_err("FastCGI parse failed (code %d)", er); khttp_fcgi_free(fcgi); - return 0; + return er == KCGI_EXIT ? 0 : 1; }
diff --git a/sql/migrations/002-signature-collections.sql b/sql/migrations/002-signature-collections.sql @@ -0,0 +1,21 @@ +-- Stop API/worker and back up DB + private files first. Preserve legacy paths. +BEGIN; +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS id UUID NOT NULL DEFAULT gen_random_uuid(); +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS label VARCHAR(80) NOT NULL DEFAULT 'Signature'; +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS is_default BOOLEAN NOT NULL DEFAULT TRUE; +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS storage_id UUID; +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS sha256 CHAR(64); +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS enrol_error TEXT; +ALTER TABLE facsimiles ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP; +DO $$ BEGIN + IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='facsimiles'::regclass + AND contype='p' AND pg_get_constraintdef(oid)='PRIMARY KEY (username)') THEN + ALTER TABLE facsimiles DROP CONSTRAINT facsimiles_pkey; + ALTER TABLE facsimiles ADD PRIMARY KEY (id); + END IF; +END $$; +CREATE UNIQUE INDEX IF NOT EXISTS facsimiles_default_idx ON facsimiles (username) WHERE is_default; +CREATE UNIQUE INDEX IF NOT EXISTS facsimiles_legacy_idx ON facsimiles (username) WHERE storage_id IS NULL; +CREATE INDEX IF NOT EXISTS facsimiles_user_idx ON facsimiles (username, created_at); +ALTER TABLE doc_decisions ADD COLUMN IF NOT EXISTS facsimile_id UUID REFERENCES facsimiles(id); +COMMIT;
diff --git a/sql/migrations/003-bounded-pdf-uploads.sql b/sql/migrations/003-bounded-pdf-uploads.sql @@ -0,0 +1,16 @@ +-- Additive: NULL counters retain the meaning of every existing complete source. +BEGIN; +ALTER TABLE documents ADD COLUMN IF NOT EXISTS source_total INTEGER; +ALTER TABLE documents ADD COLUMN IF NOT EXISTS source_received INTEGER; +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint + WHERE conrelid='documents'::regclass AND conname='documents_source_upload_check') THEN + ALTER TABLE documents ADD CONSTRAINT documents_source_upload_check CHECK ( + (source_total IS NULL AND source_received IS NULL) OR + (source_total IS NOT NULL AND source_received IS NOT NULL AND + source_total BETWEEN 6 AND 33554432 AND + source_received BETWEEN 0 AND source_total)); + END IF; +END $$; +COMMIT;
diff --git a/sql/migrations/004-detached-timestamps.sql b/sql/migrations/004-detached-timestamps.sql @@ -0,0 +1,24 @@ +-- Optional evidence, independent of document status and rendering transactions. +CREATE TABLE IF NOT EXISTS document_timestamps ( + doc_id UUID PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, + revision INTEGER NOT NULL CHECK (revision > 0), + pdf_sha256 CHAR(64) NOT NULL CHECK (pdf_sha256 ~ '^[0-9a-f]{64}$'), + state VARCHAR(12) NOT NULL DEFAULT 'pending' + CHECK (state IN ('pending', 'timestamped', 'unavailable')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 4), + started_at TIMESTAMPTZ NOT NULL, + deadline TIMESTAMPTZ NOT NULL, + next_attempt_at TIMESTAMPTZ, + timestamped_at TIMESTAMPTZ, + response BYTEA, + last_error VARCHAR(40), + CHECK (deadline = started_at + INTERVAL '1 hour'), + CHECK ((state = 'timestamped' AND timestamped_at IS NOT NULL AND + response IS NOT NULL AND octet_length(response) BETWEEN 1 AND 65536) OR + (state <> 'timestamped' AND timestamped_at IS NULL AND response IS NULL)) +); +CREATE INDEX IF NOT EXISTS document_timestamps_due_idx + ON document_timestamps (next_attempt_at) WHERE state = 'pending'; +CREATE INDEX IF NOT EXISTS documents_released_idx + ON documents (released_at) WHERE status = 'RELEASED'; +GRANT SELECT, INSERT, UPDATE ON document_timestamps TO signetd;
diff --git a/sql/migrations/README.md b/sql/migrations/README.md @@ -33,6 +33,75 @@ crash can leave an unreferenced snapshot/proof; inventory against snapshot_id an retained revision policy before any administrative removal. No automatic sweep or destructive retention policy is introduced here. -This upgrade is not native deployment/resource certification. In particular, -concurrent upload buffering and external-command deadlines remain release-gate -work; never infer safe coexistence with maa-1's other services from dev tests. +## 002 — private signature collections + +Apply `002-signature-collections.sql` before the collection-aware API/worker, +with both stopped under the same backup/approval precautions above. It adds a +UUID primary key, label/default/storage/hash/error metadata and nullable +`doc_decisions.facsimile_id`. Original username/enrolment/dimension fields remain +unchanged. It is transactional and repeatable on both the former single-user +primary key schema and the current fresh schema. + +Existing files stay `<username>.png` (`storage_id IS NULL`); existing decisions +stay NULL-reference decisions and the worker resolves their legacy file, never +a newly chosen default. New variants use `<UUID>.png` and new decisions pin an +owned enrolled UUID. Do not backfill old decisions from today's default, rename +or replace legacy originals, or move private files into DAM. New originals are +hash-checked at signing; legacy already-enrolled rows without hashes remain +supported. Keep the complete private directory with DB/queue/document backups. + +The old single-facsimile application cannot run against the upgraded primary +key. Rollback requires the verified pre-upgrade DB/files backup, not dropping +new fields and discarding collected variants. `test/signature-migration.sh` +checks repeat migration and preservation of original metadata in a temporary +isolated PostgreSQL database; `test/signature-contract.sh` covers legacy decision +replay after a default change, frozen choices, retry and ownership boundaries. + +## 003 — bounded PDF upload transport + +Apply `003-bounded-pdf-uploads.sql` with writers stopped and verified coordinated +DB/files/queue/config backups. It adds nullable integer source-total/received +counters and a checked pair/range constraint. Repeat application preserves every +old field; existing NULL/NULL sources stay complete without rewriting their PDF. +`test/upload-migration.sh` verifies a real legacy-schema fixture separately. + +Install the API, browser and lighttpd request cap together: PDF capacity remains +32MiB, but large files now use authenticated256KiB application-level chunks. +Incomplete uploads are DRAFTs, not a new status; they are not readable/editable/ +submittable or usable as templates. Back up the partial source file and SQL +counter together. A failed/uncertain final commit can leave source.pdf beside an +older counter: do not mark it complete manually. The guarded retry reconciles +publication and compares acknowledged bytes. No initial creation retry or orphan +sweep is automatic; inventory unreferenced directories before administrative +removal. + +**Do not run an old API while incomplete uploads exist:** it does not enforce +these readiness checks. Complete or explicitly discard them under the new API +with owner approval, or reconcile a tested paired DB/files rollback with all +newer activity. Blindly restoring an old backup after user activity loses data. +No preserved-preview or production upgrade is implied by source integration. + +## 004 — optional detached release timestamps + +Apply `004-detached-timestamps.sql` as database owner with writers stopped, +backups verified and explicit upgrade approval, **before the timestamp-aware +API**, even when timestamping will remain disabled. It adds an evidence table, +bounded-state/response constraints, due/released indexes and the timestamp +worker's SELECT/INSERT/UPDATE grant. Existing documents, decisions, PDF hashes +and files are unchanged; the migration does not enqueue or backdate evidence. +`test/timestamp-migration.sh` verifies legacy fields/decisions, empty new evidence, +grants and repeat application in a separate disposable database. + +`document_timestamps` contains the full RFC3161 response bound to the released +revision/hash and its persistent release-anchored one-hour/four-attempt budget. +Back it up with the unchanged final PDFs and the relevant public trust bundles. +Enable only after independently provisioning TSA trust and configuring system +cron; see `docs/timestamps.md`. Installing the binary/example alone does not +schedule requests. Stop its cron entry during upgrades/restores. Retain evidence +on rollback; do not drop rows or blindly restore an old DB after newer activity. +The older API can ignore this additive table, but cannot expose its evidence. + +These upgrades are not native deployment/resource certification. The repaired +two-max-file upload fixture does not certify parser amplification, aggregate +image/font/render resources or shared-service coexistence. Command deadlines +are not RSS/CPU quotas. Never infer safe coexistence with maa-1 from dev tests.
diff --git a/sql/schema.sql b/sql/schema.sql @@ -48,6 +48,12 @@ CREATE TABLE documents ( serial VARCHAR(200) UNIQUE, -- allocated on first submit doc_date DATE, -- fixed on first submit org_code VARCHAR(50), -- organisation (D23); NOT NULL at submit + source_total INTEGER, -- NULL for legacy/template sources + source_received INTEGER, -- acknowledged bytes; full source is immutable + CONSTRAINT documents_source_upload_check CHECK ( + (source_total IS NULL AND source_received IS NULL) OR + (source_total IS NOT NULL AND source_received IS NOT NULL AND + source_total BETWEEN 6 AND 33554432 AND source_received BETWEEN 0 AND source_total)), layout_json JSONB NOT NULL DEFAULT '{}', snapshot_id UUID, -- private snapshot-<id> directory snapshot_json JSONB, -- server-frozen layout/assets for this revision @@ -66,6 +72,29 @@ CREATE TABLE documents ( ); CREATE INDEX documents_drafter_idx ON documents (drafter_user, created_at DESC); CREATE INDEX documents_status_idx ON documents (status); +CREATE INDEX documents_released_idx ON documents (released_at) WHERE status = 'RELEASED'; + +-- Optional detached RFC3161 evidence; never controls document release. +CREATE TABLE document_timestamps ( + doc_id UUID PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, + revision INTEGER NOT NULL CHECK (revision > 0), + pdf_sha256 CHAR(64) NOT NULL CHECK (pdf_sha256 ~ '^[0-9a-f]{64}$'), + state VARCHAR(12) NOT NULL DEFAULT 'pending' + CHECK (state IN ('pending', 'timestamped', 'unavailable')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 4), + started_at TIMESTAMPTZ NOT NULL, + deadline TIMESTAMPTZ NOT NULL, + next_attempt_at TIMESTAMPTZ, + timestamped_at TIMESTAMPTZ, + response BYTEA, + last_error VARCHAR(40), + CHECK (deadline = started_at + INTERVAL '1 hour'), + CHECK ((state = 'timestamped' AND timestamped_at IS NOT NULL AND + response IS NOT NULL AND octet_length(response) BETWEEN 1 AND 65536) OR + (state <> 'timestamped' AND timestamped_at IS NULL AND response IS NULL)) +); +CREATE INDEX document_timestamps_due_idx ON document_timestamps (next_attempt_at) + WHERE state = 'pending'; CREATE TABLE doc_decisions ( id BIGSERIAL PRIMARY KEY, @@ -74,6 +103,7 @@ CREATE TABLE doc_decisions ( party INTEGER NOT NULL, signer VARCHAR(100) NOT NULL, decision VARCHAR(20) NOT NULL CHECK (decision IN ('SIGNOFF','CORRECTION','DISAPPROVE')), + facsimile_id UUID, -- selected at sign-off; NULL for legacy/check-only placement JSONB, -- {"page":2,"coords":[x1,y1,x2,y2],"ref_w":1000,"ref_h":1414} for signature zones comment TEXT NOT NULL DEFAULT '', decided_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, @@ -106,9 +136,21 @@ CREATE TABLE pim_attributes ( -- Worker reads from sig_dir after enrol, never before. Width/height let client -- auto-fit placements without seeing the image. CREATE TABLE facsimiles ( - username VARCHAR(100) PRIMARY KEY, + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + username VARCHAR(100) NOT NULL, + label VARCHAR(80) NOT NULL DEFAULT 'Signature', + is_default BOOLEAN NOT NULL DEFAULT TRUE, + storage_id UUID, -- NULL: legacy <username>.png; otherwise <UUID>.png + sha256 CHAR(64), -- worker verifies immutable enrolled bytes + enrol_error TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, enrolled_at TIMESTAMPTZ, -- NULL until enrollment complete enrolled_by VARCHAR(100) NOT NULL, -- who enrolled (self or admin) width INTEGER, -- pixels, set by worker at enrol height INTEGER ); +CREATE UNIQUE INDEX facsimiles_default_idx ON facsimiles (username) WHERE is_default; +CREATE UNIQUE INDEX facsimiles_legacy_idx ON facsimiles (username) WHERE storage_id IS NULL; +CREATE INDEX facsimiles_user_idx ON facsimiles (username, created_at); +ALTER TABLE doc_decisions ADD CONSTRAINT doc_decisions_facsimile_id_fkey + FOREIGN KEY (facsimile_id) REFERENCES facsimiles(id);
diff --git a/src/db.c b/src/db.c @@ -1,11 +1,15 @@ #include <stdio.h> #include <stdlib.h> +#include <string.h> #include "db.h" #include "util.h" +#define DB_CACHE_BYTES (256u * 1024) + static PGconn *pg; static redisContext *rc; +static int recycle_pg; PGconn * db_get(const struct conf *cf) @@ -14,15 +18,28 @@ db_get(const struct conf *cf) return pg; if (pg != NULL) PQfinish(pg); + recycle_pg = 0; pg = PQconnectdb(conf_get(cf, "db.conninfo", "dbname=signet")); if (PQstatus(pg) != CONNECTION_OK) { - fprintf(stderr, "signet: postgres: %s", PQerrorMessage(pg)); + log_err("database connection failed"); PQfinish(pg); pg = NULL; } return pg; } +/* libpq retains large I/O buffers even after PQclear(). Do not carry them + * across API requests; never close an in-flight query or worker transaction. */ +void +db_request_done(void) +{ + if (recycle_pg && pg != NULL) { + PQfinish(pg); + pg = NULL; + } + recycle_pg = 0; +} + redisContext * redis_get(const struct conf *cf) { @@ -38,7 +55,7 @@ redis_get(const struct conf *cf) rc = redisConnect(conf_get(cf, "redis.host", "127.0.0.1"), atoi(conf_get(cf, "redis.port", "6379"))); if (rc == NULL || rc->err) { - log_err("redis: %s", rc ? rc->errstr : "oom"); + log_err("Redis connection unavailable"); redis_drop(); } return rc; @@ -55,11 +72,32 @@ redis_drop(void) PGresult * db_q(PGconn *c, const char *sql, int n, const char *const *params) { - PGresult *res = PQexecParams(c, sql, n, NULL, params, NULL, NULL, 0); - ExecStatusType st = PQresultStatus(res); + PGresult *res; + ExecStatusType st; + size_t bytes = 0, len; + int i; + if (c == pg) { + for (i = 0; i < n; i++) { + if (params[i] == NULL) + continue; + len = strlen(params[i]); + if (len >= DB_CACHE_BYTES - bytes) { + recycle_pg = 1; + break; + } + bytes += len; + } + } + res = PQexecParams(c, sql, n, NULL, params, NULL, NULL, 0); + st = PQresultStatus(res); + if (c == pg && res != NULL && PQresultMemorySize(res) >= DB_CACHE_BYTES) + recycle_pg = 1; if (st != PGRES_TUPLES_OK && st != PGRES_COMMAND_OK) { - log_err("sql: %s", PQerrorMessage(c)); + /* DETAIL/CONTEXT and server messages can repeat private parameters. */ + log_err("database query failed (SQLSTATE %.5s)", + res != NULL && PQresultErrorField(res, PG_DIAG_SQLSTATE) != NULL ? + PQresultErrorField(res, PG_DIAG_SQLSTATE) : "?????"); PQclear(res); return NULL; }
diff --git a/src/db.h b/src/db.h @@ -8,6 +8,8 @@ /* (Re)connect lazily; both return NULL when the service is unreachable. */ PGconn *db_get(const struct conf *); +/* API request boundary only: release oversized libpq I/O caches. */ +void db_request_done(void); redisContext *redis_get(const struct conf *); void redis_drop(void);
diff --git a/src/http.c b/src/http.c @@ -44,6 +44,67 @@ ident_has_role(const struct ident *id, const struct conf *cf, const char *role) list_intersects(id->groups, conf_get(cf, key, "")); } +static void +free_pair(struct kpair *p) +{ + free(p->key); + free(p->val); + free(p->file); + free(p->ctype); + free(p->xcode); +} + +/* Unused form/cookie arrays must not compete with qpdf while a handler waits + * on PostgreSQL. Keep first values, as http_field() does, before borrowing them. + * Both APIs use unmapped kcgi requests; maps would point into the old array. */ +int +http_keep_fields(struct kreq *r, const char *const *names, size_t count) +{ + struct kpair *p, *fields; + size_t i, j, n = 0, oldsz = r->fieldsz; + + if (r->keysz != 0) + return -1; + for (i = 0; i < oldsz; i++) { + p = &r->fields[i]; + for (j = 0; j < count; j++) + if (strcmp(p->key, names[j]) == 0) + break; + if (j == count) { + free_pair(p); + continue; + } + for (j = 0; j < n; j++) + if (strcmp(p->key, r->fields[j].key) == 0) + break; + if (j != n) { + free_pair(p); + continue; + } + r->fields[n] = *p; + r->fields[n++].next = NULL; + } + r->fieldsz = n; + /* Identity is forwarded in headers, never in cookies. */ + for (i = 0; i < r->cookiesz; i++) + free_pair(&r->cookies[i]); + free(r->cookies); + r->cookies = NULL; + r->cookiesz = 0; + if (n == 0) { + free(r->fields); + r->fields = NULL; + return 0; + } + if (n == oldsz) + return 0; + fields = realloc(r->fields, n * sizeof(*fields)); + if (fields == NULL) + return -1; + r->fields = fields; + return 0; +} + struct kpair * http_field(struct kreq *r, const char *key) { @@ -97,11 +158,19 @@ send_json(struct kreq *r, enum khttp code, const char *body) } void -send_err(struct kreq *r, enum khttp code, const char *msg) +send_err_at(struct kreq *r, enum khttp code, const char *msg, + const char *function, int line) { - char buf[1024]; + struct ident id = { NULL, NULL }; + char buf[1024], site[96]; size_t o; + if (r->arg != NULL) + ident_read(r, r->arg, &id); + /* Error text may contain resolved attributes, filenames or DB details. */ + snprintf(site, sizeof(site), "%s:%d", function, line); + log_request(http_method_str(r->method), r->fullpath, id.user, + atoi(khttps[code]), site); o = (size_t)snprintf(buf, sizeof(buf), "{\"error\":\""); for (; *msg && o + 8 < sizeof(buf); msg++) { if (*msg == '"' || *msg == '\\') {
diff --git a/src/http.h b/src/http.h @@ -20,6 +20,7 @@ void ident_read(struct kreq *, const struct conf *, struct ident *); int ident_has_role(const struct ident *, const struct conf *, const char *role); const char *http_header(struct kreq *, const char *name); +int http_keep_fields(struct kreq *, const char *const *, size_t); struct kpair *http_field(struct kreq *, const char *key); const char *http_field_str(struct kreq *, const char *key); /* state-changing requests must carry X-Requested-With: signet (CSRF guard) */ @@ -28,7 +29,10 @@ int http_post_ok(struct kreq *); int http_path(struct kreq *, char *buf, size_t bufsz, char **seg, int max); void send_json(struct kreq *, enum khttp, const char *body); -void send_err(struct kreq *, enum khttp, const char *msg); +/* API loops lend r->arg their configuration; log the site, not error contents. */ +/* APIs lend their conf through r->arg after parsing, for failure identity. */ +void send_err_at(struct kreq *, enum khttp, const char *, const char *, int); +#define send_err(r, code, msg) send_err_at((r), (code), (msg), __func__, __LINE__) void send_file(struct kreq *, const char *path, const char *mime, const char *download_name); const char *http_method_str(enum kmethod);
diff --git a/src/pdfw.c b/src/pdfw.c @@ -1,3 +1,4 @@ +#include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> @@ -94,40 +95,85 @@ stream_obj(pdfw *p, int obj, const char *dict, const void *data, size_t len) fputs("\nendstream\nendobj\n", p->f); } -static unsigned char * -deflate_buf(const unsigned char *in, size_t len, size_t *outlen) +/* An indirect length lets compression write straight to the PDF, not a second + * image/font-sized buffer alongside the decoded pixels or loaded font bytes. */ +static int +deflate_obj(pdfw *p, int obj, const char *dict, const unsigned char *in, + size_t len) { - uLongf n = compressBound((uLong)len); - unsigned char *out = malloc(n); - - if (out == NULL || compress2(out, &n, in, (uLong)len, 6) != Z_OK) { - free(out); - return NULL; - } - *outlen = n; - return out; + z_stream z; + unsigned char buf[16384]; + uLong total; + int length, rc; + size_t n; + + if (p->err || len > UINT_MAX) + goto fail; + if ((length = new_obj(p)) == 0) + return -1; + memset(&z, 0, sizeof(z)); + if (deflateInit(&z, 6) != Z_OK) + goto fail; + begin_obj(p, obj); + fprintf(p->f, "<< %s /Filter /FlateDecode /Length %d 0 R >>\nstream\n", + dict, length); + z.next_in = (Bytef *)in; + z.avail_in = (uInt)len; + do { + z.next_out = buf; + z.avail_out = sizeof(buf); + rc = deflate(&z, Z_FINISH); + n = sizeof(buf) - z.avail_out; + if ((rc != Z_OK && rc != Z_STREAM_END) || + fwrite(buf, 1, n, p->f) != n) { + deflateEnd(&z); + goto fail; + } + } while (rc != Z_STREAM_END); + total = z.total_out; + if (deflateEnd(&z) != Z_OK) + goto fail; + fputs("\nendstream\nendobj\n", p->f); + begin_obj(p, length); + fprintf(p->f, "%lu\nendobj\n", total); + if (ferror(p->f)) + goto fail; + return 0; +fail: + p->err = 1; + return -1; } static void cprintf(pdfw *p, const char *fmt, ...) { va_list ap; + char *content; + size_t cap; int n; + if (p->err) + return; for (;;) { va_start(ap, fmt); - n = vsnprintf(p->content + p->clen, p->ccap - p->clen, fmt, ap); + n = vsnprintf(p->content ? p->content + p->clen : NULL, + p->ccap - p->clen, fmt, ap); va_end(ap); if (n >= 0 && (size_t)n < p->ccap - p->clen) { p->clen += (size_t)n; return; } - p->ccap = p->ccap ? p->ccap * 2 : 4096; - if ((p->content = realloc(p->content, p->ccap)) == NULL) { + if (n < 0 || p->ccap > SIZE_MAX / 2) { + p->err = 1; + return; + } + cap = p->ccap ? p->ccap * 2 : 4096; + if ((content = realloc(p->content, cap)) == NULL) { p->err = 1; - p->ccap = p->clen = 0; return; } + p->content = content; + p->ccap = cap; } } @@ -167,7 +213,12 @@ pdfw_open(const char *path) } fputs("%PDF-1.5\n%\xE2\xE3\xCF\xD3\n", p->f); while (p->nobj < OBJ_HELVETICA) - new_obj(p); + if (new_obj(p) == 0) { + fclose(p->f); + free(p->offs); + free(p); + return NULL; + } begin_obj(p, OBJ_HELVETICA); fputs("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica " "/Encoding /WinAnsiEncoding >>\nendobj\n", p->f); @@ -206,6 +257,10 @@ pdfw_font(pdfw *p, const char *path) ft->used = calloc((size_t)ft->ttf.nglyphs + 1, sizeof(uint32_t)); ft->path = strdup(path); if (ft->used == NULL || ft->path == NULL) { + ttf_free(&ft->ttf); + free(ft->used); + free(ft->path); + memset(ft, 0, sizeof(*ft)); p->err = 1; return PDFW_HELVETICA; } @@ -347,9 +402,9 @@ static int embed_png(pdfw *p, struct pimage *im, const char *path) { png_image png; - unsigned char *rgba = NULL, *rgb = NULL, *a = NULL, *z = NULL; - size_t npx, i, zlen; - int has_alpha = 0, smask = 0, rc = -1; + unsigned char *pixels = NULL, *rgb = NULL, *a = NULL; + size_t npx, i; + int channels, has_alpha = 0, smask = 0, rc = -1; char dict[256]; memset(&png, 0, sizeof(png)); @@ -361,55 +416,54 @@ embed_png(pdfw *p, struct pimage *im, const char *path) png_image_free(&png); return -1; } - png.format = PNG_FORMAT_RGBA; - if ((rgba = malloc(PNG_IMAGE_SIZE(png))) == NULL || - !png_image_finish_read(&png, NULL, rgba, 0, NULL)) { + channels = (png.format & PNG_FORMAT_FLAG_ALPHA) ? 4 : 3; + png.format = channels == 4 ? PNG_FORMAT_RGBA : PNG_FORMAT_RGB; + if ((pixels = malloc(PNG_IMAGE_SIZE(png))) == NULL || + !png_image_finish_read(&png, NULL, pixels, 0, NULL)) { png_image_free(&png); goto out; } im->w = (int)png.width; im->h = (int)png.height; - /* split in place: RGB packs down into the front of the RGBA buffer */ - if ((a = malloc(npx)) == NULL) - goto out; - rgb = rgba; - for (i = 0; i < npx; i++) { - a[i] = rgba[i * 4 + 3]; - if (a[i] != 0xFF) - has_alpha = 1; - rgb[i * 3] = rgba[i * 4]; - rgb[i * 3 + 1] = rgba[i * 4 + 1]; - rgb[i * 3 + 2] = rgba[i * 4 + 2]; + rgb = pixels; + if (channels == 4) { + for (i = 0; i < npx; i++) + if (pixels[i * 4 + 3] != 0xFF) { + has_alpha = 1; + break; + } + /* Split in place; opaque images need no alpha-plane allocation. */ + if (has_alpha && (a = malloc(npx)) == NULL) + goto out; + for (i = 0; i < npx; i++) { + if (has_alpha) + a[i] = pixels[i * 4 + 3]; + rgb[i * 3] = pixels[i * 4]; + rgb[i * 3 + 1] = pixels[i * 4 + 1]; + rgb[i * 3 + 2] = pixels[i * 4 + 2]; + } } if (has_alpha) { - if ((z = deflate_buf(a, npx, &zlen)) == NULL) - goto out; snprintf(dict, sizeof(dict), "/Type /XObject /Subtype /Image " "/Width %d /Height %d /BitsPerComponent 8 " - "/ColorSpace /DeviceGray /Interpolate true /Filter /FlateDecode", - im->w, im->h); + "/ColorSpace /DeviceGray /Interpolate true", im->w, im->h); smask = new_obj(p); - stream_obj(p, smask, dict, z, zlen); - free(z); - z = NULL; + if (deflate_obj(p, smask, dict, a, npx) == -1) + goto out; } free(a); a = NULL; - if ((z = deflate_buf(rgb, npx * 3, &zlen)) == NULL) - goto out; i = (size_t)snprintf(dict, sizeof(dict), "/Type /XObject /Subtype /Image " "/Width %d /Height %d /BitsPerComponent 8 " - "/ColorSpace /DeviceRGB /Interpolate true /Filter /FlateDecode", + "/ColorSpace /DeviceRGB /Interpolate true", im->w, im->h); if (smask) snprintf(dict + i, sizeof(dict) - i, " /SMask %d 0 R", smask); im->obj = new_obj(p); - stream_obj(p, im->obj, dict, z, zlen); - rc = 0; + rc = deflate_obj(p, im->obj, dict, rgb, npx * 3); out: - free(z); free(a); - free(rgba); + free(pixels); return rc; } @@ -506,19 +560,13 @@ write_font(pdfw *p, int idx) const struct ttf *t = &ft->ttf; double k = 1000.0 / t->units; int file, desc, cid, tou, g, n; - unsigned char *z; - size_t zlen; char dict[128], *cm; size_t cmlen = 0, cmcap; - if ((z = deflate_buf(t->data, t->len, &zlen)) == NULL) { - p->err = 1; - return; - } file = new_obj(p); - snprintf(dict, sizeof(dict), "/Length1 %zu /Filter /FlateDecode", t->len); - stream_obj(p, file, dict, z, zlen); - free(z); + snprintf(dict, sizeof(dict), "/Length1 %zu", t->len); + if (deflate_obj(p, file, dict, t->data, t->len) == -1) + return; desc = new_obj(p); begin_obj(p, desc); @@ -589,9 +637,16 @@ pdfw_close(pdfw *p) long xref; int i, err; + if (p->err) + goto out; end_page(p); - for (i = 0; i < p->nfonts; i++) + if (p->err) + goto out; + for (i = 0; i < p->nfonts; i++) { write_font(p, i); + if (p->err) + goto out; + } begin_obj(p, OBJ_RESOURCES); fprintf(p->f, "<< /Font << /F0 %d 0 R", OBJ_HELVETICA); @@ -618,6 +673,7 @@ pdfw_close(pdfw *p) fprintf(p->f, "trailer\n<< /Size %d /Root %d 0 R >>\nstartxref\n%ld\n%%%%EOF\n", p->nobj + 1, OBJ_CATALOG, xref); +out: err = p->err || ferror(p->f); if (fclose(p->f) != 0) err = 1;
diff --git a/src/signet-api.c b/src/signet-api.c @@ -2,15 +2,17 @@ * signet-api: FastCGI backend (kcgi, run under kfcgi). * * GET /me - * POST /me/facsimile file=<png> - * POST /facsimiles user, file=<png> (admin) + * POST /me/facsimile label, file=<png> (new immutable variant) + * POST /me/facsimile/default facsimile_id=<uuid> + * POST /me/facsimile/retry facsimile_id=<uuid> (idempotent activation) + * POST /facsimiles user, label, file=<png> (admin) * GET /docs?scope=mine|pending|involved|all * POST /docs file=<pdf> | template_id=<uuid> * GET /docs/<id> * POST /docs/<id>/save json={title,series_code,layout,route} * POST /docs/<id>/submit * POST /docs/<id>/rerender - * POST /docs/<id>/decide decision=signoff|correction|disapprove, comment, placement + * POST /docs/<id>/decide decision, comment, placement, facsimile_id * POST /docs/<id>/delete (drafts only) * GET /docs/<id>/file/<source|proof|stamped|final> * GET /templates POST /templates doc_id, name @@ -35,6 +37,7 @@ #include "http.h" #include "render.h" #include "snapshot.h" +#include "upload.h" #include "util.h" static struct conf cf; @@ -290,29 +293,21 @@ check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code, static void h_me(struct kreq *r, PGconn *pg, const struct ident *id) { - PGresult *res; - char buf[512]; - int enrolled = 0, width = 0, height = 0; - - res = db_q(pg, "SELECT width, height FROM facsimiles WHERE username = $1 AND enrolled_at IS NOT NULL", - 1, (const char *[]){ id->user }); - if (res != NULL) { - if (PQntuples(res) == 1) { - enrolled = 1; - width = atoi(PQgetvalue(res, 0, 0)); - height = atoi(PQgetvalue(res, 0, 1)); - } - PQclear(res); - } - - snprintf(buf, sizeof(buf), "{\"user\":\"%s\",\"roles\":{\"drafter\":%s," - "\"signer\":%s,\"admin\":%s},\"enrolled\":%s,\"facsimile\":{\"width\":%d,\"height\":%d}}", - id->user, + const char *p[] = { id->user, ident_has_role(id, &cf, "drafter") ? "true" : "false", ident_has_role(id, &cf, "signer") ? "true" : "false", - ident_has_role(id, &cf, "admin") ? "true" : "false", - enrolled ? "true" : "false", width, height); - send_json(r, KHTTP_200, buf); + ident_has_role(id, &cf, "admin") ? "true" : "false" }; + + /* Metadata only: original images never pass through the API. */ + send_sql_json(r, pg, "SELECT json_build_object('user', $1::varchar, 'roles', " + "json_build_object('drafter',$2::boolean,'signer',$3::boolean,'admin',$4::boolean), " + "'enrolled', EXISTS(SELECT 1 FROM facsimiles WHERE username=$1 AND is_default AND enrolled_at IS NOT NULL), " + "'facsimile', coalesce((SELECT json_build_object('id',id,'label',label,'width',width,'height',height) " + "FROM facsimiles WHERE username=$1 AND is_default AND enrolled_at IS NOT NULL), " + "json_build_object('width',0,'height',0)), " + "'facsimiles', (SELECT coalesce(json_agg(f), '[]') FROM (SELECT id,label,is_default,width,height, " + "enrolled_at IS NOT NULL AS enrolled,enrol_error AS error FROM facsimiles WHERE username=$1 " + "ORDER BY (enrol_error IS NULL) DESC, created_at DESC,id DESC LIMIT 64) f))::text", 4, p); } static void @@ -335,27 +330,45 @@ h_docs_list(struct kreq *r, PGconn *pg, const struct ident *id) snprintf(sql, sizeof(sql), "SELECT coalesce(json_agg(t), '[]')::text FROM (" "SELECT d.id, d.status, d.title, d.serial, d.drafter_user, " - "d.revision, d.current_party, " + "d.revision, d.current_party, coalesce(d.source_received<d.source_total,false) AS uploading, " "jsonb_array_length(d.route_json->'parties') AS parties, " "d.created_at, d.submitted_at, d.released_at " "FROM documents d WHERE %s ORDER BY d.created_at DESC LIMIT 200) t", where); send_sql_json(r, pg, sql, 1, p); } +static int +upload_number(const char *s, size_t *n) +{ + if (s == NULL || *s == '\0' || strlen(s) > 8 || + strspn(s, "0123456789") != strlen(s)) + return -1; + *n = strtoul(s, NULL, 10); + return *n <= UPLOAD_MAX_BYTES ? 0 : -1; +} + static void h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) { struct kpair *file = http_field(r, "file"); const char *tpl = http_field_str(r, "template_id"); - const char *p[2] = { id->user, tpl }; - char dir[600], path[700], src[700], body[128]; + const char *declared = http_field_str(r, "total_size"); + const char *p[4] = { id->user, tpl, NULL, NULL }, *docid; + char dir[600], path[700], src[700], body[200], err[256]; + char total_buf[32], received_buf[32]; + size_t total = 0; + int chunked = http_field(r, "total_size") != NULL; PGresult *res; - const char *docid; if (!ident_has_role(id, &cf, "drafter")) { send_err(r, KHTTP_403, "drafter role required"); return; } + if (chunked && (upload_number(declared, &total) == -1 || file == NULL || + file->valsz > UPLOAD_CHUNK_BYTES || total < file->valsz || (tpl != NULL && *tpl))) { + send_err(r, KHTTP_400, "PDF total must fit within 32 MiB; chunks within 256 KiB"); + return; + } if (db_do(pg, "BEGIN", 0, NULL) == -1) { send_err(r, KHTTP_500, "database error"); return; @@ -370,13 +383,23 @@ h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) "series_code, layout_json, route_json) SELECT $1::varchar, t.id, " "t.series_code, t.layout_json, t.route_json FROM templates t " "WHERE t.id = $2 AND t.retired_at IS NULL RETURNING id", 2, p); - } else if (file != NULL && file->valsz > 5 && file->valsz <= 32u * 1024 * 1024 && + } else if (file != NULL && file->valsz > 5 && file->valsz <= UPLOAD_MAX_BYTES && memcmp(file->val, "%PDF-", 5) == 0) { - res = db_q(pg, "INSERT INTO documents (drafter_user) VALUES ($1) " - "RETURNING id", 1, p); + if (!chunked) + total = file->valsz; + else { + snprintf(total_buf, sizeof(total_buf), "%zu", total); + snprintf(received_buf, sizeof(received_buf), "%zu", file->valsz); + p[2] = total_buf; + p[3] = received_buf; + } + res = db_q(pg, "INSERT INTO documents (drafter_user, source_total, source_received) " + "VALUES ($1, $2::int, $3::int) RETURNING id, " + "json_build_object('id',id,'upload_offset',source_received,'upload_total',source_total)::text", 3, + (const char *[]){ id->user, p[2], p[3] }); } else { db_do(pg, "ROLLBACK", 0, NULL); - send_err(r, KHTTP_400, "upload a PDF (max 32 MB) or pick a template"); + send_err(r, KHTTP_400, "upload a PDF (max 32 MiB) or pick a template"); return; } if (res == NULL || PQntuples(res) != 1) { @@ -392,22 +415,101 @@ h_doc_create(struct kreq *r, PGconn *pg, const struct ident *id) snprintf(src, sizeof(src), "%s/templates/%s.pdf", conf_get(&cf, "data_dir", "/var/lib/signet"), tpl ? tpl : ""); if (mkdir_p(dir, 0770) == -1 || - (tpl != NULL && *tpl ? copy_file(src, path) - : write_file(path, file->val, file->valsz, 0640)) == -1) { + (tpl != NULL && *tpl ? copy_file(src, path) : + upload_chunk(dir, total, 0, 0, file->val, file->valsz, err, sizeof(err))) < 0 || + log_event(pg, docid, id->user, "CREATED", "") == -1) { 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); + doc_path(path, sizeof(path), docid, "source.part"); unlink(path); rmdir(dir); - send_err(r, KHTTP_500, "could not record document creation"); + send_err(r, KHTTP_500, "could not store or record the PDF"); + } else if (db_do(pg, "COMMIT", 0, NULL) == -1) { + /* Retain files: the document's commit may have reached PostgreSQL. */ + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_503, "creation commit uncertain; reload your documents"); } else { - snprintf(body, sizeof(body), "{\"id\":\"%s\"}", docid); - send_json(r, KHTTP_201, body); + if (chunked) + send_json(r, KHTTP_201, PQgetvalue(res, 0, 1)); + else { + snprintf(body, sizeof(body), "{\"id\":\"%s\"}", docid); + send_json(r, KHTTP_201, body); + } + } + PQclear(res); +} + +static void +h_doc_upload(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid) +{ + struct kpair *file = http_field(r, "file"); + const char *p[3] = { docid, id->user, NULL }; + char dir[600], err[256], next_buf[32]; + size_t offset, total, received; + PGresult *res; + int next, ack_col = 2; + + if (!ident_has_role(id, &cf, "drafter")) { + send_err(r, KHTTP_403, "drafter role required"); + return; + } + if (upload_number(http_field_str(r, "offset"), &offset) == -1 || + file == NULL || file->valsz == 0 || file->valsz > UPLOAD_CHUNK_BYTES) { + send_err(r, KHTTP_400, "offset and a PDF chunk within 256 KiB required"); + return; + } + if (db_do(pg, "BEGIN", 0, NULL) == -1) { + send_err(r, KHTTP_500, "database error"); + return; + } + res = db_q(pg, "SELECT source_total, source_received, " + "json_build_object('upload_offset',source_received,'upload_total',source_total)::text FROM documents " + "WHERE id=$1 AND drafter_user=$2 AND status='DRAFT' " + "AND source_total IS NOT NULL FOR UPDATE", 2, p); + if (res == NULL) { + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_500, "database error"); + return; + } + if (PQntuples(res) != 1) { + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_409, "only your own draft upload can accept chunks"); + return; + } + total = (size_t)strtoul(PQgetvalue(res, 0, 0), NULL, 10); + received = (size_t)strtoul(PQgetvalue(res, 0, 1), NULL, 10); + doc_path(dir, sizeof(dir), docid, NULL); + next = upload_chunk(dir, total, received, offset, file->val, file->valsz, err, sizeof(err)); + if (next < 0) { + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, next == -2 ? KHTTP_409 : KHTTP_503, err); + return; + } + snprintf(next_buf, sizeof(next_buf), "%d", next); + p[2] = next_buf; + if (next != (int)received) { + PQclear(res); + res = db_q(pg, "UPDATE documents SET source_received=$3::int " + "WHERE id=$1 AND drafter_user=$2 RETURNING " + "json_build_object('upload_offset',source_received,'upload_total',source_total)::text", 3, p); + ack_col = 0; + if (res == NULL || PQntuples(res) != 1) { + if (res != NULL) + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_500, "could not record chunk; retry the same offset"); + return; + } } + if (db_do(pg, "COMMIT", 0, NULL) == -1) { + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_503, "chunk commit uncertain; retry the same offset"); + return; + } + send_json(r, KHTTP_200, PQgetvalue(res, 0, ack_col)); PQclear(res); } @@ -424,28 +526,43 @@ h_doc_get(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid) { const char *p[] = { docid, id->user, ident_has_role(id, &cf, "admin") ? "t" : "f", - ident_has_role(id, &cf, "signer") ? "t" : "f" }; + ident_has_role(id, &cf, "signer") ? "t" : "f", + *conf_get(&cf, "timestamp.url", "") && *conf_get(&cf, "timestamp.ca_file", "") ? "t" : "f" }; 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.org_code, " "d.layout_json AS layout, d.route_json AS route, d.revision, " "d.current_party, d.render_seq, d.rendered_seq, d.render_kind, " + "d.source_total AS upload_total, d.source_received AS upload_offset, " + "coalesce(d.source_received<d.source_total,false) AS uploading, " "(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 max(decided_at) FROM doc_decisions WHERE doc_id=d.id AND revision=d.revision " + "AND decision='SIGNOFF') AS signed_at, " + "(SELECT timestamped_at FROM document_timestamps WHERE doc_id=d.id AND state='timestamped' " + "AND revision=d.revision AND pdf_sha256=d.final_sha256) AS timestamped_at, " + "coalesce((SELECT CASE WHEN state='pending' AND deadline<=clock_timestamp() " + "THEN 'unavailable' ELSE state END FROM document_timestamps WHERE doc_id=d.id " + "AND revision=d.revision AND pdf_sha256=d.final_sha256), " + "CASE WHEN d.status='RELEASED' AND $5::boolean THEN CASE " + "WHEN d.released_at>clock_timestamp()-interval '1 hour' THEN 'pending' ELSE 'unavailable' END " + "ELSE 'not_requested' END) AS timestamp_status, " + "coalesce((SELECT attempts FROM document_timestamps WHERE doc_id=d.id),0) AS timestamp_attempts, " "(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, " + "(d.drafter_user = $2 AND d.status IN ('DRAFT','CORRECTION_REQUIRED') " + "AND coalesce(d.source_received=d.source_total,true)) AS can_edit, " "($4::boolean AND " CAN_DECIDE("$2") ") AS can_decide, " "($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 " + "SELECT revision, party, signer, decision, comment, decided_at, facsimile_id " "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 " ROUTE_ACCESS("$2") ")) t", 4, p); + "OR " ROUTE_ACCESS("$2") ")) t", 5, p); } static void @@ -495,7 +612,8 @@ h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid res = db_q(pg, "UPDATE documents SET title = $3, " "series_code = CASE WHEN serial IS NULL THEN $4 ELSE series_code END, " "org_code = $5, layout_json = $6::jsonb, route_json = $7::jsonb WHERE id = $1 " - "AND drafter_user = $2 AND status IN ('DRAFT','CORRECTION_REQUIRED')", 7, p); + "AND drafter_user = $2 AND status IN ('DRAFT','CORRECTION_REQUIRED') " + "AND coalesce(source_received=source_total,true)", 7, p); if (res == NULL) send_err(r, KHTTP_400, "save failed (unknown series?)"); else if (strcmp(PQcmdTuples(res), "1") != 0) @@ -531,7 +649,8 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc "CASE WHEN octet_length(route_json::text) <= 1024 * 1024 " "THEN route_json::text END, series_code, " "serial, org_code, status::text, title, revision + 1 FROM documents WHERE id = $1 AND drafter_user = $2 " - "AND status IN ('DRAFT','CORRECTION_REQUIRED') FOR UPDATE", 2, p); + "AND status IN ('DRAFT','CORRECTION_REQUIRED') " + "AND coalesce(source_received=source_total,true) FOR UPDATE", 2, p); if (res == NULL || PQntuples(res) != 1) { snprintf(err, sizeof(err), "document is not submittable by you"); goto fail; @@ -757,6 +876,8 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc const char *decision = http_field_str(r, "decision"); const char *comment = http_field_str(r, "comment"); const char *placement_json = http_field_str(r, "placement"); + const char *chosen = http_field_str(r, "facsimile_id"); + char facsimile[37] = ""; const char *p[5], *code, *action; char err[512] = "", detail[4608]; PGresult *res = NULL, *job_res = NULL; @@ -767,6 +888,16 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc size_t i, max; const char *type, *pname; + if ((chosen != NULL && !is_uuid(chosen)) || + (http_field(r, "facsimile_id") != NULL && chosen == NULL)) { + send_err(r, KHTTP_400, "invalid facsimile reference"); + return; + } + if (http_field(r, "placement") != NULL && + (placement_json == NULL || strlen(placement_json) > MAX_JSON_BYTES)) { + send_err(r, KHTTP_400, "placement must be valid text within 1 MiB"); + return; + } if (comment == NULL) comment = ""; if (strlen(comment) > 4096) { @@ -799,7 +930,9 @@ 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, d.layout_json::text FROM documents d WHERE d.id = $1 AND " + "d.revision::text, d.render_seq::text, " + "CASE WHEN octet_length(d.layout_json::text) <= 1024 * 1024 THEN d.layout_json::text END " + "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"); @@ -817,6 +950,10 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc const char *layout_str = PQgetvalue(res, 0, 5), *msg; yyjson_val *zone = NULL; + if (PQgetisnull(res, 0, 5)) { + snprintf(err, sizeof(err), "stored layout must fit within 1 MiB; request a correction"); + goto fail; + } layout_doc = yyjson_read(layout_str, strlen(layout_str), 0); if (layout_doc == NULL) { snprintf(err, sizeof(err), "invalid stored layout"); @@ -833,13 +970,23 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc } has_zone = zone != NULL; if (has_zone) { - 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; + PGresult *fres; char source[700]; + double aspect, page_w, page_h; + int enrolled; + if (chosen == NULL && db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", + 1, (const char *[]){ id->user }) == -1) + goto fail; + fres = db_q(pg, "SELECT width, height, id::text FROM facsimiles WHERE username = $1 " + "AND (($2::uuid IS NULL AND is_default) OR id=$2::uuid) " + "AND enrolled_at IS NOT NULL AND width > 0 AND height > 0 FOR SHARE", + 2, (const char *[]){ id->user, chosen }); + enrolled = fres != NULL && PQntuples(fres) == 1; + aspect = enrolled ? atof(PQgetvalue(fres, 0, 0)) / atof(PQgetvalue(fres, 0, 1)) : 0; + + if (enrolled) + snprintf(facsimile, sizeof(facsimile), "%s", PQgetvalue(fres, 0, 2)); if (fres != NULL) PQclear(fres); if (!enrolled) { @@ -861,8 +1008,8 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc } } } - if (!has_zone && placement_json != NULL) { - snprintf(err, sizeof(err), "placement is only allowed for a zone sign-off"); + if (!has_zone && (placement_json != NULL || chosen != NULL)) { + snprintf(err, sizeof(err), "placement and facsimile are only allowed for a zone sign-off"); goto fail; } @@ -872,10 +1019,10 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc snprintf(party_str, sizeof(party_str), "%d", party); if (placement_json != NULL) { - const char *ip[] = { docid, p[2], party_str, id->user, code, comment, placement_json }; + const char *ip[] = { docid, p[2], party_str, id->user, code, comment, placement_json, facsimile }; if (db_do(pg, "INSERT INTO doc_decisions (doc_id, revision, party, " - "signer, decision, comment, placement) VALUES ($1, $2::int, $3::int, $4, $5, $6, $7::jsonb)", - 7, ip) == -1) { + "signer, decision, comment, placement, facsimile_id) VALUES ($1, $2::int, $3::int, $4, $5, $6, $7::jsonb, $8::uuid)", + 8, ip) == -1) { snprintf(err, sizeof(err), "could not record the decision"); goto fail; } @@ -913,8 +1060,8 @@ h_doc_decide(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc action = code[0] == 'C' ? "CORRECTION_REQUIRED" : "DISAPPROVED"; } - snprintf(detail, sizeof(detail), "revision %s, party %d (%s): %s", - p[2], party, party_name, comment); + snprintf(detail, sizeof(detail), "revision %s, party %d (%s)%s%s: %s", + p[2], party, party_name, *facsimile ? ", facsimile " : "", facsimile, comment); if (log_event(pg, docid, id->user, action, detail) == -1 || db_do(pg, "COMMIT", 0, NULL) == -1) goto fail; @@ -961,6 +1108,8 @@ h_doc_delete(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc else { doc_path(path, sizeof(path), docid, "source.pdf"); unlink(path); + doc_path(path, sizeof(path), docid, "source.part"); + unlink(path); doc_path(path, sizeof(path), docid, NULL); rmdir(path); send_json(r, KHTTP_200, "{\"ok\":true}"); @@ -978,11 +1127,14 @@ h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid char path[700], name[64]; PGresult *res; int is_drafter, in_route, admin = p[2][0] == 't'; + unsigned char *token; + size_t token_size; const char *status; 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); + "OR $3::boolean OR " ROUTE_ACCESS("$2") ") " + "AND coalesce(d.source_received=d.source_total,true)", 3, p); if (res == NULL || PQntuples(res) != 1) { send_err(r, KHTTP_404, "not found"); goto out; @@ -993,11 +1145,13 @@ h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid if (strcmp(status, "DRAFT") == 0) in_route = 0; if (strcmp(kind, "source") != 0 && strcmp(kind, "proof") != 0 && - strcmp(kind, "stamped") != 0 && strcmp(kind, "final") != 0) { + strcmp(kind, "stamped") != 0 && strcmp(kind, "final") != 0 && + strcmp(kind, "timestamp") != 0) { send_err(r, KHTTP_404, "not found"); goto out; } - if ((strcmp(kind, "final") == 0 && strcmp(status, "RELEASED") != 0) || + if (((strcmp(kind, "final") == 0 || strcmp(kind, "timestamp") == 0) && + strcmp(status, "RELEASED") != 0) || (strcmp(kind, "stamped") == 0 && strcmp(status, "PENDING") != 0)) { send_err(r, KHTTP_404, "file not available"); goto out; @@ -1007,6 +1161,38 @@ h_doc_file(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid send_err(r, KHTTP_403, "forbidden"); goto out; } + if (strcmp(kind, "timestamp") == 0) { + PQclear(res); + res = db_q(pg, "SELECT t.response FROM document_timestamps t JOIN documents d ON d.id=t.doc_id " + "AND d.revision=t.revision AND d.final_sha256=t.pdf_sha256 " + "WHERE t.doc_id=$1 AND t.state='timestamped' AND d.status='RELEASED'", 1, p); + if (res == NULL) { + send_err(r, KHTTP_503, "timestamp unavailable"); + goto out; + } + if (PQntuples(res) != 1) { + send_err(r, KHTTP_404, "timestamp not available"); + goto out; + } + if (PQgetisnull(res, 0, 0)) { + send_err(r, KHTTP_503, "timestamp unavailable"); + goto out; + } + token = PQunescapeBytea((const unsigned char *)PQgetvalue(res, 0, 0), &token_size); + if (token == NULL || token_size == 0 || token_size > 65536) { + PQfreemem(token); + send_err(r, KHTTP_503, "timestamp unavailable"); + goto out; + } + khttp_head(r, kresps[KRESP_STATUS], "%s", khttps[KHTTP_200]); + khttp_head(r, kresps[KRESP_CONTENT_TYPE], "application/timestamp-reply"); + khttp_head(r, kresps[KRESP_CACHE_CONTROL], "no-store"); + khttp_head(r, kresps[KRESP_CONTENT_DISPOSITION], "attachment; filename=timestamp.tsr"); + khttp_body(r); + khttp_write(r, (const char *)token, token_size); + PQfreemem(token); + goto out; + } snprintf(name, sizeof(name), "%s.pdf", kind); doc_path(path, sizeof(path), docid, name); send_file(r, path, "application/pdf", name); @@ -1044,7 +1230,8 @@ h_templates(struct kreq *r, PGconn *pg, const struct ident *id) p[2] = name; res = db_q(pg, "INSERT INTO templates (name, series_code, layout_json, " "route_json, created_by) SELECT $3::varchar, series_code, layout_json, route_json, " - "$2::varchar FROM documents WHERE id = $1 AND drafter_user = $2::varchar RETURNING id", 3, p); + "$2::varchar FROM documents WHERE id = $1 AND drafter_user = $2::varchar " + "AND coalesce(source_received=source_total,true) RETURNING id", 3, p); if (res == NULL || PQntuples(res) != 1) { send_err(r, KHTTP_404, "document not found"); if (res != NULL) @@ -1314,110 +1501,172 @@ h_series_retire(struct kreq *r, PGconn *pg, const struct ident *id, const char * send_json(r, KHTTP_200, "{\"ok\":true}"); } +static int +queue_facsimile(const char *user, const char *key) +{ + redisContext *rc = redis_get(&cf); + redisReply *reply; + char job[256]; + int ok; + + if (rc == NULL) + return -1; + snprintf(job, sizeof(job), "{\"kind\":\"enrol\",\"user\":\"%s\",\"facsimile_id\":\"%s\"}", user, key); + reply = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue", "queue:stamping"), job); + if (reply == NULL) { + redis_drop(); + return -1; + } + ok = reply->type == REDIS_REPLY_INTEGER; + freeReplyObject(reply); + return ok ? 0 : -1; +} + static void -h_me_facsimile(struct kreq *r, PGconn *pg, const struct ident *id) +h_facsimile_retry(struct kreq *r, PGconn *pg, const struct ident *id) { - struct kpair *file = http_field(r, "file"); - char inbox_path[1024]; + const char *key = http_field_str(r, "facsimile_id"); + PGresult *res; if (!ident_has_role(id, &cf, "signer")) { send_err(r, KHTTP_403, "signer role required"); return; } - - if (file == NULL || file->valsz > 1048576 || file->valsz < 8) { - send_err(r, KHTTP_400, "PNG file required (≤ 1 MB)"); - return; - } - /* Check PNG signature bytes */ - if (memcmp(file->val, "\x89PNG\r\n\x1a\n", 8) != 0) { - send_err(r, KHTTP_400, "not a valid PNG file"); + if (!is_uuid(key)) { + send_err(r, KHTTP_400, "invalid facsimile reference"); return; } - - 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, 0640) == -1) { - send_err(r, KHTTP_500, "could not store facsimile"); + res = db_q(pg, "SELECT id FROM facsimiles WHERE username=$1 AND id=$2::uuid AND enrol_error IS NULL", + 2, (const char *[]){ id->user, key }); + if (res == NULL || PQntuples(res) != 1) { + if (res != NULL) + PQclear(res); + send_err(r, KHTTP_409, "choose one of your pending signatures; invalid PNGs require a new upload"); return; } - - /* Upsert facsimiles row and enqueue enrol job */ - const char *p[] = { id->user, id->user }; - db_do(pg, "INSERT INTO facsimiles (username, enrolled_by, enrolled_at) " - "VALUES ($1, $2, NULL) " - "ON CONFLICT (username) DO UPDATE SET enrolled_at = NULL", - 2, p); - - redisContext *rc = redis_get(&cf); - if (rc != NULL) { - redisReply *rep; - char job[128]; - snprintf(job, sizeof(job), "{\"kind\":\"enrol\",\"user\":\"%s\"}", id->user); - rep = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue", - "queue:stamping"), job); - if (rep != NULL) - freeReplyObject(rep); - } - - send_json(r, KHTTP_200, "{\"ok\":true}"); + PQclear(res); + if (queue_facsimile(id->user, key) == -1) + send_err(r, KHTTP_503, "could not queue activation; retry later"); + else + send_json(r, KHTTP_200, "{\"ok\":true}"); } static void -h_facsimiles(struct kreq *r, PGconn *pg, const struct ident *id) +h_facsimile_upload(struct kreq *r, PGconn *pg, const struct ident *id, int admin) { struct kpair *file = http_field(r, "file"); - const char *user = http_field_str(r, "user"); - char inbox_path[1024]; - - if (!ident_has_role(id, &cf, "admin")) { - send_err(r, KHTTP_403, "admin role required"); + const char *user = admin ? http_field_str(r, "user") : id->user; + const char *label = http_field_str(r, "label"), *p[3]; + char inbox[1024] = "", key[37], body[80]; + PGresult *res = NULL; + enum khttp failure = KHTTP_503; + const char *message = "could not queue signature; retry later"; + size_t i; + + if (!ident_has_role(id, &cf, admin ? "admin" : "signer")) { + send_err(r, KHTTP_403, admin ? "admin role required" : "signer role required"); return; } - - if (user == NULL || !is_safe_name(user)) { + if (!is_safe_name(user)) { send_err(r, KHTTP_400, "invalid user"); return; } - - if (file == NULL || file->valsz > 1048576 || file->valsz < 8) { - send_err(r, KHTTP_400, "PNG file required (≤ 1 MB)"); + if (label == NULL && http_field(r, "label") == NULL) + label = "Signature"; + if (label == NULL || !*label || strlen(label) > 80 || strspn(label, " ") == strlen(label)) { + send_err(r, KHTTP_400, "signature label must be 1 to 80 bytes"); return; } - /* Check PNG signature bytes */ - if (memcmp(file->val, "\x89PNG\r\n\x1a\n", 8) != 0) { - send_err(r, KHTTP_400, "not a valid PNG file"); + for (i = 0; label[i]; i++) + if ((unsigned char)label[i] < 32 || label[i] == 127) { + send_err(r, KHTTP_400, "signature label contains control characters"); + return; + } + if (file == NULL || file->valsz < 8 || file->valsz > 1048576 || + memcmp(file->val, "\x89PNG\r\n\x1a\n", 8) != 0) { + send_err(r, KHTTP_400, "PNG file required (max 1 MiB)"); return; } + p[0] = user; + p[1] = id->user; + p[2] = label; + if (db_do(pg, "BEGIN", 0, NULL) == -1) + goto fail; + /* The enrol worker takes this same lock before observing queued work. */ + if (db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1) + goto fail; + res = db_q(pg, "WITH k AS (SELECT gen_random_uuid() AS id) " + "INSERT INTO facsimiles (id,storage_id,username,enrolled_by,label,is_default) " + "SELECT k.id,k.id,$1::varchar,$2::varchar,$3::varchar,false FROM k WHERE " + "(SELECT count(*) FROM facsimiles WHERE username=$1 AND enrol_error IS NULL)<32 RETURNING id::text", 3, p); + if (res == NULL) + goto fail; + if (PQntuples(res) != 1) { + failure = KHTTP_409; + message = "limit of 32 ready or pending signature variants reached"; + goto fail; + } + snprintf(key, sizeof(key), "%s", PQgetvalue(res, 0, 0)); + snprintf(inbox, sizeof(inbox), "%s/%s.png", + conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), key); + if (write_file(inbox, file->val, file->valsz, 0640) == -1) + goto fail; + if (queue_facsimile(user, key) == -1) + goto fail; + /* Queue visibility is safe: the worker waits for our transaction lock. */ + if (db_do(pg, "COMMIT", 0, NULL) == -1) { + PQclear(res); + send_err(r, KHTTP_503, "enrolment commit uncertain; reload your signature collection"); + return; /* Retain potentially committed input, never overwrite a variant. */ + } + PQclear(res); + snprintf(body, sizeof(body), "{\"ok\":true,\"id\":\"%s\"}", key); + send_json(r, KHTTP_200, body); + return; +fail: + if (res != NULL) + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + if (*inbox) + unlink(inbox); + send_err(r, failure, message); +} - snprintf(inbox_path, sizeof(inbox_path), "%s/%s.png", - conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), user); +static void +h_facsimile_default(struct kreq *r, PGconn *pg, const struct ident *id) +{ + const char *key = http_field_str(r, "facsimile_id"); + const char *p[] = { id->user, key }; + PGresult *res = NULL; - if (write_file(inbox_path, file->val, file->valsz, 0640) == -1) { - send_err(r, KHTTP_500, "could not store facsimile"); + if (!ident_has_role(id, &cf, "signer")) { + send_err(r, KHTTP_403, "signer role required"); return; } - - /* Upsert facsimiles row and enqueue enrol job */ - const char *p[] = { user, id->user }; - db_do(pg, "INSERT INTO facsimiles (username, enrolled_by, enrolled_at) " - "VALUES ($1, $2, NULL) " - "ON CONFLICT (username) DO UPDATE SET enrolled_by = $2, enrolled_at = NULL", - 2, p); - - redisContext *rc = redis_get(&cf); - if (rc != NULL) { - redisReply *rep; - char job[128]; - snprintf(job, sizeof(job), "{\"kind\":\"enrol\",\"user\":\"%s\"}", user); - rep = redisCommand(rc, "LPUSH %s %s", conf_get(&cf, "queue", - "queue:stamping"), job); - if (rep != NULL) - freeReplyObject(rep); + if (!is_uuid(key)) { + send_err(r, KHTTP_400, "invalid facsimile reference"); + return; } - + if (db_do(pg, "BEGIN", 0, NULL) == -1 || + db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1) + goto fail; + res = db_q(pg, "SELECT id FROM facsimiles WHERE username=$1 AND id=$2::uuid " + "AND enrolled_at IS NOT NULL FOR UPDATE", 2, p); + if (res == NULL || PQntuples(res) != 1) + goto fail; + if (db_do(pg, "UPDATE facsimiles SET is_default=false WHERE username=$1 AND is_default", 1, p) == -1 || + db_do(pg, "UPDATE facsimiles SET is_default=true WHERE username=$1 AND id=$2::uuid", 2, p) == -1 || + log_event(pg, NULL, id->user, "FACSIMILE_DEFAULT", key) == -1 || + db_do(pg, "COMMIT", 0, NULL) == -1) + goto fail; + PQclear(res); send_json(r, KHTTP_200, "{\"ok\":true}"); + return; +fail: + if (res != NULL) + PQclear(res); + db_do(pg, "ROLLBACK", 0, NULL); + send_err(r, KHTTP_409, "choose one of your enrolled signatures"); } /* --- dispatch -------------------------------------------------------------- */ @@ -1429,22 +1678,18 @@ dispatch(struct kreq *r) char buf[512], *seg[5]; PGconn *pg; int n, get = r->method == KMETHOD_GET; - const char *method = http_method_str(r->method); ident_read(r, &cf, &id); if (id.user == NULL) { send_err(r, KHTTP_401, "no authenticated user"); - log_request(method, r->fullpath, id.user, 401, "no authenticated user"); return; } if (!get && !http_post_ok(r)) { send_err(r, KHTTP_403, "POST with X-Requested-With: signet required"); - log_request(method, r->fullpath, id.user, 403, "POST with X-Requested-With: signet required"); return; } if ((pg = db_get(&cf)) == NULL) { send_err(r, KHTTP_503, "database unavailable"); - log_request(method, r->fullpath, id.user, 503, "database unavailable"); return; } n = http_path(r, buf, sizeof(buf), seg, 5); @@ -1452,9 +1697,13 @@ dispatch(struct kreq *r) if (n == 1 && get && strcmp(seg[0], "me") == 0) h_me(r, pg, &id); else if (n == 2 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0) - h_me_facsimile(r, pg, &id); + h_facsimile_upload(r, pg, &id, 0); + else if (n == 3 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0 && strcmp(seg[2], "default") == 0) + h_facsimile_default(r, pg, &id); + else if (n == 3 && !get && strcmp(seg[0], "me") == 0 && strcmp(seg[1], "facsimile") == 0 && strcmp(seg[2], "retry") == 0) + h_facsimile_retry(r, pg, &id); else if (n == 1 && !get && strcmp(seg[0], "facsimiles") == 0) - h_facsimiles(r, pg, &id); + h_facsimile_upload(r, pg, &id, 1); else if (n == 1 && get && strcmp(seg[0], "pim") == 0) h_pim(r); else if (n == 1 && get && strcmp(seg[0], "dam") == 0) @@ -1468,7 +1717,6 @@ dispatch(struct kreq *r) h_template_delete(r, pg, &id, seg[1]); else { send_err(r, KHTTP_404, "not found"); - log_request(method, r->fullpath, id.user, 404, "not found"); } } else if (n == 1 && strcmp(seg[0], "series") == 0) @@ -1478,7 +1726,6 @@ dispatch(struct kreq *r) h_series_retire(r, pg, &id, seg[1]); else { send_err(r, KHTTP_404, "not found"); - log_request(method, r->fullpath, id.user, 404, "not found"); } } else if (n == 1 && strcmp(seg[0], "docs") == 0) @@ -1490,6 +1737,8 @@ dispatch(struct kreq *r) h_doc_file(r, pg, &id, seg[1], seg[3]); else if (n == 3 && !get && strcmp(seg[2], "save") == 0) h_doc_save(r, pg, &id, seg[1]); + else if (n == 3 && !get && strcmp(seg[2], "upload") == 0) + h_doc_upload(r, pg, &id, seg[1]); else if (n == 3 && !get && strcmp(seg[2], "submit") == 0) h_doc_submit(r, pg, &id, seg[1]); else if (n == 3 && !get && strcmp(seg[2], "rerender") == 0) @@ -1502,11 +1751,9 @@ dispatch(struct kreq *r) h_doc_unlink(r, pg, &id, seg[1]); else { send_err(r, KHTTP_404, "not found"); - log_request(method, r->fullpath, id.user, 404, "not found"); } } else { send_err(r, KHTTP_404, "not found"); - log_request(method, r->fullpath, id.user, 404, "not found"); } } @@ -1514,22 +1761,37 @@ int main(void) { static const char *const pages[] = { "index" }; + static const char *const fields[] = { + "code", "comment", "decision", "doc_id", "facsimile_id", "file", + "json", "label", "name", "offset", "pattern", "placement", "scope", + "template_id", "total_size", "user" + }; const char *path = getenv("SIGNET_CONF"); struct kfcgi *fcgi; struct kreq r; + enum kcgi_err er; + log_open("signet-api"); if (conf_load(&cf, path ? path : CONF_PATH_DEFAULT) == -1) { - fprintf(stderr, "signet-api: cannot read configuration\n"); + log_err("cannot read configuration"); return 1; } - log_open("signet-api"); umask(007); - if (khttp_fcgi_init(&fcgi, NULL, 0, pages, 1, 0) != KCGI_OK) + if (khttp_fcgi_init(&fcgi, NULL, 0, pages, 1, 0) != KCGI_OK) { + log_err("FastCGI initialization failed"); return 1; - while (khttp_fcgi_parse(fcgi, &r) == KCGI_OK) { - dispatch(&r); + } + while ((er = khttp_fcgi_parse(fcgi, &r)) == KCGI_OK) { + r.arg = &cf; + if (http_keep_fields(&r, fields, sizeof(fields) / sizeof(fields[0])) == -1) + send_err(&r, KHTTP_503, "request allocation failed"); + else + dispatch(&r); khttp_free(&r); + db_request_done(); } + if (er != KCGI_EXIT) + log_err("FastCGI parse failed (code %d)", er); khttp_fcgi_free(fcgi); - return 0; + return er == KCGI_EXIT ? 0 : 1; }
diff --git a/src/signet-timestamp.c b/src/signet-timestamp.c @@ -0,0 +1,152 @@ +/* Short-lived cron worker. Network work never runs in the rendering worker. */ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#include "conf.h" +#include "db.h" +#include "timestamp.h" +#include "util.h" + +static int +attempt(PGconn *pg, const struct conf *cf, PGresult *job) +{ + struct timestamp_reply reply; + char path[700], sha[65], hex[TIMESTAMP_MAX_REPLY * 2 + 1]; + const char *p[7], *error = "document_changed"; + PGresult *res; + size_t i; + long timeout; + struct timespec begin, now; + int success = 0; + + p[0] = PQgetvalue(job, 0, 0); + p[1] = PQgetvalue(job, 0, 1); + p[2] = PQgetvalue(job, 0, 2); + p[3] = PQgetvalue(job, 0, 3); + p[4] = NULL; + p[5] = NULL; + if (clock_gettime(CLOCK_MONOTONIC, &begin) == -1) + return -1; + timeout = atol(PQgetvalue(job, 0, 4)); + if (timeout > 10000) + timeout = 10000; + if (is_uuid(p[0]) && snprintf(path, sizeof(path), "%s/docs/%s/final.pdf", + conf_get(cf, "data_dir", "/var/lib/signet"), p[0]) < (int)sizeof(path) && + sha256_file(path, sha) == 0 && strcmp(sha, p[2]) == 0) { + if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) + return -1; + timeout -= (now.tv_sec - begin.tv_sec) * 1000 + (now.tv_nsec - begin.tv_nsec) / 1000000; + success = timestamp_fetch(conf_get(cf, "timestamp.url", ""), + conf_get(cf, "timestamp.ca_file", ""), + conf_get(cf, "timestamp.tls_ca_file", ""), sha, timeout, &reply) == 0; + error = reply.error; + } + if (success) { + for (i = 0; i < reply.size; i++) + snprintf(hex + i * 2, 3, "%02x", reply.data[i]); + p[4] = hex; + p[5] = reply.at; + } + p[6] = error; + res = db_q(pg, success + ? "UPDATE document_timestamps t SET state='timestamped', timestamped_at=$6::timestamptz, " + "response=decode($5,'hex'), next_attempt_at=NULL, last_error=$7 " + "WHERE doc_id=$1 AND revision=$2::int AND pdf_sha256=$3 AND attempts=$4::int " + "AND state='pending' AND deadline>clock_timestamp() AND EXISTS " + "(SELECT 1 FROM documents d WHERE d.id=t.doc_id AND d.status='RELEASED' " + "AND d.revision=t.revision AND d.final_sha256=t.pdf_sha256) RETURNING doc_id" + : "UPDATE document_timestamps SET state=CASE WHEN attempts=4 OR deadline<=clock_timestamp() " + "THEN 'unavailable' ELSE 'pending' END, last_error=$7 " + "WHERE doc_id=$1 AND revision=$2::int AND pdf_sha256=$3 AND attempts=$4::int " + "AND $5::text IS NULL AND $6::text IS NULL AND state='pending' RETURNING doc_id", + 7, p); + if (res == NULL) + return -1; + if (!success) + log_err("timestamp attempt failed (%s)", error); + PQclear(res); + return 0; +} + +int +main(int argc, char **argv) +{ + struct conf cf; + PGconn *pg; + PGresult *job, *lock; + struct timespec start, now; + const char *path = CONF_PATH_DEFAULT; + int c, n, rv = 0; + + while ((c = getopt(argc, argv, "c:")) != -1) { + if (c != 'c') + return 1; + path = optarg; + } + log_open("signet-timestamp"); + if (conf_load(&cf, path) == -1) + return 1; + if (*conf_get(&cf, "timestamp.url", "") == '\0' || + *conf_get(&cf, "timestamp.ca_file", "") == '\0') + return 0; + if ((pg = db_get(&cf)) == NULL || clock_gettime(CLOCK_MONOTONIC, &start) == -1) + return 1; + /* One cron runner per database, including overlapping/restarted invocations. + * Session lock disappears on crash; no document row is held over HTTPS. */ + lock = db_q(pg, "SELECT pg_try_advisory_lock(1936289381,1953721965)", 0, NULL); + if (lock == NULL) + return 1; + c = PQgetvalue(lock, 0, 0)[0] == 't'; + PQclear(lock); + if (!c) + return 0; + /* A predecessor may have died after HTTP but before its final delay. */ + sleep(1); + if (db_do(pg, "INSERT INTO document_timestamps " + "(doc_id,revision,pdf_sha256,started_at,deadline,next_attempt_at) " + "SELECT id,revision,final_sha256,released_at,released_at+interval '1 hour',released_at " + "FROM documents WHERE status='RELEASED' AND final_sha256 IS NOT NULL " + "AND released_at>clock_timestamp()-interval '1 hour' AND released_at<=clock_timestamp() " + "AND NOT EXISTS (SELECT 1 FROM document_timestamps t WHERE t.doc_id=documents.id) " + "ORDER BY released_at LIMIT 256 ON CONFLICT (doc_id) DO NOTHING", 0, NULL) == -1 || + db_do(pg, "UPDATE document_timestamps SET state='unavailable',next_attempt_at=NULL " + "WHERE state='pending' AND (deadline<=clock_timestamp() OR attempts=4)", 0, NULL) == -1) + return 1; + for (n = 0; n < 20; n++) { + if (clock_gettime(CLOCK_MONOTONIC, &now) == -1 || now.tv_sec - start.tv_sec >= 20) + break; + /* Claim/consume an attempt BEFORE I/O. Crashes cannot reset the budget. + * Slots are anchored to release, not to process starts or retry failures. */ + job = db_q(pg, "WITH due AS (SELECT t.doc_id FROM document_timestamps t " + "JOIN documents d ON d.id=t.doc_id AND d.status='RELEASED' AND d.revision=t.revision " + "AND d.final_sha256=t.pdf_sha256 WHERE t.state='pending' AND t.attempts<4 " + "AND t.next_attempt_at<=clock_timestamp() AND t.deadline>clock_timestamp() " + "ORDER BY t.next_attempt_at,t.doc_id LIMIT 1 FOR UPDATE OF t SKIP LOCKED) " + "UPDATE document_timestamps t SET attempts=attempts+1, " + "next_attempt_at=CASE t.attempts " + "WHEN 0 THEN greatest(started_at+interval '5 minutes',clock_timestamp()+interval '1 minute') " + "WHEN 1 THEN greatest(started_at+interval '20 minutes',clock_timestamp()+interval '1 minute') " + "WHEN 2 THEN greatest(started_at+interval '55 minutes',clock_timestamp()+interval '1 minute') " + "ELSE NULL END FROM due WHERE t.doc_id=due.doc_id " + "RETURNING t.doc_id::text,t.revision::text,t.pdf_sha256,t.attempts::text, " + "floor(extract(epoch FROM t.deadline-clock_timestamp())*1000)::bigint::text", 0, NULL); + if (job == NULL) { + rv = 1; + break; + } + if (PQntuples(job) == 0) { + PQclear(job); + break; + } + if (attempt(pg, &cf, job) == -1) + rv = 1; + PQclear(job); + if (rv != 0) + break; + sleep(1); /* At most one request/second, including quick failures. */ + } + return rv; +}
diff --git a/src/signetd.c b/src/signetd.c @@ -6,6 +6,7 @@ #include <sys/stat.h> #include <errno.h> +#include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> @@ -68,53 +69,75 @@ png_get_dimensions(const char *path, int *width, int *height) /* Enrol jobs have no document id or render sequence. */ static int -process_enrol(PGconn *pg, const char *user) +process_enrol(PGconn *pg, const char *user, const char *variant) { - char inbox[1024], sig[1024], tmp[1040], w[16], h[16]; - const char *p[] = { user, w, h }; + char inbox[1024], sig[1024], tmp[1040], w[16], h[16], key[37], name[65], sha[65]; + const char *p[] = { user, variant, w, h, sha }; PGresult *res; - int width, height, rv = -1; + int width, height, fd = -1, 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 (db_do(pg, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", 1, p) == -1) + goto out; + res = db_q(pg, "SELECT id::text,enrolled_at,storage_id::text FROM facsimiles WHERE username=$1 " + "AND (($2::uuid IS NULL AND storage_id IS NULL) OR id=$2::uuid) FOR UPDATE", 2, p); if (res == NULL) goto out; - if (PQntuples(res) == 0 || !PQgetisnull(res, 0, 0)) { + if (PQntuples(res) == 0 || !PQgetisnull(res, 0, 1)) { PQclear(res); rv = db_do(pg, "COMMIT", 0, NULL); goto out; } + snprintf(key, sizeof(key), "%s", PQgetvalue(res, 0, 0)); + snprintf(name, sizeof(name), "%s", PQgetisnull(res, 0, 2) ? user : PQgetvalue(res, 0, 2)); PQclear(res); + if (!is_uuid(key) || !is_safe_name(name)) + goto out; + p[1] = key; snprintf(inbox, sizeof(inbox), "%s/%s.png", - conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), user); + conf_get(&cf, "sig_inbox", "/var/lib/signet/sig-inbox"), name); snprintf(sig, sizeof(sig), "%s/%s.png", - conf_get(&cf, "sig_dir", "/var/lib/signatures"), user); + conf_get(&cf, "sig_dir", "/var/lib/signatures"), name); 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 || + if (db_do(pg, "UPDATE facsimiles SET enrol_error='PNG decoding failed; upload a new variant', " + "is_default=false WHERE id=$2::uuid AND username=$1", 2, p) == -1 || + log_event(pg, NULL, "ENROL_FAILED", key) == -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) + sha256_file(tmp, sha) == -1 || (fd = open(tmp, O_RDONLY)) == -1 || fsync(fd) == -1) goto out; + close(fd); + fd = -1; + if (rename(tmp, sig) == -1 || + (fd = open(conf_get(&cf, "sig_dir", "/var/lib/signatures"), O_RDONLY | O_DIRECTORY)) == -1 || + fsync(fd) == -1) + goto out; + close(fd); + fd = -1; 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 || + if (db_do(pg, "UPDATE facsimiles SET is_default=false WHERE username=$1 AND id<>$2::uuid " + "AND is_default AND enrolled_at IS NULL", 2, p) == -1 || + db_do(pg, "UPDATE facsimiles SET enrolled_at=CURRENT_TIMESTAMP,width=$3::int,height=$4::int, " + "sha256=$5,enrol_error=NULL,is_default=NOT EXISTS(SELECT 1 FROM facsimiles f WHERE " + "f.username=$1 AND f.is_default AND f.id<>$2::uuid) WHERE id=$2::uuid AND username=$1", 5, p) == -1 || + log_event(pg, NULL, "ENROLLED", key) == -1 || db_do(pg, "COMMIT", 0, NULL) == -1) goto out; unlink(inbox); rv = 0; out: + if (fd != -1) + close(fd); if (rv == -1) db_do(pg, "ROLLBACK", 0, NULL); return rv; @@ -206,13 +229,15 @@ render_decision(PGconn *pg, const char *id, const char *revision, yyjson_doc *doc = NULL; yyjson_val *pl, *coords; struct render_ctx cx; - char png[1024], dir[600], tmp[700]; + char png[1024], dir[600], tmp[700], sha[65]; 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 " + res = db_q(pg, "SELECT x.signer, x.placement::text, f.enrolled_at, f.storage_id::text, f.sha256 " + "FROM doc_decisions x JOIN documents d ON d.id = x.doc_id " + "LEFT JOIN facsimiles f ON f.username = x.signer AND " + "(f.id=x.facsimile_id OR (x.facsimile_id IS NULL AND f.storage_id IS NULL)) " "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); @@ -254,8 +279,17 @@ render_decision(PGconn *pg, const char *id, const char *revision, snprintf(err, errsz, "invalid signature page or coordinates"); goto out; } + if (!PQgetisnull(res, 0, 3) && !is_uuid(PQgetvalue(res, 0, 3))) { + snprintf(err, errsz, "invalid private facsimile reference"); + goto out; + } snprintf(png, sizeof(png), "%s/%s.png", - conf_get(&cf, "sig_dir", "/var/lib/signatures"), PQgetvalue(res, 0, 0)); + conf_get(&cf, "sig_dir", "/var/lib/signatures"), + PQgetisnull(res, 0, 3) ? PQgetvalue(res, 0, 0) : PQgetvalue(res, 0, 3)); + if (!PQgetisnull(res, 0, 4) && (sha256_file(png, sha) == -1 || strcmp(sha, PQgetvalue(res, 0, 4)) != 0)) { + snprintf(err, errsz, "enrolled facsimile is missing or damaged"); + goto out; + } doc_path(dir, sizeof(dir), id, NULL); snprintf(tmp, sizeof(tmp), "%s.tmp", candidate); memset(&cx, 0, sizeof(cx)); @@ -370,7 +404,7 @@ process(const char *payload) PGresult *res = NULL, *updated = NULL; yyjson_doc *job; yyjson_val *root, *revision, *sequence; - const char *id, *kind, *user, *action, *p[5]; + const char *id, *kind, *user, *variant, *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; @@ -384,10 +418,11 @@ process(const char *payload) 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)) + variant = yyjson_get_str(yyjson_obj_get(root, "facsimile_id")); + if (!is_safe_name(user) || (yyjson_obj_get(root, "facsimile_id") != NULL && !is_uuid(variant))) goto invalid; pg = db_get(&cf); - rv = pg == NULL ? -1 : process_enrol(pg, user); + rv = pg == NULL ? -1 : process_enrol(pg, user, variant); goto done; } if (kind == NULL || (strcmp(kind, "stamp") != 0 && strcmp(kind, "sign") != 0 &&
diff --git a/src/timestamp.c b/src/timestamp.c @@ -0,0 +1,173 @@ +#include <curl/curl.h> +#include <openssl/bn.h> +#include <openssl/err.h> +#include <openssl/rand.h> +#include <openssl/ts.h> +#include <openssl/x509.h> +#include <openssl/x509_vfy.h> + +#include <stdio.h> +#include <string.h> +#include <time.h> + +#include "timestamp.h" + +static size_t +receive_reply(char *data, size_t size, size_t count, void *arg) +{ + struct timestamp_reply *reply = arg; + size_t n; + + if (size != 0 && count > (TIMESTAMP_MAX_REPLY - reply->size) / size) + return 0; + n = size * count; + memcpy(reply->data + reply->size, data, n); + reply->size += n; + return n; +} + +int +timestamp_fetch(const char *url, const char *ca_file, const char *tls_ca_file, + const char *sha256, long timeout_ms, struct timestamp_reply *reply) +{ + TS_REQ *req = NULL; + TS_RESP *resp = NULL; + TS_MSG_IMPRINT *imprint = NULL; + TS_VERIFY_CTX *verify = NULL; + X509_ALGOR *algorithm = NULL, *digest; + X509_STORE *store = NULL; + STACK_OF(PKCS7_SIGNER_INFO) *signers; + const ASN1_OBJECT *digest_oid; + ASN1_INTEGER *nonce = NULL; + BIGNUM *number = NULL; + CURL *curl = NULL; + struct curl_slist *headers = NULL, *added; + unsigned char hash[32], random[16], *request = NULL; + const unsigned char *cursor; + struct tm tm; + char pair[3]; + long status = 0; + int n, i, rv = -1; + + memset(reply, 0, sizeof(*reply)); + reply->error = "request_failed"; + if (url == NULL || strncmp(url, "https://", 8) != 0 || ca_file == NULL || + *ca_file == '\0' || sha256 == NULL || strlen(sha256) != 64 || timeout_ms <= 0) + return -1; + for (i = 0; i < 64; i++) + if (strchr("0123456789abcdef", sha256[i]) == NULL) + return -1; + for (i = 0; i < 32; i++) { + unsigned int byte; + + pair[0] = sha256[i * 2]; + pair[1] = sha256[i * 2 + 1]; + pair[2] = '\0'; + if (sscanf(pair, "%x", &byte) != 1) + return -1; + hash[i] = (unsigned char)byte; + } + if ((req = TS_REQ_new()) == NULL || (imprint = TS_MSG_IMPRINT_new()) == NULL || + (algorithm = X509_ALGOR_new()) == NULL || RAND_bytes(random, sizeof(random)) != 1) + goto out; + X509_ALGOR_set0(algorithm, OBJ_nid2obj(NID_sha256), V_ASN1_NULL, NULL); + number = BN_bin2bn(random, sizeof(random), NULL); + if (number == NULL || (nonce = BN_to_ASN1_INTEGER(number, NULL)) == NULL || + TS_REQ_set_version(req, 1) != 1 || TS_MSG_IMPRINT_set_algo(imprint, algorithm) != 1 || + TS_MSG_IMPRINT_set_msg(imprint, hash, sizeof(hash)) != 1 || + TS_REQ_set_msg_imprint(req, imprint) != 1 || TS_REQ_set_nonce(req, nonce) != 1 || + TS_REQ_set_cert_req(req, 1) != 1 || (n = i2d_TS_REQ(req, &request)) <= 0) + goto out; + if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) + goto out; + curl = curl_easy_init(); + headers = curl_slist_append(NULL, "Content-Type: application/timestamp-query"); + if (curl == NULL || headers == NULL) + goto http_done; + added = curl_slist_append(headers, "Accept: application/timestamp-reply"); + if (added == NULL) + goto http_done; + headers = added; +#define OPTION(key, value) do { if (curl_easy_setopt(curl, key, value) != CURLE_OK) goto http_done; } while (0) + OPTION(CURLOPT_URL, url); + OPTION(CURLOPT_PROTOCOLS_STR, "https"); + OPTION(CURLOPT_FOLLOWLOCATION, 0L); + OPTION(CURLOPT_PROXY, ""); + OPTION(CURLOPT_NOSIGNAL, 1L); + OPTION(CURLOPT_SSL_VERIFYPEER, 1L); + OPTION(CURLOPT_SSL_VERIFYHOST, 2L); + OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); + OPTION(CURLOPT_CONNECTTIMEOUT_MS, timeout_ms < 3000 ? timeout_ms : 3000L); + OPTION(CURLOPT_TIMEOUT_MS, timeout_ms); + OPTION(CURLOPT_POST, 1L); + OPTION(CURLOPT_POSTFIELDS, request); + OPTION(CURLOPT_POSTFIELDSIZE, (long)n); + OPTION(CURLOPT_HTTPHEADER, headers); + OPTION(CURLOPT_WRITEFUNCTION, receive_reply); + OPTION(CURLOPT_WRITEDATA, reply); + if (tls_ca_file != NULL && *tls_ca_file != '\0') + OPTION(CURLOPT_CAINFO, tls_ca_file); + reply->error = "transport_failed"; + if (curl_easy_perform(curl) != CURLE_OK || + curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status) != CURLE_OK || status != 200) + goto http_done; + reply->error = "invalid_response"; + cursor = reply->data; + resp = d2i_TS_RESP(NULL, &cursor, (long)reply->size); + if (resp == NULL || cursor != reply->data + reply->size) + goto http_done; + store = X509_STORE_new(); + verify = TS_REQ_to_TS_VERIFY_CTX(req, NULL); + if (store == NULL || verify == NULL || X509_STORE_load_locations(store, ca_file, NULL) != 1) + goto http_done; + X509_VERIFY_PARAM_set_auth_level(X509_STORE_get0_param(store), 2); + /* This context already checks the requested imprint, version and nonce. + * Signature verification additionally checks the explicit trust and TSA EKU. */ +#if OPENSSL_VERSION_NUMBER >= 0x30400000L + if (TS_VERIFY_CTX_set0_store(verify, store) != 1) + goto http_done; +#else + TS_VERIFY_CTX_set_store(verify, store); +#endif + store = NULL; + TS_VERIFY_CTX_add_flags(verify, TS_VFY_SIGNATURE); + reply->error = "untrusted_response"; + /* libcrypto also accepts legacy CMS digests; require SHA-2 evidence. */ + if (TS_RESP_get_token(resp) == NULL || + (signers = PKCS7_get_signer_info(TS_RESP_get_token(resp))) == NULL || + sk_PKCS7_SIGNER_INFO_num(signers) != 1) + goto http_done; + PKCS7_SIGNER_INFO_get0_algs(sk_PKCS7_SIGNER_INFO_value(signers, 0), NULL, &digest, NULL); + if (digest == NULL) + goto http_done; + X509_ALGOR_get0(&digest_oid, NULL, NULL, digest); + n = OBJ_obj2nid(digest_oid); + if (n != NID_sha256 && n != NID_sha384 && n != NID_sha512) + goto http_done; + if (TS_RESP_verify_response(verify, resp) != 1) + goto http_done; + if (ASN1_TIME_to_tm((const ASN1_TIME *)TS_TST_INFO_get_time(TS_RESP_get_tst_info(resp)), &tm) != 1 || + tm.tm_year < 70 || tm.tm_year > 8099) + goto http_done; + snprintf(reply->at, sizeof(reply->at), "%04d-%02d-%02dT%02d:%02d:%02dZ", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); + reply->error = NULL; + rv = 0; +http_done: + curl_slist_free_all(headers); + curl_easy_cleanup(curl); + curl_global_cleanup(); +out: + TS_VERIFY_CTX_free(verify); + X509_STORE_free(store); + TS_RESP_free(resp); + OPENSSL_free(request); + ASN1_INTEGER_free(nonce); + BN_free(number); + X509_ALGOR_free(algorithm); + TS_MSG_IMPRINT_free(imprint); + TS_REQ_free(req); + ERR_clear_error(); + return rv; +#undef OPTION +}
diff --git a/src/timestamp.h b/src/timestamp.h @@ -0,0 +1,19 @@ +#ifndef SIGNET_TIMESTAMP_H +#define SIGNET_TIMESTAMP_H + +#include <stddef.h> + +#define TIMESTAMP_MAX_REPLY 65536 + +struct timestamp_reply { + unsigned char data[TIMESTAMP_MAX_REPLY]; + size_t size; + char at[32]; + const char *error; +}; + +/* HTTPS, SHA-256 imprint, fresh nonce, explicit TSA trust; no document upload. */ +int timestamp_fetch(const char *url, const char *ca_file, const char *tls_ca_file, + const char *sha256, long timeout_ms, struct timestamp_reply *reply); + +#endif
diff --git a/src/upload.c b/src/upload.c @@ -0,0 +1,96 @@ +#include <sys/stat.h> + +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +#include "upload.h" + +int +upload_chunk(const char *dir, size_t total, size_t received, size_t offset, + const void *data, size_t len, char *err, size_t errsz) +{ + const unsigned char *bytes = data; + char part[800], source[800], buf[16384]; + struct stat st; + size_t n, done = 0; + ssize_t got; + int fd = -1, dfd = -1, rv = -1; + + if (total > UPLOAD_MAX_BYTES || total < 6 || received > total || + offset > received || len == 0 || len > total || offset > total - len || + (offset < received && len > received - offset)) { + snprintf(err, errsz, "chunk is out of order or outside the declared PDF"); + return -2; + } + if (snprintf(part, sizeof(part), "%s/source.part", dir) >= (int)sizeof(part) || + snprintf(source, sizeof(source), "%s/source.pdf", dir) >= (int)sizeof(source)) + goto io; + if (received == total) + fd = open(source, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + else if (received == 0) + fd = open(part, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0640); + else { + fd = open(part, O_RDWR | O_CLOEXEC | O_NOFOLLOW); + /* A final rename can survive an uncertain SQL commit. */ + if (fd == -1 && errno == ENOENT && rename(source, part) == 0) + fd = open(part, O_RDWR | O_CLOEXEC | O_NOFOLLOW); + } + if (fd == -1 || fstat(fd, &st) == -1 || !S_ISREG(st.st_mode) || + st.st_nlink != 1 || st.st_size < 0 || (size_t)st.st_size < received || + (received == total && (size_t)st.st_size != total) || + (dfd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)) == -1) + goto io; + if (offset < received) { + /* A retry must never overwrite an acknowledged prefix. */ + while (done < len) { + n = len - done < sizeof(buf) ? len - done : sizeof(buf); + got = pread(fd, buf, n, (off_t)(offset + done)); + if (got == -1 && errno == EINTR) + continue; + if (got <= 0) + goto io; + if (memcmp(buf, bytes + done, (size_t)got) != 0) { + snprintf(err, errsz, "retry differs from an acknowledged chunk"); + rv = -2; + goto out; + } + done += (size_t)got; + } + if (fsync(dfd) == -1) + goto io; + rv = (int)received; + goto out; + } + /* SQL owns the offset: discard only an uncommitted suffix. */ + if (ftruncate(fd, (off_t)received) == -1) + goto io; + while (done < len) { + n = len - done < sizeof(buf) ? len - done : sizeof(buf); + got = pwrite(fd, bytes + done, n, (off_t)(received + done)); + if (got == -1 && errno == EINTR) + continue; + if (got <= 0) + goto io; + done += (size_t)got; + } + if (fsync(fd) == -1) + goto io; + if (received + len == total && rename(part, source) == -1) + goto io; + /* Persist initial part creation as well as final/recovery renames. */ + if (fsync(dfd) == -1) + goto io; + rv = (int)(received + len); + goto out; +io: + snprintf(err, errsz, "could not store PDF chunk; retry the same offset"); +out: + if (dfd != -1) + close(dfd); + if (fd != -1) + close(fd); + return rv; +}
diff --git a/src/upload.h b/src/upload.h @@ -0,0 +1,13 @@ +#ifndef SIGNET_UPLOAD_H +#define SIGNET_UPLOAD_H + +#include <stddef.h> + +#define UPLOAD_MAX_BYTES (32u * 1024 * 1024) +#define UPLOAD_CHUNK_BYTES (256u * 1024) + +/* Caller holds the draft's row lock. Returns next offset, -2 conflict, -1 I/O. */ +int upload_chunk(const char *, size_t, size_t, size_t, const void *, size_t, + char *, size_t); + +#endif
diff --git a/src/util.c b/src/util.c @@ -326,9 +326,12 @@ utf8_next(const char **sp) /* --- logging -------------------------------------------------------------- */ +static const char *log_ident = "signet"; + void log_open(const char *ident) { + log_ident = ident; openlog(ident, LOG_PID, LOG_LOCAL0); } @@ -336,27 +339,71 @@ void log_err(const char *fmt, ...) { va_list ap; + char message[512]; va_start(ap, fmt); - vsyslog(LOG_ERR, fmt, ap); - va_end(ap); - fprintf(stderr, "signet: "); - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); + vsnprintf(message, sizeof(message), fmt, ap); va_end(ap); - fprintf(stderr, "\n"); + syslog(LOG_ERR, "%s", message); + fprintf(stderr, "%s[%ld]: %s\n", log_ident, (long)getpid(), message); +} + +/* Never copy arbitrary path components, UUIDs or query values into logs. */ +static void +log_route(const char *path, char route[256]) +{ + static const char *const names[] = { + "me", "facsimile", "default", "retry", "facsimiles", "pim", "dam", + "templates", "retire", "delete", "series", "docs", "file", "source", + "proof", "stamped", "final", "save", "upload", "submit", "rerender", + "decide", "unlink", "attrs", "resync" + }; + const char *part = path ? path : "", *label; + char id[37]; + size_t len, i, o = 0; + int depth; + + for (depth = 0; depth < 5; depth++) { + while (*part == '/') + part++; + if (*part == '\0' || *part == '?') + break; + len = strcspn(part, "/?"); + label = ":other"; + for (i = 0; i < sizeof(names) / sizeof(names[0]); i++) + if (strlen(names[i]) == len && strncmp(part, names[i], len) == 0) { + label = names[i]; + break; + } + if (len == 36) { + memcpy(id, part, 36); + id[36] = '\0'; + if (is_uuid(id)) + label = ":id"; + } + o += (size_t)snprintf(route + o, 256 - o, "/%s", label); + part += len; + } + if (o == 0) + snprintf(route, 256, "/"); + else if (*part && *part != '?') + snprintf(route + o, 256 - o, "/..."); } void log_request(const char *method, const char *path, const char *user, - int status, const char *msg) + int status, const char *site) { - if (status < 200 || status >= 300) { - syslog(LOG_WARNING, "%s %s (user=%s status=%d): %s", - method ? method : "?", path ? path : "/", - user ? user : "?", status, msg ? msg : ""); - fprintf(stderr, "signet: %s %s (user=%s status=%d): %s\n", - method ? method : "?", path ? path : "/", - user ? user : "?", status, msg ? msg : ""); - } + char route[256]; + + if (status < 400) + return; + log_route(path, route); + if (!is_safe_name(user)) + user = "anonymous"; + syslog(status >= 500 ? LOG_ERR : LOG_WARNING, + "request method=%s route=%s actor=%s status=%d site=%s", + method, route, user, status, site); + fprintf(stderr, "%s[%ld]: request method=%s route=%s actor=%s status=%d site=%s\n", + log_ident, (long)getpid(), method, route, user, status, site); }
diff --git a/src/util.h b/src/util.h @@ -59,10 +59,10 @@ uint32_t utf8_next(const char **s); /* initialize syslog with the given identity (e.g., "signet-api") */ void log_open(const char *ident); -/* log to syslog; for errors, include the PostgreSQL/Redis error text */ +/* Log to syslog and stderr; never pass private values or raw backend errors. */ void log_err(const char *fmt, ...); -/* log request failures (non-2xx responses) */ +/* Log 4xx/5xx: normalize route/actor; method/site must be code-owned strings. */ void log_request(const char *method, const char *path, const char *user, - int status, const char *msg); + int status, const char *site); #endif
diff --git a/test/db-cache.c b/test/db-cache.c @@ -0,0 +1,84 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "db.h" + +static int +scalar(PGconn *pg, const char *sql, int n, const char *const *params) +{ + PGresult *res = db_q(pg, sql, n, params); + int value; + + assert(res != NULL && PQntuples(res) == 1); + value = atoi(PQgetvalue(res, 0, 0)); + PQclear(res); + return value; +} + +int +main(int argc, char **argv) +{ + struct conf cf; + PGconn *pg; + PGresult *res; + const char *params[3]; + char *large; + int pid; + + assert(argc == 2 && conf_load(&cf, argv[1]) == 0); + pg = db_get(&cf); + assert(pg != NULL); + pid = PQbackendPID(pg); + assert(scalar(pg, "SELECT 1", 0, NULL) == 1); + db_request_done(); + pg = db_get(&cf); + assert(PQbackendPID(pg) == pid); + + assert(db_do(pg, "BEGIN", 0, NULL) == 0); + res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL); + assert(res != NULL && PQgetlength(res, 0, 0) == 524288); + PQclear(res); + assert(PQtransactionStatus(pg) == PQTRANS_INTRANS); + assert(PQbackendPID(pg) == pid); + assert(db_do(pg, "COMMIT", 0, NULL) == 0); + db_request_done(); + pg = db_get(&cf); + assert(PQbackendPID(pg) != pid); + pid = PQbackendPID(pg); + + large = malloc(524289); + assert(large != NULL); + memset(large, 'x', 524288); + large[524288] = '\0'; + params[0] = large; + assert(scalar(pg, "SELECT length($1::text)", 1, params) == 524288); + db_request_done(); + pg = db_get(&cf); + assert(PQbackendPID(pg) != pid); + pid = PQbackendPID(pg); + + large[204800] = '\0'; + params[1] = NULL; + params[2] = large; + assert(scalar(pg, "SELECT length($1::text) + COALESCE(length($2::text), 0) + length($3::text)", + 3, params) == 409600); + db_request_done(); + pg = db_get(&cf); + assert(PQbackendPID(pg) != pid); + pid = PQbackendPID(pg); + + large[204800] = 'x'; + assert(db_q(pg, "SELECT 1/0 WHERE $1::text IS NOT NULL", 1, params) == NULL); + db_request_done(); + pg = db_get(&cf); + assert(PQbackendPID(pg) != pid); + res = db_q(pg, "SELECT repeat('x', 524288)", 0, NULL); + assert(res != NULL); + PQclear(res); + db_request_done(); + free(large); + puts("database cache: small connection reuse, large results/params/errors recycled only at API boundary"); + return 0; +}
diff --git a/test/dev-restart-contract.sh b/test/dev-restart-contract.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# Run first on a fresh dev boot, before tests replace the original worker. +# Uses a graceful signal, never changes the shared VM/host clock. +set -eu +B=http://127.0.0.1:8080 +for pass in 1 2 3; do + WEB=$(pgrep -f '^lighttpd -D -f /src/test/lighttpd-dev.conf$') + WORKER=$(pgrep -f '^/usr/local/sbin/signetd$') + [ -n "$WEB" ] && [ -n "$WORKER" ] + kill -USR1 "$WEB" + sleep 1 + OK=no + for i in $(seq 1 10); do + if curl -fsS --max-time 1 "$B/" >/dev/null 2>&1; then OK=yes; break; fi + sleep .1 + done + [ "$OK" = yes ] || { echo 'FAIL - preview stops responding after graceful restart while worker stays alive'; exit 1; } + kill -0 "$WORKER" + [ "$(awk '/^PPid:/ {print $2}' "/proc/$WORKER/status")" != "$WEB" ] || { + echo 'FAIL - web server owns the long-lived signing worker'; exit 1; + } + curl -fsS --max-time 2 -H 'Remote-User: manager' -H 'Remote-Groups: management' "$B/api/me" | jq -e '.user=="manager"' >/dev/null + sleep .2 +done +echo 'dev graceful restart: HTTP/API responsive and signing worker preserved across three restarts'
diff --git a/test/dev-up.sh b/test/dev-up.sh @@ -20,28 +20,54 @@ 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 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;" + "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; GRANT SELECT, INSERT, UPDATE ON document_timestamps TO signetd;" su-exec signet psql -q -d signet -c \ "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 -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/image.jpg /var/www/dam/seals/agency_image.jpg -cp /src/test/fixtures/sig.png /var/lib/signatures/ceo.png -cp /src/test/fixtures/sig.png /var/lib/signatures/manager.png +# Demo defaults must never replace an existing organisation asset or facsimile. +cp -n /usr/share/fonts/dejavu/DejaVuSans.ttf /var/www/dam/fonts/ +cp -n /src/test/fixtures/seal.png /var/www/dam/seals/agency_seal.png +cp -n /src/test/fixtures/image.jpg /var/www/dam/seals/agency_image.jpg +cp -n /src/test/fixtures/sig.png /var/lib/signatures/ceo.png +cp -n /src/test/fixtures/sig.png /var/lib/signatures/manager.png 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 -sed -e 's|^db.conninfo.*|db.conninfo = dbname=signet host=/run/postgresql|' \ - /src/etc/signet.conf.example > /etc/signet/signet.conf +if [ ! -f /etc/signet/signet.conf ]; then + sed -e 's|^db.conninfo.*|db.conninfo = dbname=signet host=/run/postgresql|' \ + /src/etc/signet.conf.example > /etc/signet/signet.conf +fi chmod 0644 /etc/signet/signet.conf -kfcgi -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- /usr/local/libexec/signet-api -kfcgi -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api +cleanup() { + trap - 0 INT TERM + pkill -f '^lighttpd -D -f /src/test/lighttpd-dev.conf$' 2>/dev/null || true + pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true + pkill -f '^kfcgi .* /run/signet/(api|pim).sock' 2>/dev/null || true + redis-cli SHUTDOWN SAVE >/dev/null 2>&1 || true + su-exec postgres pg_ctl -D /var/lib/postgresql/data -m fast -w stop >/dev/null 2>&1 || true +} +trap cleanup 0 +trap 'exit 0' INT TERM +# Foreground supervisors preserve worker stderr for container capture, without +# requiring a syslog daemon. OpenRC production supervision is separate. +kfcgi -d -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- /usr/local/libexec/signet-api & +API_PID=$! +kfcgi -d -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api & +PIM_PID=$! +i=0 +while [ ! -S /run/signet/api.sock ] || [ ! -S /run/signet/pim.sock ]; do + if ! kill -0 "$API_PID" || ! kill -0 "$PIM_PID" || [ "$i" -ge 5 ]; then + echo 'FastCGI supervisors did not become ready' >&2 + exit 1 + fi + i=$((i + 1)) + sleep 1 +done su-exec signetd:signet /usr/local/sbin/signetd 2>>/tmp/signetd.log & # Isolated development supplies explicit headers; no authentication server needed. @@ -49,4 +75,9 @@ echo "signet dev stack on http://localhost:8080 (explicit identity headers requi echo " Signet: http://localhost:8080/" echo " PIM: http://localhost:8080/pim/" echo " Note: Do not expose this header-trusting dev stack to untrusted clients" -exec lighttpd -D -f /src/test/lighttpd-dev.conf +# Keep the worker a child of this shell, not of lighttpd: on graceful restart +# lighttpd waits for its children, which would otherwise include signetd. +lighttpd -D -f /src/test/lighttpd-dev.conf & +HTTP_PID=$! +if wait "$HTTP_PID"; then STATUS=0; else STATUS=$?; fi +exit "$STATUS"
diff --git a/test/e2e.sh b/test/e2e.sh @@ -4,6 +4,12 @@ set -eu if [ "${1-}" = image-contract ]; then exec sh /src/test/image-contract.sh fi +if [ "${1-}" = image-memory ]; then + exec sh /src/test/image-memory.sh +fi +if [ "${1-}" = pdfw-alloc ]; then + exec sh /src/test/pdfw-alloc.sh +fi if [ "${1-}" = command-contract ]; then exec sh /src/test/command-contract.sh fi @@ -16,9 +22,25 @@ fi if [ "${1-}" = identity-contract ]; then exec sh /src/test/identity-contract.sh fi +if [ "${1-}" = request-fields ]; then + exec sh /src/test/request-fields-contract.sh +fi +if [ "${1-}" = timestamp-contract ]; then + export SIGNET_TIMESTAMP_TEST_DISPOSABLE=yes + exec sh /src/test/timestamp-contract.sh +fi +if [ "${1-}" = logging-contract ]; then + exec sh /src/test/logging-contract.sh +fi +sh /src/test/dev-restart-contract.sh sh /src/test/command-contract.sh sh /src/test/image-contract.sh +sh /src/test/image-memory.sh +sh /src/test/pdfw-alloc.sh sh /src/test/identity-contract.sh +sh /src/test/request-fields-contract.sh +SIGNET_TIMESTAMP_TEST_DISPOSABLE=yes sh /src/test/timestamp-contract.sh +SIGNET_LOGGING_TEST_DISPOSABLE=yes sh /src/test/logging-contract.sh B=http://localhost:8080 curl -fsS "$B/pim/pim.js" >/dev/null # Clean installs must include the PIM client. X='X-Requested-With: signet' @@ -139,13 +161,14 @@ check 'last decision queues release, not synchronous success' "$(get)" '.status 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" +LAST_KEY=$(as "$LAST" management "$B/api/me" | jq -r .facsimile.id) +mv "/var/lib/signatures/$LAST_KEY.png" "/var/lib/signatures/$LAST_KEY.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" +mv "/var/lib/signatures/$LAST_KEY.png.e2e-saved" "/var/lib/signatures/$LAST_KEY.png" as "$LAST" management -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null start_worker wait_ready @@ -225,4 +248,11 @@ admin -H "$X" -d '' "$B/api/docs/$CHILD/unlink" >/dev/null admin -H "$X" -d '' "$B/api/templates/$TID/delete" >/dev/null ok 'template retire/unlink/delete regression' sh /src/test/snapshot-contract.sh +sh /src/test/signature-migration.sh +sh /src/test/signature-contract.sh +sh /src/test/metadata-contract.sh +sh /src/test/pim-contract.sh +sh /src/test/upload-migration.sh +sh /src/test/upload-contract.sh +sh /src/test/parser-contract.sh echo 'all passed'
diff --git a/test/http-fields-alloc.h b/test/http-fields-alloc.h @@ -0,0 +1,5 @@ +#include <stddef.h> +#include <stdlib.h> + +void *fields_realloc(void *, size_t); +#define realloc fields_realloc
diff --git a/test/http-fields.c b/test/http-fields.c @@ -0,0 +1,98 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "http.h" + +static int fail_resize; + +void * +fields_realloc(void *p, size_t n) +{ + return fail_resize ? NULL : realloc(p, n); +} + +static void +pair(struct kpair *p, const char *key, const char *value) +{ + p->key = strdup(key); + p->val = strdup(value); + p->valsz = strlen(value); + p->file = strdup("fixture.png"); + p->ctype = strdup("application/octet-stream"); + p->xcode = strdup("binary"); + assert(p->key && p->val && p->file && p->ctype && p->xcode); +} + +static void +exercise(int fail) +{ + static const char *const names[] = { "file", "json", "scope" }; + struct kreq r; + struct kpair *file; + size_t i; + char key[64]; + + memset(&r, 0, sizeof(r)); + r.fieldsz = 10006; + r.fields = calloc(r.fieldsz, sizeof(*r.fields)); + r.cookiesz = 1000; + r.cookies = calloc(r.cookiesz, sizeof(*r.cookies)); + assert(r.fields && r.cookies); + for (i = 0; i < 10000; i++) { + snprintf(key, sizeof(key), "unused-%zu", i); + pair(&r.fields[i], key, "ignored"); + } + pair(&r.fields[10000], "json", "first"); + pair(&r.fields[10001], "json", "second"); + pair(&r.fields[10002], "file", "PDF"); + r.fields[10002].val[1] = '\0'; + pair(&r.fields[10003], "scope", ""); + pair(&r.fields[10004], "scope", "all"); + pair(&r.fields[10005], "file", "wrong duplicate"); + for (i = 0; i < r.cookiesz; i++) + pair(&r.cookies[i], "identity-is-not-a-cookie", "ignored"); + + /* Never move a mapped request's storage out from under kcgi's maps. */ + r.keysz = 1; + assert(http_keep_fields(&r, names, 3) == -1); + assert(r.fieldsz == 10006 && r.cookiesz == 1000); + r.keysz = 0; + fail_resize = fail; + assert(http_keep_fields(&r, names, 3) == (fail ? -1 : 0)); + assert(r.fieldsz == 3 && r.cookiesz == 0 && r.cookies == NULL); + assert(strcmp(http_field_str(&r, "json"), "first") == 0); + assert(strcmp(http_field_str(&r, "scope"), "") == 0); + file = http_field(&r, "file"); + assert(file && file->valsz == 3 && memcmp(file->val, "P\0F", 3) == 0); + assert(strcmp(file->file, "fixture.png") == 0); + assert(http_field_str(&r, "file") == NULL); + assert(http_field(&r, "unused-0") == NULL); + assert(file->next == NULL); + fail_resize = 0; + if (!fail) { + assert(http_keep_fields(&r, names, 3) == 0); + assert(r.fieldsz == 3); + } + /* Exercise the real library destructor after moving/removing its pairs. */ + khttp_child_free(&r); + + memset(&r, 0, sizeof(r)); + r.fieldsz = 1; + r.fields = calloc(1, sizeof(*r.fields)); + assert(r.fields); + pair(r.fields, "unknown", "ignored"); + assert(http_keep_fields(&r, names, 3) == 0); + assert(r.fields == NULL && r.fieldsz == 0); + khttp_child_free(&r); +} + +int +main(void) +{ + exercise(0); + exercise(1); + puts("request fields: bounded retention, first values, binary files, cookies and failed shrink passed"); + return 0; +}
diff --git a/test/identity-contract.sh b/test/identity-contract.sh @@ -8,11 +8,25 @@ cp "$CF" "$BACKUP" stop_apis() { pkill -f '^kfcgi .* /run/signet/(api|pim).sock' 2>/dev/null || true pkill -f '^/usr/local/libexec/(signet-api|pim-api)' 2>/dev/null || true + i=0 + while pgrep -f '^kfcgi .* /run/signet/(api|pim).sock' >/dev/null; do + [ "$i" -lt 5 ] || return 1 + i=$((i + 1)) + sleep 1 + done rm -f /run/signet/api.sock /run/signet/pim.sock } start_apis() { - kfcgi -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- /usr/local/libexec/signet-api - kfcgi -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api + kfcgi -d -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- /usr/local/libexec/signet-api >>/proc/1/fd/2 2>&1 & + api=$! + kfcgi -d -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api >>/proc/1/fd/2 2>&1 & + pim=$! + i=0 + while [ ! -S /run/signet/api.sock ] || [ ! -S /run/signet/pim.sock ]; do + kill -0 "$api" && kill -0 "$pim" && [ "$i" -lt 5 ] || return 1 + i=$((i + 1)) + sleep 1 + done } cleanup() { cp "$BACKUP" "$CF" @@ -20,7 +34,7 @@ cleanup() { start_apis rm -f "$BACKUP" } -trap cleanup EXIT +trap cleanup 0 fail() { echo "FAIL - $*"; exit 1; } status() { want=$1; shift
diff --git a/test/image-contract.c b/test/image-contract.c @@ -1,5 +1,8 @@ #include <assert.h> #include <stdio.h> +#include <string.h> + +#include <png.h> #include "pdfw.h" #include "util.h" @@ -10,6 +13,26 @@ main(int argc, char **argv) pdfw *p; int w, h; char opaque[1024], output[1024]; + const unsigned char rgb[] = { 10, 20, 30, 200, 210, 220 }; + const unsigned char rgba[] = { 10, 20, 30, 0, 40, 50, 60, 128, 70, 80, 90, 255 }; + const unsigned char solid[] = { 1, 2, 3, 255, 4, 5, 6, 255, 7, 8, 9, 255, 10, 11, 12, 255 }; + const unsigned char gray[] = { 0, 50, 100, 200, 255 }; + const unsigned char indices[] = { 0, 1, 0, 1, 0, 1 }; + const unsigned char palette[] = { 10, 20, 30, 0, 200, 210, 220, 128 }; + const struct { + png_uint_32 format; + const unsigned char *data; + int alpha; + } variants[] = { + { PNG_FORMAT_RGB, rgb, 0 }, + { PNG_FORMAT_RGBA, rgba, 1 }, + { PNG_FORMAT_RGBA, solid, 0 }, + { PNG_FORMAT_GRAY, gray, 0 }, + { PNG_FORMAT_RGBA_COLORMAP, indices, 1 } + }; + size_t i, x; + FILE *colors, *alpha; + png_image png; assert(argc == 4); snprintf(opaque, sizeof(opaque), "%s/asset-0", argv[3]); @@ -27,6 +50,44 @@ main(int argc, char **argv) assert(copy_file(argv[2], opaque) == 0); assert(pdfw_image_size(p, opaque, &w, &h) == 0 && w == 200 && h == 200); assert(pdfw_image(p, opaque, 50, 300, 200, 200) == 0); + for (i = 0; i < sizeof(variants) / sizeof(variants[0]); i++) { + memset(&png, 0, sizeof(png)); + png.version = PNG_IMAGE_VERSION; + png.width = (png_uint_32)i + 2; + png.height = 1; + png.format = variants[i].format; + png.colormap_entries = 2; + snprintf(opaque, sizeof(opaque), "%s/variant-%zu.png", argv[3], i + 2); + assert(png_image_write_to_file(&png, opaque, 0, variants[i].data, + 0, palette) != 0); + assert(pdfw_image(p, opaque, 10, 10 + i * 20, 100, 10) == 0); + snprintf(opaque, sizeof(opaque), "%s/variant-%zu.rgb", argv[3], i + 2); + assert((colors = fopen(opaque, "wb")) != NULL); + alpha = NULL; + if (variants[i].alpha) { + snprintf(opaque, sizeof(opaque), "%s/variant-%zu.alpha", argv[3], i + 2); + assert((alpha = fopen(opaque, "wb")) != NULL); + } + for (x = 0; x < i + 2; x++) { + const unsigned char *pixel; + + if (png.format & PNG_FORMAT_FLAG_COLORMAP) + pixel = palette + indices[x] * 4; + else if (png.format == PNG_FORMAT_GRAY) { + assert(fputc(gray[x], colors) != EOF); + assert(fputc(gray[x], colors) != EOF); + assert(fputc(gray[x], colors) != EOF); + continue; + } else + pixel = variants[i].data + x * (png.format == PNG_FORMAT_RGBA ? 4 : 3); + assert(fwrite(pixel, 1, 3, colors) == 3); + if (alpha != NULL) + assert(fputc(pixel[3], alpha) != EOF); + } + assert(fclose(colors) == 0); + if (alpha != NULL) + assert(fclose(alpha) == 0); + } assert(pdfw_close(p) == 0); puts("image content contract: all passed"); return 0;
diff --git a/test/image-contract.sh b/test/image-contract.sh @@ -11,4 +11,19 @@ ${CC:-cc} -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ "$TMP/sha256.o" -lpng -lz -lm -o "$TMP/image-contract" "$TMP/image-contract" test/fixtures/image.jpg test/fixtures/seal.png "$TMP" qpdf --check "$TMP/image.pdf" >/dev/null -qpdf --json "$TMP/image.pdf" | jq -e '[.. | objects | select(.["/Subtype"]? == "/Image") | .["/Interpolate"]] | length > 0 and all(. == true)' >/dev/null +qpdf --json "$TMP/image.pdf" > "$TMP/image.json" +jq -e '[.. | objects | select(.["/Subtype"]? == "/Image") | .["/Interpolate"]] | length > 0 and all(. == true)' "$TMP/image.json" >/dev/null +for width in 2 3 4 5 6; do + jq -e --argjson width "$width" '.qpdf[1] | to_entries | map(select(.value.stream.dict["/ColorSpace"] == "/DeviceRGB" and .value.stream.dict["/Width"] == $width and .value.stream.dict["/Height"] == 1)) | if length == 1 then .[0] else error("expected one RGB variant") end' "$TMP/image.json" > "$TMP/variant.json" + object=$(jq -er '.key | capture("obj:(?<id>[0-9]+)").id' "$TMP/variant.json") + qpdf --show-object="$object" --filtered-stream-data "$TMP/image.pdf" > "$TMP/actual-rgb" + cmp "$TMP/variant-$width.rgb" "$TMP/actual-rgb" + if [ -f "$TMP/variant-$width.alpha" ]; then + mask=$(jq -er '.value.stream.dict["/SMask"] | split(" ")[0]' "$TMP/variant.json") + qpdf --show-object="$mask" --filtered-stream-data "$TMP/image.pdf" > "$TMP/actual-alpha" + cmp "$TMP/variant-$width.alpha" "$TMP/actual-alpha" + else + jq -e '.value.stream.dict["/SMask"] == null' "$TMP/variant.json" > /dev/null + fi +done +echo 'image streams: RGB, gray, opaque RGBA, transparent RGBA/palette exact bytes passed'
diff --git a/test/image-memory.sh b/test/image-memory.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Linux native writer regression only; does not certify the application cohort. +set -eu +ulimit -c 0 +cd "$(dirname "$0")/.." +T=$(mktemp -d /tmp/signet-image-memory.XXXXXX) +trap 'rm -rf "$T"' 0 +trap 'exit 1' HUP INT TERM +CC=${CC:-cc} +"$CC" -O2 -std=c99 -Wall -Wextra test/resource-image.c -lpng -o "$T/image" +"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o" +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor test/resource-pdfw.c src/pdfw.c src/ttf.c src/util.c \ + "$T/sha256.o" -lpng -lz -lm -o "$T/writer" +"$T/image" "$T/image.png" "$T/rgb" +cp /usr/share/fonts/dejavu/DejaVuSans.ttf "$T/font.ttf" +dd if=/dev/zero bs=1048576 count=2 >> "$T/font.ttf" 2>/dev/null +"$T/writer" "$T/font.ttf" "$T/image.png" "$T/image.pdf" +if "$T/writer" "$T/font.ttf" "$T/image.png" /dev/full; then + echo 'FAIL - writer accepted a failed output stream' >&2 + exit 1 +fi +qpdf --check "$T/image.pdf" > /dev/null +qpdf --json "$T/image.pdf" > "$T/image.json" +font_bytes=$(wc -c < "$T/font.ttf") +image_obj=$(jq -er '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Subtype"] == "/Image")) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected one image") end' "$T/image.json") +font_obj=$(jq -er --argjson size "$font_bytes" '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Length1"] == $size)) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected exact font") end' "$T/image.json") +qpdf --show-object="$image_obj" --filtered-stream-data "$T/image.pdf" > "$T/actual-rgb" +qpdf --show-object="$font_obj" --filtered-stream-data "$T/image.pdf" > "$T/actual-font" +cmp "$T/rgb" "$T/actual-rgb" +cmp "$T/font.ttf" "$T/actual-font" +pdftotext "$T/image.pdf" "$T/text" +grep -q 'Font stays live while PNG is embedded: ₹' "$T/text" +echo 'image memory contract: maximum PNG and live font, exact RGB/font bytes and Unicode passed'
diff --git a/test/lighttpd-dev.conf b/test/lighttpd-dev.conf @@ -6,6 +6,14 @@ server.username = "lighttpd" server.groupname = "lighttpd" server.errorlog = "/dev/stderr" server.max-request-size = 34000 +# Dense form encodings amplify per-field allocations before handlers run. +# Large logical JSON/PNG fields and PDF chunks use multipart, not URL encoding. +$HTTP["url"] =~ "^/(api|pim-api)" { + server.max-request-size = 16 + $REQUEST_HEADER["Content-Type"] =~ "(?i)^multipart/form-data[ \\t]*;" { + server.max-request-size = 1100 + } +} index-file.names = ( "index.html" ) mimetype.assign = ( ".html" => "text/html", ".js" => "text/javascript", ".css" => "text/css", ".png" => "image/png", ".jpg" => "image/jpeg", ".ttf" => "font/ttf", ".pdf" => "application/pdf" )
diff --git a/test/log-request.c b/test/log-request.c @@ -0,0 +1,22 @@ +#include <string.h> + +#include "util.h" + +int +main(void) +{ + char long_path[4096]; + + log_open("logging-fixture"); + log_request("GET", "/docs/LOG_PRIVATE\nfake/file/proof?token=LOG_PRIVATE", + "LOG_PRIVATE\ractor", 400, "fixture:1"); + memset(long_path, 'x', sizeof(long_path) - 1); + long_path[0] = '/'; + long_path[sizeof(long_path) - 1] = '\0'; + log_request("POST", long_path, "valid-user", 500, "fixture:2"); + log_request("GET", NULL, NULL, 401, "fixture:3"); + log_request("POST", "/docs/00000000-0000-0000-0000-000000000000/save", + "valid-user", 409, "fixture:4"); + log_request("GET", "/me", "success", 200, "fixture:5"); + return 0; +}
diff --git a/test/logging-contract.sh b/test/logging-contract.sh @@ -0,0 +1,141 @@ +#!/bin/sh +# Destructive isolated-dev check: real API requests and a temporary LOCAL0 sink. +set -eu +[ "${SIGNET_LOGGING_TEST_DISPOSABLE:-}" = yes ] || { + echo 'refusing: set SIGNET_LOGGING_TEST_DISPOSABLE=yes on a disposable stack' >&2 + exit 2 +} +cd /src +umask 077 +T=$(mktemp -d /tmp/signet-logging.XXXXXX) +ACTOR=lc_$$ +SECRET=LOG_PRIVATE_$$ +ORG=lc_org_$$ +NAME=lc_fail_$$ +SAVED=lc_saved_$$ +SYSLOG=; SOCKET_OWNED=no; SQL_SETUP=no; REDIS_POISON=no; REDIS_SAVED=no +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; } +cleanup() { + if [ "$SQL_SETUP" = yes ]; then + sql -c "DROP TRIGGER IF EXISTS $NAME ON pim_attributes; DROP TRIGGER IF EXISTS $NAME ON series; DROP FUNCTION IF EXISTS $NAME();" >/dev/null 2>&1 || true + fi + if [ "$REDIS_POISON" = yes ]; then + redis-cli DEL pim:orgs >/dev/null 2>&1 || true + [ "$REDIS_SAVED" = no ] || redis-cli RENAME "$SAVED" pim:orgs >/dev/null 2>&1 || true + fi + if [ -n "$SYSLOG" ]; then + kill -TERM "$SYSLOG" 2>/dev/null || true + wait "$SYSLOG" 2>/dev/null || true + fi + [ "$SOCKET_OWNED" = no ] || rm -f /dev/log + rm -rf "$T" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +[ ! -e /dev/log ] && [ ! -L /dev/log ] || { + echo 'FAIL - refusing to replace an existing syslog socket' >&2; exit 1; +} +CC=${CC:-cc} +"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o" +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor test/log-request.c src/util.c "$T/sha256.o" -o "$T/log-request" +"$T/log-request" 2> "$T/unit-stderr" +[ "$(wc -l < "$T/unit-stderr" | tr -d ' ')" = 4 ] +! grep -qE 'LOG_PRIVATE|success|fake|token=' "$T/unit-stderr" +grep -F 'route=/docs/:other/file/proof actor=anonymous status=400 site=fixture:1' "$T/unit-stderr" >/dev/null +grep -F 'route=/docs/:id/save actor=valid-user status=409 site=fixture:4' "$T/unit-stderr" >/dev/null +printf 'local0.warn\t%s\n' "$T/local0" > "$T/syslog.conf" +syslogd -n -O /dev/null -s 0 -f "$T/syslog.conf" > "$T/syslogd" 2>&1 & +SYSLOG=$! +tries=0 +while [ ! -S /dev/log ] && [ "$tries" -lt 5 ]; do + kill -0 "$SYSLOG" + tries=$((tries + 1)) + sleep 1 +done +[ -S /dev/log ] || { echo 'FAIL - syslog socket unavailable' >&2; exit 1; } +SOCKET_OWNED=yes +logger -p user.err "$SECRET-facility" +logger -p local0.info "$SECRET-priority" +for binary in signet-api pim-api; do + if SIGNET_CONF="$T/$SECRET-config" "/usr/local/libexec/$binary" 2> "$T/startup"; then + echo 'FAIL - API accepted missing configuration' >&2; exit 1 + fi + grep -F 'cannot read configuration' "$T/startup" >/dev/null +done +request() { + want=$1; app=$2; method=$3; route=$4; actor=$5; path=$6; shift 6 + if [ "$actor" != anonymous ]; then set -- -H "Remote-User: $actor" "$@"; fi + code=$(curl --max-time 20 -sS -o "$T/response" -w '%{http_code}' \ + -X "$method" "$@" "http://127.0.0.1:8080/$path") + [ "$code" = "$want" ] || { echo "FAIL - $app $method status=$code expected=$want" >&2; exit 1; } + match="request method=$method route=$route actor=$actor status=$want site=" + tries=0 + while [ "$tries" -lt 5 ]; do + if [ -f "$T/local0" ] && grep -F "$app[" "$T/local0" > "$T/component" && + grep -F "$match" "$T/component" > "$T/matched"; then break; fi + tries=$((tries + 1)) + sleep 1 + done + [ -f "$T/matched" ] && [ "$(wc -l < "$T/matched" | tr -d ' ')" = 1 ] && + grep -F "$app[" "$T/matched" >/dev/null && + grep -E 'site=[A-Za-z_][A-Za-z0-9_]*:[0-9]+$' "$T/matched" >/dev/null || { + echo "FAIL - missing/duplicate/unsafe LOCAL0 record: $app $method $route status=$want" >&2; exit 1; + } + printf 'expect_request=%s|%s|%s|%s|%s\n' "$app" "$method" "$route" "$actor" "$want" +} +request 400 signet-api POST /docs "${ACTOR}_doc" api/docs \ + -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -d "unused=$SECRET-body" +request 400 pim-api POST /attrs "${ACTOR}_pim" pim-api/attrs \ + -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "org=$ORG&value=$SECRET-value" +request 404 signet-api GET /:other "${ACTOR}_path" "api/$SECRET-path?token=$SECRET-query" \ + -H "Authorization: Bearer $SECRET-token" -H "Cookie: credential=$SECRET-cookie" +request 404 signet-api GET /docs/:id/file/proof "${ACTOR}_file" \ + api/docs/00000000-0000-0000-0000-000000000000/file/proof +request 401 signet-api GET /me anonymous api/me -H 'Remote-User:' +request 401 pim-api GET /me anonymous pim-api/me -H "Remote-User: $SECRET/invalid" +request 403 signet-api POST /docs "${ACTOR}_csrf" api/docs -H 'Remote-Groups: clerks' -d '' +request 403 pim-api POST /attrs "${ACTOR}_role" pim-api/attrs \ + -H 'Remote-Groups: unknown' -H 'X-Requested-With: signet' -d '' +# Backend messages/DETAIL may repeat submitted values; log only SQLSTATE. +SQL_SETUP=yes +sql -c "CREATE FUNCTION $NAME() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF TG_TABLE_NAME='series' THEN RAISE EXCEPTION '$SECRET-db' USING DETAIL='$SECRET-detail', ERRCODE='23505'; ELSE RAISE EXCEPTION '$SECRET-db' USING DETAIL='$SECRET-detail'; END IF; END \$\$; CREATE TRIGGER $NAME BEFORE INSERT ON series FOR EACH ROW WHEN (NEW.code='$SECRET') EXECUTE FUNCTION $NAME(); CREATE TRIGGER $NAME BEFORE INSERT ON pim_attributes FOR EACH ROW WHEN (NEW.org_code='$ORG') EXECUTE FUNCTION $NAME();" >/dev/null +request 500 signet-api POST /series "${ACTOR}_sql" api/series \ + -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "code=$SECRET&pattern=TEST/{seq:02}" +request 500 pim-api POST /attrs "${ACTOR}_sql" pim-api/attrs \ + -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d "org=$ORG&key=test&type=text&value=$SECRET-value" +[ "$(redis-cli EXISTS "$SAVED")" = 0 ] || { echo 'FAIL - Redis backup key exists' >&2; exit 1; } +if [ "$(redis-cli EXISTS pim:orgs)" = 1 ]; then + redis-cli RENAME pim:orgs "$SAVED" >/dev/null + REDIS_SAVED=yes +fi +REDIS_POISON=yes +redis-cli SET pim:orgs "$SECRET-redis" >/dev/null +request 503 pim-api POST /resync "${ACTOR}_redis" pim-api/resync \ + -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d '' +for app in api pim-api; do + curl --max-time 20 -fsS -H "Remote-User: ${ACTOR}_ok" -H 'Remote-Groups: clerks' \ + "http://127.0.0.1:8080/$app/me" > /dev/null +done +sleep 1 +! grep -qF "$SECRET" "$T/local0" || { echo 'FAIL - private data or excluded syslog facility/priority leaked' >&2; exit 1; } +! grep -qF "actor=${ACTOR}_ok " "$T/local0" || { echo 'FAIL - successful requests logged as failures' >&2; exit 1; } +grep -F 'SQLSTATE 23505' "$T/local0" > /dev/null +grep -F 'SQLSTATE P0001' "$T/local0" > /dev/null +kill -TERM "$SYSLOG" +wait "$SYSLOG" 2>/dev/null || true +SYSLOG= +rm -f /dev/log +SOCKET_OWNED=no +# The host-side check must see stderr records even without a syslog receiver. +for endpoint in api/docs pim-api/attrs; do + case "$endpoint" in api/docs) app=signet-api; route=/docs;; *) app=pim-api; route=/attrs;; esac + code=$(curl --max-time 20 -sS -o "$T/response" -w '%{http_code}' \ + -H "Remote-User: ${ACTOR}_fallback" -H 'Remote-Groups: clerks,signet-admins' \ + -H 'X-Requested-With: signet' -d '' "http://127.0.0.1:8080/$endpoint") + [ "$code" = 400 ] + printf 'expect_request=%s|POST|%s|%s_fallback|400\n' "$app" "$route" "$ACTOR" +done +printf 'logging_private_marker=%s\n' "$SECRET" +printf 'logging_success_actor=%s_ok\n' "$ACTOR" +echo 'logging contract: both API handler/auth/file/SQL/Redis failures, LOCAL0 filtering, privacy and success silence passed'
diff --git a/test/logging-dev.sh b/test/logging-dev.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# Run where the existing podman CLI works, against an explicitly disposable stack. +set -eu +[ "${SIGNET_LOGGING_TEST_DISPOSABLE:-}" = yes ] && [ "$#" = 1 ] || { + echo 'usage: SIGNET_LOGGING_TEST_DISPOSABLE=yes sh test/logging-dev.sh disposable-container' >&2 + exit 2 +} +umask 077 +T=$(mktemp -d /tmp/signet-logging-dev.XXXXXX) +trap 'rm -rf "$T"' 0 +trap 'exit 1' HUP INT TERM +podman logs "$1" > "$T/before" 2>&1 +before=$(wc -l < "$T/before") +podman exec -e SIGNET_LOGGING_TEST_DISPOSABLE=yes "$1" sh /src/test/logging-contract.sh > "$T/probe" +sleep 1 +podman logs "$1" > "$T/all" 2>&1 +awk -v before="$before" 'NR > before' "$T/all" > "$T/capture" +while IFS='|' read -r app method route actor status; do + match="request method=$method route=$route actor=$actor status=$status site=" + grep -F "$match" "$T/capture" > "$T/component" && + grep -E "^$app\\[[0-9]+\\]: " "$T/component" > "$T/matched" || { + echo "FAIL - real container capture missing $app $method $route status=$status" >&2; exit 1; + } + [ "$(wc -l < "$T/matched" | tr -d ' ')" = 1 ] || { + echo 'FAIL - duplicate request failure records in real capture' >&2; exit 1; + } +done <<EOF +$(awk -F= '/^expect_request=/ {print $2}' "$T/probe") +EOF +marker=$(awk -F= '/^logging_private_marker=/ {print $2}' "$T/probe") +success=$(awk -F= '/^logging_success_actor=/ {print $2}' "$T/probe") +[ -n "$marker" ] && [ -n "$success" ] +! grep -qF "$marker" "$T/capture" || { echo 'FAIL - private data in real container capture' >&2; exit 1; } +! grep -qF "actor=$success " "$T/capture" || { echo 'FAIL - success logged as failure' >&2; exit 1; } +cat "$T/probe" +echo 'logging dev capture: real podman logs contains both API failure records without private values'
diff --git a/test/metadata-contract.sh b/test/metadata-contract.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# Destructive fixture contracts: disposable dev stack only. +set -eu +B=http://localhost:8080 +X='X-Requested-With: signet' +T=$(mktemp -d /tmp/metadata-contract.XXXXXX) +trap 'rm -rf "$T"' EXIT +as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } +fail() { echo "FAIL - $*" >&2; exit 1; } +status() { want=$1; shift; got=$(curl -sS -o "$T/response" -w '%{http_code}' -H 'Remote-User: manager' -H 'Remote-Groups: management' -H "$X" "$@"); [ "$got" = "$want" ] || fail "HTTP $got expected $want"; } +getdoc() { as manager management "$B/api/docs/$ID"; } +newdoc() { + ID=$(as asha clerks -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -er .id) + J='{"title":"Metadata bounds","org_code":"METADATA18","route":{"parties":[{"name":"Signer","signer":"manager"}]},"layout":{"reference_width":1000,"reference_height":1414,"imprints":[{"type":"signature_zone","party":"Signer","page":1,"coords":[120,550,500,700],"min_w":50,"min_h":20}]}}' + as asha clerks -H "$X" --form-string "json=$J" "$B/api/docs/$ID/save" >/dev/null + as asha clerks -H "$X" -d '' "$B/api/docs/$ID/submit" >/dev/null + for i in $(seq 1 100); do + D=$(getdoc) + [ "$(echo "$D" | jq -r .render_error)" = null ] || fail 'fixture render failed' + [ "$(echo "$D" | jq -r .rendering)" = false ] && return + sleep .1 + done + fail 'fixture render timeout' +} +PL='{"page":1,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' +printf '%s' "$PL" > "$T/placement" +N=$(wc -c < "$T/placement") +head -c $((1048576-N)) /dev/zero | tr '\000' ' ' >> "$T/placement" +cp "$T/placement" "$T/over" +printf ' ' >> "$T/over" +if [ "${1-}" != legacy ]; then +newdoc +status 400 -F decision=signoff -F "placement=<$T/over" "$B/api/docs/$ID/decide" +getdoc | jq -e '(.decisions|length)==0 and .can_decide' >/dev/null || fail 'oversized placement changed decision state' +printf '%s\000suffix' "$PL" > "$T/nul" +status 400 -F decision=signoff -F "placement=<$T/nul" "$B/api/docs/$ID/decide" +status 200 -F decision=signoff -F "placement=<$T/placement" "$B/api/docs/$ID/decide" +fi +# Legacy pending layouts must be bounded in SQL before libpq materialises them. +newdoc +su-exec postgres psql -X -q -v ON_ERROR_STOP=1 -d signet -c "UPDATE documents SET layout_json=jsonb_set(layout_json,'{legacy_padding}',to_jsonb(repeat('界',350000))) WHERE id='$ID'" >/dev/null +status 409 -F decision=signoff --form-string "placement=$PL" "$B/api/docs/$ID/decide" +getdoc | jq -e '(.decisions|length)==0 and .can_decide' >/dev/null || fail 'oversized stored layout changed decision state' +# Returning the document for correction must remain possible without loading layout. +status 200 -F decision=correction -F comment=Resize "$B/api/docs/$ID/decide" +echo 'metadata contract: exact placement limit, oversize/NUL rejection, legacy layout bound and correction passed'
diff --git a/test/parser-contract.sh b/test/parser-contract.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Isolated dev only: pre-kcgi admission, not a whole-runtime RSS certificate. +set -eu +T=$(mktemp -d /tmp/parser-contract.XXXXXX) +trap 'rm -rf "$T"' EXIT +request() { + want=$1; path=$2; type=$3; shift 3 + code=$(curl --max-time 20 --path-as-is -sS -o "$T/reply" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -H "Content-Type: $type" "$@" --data-binary "@$T/body" "http://localhost:8080/$path") + [ "$code" = "$want" ] || { echo "FAIL - parser HTTP $code expected $want ($path, $type)" >&2; exit 1; } +} +# One byte over the dense-form transport cap must never enter kcgi. +awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x="}' > "$T/body" +for path in api/parser-probe apiBAD pim-api/parser-probe pim-apiBAD '%61pi/parser-probe' 'dam/../api/parser-probe'; do + for type in application/x-www-form-urlencoded text/plain application/json 'multipart/form-datax; boundary=z'; do + request 413 "$path" "$type" + done +done +# Ambiguous content types cannot select the large cap and a dense parser. +for first in 'multipart/form-data; boundary=z' application/x-www-form-urlencoded; do + second=application/x-www-form-urlencoded + [ "$first" != "$second" ] || second='multipart/form-data; boundary=z' + code=$(curl --max-time 20 -sS -o "$T/reply" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -H "Content-Type: $first" -H "Content-Type: $second" --data-binary "@$T/body" http://localhost:8080/api/parser-probe) + case "$code" in 400|413) ;; *) echo "FAIL - ambiguous content type HTTP $code" >&2; exit 1;; esac +done +# Unknown-length transfer must have the same cap as a known Content-Length. +request 413 api/parser-probe application/x-www-form-urlencoded -H 'Transfer-Encoding: chunked' +# Exact dense-form limit is still accepted by the parser (the route is unknown). +awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x"}' > "$T/body" +request 404 api/parser-probe application/x-www-form-urlencoded +# A real multipart body above16KiB remains admitted, including MIME case folding. +printf '%s\r\n' '--z' 'Content-Disposition: form-data; name="unused"' '' > "$T/body" +dd if=/dev/zero bs=1024 count=32 >> "$T/body" 2>/dev/null +printf '\r\n%s\r\n' '--z--' >> "$T/body" +request 404 api/parser-probe 'multipart/form-data; boundary=z' +request 404 api/parser-probe 'Multipart/Form-Data; boundary=z' +# Multipart itself retains the1100KiB transport cap. +dd if=/dev/zero of="$T/body" bs=1024 count=1101 2>/dev/null +request 413 api/parser-probe 'multipart/form-data; boundary=z' +echo 'parser contract: dense form cap/exact boundary, encoded prefixes, unknown-length transfer and multipart allowance passed'
diff --git a/test/pdfw-alloc.c b/test/pdfw-alloc.c @@ -0,0 +1,231 @@ +#include <sys/wait.h> + +#include <assert.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "pdfw.h" + +/* Only pdfw.c/ttf.c allocations are redirected, never libc or codec internals. */ +static void *live[1024]; +static size_t calls, fail_at; +static int persistent, failed; + +static int +reject(void) +{ + calls++; + if (fail_at && (calls == fail_at || (persistent && calls > fail_at))) { + failed = 1; + return 1; + } + return 0; +} + +static void +record(void *p) +{ + size_t i; + + if (p == NULL) + return; + for (i = 0; i < sizeof(live) / sizeof(live[0]); i++) + if (live[i] == NULL) { + live[i] = p; + return; + } + abort(); +} + +void * +test_malloc(size_t n) +{ + void *p; + + if (reject()) + return NULL; + p = malloc(n); + record(p); + return p; +} + +void * +test_calloc(size_t n, size_t size) +{ + void *p; + + if (reject()) + return NULL; + p = calloc(n, size); + record(p); + return p; +} + +void * +test_realloc(void *old, size_t n) +{ + void *p; + size_t i; + + if (reject()) + return NULL; + if (old == NULL) { + p = realloc(NULL, n); + record(p); + return p; + } + for (i = 0; i < sizeof(live) / sizeof(live[0]); i++) + if (live[i] == old) + break; + assert(i < sizeof(live) / sizeof(live[0])); + p = realloc(old, n); + if (p != NULL) + live[i] = p; + return p; +} + +char * +test_strdup(const char *s) +{ + char *p = test_malloc(strlen(s) + 1); + + if (p != NULL) + strcpy(p, s); + return p; +} + +void +test_free(void *p) +{ + size_t i; + + if (p == NULL) + return; + for (i = 0; i < sizeof(live) / sizeof(live[0]); i++) + if (live[i] == p) + break; + assert(i < sizeof(live) / sizeof(live[0])); + live[i] = NULL; + free(p); +} + +static int +check_leaks(void) +{ + size_t i, n = 0; + + for (i = 0; i < sizeof(live) / sizeof(live[0]); i++) + if (live[i] != NULL) + n++; + if (n) + fprintf(stderr, "FAIL: %zu writer/font allocations leaked\n", n); + return n ? 1 : 0; +} + +static int +exercise(const char *mode, const char *font_path, const char *image, + const char *output) +{ + pdfw *p; + char text[12000]; + int font, rc, image_rc; + + if (strcmp(mode, "open") == 0) { + fail_at = 2; + persistent = 1; + } + p = pdfw_open(output); + if (p == NULL) + return check_leaks(); + if (strcmp(mode, "open") == 0) { + pdfw_close(p); + fprintf(stderr, "FAIL: open accepted failed object allocation\n"); + return 1; + } + pdfw_page(p, 595, 842); + if (strcmp(mode, "growth") == 0) { + pdfw_text(p, PDFW_HELVETICA, 12, 10, 20, "initial buffer"); + fail_at = calls + 1; + } + if (strcmp(mode, "font-used") == 0) + fail_at = calls + 2; /* ttf bytes, then glyph bookkeeping */ + if (strcmp(mode, "font-path") == 0) + fail_at = calls + 3; + if (strcmp(mode, "growth") == 0) + font = PDFW_HELVETICA; + else + font = pdfw_font(p, font_path); + memset(text, 'A', sizeof(text) - 1); + text[sizeof(text) - 1] = '\0'; + pdfw_text(p, font, 12, 10, 20, text); + pdfw_clip_circle(p, 100, 100, 20); + image_rc = pdfw_image(p, image, 80, 80, 40, 40); + pdfw_clip_end(p); + pdfw_page(p, 842, 595); + pdfw_text(p, font, 12, 10, 20, "Second page (text) \\ and Unicode: ₹"); + pdfw_image(p, image, 80, 80, 40, 40); + rc = pdfw_close(p); + if (fail_at && !failed) { + fprintf(stderr, "FAIL: allocation injection not reached\n"); + return 1; + } + if ((!fail_at && (rc != 0 || font == PDFW_HELVETICA || image_rc != 0)) || + (failed && (strcmp(mode, "sweep") != 0 || + (font != PDFW_HELVETICA && image_rc == 0)) && rc != -1)) { + fprintf(stderr, "FAIL: unexpected render/close result %d\n", rc); + return 1; + } + return check_leaks(); +} + +static int +run_case(const char *mode, const char *font, const char *image, + const char *output, size_t at, int permanent) +{ + pid_t pid; + int status; + + fflush(NULL); + pid = fork(); + assert(pid != -1); + if (pid == 0) { + alarm(3); + calls = 0; + fail_at = at; + persistent = permanent; + exit(exercise(mode, font, image, output)); + } + assert(waitpid(pid, &status, 0) == pid); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + fprintf(stderr, "FAIL: %s allocation=%zu persistent=%d status=%d\n", + mode, at, permanent, status); + return 1; + } + return 0; +} + +int +main(int argc, char **argv) +{ + const char *modes[] = { "open", "growth", "font-used", "font-path" }; + size_t i, total; + int errors = 0, permanent; + + assert(argc == 4); + /* Keep the healthy two-page PDF for independent qpdf validation. */ + if (exercise("healthy", argv[1], argv[2], argv[3]) != 0) + return 1; + total = calls; + for (i = 0; i < sizeof(modes) / sizeof(modes[0]); i++) + errors += run_case(modes[i], argv[1], argv[2], "/dev/null", 0, 0); + for (permanent = 0; permanent <= 1; permanent++) + for (i = 1; i <= total; i++) + errors += run_case("sweep", argv[1], argv[2], "/dev/null", + i, permanent); + printf("pdfw allocation contract: %zu sites, transient/persistent failures, " + "%d failed cases\n", total, errors); + return errors ? 1 : 0; +}
diff --git a/test/pdfw-alloc.h b/test/pdfw-alloc.h @@ -0,0 +1,15 @@ +#include <stddef.h> +#include <stdlib.h> +#include <string.h> + +void *test_malloc(size_t); +void *test_calloc(size_t, size_t); +void *test_realloc(void *, size_t); +char *test_strdup(const char *); +void test_free(void *); + +#define malloc test_malloc +#define calloc test_calloc +#define realloc test_realloc +#define strdup test_strdup +#define free test_free
diff --git a/test/pdfw-alloc.sh b/test/pdfw-alloc.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Deterministic writer/font allocation faults; no services or real user assets. +set -eu +ulimit -c 0 +cd "$(dirname "$0")/.." +TMP=$(mktemp -d /tmp/signet-pdfw-alloc.XXXXXX) +trap 'rm -rf "$TMP"' 0 +trap 'exit 1' HUP INT TERM +FONT=${SIGNET_TEST_FONT:-/usr/share/fonts/dejavu/DejaVuSans.ttf} +CC=${CC:-cc} +"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$TMP/sha256.o" +for source in pdfw ttf; do + "$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor -include test/pdfw-alloc.h -c "src/$source.c" \ + -o "$TMP/$source.o" +done +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor test/pdfw-alloc.c src/util.c "$TMP/pdfw.o" "$TMP/ttf.o" \ + "$TMP/sha256.o" -lpng -lz -lm -o "$TMP/pdfw-alloc" +"$TMP/pdfw-alloc" "$FONT" test/fixtures/seal.png "$TMP/healthy.pdf" +qpdf --check "$TMP/healthy.pdf" >/dev/null +test "$(pdfinfo "$TMP/healthy.pdf" | awk '/^Pages:/ {print $2}')" = 2 +printf '%s\n' 'pdfw allocation contract: healthy two-page PDF passed'
diff --git a/test/pim-contract.sh b/test/pim-contract.sh @@ -0,0 +1,149 @@ +#!/bin/sh +# Destructive fixtures and worker signal: disposable dev stack only. +set -eu +B=http://localhost:8080 +T=$(mktemp -d /tmp/pim-contract.XXXXXX) +ORG=PIM19_$$ +MARK=pim-queue-preserve-$$ +APP=pim_order_probe_$$ +BG='' +HOLDER='' +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet -c "$1"; } +release() { sql "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='$APP'" >/dev/null; } +pool() { + pkill -f '^kfcgi.*pim.sock' 2>/dev/null || true + pkill -f '^/usr/local/libexec/pim-api$' 2>/dev/null || true + pool_wait=0 + while pgrep -f '^kfcgi.*pim.sock' >/dev/null; do + [ "$pool_wait" -lt 5 ] || return 1 + pool_wait=$((pool_wait + 1)) + sleep 1 + done + rm -f /run/signet/pim.sock + kfcgi -d -n "$1" -N "$1" -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api >>/proc/1/fd/2 2>&1 & + pool_pid=$! + pool_wait=0 + while [ ! -S /run/signet/pim.sock ]; do + kill -0 "$pool_pid" && [ "$pool_wait" -lt 5 ] || return 1 + pool_wait=$((pool_wait + 1)) + sleep 1 + done +} +WORKER=$(pgrep -f '^/usr/local/sbin/signetd$') +cleanup() { + release || true + for p in $BG $HOLDER; do wait "$p" 2>/dev/null || true; done + if [ "$(redis-cli EXISTS "$MARK:registry-backup")" = 1 ]; then + redis-cli DEL pim:orgs >/dev/null + redis-cli RENAME "$MARK:registry-backup" pim:orgs >/dev/null + fi + for q in queue:stamping queue:stamping:processing; do redis-cli LREM "$q" 0 "$MARK" >/dev/null; done + kill -CONT "$WORKER" 2>/dev/null || true + redis-cli DEL "$MARK:foreign" "$MARK:waiting" "$MARK:metadata" "$ORG:metadata" "$ORG:images" >/dev/null + redis-cli SREM pim:orgs "$ORG" >/dev/null + pool 1 + rm -rf "$T" +} +trap cleanup 0 +fail() { echo "FAIL - $*" >&2; exit 1; } +post() { curl --max-time 20 -fsS -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' "$@"; } +put() { post --form-string "org=$ORG" -F "key=$1" -F "type=$2" --form-string "value=$3" "$B/pim-api/attrs" >/dev/null; } +resync() { post -d '' "$B/pim-api/resync" >/dev/null; } +pool 2 +put text text first +put changing text old +kill -STOP "$WORKER" +# The blocked Redis BRPOPLPUSH may move one marker even while worker is stopped. +# Both list snapshots are stable after these synchronous pushes complete. +redis-cli LPUSH queue:stamping "$MARK" "$MARK" >/dev/null +redis-cli LPUSH queue:stamping:processing "$MARK" >/dev/null +redis-cli SET "$MARK:foreign" keep EX 600 >/dev/null +redis-cli LPUSH "$MARK:waiting" enrol-job stamp-job >/dev/null +redis-cli HSET "$MARK:metadata" external kept >/dev/null +redis-cli --raw LRANGE queue:stamping 0 -1 > "$T/queue" +redis-cli --raw LRANGE queue:stamping:processing 0 -1 > "$T/processing" +resync +[ "$(redis-cli --raw GET "$MARK:foreign")" = keep ] || fail 'resync deleted unrelated Redis key' +[ "$(redis-cli --raw LLEN "$MARK:waiting")" = 2 ] || fail 'resync deleted unrelated waiting jobs' +redis-cli --raw LRANGE queue:stamping 0 -1 > "$T/queue.after" +redis-cli --raw LRANGE queue:stamping:processing 0 -1 > "$T/processing.after" +cmp "$T/queue" "$T/queue.after" || fail 'waiting signing jobs changed' +cmp "$T/processing" "$T/processing.after" || fail 'processing signing jobs changed' +[ "$(redis-cli TTL "$MARK:foreign")" -gt 0 ] || fail 'foreign TTL lost' +put changing image seals/agency_seal.png +[ "$(redis-cli HEXISTS "$ORG:metadata" changing)" = 0 ] || fail 'type change retained stale text' +[ "$(redis-cli --raw HGET "$ORG:images" changing)" = seals/agency_seal.png ] || fail 'type change missing image' +# Delete by key, even if supplied type differs from its stored type. +put changing text '' +[ "$(redis-cli HEXISTS "$ORG:images" changing)" = 0 ] || fail 'delete retained stale opposite-type mirror' +# Resync repairs stale fields/types for current and previously managed organisations. +redis-cli HSET "$ORG:metadata" ghost stale >/dev/null +redis-cli HSET "$ORG:images" text wrong-type >/dev/null +sql "INSERT INTO pim_attributes (org_code,attr_key,attr_type,attr_value) VALUES ('$ORG','legacy_empty','text','')" >/dev/null +redis-cli HSET "$ORG:metadata" legacy_empty stale >/dev/null +resync +[ "$(redis-cli --raw HGET "$ORG:metadata" text)" = first ] || fail 'resync did not restore canonical text' +[ "$(redis-cli HEXISTS "$ORG:metadata" ghost)" = 0 ] || fail 'resync retained unknown attribute' +[ "$(redis-cli HEXISTS "$ORG:images" text)" = 0 ] || fail 'resync retained opposite type' +[ "$(redis-cli HEXISTS "$ORG:metadata" legacy_empty)" = 0 ] || fail 'legacy empty row became a cached value' +sql "DELETE FROM pim_attributes WHERE org_code='$ORG' AND attr_key='legacy_empty'" >/dev/null +# Wrong-type registry errors must be reported without changing other mirror keys. +redis-cli RENAME pim:orgs "$MARK:registry-backup" >/dev/null +redis-cli SET pim:orgs broken >/dev/null +CODE=$(curl --max-time 20 -sS -o "$T/error" -w '%{http_code}' -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d '' "$B/pim-api/resync") +[ "$CODE" = 503 ] || fail 'invalid registry reported success' +[ "$(redis-cli --raw HGET "$ORG:metadata" text)" = first ] || fail 'failed resync mutated canonical key' +[ "$(redis-cli --raw GET "$MARK:foreign")" = keep ] || fail 'failed resync mutated foreign key' +CODE=$(curl --max-time 20 -sS -o "$T/error" -w '%{http_code}' -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -F "org=$ORG" -F key=failed -F type=text -F value=saved "$B/pim-api/attrs") +[ "$CODE" = 503 ] || fail 'failed cache write reported success' +[ "$(sql "SELECT attr_value FROM pim_attributes WHERE org_code='$ORG' AND attr_key='failed'")" = saved ] || fail 'cache error lost committed PIM value' +[ "$(redis-cli HEXISTS "$ORG:metadata" failed)" = 0 ] || fail 'failed cache write partially changed mirror' +redis-cli DEL pim:orgs >/dev/null +redis-cli RENAME "$MARK:registry-backup" pim:orgs >/dev/null +resync +[ "$(redis-cli --raw HGET "$ORG:metadata" failed)" = saved ] || fail 'resync failed to recover committed value' +put failed text '' +redis-cli SADD pim:orgs .unsafe >/dev/null +CODE=$(curl --max-time 20 -sS -o "$T/error" -w '%{http_code}' -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -d '' "$B/pim-api/resync") +[ "$CODE" = 503 ] || fail 'invalid registry name reported success' +[ "$(redis-cli --raw HGET "$ORG:metadata" text)" = first ] || fail 'name validation error mutated mirror' +redis-cli SREM pim:orgs .unsafe >/dev/null +# Two actual PIM workers must serialize DB+mirror writes against resync. +env PGAPPNAME="$APP" su-exec postgres psql -X -qAt -d signet -c "SELECT pg_advisory_lock(hashtextextended('signet:pim-mirror',0)); SELECT pg_sleep(15)" > "$T/holder" 2>&1 & +HOLDER=$! +for n in $(seq 1 30); do + [ "$(sql "SELECT count(*) FROM pg_stat_activity WHERE application_name='$APP' AND wait_event='PgSleep'")" = 1 ] && break + sleep .1 +done +[ "$n" -lt 30 ] || fail 'owned mirror lock holder did not start' +put text text ordered > "$T/upsert" 2>&1 & +P1=$! +resync > "$T/resync" 2>&1 & +P2=$! +BG="$P1 $P2" +READY=0 +for n in $(seq 1 30); do + COUNT=$(sql "SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a USING(pid) WHERE l.locktype='advisory' AND NOT l.granted AND a.query LIKE '%signet:pim-mirror%'") + if [ "$COUNT" = 2 ]; then READY=1; break; fi + sleep .1 +done +[ "$READY" = 1 ] || fail 'both PIM handlers did not wait for the shared mirror lock' +[ "$(sql "SELECT attr_value FROM pim_attributes WHERE org_code='$ORG' AND attr_key='text'")" = first ] || fail 'write bypassed mirror lock' +release +wait "$P1"; wait "$P2" +BG='' +wait "$HOLDER" 2>/dev/null || true +HOLDER='' +[ "$(redis-cli --raw HGET "$ORG:metadata" text)" = ordered ] || fail 'concurrent resync lost newer value' +[ "$(sql "SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a USING(pid) WHERE l.locktype='advisory' AND a.query LIKE '%signet:pim-mirror%'")" = 0 ] || fail 'PIM handler retained session lock' +put text text '' +redis-cli HSET "$ORG:metadata" ghost stale >/dev/null +resync +[ "$(redis-cli EXISTS "$ORG:metadata" "$ORG:images")" = 0 ] || fail 'empty managed organisation retained stale keys' +redis-cli --raw LRANGE queue:stamping 0 -1 > "$T/queue.after" +redis-cli --raw LRANGE queue:stamping:processing 0 -1 > "$T/processing.after" +cmp "$T/queue" "$T/queue.after" || fail 'later PIM operations changed waiting jobs' +cmp "$T/processing" "$T/processing.after" || fail 'later PIM operations changed processing jobs' +[ "$(redis-cli --raw HGET "$MARK:metadata" external)" = kept ] || fail 'resync deleted unowned metadata hash' +[ "$(redis-cli --raw GET "$MARK:foreign")" = keep ] || fail 'later PIM operations changed foreign value' +echo 'PIM contract: queues/foreign keys preserved; canonical types/deletion, fail-closed errors and two-worker ordering passed'
diff --git a/test/render-contract.sh b/test/render-contract.sh @@ -128,18 +128,19 @@ 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'; + RAISE EXCEPTION 'ticket10 completion update failure' USING ERRCODE='P2210'; END IF; RETURN NEW; END $$; CREATE TRIGGER ticket10_fail BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION ticket10_fail(); SQL start_worker +# Match fixture SQLSTATE, not private PostgreSQL message/DETAIL text. for i in $(seq 1 80); do - grep -q 'ticket10 completion update failure' /tmp/render-contract-worker.log && break + grep -q 'SQLSTATE P2210' /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' +grep -q 'SQLSTATE P2210' /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' @@ -170,7 +171,7 @@ 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'; + RAISE EXCEPTION 'release completion update failure' USING ERRCODE='P2211'; END IF; RETURN NEW; END $$; @@ -178,10 +179,10 @@ CREATE TRIGGER ticket10_fail BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUN SQL start_worker for i in $(seq 1 80); do - grep -q 'release completion update failure' /tmp/render-contract-worker.log && break + grep -q 'SQLSTATE P2211' /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' +grep -q 'SQLSTATE P2211' /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) @@ -263,10 +264,10 @@ done 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 +CORRUPT=$(as corruptsigner management -H "$X" -F file=@/tmp/truncated-sig.png "$B/api/me/facsimile" | jq -r .id) 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' +[ ! -e "/var/lib/signatures/$CORRUPT.png" ] || fail 'truncated PNG published' +[ ! -e "/var/lib/signet/sig-inbox/$CORRUPT.png" ] || fail 'invalid enrolment inbox retained' ok 'enrolment fully decodes PNG before publishing a facsimile' echo 'render contract: all passed'
diff --git a/test/request-fields-contract.sh b/test/request-fields-contract.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# Native ownership/failure check plus real first-value compatibility in both APIs. +set -eu +cd "$(dirname "$0")/.." +T=$(mktemp -d /tmp/signet-request-fields.XXXXXX) +trap 'rm -rf "$T"' 0 +trap 'exit 1' HUP INT TERM +CC=${CC:-cc} +"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o" +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor -include test/http-fields-alloc.h -c src/http.c -o "$T/http.o" +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor test/http-fields.c "$T/http.o" src/conf.c src/util.c \ + "$T/sha256.o" -lkcgi -lz -o "$T/http-fields" +"$T/http-fields" +"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor -I/usr/include/postgresql test/db-cache.c src/db.c src/conf.c src/util.c \ + "$T/sha256.o" -lpq -lhiredis -o "$T/db-cache" +printf '%s\n' 'db.conninfo = dbname=signet host=/run/postgresql user=signet' > "$T/db.conf" +"$T/db-cache" "$T/db.conf" +B=http://localhost:8080 +ORG=request_fields_$$ +curl --max-time 20 -fsS -H 'Remote-User: root' -H 'Remote-Groups: signet-admins' \ + -H 'X-Requested-With: signet' -F "org=$ORG" -F key=first -F key=second \ + -F type=text -F value=original -F value=duplicate -F unused=ignored \ + "$B/pim-api/attrs" > /dev/null +curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \ + "$B/api/pim" > "$T/pim" +jq -e --arg org "$ORG" '.[$org].text.first == "original" and .[$org].text.second == null' "$T/pim" > /dev/null +code=$(curl --max-time 20 -sS -o "$T/invalid" -w '%{http_code}' \ + -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' \ + -F file=@test/fixtures/letter.pdf -F file=@test/fixtures/seal.png \ + -F total_size=broken -F total_size=1 "$B/api/docs") +[ "$code" = 400 ] || { + echo "FAIL - duplicate total_size HTTP $code, expected400" >&2 + exit 1 +} +curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \ + -H 'X-Requested-With: signet' -F file=@test/fixtures/letter.pdf \ + -F file=@test/fixtures/seal.png -F unused=ignored "$B/api/docs" > "$T/doc" +ID=$(jq -er .id "$T/doc") +curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \ + "$B/api/docs/$ID/file/source" > "$T/source.pdf" +cmp test/fixtures/letter.pdf "$T/source.pdf" +echo 'request fields HTTP: both APIs keep first duplicate values and exact uploaded PDF'
diff --git a/test/resource-a5-probe.sh b/test/resource-a5-probe.sh @@ -0,0 +1,113 @@ +#!/bin/sh +# Representative synthetic workload, not a replacement for max-input diagnostics. +set -eu +[ "${SIGNET_RESOURCE_PROBE_DISPOSABLE:-}" = yes ] || { + echo 'refusing: use an explicitly disposable development stack' >&2 + exit 2 +} +cd /src +T=$(mktemp -d /tmp/signet-resource-a5.XXXXXX) +SAMPLER= +cleanup() { + if [ -n "$SAMPLER" ]; then + kill -TERM "$SAMPLER" 2>/dev/null || true + wait "$SAMPLER" 2>/dev/null || true + fi + rm -rf "$T" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +cc -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o" +cc -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + -Isrc -Ivendor test/resource-a5.c src/pdfw.c src/ttf.c src/util.c \ + "$T/sha256.o" -lpng -lz -o "$T/a5" +cc -O2 -std=c99 -Wall -Wextra test/resource-rss.c -o "$T/rss" +"$T/a5" "$T/source.pdf" +qpdf --check "$T/source.pdf" > /dev/null +pdfinfo "$T/source.pdf" > "$T/info" +grep -q '^Pages: *1$' "$T/info" +grep -q '^Page size: *420 x 595 pts' "$T/info" +images() { pdfimages -list "$1" | awk '$3 == "image" {n++} END {print n+0}'; } +[ "$(images "$T/source.pdf")" = 0 ] +source_hash=$(sha256sum "$T/source.pdf" | cut -d ' ' -f 1) +echo "profile=synthetic_text_only_A5; source_bytes=$(wc -c < "$T/source.pdf"); batch_size=32; concurrency=sequential" +B=http://localhost:8080 +ORG=a5_resource_$$ +request() { + user=$1; groups=$2; shift 2 + curl --max-time 30 -fsS -H "Remote-User: $user" -H "Remote-Groups: $groups" \ + -H 'X-Requested-With: signet' "$@" +} +request root signet-admins -F "org=$ORG" -F key=reference -F type=text \ + -F value=SYNTHETIC-REFERENCE "$B/pim-api/attrs" > /dev/null +request root signet-admins -F "org=$ORG" -F key=seal -F type=image \ + -F value=seals/agency_seal.png "$B/pim-api/attrs" > /dev/null +jq -nc --arg org "$ORG" '{title:"Synthetic A5 resource batch",org_code:$org, + route:{parties:[{name:"Manager",signer:"manager"}]}, + layout:{reference_width:1000,reference_height:1416,imprints:[ + {page:1,type:"pim_text",ref:"reference",font:"fonts/DejaVuSans.ttf",coords:[70,1240,600,1270]}, + {page:1,type:"pim_image",ref:"seal",coords:[650,1050,830,1230]}, + {page:1,type:"signature_zone",party:"Manager",coords:[300,1280,800,1390],min_w:50,min_h:20} + ]}}' > "$T/layout.json" +wait_ready() { + attempt=0 + while :; do + request asha clerks "$B/api/docs/$ID" > "$T/doc.json" + jq -e '.render_error == null' "$T/doc.json" > /dev/null + if jq -e '.rendered_seq == .render_seq' "$T/doc.json" > /dev/null; then return; fi + attempt=$((attempt + 1)); [ "$attempt" -lt 200 ]; sleep .05 + done +} +: > "$T/peak" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & +SAMPLER=$! +attempt=0 +while ! grep -q '^sampler_ready=1$' "$T/peak"; do + attempt=$((attempt + 1)); [ "$attempt" -lt 100 ]; sleep .05 +done +n=0 +while [ "$n" -lt 32 ]; do + request asha clerks -F "file=@$T/source.pdf" "$B/api/docs" > "$T/created.json" + ID=$(jq -er .id "$T/created.json") + request asha clerks -F "json=<$T/layout.json" "$B/api/docs/$ID/save" > /dev/null + request asha clerks -d '' "$B/api/docs/$ID/submit" > /dev/null + wait_ready + request asha clerks "$B/api/docs/$ID/file/source" > "$T/returned-source.pdf" + [ "$(sha256sum "$T/returned-source.pdf" | cut -d ' ' -f 1)" = "$source_hash" ] + request asha clerks "$B/api/docs/$ID/file/proof" > "$T/proof.pdf" + pdfinfo "$T/proof.pdf" > "$T/info" + grep -q '^Pages: *1$' "$T/info" + grep -q '^Page size: *420 x 595 pts' "$T/info" + [ "$(images "$T/proof.pdf")" = 1 ] + request manager management -F decision=signoff \ + -F 'placement={"page":1,"coords":[300,1280,800,1390],"ref_w":1000,"ref_h":1416}' \ + "$B/api/docs/$ID/decide" > /dev/null + wait_ready + jq -e '.status == "RELEASED" and (.events | map(.action) | index("RELEASED")) != null' "$T/doc.json" > /dev/null + request asha clerks "$B/api/docs/$ID/file/final" > "$T/final.pdf" + [ "$(sha256sum "$T/final.pdf" | cut -d ' ' -f 1)" = "$(jq -er .final_sha256 "$T/doc.json")" ] + qpdf --check "$T/final.pdf" > /dev/null + pdfinfo "$T/final.pdf" > "$T/info" + grep -q '^Pages: *2$' "$T/info" + grep -q '^Page size: *420 x 595 pts' "$T/info" + pdftotext -f 1 -l 1 "$T/final.pdf" "$T/body.txt" + grep -q 'SYNTHETIC A5 RESOURCE FIXTURE' "$T/body.txt" + grep -q 'SYNTHETIC-REFERENCE' "$T/body.txt" + [ "$(grep -c 'Example line [0-9]' "$T/body.txt")" = 29 ] + [ "$(images "$T/final.pdf")" = 2 ] + pdftotext -f 2 "$T/final.pdf" "$T/audit.txt" + grep -q SIGNOFF "$T/audit.txt" + n=$((n + 1)) +done +kill -TERM "$SAMPLER" +wait "$SAMPLER" +SAMPLER= +while IFS= read -r line; do printf '%s\n' "$line"; done < "$T/peak" +peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak") +[ "$peak" -gt 0 ] +echo 'completed=32; source_hashes=exact; A5_body_pages=preserved; text_rows=29_each; seal_and_facsimile=present; release_hashes=exact; audit_pages=present' +if [ "$((peak * 1024))" -ge 60000000 ]; then + echo 'budget_result=exceeded; ticket20 remains OPEN' + exit 1 +fi +echo 'budget_result=within_for_representative_fixture; worst_case_and_native_gates_remain_OPEN'
diff --git a/test/resource-a5.c b/test/resource-a5.c @@ -0,0 +1,31 @@ +/* Synthetic text-only A5 input: no payroll records or images from real files. */ +#include <stdio.h> + +#include "pdfw.h" + +int +main(int argc, char **argv) +{ + pdfw *p; + char line[128]; + int row; + + if (argc != 2) + return 2; + p = pdfw_open(argv[1]); + if (p == NULL) + return 1; + if (pdfw_page(p, 420, 595) != 0) { + pdfw_close(p); + return 1; + } + pdfw_text(p, PDFW_HELVETICA, 13, 30, 555, "SYNTHETIC A5 RESOURCE FIXTURE"); + pdfw_text(p, PDFW_HELVETICA, 10, 30, 533, "Reference: TEST-ONLY Period: Example month"); + for (row = 0; row < 29; row++) { + snprintf(line, sizeof(line), + "Example line %02d Description Units: 1 Amount: 100.00", row + 1); + pdfw_text(p, PDFW_HELVETICA, 8, 30, 510 - row * 11, line); + } + pdfw_text(p, PDFW_HELVETICA, 9, 30, 135, "All entries are synthetic. Not a real payroll document."); + return pdfw_close(p) == 0 ? 0 : 1; +}
diff --git a/test/resource-image-probe.sh b/test/resource-image-probe.sh @@ -0,0 +1,332 @@ +#!/bin/sh +# Opt-in destructive disposable-stack fixture, not native/mixed-load acceptance. +set -eu +[ "${SIGNET_RESOURCE_PROBE_DISPOSABLE:-}" = yes ] || { + echo 'refusing: set SIGNET_RESOURCE_PROBE_DISPOSABLE=yes on a disposable stack' >&2 + exit 2 +} +cd /src +ACTIVE=${SIGNET_RESOURCE_PARSE_WINDOW:-no} +case "$ACTIVE" in yes|no|preload|worker-first) ;; *) exit 2;; esac +EXCLUSION=${SIGNET_RESOURCE_PARSE_EXCLUSION:-no} +case "$EXCLUSION" in yes) [ "$ACTIVE" = yes ];; no) ;; *) exit 2;; esac +T=$(mktemp -d /tmp/signet-resource-image.XXXXXX) +NAME=resource_image_$$ +SAMPLER=; CLIENTS=; LOCKER=; WORKER_STOPPED=no +GATE_PID=; ACTIVE_CLIENT=; PIM_REPLACED=no +restart_pim() { + pkill -CONT -f '^/usr/local/libexec/pim-api$' 2>/dev/null || true + pkill -f '^kfcgi .* /run/signet/pim.sock' 2>/dev/null || true + pkill -f '^/usr/local/libexec/pim-api$' 2>/dev/null || true + tries=0 + while pgrep -f '^kfcgi .* /run/signet/pim.sock' >/dev/null || + pgrep -f '^/usr/local/libexec/pim-api$' >/dev/null; do + tries=$((tries + 1)) + if [ "$tries" -eq 5 ]; then + pkill -KILL -f '^/usr/local/libexec/pim-api$' 2>/dev/null || true + pkill -KILL -f '^kfcgi .* /run/signet/pim.sock' 2>/dev/null || true + fi + [ "$tries" -lt 7 ]; sleep 1 + done + rm -f /run/signet/pim.sock + if [ "$1" = gate ]; then + SIGNET_PARSE_GATE="$T/gate" LD_PRELOAD="$T/parse-gate.so" \ + kfcgi -d -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api >>/proc/1/fd/2 2>&1 & + else + kfcgi -d -n 1 -N 1 -s /run/signet/pim.sock -u lighttpd -U signet -p / -- /usr/local/libexec/pim-api >>/proc/1/fd/2 2>&1 & + fi + supervisor=$!; tries=0 + while [ ! -S /run/signet/pim.sock ]; do + kill -0 "$supervisor" + tries=$((tries + 1)); [ "$tries" -lt 5 ]; sleep 1 + done +} +KEY=$((1800000000 + $$)) +HOLDER=${NAME}_holder +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; } +start_worker() { + if [ "$ACTIVE" = worker-first ] && [ -d "$T/bin" ]; then + su-exec signetd:signet env PATH="$T/bin:$PATH" /usr/local/sbin/signetd >> "$T/worker.log" 2>&1 & + else + su-exec signetd:signet /usr/local/sbin/signetd >> "$T/worker.log" 2>&1 & + fi +} +cleanup() { + if [ -d "$T/worker-gate" ]; then + : > "$T/worker-gate/release" + rm -f "$T/bin/qpdf" + rmdir "$T/bin" 2>/dev/null || true + pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true + WORKER_STOPPED=yes + fi + if [ -f "$T/gate/paused" ]; then + read -r GATE_PID ignored < "$T/gate/paused" || true + [ -z "$GATE_PID" ] || kill -CONT "$GATE_PID" 2>/dev/null || true + fi + if [ -n "$ACTIVE_CLIENT" ]; then + kill "$ACTIVE_CLIENT" 2>/dev/null || true + wait "$ACTIVE_CLIENT" 2>/dev/null || true + fi + if [ "$PIM_REPLACED" = yes ]; then restart_pim normal || true; fi + for p in $CLIENTS; do kill "$p" 2>/dev/null || true; done + sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='$HOLDER'" > /dev/null 2>&1 || true + [ -z "$LOCKER" ] || wait "$LOCKER" 2>/dev/null || true + sql -c "DROP TRIGGER IF EXISTS $NAME ON documents; DROP FUNCTION IF EXISTS $NAME()" > /dev/null 2>&1 || true + [ "$WORKER_STOPPED" = no ] || start_worker + if [ -n "$SAMPLER" ]; then + kill -TERM "$SAMPLER" 2>/dev/null || true + wait "$SAMPLER" 2>/dev/null || true + fi + rm -f "/var/www/dam/seals/$NAME.png" "/var/www/dam/fonts/$NAME.ttf" + rm -rf "$T" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +cc -O2 -std=c99 -Wall -Wextra test/resource-image.c -lpng -o "$T/image" +cc -O2 -std=c99 -Wall -Wextra test/resource-rss.c -o "$T/rss" +if [ "$ACTIVE" != no ]; then + cc -O2 -std=c99 -Wall -Wextra -fPIC -shared -Isrc test/resource-parse-gate.c -ldl -o "$T/parse-gate.so" + chmod 755 "$T" + chmod 644 "$T/parse-gate.so" + mkdir "$T/gate" + chown signet:signet "$T/gate" + chmod 700 "$T/gate" +fi +if [ "$ACTIVE" = worker-first ]; then + mkdir "$T/bin" "$T/worker-gate" + chmod 755 "$T/bin" "$T/worker-gate" + chown signetd:signet "$T/worker-gate" + # Only this owned worker's PATH changes; the real qpdf binary is untouched. + printf '%s\n' '#!/bin/sh' \ + "gate='$T/worker-gate'" \ + ': > "$gate/ready"' \ + 'while [ ! -f "$gate/release" ]; do sleep .05; done' \ + 'exec /usr/bin/qpdf "$@"' > "$T/bin/qpdf" + chmod 755 "$T/bin/qpdf" +fi +"$T/image" "/var/www/dam/seals/$NAME.png" "$T/rgb" +cp /usr/share/fonts/dejavu/DejaVuSans.ttf "/var/www/dam/fonts/$NAME.ttf" +dd if=/dev/zero bs=1048576 count=2 >> "/var/www/dam/fonts/$NAME.ttf" 2>/dev/null +chmod 644 "/var/www/dam/seals/$NAME.png" "/var/www/dam/fonts/$NAME.ttf" +bytes=$(wc -c < "/var/www/dam/seals/$NAME.png") +font_bytes=$(wc -c < "/var/www/dam/fonts/$NAME.ttf") +default_bytes=$(wc -c < /usr/share/fonts/dejavu/DejaVuSans.ttf) +echo "png_bytes=$bytes; loaded_font_bytes=$font_bytes; snapshot_assets_bytes=$((bytes + font_bytes + default_bytes))" +[ "$((bytes + font_bytes + default_bytes))" -le 16777216 ] +request() { + curl --max-time 60 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' \ + -H 'X-Requested-With: signet' "$@" +} +B=http://localhost:8080 +curl --max-time 60 -fsS -H 'Remote-User: root' -H 'Remote-Groups: signet-admins' \ + -H 'X-Requested-With: signet' -F "org=$NAME" -F key=image -F type=image \ + -F "value=seals/$NAME.png" "$B/pim-api/attrs" > /dev/null +request -F "file=@test/fixtures/letter.pdf" "$B/api/docs" > "$T/created" +ID=$(jq -er .id "$T/created") +jq -nc --arg org "$NAME" --arg font "fonts/$NAME.ttf" \ + '{title:"Maximum PNG and live font resource fixture",org_code:$org, + route:{parties:[{name:"Manager",signer:"manager"}]}, + layout:{reference_width:1000,reference_height:1414,imprints:[ + {type:"date",page:1,font:$font,coords:[100,100,700,140]}, + {type:"pim_image",page:1,ref:"image",coords:[100,200,900,1000]} + ]}}' > "$T/layout" +request -F "json=<$T/layout" "$B/api/docs/$ID/save" > /dev/null +# The optional window mode instead holds one completed PIM parse before pruning; +# preload is its control without that request. Neither changes product binaries. +# Queue the render first, then retain two admitted, densely populated API bodies +# at their INSERTs. Admit them one at a time so this fixture isolates retained +# bodies plus rendering, not simultaneous parser startup (a separate open gap). +# The worker remains independent of those two API handlers. +pkill -f '^/usr/local/sbin/signetd$' +WORKER_STOPPED=yes +sleep 1 +request -d '' "$B/api/docs/$ID/submit" > /dev/null +{ + printf '%s\r\n' '--z' 'Content-Disposition: form-data; name="file"; filename="first.pdf"' 'Content-Type: application/pdf' '' '%PDF-1.4' '--z' 'Content-Disposition:a;name=unused' 'Content-Type:multipart/mixed;boundary=y' '' + awk 'BEGIN {for(i=0;i<35000;i++) printf "--y\r\nContent-Disposition:a\r\n\r\n\r\n"; printf "--y--\r\n"}' + printf '%s\r\n' '--z--' +} > "$T/body" +if [ "$ACTIVE" = no ]; then retained=2; else retained=0; fi +echo "concurrent_api_requests=$retained; multipart_body_bytes=$(wc -c < "$T/body")" +if [ "$ACTIVE" = no ]; then +sql -c "CREATE FUNCTION $NAME() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN PERFORM pg_advisory_xact_lock($KEY); RETURN NEW; END \$\$; CREATE TRIGGER $NAME BEFORE INSERT ON documents FOR EACH ROW EXECUTE FUNCTION $NAME()" > /dev/null +su-exec postgres env PGAPPNAME="$HOLDER" psql -X -q -v ON_ERROR_STOP=1 -d signet \ + -c "SELECT pg_advisory_lock($KEY); SELECT pg_sleep(60)" > "$T/holder" 2>&1 & +LOCKER=$! +n=0 +while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND granted")" != 1 ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +fi +: > "$T/peak" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & +SAMPLER=$! +n=0 +while ! grep -q '^sampler_ready=1$' "$T/peak"; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +if [ "$ACTIVE" = no ]; then +for n in 1 2; do + request -H 'Content-Type: multipart/form-data; boundary=z' --data-binary "@$T/body" \ + "$B/api/docs" > "$T/upload.$n" & + CLIENTS="$CLIENTS $!" + attempts=0 + while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND NOT granted")" != "$n" ]; do + attempts=$((attempts + 1)); [ "$attempts" -lt 100 ]; sleep .05 + done +done +fi +echo "held_api_requests=$retained" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" --once +kill -TERM "$SAMPLER" +wait "$SAMPLER" +SAMPLER= +parse_peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak") +echo "parser_phase_peak_kib=$parse_peak" +: > "$T/peak" +if [ "$ACTIVE" != no ]; then + "$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" --qpdf > "$T/peak" & +else + "$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & +fi +SAMPLER=$! +attempts=0 +while ! grep -q '^sampler_ready=1$' "$T/peak"; do + attempts=$((attempts + 1)); [ "$attempts" -lt 100 ]; sleep .05 +done +if [ "$ACTIVE" != no ]; then + PIM_REPLACED=yes + restart_pim gate + echo "parser_window_mode=$ACTIVE" +fi +if [ "$ACTIVE" = yes ]; then + curl --max-time 60 -sS -o "$T/active-response" -w '%{http_code}' \ + -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' \ + -H 'X-Requested-With: signet' -H 'Content-Type: multipart/form-data; boundary=z' \ + --data-binary "@$T/body" \ + "$B/pim-api/parser-probe" > "$T/active-status" & + ACTIVE_CLIENT=$!; attempts=0 + while [ ! -f "$T/gate/paused" ]; do + kill -0 "$ACTIVE_CLIENT" + attempts=$((attempts + 1)); [ "$attempts" -lt 10 ]; sleep 1 + done + read -r GATE_PID gate_fields < "$T/gate/paused" + [ "$gate_fields" -ge 35000 ] + attempts=0 + while [ "$(awk '/^State:/ { print $2 }' "/proc/$GATE_PID/status")" != T ]; do + attempts=$((attempts + 1)); [ "$attempts" -lt 10 ]; sleep 1 + done + echo "parser_delivery_window=held_before_pruning; fields=$gate_fields; pid=$GATE_PID" +fi +start_worker +WORKER_STOPPED=no +if [ "$ACTIVE" = worker-first ]; then + n=0 + while [ ! -f "$T/worker-gate/ready" ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + curl --max-time 60 -sS -o "$T/active-response" -w '%{http_code}' \ + -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' \ + -H 'X-Requested-With: signet' -H 'Content-Type: multipart/form-data; boundary=z' \ + --data-binary "@$T/body" "$B/pim-api/parser-probe" > "$T/active-status" & + ACTIVE_CLIENT=$!; n=0 + while [ ! -f "$T/gate/admission-wait" ]; do + kill -0 "$ACTIVE_CLIENT" + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + [ ! -f "$T/gate/paused" ] + worker=$(pgrep -f '^/usr/local/sbin/signetd$') + inode=$(stat -c %i /var/lib/signet/.workload.lock) + awk -v pid="$worker" -v inode="$inode" ' + $2 == "POSIX" && $4 == "WRITE" && $5 == pid { + split($6, a, ":"); if (a[3] == inode) found=1 + } END {exit !found}' /proc/locks + echo 'worker_parser_exclusion=ready_request_waiting_before_parent_parse' + : > "$T/worker-gate/release" +fi +if [ "$EXCLUSION" = yes ]; then + # Require an actual kernel lock waiter, not a timeout or missing qpdf sample. + worker=$(pgrep -f '^/usr/local/sbin/signetd$') + inode=$(stat -c %i /var/lib/signet/.workload.lock) + n=0 + while ! awk -v pid="$worker" -v inode="$inode" ' + $2 == "->" && $6 == pid {split($7, a, ":"); if (a[3] == inode) found=1} + END {exit !found}' /proc/locks; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + [ "$(awk '/^State:/ { print $2 }' "/proc/$GATE_PID/status")" = T ] + [ "$(sql -c "SELECT rendered_seq < render_seq AND render_error IS NULL FROM documents WHERE id='$ID'")" = t ] + echo 'parser_worker_exclusion=kernel_lock_wait_verified' + kill -CONT "$GATE_PID" + wait "$ACTIVE_CLIENT" + ACTIVE_CLIENT= + [ "$(head -n 1 "$T/active-status")" = 404 ] + echo 'admitted_parser_request=404_after_resume' +fi +n=0 +while [ "$(sql -c "SELECT render_error IS NULL AND rendered_seq=render_seq FROM documents WHERE id='$ID'")" != t ]; do + n=$((n + 1)); [ "$n" -lt 300 ]; sleep .05 +done +if [ "$ACTIVE" = worker-first ]; then + n=0 + while [ ! -f "$T/gate/paused" ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + read -r GATE_PID gate_fields < "$T/gate/paused" + [ "$gate_fields" -ge 35000 ] + n=0 + while [ "$(awk '/^State:/ { print $2 }' "/proc/$GATE_PID/status")" != T ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + kill -CONT "$GATE_PID" + wait "$ACTIVE_CLIENT" + ACTIVE_CLIENT= + [ "$(head -n 1 "$T/active-status")" = 404 ] + echo "admitted_parser_request=404_after_worker; fields=$gate_fields" +fi +if [ "$ACTIVE" = yes ] && [ "$EXCLUSION" = no ]; then + [ "$(awk '/^State:/ { print $2 }' "/proc/$GATE_PID/status")" = T ] + kill -CONT "$GATE_PID" + wait "$ACTIVE_CLIENT" + ACTIVE_CLIENT= + [ "$(head -n 1 "$T/active-status")" = 404 ] + echo 'admitted_parser_request=404_after_resume' +fi +if [ -n "$LOCKER" ]; then + sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='$HOLDER'" > /dev/null + wait "$LOCKER" 2>/dev/null || true + LOCKER= +fi +for p in $CLIENTS; do wait "$p"; done +CLIENTS= +if [ "$ACTIVE" = no ]; then + for n in 1 2; do jq -e '.id != null' "$T/upload.$n" > /dev/null; done +fi +request "$B/api/docs/$ID/file/proof" > "$T/proof.pdf" +qpdf --check "$T/proof.pdf" > /dev/null +qpdf --json "$T/proof.pdf" > "$T/proof.json" +image_obj=$(jq -er '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Subtype"] == "/Image")) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected one image") end' "$T/proof.json") +font_obj=$(jq -er --argjson size "$font_bytes" '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Length1"] == $size)) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected exact font") end' "$T/proof.json") +qpdf --show-object="$image_obj" --filtered-stream-data "$T/proof.pdf" > "$T/actual-rgb" +qpdf --show-object="$font_obj" --filtered-stream-data "$T/proof.pdf" > "$T/actual-font" +cmp "$T/rgb" "$T/actual-rgb" +cmp "/var/www/dam/fonts/$NAME.ttf" "$T/actual-font" +echo 'decoded_PDF_RGB_and_embedded_font=exact_source_bytes' +kill -TERM "$SAMPLER" +wait "$SAMPLER" +SAMPLER= +while IFS= read -r line; do printf '%s\n' "$line"; done < "$T/peak" +peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak") +[ "$peak" -gt 0 ] +if [ "$ACTIVE" != no ]; then + qpdf_peak=$(awk -F= '/transient_sampled_qpdf_app_peak_kib/ {print $2}' "$T/peak") + [ "$qpdf_peak" -gt 0 ] || { echo 'FAIL - qpdf overlap was not sampled' >&2; exit 1; } + echo "qpdf_phase_peak_bytes=$((qpdf_peak * 1024))" +fi +[ "$parse_peak" -le "$peak" ] || peak=$parse_peak +echo "document=$ID; png_pixels=4194304; budget_bytes=60000000" +if [ "$((peak * 1024))" -ge 60000000 ]; then + echo 'budget_result=exceeded; native/resource gate remains OPEN' + exit 1 +fi +echo 'budget_result=within_for_fixture; native/resource gate remains OPEN'
diff --git a/test/resource-image.c b/test/resource-image.c @@ -0,0 +1,67 @@ +#include <stdint.h> +#include <stdio.h> + +#include <png.h> + +/* Maximum admitted PNG pixels with deterministic, poorly compressible RGB. */ +int +main(int argc, char **argv) +{ + png_structp png; + png_infop info; + FILE *image, *raw; + unsigned char row[2048 * 3]; + uint32_t state = 1; + size_t x, y; + volatile int rc = 1; + + if (argc != 3) + return 2; + image = fopen(argv[1], "wb"); + if (image == NULL) + return 1; + raw = fopen(argv[2], "wb"); + if (raw == NULL) { + fclose(image); + return 1; + } + png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + if (png == NULL) + goto out; + info = png_create_info_struct(png); + if (info == NULL) { + png_destroy_write_struct(&png, NULL); + goto out; + } + if (setjmp(png_jmpbuf(png))) { + png_destroy_write_struct(&png, &info); + goto out; + } + png_init_io(png, image); + png_set_IHDR(png, info, 2048, 2048, 8, PNG_COLOR_TYPE_RGB, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + png_set_filter(png, PNG_FILTER_TYPE_BASE, PNG_FILTER_NONE); + png_write_info(png, info); + for (y = 0; y < 2048; y++) { + for (x = 0; x < sizeof(row); x++) { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + row[x] = (unsigned char)state; + } + png_write_row(png, row); + if (fwrite(row, 1, sizeof(row), raw) != sizeof(row)) { + png_destroy_write_struct(&png, &info); + goto out; + } + } + png_write_end(png, NULL); + png_destroy_write_struct(&png, &info); + rc = 0; +out: + if (fclose(image) != 0) + rc = 1; + if (fclose(raw) != 0) + rc = 1; + return rc; +}
diff --git a/test/resource-parse-gate.c b/test/resource-parse-gate.c @@ -0,0 +1,84 @@ +/* Disposable LD_PRELOAD scheduling probe; never linked into product binaries. */ +#define _POSIX_C_SOURCE 200809L +#include <sys/select.h> + +#include <dlfcn.h> +#include <fcntl.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#include "http.h" + +/* Observe the admission retry without stopping it or consuming kcgi's socket. */ +int +pselect(int nfds, fd_set *reads, fd_set *writes, fd_set *excepts, + const struct timespec *timeout, const sigset_t *mask) +{ + static int (*wait_ready)(int, fd_set *, fd_set *, fd_set *, + const struct timespec *, const sigset_t *); + static int observed; + const char *dir = getenv("SIGNET_PARSE_GATE"); + char path[512]; + int fd; + + if (wait_ready == NULL) { + wait_ready = (int (*)(int, fd_set *, fd_set *, fd_set *, + const struct timespec *, const sigset_t *))dlsym(RTLD_NEXT, "pselect"); + if (wait_ready == NULL) + _exit(126); + } + if (nfds == 0 && timeout != NULL && dir != NULL && !observed) { + if (snprintf(path, sizeof(path), "%s/admission-wait", dir) >= (int)sizeof(path)) + _exit(127); + fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600); + if (fd == -1 || close(fd) == -1) + _exit(128); + observed = 1; + } + return wait_ready(nfds, reads, writes, excepts, timeout, mask); +} + +/* Hold the real library's completed, unpruned request, without copying it. */ +enum kcgi_err +khttp_fcgi_parse(struct kfcgi *fcgi, struct kreq *req) +{ + static enum kcgi_err (*parse)(struct kfcgi *, struct kreq *); + static int gated; + const char *dir; + char path[512], pending[512], record[64]; + enum kcgi_err result; + int fd, n; + + if (parse == NULL) { + parse = (enum kcgi_err (*)(struct kfcgi *, struct kreq *)) + dlsym(RTLD_NEXT, "khttp_fcgi_parse"); + if (parse == NULL) + _exit(120); + } + result = parse(fcgi, req); + dir = getenv("SIGNET_PARSE_GATE"); + if (result != KCGI_OK || gated || dir == NULL || req->fieldsz < 35000) + return result; + gated = 1; + n = snprintf(path, sizeof(path), "%s/paused", dir); + if (n < 0 || (size_t)n >= sizeof(path)) + _exit(121); + n = snprintf(pending, sizeof(pending), "%s/preparing", dir); + if (n < 0 || (size_t)n >= sizeof(pending)) + _exit(121); + fd = open(pending, O_CREAT | O_EXCL | O_WRONLY, 0600); + if (fd == -1) + _exit(122); + n = snprintf(record, sizeof(record), "%ld %zu\n", (long)getpid(), req->fieldsz); + if (n < 0 || (size_t)n >= sizeof(record) || + write(fd, record, (size_t)n) != n || close(fd) == -1) + _exit(123); + /* Publish readiness only after the complete PID/count record is visible. */ + if (rename(pending, path) == -1) + _exit(125); + if (raise(SIGSTOP) != 0) + _exit(124); + return result; +}
diff --git a/test/resource-parser-probe.sh b/test/resource-parser-probe.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# Opt-in disposable diagnostic, never for preserved/shared/production stacks. +set -eu +[ "${SIGNET_RESOURCE_PROBE_DISPOSABLE:-}" = yes ] || exit 2 +T=$(mktemp -d /tmp/resource-parser.XXXXXX) +S=; PIDS= +cleanup() { + for p in $PIDS; do kill "$p" 2>/dev/null || true; done + if [ -n "$S" ]; then kill -TERM "$S" 2>/dev/null || true; wait "$S" 2>/dev/null || true; fi + rm -rf "$T" +} +trap cleanup EXIT +cc -std=c99 -Wall -Wextra -O2 /src/test/resource-rss.c -o "$T/rss" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" --once | awk -F= '{print "baseline_app_rss_kib=" $2}' +: > "$T/peak" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & S=$! +for n in $(seq 1 100); do grep -q '^sampler_ready=1' "$T/peak" && break; sleep .01; done +grep -q '^sampler_ready=1' "$T/peak" +QUERY=$(awk 'BEGIN {for(i=0;i<1000;i++) printf "x=&"}') +COOKIE=$(awk 'BEGIN {for(i=0;i<1000;i++) printf "x=;"}') +phase() { + name=$1; ct=$2; want=$3 + echo "phase=$name; body_bytes=$(wc -c < "$T/body")" + for n in 1 2 3; do + endpoint=api; [ "$n" != 3 ] || endpoint=pim-api + ( + code=$(curl --max-time 30 -sS -o "$T/reply.$n" -w '%{http_code}' -H 'Remote-User: admin' -H 'Remote-Groups: signet-admins' -H 'X-Requested-With: signet' -H "Content-Type: $ct" -H "Cookie: $COOKIE" --data-binary "@$T/body" "http://localhost:8080/$endpoint/parser-probe?$QUERY") + [ "$code" = "$want" ] || { echo "FAIL - $name HTTP $code expected $want" >&2; exit 1; } + ) & PIDS="$PIDS $!" + done + for p in $PIDS; do wait "$p"; done; PIDS= +} +awk 'BEGIN {for(i=0;i<300000;i++) printf "x=&"}' > "$T/body" +phase rejected_dense_url application/x-www-form-urlencoded 413 +awk 'BEGIN {for(i=0;i<225000;i++) printf "x=\r\n"}' > "$T/body" +phase rejected_dense_text text/plain 413 +# Exact16KiB accepted dense forms, not only rejected large requests. +awk 'BEGIN {for(i=0;i<5461;i++) printf "x=&"; printf "x"}' > "$T/body" +phase accepted_dense_url application/x-www-form-urlencoded 404 +# Short nested MIME parts inherit the outer name: denser than normal FormData. +{ + printf '%s\r\n' '--z' 'Content-Disposition:a;name=x' 'Content-Type:multipart/mixed;boundary=y' '' + awk 'BEGIN {for(i=0;i<35000;i++) printf "--y\r\nContent-Disposition:a\r\n\r\n\r\n";printf "--y--\r\n"}' + printf '%s\r\n' '--z--' +} > "$T/body" +phase accepted_dense_nested_multipart 'multipart/form-data; boundary=z' 404 +kill -TERM "$S"; wait "$S"; S= +awk '{print}' "$T/peak" +peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak") +[ -n "$peak" ] && [ "$peak" -gt 0 ] && [ "$((peak * 1024))" -lt 60000000 ] || { echo 'FAIL - parser fixture exceeds60MB aggregate application RSS'; exit 1; } +echo 'budget_result=within_for_parser_fixture; mixed-render/native gate remains OPEN'
diff --git a/test/resource-pdfw.c b/test/resource-pdfw.c @@ -0,0 +1,35 @@ +#include <sys/resource.h> + +#include <stdio.h> + +#include "pdfw.h" + +/* Linux-only fixture measurement, not a per-process production limit. */ +int +main(int argc, char **argv) +{ + struct rusage usage; + pdfw *p; + int font, image_rc, close_rc; + + if (argc != 4) + return 2; + p = pdfw_open(argv[3]); + if (p == NULL) + return 1; + font = pdfw_font(p, argv[1]); + pdfw_page(p, 595, 842); + pdfw_text(p, font, 12, 20, 800, "Font stays live while PNG is embedded: ₹"); + image_rc = pdfw_image(p, argv[2], 20, 200, 500, 500); + close_rc = pdfw_close(p); + if (font == PDFW_HELVETICA || image_rc != 0 || close_rc != 0 || + getrusage(RUSAGE_SELF, &usage) != 0) + return 1; + printf("native_writer_peak_kib=%ld; fixture_ceiling_kib=24576\n", + usage.ru_maxrss); + if (usage.ru_maxrss <= 0 || usage.ru_maxrss >= 24576) { + fprintf(stderr, "FAIL - writer fixture exceeds its24MiB regression ceiling\n"); + return 1; + } + return 0; +}
diff --git a/test/resource-rss.c b/test/resource-rss.c @@ -0,0 +1,101 @@ +#define _POSIX_C_SOURCE 200809L +#include <dirent.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +static volatile sig_atomic_t stop; + +static void +done(int sig) +{ + (void)sig; + stop = 1; +} + +int +main(int argc, char **argv) +{ + DIR *d; + struct dirent *de; + FILE *f; + char path[128], line[256], name[16], cohort[8192]; + unsigned int uid, ids[3]; + size_t rss, sum, peak = 0, qpdf_peak = 0, used; + int detail = getenv("SIGNET_RSS_DETAIL") != NULL; + struct timespec nap = { 0, 1000000 }; + int i, ready = 0, once, track_qpdf, have_qpdf; + + if (argc != 4 && argc != 5) + return 2; + once = argc == 5 && strcmp(argv[4], "--once") == 0; + track_qpdf = argc == 5 && strcmp(argv[4], "--qpdf") == 0; + if (argc == 5 && !once && !track_qpdf) + return 2; + for (i = 0; i < 3; i++) + ids[i] = (unsigned int)strtoul(argv[i + 1], NULL, 10); + signal(SIGTERM, done); + signal(SIGINT, done); + while (!stop) { + sum = 0; + used = 0; + cohort[0] = '\0'; + have_qpdf = 0; + if ((d = opendir("/proc")) == NULL) + return 1; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] < '0' || de->d_name[0] > '9') + continue; + if (snprintf(path, sizeof(path), "/proc/%s/status", de->d_name) >= (int)sizeof(path)) + continue; + if ((f = fopen(path, "r")) == NULL) + continue; + uid = (unsigned int)-1; + rss = 0; + name[0] = '\0'; + while (fgets(line, sizeof(line), f)) { + if ((track_qpdf || detail) && sscanf(line, "Name: %15s", name) == 1) + continue; + if (sscanf(line, "Uid: %u", &uid) == 1) + continue; + if (sscanf(line, "VmRSS: %zu", &rss) == 1) + continue; + } + fclose(f); + if (uid == ids[0] || uid == ids[1] || uid == ids[2]) { + sum += rss; + if (detail && used < sizeof(cohort)) { + int n = snprintf(cohort + used, sizeof(cohort) - used, + " %s:%s:%zu", de->d_name, name, rss); + if (n > 0) + used += (size_t)n; + } + if (track_qpdf && rss && strcmp(name, "qpdf") == 0) + have_qpdf = 1; + } + } + closedir(d); + if (sum > peak) + peak = sum; + if (have_qpdf && sum > qpdf_peak) { + qpdf_peak = sum; + if (detail) + fprintf(stderr, "qpdf_cohort_peak=%zu;%s\n", sum, cohort); + } + if (!once && !ready) { + printf("sampler_ready=1\n"); + fflush(stdout); + ready = 1; + } + if (once) + break; + nanosleep(&nap, NULL); + } + printf("transient_sampled_app_peak_kib=%zu\n", peak); + if (track_qpdf) + printf("transient_sampled_qpdf_app_peak_kib=%zu\n", qpdf_peak); + return 0; +}
diff --git a/test/resource-upload-probe.sh b/test/resource-upload-probe.sh @@ -0,0 +1,101 @@ +#!/bin/sh +# Opt-in disposable-stack diagnostic; this is not native/coexistence certification. +set -eu +[ "${SIGNET_RESOURCE_PROBE_DISPOSABLE:-}" = yes ] || { + echo 'refusing: set SIGNET_RESOURCE_PROBE_DISPOSABLE=yes on a disposable stack' >&2; exit 2; +} +T=$(mktemp -d /tmp/resource-upload.XXXXXX) +NAME=resource_upload_probe_$$ +KEY=$((1800000000 + $$)) +HOLDER=resource_upload_holder_$$ +SAMPLER=; LOCKER=; CLIENTS= +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; } +cleanup() { + for p in $CLIENTS; do kill "$p" 2>/dev/null || true; done + sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='$HOLDER'" >/dev/null 2>&1 || true + [ -z "$LOCKER" ] || wait "$LOCKER" 2>/dev/null || true + [ -z "$SAMPLER" ] || { kill -TERM "$SAMPLER" 2>/dev/null || true; wait "$SAMPLER" 2>/dev/null || true; } + sql -c "DROP TRIGGER IF EXISTS $NAME ON documents; DROP FUNCTION IF EXISTS $NAME()" >/dev/null 2>&1 || true + rm -rf "$T" +} +trap cleanup EXIT +app_rss() { + "$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" --once | awk -F= '{print $2}' +} +cc -std=c99 -Wall -Wextra -O2 /src/test/resource-rss.c -o "$T/rss" +"$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/peak" & SAMPLER=$! +dd if=/dev/zero of="$T/zero" bs=262144 count=1 2>/dev/null +# Exercise a near-cap body, including fields the upload handler ignores. +dd if=/dev/zero of="$T/padding" bs=1024 count=832 2>/dev/null +cp "$T/zero" "$T/first" +printf '%%PDF-1.4\n' | dd of="$T/first" conv=notrunc 2>/dev/null +sql -c "CREATE FUNCTION $NAME() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN PERFORM pg_advisory_xact_lock($KEY); RETURN NEW; END \$\$; CREATE TRIGGER $NAME BEFORE INSERT ON documents FOR EACH ROW EXECUTE FUNCTION $NAME()" >/dev/null +su-exec postgres env PGAPPNAME="$HOLDER" psql -X -q -v ON_ERROR_STOP=1 -d signet -c "SELECT pg_advisory_lock($KEY); SELECT pg_sleep(30)" > "$T/holder" 2>&1 & LOCKER=$! +for n in $(seq 1 100); do + [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND granted")" = 1 ] && break + sleep .05 +done +[ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND granted")" = 1 ] +echo "baseline_app_rss_kib=$(app_rss)" +post() { + curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' "$@" +} +upload() { + n=$1 + post -F total_size=33554432 -F "file=@$T/first" -F "unused=@$T/padding" http://localhost:8080/api/docs > "$T/reply.$n" + id=$(jq -er .id "$T/reply.$n") + offset=$(jq -er .upload_offset "$T/reply.$n") + while [ "$offset" -lt 33554432 ]; do + post -F "offset=$offset" -F "file=@$T/zero" "http://localhost:8080/api/docs/$id/upload" > "$T/reply.$n" + next=$(jq -er .upload_offset "$T/reply.$n") + [ "$next" = "$((offset + 262144))" ] || return 1 + offset=$next + done + curl --max-time 20 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "http://localhost:8080/api/docs/$id/file/source" > "$T/source.$n" + [ "$(wc -c < "$T/source.$n" | tr -d ' ')" = 33554432 ] + # Independently reconstruct the complete expected byte stream, not just length. + { dd if="$T/first" bs=262144 count=1 2>/dev/null; dd if=/dev/zero bs=262144 count=127 2>/dev/null; } | sha256sum > "$T/expected.$n" + sha256sum < "$T/source.$n" > "$T/actual.$n" + cmp "$T/expected.$n" "$T/actual.$n" + echo "completed_upload_$n=33554432; source_sha256_verified" +} +for n in 1 2; do upload "$n" > "$T/result.$n" 2> "$T/error.$n" & CLIENTS="$CLIENTS $!"; done +for n in $(seq 1 100); do + [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND NOT granted")" = 2 ] && break + sleep .05 +done +[ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND objid=$KEY AND NOT granted")" = 2 ] +echo held_uploads=2 +echo upload_bytes_each=33554432 +peak=0 +for n in $(seq 1 10); do + rss=$(app_rss); [ "$rss" -le "$peak" ] || peak=$rss; sleep .05 +done +echo "held_app_rss_kib=$peak" +sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='$HOLDER'" >/dev/null +wait "$LOCKER" 2>/dev/null || true; LOCKER= +for p in $CLIENTS; do wait "$p" || { echo 'FAIL - chunked upload/download client' >&2; exit 1; }; done +CLIENTS= +for n in 1 2; do while IFS= read -r line; do printf '%s\n' "$line"; done < "$T/result.$n"; done +# Both Content-Length and unknown-length chunked legacy bodies must be rejected +# by lighttpd before kcgi, without lowering the accepted complete-file limit. +for n in 1 2; do + ( + if [ "$n" = 1 ]; then set --; else set -- -H 'Transfer-Encoding: chunked'; fi + code=$(curl --max-time 20 -sS -o "$T/rejected.$n" -w '%{http_code}' "$@" \ + -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' \ + -F "file=@$T/source.$n" http://localhost:8080/api/docs) + [ "$code" = 413 ] + ) & CLIENTS="$CLIENTS $!" +done +for p in $CLIENTS; do wait "$p"; done; CLIENTS= +echo 'legacy_32MiB_raw_and_chunked_transfer_requests=413_before_kcgi' +kill -TERM "$SAMPLER"; wait "$SAMPLER"; SAMPLER= +while IFS= read -r line; do printf '%s\n' "$line"; done < "$T/peak" +peak=$(awk -F= '/transient_sampled_app_peak_kib/ {print $2}' "$T/peak") +echo budget_bytes=60000000 +if [ "$((peak * 1024))" -gt 60000000 ]; then + echo 'budget_result=exceeded; native/resource gate remains OPEN' +else + echo 'budget_result=within_for_fixture; native/resource gate remains OPEN' +fi
diff --git a/test/signature-contract.sh b/test/signature-contract.sh @@ -0,0 +1,154 @@ +#!/bin/sh +# Destructive acceptance only in an isolated dev stack; all data is synthetic. +set -eu +B=http://localhost:8080 +X='X-Requested-With: signet' +U=collection_$(date +%s) +O=other_$(date +%s) +T=$(mktemp -d /tmp/signature-contract.XXXXXX) +as() { u=$1; g=$2; shift 2; curl -fsS -H "Remote-User: $u" -H "Remote-Groups: $g" "$@"; } +me() { as "$U" management "$B/api/me"; } +fail() { echo "FAIL - $*" >&2; exit 1; } +status() { want=$1; u=$2; g=$3; shift 3; got=$(curl -sS -o "$T/response" -w '%{http_code}' -H "Remote-User: $u" -H "Remote-Groups: $g" -H "$X" "$@"); [ "$got" = "$want" ] || fail "HTTP $got expected $want"; } +stop() { pkill -f '^/usr/local/sbin/signetd$' 2>/dev/null || true; sleep .2; } +start() { su-exec signetd:signet /usr/local/sbin/signetd >>/tmp/signature-contract-worker.log 2>&1 & } +cleanup() { + redis-cli ACL SETUSER default +lpush >/dev/null 2>&1 || true + if [ -f "$T/saved.png" ]; then + cp "$T/saved.png" "/var/lib/signatures/$SQUARE.png" + chown signetd:signet "/var/lib/signatures/$SQUARE.png" + chmod 600 "/var/lib/signatures/$SQUARE.png" + fi + stop; start + rm -rf "$T" +} +trap cleanup EXIT +upload() { as "$U" management -H "$X" -F "label=$1" -F "file=@$2" "$B/api/me/facsimile" | jq -er .id || fail 'enrolment must return an immutable variant reference'; } +ready() { + for i in $(seq 1 100); do + f=$(me | jq -c --arg id "$1" '.facsimiles[] | select(.id==$id)') + [ "$(printf '%s' "$f" | jq -r .error)" = null ] || fail 'enrolment failed' + [ "$(printf '%s' "$f" | jq -r .enrolled)" = true ] && return + sleep .1 + done + fail 'enrolment timeout' +} +default_to() { as "$U" management -H "$X" -F "facsimile_id=$1" "$B/api/me/facsimile/default" >/dev/null; } +getdoc() { as "$U" management "$B/api/docs/$ID"; } +waitdoc() { + for i in $(seq 1 100); do + D=$(getdoc) + [ "$(echo "$D" | jq -r .render_error)" = null ] || fail 'render failed' + [ "$(echo "$D" | jq -r .rendering)" = false ] && return + sleep .1 + done + fail 'render timeout' +} +newdoc() { + ID=$(as asha clerks -H "$X" -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" | jq -er .id) + J=$(jq -nc --arg u "$U" '{title:"Signature collection",org_code:"COLLECTION16",route:{parties:[{name:"Signer",signer:$u}]},layout:{reference_width:1000,reference_height:1414,imprints:[{type:"signature_zone",party:"Signer",page:1,coords:[120,550,500,700],min_w:50,min_h:20}]}}') + as asha clerks -H "$X" --form-string "json=$J" "$B/api/docs/$ID/save" >/dev/null + as asha clerks -H "$X" -d '' "$B/api/docs/$ID/submit" >/dev/null + waitdoc +} +PL='{"page":1,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}' +FULL=$(upload 'Full signature' /src/test/fixtures/sig.png); ready "$FULL" +SQUARE=$(upload 'Short signature' /src/test/fixtures/seal.png); ready "$SQUARE" +me | jq -e --arg id "$FULL" '.facsimile.id==$id and ([.facsimiles[]|select(.enrolled)]|length)==2 and ([.facsimiles[]|select(.is_default)]|length)==1' >/dev/null || fail 'collection/default lost on second enrolment' +[ "$(stat -c %a "/var/lib/signatures/$SQUARE.png")" = 600 ] || fail 'private image permissions' +if su-exec signet test -r "/var/lib/signatures/$SQUARE.png"; then fail 'API can read private image'; fi +FOREIGN=$(as root signet-admins -H "$X" -F "user=$O" -F 'label=Admin enrolled' -F file=@/src/test/fixtures/sig.png "$B/api/facsimiles" | jq -er .id) +status 403 "$U" clerks -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +status 409 "$U" management -F "facsimile_id=$FOREIGN" "$B/api/me/facsimile/default" +status 409 "$U" management -F "facsimile_id=$FOREIGN" "$B/api/me/facsimile/retry" +status 400 "$U" management --form-string 'facsimile_id=../manager' "$B/api/me/facsimile/default" +status 400 "$U" management -F 'label=' -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +status 400 "$U" management -F 'label= ' -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +printf 'bad\000label' > "$T/label" +status 400 "$U" management -F "label=<$T/label" -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +status 403 "$U" clerks -F "facsimile_id=$SQUARE" "$B/api/me/facsimile/retry" +status 404 "$U" management "$B/api/me/facsimile/$SQUARE" +status 404 "$U" management "$B/dam/$SQUARE.png" +newdoc +status 409 "$U" management -F decision=signoff -F "facsimile_id=$FOREIGN" --form-string "placement=$PL" "$B/api/docs/$ID/decide" +getdoc | jq -e '(.decisions|length)==0 and .can_decide' >/dev/null || fail 'foreign choice recorded' +printf '%s\000suffix' "$SQUARE" > "$T/reference" +status 400 "$U" management -F decision=signoff --form-string "placement=$PL" -F "facsimile_id=<$T/reference" "$B/api/docs/$ID/decide" +stop +as "$U" management -H "$X" -F decision=signoff -F "facsimile_id=$SQUARE" --form-string "placement=$PL" "$B/api/docs/$ID/decide" >/dev/null +getdoc | jq -e --arg id "$SQUARE" '.decisions[0].facsimile_id==$id' >/dev/null || fail 'selected reference not frozen' +default_to "$SQUARE"; default_to "$FULL" +cp "/var/lib/signatures/$SQUARE.png" "$T/saved.png" +cp /src/test/fixtures/sig.png "/var/lib/signatures/$SQUARE.png" +chown signetd:signet "/var/lib/signatures/$SQUARE.png" +start +for i in $(seq 1 100); do D=$(getdoc); [ "$(echo "$D" | jq -r .render_error)" != null ] && break; sleep .1; done +echo "$D" | jq -e '.status=="PENDING" and (.render_error|contains("damaged"))' >/dev/null || fail 'changed variant silently used' +stop +cp "$T/saved.png" "/var/lib/signatures/$SQUARE.png"; rm "$T/saved.png" +chown signetd:signet "/var/lib/signatures/$SQUARE.png" +chmod 600 "/var/lib/signatures/$SQUARE.png" +as "$U" management -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null +start; waitdoc +[ "$(echo "$D" | jq -r .status)" = RELEASED ] || fail 'release missing' +as "$U" management "$B/api/docs/$ID/file/final" -o "$T/final.pdf" +pdfimages -list "$T/final.pdf" | awk '$3=="image" {print $4 "x" $5}' | grep -qx 200x200 || fail 'queued selection followed the default instead' +qpdf --check "$T/final.pdf" >/dev/null +# Missing reference remains compatible, but is resolved now, not in the worker. +newdoc; stop +as "$U" management -H "$X" -F decision=signoff --form-string "placement=$PL" "$B/api/docs/$ID/decide" >/dev/null +getdoc | jq -e --arg id "$FULL" '.decisions[0].facsimile_id==$id' >/dev/null || fail 'default choice not pinned' +default_to "$SQUARE"; start; waitdoc +as "$U" management "$B/api/docs/$ID/file/final" -o "$T/final.pdf" +pdfimages -list "$T/final.pdf" | awk '$3=="image" {print $4 "x" $5}' | grep -qx 300x80 || fail 'default changed queued sign-off' +head -c 33 /src/test/fixtures/sig.png > "$T/truncated.png" +BAD=$(upload 'Broken upload' "$T/truncated.png") +for i in $(seq 1 100); do me | jq -e --arg id "$BAD" 'any(.facsimiles[]; .id==$id and .error!=null)' >/dev/null && break; sleep .1; done +me | jq -e --arg id "$SQUARE" --arg bad "$BAD" '.facsimile.id==$id and any(.facsimiles[]; .id==$bad and .error!=null and (.enrolled|not))' >/dev/null || fail 'failed upload displaced default' +[ ! -e "/var/lib/signatures/$BAD.png" ] && [ ! -e "/var/lib/signet/sig-inbox/$BAD.png" ] || fail 'invalid image retained' +status 409 "$U" management -F "facsimile_id=$BAD" "$B/api/me/facsimile/retry" +# LPUSH denial must not leave an unqueued pending row or upload file. +BEFORE=$(me | jq '.facsimiles|length') +redis-cli ACL SETUSER default -lpush >/dev/null +status 503 "$U" management -F label=QueueDown -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +redis-cli ACL SETUSER default +lpush >/dev/null +[ "$(me | jq '.facsimiles|length')" = "$BEFORE" ] || fail 'queue outage left pending metadata' +# Persisted pre-upgrade decisions have NULL references and mean the legacy +# username.png, never a newer default. Emulate that exact stored shape. +SAVED_USER=$U +U=manager +LEGACY=$(su-exec postgres psql -X -At -d signet -c "SELECT id FROM facsimiles WHERE username='manager' AND storage_id IS NULL") +OLD_DEFAULT=$(me | jq -r .facsimile.id) +ALTERNATE=$(upload 'Legacy replay alternate' /src/test/fixtures/seal.png); ready "$ALTERNATE" +default_to "$LEGACY" +newdoc; stop +as "$U" management -H "$X" -F decision=signoff --form-string "placement=$PL" "$B/api/docs/$ID/decide" >/dev/null +su-exec postgres psql -X -v ON_ERROR_STOP=1 -d signet -c "UPDATE doc_decisions SET facsimile_id=NULL WHERE doc_id='$ID'" >/dev/null +default_to "$ALTERNATE"; start; waitdoc +as "$U" management "$B/api/docs/$ID/file/final" -o "$T/final.pdf" +pdfimages -list "$T/final.pdf" | awk '$3=="image" {print $4 "x" $5}' | grep -qx 300x80 || fail 'legacy decision followed a new default' +default_to "$OLD_DEFAULT" +U=$SAVED_USER +# Bound live/pending metadata without blocking retries after invalid PNGs. +Q=quota_$(date +%s) +stop +for i in $(seq 1 32); do + as "$Q" management -H "$X" -F "label=Variant $i" -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" >/dev/null +done +status 409 "$Q" management -F label=TooMany -F file=@/src/test/fixtures/sig.png "$B/api/me/facsimile" +PENDING=$(as "$Q" management "$B/api/me" | jq -r '.facsimiles[0].id') +status 409 "$Q" management -F "facsimile_id=$PENDING" "$B/api/me/facsimile/default" +# Simulate a lost queued activation, then retry twice: no replacement or double activation. +JOB=$(jq -nc --arg u "$Q" --arg id "$PENDING" '{kind:"enrol",user:$u,facsimile_id:$id}') +[ "$(redis-cli LREM queue:stamping 0 "$JOB")" = 1 ] || fail 'lost-activation fixture did not remove its exact queued job' +status 200 "$Q" management -F "facsimile_id=$PENDING" "$B/api/me/facsimile/retry" +status 200 "$Q" management -F "facsimile_id=$PENDING" "$B/api/me/facsimile/retry" +start +for i in $(seq 1 100); do + COUNT=$(as "$Q" management "$B/api/me" | jq '[.facsimiles[]|select(.enrolled)]|length') + [ "$COUNT" = 32 ] && break + sleep .1 +done +[ "$COUNT" = 32 ] || fail 'bounded collection did not activate' +as "$Q" management "$B/api/me" | jq -e '[.facsimiles[]|select(.is_default)]|length==1' >/dev/null || fail 'first activation produced multiple defaults' +echo 'signature collection contract: all passed'
diff --git a/test/signature-migration.sh b/test/signature-migration.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Real PostgreSQL upgrade from the former metadata schema, in a temporary DB. +set -eu +DB=signature_upgrade_$$ +su-exec postgres createdb -O signet "$DB" +trap 'su-exec postgres dropdb --if-exists --force "$DB" >/dev/null' EXIT +sql() { su-exec signet psql -X -At -v ON_ERROR_STOP=1 -d "$DB" "$@"; } +sql <<'SQL' >/dev/null +CREATE TABLE facsimiles (username VARCHAR(100) PRIMARY KEY, enrolled_at TIMESTAMPTZ, + enrolled_by VARCHAR(100) NOT NULL, width INTEGER, height INTEGER); +CREATE TABLE doc_decisions (id BIGINT PRIMARY KEY, signer VARCHAR(100), placement JSONB); +INSERT INTO facsimiles VALUES ('manager','2026-09-19','admin',300,80),('pending',NULL,'pending',NULL,NULL); +INSERT INTO doc_decisions VALUES (1,'manager','{"page":1}'); +SQL +fingerprint() { sql -c 'SELECT md5(json_agg(t ORDER BY username)::text) FROM (SELECT username,enrolled_at,enrolled_by,width,height FROM facsimiles) t'; } +BEFORE=$(fingerprint) +sql -f /src/sql/migrations/002-signature-collections.sql >/dev/null +sql -f /src/sql/migrations/002-signature-collections.sql >/dev/null +[ "$BEFORE" = "$(fingerprint)" ] || { echo 'legacy metadata changed'; exit 1; } +[ "$(sql -c "SELECT count(*) FROM facsimiles WHERE storage_id IS NULL AND is_default AND label='Signature'")" = 2 ] +[ "$(sql -c 'SELECT facsimile_id IS NULL FROM doc_decisions WHERE id=1')" = t ] +sql <<'SQL' >/dev/null +INSERT INTO facsimiles (username,enrolled_by,label,is_default,storage_id) + VALUES ('manager','manager','Short',false,gen_random_uuid()); +UPDATE doc_decisions SET facsimile_id=(SELECT id FROM facsimiles WHERE username='manager' AND storage_id IS NULL); +SQL +sql -f /src/sql/migrations/002-signature-collections.sql >/dev/null +[ "$(sql -c "SELECT count(*) FROM facsimiles WHERE username='manager'")" = 2 ] +echo 'signature migration: original metadata preserved, legacy decisions retained, repeat upgrade and collection insert passed'
diff --git a/test/signing-flow.mjs b/test/signing-flow.mjs @@ -15,6 +15,7 @@ try { 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' }); + if (page.url().startsWith(base)) await page.reload(); } await identity('root', 'signet-admins'); for (const [key, type, value] of [['gstin', 'text', '33AAAAA0000A1Z5'], ['seal', 'image', 'seals/agency_seal.png'], ['logo', 'image', 'seals/agency_image.jpg']]) { @@ -83,7 +84,32 @@ try { await identity(finalSigner, 'management'); assert.equal((await context.request.get(base + `/api/docs/${id}`)).status(), 404); await identity('manager', 'management'); + const originalSignature = (await (await context.request.get(base + '/api/me')).json()).facsimile; + await page.getByRole('link', { name: 'My signatures', exact: true }).click(); + await page.getByRole('heading', { name: 'My signatures', exact: true }).waitFor(); + const alternateLabel = 'Browser alternate ' + Date.now(); + await page.getByLabel('Signature label', { exact: true }).fill(alternateLabel); + await page.getByLabel('Or upload PNG', { exact: true }).setInputFiles(new URL('fixtures/seal.png', import.meta.url).pathname); + await page.getByRole('button', { name: 'Enrol signature', exact: true }).click(); + await page.getByText(alternateLabel, { exact: true }).waitFor(); + let collection = await (await context.request.get(base + '/api/me')).json(); + const alternate = collection.facsimiles.find((f) => f.label === alternateLabel); + assert(alternate.enrolled); + assert.equal(collection.facsimile.id, originalSignature.id, 'adding a variant must not replace the default'); + await page.locator('.row').filter({ has: page.getByText(alternateLabel, { exact: true }) }).getByRole('button', { name: /as default$/ }).click(); + await page.getByText('Default updated', { exact: true }).waitFor(); + assert.equal((await (await context.request.get(base + '/api/me')).json()).facsimile.id, alternate.id); + await page.locator('.row').filter({ has: page.getByText(originalSignature.label, { exact: true }) }).getByRole('button', { name: /as default$/ }).click(); + await page.waitForFunction((name) => [...document.querySelectorAll('.card .row')].some((r) => r.textContent.includes(name) && r.textContent.includes('Default')), originalSignature.label); + await page.screenshot({ path: output + '/signature-collection.png', fullPage: true }); await open(); + await page.getByLabel('Signature to use', { exact: true }).selectOption(alternate.id); + let shape = await page.locator('area[data-placement]').getAttribute('data-coords'); + let bounds = shape.split(',').map(Number); + assert(Math.abs((bounds[2] - bounds[0]) / (bounds[3] - bounds[1]) - 1) < .01, 'picker must refit to selected dimensions'); + assert.equal(await page.locator('area[data-placement]').count(), 1); + await page.screenshot({ path: output + '/signature-picker.png', fullPage: true }); + await page.getByLabel('Signature to use', { exact: true }).selectOption(originalSignature.id); let placement = page.locator('.placement'); await placement.waitFor(); let coords = await page.locator('area[data-placement]').getAttribute('data-coords'); @@ -102,7 +128,7 @@ try { 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(); + assert.equal((await ready()).decisions[0].facsimile_id, originalSignature.id, 'browser choice must be recorded'); await open(); await capture('stamped'); await identity('auditor', 'management'); @@ -127,6 +153,25 @@ try { 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); + // A full collection must remain usable, including long labels and the form below it. + const listContext = await browser.newContext({ viewport: { width: 800, height: 700 }, extraHTTPHeaders: { + 'Remote-User': 'collection_ui_' + Date.now(), 'Remote-Groups': 'management', 'X-Requested-With': 'signet' + } }); + const sample = await readFile(new URL('fixtures/sig.png', import.meta.url)); + for (let i = 0; i < 32; i++) { + assert((await listContext.request.post(base + '/api/me/facsimile', { multipart: { + label: i ? 'Variant ' + i : 'W'.repeat(80), file: { name: 'sig.png', mimeType: 'image/png', buffer: sample } + } })).ok()); + } + const listPage = await listContext.newPage(); + listPage.on('pageerror', (e) => errors.push(e.message)); + await listPage.goto(base + '/#/signatures'); + await listPage.getByRole('heading', { name: 'My signatures', exact: true }).waitFor(); + await listPage.getByRole('button', { name: 'Enrol signature', exact: true }).scrollIntoViewIfNeeded(); + assert(await listPage.locator('.signature-collection').evaluate((el) => el.scrollTop > 0)); + assert(await listPage.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + await listPage.screenshot({ path: output + '/signature-collection-scroll.png' }); + await listContext.close(); 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) {
diff --git a/test/snapshot-contract.sh b/test/snapshot-contract.sh @@ -88,9 +88,9 @@ PL2='{"page":2,"coords":[400,1000,850,1200],"ref_w":1000,"ref_h":1414}' new_doc # Ignored JSON must not bypass the bounded parse/clone path; include legacy rows. printf '%s' "$LAYOUT" | jq -cj '.layout.unused="" | .layout.unused=("x" * (1048576 - (tojson | utf8bytelength)))' > "$TMP/large-json" -status 200 --data-urlencode "json@$TMP/large-json" "$B/api/docs/$ID/save" +status 200 --form "json=<$TMP/large-json" "$B/api/docs/$ID/save" printf ' ' >> "$TMP/large-json" -status 400 --data-urlencode "json@$TMP/large-json" "$B/api/docs/$ID/save" +status 400 --form "json=<$TMP/large-json" "$B/api/docs/$ID/save" save "$LAYOUT" >/dev/null for column in layout_json route_json; do sql -c "UPDATE documents SET $column=$column || jsonb_build_object('unused',repeat(chr(2949),350000)) WHERE id='$ID'" >/dev/null @@ -225,12 +225,13 @@ chmod 0440 "$SNAP/asset-0" rm "$FONT" "$EXPLICIT" "$SEAL" "$JPEG" sql <<SQL >/dev/null CREATE FUNCTION snapshot_complete() RETURNS trigger LANGUAGE plpgsql AS \$\$ -BEGIN IF NEW.id='$ID' AND NEW.rendered_seq>OLD.rendered_seq THEN RAISE EXCEPTION 'snapshot completion replay $ID'; END IF; RETURN NEW; END \$\$; +BEGIN IF NEW.id='$ID' AND NEW.rendered_seq>OLD.rendered_seq THEN RAISE EXCEPTION 'snapshot completion replay' USING ERRCODE='P2212'; END IF; RETURN NEW; END \$\$; CREATE TRIGGER snapshot_complete BEFORE UPDATE ON documents FOR EACH ROW EXECUTE FUNCTION snapshot_complete(); SQL as asha clerks -H "$X" -d '' "$B/api/docs/$ID/rerender" >/dev/null -for i in $(seq 1 100); do grep -q "snapshot completion replay $ID" /tmp/snapshot-worker.log && break; sleep .1; done -grep -q "snapshot completion replay $ID" /tmp/snapshot-worker.log || fail 'stamp completion database failure not exercised' +# A unique SQLSTATE proves this fixture fired without logging server text/IDs. +for i in $(seq 1 100); do grep -q 'SQLSTATE P2212' /tmp/snapshot-worker.log && break; sleep .1; done +grep -q 'SQLSTATE P2212' /tmp/snapshot-worker.log || fail 'stamp completion database failure not exercised' stop CACHE_HASH=$(sha256sum "$BASE/proof-$KEY.pdf" | cut -d ' ' -f 1) CALLS=$(wc -l < "$TMP/qpdf-calls")
diff --git a/test/timestamp-client.c b/test/timestamp-client.c @@ -0,0 +1,24 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "timestamp.h" + +int +main(int argc, char **argv) +{ + struct timestamp_reply reply; + int rc; + + assert(argc == 6); + rc = timestamp_fetch(argv[1], argv[2], argv[3], + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + atol(argv[5]), &reply); + if (strcmp(argv[4], "good") == 0) + assert(rc == 0 && reply.error == NULL && reply.size > 0 && reply.at[0] != '\0'); + else + assert(rc == -1 && reply.error != NULL && reply.at[0] == '\0'); + printf("timestamp verification case=%s passed\n", argv[4]); + return 0; +}
diff --git a/test/timestamp-contract.sh b/test/timestamp-contract.sh @@ -0,0 +1,277 @@ +#!/bin/sh +# Local synthetic HTTPS TSA only. Never run against preserved/shared services. +set -eu +[ "${SIGNET_TIMESTAMP_TEST_DISPOSABLE:-}" = yes ] || exit 2 +cd /src +T=$(mktemp -d /tmp/signet-timestamp.XXXXXX) +SERVER=; HOLDER=; CRON=; RUNNER=; SAMPLER=; RENAMED=; API_CONFIGURED= +cleanup() { + if [ -n "$API_CONFIGURED" ]; then restart_api /etc/signet/signet.conf || true; fi + if [ -n "$RENAMED" ]; then sql -c 'ALTER TABLE document_timestamps RENAME COLUMN fixture_response TO response' > /dev/null 2>&1 || true; fi + if [ -n "$SAMPLER" ]; then kill "$SAMPLER" 2>/dev/null || true; wait "$SAMPLER" 2>/dev/null || true; fi + if [ -n "$RUNNER" ]; then kill "$RUNNER" 2>/dev/null || true; wait "$RUNNER" 2>/dev/null || true; fi + if [ -n "$CRON" ]; then kill "$CRON" 2>/dev/null || true; wait "$CRON" 2>/dev/null || true; fi + pkill -f "^/usr/local/libexec/signet-timestamp -c $T/worker[.]conf$" 2>/dev/null || true + if [ -n "$HOLDER" ]; then + sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='timestamp_holder_$$'" > /dev/null 2>&1 || true + wait "$HOLDER" 2>/dev/null || true + fi + if [ -n "$SERVER" ]; then kill "$SERVER" 2>/dev/null || true; wait "$SERVER" 2>/dev/null || true; fi + rm -rf "$T" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +chmod 755 "$T" +if [ "${SIGNET_TIMESTAMP_TEST_RSS:-no}" = yes ]; then + cc -std=c99 -O2 -Wall -Wextra test/resource-rss.c -o "$T/rss" + : > "$T/rss.log" + "$T/rss" "$(id -u signet)" "$(id -u signetd)" "$(id -u lighttpd)" > "$T/rss.log" & + SAMPLER=$!; n=0 + while ! grep -q '^sampler_ready=1$' "$T/rss.log"; do + kill -0 "$SAMPLER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .01 + done +fi +sh /src/test/timestamp-migration.sh +cc -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \ + test/timestamp-fixture.c -lssl -lcrypto -o "$T/fixture" +cc -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra -Isrc \ + $(pkg-config --cflags libcurl libcrypto) test/timestamp-client.c src/timestamp.c \ + $(pkg-config --libs libcurl libcrypto) -o "$T/client" +"$T/fixture" "$T" > "$T/server.log" 2>&1 & +SERVER=$!; n=0 +while [ ! -f "$T/port" ]; do + kill -0 "$SERVER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +port=$(tr -d '\n' < "$T/port") +URL=https://127.0.0.1:$port +"$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" good 3000 +for mode in good384 good512; do + printf '%s\n' "$mode" > "$T/mode" + "$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" good 3000 +done +for mode in nonce imprint signature malformed oversize http expired weak rejected; do + printf '%s\n' "$mode" > "$T/mode" + "$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" "$mode" 3000 +done +printf '%s\n' good > "$T/mode" +"$T/client" "$URL" "$T/other.pem" "$T/ca.pem" untrusted_tsa 3000 +"$T/client" "$URL" "$T/ca.pem" "$T/other.pem" untrusted_https 3000 +"$T/client" "http://127.0.0.1:$port" "$T/ca.pem" "$T/ca.pem" non_https 3000 +printf '%s\n' slow > "$T/mode" +"$T/client" "$URL" "$T/ca.pem" "$T/ca.pem" timeout 200 +sleep 2 +printf '%s\n' good > "$T/mode" +# Existing tests may have released synthetic documents; keep this fixture's +# network work scoped to the new document. This is why opt-in is mandatory. +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d signet "$@"; } +sql -f sql/migrations/004-detached-timestamps.sql > /dev/null +sql -f sql/migrations/004-detached-timestamps.sql > /dev/null +sql -c "UPDATE document_timestamps SET state='unavailable',next_attempt_at=NULL WHERE state='pending'; + INSERT INTO document_timestamps (doc_id,revision,pdf_sha256,state,started_at,deadline) + SELECT id,revision,final_sha256,'unavailable',released_at,released_at+interval '1 hour' + FROM documents WHERE status='RELEASED' ON CONFLICT (doc_id) DO NOTHING" > /dev/null +awk '!/^timestamp\./' /etc/signet/signet.conf > "$T/worker.conf" +printf 'timestamp.url = %s\ntimestamp.ca_file = %s/ca.pem\ntimestamp.tls_ca_file = %s/ca.pem\n' "$URL" "$T" "$T" >> "$T/worker.conf" +chmod 644 "$T/worker.conf" "$T/ca.pem" +run_worker() { su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf"; } +restart_api() { + pkill -f '^kfcgi .* /run/signet/api.sock' 2>/dev/null || true + pkill -f '^/usr/local/libexec/signet-api' 2>/dev/null || true + tries=0 + while pgrep -f '^kfcgi .* /run/signet/api.sock|^/usr/local/libexec/signet-api' > /dev/null; do + tries=$((tries + 1)); [ "$tries" -lt 100 ]; sleep .05 + done + rm -f /run/signet/api.sock + SIGNET_CONF="$1" kfcgi -d -n 2 -N 2 -s /run/signet/api.sock -u lighttpd -U signet -p / -- \ + /usr/local/libexec/signet-api >> /proc/1/fd/2 2>&1 & + api_pid=$!; tries=0 + while [ ! -S /run/signet/api.sock ] || ! curl --max-time 2 -fsS -H 'Remote-User: asha' -H 'Remote-Groups: clerks' http://localhost:8080/api/me > /dev/null 2>&1; do + kill -0 "$api_pid"; tries=$((tries + 1)); [ "$tries" -lt 100 ]; sleep .05 + done +} +B=http://localhost:8080 +request() { + user=$1; groups=$2; shift 2 + curl --max-time 30 -fsS -H "Remote-User: $user" -H "Remote-Groups: $groups" \ + -H 'X-Requested-With: signet' "$@" +} +ORG=timestamp_test_$$ +request root signet-admins -F "org=$ORG" -F key=reference -F type=text -F value=synthetic "$B/pim-api/attrs" > /dev/null +request asha clerks -F file=@test/fixtures/letter.pdf "$B/api/docs" > "$T/created" +ID=$(jq -er .id "$T/created") +jq -nc --arg org "$ORG" '{title:"Synthetic detached timestamp",org_code:$org, + route:{parties:[{name:"Manager",signer:"manager"}]}, + layout:{reference_width:1000,reference_height:1414,imprints:[]}}' > "$T/layout" +request asha clerks -F "json=<$T/layout" "$B/api/docs/$ID/save" > /dev/null +request asha clerks -d '' "$B/api/docs/$ID/submit" > /dev/null +wait_ready() { + n=0 + while :; do + request asha clerks "$B/api/docs/$ID" > "$T/doc" + jq -e '.render_error == null' "$T/doc" > /dev/null + if jq -e '.rendered_seq == .render_seq' "$T/doc" > /dev/null; then return; fi + n=$((n + 1)); [ "$n" -lt 200 ]; sleep .05 + done +} +wait_ready +request manager management -F decision=signoff "$B/api/docs/$ID/decide" > /dev/null +wait_ready +jq -e '.status == "RELEASED" and .signed_at != null and .timestamped_at == null' "$T/doc" > /dev/null +SHA=$(jq -er .final_sha256 "$T/doc") +SIGNED=$(jq -er .signed_at "$T/doc") +jq -e '.timestamp_status == "not_requested" and .timestamp_attempts == 0' "$T/doc" > /dev/null +API_CONFIGURED=yes +restart_api "$T/worker.conf" +request asha clerks "$B/api/docs/$ID" > "$T/doc" +jq -e '.timestamp_status == "pending" and .timestamped_at == null' "$T/doc" > /dev/null +# A concurrent runner cannot claim an attempt while the session lock is held. +su-exec postgres env PGAPPNAME="timestamp_holder_$$" psql -X -q -d signet \ + -c 'SELECT pg_advisory_lock(1936289381,1953721965); SELECT pg_sleep(30)' > "$T/holder" 2>&1 & +HOLDER=$!; n=0 +while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 1 ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +count=$(tr -d '\n' < "$T/requests") +run_worker +[ "$(tr -d '\n' < "$T/requests")" = "$count" ] +sql -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='timestamp_holder_$$'" > /dev/null +wait "$HOLDER" 2>/dev/null || true +HOLDER= +# HTTP failure must not alter the final PDF, release, or recorded sign-off time. +printf '%s\n' http > "$T/mode" +for attempt in 1 2 3 4; do + if [ "$attempt" -gt 1 ]; then + sql -c "UPDATE document_timestamps SET next_attempt_at=clock_timestamp()-interval '1 second' WHERE doc_id='$ID'" > /dev/null + fi + run_worker + [ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = "$attempt" ] + if [ "$attempt" = 1 ]; then + [ "$(sql -c "SELECT next_attempt_at=started_at+interval '5 minutes' FROM document_timestamps WHERE doc_id='$ID'")" = t ] + fi +done +[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = unavailable ] +request asha clerks "$B/api/docs/$ID" > "$T/doc" +jq -e --arg signed "$SIGNED" '.status == "RELEASED" and .signed_at == $signed and .timestamp_status == "unavailable" and .timestamped_at == null' "$T/doc" > /dev/null +count=$(tr -d '\n' < "$T/requests") +run_worker +[ "$(tr -d '\n' < "$T/requests")" = "$count" ] +# A crash after claim/request consumes its slot; restarting cannot reclaim it. +sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null +rm -f "$T/holding" "$T/release" +printf '%s\n' hold > "$T/mode" +su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf" > "$T/crashed" 2>&1 & +RUNNER=$!; n=0 +while [ ! -f "$T/holding" ]; do + kill -0 "$RUNNER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +[ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = 1 ] +kill -KILL "$RUNNER"; wait "$RUNNER" 2>/dev/null || true; RUNNER= +: > "$T/release" +n=0 +while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 0 ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +count=$(tr -d '\n' < "$T/requests") +run_worker +[ "$(sql -c "SELECT attempts FROM document_timestamps WHERE doc_id='$ID'")" = 1 ] +[ "$(tr -d '\n' < "$T/requests")" = "$count" ] +# A missed window expires without another request, even after process restart. +sql -c "UPDATE document_timestamps SET state='pending',attempts=1,started_at=CURRENT_TIMESTAMP-interval '2 hours', + deadline=CURRENT_TIMESTAMP-interval '1 hour',next_attempt_at=clock_timestamp()-interval '1 hour' WHERE doc_id='$ID'" > /dev/null +run_worker +[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = unavailable ] +[ "$(tr -d '\n' < "$T/requests")" = "$count" ] +# Reset only this synthetic fixture's evidence to exercise successful validation. +sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null +printf '%s\n' good > "$T/mode" +run_worker +request asha clerks "$B/api/docs/$ID" > "$T/doc" +jq -e --arg sha "$SHA" --arg signed "$SIGNED" '.status == "RELEASED" and .final_sha256 == $sha and .signed_at == $signed and .timestamp_status == "timestamped" and .timestamped_at != null and .timestamp_attempts == 1' "$T/doc" > /dev/null +request asha clerks "$B/api/docs/$ID/file/final" > "$T/final.pdf" +[ "$(sha256sum "$T/final.pdf" | cut -d ' ' -f 1)" = "$SHA" ] +request asha clerks "$B/api/docs/$ID/file/timestamp" > "$T/download.tsr" +cmp "$T/download.tsr" "$T/response.der" +request manager management "$B/api/docs/$ID/file/timestamp" > "$T/party.tsr" +cmp "$T/download.tsr" "$T/party.tsr" +request root signet-admins "$B/api/docs/$ID/file/timestamp" > "$T/admin.tsr" +cmp "$T/download.tsr" "$T/admin.tsr" +# Backend failure is temporarily unavailable, not a false missing-evidence claim. +sql -c 'ALTER TABLE document_timestamps RENAME COLUMN response TO fixture_response' > /dev/null +RENAMED=yes +code=$(curl --max-time 10 -sS -o "$T/backend" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp") +[ "$code" = 503 ] +sql -c 'ALTER TABLE document_timestamps RENAME COLUMN fixture_response TO response' > /dev/null +RENAMED= +# Even a valid stored response must match the released revision AND hash. +sql -c "UPDATE document_timestamps SET revision=revision+1 WHERE doc_id='$ID'" > /dev/null +code=$(curl --max-time 10 -sS -o "$T/stale" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp") +[ "$code" = 404 ] +sql -c "UPDATE document_timestamps SET revision=revision-1,pdf_sha256=repeat('b',64) WHERE doc_id='$ID'" > /dev/null +code=$(curl --max-time 10 -sS -o "$T/stale" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp") +[ "$code" = 404 ] +request asha clerks "$B/api/docs/$ID" > "$T/stale-meta" +jq -e '.timestamped_at == null and .timestamp_status != "timestamped"' "$T/stale-meta" > /dev/null +sql -c "UPDATE document_timestamps SET pdf_sha256='$SHA' WHERE doc_id='$ID'" > /dev/null +code=$(curl --max-time 10 -sS -o "$T/denied" -w '%{http_code}' -H 'Remote-User: unrelated' -H 'Remote-Groups: clerks' "$B/api/docs/$ID/file/timestamp") +[ "$code" = 404 ] +count=$(tr -d '\n' < "$T/requests") +run_worker +[ "$(tr -d '\n' < "$T/requests")" = "$count" ] +if sql -c "UPDATE document_timestamps SET attempts=5 WHERE doc_id='$ID'" > "$T/constraint" 2>&1; then exit 1; fi +if sql -c "UPDATE document_timestamps SET response=repeat('x',65537)::bytea WHERE doc_id='$ID'" > "$T/constraint" 2>&1; then exit 1; fi +# Hold a real TSA request while a different document signs and releases. +sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null +rm -f "$T/holding" "$T/release" +printf '%s\n' hold > "$T/mode" +su-exec signetd:signet /usr/local/libexec/signet-timestamp -c "$T/worker.conf" > "$T/background" 2>&1 & +RUNNER=$!; n=0 +while [ ! -f "$T/holding" ]; do + kill -0 "$RUNNER"; n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 +done +ORIGINAL=$ID +request asha clerks -F file=@test/fixtures/letter.pdf "$B/api/docs" > "$T/second" +ID=$(jq -er .id "$T/second") +request asha clerks -F "json=<$T/layout" "$B/api/docs/$ID/save" > /dev/null +request asha clerks -d '' "$B/api/docs/$ID/submit" > /dev/null +wait_ready +request manager management -F decision=signoff "$B/api/docs/$ID/decide" > /dev/null +wait_ready +jq -e '.status == "RELEASED"' "$T/doc" > /dev/null +kill -0 "$RUNNER" +[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ORIGINAL'")" = pending ] +: > "$T/release" +wait "$RUNNER"; RUNNER= +ID=$ORIGINAL +[ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" = timestamped ] +printf '%s\n' good > "$T/mode" +echo 'timestamp independence: another document released while HTTPS request was held' +# Optional real scheduler acceptance; does not change the host/VM clock. +if [ "${SIGNET_TIMESTAMP_TEST_CRON:-no}" = yes ]; then + sql -c "DELETE FROM document_timestamps WHERE doc_id='$ID'" > /dev/null + mkdir "$T/crontabs" + printf '* * * * * /usr/local/libexec/signet-timestamp -c %s/worker.conf\n' "$T" > "$T/crontabs/signetd" + crond -f -c "$T/crontabs" -l 8 > "$T/cron.log" 2>&1 & + CRON=$!; n=0 + while [ "$(sql -c "SELECT state FROM document_timestamps WHERE doc_id='$ID'")" != timestamped ]; do + kill -0 "$CRON"; n=$((n + 1)); [ "$n" -lt 75 ]; sleep 1 + done + n=0 + while [ "$(sql -c "SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=1936289381 AND objid=1953721965 AND granted")" != 0 ]; do + n=$((n + 1)); [ "$n" -lt 100 ]; sleep .05 + done + kill "$CRON"; wait "$CRON" 2>/dev/null || true; CRON= + echo 'timestamp cron: real scheduled invocation passed' +fi +# Normal document status/event history is never replaced by timestamp outcomes. +[ "$(sql -c "SELECT count(*) FROM doc_events WHERE doc_id='$ID' AND action='RELEASED'")" = 1 ] +restart_api /etc/signet/signet.conf +API_CONFIGURED= +request asha clerks "$B/api/docs/$ID" > "$T/doc" +jq -e '.timestamp_status == "timestamped" and .timestamped_at != null' "$T/doc" > /dev/null +if [ -n "$SAMPLER" ]; then + kill "$SAMPLER"; wait "$SAMPLER"; SAMPLER= + peak=$(awk -F= '/^transient_sampled_app_peak_kib=/{print $2}' "$T/rss.log") + [ -n "$peak" ] && [ "$((peak * 1024))" -lt 60000000 ] + printf 'timestamp_contract_sampled_app_peak_kib=%s\n' "$peak" +fi +echo 'timestamp contract: nonce/imprint/signature/trust/TLS/size/status/timeouts, bounded retries, expiry, immutable PDF, separate times and authorized evidence passed'
diff --git a/test/timestamp-fixture.c b/test/timestamp-fixture.c @@ -0,0 +1,249 @@ +/* Private, local HTTPS TSA fixture. Keys are ephemeral and never leave memory. */ +#include <sys/socket.h> + +#include <arpa/inet.h> +#include <assert.h> +#include <netinet/in.h> +#include <signal.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#include <openssl/pem.h> +#include <openssl/rsa.h> +#include <openssl/ssl.h> +#include <openssl/ts.h> +#include <openssl/x509v3.h> + +static EVP_PKEY * +key(void) +{ + EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); + EVP_PKEY *p = NULL; + + assert(ctx && EVP_PKEY_keygen_init(ctx) > 0); + assert(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048) > 0); + assert(EVP_PKEY_keygen(ctx, &p) > 0); + EVP_PKEY_CTX_free(ctx); + return p; +} + +static void +extension(X509 *cert, X509 *issuer, int nid, const char *value) +{ + X509V3_CTX ctx; + X509_EXTENSION *ext; + + X509V3_set_ctx(&ctx, issuer, cert, NULL, NULL, 0); + ext = X509V3_EXT_conf_nid(NULL, &ctx, nid, (char *)value); + assert(ext && X509_add_ext(cert, ext, -1)); + X509_EXTENSION_free(ext); +} + +static X509 * +certificate(EVP_PKEY *p, X509 *issuer, EVP_PKEY *issuer_key, int purpose) +{ + X509 *cert = X509_new(); + X509_NAME *name; + + assert(cert && X509_set_version(cert, 2)); + assert(ASN1_INTEGER_set(X509_get_serialNumber(cert), purpose + 1)); + assert(X509_gmtime_adj(X509_getm_notBefore(cert), -60)); + assert(X509_gmtime_adj(X509_getm_notAfter(cert), 86400)); + assert(X509_set_pubkey(cert, p)); + name = X509_get_subject_name(cert); + assert(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, + (unsigned char *)(purpose == 0 ? "Synthetic TSA root" : purpose == 1 ? "Synthetic TSA" : "localhost"), -1, -1, 0)); + assert(X509_set_issuer_name(cert, issuer ? X509_get_subject_name(issuer) : name)); + extension(cert, issuer ? issuer : cert, NID_basic_constraints, + purpose == 0 ? "critical,CA:TRUE" : "critical,CA:FALSE"); + extension(cert, issuer ? issuer : cert, NID_key_usage, + purpose == 0 ? "critical,keyCertSign,cRLSign" : "critical,digitalSignature"); + extension(cert, issuer ? issuer : cert, NID_subject_key_identifier, "hash"); + if (purpose == 1) + extension(cert, issuer, NID_ext_key_usage, "critical,timeStamping"); + if (purpose == 2) { + extension(cert, issuer, NID_ext_key_usage, "serverAuth"); + extension(cert, issuer, NID_subject_alt_name, "IP:127.0.0.1,DNS:localhost"); + } + assert(X509_sign(cert, issuer_key ? issuer_key : p, EVP_sha256())); + return cert; +} + +static ASN1_INTEGER * +serial(TS_RESP_CTX *ctx, void *arg) +{ + static long count; + ASN1_INTEGER *n = ASN1_INTEGER_new(); + + (void)ctx; + (void)arg; + assert(n && ASN1_INTEGER_set(n, ++count)); + return n; +} + +static void +save(const char *dir, const char *name, const void *data, size_t size) +{ + char path[512]; + FILE *f; + + snprintf(path, sizeof(path), "%s/%s", dir, name); + assert((f = fopen(path, "wb")) != NULL); + assert(fwrite(data, 1, size, f) == size && fclose(f) == 0); +} + +int +main(int argc, char **argv) +{ + EVP_PKEY *ca_key, *tsa_key, *tls_key, *other_key; + X509 *ca, *tsa, *tls, *other, *expired; + SSL_CTX *ssl_ctx; + TS_RESP_CTX *ts_ctx; + ASN1_OBJECT *policy; + struct sockaddr_in addr = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) }; + socklen_t addrlen = sizeof(addr); + char path[512], header[256], input[8192], mode[32], ready[512]; + int sock, fd, n, size, used, body_offset, count = 0; + FILE *f; + + assert(argc == 2); + signal(SIGPIPE, SIG_IGN); + ca_key = key(); tsa_key = key(); tls_key = key(); other_key = key(); + ca = certificate(ca_key, NULL, NULL, 0); + tsa = certificate(tsa_key, ca, ca_key, 1); + expired = certificate(tsa_key, ca, ca_key, 1); + assert(X509_gmtime_adj(X509_getm_notAfter(expired), -1)); + assert(X509_sign(expired, ca_key, EVP_sha256())); + tls = certificate(tls_key, ca, ca_key, 2); + other = certificate(other_key, NULL, NULL, 0); + snprintf(path, sizeof(path), "%s/ca.pem", argv[1]); + assert((f = fopen(path, "w")) && PEM_write_X509(f, ca) && fclose(f) == 0); + snprintf(path, sizeof(path), "%s/other.pem", argv[1]); + assert((f = fopen(path, "w")) && PEM_write_X509(f, other) && fclose(f) == 0); + ssl_ctx = SSL_CTX_new(TLS_server_method()); + assert(ssl_ctx && SSL_CTX_use_certificate(ssl_ctx, tls) && SSL_CTX_use_PrivateKey(ssl_ctx, tls_key)); + ts_ctx = TS_RESP_CTX_new(); + policy = OBJ_txt2obj("1.2.3.4", 1); + assert(ts_ctx && policy && TS_RESP_CTX_set_signer_cert(ts_ctx, tsa)); + assert(TS_RESP_CTX_set_signer_key(ts_ctx, tsa_key)); + assert(TS_RESP_CTX_set_signer_digest(ts_ctx, EVP_sha256())); + assert(TS_RESP_CTX_set_def_policy(ts_ctx, policy)); + assert(TS_RESP_CTX_add_md(ts_ctx, EVP_sha256())); + TS_RESP_CTX_set_serial_cb(ts_ctx, serial, NULL); + sock = socket(AF_INET, SOCK_STREAM, 0); + assert(sock >= 0 && bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0); + assert(getsockname(sock, (struct sockaddr *)&addr, &addrlen) == 0 && listen(sock, 16) == 0); + snprintf(header, sizeof(header), "%u\n", ntohs(addr.sin_port)); + save(argv[1], "preparing", header, strlen(header)); + snprintf(path, sizeof(path), "%s/preparing", argv[1]); + snprintf(ready, sizeof(ready), "%s/port", argv[1]); + assert(rename(path, ready) == 0); + while ((fd = accept(sock, NULL, NULL)) >= 0) { + SSL *ssl = SSL_new(ssl_ctx); + BIO *body; + TS_REQ *req; + TS_RESP *response; + const unsigned char *cursor; + unsigned char *der = NULL, *query = NULL; + int query_size, response_size, status = 200; + + SSL_set_fd(ssl, fd); + if (SSL_accept(ssl) != 1) + goto closed; + used = 0; body_offset = 0; size = 0; + while (used < (int)sizeof(input) - 1) { + n = SSL_read(ssl, input + used, sizeof(input) - 1 - (size_t)used); + if (n <= 0) + goto closed; + used += n; + input[used] = '\0'; + if (body_offset == 0 && strstr(input, "\r\n\r\n")) { + char *length = strstr(input, "Content-Length:"); + + assert(length && sscanf(length, "Content-Length: %d", &size) == 1 && size > 0 && size < 4096); + body_offset = (int)(strstr(input, "\r\n\r\n") - input) + 4; + } + if (body_offset && used >= body_offset + size) + break; + } + assert(body_offset && used >= body_offset + size); + cursor = (unsigned char *)input + body_offset; + req = d2i_TS_REQ(NULL, &cursor, size); + assert(req && cursor == (unsigned char *)input + body_offset + size); + assert(TS_REQ_get_nonce(req) != NULL); + snprintf(header, sizeof(header), "%d\n", ++count); + save(argv[1], "requests", header, strlen(header)); + strcpy(mode, "good"); + snprintf(path, sizeof(path), "%s/mode", argv[1]); + if ((f = fopen(path, "r")) != NULL) { + assert(fgets(mode, sizeof(mode), f)); + mode[strcspn(mode, "\r\n")] = '\0'; + fclose(f); + } + if (strcmp(mode, "nonce") == 0) { + ASN1_INTEGER *wrong = ASN1_INTEGER_new(); + + assert(wrong && ASN1_INTEGER_set(wrong, 1) && TS_REQ_set_nonce(req, wrong)); + ASN1_INTEGER_free(wrong); + } + if (strcmp(mode, "imprint") == 0) { + unsigned char wrong[32] = { 0 }; + + assert(TS_MSG_IMPRINT_set_msg(TS_REQ_get_msg_imprint(req), wrong, sizeof(wrong))); + } + if (strcmp(mode, "rejected") == 0) + assert(TS_REQ_set_version(req, 2)); + assert(TS_RESP_CTX_set_signer_cert(ts_ctx, strcmp(mode, "expired") == 0 ? expired : tsa)); + assert(TS_RESP_CTX_set_signer_digest(ts_ctx, + strcmp(mode, "weak") == 0 ? EVP_sha1() : + strcmp(mode, "good384") == 0 ? EVP_sha384() : + strcmp(mode, "good512") == 0 ? EVP_sha512() : EVP_sha256())); + query_size = i2d_TS_REQ(req, &query); + assert(query_size > 0); + body = BIO_new_mem_buf(query, query_size); + assert(body && (response = TS_RESP_create_response(ts_ctx, body))); + response_size = i2d_TS_RESP(response, &der); + assert(response_size > 0); + if (strcmp(mode, "signature") == 0) + der[response_size - 1] ^= 1; + if (strcmp(mode, "hold") == 0) { + struct timespec delay = { 0, 10000000 }; + int tries = 0; + + save(argv[1], "holding", "", 0); + snprintf(path, sizeof(path), "%s/release", argv[1]); + while (access(path, F_OK) != 0 && tries++ < 500) + nanosleep(&delay, NULL); + } + if (strcmp(mode, "slow") == 0) + sleep(2); + if (strcmp(mode, "http") == 0) + status = 503; + if (strcmp(mode, "malformed") == 0) + memset(der, 'x', (size_t)response_size); + if (strcmp(mode, "oversize") == 0) { + snprintf(header, sizeof(header), "HTTP/1.1 200 OK\r\nContent-Length: 70000\r\nConnection: close\r\n\r\n"); + SSL_write(ssl, header, (int)strlen(header)); + memset(input, 'x', sizeof(input)); + for (n = 0; n < 9; n++) + if (SSL_write(ssl, input, sizeof(input)) <= 0) break; + } else { + snprintf(header, sizeof(header), "HTTP/1.1 %d Test\r\nContent-Type: application/timestamp-reply\r\nContent-Length: %d\r\nConnection: close\r\n\r\n", status, response_size); + SSL_write(ssl, header, (int)strlen(header)); + SSL_write(ssl, der, response_size); + } + save(argv[1], "response.der", der, (size_t)response_size); + OPENSSL_free(der); + OPENSSL_free(query); + TS_RESP_free(response); + TS_REQ_free(req); + BIO_free(body); +closed: + SSL_free(ssl); + close(fd); + } + return 0; +}
diff --git a/test/timestamp-migration.sh b/test/timestamp-migration.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# Synthetic legacy-schema fixture in a separate, disposable PostgreSQL database. +set -eu +DB=timestamp_upgrade_$$ +T=$(mktemp -d /tmp/timestamp-migration.XXXXXX) +cleanup() { + su-exec postgres dropdb --if-exists "$DB" > /dev/null + rm -rf "$T" +} +trap cleanup 0 +trap 'exit 1' HUP INT TERM +su-exec postgres createdb "$DB" +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d "$DB" "$@"; } +sql -c "CREATE TABLE documents (id uuid PRIMARY KEY DEFAULT gen_random_uuid(),title text,status text,revision integer,final_sha256 char(64),released_at timestamptz); + INSERT INTO documents (title,status,revision,final_sha256,released_at) VALUES + ('Old draft','DRAFT',0,NULL,NULL),('Old pending','PENDING',1,NULL,NULL), + ('Old released','RELEASED',1,repeat('a',64),CURRENT_TIMESTAMP-interval '2 days'); + CREATE TABLE doc_decisions (doc_id uuid REFERENCES documents(id),decision text,decided_at timestamptz); + INSERT INTO doc_decisions SELECT id,'SIGNOFF',released_at FROM documents WHERE status='RELEASED'" > /dev/null +facts() { + sql -c "SELECT md5(string_agg(to_jsonb(d)::text,E'\n' ORDER BY id)) FROM documents d; + SELECT md5(string_agg(to_jsonb(d)::text,E'\n' ORDER BY doc_id)) FROM doc_decisions d" +} +facts > "$T/before" +for repeat in 1 2; do + sql -f /src/sql/migrations/004-detached-timestamps.sql > /dev/null + facts > "$T/after" + cmp "$T/before" "$T/after" + [ "$(sql -c 'SELECT count(*) FROM document_timestamps')" = 0 ] +done +[ "$(sql -c "SELECT has_table_privilege('signetd','document_timestamps','SELECT') AND has_table_privilege('signetd','document_timestamps','INSERT') AND has_table_privilege('signetd','document_timestamps','UPDATE')")" = t ] +echo 'timestamp migration: legacy documents/decisions preserved, no historical backfill, worker grants and repeat application passed'
diff --git a/test/upload-browser.mjs b/test/upload-browser.mjs @@ -0,0 +1,84 @@ +// Development-only browser transport regression; use a disposable dev stack. +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdir, writeFile } 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-upload-browser'; +await mkdir(output, { recursive: true }); + +// Valid two-page PDF with a large unused stream, exactly the accepted file limit. +function pdf(padding) { + const text = (s) => `BT /F1 18 Tf 72 770 Td (${s}) Tj ET`; + const a = text('Upload contract - page 1'), b = text('Upload contract - page 2'); + const page = (n) => `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 7 0 R >> >> /Contents ${n} 0 R >>`; + const objects = ['<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', page(5), page(6), `<< /Length ${a.length} >>\nstream\n${a}\nendstream`, `<< /Length ${b.length} >>\nstream\n${b}\nendstream`, '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>']; + let head = '%PDF-1.4\n', offsets = []; + for (const [i, object] of objects.entries()) { offsets.push(head.length); head += `${i + 1} 0 obj\n${object}\nendobj\n`; } + offsets.push(head.length); + head += `8 0 obj\n<< /Length ${padding} >>\nstream\n`; + const end = '\nendstream\nendobj\n'; + const xref = head.length + padding + end.length; + const tail = `xref\n0 9\n0000000000 65535 f \n${offsets.map((n) => `${String(n).padStart(10, '0')} 00000 n \n`).join('')}trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + return Buffer.concat([Buffer.from(head), Buffer.alloc(padding), Buffer.from(end + tail)]); +} +const limit = 32 * 1024 * 1024; +let padding = limit - pdf(0).length, bytes = pdf(padding); +while (bytes.length !== limit) { padding += limit - bytes.length; bytes = pdf(padding); } +const fixture = output + '/max.pdf'; +await writeFile(fixture, bytes); +const digest = (value) => createHash('sha256').update(value).digest('hex'); +const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true }); +const errors = []; +try { + const context = await browser.newContext({ viewport: { width: 1200, height: 900 } }); + await context.setExtraHTTPHeaders({ 'Remote-User': 'asha', 'Remote-Groups': 'clerks', 'X-Requested-With': 'signet' }); + const page = await context.newPage(); + page.on('pageerror', (e) => errors.push(e.message)); + let release, begun, heldId, held = false; + const gate = new Promise((resolve) => { release = resolve; }); + const started = new Promise((resolve) => { begun = resolve; }); + await page.route('**/api/docs/*/upload', async (route) => { + if (!held) { held = true; heldId = /docs\/([^/]+)\/upload/.exec(route.request().url())[1]; begun(); await gate; } + await route.continue(); + }); + await page.goto(base + '/#/'); + await page.getByRole('button', { name: 'New document', exact: true }).waitFor(); + await page.locator('input[type=file]').setInputFiles(fixture); + await page.getByRole('button', { name: 'New document', exact: true }).click(); + let timer; + try { await Promise.race([started, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('upload gate was not reached')), 30000); })]); } + finally { clearTimeout(timer); } + assert(await page.getByRole('button', { name: 'New document', exact: true }).isDisabled()); + assert(await page.getByRole('progressbar', { name: 'PDF upload progress' }).isVisible()); + assert.equal(await page.locator('progress').evaluate((p) => p.value), 262144); + const partial = await (await context.request.get(base + '/api/docs/' + heldId)).json(); + assert(partial.uploading && !partial.can_edit); + assert.equal((await context.request.get(base + `/api/docs/${heldId}/file/source`)).status(), 404); + await page.screenshot({ path: output + '/progress.png' }); + release(); + await page.waitForURL('**/#/doc/' + heldId, { timeout: 90000 }); + await page.waitForFunction(() => document.querySelectorAll('.page img').length === 2 && [...document.querySelectorAll('.page img')].every((i) => i.complete && i.naturalWidth)); + const source = await context.request.get(base + `/api/docs/${heldId}/file/source`); + assert.equal(digest(await source.body()), digest(bytes)); + await page.screenshot({ path: output + '/complete.png' }); + // A non-retryable chunk failure exposes only the safe incomplete-draft view. + let failedId; + await page.unroute('**/api/docs/*/upload'); + await page.route('**/api/docs/*/upload', async (route) => { + failedId = /docs\/([^/]+)\/upload/.exec(route.request().url())[1]; + await route.fulfill({ status: 409, contentType: 'application/json', body: '{"error":"fixture chunk conflict"}' }); + }); + await page.goto(base + '/#/'); + await page.getByRole('button', { name: 'New document', exact: true }).waitFor(); + await page.locator('input[type=file]').setInputFiles(fixture); + await page.getByRole('button', { name: 'New document', exact: true }).click(); + await page.getByRole('heading', { name: 'Upload incomplete', exact: true }).waitFor(); + assert.equal(await page.locator('.page').count(), 0); + await page.screenshot({ path: output + '/incomplete.png' }); + await page.getByRole('button', { name: 'Delete incomplete draft', exact: true }).click(); + await page.getByRole('button', { name: 'New document', exact: true }).waitFor(); + assert.equal((await context.request.get(base + '/api/docs/' + failedId)).status(), 404); + assert.deepEqual(errors, []); + console.log(JSON.stringify({ result: 'passed', max_bytes: bytes.length, source_sha256: digest(bytes), id: heldId, two_pages: true, incomplete_delete: true })); +} finally { await browser.close(); }
diff --git a/test/upload-client.mjs b/test/upload-client.mjs @@ -0,0 +1,54 @@ +// Development-only contract for the real browser transport helper. +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import vm from 'node:vm'; + +const source = await fs.readFile(new URL('../www/app.js', import.meta.url), 'utf8'); +const helper = source.slice(source.indexOf('async function uploadPdf('), source.indexOf('\nconst fmtTime')); +const chunk = 256 * 1024; +const file = (size) => ({ size, slice: (start, end) => new Blob([new Uint8Array(Math.min(end, size) - start)]) }); +const load = (api) => vm.runInNewContext(helper + '\nuploadPdf', { api }); +let calls = [], progress = []; +let upload = load(async (path, { fields }) => { + calls.push({ path, offset: fields.offset, size: fields.file.size }); + return path === '/docs' ? { id: 'draft', upload_offset: fields.file.size, upload_total: 32 * 1024 * 1024 } : + { upload_offset: fields.offset + fields.file.size, upload_total: 32 * 1024 * 1024 }; +}); +assert.equal((await upload(file(32 * 1024 * 1024), (n) => progress.push(n))).id, 'draft'); +assert.equal(calls.length, 128); +assert(calls.every((c) => c.size <= chunk)); +assert.equal(progress.at(-1), 32 * 1024 * 1024); +assert.equal(calls[1].offset, chunk); +assert.equal(calls.at(-1).offset, 127 * chunk); +let attempted = 0; +upload = load(async () => { attempted++; }); +await assert.rejects(upload(file(32 * 1024 * 1024 + 1), () => {}), /32 MiB/); +await assert.rejects(upload(file(5), () => {}), /32 MiB/); +assert.equal(attempted, 0); +// Only an identified chunk is retried, with exactly the same body and offset. +let retryFields, retries = 0; +upload = load(async (path, { fields }) => { + if (path === '/docs') return { id: 'retry', upload_offset: chunk, upload_total: chunk + 7 }; + if (retries++ === 0) { retryFields = fields; throw new Error('network interrupted after commit'); } + assert.equal(fields, retryFields); + assert.equal(fields.offset, chunk); + assert.equal(fields.file.size, 7); + return { upload_offset: chunk + 7, upload_total: chunk + 7 }; +}); +assert.equal((await upload(file(chunk + 7), () => {})).id, 'retry'); +assert.equal(retries, 2); +let conflicts = 0; +upload = load(async (path) => { + if (path === '/docs') return { id: 'conflict', upload_offset: chunk, upload_total: chunk + 1 }; + conflicts++; + const err = new Error('conflict'); err.status = 409; throw err; +}); +await assert.rejects(upload(file(chunk + 1), () => {}), (e) => e.status === 409 && e.docId === 'conflict'); +assert.equal(conflicts, 1); +upload = load(async (path) => path === '/docs' ? { id: 'stale', upload_offset: chunk, upload_total: chunk + 1 } : { upload_offset: chunk, upload_total: chunk + 1 }); +await assert.rejects(upload(file(chunk + 1), () => {}), (e) => e.docId === 'stale' && /progress/.test(e.message)); +let creations = 0; +upload = load(async () => { creations++; throw new Error('unknown creation result'); }); +await assert.rejects(upload(file(100), () => {}), /unknown creation/); +assert.equal(creations, 1); +console.log('upload client: exact 32 MiB, bounded slices, tail, exact retry, no conflict/creation retry and stale progress passed');
diff --git a/test/upload-contract.sh b/test/upload-contract.sh @@ -0,0 +1,92 @@ +#!/bin/sh +# Destructive fixture contracts: disposable dev stack only. +set -eu +B=http://localhost:8080 +T=$(mktemp -d /tmp/upload-contract.XXXXXX) +FAILER=upload_commit_fail_$$ +cleanup() { + su-exec postgres psql -X -q -d signet -c "DROP TRIGGER IF EXISTS $FAILER ON documents; DROP FUNCTION IF EXISTS $FAILER()" >/dev/null 2>&1 || true + rm -rf "$T" +} +trap cleanup EXIT +fail() { echo "FAIL - $*" >&2; exit 1; } +request() { + want=$1; user=$2; groups=$3; shift 3 + got=$(curl --max-time 20 -sS -o "$T/response" -w '%{http_code}' -H "Remote-User: $user" -H "Remote-Groups: $groups" -H 'X-Requested-With: signet' "$@") + [ "$got" = "$want" ] || fail "HTTP $got expected $want" +} +post() { want=$1; shift; request "$want" asha clerks "$@"; } +dd if=/dev/zero of="$T/first" bs=262144 count=1 2>/dev/null +printf '%%PDF-1.4\n' | dd of="$T/first" conv=notrunc 2>/dev/null +dd if=/dev/zero of="$T/last" bs=262144 count=1 2>/dev/null +post 201 -F total_size=524288 -F "file=@$T/first" "$B/api/docs" +ID=$(jq -er .id "$T/response") +jq -e '.upload_offset==262144 and .upload_total==524288' "$T/response" >/dev/null || fail 'bounded upload initial offset missing' +request 200 asha clerks "$B/api/docs/$ID" +jq -e '.uploading and (.can_edit|not)' "$T/response" >/dev/null || fail 'partial source is editable' +request 404 asha clerks "$B/api/docs/$ID/file/source" +request 404 admin signet-admins "$B/api/docs/$ID/file/source" +request 404 manager management "$B/api/docs/$ID" +post 404 -F "doc_id=$ID" -F name=Incomplete "$B/api/templates" +J='{"title":"Chunked upload","org_code":"UPLOAD20","layout":{"reference_width":1000,"reference_height":1414,"imprints":[]},"route":{"parties":[{"name":"Check","signer":"manager"}]}}' +post 409 --form-string "json=$J" "$B/api/docs/$ID/save" +# Force otherwise-submittable metadata to independently test the submit gate. +su-exec postgres psql -X -q -v ON_ERROR_STOP=1 -d signet -c "UPDATE documents SET title='Chunked upload',org_code='UPLOAD20',layout_json='{\"reference_width\":1000,\"reference_height\":1414,\"imprints\":[]}',route_json='{\"parties\":[{\"name\":\"Check\",\"signer\":\"manager\"}]}' WHERE id='$ID'" >/dev/null +post 409 -d '' "$B/api/docs/$ID/submit" +jq -e '.error=="document is not submittable by you"' "$T/response" >/dev/null || fail 'submit rejected for a reason other than readiness' +request 409 other clerks -F offset=262144 -F "file=@$T/last" "$B/api/docs/$ID/upload" +request 403 manager management -F offset=262144 -F "file=@$T/last" "$B/api/docs/$ID/upload" +post 409 -F offset=262145 -F "file=@$T/last" "$B/api/docs/$ID/upload" +post 400 -F offset=-1 -F "file=@$T/last" "$B/api/docs/$ID/upload" +post 400 -F offset=NaN -F "file=@$T/last" "$B/api/docs/$ID/upload" +cp "$T/first" "$T/overchunk"; printf x >> "$T/overchunk" +post 400 -F total_size=524288 -F "file=@$T/overchunk" "$B/api/docs" +post 400 -F offset=262144 -F "file=@$T/overchunk" "$B/api/docs/$ID/upload" +# Prefix retries are idempotent but cannot change acknowledged bytes. +post 200 -F offset=0 -F "file=@$T/first" "$B/api/docs/$ID/upload" +post 409 -F offset=0 -F "file=@$T/last" "$B/api/docs/$ID/upload" +# Simulate uncommitted suffix bytes and a failed commit AFTER final publication. +printf junk >> "/var/lib/signet/docs/$ID/source.part" +su-exec postgres psql -X -q -v ON_ERROR_STOP=1 -d signet -c "CREATE FUNCTION $FAILER() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN IF NEW.id='$ID'::uuid AND NEW.source_received=NEW.source_total THEN RAISE EXCEPTION 'upload commit fixture'; END IF; RETURN NEW; END \$\$; CREATE CONSTRAINT TRIGGER $FAILER AFTER UPDATE ON documents DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION $FAILER()" >/dev/null +post 503 -F offset=262144 -F "file=@$T/last" "$B/api/docs/$ID/upload" +[ -f "/var/lib/signet/docs/$ID/source.pdf" ] || fail 'fixture did not reach final publication' +request 404 asha clerks "$B/api/docs/$ID/file/source" +request 404 admin signet-admins "$B/api/docs/$ID/file/source" +request 200 asha clerks "$B/api/docs/$ID" +jq -e '.uploading and .upload_offset==262144' "$T/response" >/dev/null || fail 'failed commit advanced offset' +su-exec postgres psql -X -q -v ON_ERROR_STOP=1 -d signet -c "DROP TRIGGER $FAILER ON documents; DROP FUNCTION $FAILER()" >/dev/null +# Two concurrent retries serialize: exactly one append, both acknowledge it. +PIDS= +for n in 1 2; do + ( + code=$(curl --max-time 20 -sS -o "$T/concurrent.$n" -w '%{http_code}' -H 'Remote-User: asha' -H 'Remote-Groups: clerks' -H 'X-Requested-With: signet' -F offset=262144 -F "file=@$T/last" "$B/api/docs/$ID/upload") + [ "$code" = 200 ] && jq -e '.upload_offset==524288 and .upload_total==524288' "$T/concurrent.$n" >/dev/null + ) & PIDS="$PIDS $!" +done +for p in $PIDS; do wait "$p" || fail 'concurrent chunk retry'; done +cp "$T/concurrent.1" "$T/response" +jq -e '.upload_offset==524288 and .upload_total==524288' "$T/response" >/dev/null || fail 'last chunk offset' +post 200 -F offset=262144 -F "file=@$T/last" "$B/api/docs/$ID/upload" +post 409 -F offset=0 -F "file=@$T/last" "$B/api/docs/$ID/upload" +request 200 asha clerks "$B/api/docs/$ID/file/source" +{ dd if="$T/first" bs=262144 count=1 2>/dev/null; dd if="$T/last" bs=262144 count=1 2>/dev/null; } > "$T/expected" +cmp "$T/expected" "$T/response" || fail 'assembled source bytes changed' +request 200 asha clerks "$B/api/docs/$ID" +jq -e '(.uploading|not) and .can_edit and .revision==0 and .serial==null' "$T/response" >/dev/null || fail 'completed source state' +post 200 --form-string "json=$J" "$B/api/docs/$ID/save" +# Existing small multipart clients remain supported, but cannot mutate source. +post 201 -F file=@/src/test/fixtures/letter.pdf "$B/api/docs" +SMALL=$(jq -er .id "$T/response") +post 409 -F offset=0 -F "file=@$T/first" "$B/api/docs/$SMALL/upload" +# Limit malicious/unknown CGI routes before kcgi, not just in the upload handler. +dd if=/dev/zero of="$T/oversize" bs=1048576 count=2 2>/dev/null +for path in api/docs apiBAD pim-api/attrs pim-apiBAD '%61pi/docs' 'api%2Fdocs' 'dam/../api/docs' '/api/docs'; do + post 413 --path-as-is -F "file=@$T/oversize" "$B/$path" +done +post 400 -F total_size=33554433 -F "file=@$T/first" "$B/api/docs" +# Cancelling an incomplete draft removes both the row and partial file. +post 201 -F total_size=524288 -F "file=@$T/first" "$B/api/docs" +CANCEL=$(jq -er .id "$T/response") +post 200 -d '' "$B/api/docs/$CANCEL/delete" +[ ! -e "/var/lib/signet/docs/$CANCEL" ] || fail 'cancel retained partial file' +echo 'upload contract: ownership, gates, replay, byte assembly, cancellation and pre-parser caps passed'
diff --git a/test/upload-migration.sh b/test/upload-migration.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Isolated legacy-schema fixture; never changes the running application database. +set -eu +DB=upload_upgrade_$$ +T=$(mktemp -d /tmp/upload-migration.XXXXXX) +cleanup() { su-exec postgres dropdb --if-exists "$DB" >/dev/null; rm -rf "$T"; } +trap cleanup EXIT +su-exec postgres createdb "$DB" +sql() { su-exec postgres psql -X -qAt -v ON_ERROR_STOP=1 -d "$DB" "$@"; } +sql -c "CREATE TABLE documents (id uuid PRIMARY KEY DEFAULT gen_random_uuid(),title text NOT NULL,status text NOT NULL,layout_json jsonb NOT NULL); INSERT INTO documents (title,status,layout_json) VALUES ('Old draft','DRAFT','{}'),('Old pending','PENDING','{\"imprints\":[]}'),('Old released','RELEASED','{}')" >/dev/null +facts() { sql -c "SELECT md5(string_agg((to_jsonb(d)-'source_total'-'source_received')::text,E'\\n' ORDER BY id)) FROM documents d"; } +facts > "$T/before" +for n in 1 2; do + sql -f /src/sql/migrations/003-bounded-pdf-uploads.sql >/dev/null + facts > "$T/after" + cmp "$T/before" "$T/after" +done +[ "$(sql -c 'SELECT count(*) FROM documents WHERE source_total IS NULL AND source_received IS NULL')" = 3 ] +if sql -c 'UPDATE documents SET source_total=524288' > "$T/rejected" 2>&1; then echo 'FAIL - partial NULL counter accepted' >&2; exit 1; fi +if sql -c 'UPDATE documents SET source_total=33554433,source_received=1' > "$T/rejected" 2>&1; then echo 'FAIL - oversized total accepted' >&2; exit 1; fi +if sql -c 'UPDATE documents SET source_total=6,source_received=7' > "$T/rejected" 2>&1; then echo 'FAIL - received beyond total accepted' >&2; exit 1; fi +echo 'upload migration: old fields/NULL source meaning preserved; repeat apply and constraints passed'
diff --git a/todo.txt b/todo.txt @@ -7,4 +7,5 @@ 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 Verify forwarded-identity boundary, DAM policy and native Alpine deployment +ops +dam +api +worker +test status:needs-info id:14 blockedby:10,11,12,13 @before-production @owner-question spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-14.md +2026-11-10 Verify forwarded-identity boundary, DAM policy and native Alpine deployment +ops +dam +api +worker +test status:needs-info id:14 blockedby:10,11,12,13,19,20,21,22 @before-production @owner-question spec:.scratch/roadmap/spec.md note:.scratch/roadmap/ticket-14.md +(A) 2026-11-14 Finish aggregate parser/image/font/render budgets and native acceptance;retained-request mixed case dev-verified source-only, active-parser/other/native gates open +api +worker +ops +test status:ready-for-agent id:20 note:.scratch/parser-window.md
diff --git a/www/app.js b/www/app.js @@ -83,6 +83,32 @@ async function api(path, { method = 'GET', fields, raw } = {}) { return data; } +async function uploadPdf(file, progress) { + const chunkSize = 256 * 1024; + if (file.size < 6 || file.size > 32 * 1024 * 1024) throw new Error('Choose a PDF up to 32 MiB'); + let id; + try { + let result = await api('/docs', { method: 'POST', fields: { total_size: file.size, file: file.slice(0, chunkSize) } }); + id = result.id; + let offset = result.upload_offset; + if (!id || offset !== Math.min(chunkSize, file.size) || result.upload_total !== file.size) throw new Error('Invalid upload response'); + progress(offset, file.size); + while (offset < file.size) { + const fields = { offset, file: file.slice(offset, offset + chunkSize) }; + try { result = await api(`/docs/${id}/upload`, { method: 'POST', fields }); } + catch (e) { + if (e.status && e.status < 500) throw e; + // Exact chunk retries cannot duplicate or replace acknowledged bytes. + result = await api(`/docs/${id}/upload`, { method: 'POST', fields }); + } + if (result.upload_offset !== Math.min(offset + chunkSize, file.size) || result.upload_total !== file.size) throw new Error('Invalid upload progress'); + offset = result.upload_offset; + progress(offset, file.size); + } + return { id }; + } catch (e) { e.docId = id; throw e; } +} + const fmtTime = (s) => (s ? new Date(s).toLocaleString() : ''); /* strftime subset shared with the server's date imprints and series patterns */ @@ -269,9 +295,15 @@ function syncOverlay(page) { }); } +function signingFacsimile() { + const key = document.getElementById('signing-facsimile')?.value; + return app.me.facsimiles.find((f) => f.id === key) || app.me.facsimile; +} + function constrainPlacement(area, bounds, resizing) { const zone = [...area.closest('.page').querySelectorAll('area:not([data-placement])')].find((a) => a.dataset.type === 'signature_zone' && a.dataset.party === area.dataset.party); - const z = bboxOf(zone), ratio = app.me.facsimile.width / app.me.facsimile.height; + const facsimile = signingFacsimile(); + const z = bboxOf(zone), ratio = facsimile.width / facsimile.height; let [x, y, x2, y2] = bounds, w = x2 - x, height = y2 - y; if (resizing) { w = Math.min(z[2] - x, (z[3] - y) * ratio, Math.max(+zone.dataset.min_w, +zone.dataset.min_h * ratio, w)); @@ -286,14 +318,18 @@ function setupPlacement() { const party = doc.route.parties[doc.current_party - 1]; const zone = [...document.querySelectorAll('area[data-type="signature_zone"]')].find((a) => a.dataset.party === party.name); if (!zone) return; + document.querySelectorAll('area[data-placement]').forEach((area) => area.remove()); + document.getElementById('placement-fit-error')?.remove(); + selected = null; const page = zone.closest('.page'), z = bboxOf(zone); - const ratio = app.me.facsimile.width / app.me.facsimile.height; + const facsimile = signingFacsimile(); + const ratio = facsimile.width / facsimile.height; let w = z[2] - z[0], height = w / ratio; if (height > z[3] - z[1]) { height = z[3] - z[1]; w = height * ratio; } const x = z[0] + (z[2] - z[0] - w) / 2, y = z[1] + (z[3] - z[1] - height) / 2; addArea(page, { type: 'signature_zone', party: party.name, placement: true, coords: [x, y, x + w, y + height] }); if (w < +zone.dataset.min_w || height < +zone.dataset.min_h) { - document.querySelector('.side').append(h('p', { class: 'notice error' }, 'Your facsimile cannot fit this zone at its minimum size. Request a correction to enlarge the zone.')); + document.querySelector('.side').append(h('p', { id: 'placement-fit-error', class: 'notice error' }, 'This facsimile cannot fit the zone at its minimum size. Choose another signature or request a correction to enlarge the zone.')); } syncOverlay(page); } @@ -322,7 +358,8 @@ function startDrag(e, area, box, page) { } if (area.dataset.placement) { if (resizing) { - const ratio = app.me.facsimile.width / app.me.facsimile.height; + const facsimile = signingFacsimile(); + const ratio = facsimile.width / facsimile.height; x2 = x1 + start[2] - start[0] + (Math.abs(dx) >= Math.abs(dy * ratio) ? dx : dy * ratio); } constrainPlacement(area, [x1, y1, x2, y2], resizing); @@ -585,6 +622,14 @@ async function showDoc(id) { view.replaceChildren(h('p', { class: 'notice error' }, e.message)); return; } + if (doc.uploading) { + const remove = doc.drafter_user === app.me.user && app.me.roles.drafter ? h('button', { class: 'danger', onclick: () => act(async () => { + await api(`/docs/${id}/delete`, { method: 'POST' }); location.hash = '#/'; + }, 'Incomplete draft deleted', false) }, 'Delete incomplete draft') : null; + view.replaceChildren(h('div', { class: 'card' }, h('h1', {}, 'Upload incomplete'), + h('p', {}, 'This draft cannot be edited or submitted until its PDF upload is complete. Delete the incomplete draft and upload the PDF again.'), remove)); + return; + } if (doc.can_decide) app.me = await api('/me'); doc.mode = doc.can_edit ? 'edit' : 'preview'; const pending = ['PENDING'].includes(doc.status); @@ -650,9 +695,30 @@ async function showDoc(id) { h('label', { class: 'row' }, h('input', { type: 'checkbox', checked: true, style: 'flex:0;width:auto', onchange: (e) => document.querySelector('.workspace').classList.toggle('hide-overlays', !e.target.checked) }), 'Show imprint overlays'), h('h2', {}, 'Document'), h('p', {}, h('span', { class: 'mono' }, doc.serial || '(no serial)'), h('br'), `Prepared by ${doc.drafter_user}`, h('br'), `Submitted ${fmtTime(doc.submitted_at)} · revision ${doc.revision}`), - doc.status === 'RELEASED' ? h('p', {}, `Released ${fmtTime(doc.released_at)}`, h('br'), h('span', { class: 'mono' }, 'sha256 ' + doc.final_sha256), h('br'), + doc.status === 'RELEASED' ? h('p', {}, `Signed at: ${fmtTime(doc.signed_at)} (Signet server time)`, h('br'), + `Released ${fmtTime(doc.released_at)}`, h('br'), h('span', { class: 'mono' }, 'sha256 ' + doc.final_sha256), h('br'), h('button', { class: 'primary', onclick: () => act(async () => { const buf = await api(`/docs/${id}/file/final`, { raw: true }); window.open(URL.createObjectURL(new Blob([buf], { type: 'application/pdf' }))); }, null, false) }, 'Open print copy (PDF)')) : null, h('h2', {}, 'Signing route'), routeEditor(doc.route, false)); + if (doc.status === 'RELEASED') { + const timestampText = doc.timestamp_status === 'timestamped' + ? `Externally timestamped at: ${fmtTime(doc.timestamped_at)} (timestamp authority)` + : doc.timestamp_status === 'pending' ? 'External timestamp pending' + : doc.timestamp_status === 'unavailable' ? 'External timestamp unavailable' : 'External timestamp not requested'; + side.append(h('h2', {}, 'External timestamp'), h('p', {}, timestampText)); + if (doc.timestamp_status === 'pending') side.append(h('button', { + onclick: () => act(() => showDoc(id), null, false), + }, 'Refresh timestamp status')); + if (doc.timestamp_status === 'timestamped') side.append( + h('p', {}, 'Confirms that this released PDF existed by the timestamp authority’s time; it does not independently verify the earlier sign-off time.'), + h('button', { onclick: () => act(async () => { + const buf = await api(`/docs/${id}/file/timestamp`, { raw: true }); + const link = h('a', { href: URL.createObjectURL(new Blob([buf], { type: 'application/timestamp-reply' })), download: 'timestamp.tsr' }); + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(link.href), 1000); + }, null, false) }, 'Download timestamp evidence (.tsr)')); + } if (doc.can_decide) { const comment = h('textarea', { rows: 3, placeholder: 'Comment (required unless signing off)' }); const currentParty = doc.current_party > 0 && doc.route.parties ? doc.route.parties[doc.current_party - 1] : null; @@ -660,52 +726,7 @@ async function showDoc(id) { const needsEnrolment = hasZone && !app.me.enrolled; if (needsEnrolment) { - /* Show enrolment dialog */ - const canvas = h('canvas', { width: 400, height: 200, class: 'enrol-canvas' }); - const fileInput = h('input', { type: 'file', accept: 'image/png', style: 'margin: 1rem 0' }); - let isDrawing = false; - let ctx = canvas.getContext('2d'); - ctx.fillStyle = 'transparent'; - ctx.fillRect(0, 0, canvas.width, canvas.height); - ctx.strokeStyle = '#000'; - ctx.lineWidth = 2; - - const point = (e) => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * canvas.width / r.width, (e.clientY - r.top) * canvas.height / r.height]; }; - const drawStart = (e) => { isDrawing = true; canvas.setPointerCapture(e.pointerId); ctx.beginPath(); ctx.moveTo(...point(e)); }; - const drawMove = (e) => { if (isDrawing) { ctx.lineTo(...point(e)); ctx.stroke(); } }; - const drawEnd = () => { isDrawing = false; }; - canvas.addEventListener('pointerdown', drawStart); - canvas.addEventListener('pointermove', drawMove); - canvas.addEventListener('pointerup', drawEnd); - canvas.addEventListener('pointercancel', drawEnd); - - const enrol = async () => { - let blob; - if (fileInput.files[0]) { - blob = fileInput.files[0]; - } else { - blob = await new Promise((res) => canvas.toBlob(res, 'image/png')); - } - await api('/me/facsimile', { method: 'POST', fields: { file: blob } }); - toast('Signature enrolled. Waiting for activation…'); - /* Poll /me until enrolled */ - for (let i = 0; i < 30; i++) { - await new Promise((r) => setTimeout(r, 500)); - const me = await api('/me'); - if (me.enrolled) { - toast('Ready to sign!'); - app.me = me; - await showDoc(id); - return; - } - } - throw new Error('Enrolment timeout'); - }; - - side.append(h('h2', {}, 'Enrol your signature'), - h('p', {}, 'Draw your signature in the box below or upload a PNG file'), - canvas, fileInput, - h('div', { class: 'actions' }, h('button', { class: 'primary', onclick: () => act(enrol, null, false) }, 'Enrol signature'))); + side.append(h('h2', {}, 'Enrol your signature'), enrolmentForm(() => showDoc(id))); } else { /* Show decision UI */ const placementInput = hasZone ? h('input', { type: 'hidden', id: 'f-placement', value: '' }) : null; @@ -716,10 +737,15 @@ async function showDoc(id) { if (!area) throw new Error('Placement required for signature zones'); const img = area.closest('.page').querySelector('img'); fields.placement = JSON.stringify({ page: +area.closest('.page').dataset.page, coords: getCoords(area), ref_w: img.naturalWidth, ref_h: img.naturalHeight }); + fields.facsimile_id = signingFacsimile().id; } return api(`/docs/${id}/decide`, { method: 'POST', fields }); }, 'Recorded'); side.append(h('h2', {}, 'Your decision'), comment); + if (hasZone) side.append(h('label', { for: 'signing-facsimile' }, 'Signature to use'), + selectEl(app.me.facsimiles.filter((f) => f.enrolled).map((f) => [f.id, f.label + (f.is_default ? ' (default)' : '')]), + app.me.facsimile.id, () => setupPlacement(), { id: 'signing-facsimile' }), + h('a', { href: '#/signatures' }, 'Manage my signatures')); if (placementInput) side.append(h('p', { class: 'notice' }, 'Position your facsimile inside the signature zone. Drag the placement or use arrow keys; Shift and arrows resize.')); if (placementInput) side.append(placementInput); side.append(h('div', { class: 'actions' }, @@ -742,6 +768,71 @@ async function showDoc(id) { } } +/* ---------- private signature collection (metadata only) ---------- */ + +function enrolmentForm(onReady) { + const label = h('input', { id: 'signature-label', maxlength: 80, value: app.me.enrolled ? '' : 'Signature' }); + const file = h('input', { id: 'signature-upload', type: 'file', accept: 'image/png' }); + const canvas = h('canvas', { width: 400, height: 200, class: 'enrol-canvas', 'aria-label': 'Draw signature' }); + const ctx = canvas.getContext('2d'); + let drawing = false, drawn = false; + ctx.strokeStyle = '#000'; ctx.lineWidth = 2; + const point = (e) => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) * canvas.width / r.width, (e.clientY - r.top) * canvas.height / r.height]; }; + canvas.addEventListener('pointerdown', (e) => { drawing = true; canvas.setPointerCapture(e.pointerId); ctx.beginPath(); ctx.moveTo(...point(e)); }); + canvas.addEventListener('pointermove', (e) => { if (drawing) { ctx.lineTo(...point(e)); ctx.stroke(); drawn = true; } }); + canvas.addEventListener('pointerup', () => { drawing = false; }); + canvas.addEventListener('pointercancel', () => { drawing = false; }); + const button = h('button', { class: 'primary', onclick: async () => { + button.disabled = true; + try { + if (!label.value.trim()) throw new Error('Give this signature a label'); + if (!file.files[0] && !drawn) throw new Error('Draw a signature or choose a PNG file'); + const blob = file.files[0] || await new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); + const created = await api('/me/facsimile', { method: 'POST', fields: { label: label.value.trim(), file: blob } }); + toast('Waiting for signature activation…'); + for (let i = 0; i < 30; i++) { + await new Promise((resolve) => setTimeout(resolve, 500)); + if (!button.isConnected) return; + const me = await api('/me'); + const variant = me.facsimiles.find((f) => f.id === created.id); + if (variant?.error) throw new Error(variant.error); + if (variant?.enrolled) { app.me = me; toast('Signature ready'); await onReady(); return; } + } + throw new Error('Activation is still pending; check My signatures before uploading again'); + } catch (e) { toast(e.message, true); } + finally { button.disabled = false; } + } }, 'Enrol signature'); + return h('div', {}, h('p', {}, 'Draw or upload a PNG (max 1 MiB). Originals remain private. Enrolled images cannot be replaced; add a new variant instead.'), + h('label', { for: 'signature-label' }, 'Signature label'), label, canvas, + h('button', { onclick: () => { ctx.clearRect(0, 0, canvas.width, canvas.height); drawn = false; } }, 'Clear drawing'), + h('label', { for: 'signature-upload' }, 'Or upload PNG'), file, + h('div', { class: 'actions' }, button)); +} + +async function showSignatures() { + clearTimeout(pollTimer); + doc = null; + app.me = await api('/me'); + const view = document.getElementById('view'); + if (!app.me.roles.signer) { + view.replaceChildren(h('p', { class: 'notice' }, 'A signer role is required to manage your signatures.')); + return; + } + view.replaceChildren(h('section', { class: 'signature-collection' }, h('h1', {}, 'My signatures'), + h('p', {}, 'Choose a default for future sign-offs. Changing it never alters a recorded decision. Up to 32 ready or pending variants.'), + h('div', { class: 'card' }, app.me.facsimiles.length ? app.me.facsimiles.map((f) => h('div', { class: 'row' }, + h('strong', {}, f.label), h('span', {}, f.error || (!f.enrolled ? 'Awaiting activation' : f.is_default ? 'Default' : 'Ready')), + !f.enrolled && !f.error ? h('button', { 'aria-label': 'Retry activation of ' + f.label, onclick: () => act(async () => { + await api('/me/facsimile/retry', { method: 'POST', fields: { facsimile_id: f.id } }); + await showSignatures(); + }, 'Activation queued', false) }, 'Retry activation') : null, + f.enrolled && !f.is_default ? h('button', { 'aria-label': 'Use ' + f.label + ' as default', onclick: () => act(async () => { + await api('/me/facsimile/default', { method: 'POST', fields: { facsimile_id: f.id } }); + await showSignatures(); + }, 'Default updated', false) }, 'Use as default') : null)) : h('p', {}, 'No signatures enrolled yet.')), + h('h2', {}, 'Add a signature'), h('div', { class: 'card' }, enrolmentForm(showSignatures)))); +} + /* ---------- dashboard ---------- */ async function showDashboard(scope) { @@ -757,21 +848,27 @@ async function showDashboard(scope) { const file = h('input', { type: 'file', accept: 'application/pdf' }); const tpl = selectEl([['', 'or start from a template…'], ...app.templates.map((t) => [t.id, t.name])], '', () => {}); + const progress = h('progress', { hidden: true, max: 1, value: 0, 'aria-label': 'PDF upload progress' }); const create = () => act(async () => { - const fields = tpl.value ? { template_id: tpl.value } : file.files[0] ? { file: file.files[0] } : null; - if (!fields) throw new Error('Choose a PDF or a template first'); - const res = await api('/docs', { method: 'POST', fields }); - location.hash = '#/doc/' + res.id; + if (!tpl.value && !file.files[0]) throw new Error('Choose a PDF or a template first'); + createButton.disabled = file.disabled = tpl.disabled = true; + try { + const res = tpl.value ? await api('/docs', { method: 'POST', fields: { template_id: tpl.value } }) : + await uploadPdf(file.files[0], (offset, total) => { progress.hidden = false; progress.max = total; progress.value = offset; }); + location.hash = '#/doc/' + res.id; + } catch (e) { if (e.docId) location.hash = '#/doc/' + e.docId; throw e; } + finally { createButton.disabled = file.disabled = tpl.disabled = false; progress.hidden = true; } }, null, false); + const createButton = h('button', { class: 'primary', style: 'flex:0 0 auto', onclick: create }, 'New document'); view.replaceChildren( h('h1', {}, 'Documents'), - r.drafter ? h('div', { class: 'card', style: 'margin-bottom:1rem' }, h('div', { class: 'row' }, file, tpl, h('button', { class: 'primary', style: 'flex:0 0 auto', onclick: create }, 'New document'))) : null, + r.drafter ? h('div', { class: 'card', style: 'margin-bottom:1rem' }, h('div', { class: 'row' }, file, tpl, createButton, progress)) : null, h('div', { class: 'tabs', role: 'tablist' }, tabs.map(([k, label]) => h('button', { role: 'tab', 'aria-selected': String(k === scope), onclick: () => showDashboard(k) }, label))), h('div', { class: 'card' }, rows.length ? h('table', {}, h('thead', {}, h('tr', {}, ['Document', 'Status', 'Prepared by', 'Parties', 'Created'].map((t) => h('th', {}, t)))), h('tbody', {}, rows.map((d) => h('tr', { class: 'click', onclick: () => { location.hash = '#/doc/' + d.id; } }, - h('td', {}, d.title || d.serial || 'Untitled draft'), + h('td', {}, d.title || d.serial || (d.uploading ? 'Incomplete upload' : 'Untitled draft')), h('td', {}, h('span', { class: 'status ' + d.status }, d.status.replace(/_/g, ' '))), h('td', {}, d.drafter_user), h('td', {}, d.status === 'DRAFT' ? '' : `${Math.min(d.current_party, d.parties)} / ${d.parties}`), @@ -801,6 +898,7 @@ function route() { const m = location.hash.match(/^#\/doc\/([0-9a-f-]{36})$/); if (m) showDoc(m[1]); else if (location.hash === '#/series') showSeries(); + else if (location.hash === '#/signatures') showSignatures().catch((e) => toast(e.message, true)); else showDashboard(); } @@ -816,6 +914,7 @@ async function boot() { document.getElementById('view').replaceChildren(h('p', { class: 'notice error' }, 'Not signed in: ' + e.message)); return; } + document.getElementById('signature-nav').hidden = !app.me.roles.signer; const who = document.getElementById('whoami'); who.textContent = app.me.user + ' · ' + Object.entries(app.me.roles).filter(([, v]) => v).map(([k]) => k).join(', '); if (localStorage.getItem('signetDevIdentity')) {
diff --git a/www/index.html b/www/index.html @@ -12,6 +12,7 @@ <nav> <a href="#/">Documents</a> <a href="#/series">Series</a> + <a id="signature-nav" href="#/signatures" hidden>My signatures</a> <a href="/pim/">PIM</a> </nav> <span id="whoami"></span> @@ -19,6 +20,6 @@ <main id="view"></main> <div class="toast" role="status" hidden></div> <script src="vendor/pdf.min.js"></script> -<script src="app.js"></script> +<script src="app.js?v=bounded-pdf-1"></script> </body> </html>
diff --git a/www/style.css b/www/style.css @@ -91,6 +91,10 @@ tr.click:hover td { background: #f6f9fc; } .history { font-size: 13px; margin: 0; padding: 0; list-style: none; } .history li { padding: .35rem 0; border-bottom: 1px solid var(--line); } .history .c { color: var(--muted); display: block; } +.signature-collection { height: 100%; overflow-y: auto; padding: 1.2rem; } +.signature-collection > * { max-width: 48rem; } +.signature-collection .row > strong { min-width: 0; overflow-wrap: anywhere; } +.signature-collection .row + .row { margin-top: .5rem; padding-top: .5rem; border-top: 1px solid var(--line); } .enrol-canvas { display: block; max-width: 100%; touch-action: none; border: 1px solid var(--line); margin: 1rem 0; } .actions { display: flex; gap: .4rem; flex-wrap: wrap; margin-top: .8rem; } .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; word-break: break-all; }
: asapien/signet