diff --git a/.claude/audits/2026-10-24-rust-r5-5-closing-security.md b/.claude/audits/2026-10-24-rust-r5-5-closing-security.md new file mode 100644 index 00000000..6a774632 --- /dev/null +++ b/.claude/audits/2026-10-24-rust-r5-5-closing-security.md @@ -0,0 +1,208 @@ +# Security audit: R5.5 closing corrections (diff 13db553..257a29b) + +- date: 2026-10-24 | branch `feature/rust-r5-pipeline-core` | mode: audit (targeted diff), fresh run +- contract: `.claude/tasks/contracts/2026-10-24-rust-r5-5-closing.md` (K1-K8) +- scope: `git diff 13db553..257a29b`, 15 files (8 code/doc + 7 `.claude/` registry, task, plan files) +- nothing run against a real stack, no service key used, no transfer tool, no delete, no code edited + +## Focus 1: `check_v3_shape` and the untrusted v3 entries + +Entries traced (wasm `crates/wasm/src/lib.rs` → `crates/core/src/facade.rs` → `ops.rs` / `session.rs`): + +| Entry | Path | Shape check | +|---|---|---| +| `SheetHandle.import_pdf` / `import_pdf_bytes` | `facade::import_pdf` → `pdf/import.rs:29` `import_archive` → `read_archive_document` → `read_report_document` | yes (`report/read.rs:80`) | +| `archive.import` op | `ops.rs:345` → `session::import_archive` → same | yes | +| `draft.restore` op, draft text | `ops.rs:316` → `session.rs:85` `read_report_document` | yes | +| `draft.restore` op, archive text | `session.rs:103-106` `parse_envelope` | yes (`archive/read.rs:124-125`) | +| `restore_copy_bytes` | `facade.rs:86-101` → `restore_draft(.., None)` | yes | +| `report-compare` CLI | `pdf/compare/mod.rs:133` → `read_archive_document` | yes | + +These are the only paths by which an external v3 report enters. The remaining typed reads of +`Report` take the store's report, which is always the core's canonical output: the reducers +(`ops.rs:64-87`), `archive.snapshot` (`ops.rs:301-303`), the export session (`pdf/write/input.rs:26`), +and `export_from_envelope` (`pdf/write/export.rs:117-130`, a public library fn with test-only +callers, not exported by wasm or a binary). + +Panic review: `check_v3_shape` (`report/read.rs:55-71`) uses only `Value::get`, `as_array`, +`is_object`, `is_string`, `enumerate` and `format!`. No indexing, no unwrap, no recursion. A +non-object or `null` input returns `Ok` and the typed read refuses it. No panic path. + +Authentic shapes: the core's writer emits `sheet` and `practitioner` as objects and `severity` as +a string or omits it (`skip_serializing_if`). Zod refused arrays, one-key maps and `null` for every +earlier v3 writer. `null` severity was already refused before this diff: `js::present` calls +`Severity::deserialize(null)`, which fails. No authentic shape is newly refused. Hermetic suites +were rerun here and are green: `archive_rules` 38, `report_rules` 17, `characterisation` 4, +`characterisation_serde_tolerance` 5, `pdf_import` 3. + +Bypass found (M1 below). The check reads keys on the raw value, so any shape where the parent +container is itself positional skips it, because `Value::get(&str)` on an array returns `None`. + +## Focus 2: upload tool, `Protocol` and `own_address` + +`Protocol` is final: `storage.rs:189-197` retries `Io`, `Timeout`, `HostNotFound` and +`ConnectionFailed` only, plus 5xx (`storage.rs:79-80`). `final_error` (`storage.rs:203-215`) +carries no error text, so neither the key nor the header shows. The test +`a_malformed_answer_is_final_and_not_retried` is green: one request, exit 1. + +`own_address` (`main.rs:114-122`), measured on this host with the same syscalls (UDP bind then +connect, nothing sent): + +| DEV host | bind | connect | local_addr == ip | own_address | +|---|---|---|---|---| +| 255.255.255.255 (and the host's `brd` addresses, unit test) | ok | EACCES (13) | n/a | false | +| 0.0.0.0 | ok | ok | 127.0.0.1, no | false | +| 224.0.0.251, 239.255.255.250 (multicast) | ok | ok | yes | **true** (L3) | +| another host's private address | EADDRNOTAVAIL (`ip_nonlocal_bind` = 0) | n/a | n/a | false | + +Even with `ip_nonlocal_bind=1`, the connect route lookup refuses a non-local source address +(no `IP_FREEBIND` / `IP_TRANSPARENT` is set). So a non-local unicast address does not pass. + +Defense in depth holds. `host_is_allowed` (`curation/upload.rs:190-200`) only accepts the DEV +host when the URL host is loopback or RFC 1918 and parses equal to it. Multicast and public +addresses are neither. The kernel also refuses a TCP connect to multicast. + +Packet: `own_address` sends nothing. A UDP `connect` only records the peer, there is no +`send`/`send_to`, and the socket is dropped on return. It joins no multicast group. + +## Focus 3: secrets and SQL claims + +- No secret value in the diff. The added lines contain no JWT (`eyJ…`), no CLI default secret + string, no `sb_secret_` / `sb_publishable_` key and no password literal. `iss: supabase-demo` + is a claim name, not a key. +- Repo-wide (tracked, at 257a29b) search for the CLI default JWT secret, `eyJhbGciOi`, + `eyJpc3Mi` and `sb_secret_`/`sb_publishable_` keys. Only `crates/worker/src/config.rs:324,326` + matches: a fabricated test token (payload `{"role":"service_role","exp":…}`, signature + literally `sig`) and the placeholder `sb_secret_abc`. These are not credentials. The only + tracked env file is `.env.example`. +- `supabase/config.toml` `[auth]` (lines 73-96) sets no `jwt_secret` and no signing keys, which + matches ENVIRONMENTS.md §3.6. The claim that the service key is the public demo key was not + checked independently: that would mean reading the key value. +- `confirm_sheet_asset_upload`: `20261009100000_sheet_asset_storage.sql:57-58` runs `revoke all + … from public, anon, authenticated` and `grant execute … to service_role`. No later migration + re-grants it. The function (lines 34-52) sets `uploaded_at` with no `storage.objects` existence + or byte check. pgTAP `006_sheet_asset_storage.sql:73-80` covers editor 42501, service-role + confirm of A and B, and idempotence. It has no `anon` assertion, which matches the doc. +- The bucket has no INSERT, UPDATE or DELETE policy. The only `storage.objects` policies in + all migrations are `anatomical_sheet_assets_read` (select), `avatars_read` (select) and + `avatars_upload` (insert, pinned to `bucket_id = 'avatars'`, `20261013100000:284-291`). + RUST.md §11.18 is accurate. +- No file under `supabase/` changed in the diff (K5). + +## Findings + +### M1 [MEDIUM] `check_v3_shape` bypassable through a positional parent +`crates/core/src/domain/report/read.rs:61-69`, `crates/core/src/domain/archive/read.rs:124-125` + +- An observation written as a positional array (`[id, zones, findings, freeTextFindings, + {"mild": null}, comment]`) is accepted on every entry. `observation.get("severity")` returns + `None` on an array, and serde's derived `Observation` visitor reads the sequence, one-key + severity map included. +- In `parse_envelope`, a `report` written as an array (or the whole envelope as an array) makes + `check_v3_shape` see no keys. All three refused shapes (sheet array, practitioner array, + severity map) are then accepted. +- In the import path a report-level or envelope-level array is still refused, because + `version_of` and `envelope_version_of` require an object. +- K4 states that the three shapes are refused at both v3 entries. That holds only when every + parent is an object. +- Impact is low. The field values still pass every field rule and the core re-serialises + canonically, so there is no injection. What remains is a parser differential with the N-1 Zod + reader. Established by reading: it is the same `visit_seq` mechanism the R5.5 + characterisation proved for `sheet` and `practitioner`. No probe was executed, because writing + a test is outside this audit. +- Fix direction (owner scope): require `observations[i]` to be an object, and in + `parse_envelope` require both `data` and `report` to be objects before the shape check. A + generic guard is an alternative. + +### M2 [MEDIUM, pre-existing, outside the diff, documented by it] DEV API reachable as `service_role` from the LAN +`supabase/config.toml:73-96`, `docs/development/ENVIRONMENTS.md` §3.6 + +- The stack runs on the CLI's public default JWT secret and 54321 is LAN-open by design. +- Any device on the private network can therefore act as `service_role` on DEV data, bypassing + RLS. The doc states this accurately and leaves the choice to the owner. Production is not + involved. +- Not introduced by this diff, so not gated here. Resolve it before any non-test data reaches + DEV: own `jwt_secret` / signing keys through `env()`, or narrow the 54321 rule. + +### L1 [LOW] Remaining serde tolerance on the other nested v3 structs +`crates/core/src/domain/report/read.rs:52-54` + +- `animal`, `owner`, `zones[]`, `findings[]`, `vertebrae[]` and `nextAppointment` variants as + positional arrays, and `side` as a one-key map, are still accepted. +- This is within the owner's go ("three shapes only"). But the doc comment ("The shapes Zod + refused and serde's derives accept") reads as a complete list, and BDR-069's rationale + ("crafted file could swap same-typed fields") applies to these shapes too. +- Hint: word the comment and §11.18 as "three of the shapes". + +### L2 [LOW] Error text contradicts behaviour +`crates/core/src/domain/report/read.rs:66` + +The message says "expected a string or null", but `null` is refused. The test's own comment +says so (`characterisation_serde_tolerance.rs`, "null stays refused"). + +### L3 [LOW] `own_address` accepts IPv4 multicast +`crates/core/src/bin/upload_sheet_assets/main.rs:110-122` + +- Measured: bind and connect succeed and `local_addr` equals the address. The "own unicast" + claim in the doc comment and in RUST.md §11.18 is therefore inaccurate. +- Not exploitable: `host_is_allowed` requires RFC 1918 or loopback, and TCP to multicast is + refused by the kernel. The unit test (`main.rs:255-266`) does not cover multicast. +- Hint: add `!ip.is_multicast()`, or rely on and state the private-range filter. + +### L4 [LOW] `own_address` unit test is vacuous without `ip` +`crates/core/src/bin/upload_sheet_assets/main.rs:237-244` + +If the `ip` command is missing, `unwrap_or_default` yields empty lists and the host unicast and +broadcast loops check nothing. The test still passes. This affects test strength only. + +### L5 [LOW, pre-existing, documented] `confirm_sheet_asset_upload` does not check the object +`supabase/migrations/20261009100000_sheet_asset_storage.sql:34-52` + +The guard is EXECUTE (service_role only) and no API role can place bytes, so this is not +exploitable today. The debt is recorded in RUST.md §11.18: check the object's existence and size +before any public exposure. + +### L6 [LOW] Typed reads of `Report` outside the two checked entries +`crates/core/src/ops.rs:64-87, 301-303`, `crates/core/src/pdf/write/input.rs:26`, +`crates/core/src/pdf/write/export.rs:117-130` + +These take store or core-canonical reports today, so none of them is an external entry. If +`export_from_envelope` ever reads a file-borne envelope, it skips `check_v3_shape`. + +## Anti-gaming + +The diff adds no `nosemgrep`, `nosec` or `eslint-disable` comment and no new `#[allow]`. The +`#![allow(clippy::…)]` in `characterisation_serde_tolerance.rs` predates the diff and is a lint +allowance, not a security suppression. + +## Notes + +- One command was refused by the permission rules: `git check-ignore -v .env.worker .env; grep + -n "SERVICE_ROLE\|SECRET\|KEY" .env.example`. It was not rerun in another form. The + tracked-env check used `git ls-files` instead, and the only result is `.env.example`. +- Guardrails scanner (`--domain api,supabase`): 0 FAIL, 1 WARN, 1 MANUAL. The WARN + (`SB-POLICY-NOT-OWNER`, `20261008110000_anatomical_sheets.sql:1177`) is in a file outside the + diff and is filtered out. MANUAL is not reported. +- Hermetic runs: `cargo test -p faunosteo-core --features upload --bin upload-sheet-assets + --test upload_tool --test characterisation_serde_tolerance --test archive_rules --test + report_rules` gave 1 + 13 + 5 + 38 + 17 passed. `--features pdf-read --test pdf_import --test + characterisation` gave 3 + 4 passed. `upload_tool` targets an in-process loopback stub with a + made-up key. + +``` +SECURITY — VERDICT: PASS +TOOL: semgrep 1.168.0 — p/security-audit, p/secrets, p/owasp-top-ten +SCOPE: 15 files +BLOCKING: + (none) +REPORTED (non-blocking): + - [MEDIUM] check_v3_shape bypass via positional parent — crates/core/src/domain/report/read.rs:61-69, crates/core/src/domain/archive/read.rs:124-125 + - [MEDIUM] DEV stack service_role reachable from LAN (pre-existing, documented) — supabase/config.toml:73-96, docs/development/ENVIRONMENTS.md §3.6 + - [LOW] other nested v3 serde tolerance, doc comment overstates completeness — crates/core/src/domain/report/read.rs:52-54 + - [LOW] error text "or null" contradicts refusal — crates/core/src/domain/report/read.rs:66 + - [LOW] own_address accepts IPv4 multicast (blocked downstream by host_is_allowed) — crates/core/src/bin/upload_sheet_assets/main.rs:114-122 + - [LOW] own_address test vacuous without `ip` — crates/core/src/bin/upload_sheet_assets/main.rs:237-244 + - [LOW] confirm_sheet_asset_upload no object check (pre-existing, documented) — supabase/migrations/20261009100000_sheet_asset_storage.sql:34-52 + - [LOW] internal typed Report reads skip the shape check — crates/core/src/pdf/write/export.rs:117-130, crates/core/src/ops.rs:64-87 +PROOF: semgrep 74 rules on 15 files → 0 findings (0 errors); checklist 8 checks → 2 findings (+ guardrails 0 FAIL / 1 WARN out of diff, filtered); targeted review 3 focus areas → 6 findings +``` diff --git a/crates/core/src/bin/upload_sheet_assets/main.rs b/crates/core/src/bin/upload_sheet_assets/main.rs index dc7ccb83..8e3c5062 100644 --- a/crates/core/src/bin/upload_sheet_assets/main.rs +++ b/crates/core/src/bin/upload_sheet_assets/main.rs @@ -115,6 +115,10 @@ fn own_address(host: &str) -> bool { let Ok(ip) = host.parse::() else { return false; }; + // A multicast group binds and connects like an own address on Linux: never unicast. + if ip.is_multicast() { + return false; + } let Ok(socket) = std::net::UdpSocket::bind((ip, 0)) else { return false; }; @@ -254,7 +258,14 @@ mod tests { #[test] fn only_an_own_unicast_address_counts_as_the_dev_address() { assert!(own_address("127.0.0.1")); - for refused in ["255.255.255.255", "203.0.113.7", "not-an-ip", ""] { + for refused in [ + "255.255.255.255", + "224.0.0.1", + "239.255.255.250", + "203.0.113.7", + "not-an-ip", + "", + ] { assert!(!own_address(refused), "{refused}"); } let (unicast, broadcast) = host_addresses(); diff --git a/crates/core/src/domain/archive/read.rs b/crates/core/src/domain/archive/read.rs index 14bf5b3a..5419b9dd 100644 --- a/crates/core/src/domain/archive/read.rs +++ b/crates/core/src/domain/archive/read.rs @@ -121,6 +121,10 @@ fn snapshot_matches(snapshot: &SheetSnapshot, report: &Report) -> bool { /// `ReportArchiveEnvelopeSchema.parse`: the shape of a whole envelope (the snapshot's shape /// only, no caps nor integrity), as the session keeps it. pub fn parse_envelope(data: &Value) -> Result { + // A positional envelope would carry its report past the check unseen. + if !data.is_object() { + return Err(serde::de::Error::custom("envelope: expected an object")); + } let report = data.get("report").unwrap_or(&Value::Null); check_v3_shape(report).map_err(serde::de::Error::custom)?; ReportArchiveEnvelope::deserialize(data) diff --git a/crates/core/src/domain/report/read.rs b/crates/core/src/domain/report/read.rs index 0fb983ef..e91685b1 100644 --- a/crates/core/src/domain/report/read.rs +++ b/crates/core/src/domain/report/read.rs @@ -51,8 +51,13 @@ pub fn version_of(data: &Value) -> Option { /// The shapes Zod refused and serde's derives accept (owner go 2026-10-24, RUST.md §11.18): /// `sheet` and `practitioner` written as positional arrays, a `severity` written as a one-key -/// map. Checked on the raw value before the typed read; nothing else is widened or narrowed. +/// map. Checked on the raw value before the typed read. The report and each observation must +/// be objects themselves, or a positional parent would carry those fields past the check +/// unseen; nothing else is widened or narrowed. pub fn check_v3_shape(data: &Value) -> Result<(), String> { + if !data.is_object() { + return Err("report: expected an object".to_owned()); + } for key in ["sheet", "practitioner"] { if data.get(key).is_some_and(|value| !value.is_object()) { return Err(format!("{key}: expected an object")); @@ -60,11 +65,14 @@ pub fn check_v3_shape(data: &Value) -> Result<(), String> { } let observations = data.get("observations").and_then(Value::as_array); for (index, observation) in observations.into_iter().flatten().enumerate() { - let severity = observation.get("severity"); - if severity.is_some_and(|value| !value.is_string()) { - return Err(format!( - "observations[{index}].severity: expected a string or null" - )); + if !observation.is_object() { + return Err(format!("observations[{index}]: expected an object")); + } + if observation + .get("severity") + .is_some_and(|value| !value.is_string()) + { + return Err(format!("observations[{index}].severity: expected a string")); } } Ok(()) diff --git a/crates/core/tests/characterisation_serde_tolerance.rs b/crates/core/tests/characterisation_serde_tolerance.rs index 89cdaa57..ba16f047 100644 --- a/crates/core/tests/characterisation_serde_tolerance.rs +++ b/crates/core/tests/characterisation_serde_tolerance.rs @@ -106,3 +106,25 @@ fn the_envelope_entry_refuses_the_same_shapes() { assert!(parse_envelope(&wrapped).is_err()); } } + +#[test] +fn a_positional_parent_does_not_carry_a_refused_shape_past_the_check() { + let mut report = demo(); + let o = report["observations"][0].clone(); + report["observations"][0] = json!([ + o["id"], o["zones"], o["findings"], o["freeTextFindings"], { "mild": null }, o["comment"] + ]); + refused_with(&report, "observations[0]: expected an object"); + let envelope: Value = serde_json::from_str(&common::repo_file( + "apps/app/tests/fixtures/goldens/r2/envelope.demo.fr.nologos.json", + )) + .unwrap(); + let fields = envelope.as_object().unwrap(); + let mut positional: Vec = fields.values().cloned().collect(); + let at = fields.keys().position(|key| key == "report").unwrap(); + positional[at] = sheet_as_array(); + assert!(parse_envelope(&Value::Array(positional)).is_err()); + let mut wrapped = envelope.clone(); + wrapped["report"] = json!([1, 2, 3]); + assert!(parse_envelope(&wrapped).is_err()); +} diff --git a/docs/development/RUST.md b/docs/development/RUST.md index 0c293e7f..fda86c3c 100644 --- a/docs/development/RUST.md +++ b/docs/development/RUST.md @@ -3411,7 +3411,10 @@ other LOW reserves of §11.16 stay tracked. **Serde hardening of three v3 shapes (owner go).** `report::read::check_v3_shape` refuses on the raw value, before the typed read, `sheet` or `practitioner` not an object and an observation `severity` not a string -(`ReadFailure::Invalid` with the field named). Called at the two entries that read a v3 report from outside: +(`ReadFailure::Invalid` with the field named at `read_report_document`; a `serde_json::Error` at +`parse_envelope`, whose caller drops the copy as before). The report, each observation and the envelope +must be objects themselves, or a positional parent would carry those fields past the check (found by the +closing gates, test `a_positional_parent_does_not_carry_a_refused_shape_past_the_check`). Called at the two entries that read a v3 report from outside: `read_report_document` (v3 branch: PDF import, bare archives, draft restore) and `parse_envelope` (the session's archive copy). Nothing else narrowed: an unknown field and an absent `severity` are read as before; `null` severity was and stays refused (optional, never nullable). Test `characterisation_serde_tolerance` turned @@ -3436,3 +3439,12 @@ rootless or rootful Docker, a probe from another device) and the two remedies ar firewall or configuration was changed. **R5.6 prepared, not started.** Plan `.claude/tasks/plans/2026-10-24-rust-r5-6-fingerprint-switch.md`. + +Closing gates round 1 (257a29b): `pnpm check:all` green 03:39:24; security PASS (2 MEDIUM, 6 LOW, +`.claude/audits/2026-10-24-rust-r5-5-closing-security.md`); fresh verifier ECARTS(2): the shape check was +blind under a positional observation or envelope (fixed, as above), and a stale "or null" message (fixed). +Also fixed: a multicast address no longer counts as an own address (it binds and connects on Linux; the +private-range rule masked it end to end). Kept: the binary's own-address test checks nothing more than +loopback where `ip` is absent; the internal typed re-reads (`pdf/write/export.rs`, `ops.rs`) read values the +core itself built and skip the raw shape check; the other nested v3 fields and v2 keep serde's leniency +(outside the go).