: asapien/signet

commit 3b5ff3eb128543ebd6e04c7e5e5639f208b65b64
parent ec4858aac617d68e6005c685b28c8de5bba8c417
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Thu, 12 Nov 2026 08:22:07 +0530

Integrate initial runtime metadata guard without claiming native readiness
5 files changed, 73 insertions(+), 15 deletions(-)
M
.scratch/roadmap/ticket-14.md
|
38
++++++++++++++++++++++++++++++++------
M
HANDOFF.md
|
16
++++++++++------
M
README.md
|
4
++++
M
src/signet-api.c
|
17
++++++++++++++---
M
test/snapshot-contract.sh
|
13
+++++++++++++
diff --git a/.scratch/roadmap/ticket-14.md b/.scratch/roadmap/ticket-14.md
@@ -20,6 +20,33 @@ full on2026-11-12. It is a discussion handoff, not approval for customer feature
 - Repository remote and hosted spec/ticket URLs are needed to publish the draft
   PR and use correct closing links. No Git remote/gh currently exists here.
 
+## Local incremental hardening (not production acceptance)
+
+Document-save JSON is now limited to1MiB before yyjson parsing. Submit applies
+that same byte bound to each stored layout/route in PostgreSQL before libpq
+transfers it, so oversized legacy fields cannot reach snapshot cloning. This
+bounds the new clone path, not all HTTP buffering, PIM or placement parsing.
+
+Retained regression in test/snapshot-contract.sh accepts exactly1MiB, rejects
+one extra whitespace byte with400, and rejects legacy layout/route containing
+350,000 multibyte characters (>1MiB) with409 before any snapshot/serial exists.
+The old API accepted the oversized request: /tmp/signet-ticket14-json-red.log.
+
+Fresh image signet-roadmap-guards, container of the same name on :8084:
+
+- /tmp/signet-ticket14-build.log: clean -Wall -Wextra build, no warnings/errors.
+- /tmp/signet-ticket14-e2e.log and /tmp/signet-ticket14-render.log: all passed,
+  including identity, snapshot mutation/recovery and the new byte-boundary cases.
+- /tmp/signet-ticket14-browser.log and /tmp/signet-ticket14-progress.log: signing
+  and polling/failure/retry regressions pass. Rendering maths/assets unchanged.
+- /tmp/signet-ticket14-rss-summary.txt: approximately32,135KB maximum aggregate
+  app RSS across730samples. Same UID/process selection as ticket12; ps unit
+  rounding and sampling can miss short peaks. Excludes PostgreSQL/Redis/client.
+  This fixture run is not native, concurrent-upload or hard peak certification.
+- Image ID in /tmp/signet-ticket14-image.txt; browser evidence in
+  /tmp/signet-ticket14-{browser,progress}/. Host is Darwin, Git remote absent and
+  gh unavailable. No proxy/native production checks or publication were performed.
+
 ## Unfinished technical acceptance (must not be checked off)
 
 - Real trusted-header overwrite/spoof prevention, missing identity, authenticated

@@ -29,12 +56,11 @@ full on2026-11-12. It is a discussion handoff, not approval for customer feature
   children/deadlines and timeout/crash recovery. run_cmd currently has no child
   timeout/resource limits. The new streamed frozen-input cap alone does not bound
   decoded image/font memory, upload concurrency or total child RSS.
-- Bound/prune JSON metadata before parsing/cloning/serializing. Save currently
-  accepts arbitrary unused JSON members up to the buffered request limit;
-  snapshot_create clones the layout, so oversized ignored/client-value fields can
-  amplify heap use. The referenced-text/asset caps are not a whole-JSON cap.
-  This needs local resource hardening as well as native measurement; owner/proxy
-  questions are not the only unfinished work.
+- Audit other metadata/PIM/placement parse paths and aggregate buffering; the
+  save/submit clone guard above is not a whole-runtime memory bound. Oversized
+  ignored/client-value fields originally amplified snapshot heap use despite the
+  referenced-text/asset caps. Local resource work is still necessary as well as
+  native measurement; owner/proxy questions are not the only unfinished work.
 - Measure complete application cohort including qpdf/pdfinfo, incremental shared
   PostgreSQL/Redis impact, CPU/I/O and recovery, on target-class native Alpine.
   Sampling sequential synthetic fixtures is not a hard peak bound.
diff --git a/HANDOFF.md b/HANDOFF.md
@@ -306,8 +306,12 @@ The implementation scopes and acceptance criteria are in
 4. **Ticket 13 completed:** fail-closed identity handling, config-only role/header
    mapping and both-API tests pass without an authentication-server dependency.
    See `.scratch/roadmap/ticket-13.md`. Proxy trust remains ticket 14.
-5. **Ticket 14 (production gate):** verify trusted proxy identity enforcement,
-   DAM write policy, OpenRC, permissions, Redis AOF, CSP and RSS on Alpine.
+5. **Ticket14 incomplete, before production:** verify trusted proxy identity,
+   decide DAM writer policy and complete runtime/native Alpine/OpenRC acceptance.
+   First local guard limits save/submit JSON before parse/clone (including legacy
+   multibyte rows); fixture suites/browser pass. This does not bound HTTP upload
+   buffering, other parse paths, decoded images or child lifetime/resources.
+   Owner inputs, remaining work and evidence: `.scratch/roadmap/ticket-14.md`.
    Keep provider-specific auth experiments separate from application work.
 6. Later: font-list validation and document-list pagination/search.
 

@@ -316,10 +320,10 @@ historical completed tickets do not substitute for fresh evidence.
 
 ## 8. Dev environment facts
 
-* Latest isolated roadmap verification: image `signet-roadmap`, container
-  `signet-roadmap-review` on :8082; throw-away DB and explicit test identities.
-  Original ticket11 evidence stack remains on :8080. No production/maa-1 services
-  changed. Fixture RSS samples do not certify native peak resource safety.
+* Latest isolated verification: image/container `signet-roadmap-guards` on :8084;
+  ticket12 stack `signet-roadmap-review` remains on :8082, ticket11 on :8080.
+  Throw-away DBs and explicit identities; no production/maa-1 services changed.
+  Fixture RSS samples do not certify native peak resource safety.
 * Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created
   for this project; image `signet-dev`; a container named `signet` may still
   be running on :8080 with throw-away data. `test/dev-up.sh` initialises the DB
diff --git a/README.md b/README.md
@@ -165,6 +165,10 @@ 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.
+* **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.
 * **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
diff --git a/src/signet-api.c b/src/signet-api.c
@@ -39,6 +39,8 @@
 
 static struct conf cf;
 
+/* Bound parse/clone work independently of the PDF upload limit. */
+#define MAX_JSON_BYTES (1024u * 1024)
 #define PENDING "('PENDING')"
 #define IN_ROUTE(u) "EXISTS (SELECT 1 FROM jsonb_array_elements(d.route_json->'parties') p " \
 	"WHERE p->>'signer' = " u ")"

@@ -455,8 +457,9 @@ h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid
 	char *ltxt = NULL, *rtxt = NULL;
 	PGresult *res;
 
-	if (json == NULL || (doc = yyjson_read(json, strlen(json), 0)) == NULL) {
-		send_err(r, KHTTP_400, "json field missing or malformed");
+	if (json == NULL || strlen(json) > MAX_JSON_BYTES ||
+	    (doc = yyjson_read(json, strlen(json), 0)) == NULL) {
+		send_err(r, KHTTP_400, "json field missing, malformed or over 1 MiB");
 		return;
 	}
 	root = yyjson_doc_get_root(doc);

@@ -522,13 +525,21 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc
 		send_err(r, KHTTP_500, "database error");
 		return;
 	}
-	res = db_q(pg, "SELECT layout_json::text, route_json::text, series_code, "
+	/* Match MAX_JSON_BYTES before transferring legacy JSON into this process. */
+	res = db_q(pg, "SELECT CASE WHEN octet_length(layout_json::text) <= 1024 * 1024 "
+	    "THEN layout_json::text END, "
+	    "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);
 	if (res == NULL || PQntuples(res) != 1) {
 		snprintf(err, sizeof(err), "document is not submittable by you");
 		goto fail;
 	}
+	if (PQgetisnull(res, 0, 0) || PQgetisnull(res, 0, 1)) {
+		snprintf(err, sizeof(err), "layout and route must each fit within 1 MiB");
+		goto fail;
+	}
 	submit_action = strcmp(PQgetvalue(res, 0, 5), "CORRECTION_REQUIRED") == 0
 	    ? "RESUBMITTED" : "SUBMITTED";
 	if (strspn(PQgetvalue(res, 0, 6), " \t\r\n") == strlen(PQgetvalue(res, 0, 6))) {
diff --git a/test/snapshot-contract.sh b/test/snapshot-contract.sh
@@ -83,6 +83,19 @@ LAYOUT=$(jq -nc --arg org "$ORG" --arg series "$SERIES" '{title:"Frozen revision
 PL1='{"page":1,"coords":[120,550,500,700],"ref_w":1000,"ref_h":1414}'
 PL2='{"page":2,"coords":[400,1000,850,1200],"ref_w":1000,"ref_h":1414}'
 new_doc
+# 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"
+printf ' ' >> "$TMP/large-json"
+status 400 --data-urlencode "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
+	status 409 -d '' "$B/api/docs/$ID/submit"
+	save "$LAYOUT" >/dev/null
+done
+[ "$(find "$BASE" -maxdepth 1 -name 'snapshot-*' | wc -l)" = 0 ] || fail 'oversized JSON created a snapshot'
+echo 'ok   - oversized save/legacy layout/route JSON is rejected before snapshot cloning'
 # Invalid assets fail before serial allocation; never follow a symlink out of DAM.
 ln -s /src/test/fixtures/seal.png /var/www/dam/seals/snapshot12-link.png
 redis-cli HSET "$ORG:images" seal seals/snapshot12-link.png >/dev/null