Files
faunosteo/.claude/audits/2026-10-24-rust-r5-6-prep-security.md
bchanot 943a25a98f fix(domain): R5.6 prep gates, strict declared block, patch builds, docs corrected
v1 refuses a non-hex or historical value (NotCanonical); the switch patch now builds
report-compare and refuses unknown block keys; RUST.md 11.19 states the measured
rehearsal (4 + 3 expected failures) instead of a green claim.
2026-10-24 14:57:44 +02:00

169 lines
14 KiB
Markdown

# Security audit: R5.6 preparation (diff 1f8873d..3b9a395 + the unapplied switch patch)
- date: 2026-10-24 | branch `feature/rust-r5-pipeline-core` | mode: audit (targeted delta), fresh run
- scope: `git diff 1f8873d..HEAD` (12 files: `fingerprint.rs`, its test and oracle, the Node differential,
`Cargo.toml`, `mod.rs`, `rust-check.sh`, RUST.md §11.19, plan, TODO, journal, the patch file) and
`.claude/tasks/plans/r5-6-switch.patch` read as the future change (9 files: `pipeline.rs`, `archive/read.rs`,
`report/rebase.rs`, `sheet/loaded.rs`, `facade.rs`, `pdf/compare/lines.rs`, `pdf/write/input.rs`,
`.prettierignore`, `tests/fingerprint_consumers.rs`)
- owner decisions checked against: convention `sha256-rfc8785-validated-v1`; `TRUSTED_ALIASES` the only alias
authority, bound to sheet and content; `sheet-ref.json` block descriptive, a contradiction refused; an archive's
alias list never trusted
- not done on purpose: no worktree, the patch was not applied (`git apply --check` only: applies cleanly). The
auditor contract forbids mutating code, even a scratch copy; every patch claim below comes from reading.
No service key, no network, no transfer tool, no delete, no code edited. Tree clean before and after.
- run: `cargo test -p faunosteo-core --features fingerprint,pdf-read --locked --offline --test sheet_fingerprint`
with `CARGO_TARGET_DIR` in the session scratchpad → 9 passed. Independent Node recomputation of the draft
(`node -e`, no file written): sha256 of the bytes = `27c7383c…2660` (the alias), raw JCS = `a56e4a24…88a1` =
`oracles/r5/fingerprints.json` `b_rfc8785`.
## Focus 1: can a forged, unknown or foreign-sheet alias make a different document count as the same?
No. `equivalence` (`crates/core/src/domain/sheet/fingerprint.rs:62-79`) returns `TrustedAlias` only when the two
values are exactly the registered `(canonical, alias)` pair, either way round, under the registered `sheet_id`.
There is no transitivity, no prefix or case folding, and `alias_convention` plays no part. Every unknown value is
`Different`, which fails safe: rebase (data kept, items flagged), snapshot dropped, export refused.
At each of the patch's call sites the sheet id is compared before or alongside the equivalence, and the shared id is
the one passed in:
| Site (patch line) | Sheet-id guard | Id passed to `equivalence` |
|---|---|---|
| `report/rebase.rs` (patch L122-126) | `same_sheet &&` | `sheet.reference.sheet_id` |
| `archive/read.rs` `snapshot_matches` (patch L92-100) | `snapshot.sheet_id == report.sheet_id &&` | `report.sheet.sheet_id` |
| `pdf/write/input.rs` `assert_exportable` (patch L248-258) | `sheet_id != … \|\|` | `reference.sheet_id` |
| `pdf/compare/lines.rs` `sheet_line` (patch L212-230) | `sheet_id == … &&` | `reference.sheet_id` |
`check_declared` (`fingerprint.rs:90-108`) can only refuse. `LoadedSheet::from_bundle` drops the declared block
once checked (patch L170-179) and stores no alias. An archive cannot carry an alias list: `SheetSnapshotRef` is
`deny_unknown_fields` (`crates/core/src/domain/archive/snapshot.rs:42`), and nothing reads one.
What the registered pair asserts is proven. The committed `draft/document.json` hashes to the alias by bytes and to
the canonical value through `sheet_fingerprint` (test `the_draft_gives_the_frozen_validated_value`), so both values
are the same bytes. The report stamp and the snapshot stamp are both attacker-controlled strings that could already
be set to the bundled value before the patch. The pair therefore gives a forger no new capability.
## Focus 2: does the patch loosen an archive or envelope check, or hide a real content difference?
`snapshot_matches` and `assert_exportable` are loosened by exactly the registered pair and nothing else. They hide no
content difference, because the pair is one content. The loosening has one side effect on data compatibility,
finding M1 below. It is not a forging vector.
## Focus 3: JCS (`canonical_json`) edge cases
- **Member order:** sorted by `encode_utf16()` vectors (`fingerprint.rs:136-142`), which is RFC 8785's UTF-16
code-unit order. Astral vs BMP is correct (`U+FB33` after `U+1F600`), cross-checked against Node's `<`.
- **Strings:** `"` and `\` escaped, U+0000-U+001F with the short forms, otherwise lowercase `\u00xx`. DEL, `/`,
U+2028 and U+2029 stay verbatim, with no normalisation (`é` ≠ `e`+U+0301). This matches RFC 8785 §3.2.2.2 and
`JSON.stringify`. Lone surrogates are refused at parse (`crates/core/src/domain/js.rs:42-47`), so they get no hash
and are never altered.
- **Numbers:** `js_number` (V8 oracle, 44,322 rows, green). Parsing uses serde_json `float_roundtrip` (workspace
`Cargo.toml`), so it is correctly rounded like `JSON.parse`. A big integer goes `u64 → f64` with nearest-even
rounding, which equals JS (`9007199254740993 → …992`). `JsInt` is f64-backed (`js.rs:94-125`), so there is no
i64 precision divergence. Non-finite values cannot be reached (the parser refuses them).
- **Injectivity:** `canonical_json` is injective on `Value` except `-0`/`0`, both printed `0`. That collision is
spec-conformant, and the core treats the two the same.
- **Duplicate keys:** last wins, as in `JSON.parse` (L2).
- **Unknown keys:** the typed reading is strict (`deny_unknown_fields` on every object, `schema.rs:4`), so no
collision can come from unknown keys (L1 is a documentation error).
- **Defaults:** filling Zod defaults merges only documents with the same meaning.
Net: two documents collide only when the core itself cannot tell them apart. The same document always gives the same
hash in this build and in an RFC 8785 implementation fed the same validated value.
## Focus 4: can the validation before hashing be bypassed?
No, not on any stamping path. `sheet_fingerprint` (`fingerprint.rs:207-221`) runs a strict parse, the strict R2 type,
`validate_sheet_document` with zero issues (warnings included), then `to_value`, JCS and SHA-256. The patch's only
stamping site hashes the exact text written as `document.json` (`pipeline.rs:309` and `:340`, patch L37).
`canonical_json` is public and unvalidated, but no stamping caller uses it. The legacy TypeScript writer
(`import:equine:legacy` until R5.7) still stamps v0 bytes, and the load check does not notice (M2).
## Findings
### M1 [MEDIUM] Envelopes with mixed stamps after the switch lose their snapshot in every pre-switch reader
- After the switch, an old report keeps its `27c7…` stamp on the alias path. The patch's own test asserts this:
`a_report_on_the_historical_value_is_not_rebased_and_keeps_its_stamp`, patch L300; the code is patch L122-126.
- The export snapshot is stamped from the loaded sheet:
`crates/core/src/domain/archive/snapshot_rules.rs:60` → `12d7…`.
- The patched `assert_exportable` accepts the pair and writes it (`crates/core/src/pdf/write/input.rs:204-213`
after the patch). Every old report re-exported after the switch therefore yields `report=27c7…`,
`sheetSnapshot.ref=12d7…`.
- Readers that compare stamps strictly read these envelopes as `snapshot_rejected: sheet_mismatch`:
- the frozen N-1 reader (`packages/core-wasm/tests/n-1/domain/archive/envelope.ts:97-102`);
- today's reader (`crates/core/src/domain/archive/read.rs:116-119`), which is what a `git revert` rollback
restores;
- any deployed pre-switch build.
- Effect: the report is kept, but the archived labels are lost for those readers. Plan §B.12 anticipates only the
rebase of `12d7…` archives, not this.
- It also makes the `TRUSTED_ALIASES` entry permanent. Removing it later (R5.7 cleanup or after) would drop these
snapshots in the current reader too.
- No rehearsal could catch it, because the seed was never switched (L5).
- Fix direction, an owner decision: (a) stamp the snapshot with the report's own stamp when `equivalence` says
`TrustedAlias`; or (b) re-stamp the report with the canonical value on the alias path, which contradicts "stamp
kept"; or (c) accept it, and record "a registry entry is never removed" plus an N-1 test of a re-exported old
report.
### M2 [MEDIUM] The declared-block check is incomplete against "a contradiction must be refused" and plan §B.4/§B.11
Where: patch L148-149 and L170-179 (`crates/core/src/domain/sheet/loaded.rs`), and `fingerprint.rs:90-108`.
- **(a) The check is opt-in.** The block is `#[serde(default)] Option<…>`, and `BundledRef` ignores unknown keys. An
absent or misspelled block (`fingerprints`) skips every check, but plan §B.4 says a reference without a known
convention name is refused.
- **(b) A legacy value under v1 passes.** `check_declared` iterates only the listed aliases.
`document_sha256: "27c7…"` with `{convention: v1, aliases: []}` passes: a sheet declaring v1 while carrying the
v0 value.
- **(c) No hex check.** Nothing checks the bundle's `document_sha256` as 64-hex at load. Plan §B.11 lists "a
malformed hex value" as a tested refusal, and that refusal is absent.
- **(d) Loose block type.** `DeclaredFingerprint` accepts unknown keys.
No false equivalence follows, because `equivalence` never reads the block. The residual risk is convention drift that
goes undetected, for example `import:equine:legacy` rewriting `sheet-ref.json` without the block.
Fix direction: refuse when `document_sha256` is a registered alias of this sheet under a declared v1; apply
`is_sha256_hex` to the ref; put `deny_unknown_fields` on the block type; decide whether absence is refused after the
switch.
### Low findings
| ID | Location | Finding | Direction |
|---|---|---|---|
| L1 | `fingerprint.rs:6-7` | The doc says "unknown keys dropped". The reading is strict (`schema.rs:4`): an unknown key gives `FingerprintError::Shape`. The behaviour is safer than documented. | Correct the doc |
| L2 | `js.rs:42-47`, oracle case 6 | Duplicate member names are accepted with last wins, where RFC 8785 assumes I-JSON. `{"k":1,"k":2}` and `{"k":2}` share a fingerprint. The core and `JSON.parse` read both the same; a first-wins consumer would differ. | Accepted by design; state it in the v1 definition |
| L3 | patch L219-230 (`lines.rs:347-366` after the patch) | The alias branch of `sheet_line` drops the draft/published status that the same-sheet line prints (`lines.rs:351-358`). | Diagnostic only |
| L4 | `fingerprint.rs:112` | `canonical_json` is public and has no validation step. No stamping caller uses it today. | Keep `sheet_fingerprint` the only stamping entry |
| L5 | TODO.md R5.6 prep line; RUST.md §11.19; patch L268 | The evidence conflicts. TODO says "rehearsed (rust:check + check:all 14:32:05 green)"; RUST.md says four suites fail with the generator switched. The rehearsal never regenerated the seed, so the app, N-1 and report-compare suites ran on `27c7…` with the alias paths dormant. The test header cites a non-existent `r5-6-consumers.patch`. | Rerun the gates on a switched seed at the switch |
| L6 | patch `fingerprint_consumers.rs` | No consumer-level test covers a foreign `sheet_id` carrying the registered pair (rebase, archive, export, compare). The four sites are correct by reading; only `equivalence` is unit-tested for it (`sheet_fingerprint.rs`). | Add one case per site |
| L7 | patch L37 | `sheet_fingerprint` parses and validates before the drawings' resource bound (RUST.md §11.19). This is an operator tool on repository input. | Move it after the bound, as planned |
| L8 | `sheet_fingerprint.rs:6`, patch L272 | New `#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]`. All 39 existing test crates carry the same allow, it applies to test targets only, and it is not a security suppression. | Context |
| L9 | `rebase.rs:40` | Pre-existing, kept by the patch: equal stamps skip the rebase without comparing `sheet_id`. The bundle's `document_sha256` is never recomputed at load (wasm has no `fingerprint` feature), so the build is trusted, as with v0. | Context |
Checklist and tool notes:
- Semgrep's packs carry little Rust taint coverage; the manual review above carries this scope.
- The guardrails scanner reports 1 WARN (`SB-POLICY-NOT-OWNER`,
`supabase/migrations/20261008110000_anatomical_sheets.sql:1177`). It is outside this delta and was filtered.
```
SECURITY — VERDICT: PASS
TOOL: semgrep 1.168.0 — p/security-audit, p/secrets, p/owasp-top-ten
SCOPE: 21 files (12 diff files incl. the patch file, 7 patch target files at HEAD, js.rs + json.rs as context); semgrep on 18 (journal.md, TODO.md, RUST.md read and grepped only)
BLOCKING:
(none)
REPORTED (non-blocking):
- [MEDIUM] mixed-stamp envelopes rejected by every pre-switch reader (N-1, rollback, older builds); registry entry becomes permanent — crates/core/src/domain/archive/snapshot_rules.rs:60, patch L122-126 (report/rebase.rs), crates/core/src/pdf/write/input.rs:204-213, packages/core-wasm/tests/n-1/domain/archive/envelope.ts:97-102
- [MEDIUM] declared-block check opt-in, legacy value under v1 accepted, no hex check, block not strict — patch L148-149 + L170-179 (domain/sheet/loaded.rs), crates/core/src/domain/sheet/fingerprint.rs:90-108
- [LOW] doc says unknown keys dropped, reading is strict — crates/core/src/domain/sheet/fingerprint.rs:6-7
- [LOW] duplicate member names accepted (last wins), not I-JSON — crates/core/src/domain/js.rs:42-47
- [LOW] report-compare alias line drops draft/published status — patch L219-230 (pdf/compare/lines.rs)
- [LOW] canonical_json public without validation (no stamping caller) — crates/core/src/domain/sheet/fingerprint.rs:112
- [LOW] rehearsal evidence conflicts, seed never switched, header cites missing r5-6-consumers.patch — .claude/tasks/TODO.md, docs/development/RUST.md §11.19, patch L268
- [LOW] no consumer-level foreign-sheet test of the registered pair — patch tests/fingerprint_consumers.rs
- [LOW] fingerprint computed before the drawings bound — patch L37 (curation/draft/pipeline.rs)
- [LOW] test-crate clippy allow, existing convention, not a security suppression — crates/core/tests/sheet_fingerprint.rs:6, patch L272
- [LOW] pre-existing: rebase on equal sha ignores sheet_id; bundle sha never recomputed at load — crates/core/src/domain/report/rebase.rs:40
PROOF: semgrep 157 rules on 18 files → 0 findings (0 errors); checklist 8 checks → 0 findings in scope (guardrails 0 FAIL / 1 WARN out of scope, filtered); targeted review 4 focus areas → 2 MEDIUM, 9 LOW; cargo test sheet_fingerprint 9 passed; git apply --check clean (not applied)
```