diff --git a/.claude/audits/2026-10-25-rust-r5-6-final-security.md b/.claude/audits/2026-10-25-rust-r5-6-final-security.md new file mode 100644 index 00000000..f83218ef --- /dev/null +++ b/.claude/audits/2026-10-25-rust-r5-6-final-security.md @@ -0,0 +1,127 @@ +# Security audit: R5.6 final switch state (M1 correction) + +- Date: 2026-10-25. Mode: audit, fresh and blind (no prior verdict used). +- Target: worktree `/tmp/claude-1000/-home-bchanot-Documents-faunosteo/3571c861-cd6e-4751-a25e-c26da95beb85/scratchpad/r56final`, + detached at 8e77e37 + `.claude/tasks/plans/r5-6-switch.patch`. The worktree diff is line-identical to the committed + patch at baff882 (index lines aside). No code under `crates/ packages/ apps/ scripts/ supabase/` differs between + 943a25a, 8e77e37 and baff882, so the patch applies to the official code state. +- Contract: `.claude/tasks/contracts/2026-10-25-rust-r5-6-rehearsal.md` S1-S8 and the 2026-10-25 Clarification. +- Scope: the 30 files of the diff (9 Rust sources, Cargo.toml, 7 Rust tests + 2 fixtures, 4 TS tests/helpers, + 2 scripts, package.json, .prettierignore, CLAUDE.md, the 2 switched seed files). + +## Attack on the alias decision + +Every Rust site that decides "same document" was enumerated (grep of `equivalence`, `TRUSTED_ALIASES`, +`TrustedAlias`, `same_document`, `recognises_historical_stamp`, `document_sha256` across `crates/core/src`, +`crates/wasm/src`, `apps/app/src`, `packages/core-wasm/src`). + +| Path | Decision | Result | +|---|---|---| +| `ops.rs:361` `archive.snapshot` → `snapshot_rules.rs:60-68` `build_sheet_snapshot` | alias only through `recognises_historical_stamp` | holds | +| `pdf/write/input.rs:204-210` `assert_exportable` (wasm export session, `export_pdf`, `export_from_envelope`) | strict `sheet_id` + `document_sha256` equality, unchanged from 943a25a | holds | +| `report/rebase.rs:42-46` (reached by `draft.restore`, `archive.import`, `import_pdf`, `restore_copy`) | exact equality (pre-existing) or `recognises_historical_stamp` with same sheet id | holds | +| `archive/read.rs:116-119` `snapshot_matches` | strict equality report vs archived snapshot, unchanged | holds (mixed alias/canonical archive loses its snapshot, tested) | +| `pdf/compare/lines.rs:350-376` report-compare | `recognises_historical_stamp`, both raw values printed through `esc` | holds | +| `session.rs`, `ops.rs`, `facade.rs` (one arm), `crates/wasm` | no own comparison; route to the above | holds | +| app TypeScript | no stamp comparison (only `provider.ts:52` copies the ref) | holds | + +`recognises_historical_stamp` (`loaded.rs:163-171`) requires, in this order: a loader-verified `v1` value, that value +still equal to `reference.document_sha256`, the registry pair (sheet id, stamp as alias, verified value as canonical, +one direction only, `fingerprint.rs:63-75`), and a fresh `document_fingerprint(&self.document)` equal to the verified +value. Because the registry canonical must equal a value recomputed from the current document, the privilege is +granted only when the loaded content hashes to the registered equine canonical (SHA-256 preimage otherwise). A +JS caller building a `SheetHandle` from a hand-made bundle gains nothing unless its document is that content. + +Forging the private state: +- Struct literal and functional update `..base`: impossible outside `loaded.rs` (private `verified_fingerprint`, + `index`, `drawings`; E0451). No other constructor than `from_bundle` (grep: test helpers all go through it). +- `Deserialize`, `Default`, `Serialize`: not derived on `LoadedSheet`. `unsafe_code = "forbid"` workspace-wide + (`Cargo.toml:55`), no transmute. No `Cell`/`RefCell`. +- `Clone`: copies a consistent state; mutating the clone's pub `document` or `reference` is caught by the + recomputation and the `verified == reference` check (tested, `r5_6_switch.rs` `a_mutated_document_or_reference_never_keeps_the_alias`). +- `SheetHandle` (`crates/wasm/src/lib.rs:26-37`) holds the sheet privately; no `&mut` access to it from JS. +- Even a forged `verified_fingerprint` on a v0 sheet would only grant the alias when the content is the canonical + one: a policy deviation from S3, never a content confusion. + +Fingerprint block handling (`loaded.rs:39-57`, `191-210`): absent → v0, unverified, no privilege; explicit `null` → +refused (`present_block`); string, unknown key, missing key → refused (`deny_unknown_fields`, required fields); +convention other than `v1`, non 64-lowercase-hex value, value equal to a registered alias, unregistered alias in the +list, value not recomputed from the document (including a document with integrity errors) → refused at load, +closed `invalid_sheet` kind, detail never rendered (`useSheet.ts:60`). Duplicate JSON key: last wins, a trailing +`null` is refused. A misspelt block key at `ref` level (no `deny_unknown_fields` on `BundledRef`) loads as v0: +fail-closed (less privilege, old reports rebase onto identical content). + +v1 with warnings (`fingerprint.rs:253-256`): errors refuse, warnings do not. This only widens which documents +get a value; it grants no equivalence, and a warning-only document with another content gets another value +(tested, it rebases old reports). + +## Recursion and cost + +- `canonical_json` (`fingerprint.rs:121-193`): containers refused at depth ≥ 128 with `CanonicalError::TooDeep`, + tested at the bound (`sheet_fingerprint.rs:280-292`). Its only non-test caller is `document_fingerprint`, whose + only caller is `loaded.rs` on the loaded sheet's document (the build-time bundle). Attacker data (archives, + drafts, PDFs, rescue copies) never reaches `canonical_json`; archived snapshot finding depth stays capped at 8 + by `assert_snapshot` before shape. The new load-time `validate_sheet_document` + `serde_json::to_value` on the + bundle are bounded by serde_json's parse limit (127 containers). +- Recomputation cost: native release, a test with about 3 fingerprints, 7 loads and 1 import runs in 84-87 ms + against 32 ms for 3 loads with none, so one fingerprint of the 296 KB document is in the low milliseconds. + The recomputation runs only when the stamp already equals the registered alias (short-circuit order, + `loaded.rs:167-170`; identical stamps never pay it), at most once per `archive.snapshot` (once per export, + `export.ts:146`), per import (one candidate, `import.rs:24-30`) or per draft restore, plus one at each v1 + load. Import worker timeout 20 s (`controller.ts:19`). Repeated calls only cost the user's own tab: no DoS. + +## Findings + +No CRITICAL, no HIGH, no new security suppression. + +- [LOW] hardening — `crates/core/src/domain/sheet/fingerprint.rs:63` — `equivalence` is a crate-public function + that answers `TrustedAlias` from the registry alone, with no verified state and no recomputation. Its only + caller today is `recognises_historical_stamp` (`loaded.rs:169`); a future caller (the Supabase sheet provider + of Step 13, a new export path) could reopen the flaw of the previous round. Hint: `pub(crate)` or private to + `loaded`, or a census test that pins its callers. +- [LOW] by design, context — `crates/core/src/pdf/write/input.rs:204-210` — the export session accepts any + self-consistent caller-supplied (report, snapshot) pair: a script in the page can write an archive whose report + and snapshot both carry the alias with a hand-built snapshot. No equivalence is granted there (every reader + re-decides against its loaded sheet), the alias adds nothing a forged canonical stamp could not already do, + and this is the pre-switch behaviour for any stamp. +- [LOW] context, pre-existing — `crates/core/src/domain/report/rebase.rs:43` — the exact-equality branch keeps a + report of another sheet id unrebased when it carries the loaded value; unchanged since R2 (the new alias branch + does check the sheet id). Equal SHA-256 means equal content, so no confusion. +- [LOW] context — `crates/core/tests/r5_6_switch.rs:8` — new `#![allow(clippy::disallowed_methods, + clippy::unwrap_used, clippy::expect_used)]`, test-only, the header 40 existing test files carry; not a + security-tool suppression. +- Out of diff, filtered: guardrails `WARN SB-POLICY-NOT-OWNER` + `supabase/migrations/20261008110000_anatomical_sheets.sql:1177` (`species_select_active`, catalog read + policy), pre-existing. + +Non-security note: `r5_6_switch.rs:133-135` writes `/target/tmp/r5-6/` even when `CARGO_TARGET_DIR` points +elsewhere (git-ignored, `.gitignore:65`). + +## Proof + +- semgrep 1.168.0, `p/security-audit`, `p/secrets`, `p/owasp-top-ten`, `--metrics=off`: 163 rules on the 30 diff + files, 0 results, 0 errors. Caveat: these packs carry few Rust rules; the Rust review above is manual. + `p/*` content is fetched at run time, not frozen by the CLI pin. +- Checklist, 9 checks on the added lines and the tree: hardcoded secret/auth URL (0), SQL by concatenation (0), + unsanitised render/eval (0), sensitive endpoint without authz (n/a, no endpoint in the diff), internal error to + the user (0: `invalid_sheet` detail not rendered), secret/PII in a log (0), tracked `.env` (0, only + `.env.example`), guardrails `--domain api,supabase` (0 FAIL, 1 WARN out of diff, filtered), new suppressions (0 + security; 1 test lint allow, LOW). +- Hermetic tests run in the worktree, `CARGO_TARGET_DIR=/target`, release, `--features cli`: + `r5_6_switch` + `sheet_fingerprint` 25 passed; `pdf_import`, `pdf_compare`, `archive_rules`, `report_rules`, + `sheet_contract` 78 passed. +- Seed check: `draft/document.json` still hashes (bytes) to the registered alias 27c7…, `document.json`, + `horse.svg`, `equine_draft.sql` unchanged; only `sheet-ref.json` and the map's `sheet.documentSha256` changed. +- Nothing edited in either tree except this report; no network beyond the semgrep rule download, no Supabase. + +TOOL: semgrep 1.168.0 — p/security-audit, p/secrets, p/owasp-top-ten +SCOPE: 30 files +BLOCKING: + (none) +REPORTED (non-blocking): + - [LOW] hardening: crate-public registry-only `equivalence` — crates/core/src/domain/sheet/fingerprint.rs:63 + - [LOW] by design: export accepts caller-supplied consistent snapshot — crates/core/src/pdf/write/input.rs:204 + - [LOW] pre-existing: exact-equality rebase branch without sheet id — crates/core/src/domain/report/rebase.rs:43 + - [LOW] test lint allow (crate convention) — crates/core/tests/r5_6_switch.rs:8 +PROOF: semgrep 163 rules on 30 files → 0 findings; checklist 9 checks → 4 findings (LOW), 1 out-of-diff WARN filtered +SECURITY — VERDICT: PASS diff --git a/.claude/audits/2026-10-25-rust-r5-6-final-verify.md b/.claude/audits/2026-10-25-rust-r5-6-final-verify.md new file mode 100644 index 00000000..c099f4df --- /dev/null +++ b/.claude/audits/2026-10-25-rust-r5-6-final-verify.md @@ -0,0 +1,14 @@ +# R5.6 final rehearsal — fresh verifier (Opus), persisted by the orchestrator (verifier is read-only) + +Contract `.claude/tasks/contracts/2026-10-25-rust-r5-6-rehearsal.md` (S1-S8 + 2026-10-25 Clarification); final worktree r56final (8e77e37 + patch at baff882). + +VERIFY — VERDICT: CONFORME (8/8) + +- S1 MET: decision in snapshot_rules.rs build_sheet_snapshot via recognises_historical_stamp (private verified value, reference equality, registry one-way, recompute now); 9 scenarios tested (r5_6_switch 14/14, vitest N-1 2/2, app 2/2); rollback: unpatched build's report-compare reads the re-export, snapshot kept +- S2 MET: input.rs, archive/read.rs, session.rs, ops.rs, crates/wasm, n-1 unchanged vs 943a25a; equality strict +- S3 MET: probe through facade::load_sheet: v0 canonical = no privilege; null/string/{}/array/missing/extra/v0/upper/alias/63-hex/other/forged/self-alias/content-changed/foreign-id refused; warnings-only v1 loads verified +- S4 MET: only the two seed files differ; document.json, horse.svg, equine_draft.sql byte-identical; no oracle/golden/ledger/n-1 in patch; original contexts + post-switch twins +- S5 MET (12-hex prefixes, the tool's style); S6 MET; S7 MET (main tree clean, seed 27c7, patch applies); S8 MET (rust:check rc 0, 1475 passed; check:all 01:53:59 cited) +- Direct-API probe: v1 + old report → 27c7/27c7 exported; v0 canonical → SheetMismatch; mutated document / reference value / reference id → refused; other sheet id → refused; forged stamp → refused; canonical_json 128 OK, 129 TooDeep, 5000 TooDeep without overflow +- Observations: stale comments fingerprint.rs (6, 15, 246-247); RUST.md §11.20 superseded mechanism (superseded by §11.21); null block → invalid_shape in facade (refusal either way) +- FLOOR clean diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 37ecb52d..704848ba 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -362,3 +362,7 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp - M1 in input.rs; equivalence one-way + fingerprint_verified (v1 recomputed at load, sha2 in wasm). Goldens reproduced byte-exact on switched sheet. - Original contexts via pre-switch fixtures (O7, O10, R2, ledger, TS + app goldens); check:all 00:56:22 green switched. - Slip: `pnpm format` rewrote append-only audits in worktree → reverted. Never format over .claude/. + +## 2026-10-25 (R5.6 M1 fix) +- Cause M1: export sees only snapshot. Fix in build_sheet_snapshot via recognises_historical_stamp (private verified + recompute at use); input.rs strict, unchanged. +- null block refused, warnings allowed (is_publishable), canonical depth 128. Fresh worktree final: all gates green, security PASS, verifier CONFORME 8/8. STOP before activation. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 92e17e24..9f42aa0c 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -347,6 +347,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] M1 option 1 (input.rs), directional equivalence + fingerprint_verified, v0/v1 load rules, report-compare status, generator order - [x] original contexts (O7, O10, R2 Zod, R5.1 ledger, TS golden, app goldens) + separate post-switch tests; rust:check + check:all 00:56:22 green on switched state - [x] gates: security PASS (1 MEDIUM, 6 LOW), verifier ECARTS(3) = export grants alias without fingerprint_verified (fix needs snapshot_rules.rs, outside scope) → checkpoint, STOP, owner decision + - [x] R5.6 M1 correction + full rehearsal (owner 2026-10-25; snapshot_rules.rs authorised): recognises_historical_stamp, null block refused, warnings allowed, depth 128; fresh worktree r56final: rust:check + check:all 01:53:59 green; security PASS (LOW); verifier CONFORME 8/8 → checkpoint, STOP (activation on signal) - [ ] R5.6 D-R5 switch (convention, aliases, membership test in gated readers with per-file go, seed regenerated once by the Rust tool, `.prettierignore`, CHANGELOG) - [ ] R5.7 consumer census, domain fixtures moved, packages deleted, xmldom + prettier out of the lockfile, docs, ledger; `pnpm check:all`; merge only on the owner's signal - [ ] DEV hardening (owner 2026-10-24, risk accepted temporarily, not scheduled): Supabase on CLI demo keys + 54321 LAN-open (rootless, UFW allow incoming, no 54321 rule) → own JWT secret/signing keys via env() or narrower 54321 rule before any untrusted device or user (ENVIRONMENTS.md §3.6); never these keys in production; `confirm_sheet_asset_upload` object check before public exposure diff --git a/docs/development/RUST.md b/docs/development/RUST.md index 09074c0a..b4d2a8b3 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -3590,3 +3590,48 @@ an alias. Not applied: awaiting the owner. LOW kept: `"fingerprint": null` and a (no privilege), public mutable `reference`/`fingerprint_verified` fields, a draft-allowed validation warning would make a `v1` bundle unloadable, `canonical_json` recursion unbounded (trusted input today), stale comments on `pnpm import:equine` in `scripts/import-equine.sh` and CLAUDE.md. + +### 11.21 R5.6 M1 corrected, full rehearsal repeated (2026-10-25) + +Owner brief « R5.6 : autorisation de correction M1, nouvelle répétition obligatoire ». Supersedes the M1 +mechanism of §11.20: `input.rs` `keep_the_report_stamp` is gone and `pdf/write/input.rs` is unchanged +from 943a25a (strict equality). Final patch `.claude/tasks/plans/r5-6-switch.patch` (30 files, baff882), +rehearsed in a fresh detached worktree of 8e77e37. + +**Cause of the defect.** The export only sees the snapshot (`ExportInput`), never the loaded sheet, so +it could not know whether the sheet's `v1` value had been verified; it granted the registered pair on the +value the snapshot claimed (verifier probe: a v0 sheet carrying the canonical value exported an old +report). + +**Fix.** The decision is taken where the loaded sheet is known: `domain/archive/snapshot_rules.rs` +`build_sheet_snapshot` (behind `archive.snapshot`) keeps the report's historical stamp only when +`LoadedSheet::recognises_historical_stamp` holds: the loader verified a `v1` block (private +`verified_fingerprint`, set only by `from_bundle`), that value still equals the reference, the registry +binds the stamp to it for this sheet id (one direction), and the current document recomputes to it at +the moment of the decision (so a mutated pub `document` or `reference` loses the privilege). The rebase +and `report-compare` use the same predicate; the export refuses any report whose stamp differs from the +snapshot's. `"fingerprint": null` and malformed blocks are refused (`present_block`); a `v1` fingerprint +refuses integrity errors and accepts draft warnings (`is_publishable`: the two warning rules are +allowed in a draft and never block publication; a warnings-only `v1` sheet loads); `canonical_json` is +bounded at 128 levels (`CanonicalError::TooDeep`, serde_json's parse limit). Public API: the patch's own +pub field `fingerprint_verified` becomes the method `is_fingerprint_verified()`; no released or wasm API +changes. + +**Gates on the exact final state.** `pnpm rust:check` green; `pnpm check:all` green 01:53:59; `--check` +0 differences; the Rust `--out` equals the switched seed for `sheet-ref.json` and +`report-migration-map.json` and leaves `document.json`, `horse.svg` and `equine_draft.sql` byte-identical. +`r5_6_switch` 14 (direct export API: unverified v0 refused, mutated document or reference refused, +another sheet id refused, contradicting `v1` content refused at load, `null` and malformed blocks refused, +warnings-only `v1` loads, the earlier scenarios), `sheet_fingerprint` 11 (depth 128/129), vitest +`r5-6.n-1` 2 (snapshot from the core's `archive.snapshot`; the v0 counterpart refused), app goldens and R4 +digests byte for byte. Security PASS, LOW only (`.claude/audits/2026-10-25-rust-r5-6-final-security.md`); +fresh verifier CONFORME 8/8 with its own direct-API probe (`.claude/audits/2026-10-25-rust-r5-6-final-verify.md`). +Wasm: 1,532,324 B raw / 518,018 B gzip before, 1,575,574 / 531,715 after (+43 KB raw, +13.7 KB gzip: `sha2`, +the canonicaliser, the load check); no wasm size budget is defined in the repository. + +Residual, not changed after the last gate: `equivalence` is public and grants from the registry alone (its +only caller is the proof predicate; make it crate-private at activation); stale comments in +`fingerprint.rs` (lines 6, 15, 246-247: "zero integrity issue", "will declare"); a page script can still +hand the export a self-consistent report and snapshot (no equivalence results, every reader decides again); +the rebase's exact-equality branch has no sheet-id check (since R2); `r5_6_switch` writes its re-export under +`/target/tmp` regardless of `CARGO_TARGET_DIR`.