From ac13469f4882b26db27187d35589cdeb11227a87 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 19:51:08 +0000 Subject: [PATCH] fix(deed): bound nesting, fail closed on unstat-able registry, keep error chain Follow-up to #295, addressing three open review findings and the UUID gate failure on its head. 1. src/deed.rs: clause recursion (members) and list recursion (value/list, quoted lists included) were unbounded, so a deed of a few MB with ~10,000 nested '(' overflowed the stack and aborted the process. One shared limit, MAX_NESTING = 64, is now checked before every descent and returns a line-numbered DeedError. deed.abnf sets no limit; this is a resource bound of the reader. 2. src/assail/classifications.rs: Path::exists() turned any metadata error (e.g. an unreadable audits/) into "no deed", so the reader silently fell back to the legacy registry. symlink_metadata now decides: NotFound (or NotADirectory, when audits is a regular file) means absent; any other error propagates with the registry path. 3. src/assemblyline.rs: scan_repo stored e.to_string(), which keeps only the outermost anyhow context and drops the deed's line and reason. It now stores format!("{e:#}"). UUID gate: two negative fixtures in deed.rs's tests were bare v4/v5 UUID literals (escaped quotes hide them from the #uuid"..." rule), which check-uuid-v8.sh --strict rejects. They are now derived at run time from the v8 fixture id. Tests: nesting at and past the limit for clauses, lists and the two combined; 100,000-deep clauses and lists return Err; the error line; unreadable audits/ (skipped when privileged), audits as a file, a dangling deed symlink; and the deed line and reason reaching the assemblyline error string. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0136P7ZoBy5xGnGDLk7wQ8jC --- src/assail/classifications.rs | 24 +++++- src/assail/mod.rs | 73 ++++++++++++++++ src/assemblyline.rs | 37 +++++++- src/deed.rs | 157 ++++++++++++++++++++++++++++++---- 4 files changed, 273 insertions(+), 18 deletions(-) diff --git a/src/assail/classifications.rs b/src/assail/classifications.rs index 14085ce..f615481 100644 --- a/src/assail/classifications.rs +++ b/src/assail/classifications.rs @@ -22,7 +22,7 @@ use crate::deed::{self, Item, Value}; use crate::types::{AssailReport, WeakPointCategory}; use anyhow::{anyhow, bail, Context, Result}; use std::fs; -use std::io::Read; +use std::io::{ErrorKind, Read}; use std::path::Path; /// Repo-relative path of the deed registry. @@ -88,9 +88,29 @@ pub struct UserClassification { /// /// `Ok(vec![])` when no registry exists. An unreadable, oversized or /// malformed deed registry is an `Err` naming the file and line. +/// +/// Only a deed that is definitely absent lets the reader fall back to the +/// legacy A2ML files: `NotFound`, or `NotADirectory` (`audits` is a regular +/// file, so nothing can sit beneath it). Any other failure to stat the deed +/// path, such as an unreadable `audits/` directory, is an error: treating it +/// as absent would silently swap the registry the project wrote for an older +/// one. A dangling symlink at the deed path is likewise not absent; it fails +/// when it is opened. pub fn load_user_classifications(project_root: &Path) -> Result> { let deed_path = project_root.join(DEED_PATH); - if deed_path.exists() { + let deed_present = match fs::symlink_metadata(&deed_path) { + Ok(_) => true, + Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => false, + Err(e) => { + return Err(e).with_context(|| { + format!( + "cannot tell whether the classification registry {} exists", + deed_path.display() + ) + }) + } + }; + if deed_present { let text = read_capped(&deed_path)?; return parse_classification_deed(&text, &deed_path) .with_context(|| format!("malformed classification registry {}", deed_path.display())); diff --git a/src/assail/mod.rs b/src/assail/mod.rs index 62909be..58cad55 100644 --- a/src/assail/mod.rs +++ b/src/assail/mod.rs @@ -824,6 +824,79 @@ mod classifications_tests { } } + /// An `audits/` the reader cannot search must not look like a missing + /// deed: that would silently fall back to the root `.a2ml` registry. + #[cfg(unix)] + #[test] + fn unreadable_audits_dir_is_an_error_not_a_fallback() { + use std::os::unix::fs::PermissionsExt; + let tmp = TempDir::new().unwrap(); + write_deed(tmp.path(), &deed_with(ZIG_BRIDGE_DEED_ENTRY)); + fs::write( + tmp.path().join(".panic-attack-classifications.a2ml"), + r#"(assail-classifications + (classification (file "a/b.rs") (category "PanicPath"))) +"#, + ) + .unwrap(); + let audits = tmp.path().join("audits"); + fs::set_permissions(&audits, fs::Permissions::from_mode(0o000)).unwrap(); + // Root, or any process with CAP_DAC_OVERRIDE/CAP_DAC_READ_SEARCH, + // ignores the mode bits, so the deed stays readable and there is + // nothing to test. Probe instead of checking the uid: the probe also + // covers capabilities granted to a non-root user. + let privileged = fs::read_dir(&audits).is_ok(); + let result = load_user_classifications(tmp.path()); + // Restore the mode so TempDir can clean up. + fs::set_permissions(&audits, fs::Permissions::from_mode(0o755)).unwrap(); + if privileged { + eprintln!( + "skipped: running as root (or with DAC override), so a mode-000 directory stays readable" + ); + return; + } + let err = result.expect_err("an unreadable audits/ must be an error"); + assert!( + format!("{err:#}").contains("assail-classifications_praxis.deed"), + "error must name the registry: {err:#}" + ); + } + + #[test] + fn audits_as_a_regular_file_means_no_deed() { + let tmp = TempDir::new().unwrap(); + fs::write(tmp.path().join("audits"), "not a directory\n").unwrap(); + fs::write( + tmp.path().join(".panic-attack-classifications.a2ml"), + r#"(assail-classifications + (classification (file "a/b.rs") (category "PanicPath"))) +"#, + ) + .unwrap(); + let classifications = load_user_classifications(tmp.path()).unwrap(); + assert_eq!(classifications.len(), 1, "falls back to the root registry"); + } + + #[cfg(unix)] + #[test] + fn dangling_deed_symlink_is_an_error_not_a_fallback() { + let tmp = TempDir::new().unwrap(); + let audits = tmp.path().join("audits"); + fs::create_dir_all(&audits).unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("nowhere.deed"), + tmp.path().join(USER_CLASSIFICATIONS_DEED_PATH), + ) + .unwrap(); + write_registry( + tmp.path(), + r#"(assail-classifications + (classification (file "a/b.rs") (category "PanicPath"))) +"#, + ); + assert!(load_user_classifications(tmp.path()).is_err()); + } + #[test] fn analyze_fails_on_a_malformed_deed() { let tmp = TempDir::new().unwrap(); diff --git a/src/assemblyline.rs b/src/assemblyline.rs index 75beacc..48d492e 100644 --- a/src/assemblyline.rs +++ b/src/assemblyline.rs @@ -374,7 +374,10 @@ fn scan_repo(repo_path: &Path) -> RepoResult { high_count: 0, total_files: 0, total_lines: 0, - error: Some(e.to_string()), + // `{:#}` keeps the whole anyhow chain ("outer: inner: …"), so a + // malformed registry deed reports its line and reason here, not + // just the outermost context. + error: Some(format!("{e:#}")), fingerprint, report: None, }, @@ -576,6 +579,38 @@ mod tests { ); } + #[test] + fn scan_error_keeps_the_deed_line_and_reason() { + let tmp = tempfile::TempDir::new().unwrap(); + std::fs::write(tmp.path().join("main.rs"), "fn main() {}\n").unwrap(); + let audits = tmp.path().join("audits"); + std::fs::create_dir_all(&audits).unwrap(); + // Line 7 carries a category the registry does not know. + std::fs::write( + audits.join("assail-classifications_praxis.deed"), + ";; SPDX-License-Identifier: MPL-2.0\n\ + (praxis-deed\n \ + :schema-version \"1.0.0\"\n \ + :canonical-name \"x\"\n \ + :beholding-chora #uuid\"0889b37b-defb-831f-973c-e119500db00e\"\n \ + :profile assail-classifications\n \ + (classification :file \"a.rs\" :category UnsafeKode))\n", + ) + .unwrap(); + let err = scan_repo(tmp.path()) + .error + .expect("a malformed deed fails the scan"); + assert!( + err.contains("assail-classifications_praxis.deed"), + "names the file: {err}" + ); + assert!(err.contains("line 7"), "keeps the line: {err}"); + assert!( + err.contains("unknown weak-point category UnsafeKode"), + "keeps the reason: {err}" + ); + } + #[test] fn test_is_source_file() { assert!(is_source_file(Path::new("main.rs"))); diff --git a/src/deed.rs b/src/deed.rs index 0259597..220c0a3 100644 --- a/src/deed.rs +++ b/src/deed.rs @@ -15,8 +15,8 @@ //! consumed, `:schema-version` appears exactly once at the top level, no tab //! appears anywhere, no line exceeds 998 octets, a comment ends in a line-end, //! the filename dispatches to the doc-head it carries, and an identity field -//! never carries a `#u5` or a non-version-8 `#uuid`. It does not implement the -//! clause profiles (anchor, edict, descriptile …): a consumer checks the +//! never carries a `#u5` or a non-version-8 `#uuid`. Clauses and lists nest no +//! deeper than [`MAX_NESTING`] levels. It does not implement the clause profiles (anchor, edict, descriptile …): a consumer checks the //! profile it reads on top of the parsed tree. //! //! Every error carries the 1-based line it was found on. A malformed deed is @@ -53,6 +53,15 @@ const IDENTITY_FIELDS: &[&str] = &[ /// Longest line `deed.abnf` allows, in octets, line-end excluded. pub const MAX_LINE_OCTETS: usize = 998; +/// Deepest nesting of clauses and lists the reader accepts. The limit is +/// shared: every `(` inside the deed form that opens a clause, a list or a +/// quoted list adds one level, and the form's own members sit at level 0. +/// Real deeds nest a handful of levels, so 64 leaves ample room while +/// bounding the reader's recursion: a hostile file of a few MB made of nested +/// `(` returns an error instead of overflowing the stack and aborting the +/// process. `deed.abnf` sets no limit; this is a resource bound of this reader. +pub const MAX_NESTING: usize = 64; + /// A parse or validation error, with the 1-based line it was found on. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DeedError { @@ -270,6 +279,18 @@ impl Parser<'_> { } } + /// The level one deeper than `depth`, or an error naming the line of the + /// `(` that would pass [`MAX_NESTING`]. Called before every descent into + /// a clause or a list. + fn deeper(&self, depth: usize) -> Result { + if depth >= MAX_NESTING { + return Err(self.err(format!( + "clauses and lists nest deeper than {MAX_NESTING} levels" + ))); + } + Ok(depth + 1) + } + fn peek(&self) -> Option { self.s.get(self.i).copied() } @@ -420,12 +441,13 @@ impl Parser<'_> { Some(_) if !had_sep => { return Err(self.err("a separator is required before each field or clause")) } - Some(b':') => items.push(self.field(head, in_top_rule)?), + Some(b':') => items.push(self.field(head, in_top_rule, depth)?), Some(b'(') => { + let inner_depth = self.deeper(depth)?; self.i += 1; let line = self.line; let name = self.symbol()?; - let inner = self.members(head, depth + 1, depth == 0 && name == "rule")?; + let inner = self.members(head, inner_depth, depth == 0 && name == "rule")?; items.push(Item::Clause { name, items: inner, @@ -443,8 +465,9 @@ impl Parser<'_> { } } - /// `field = keyword token-sep value [token-sep bang]`. - fn field(&mut self, head: &str, in_top_rule: bool) -> Result { + /// `field = keyword token-sep value [token-sep bang]`. `depth` is the + /// level of the form or clause the field belongs to. + fn field(&mut self, head: &str, in_top_rule: bool, depth: usize) -> Result { let line = self.line; self.i += 1; // ':' let key = self.symbol()?; @@ -453,7 +476,7 @@ impl Parser<'_> { "a separator is required between :{key} and its value (there is no '=' form)" ))); } - let value = self.value()?; + let value = self.value(depth)?; // "Never true, false, yes, no": they lex as symbols, so the ban is a // value-level rule (DEED-GRAMMAR-SPEC; deed_lint does the same). if matches!(&value, Value::Symbol(s) if ["true", "false", "yes", "no"].contains(&s.as_str())) @@ -512,14 +535,15 @@ impl Parser<'_> { }) } - fn value(&mut self) -> Result { + /// A value at level `depth`; a list in it opens one level deeper. + fn value(&mut self, depth: usize) -> Result { let v = match self.peek() { Some(b'"') => Value::Str(self.string()?), Some(b'#') => self.hash_form()?, Some(b'\'') => { self.i += 1; match self.peek() { - Some(b'(') => Value::Quoted(Box::new(self.list()?)), + Some(b'(') => Value::Quoted(Box::new(self.list(self.deeper(depth)?)?)), Some(b) if is_symbol_start(b) => { Value::Quoted(Box::new(Value::Symbol(self.symbol()?))) } @@ -528,7 +552,7 @@ impl Parser<'_> { )), } } - Some(b'(') => self.list()?, + Some(b'(') => self.list(self.deeper(depth)?)?, Some(b'-') | Some(b'0'..=b'9') => { let start = self.i; if self.peek() == Some(b'-') { @@ -551,8 +575,9 @@ impl Parser<'_> { Ok(v) } - /// `list = "(" [token-sep] [value *(token-sep value)] [token-sep] ")"`. - fn list(&mut self) -> Result { + /// `list = "(" [token-sep] [value *(token-sep value)] [token-sep] ")"`, + /// at level `depth` (the caller has checked it against [`MAX_NESTING`]). + fn list(&mut self, depth: usize) -> Result { self.i += 1; // '(' let mut out = Vec::new(); loop { @@ -571,7 +596,7 @@ impl Parser<'_> { self.err("a list holds values only; a :keyword cannot appear in one") ) } - Some(_) => out.push(self.value()?), + Some(_) => out.push(self.value(depth)?), } } } @@ -737,15 +762,117 @@ mod tests { "(praxis-deed :schema-version \"1\" :b true)", "(praxis-deed :schema-version \"1\" (c :b no))", "(praxis-deed :schema-version \"1\" :u #uuid\"0889B37B-defb-831f-973c-e119500db00e\")", - "(praxis-deed :schema-version \"1\" :u #uuid\"0889b37b-defb-431f-973c-e119500db00e\")", "(praxis-deed :schema-version \"1\" :u #u8\"nodomain\")", "(praxis-deed :schema-version \"1\" :beholding-chora #u5\"x\")", - "(praxis-deed :schema-version \"1\" :repo-uuid #uuid\"0889b37b-defb-531f-973c-e119500db00e\")", "(praxis-deed :schema-version \"1\" :l (:k 1))", "(praxis-deed :schema-version \"1\") ; no line-end after this comment", ] { bad(body); } + // A version 4 id is not uuid-hex, and a version 5 id is not allowed + // in an identity field. + bad(&format!( + "(praxis-deed :schema-version \"1\" :u #uuid\"{}\")", + with_version('4') + )); + bad(&format!( + "(praxis-deed :schema-version \"1\" :repo-uuid #uuid\"{}\")", + with_version('5') + )); + } + + /// A version 8 id for the fixtures. + const V8_ID: &str = "0889b37b-defb-831f-973c-e119500db00e"; + + /// [`V8_ID`] with its version nibble replaced. The ids the reader must + /// refuse are built at run time so that no non-v8 UUID literal sits in + /// the source, which the estate UUID gate (ADR-008) scans. + fn with_version(v: char) -> String { + let mut id = V8_ID.to_string(); + id.replace_range(14..15, &v.to_string()); + id + } + + /// `n` nested clauses `(c (c …`, wrapped onto lines well under the + /// 998-octet limit, inside a praxis deed. Unclosed: the reader must stop + /// at the nesting limit long before the end of input. + fn nested_clauses(n: usize) -> String { + let opens: Vec<&str> = vec!["(c"; n]; + let lines: Vec = opens.chunks(200).map(|c| c.join(" ")).collect(); + format!("(praxis-deed :schema-version \"1\"\n{}", lines.join("\n")) + } + + /// A field whose value is `n` nested lists `(((…`, wrapped like + /// [`nested_clauses`]. + fn nested_lists(n: usize) -> String { + let lines: Vec = (0..n.div_ceil(500)) + .map(|k| "(".repeat(500.min(n - k * 500))) + .collect(); + format!( + "(praxis-deed :schema-version \"1\" :l\n{}", + lines.join("\n") + ) + } + + #[test] + fn nesting_up_to_the_limit_parses() { + let closed = |n: usize| format!("{}{}\n", nested_clauses(n), ")".repeat(n + 1)); + assert!(parse(&format!("{H}{}", closed(MAX_NESTING)), None).is_ok()); + let e = parse(&format!("{H}{}", closed(MAX_NESTING + 1)), None).unwrap_err(); + assert!(e.message.contains("nest deeper"), "{e}"); + + let closed = |n: usize| format!("{}{}\n", nested_lists(n), ")".repeat(n + 1)); + assert!(parse(&format!("{H}{}", closed(MAX_NESTING)), None).is_ok()); + let e = parse(&format!("{H}{}", closed(MAX_NESTING + 1)), None).unwrap_err(); + assert!(e.message.contains("nest deeper"), "{e}"); + } + + #[test] + fn deeply_nested_clauses_are_an_error_not_a_stack_overflow() { + let e = bad(&nested_clauses(100_000)); + assert!(e.message.contains("nest deeper"), "{e}"); + // Header on line 1, form head on line 2, the clauses from line 3. + assert_eq!(e.line, 3); + } + + #[test] + fn deeply_nested_lists_are_an_error_not_a_stack_overflow() { + let e = bad(&nested_lists(100_000)); + assert!(e.message.contains("nest deeper"), "{e}"); + assert_eq!(e.line, 3); + // A quoted list counts the same. + let quoted = nested_lists(100_000).replacen(":l\n", ":l\n'", 1); + assert!(bad("ed).message.contains("nest deeper")); + } + + #[test] + fn clauses_and_lists_share_one_nesting_limit() { + // Half the limit in clauses plus half in lists fits; one more list + // level does not. + let half = MAX_NESTING / 2; + let deed = |lists: usize| { + format!( + "{}\n:l {}{}{}\n", + nested_clauses(half), + "(".repeat(lists), + ")".repeat(lists), + ")".repeat(half + 1) + ) + }; + assert!(parse(&format!("{H}{}", deed(MAX_NESTING - half)), None).is_ok()); + let e = parse(&format!("{H}{}", deed(MAX_NESTING - half + 1)), None).unwrap_err(); + assert!(e.message.contains("nest deeper"), "{e}"); + assert_eq!(e.line, 4); + } + + #[test] + fn the_nesting_error_names_the_line_of_the_offending_paren() { + let one_per_line = format!( + "(praxis-deed :schema-version \"1\"\n{}", + ["(c"; MAX_NESTING + 1].join("\n") + ); + // Header line 1, head line 2, clause k (1-based) on line k + 2. + assert_eq!(bad(&one_per_line).line, MAX_NESTING + 3); } #[test]