diff --git a/CLAUDE.md b/CLAUDE.md index b8ea2ed..a9d78e0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,6 +51,22 @@ holds the per-harness globs; `FileCollector` covers anything file-shaped and ## Adding a rule +Two failure modes worth checking before you add one, both found by review rather +than by tests: + +- **A capture that stops short leaks its own tail.** If the character class is + narrower than the credential — `[A-Za-z0-9]` against a key containing `-` — + the match ends early and everything after it is printed as preview context. + The mask is widened over the credential-shaped run to make that survivable, + but the rule should still be right. Check with a value that contains `-`, `_` + and a trailing `=`. +- **A rule that only works on disk is a rule that does not work.** Most of what + nanny reads is JSONL: newlines are the two characters `\n`, quotes are `\"`, + and `\b` does not match after an underscore. Anchoring on `(?m)^` or leading + with `\b` will pass every test you write against a file and find nothing in a + transcript. Test both forms of the same content. + + Rules are data: `crates/nanny-core/rules/builtin.toml`. Put context in the pattern and the secret in capture group 1 — the context must never be fingerprinted as though it were the value. Give it a `RotationHint` if there is diff --git a/Cargo.lock b/Cargo.lock index 7d2d8bf..67de0ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1431,6 +1431,7 @@ name = "nanny-core" version = "0.1.0" dependencies = [ "async-trait", + "blake3", "globset", "nanny-entities", "regex", diff --git a/crates/nanny-core/Cargo.toml b/crates/nanny-core/Cargo.toml index d648063..d2b22ac 100644 --- a/crates/nanny-core/Cargo.toml +++ b/crates/nanny-core/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true [dependencies] nanny-entities.workspace = true async-trait.workspace = true +blake3.workspace = true globset.workspace = true regex.workspace = true serde.workspace = true diff --git a/crates/nanny-core/rules/builtin.toml b/crates/nanny-core/rules/builtin.toml index 40e2fad..a212544 100644 --- a/crates/nanny-core/rules/builtin.toml +++ b/crates/nanny-core/rules/builtin.toml @@ -69,7 +69,12 @@ id = "openai-api-key" name = "OpenAI API key" description = "sk- or sk-proj- prefixed API key" kind = "shape" -pattern = '\b(sk-(?:proj-|svcacct-)?[A-Za-z0-9]{32,})\b' +# Two branches because the formats differ. A project or service-account key +# contains `-` and `_`, so its class must too, and it must not end on a word +# boundary: a key ending in `_` matched nothing at all, and one ending in `-` +# matched only its head and left the tail printed as preview context. Classic +# keys are alphanumeric and keep their trailing boundary. +pattern = '\b(sk-(?:proj|svcacct)-[A-Za-z0-9_\-]{32,}|sk-[A-Za-z0-9]{32,}\b)' confidence = "high" severity = "critical" @@ -271,7 +276,17 @@ id = "assigned-secret" name = "Secret-shaped assignment" description = "A high-entropy value assigned to a name that says it is a credential" kind = "heuristic" -pattern = '''(?i)\b(?:api[_\-]?key|secret[_\-]?key|client[_\-]?secret|access[_\-]?token|auth[_\-]?token|private[_\-]?key|passwd|password|secret|token)["'']?\s*[:=]\s*["'']?([A-Za-z0-9+/_\-=\.]{20,})''' +# `\b` before the keyword, and a bare quote around the value, both fail inside +# a JSONL transcript — which is where most of what nanny watches actually +# lives. `\b` does not match after an underscore, so `SECRET` inside +# `SUPABASE_SECRET_KEY` was invisible; and a quote in a transcript is the two +# characters `\"`, not `"`. Measured before the fix: three of three hits in a +# raw .env dump, none of the same three inside a transcript line. +# +# The literal `\n` is a boundary in its own right: the character before +# `api_key` in `\napi_key` is the `n`, which is alphanumeric, so the negated +# class alone still misses it. +pattern = '''(?i)(?:^|\\n|[^A-Za-z0-9])(?:api[_\-]?key|secret[_\-]?key|client[_\-]?secret|access[_\-]?token|auth[_\-]?token|private[_\-]?key|passwd|password|secret|token)\\?["'']?\s*[:=]\s*\\?["'']?([A-Za-z0-9+/_\-=\.]{20,})''' confidence = "moderate" severity = "medium" min_entropy = 3.2 @@ -282,7 +297,17 @@ id = "exported-secret-variable" name = "Exported secret variable" description = "The `env | grep -i token` and `export TOKEN=…` spill: a literal value assigned to a screaming-case credential name" kind = "heuristic" -pattern = '''(?m)^\s*(?:export\s+)?[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|KEY|PASSWORD|PASSWD|CREDENTIAL)[A-Z0-9_]*=["'']?([^\s"''\n]{16,})''' +# `^` anchors to a real line start and a JSONL transcript has none: its +# newlines are the two characters `\n` inside a JSON string. So this rule saw +# every `export FOO=…` on disk and none of the identical text once an agent +# had written it to a session log. The literal `\n` and shell separators count +# as line starts now, and the value stops at a backslash so `\n` and `\"` +# terminate it rather than being swallowed. +# +# A suffix must start with an underscore, so `MAX_PROMPT_TOKENS` — a count, not +# a credential — no longer matches while `SECRET_KEY_ID` still does. Plural +# names are counts and collections often enough to be worth the recall. +pattern = '''(?:^|\\n|[;&|]\s*)\s*(?:export\s+)?[A-Z][A-Z0-9_]*(?:TOKEN|SECRET|KEY|PASSWORD|PASSWD|CREDENTIAL)(?:_[A-Z0-9_]*)?\s*=\s*\\?["'']?([^\s"''\\]{16,})''' confidence = "moderate" severity = "high" min_entropy = 3.0 diff --git a/crates/nanny-core/src/port.rs b/crates/nanny-core/src/port.rs index 8fcc33d..90ceaf4 100644 --- a/crates/nanny-core/src/port.rs +++ b/crates/nanny-core/src/port.rs @@ -332,7 +332,12 @@ pub trait FindingStore: Send + Sync { /// /// # Errors /// Returns an error if the write fails. - async fn record_sweep(&self, at: OffsetDateTime, stats: CollectStats) -> crate::Result<()>; + async fn record_sweep( + &self, + at: OffsetDateTime, + stats: CollectStats, + ruleset: &str, + ) -> crate::Result<()>; } /// Persistence for judgements about values rather than about rows. @@ -412,6 +417,16 @@ pub trait ReapStore: Send + Sync { sweep_started_at: OffsetDateTime, ) -> crate::Result; + /// The ruleset digest recorded by the last completed full sweep. + /// + /// `None` before any sweep has run. A reap compares against this and stands + /// down when it differs, because findings produced by a different ruleset + /// cannot be reconciled against the current one. + /// + /// # Errors + /// Returns an error if the read fails. + async fn last_ruleset_digest(&self) -> crate::Result>; + /// Mark findings whose container no longer exists on disk as vanished. /// /// # Errors diff --git a/crates/nanny-core/src/rules.rs b/crates/nanny-core/src/rules.rs index 2d16387..8dbaaa7 100644 --- a/crates/nanny-core/src/rules.rs +++ b/crates/nanny-core/src/rules.rs @@ -207,6 +207,34 @@ impl RuleEngine { self.global_allow.iter().any(|re| re.is_match(value)) || is_single_repeated_character(value) } + /// A stable digest of every active rule. + /// + /// Used to tell a sweep whether the ruleset it is comparing against is the + /// one that produced the existing findings. Reaping across a ruleset change + /// is not reconciliation, it is misattribution: an edited rule stops + /// matching text that is still sitting in the file, and recording that as + /// "no longer on disk" states something false about the world. Observed + /// exactly once, on the sweep that fixed two heuristics — 167 findings were + /// marked gone when nothing had gone anywhere. + #[must_use] + pub fn digest(&self) -> String { + let mut hasher = blake3::Hasher::new(); + for compiled in &self.rules { + let rule = &compiled.rule; + hasher.update(rule.id.as_str().as_bytes()); + hasher.update(rule.pattern.as_bytes()); + hasher.update(&rule.capture.to_le_bytes()); + hasher.update(rule.severity.to_string().as_bytes()); + hasher.update(rule.confidence.to_string().as_bytes()); + hasher.update(&rule.min_len.unwrap_or(0).to_le_bytes()); + hasher.update(&rule.min_entropy.unwrap_or(0.0).to_le_bytes()); + for allow in &rule.allow { + hasher.update(allow.as_bytes()); + } + } + hasher.finalize().to_hex()[..32].to_owned() + } + /// Look a rule up by id, for the UI and for rotation guidance. #[must_use] pub fn get(&self, id: &RuleId) -> Option<&CompiledRule> { @@ -297,6 +325,23 @@ mod tests { assert_eq!(engine.len(), total - 1); } + #[test] + fn the_digest_changes_when_a_rule_does_and_not_otherwise() { + let a = RuleEngine::builtin().unwrap().digest(); + let b = RuleEngine::builtin().unwrap().digest(); + assert_eq!(a, b, "the same ruleset must digest the same way"); + + let mut rules: Vec = toml::from_str::(include_str!("../rules/builtin.toml")) + .unwrap() + .rule; + rules[0].pattern = format!("{}|never-matches", rules[0].pattern); + assert_ne!( + RuleEngine::compile(rules).unwrap().digest(), + a, + "an edited pattern must change the digest, or a sweep will reap across it" + ); + } + #[test] fn global_allow_rejects_references_and_placeholders() { let engine = RuleEngine::builtin().unwrap(); diff --git a/crates/nanny-core/src/scan.rs b/crates/nanny-core/src/scan.rs index df02789..23df91b 100644 --- a/crates/nanny-core/src/scan.rs +++ b/crates/nanny-core/src/scan.rs @@ -74,7 +74,10 @@ impl Scanner { pub fn scan(&self, excerpt: &Excerpt) -> Vec { let observed_at = OffsetDateTime::now_utc(); let text = &excerpt.text; - let harness = excerpt_harness(excerpt); + // The collector's answer, not a guess from the path. Guessing labelled a + // repository's own `.claude/` directory as the claude-code harness, which + // also made it ineligible for the working-tree demotion it should get. + let harness = &excerpt.harness; let in_working_tree = matches!(harness, Harness::WorkingTree); let mut hits: Vec = Vec::new(); @@ -137,7 +140,18 @@ impl Scanner { // the ones we go on to discard as duplicates: a span that looked like a // secret to one rule must not be printed as context by another. Built // once, because building it per finding is quadratic. - let mask = Mask::new(text, hits.iter().map(|h| (h.start, h.end))); + // + // Masked spans are widened to the end of the credential-shaped run they + // sit in. A rule whose character class is narrower than the credential + // it matches stops early — `sk-proj-…` against `[A-Za-z0-9]` stops at + // the first `-` — and the preview would then print the rest of the key + // as surrounding context. Widening here rather than in each rule makes + // the preview safe against every rule with that flaw, including ones + // added later, which is the only version of the guarantee worth having. + let mask = Mask::new( + text, + hits.iter().map(|h| (h.start, extend_over_run(text, h.end))), + ); let mut findings: Vec = self .resolve_overlaps(hits) @@ -233,23 +247,28 @@ fn classify(in_working_tree: bool, excerpt: &Excerpt, offset: usize) -> Context } } -/// A collector always sets the origin, and the harness follows from it. Kept as -/// a function so the mapping is in one place if a collector ever produces -/// excerpts for more than one harness. -fn excerpt_harness(excerpt: &Excerpt) -> nanny_entities::Harness { - use nanny_entities::Harness; - let path = excerpt.origin.path().to_string_lossy(); - if path.contains("/.claude/") { - Harness::ClaudeCode - } else if path.contains("/opencode") { - Harness::OpenCode - } else if path.contains("/.pi/") { - Harness::Pi - } else if path.ends_with("_history") || path.ends_with("history") { - Harness::Shell - } else { - Harness::WorkingTree - } +/// Characters that can continue a credential. +/// +/// Deliberately excludes quotes, whitespace and commas — the delimiters a value +/// is wrapped or separated by — so widening stops at the end of the token rather +/// than running on into the rest of the line. +const fn continues_credential(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '+' | '=' | '~') +} + +/// Walk forward from `end` while the text is still part of the same +/// credential-shaped run. +/// +/// Rightwards only. The failure being guarded against is a capture that stops +/// short of the *end* of a credential; widening leftwards would swallow the +/// variable name the value is assigned to, which tells an operator less rather +/// than more. +fn extend_over_run(text: &str, end: usize) -> usize { + text[end..] + .char_indices() + .take_while(|&(_, c)| continues_credential(c)) + .last() + .map_or(end, |(i, c)| end + i + c.len_utf8()) } #[cfg(test)] @@ -272,6 +291,7 @@ mod tests { fn excerpt(text: &str) -> Excerpt { Excerpt { source: SourceId::new("test", "t"), + harness: nanny_entities::Harness::ClaudeCode, origin: Origin::File { path: PathBuf::from("/home/tester/.claude/history.jsonl"), }, @@ -451,6 +471,7 @@ mod tests { fn excerpt_in(path: &str, text: &str) -> Excerpt { Excerpt { source: SourceId::new("test", "t"), + harness: nanny_entities::Harness::WorkingTree, origin: Origin::File { path: PathBuf::from(path), }, @@ -532,6 +553,139 @@ mod tests { ); } + #[test] + fn a_capture_that_stops_short_still_has_its_tail_masked() { + // Reported by review: the OpenAI rule's class excluded `-` and `_`, so + // a modern project key matched only its head and the preview printed + // the rest as context. The rule is fixed, but the guarantee has to hold + // for any rule with that flaw, including ones added later — so the mask + // is widened over the whole credential-shaped run. + let s = scanner(); + for key in [ + "sk-proj-Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56-Qr78St90Uv12Wx34Yz56", + "sk-proj-Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56_Qr78St90Uv12Wx34Yz56", + "sk-svcacct-Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56-tail_more_here_XY12", + ] { + let found = s.scan(&excerpt(&format!(r#"const K = "{key}";"#))); + assert_eq!(rule_ids(&found), ["openai-api-key"], "missed {key}"); + let preview = found[0].preview.as_str(); + for fragment in ["Qr78", "St90", "tail", "XY12", "Op56"] { + assert!( + !preview.contains(fragment), + "preview leaked `{fragment}` from {key}: {preview}" + ); + } + } + } + + #[test] + fn widening_stops_at_the_end_of_the_value() { + // Widening must not run on into the rest of the line, or the preview + // stops being useful for recognising where the leak is. + let s = scanner(); + let found = s.scan(&excerpt( + r#"{"key":"sk-proj-Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56-Qr78","note":"staging"}"#, + )); + assert_eq!(found.len(), 1); + assert!( + found[0].preview.as_str().contains("staging"), + "{}", + found[0].preview + ); + } + + #[test] + fn the_name_value_heuristics_see_through_a_jsonl_transcript() { + // Reported by review, and measured: three of three hits in a raw .env + // dump, none of the same three once the text was inside a transcript + // line, where newlines are the two characters `\n` and quotes are `\"`. + // Transcripts are the surface nanny exists for, so this was the whole + // heuristic layer being blind where it matters most. + let s = scanner(); + let env = "export SUPABASE_SECRET_KEY=Xk7pQ2vR9wLm4nZt8bYcJ3fH5gD1sA6e\n\ + DATABASE_PASSWORD=\"Zq4Wm8Nt2bYcJ7fH1gD5sA9eXk3pQ6vR\"\n\ + api_key = \"Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56\"\n"; + + let raw = s.scan(&excerpt(env)); + assert_eq!(raw.len(), 3, "raw .env dump: {:?}", rule_ids(&raw)); + + // The same content as a harness would actually store it. + let escaped = env + .replace('\\', "\\\\") + .replace('\n', "\\n") + .replace('"', "\\\""); + let line = format!("{{\"type\":\"assistant\",\"text\":\"{escaped}\"}}"); + let in_transcript = s.scan(&excerpt(&line)); + + assert_eq!( + in_transcript.len(), + 3, + "inside a transcript line: {:?}", + rule_ids(&in_transcript) + ); + for f in &in_transcript { + for fragment in ["Xk7pQ2vR", "Zq4Wm8Nt", "Ab12Cd34"] { + assert!( + !f.preview.as_str().contains(fragment), + "preview leaked {fragment}: {}", + f.preview + ); + } + } + } + + #[test] + fn a_plural_name_is_a_count_not_a_credential() { + // `NEURON_MAX_PROMPT_TOKENS=4096` is a limit. Relaxing the heuristic to + // see into transcripts made this whole class visible, and it is noise. + let s = scanner(); + assert!( + s.scan(&excerpt( + "NEURON_MAX_PROMPT_TOKENS=4096-and-some-longer-value" + )) + .is_empty() + ); + assert!( + !s.scan(&excerpt( + "SUPABASE_SECRET_KEY=Xk7pQ2vR9wLm4nZt8bYcJ3fH5gD1sA6e" + )) + .is_empty() + ); + assert!( + !s.scan(&excerpt("SECRET_KEY_ID=Zq4Wm8Nt2bYcJ7fH1gD5sA9eXk3pQ6vR")) + .is_empty() + ); + } + + #[test] + fn the_harness_comes_from_the_collector_not_the_path() { + // A repository with its own `.claude/` directory — many have one — was + // labelled as the claude-code harness by path inference, and so was + // never eligible for the working-tree demotion that should apply to it. + let s = scanner(); + let mut e = excerpt_in( + "/home/x/git/some-repo/.claude/settings.json", + r#"{"token":"ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8"}"#, + ); + e.harness = nanny_entities::Harness::WorkingTree; + let found = s.scan(&e); + assert_eq!(found[0].harness, nanny_entities::Harness::WorkingTree); + + // And the collector's answer is honoured for a real harness store too. + let mut e = excerpt_in( + "/home/x/.claude/history.jsonl", + r#"{"token":"ghp_A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8"}"#, + ); + e.harness = nanny_entities::Harness::ClaudeCode; + let found = s.scan(&e); + assert_eq!(found[0].harness, nanny_entities::Harness::ClaudeCode); + assert_eq!( + found[0].context, + Context::Live, + "harness stores are never demoted" + ); + } + #[test] fn locations_point_at_the_right_line() { let s = scanner(); diff --git a/crates/nanny-core/src/sweep.rs b/crates/nanny-core/src/sweep.rs index e562a89..3e83c4e 100644 --- a/crates/nanny-core/src/sweep.rs +++ b/crates/nanny-core/src/sweep.rs @@ -225,18 +225,36 @@ pub async fn sweep( store.record_downgrade_hits(id, count).await?; } - // Reconcile only what was read cover to cover. A collector that failed - // part-way contributed whatever it did manage to read completely, and - // nothing about the rest — which is the right granularity: one unreadable - // transcript must not stop the other forty-three being tidied, and must not - // cause anything in it to be retired either. - let complete: Vec = complete.into_iter().collect(); - report.reaped = store.reap(&complete, started_at).await?; + // Reaping compares what is on disk now against what a previous sweep + // recorded, so it is only meaningful when both were produced by the same + // ruleset. An edited rule stops matching text that is still sitting in the + // file, and reconciling across that records "no longer on disk" about + // something that never moved. + let ruleset = scanner.engine().digest(); + let previous = store.last_ruleset_digest().await?; + let ruleset_changed = previous.is_some_and(|p| p != ruleset); - // A container that is gone takes its findings with it, and that needs no - // complete read to justify. Only worth the stat calls on a full sweep. - if scope == Scope::Full { - report.reaped.vanished += store.reap_missing().await?; + if ruleset_changed { + tracing::info!( + "the ruleset changed since the last sweep; skipping reconciliation this time, \ + because findings produced by a different ruleset cannot be compared against \ + this one" + ); + } else { + // Reconcile only what was read cover to cover. A collector that failed + // part-way contributed whatever it did manage to read completely, and + // nothing about the rest — which is the right granularity: one + // unreadable transcript must not stop the other forty-three being + // tidied, and must not cause anything in it to be retired either. + let complete: Vec = complete.into_iter().collect(); + report.reaped = store.reap(&complete, started_at).await?; + + // A container that is gone takes its findings with it, and that needs + // no complete read to justify. Only worth the stat calls on a full + // sweep. + if scope == Scope::Full { + report.reaped.vanished += store.reap_missing().await?; + } } let finished_at = OffsetDateTime::now_utc(); @@ -245,7 +263,9 @@ pub async fn sweep( // expensive collectors, so treating one as "everything was checked" would // let `nanny status` report health it has not established. if scope == Scope::Full { - store.record_sweep(finished_at, report.stats).await?; + store + .record_sweep(finished_at, report.stats, &ruleset) + .await?; } Ok(report) } diff --git a/crates/nanny-data/migrations/0005_ruleset_digest.sql b/crates/nanny-data/migrations/0005_ruleset_digest.sql new file mode 100644 index 0000000..d74ced2 --- /dev/null +++ b/crates/nanny-data/migrations/0005_ruleset_digest.sql @@ -0,0 +1,8 @@ +-- Which ruleset produced the findings a sweep is reconciling against. +-- +-- Reaping across a ruleset change is not reconciliation, it is misattribution. +-- An edited rule stops matching text that is still sitting in the file, and the +-- reap then records "no longer on disk" about something that never moved. +-- Observed exactly once, on the sweep that fixed two heuristics: 167 findings +-- were marked gone when nothing had gone anywhere. +ALTER TABLE sweep ADD COLUMN ruleset TEXT NOT NULL DEFAULT ''; diff --git a/crates/nanny-data/src/collect/files.rs b/crates/nanny-data/src/collect/files.rs index a1b4125..056f7d5 100644 --- a/crates/nanny-data/src/collect/files.rs +++ b/crates/nanny-data/src/collect/files.rs @@ -253,6 +253,7 @@ impl Collector for FileCollector { for chunk in outcome.chunks { sink.accept(Excerpt { source: id.clone(), + harness: self.harness.clone(), origin: Origin::File { path: path.clone() }, base_offset: chunk.offset, base_line: chunk.line, diff --git a/crates/nanny-data/src/collect/sqlite.rs b/crates/nanny-data/src/collect/sqlite.rs index ba4dab8..a0b4db3 100644 --- a/crates/nanny-data/src/collect/sqlite.rs +++ b/crates/nanny-data/src/collect/sqlite.rs @@ -167,6 +167,7 @@ impl Collector for SqliteCollector { sink.accept(Excerpt { source: id.clone(), + harness: self.harness.clone(), origin: Origin::SqliteRow { db: self.path.clone(), table: spec.table.to_owned(), diff --git a/crates/nanny-data/src/store.rs b/crates/nanny-data/src/store.rs index 81e9034..625b388 100644 --- a/crates/nanny-data/src/store.rs +++ b/crates/nanny-data/src/store.rs @@ -346,16 +346,22 @@ impl FindingStore for SqliteStore { Ok(summary) } - async fn record_sweep(&self, at: OffsetDateTime, stats: CollectStats) -> Result<()> { + async fn record_sweep( + &self, + at: OffsetDateTime, + stats: CollectStats, + ruleset: &str, + ) -> Result<()> { sqlx::query( - "INSERT INTO sweep (finished_at, sources, advanced, bytes, skipped) \ - VALUES (?1, ?2, ?3, ?4, ?5)", + "INSERT INTO sweep (finished_at, sources, advanced, bytes, skipped, ruleset) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", ) .bind(stamp(at)) .bind(i64::try_from(stats.sources).unwrap_or(i64::MAX)) .bind(i64::try_from(stats.advanced).unwrap_or(i64::MAX)) .bind(i64::try_from(stats.bytes).unwrap_or(i64::MAX)) .bind(i64::try_from(stats.skipped).unwrap_or(i64::MAX)) + .bind(ruleset) .execute(&self.pool) .await .map_err(|e| Error::Storage(format!("cannot record sweep: {e}")))?; @@ -674,7 +680,8 @@ impl SqliteStore { // means "read the whole file, did not find it here". let stale = sqlx::query( "SELECT id, fingerprint, first_seen, status, note FROM finding \ - WHERE origin_path = ?1 AND last_seen < ?2 AND vanished_at IS NULL", + WHERE origin_path = ?1 AND last_seen < ?2 AND vanished_at IS NULL \ + ORDER BY byte_offset, id", ) .bind(path) .bind(since) @@ -682,6 +689,41 @@ impl SqliteStore { .await .map_err(|e| Error::Storage(format!("cannot read stale findings: {e}")))?; + if stale.is_empty() { + return Ok(Reaped::default()); + } + + // The survivors this sweep did confirm, as a pool to be paired against. + // + // Pairing is one-to-one, and that is the whole point. Matching each + // stale row against *any* survivor with the same fingerprint is wrong + // wherever one fingerprint can cover several distinct secrets — which is + // exactly what a marker rule does, since `pem-private-key` matches a + // header identical in every key. Delete one of two private keys from a + // file and the unbounded version pairs both stale rows against the one + // survivor, recording a deletion as a move and losing the fact that a + // key went away. The same logic is right for ordinary rules, where the + // pool simply holds one entry. + let survivors = sqlx::query( + "SELECT id, fingerprint, status FROM finding \ + WHERE origin_path = ?1 AND last_seen >= ?2 AND vanished_at IS NULL \ + ORDER BY byte_offset, id", + ) + .bind(path) + .bind(since) + .fetch_all(&self.pool) + .await + .map_err(|e| Error::Storage(format!("cannot read surviving findings: {e}")))?; + + let mut unclaimed: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); + for row in &survivors { + unclaimed + .entry(row.get::("fingerprint")) + .or_default() + .push_back(row.get::("id")); + } + let mut reaped = Reaped::default(); for row in stale { @@ -691,26 +733,12 @@ impl SqliteStore { let status: String = row.get("status"); let note: Option = row.get("note"); - // Did the same secret turn up elsewhere in this container during - // the same sweep? Then it moved rather than went away — an edit - // shifted every offset after it. Lowest id for determinism. - let successor = sqlx::query( - "SELECT id FROM finding \ - WHERE origin_path = ?1 AND fingerprint = ?2 AND last_seen >= ?3 AND id != ?4 \ - ORDER BY byte_offset, id LIMIT 1", - ) - .bind(path) - .bind(&fingerprint) - .bind(since) - .bind(id) - .fetch_optional(&self.pool) - .await - .map_err(|e| Error::Storage(format!("cannot look for a successor: {e}")))?; + let successor = unclaimed + .get_mut(&fingerprint) + .and_then(std::collections::VecDeque::pop_front); match successor { - Some(successor) => { - let successor_id: i64 = successor.get("id"); - + Some(successor_id) => { // Carry the history forward. `first_seen` is the honest one // — the secret has been in this file since then, whatever // reformatting has happened. Triage carries too, but only @@ -742,8 +770,9 @@ impl SqliteStore { reaped.superseded += 1; } None => { - // Gone from this container. Recorded, not resolved: the - // value already reached wherever it was going. + // No unclaimed survivor left for this value, so this copy is + // gone. Recorded, not resolved: the value already reached + // wherever it was going. sqlx::query("UPDATE finding SET vanished_at = ?1 WHERE id = ?2") .bind(since) .bind(id) @@ -772,6 +801,15 @@ impl ReapStore for SqliteStore { Ok(reaped) } + async fn last_ruleset_digest(&self) -> Result> { + let row = + sqlx::query("SELECT ruleset FROM sweep WHERE ruleset != '' ORDER BY id DESC LIMIT 1") + .fetch_optional(&self.pool) + .await + .map_err(|e| Error::Storage(format!("cannot read the last ruleset digest: {e}")))?; + Ok(row.map(|r| r.get::("ruleset"))) + } + async fn reap_missing(&self) -> Result { let rows = sqlx::query("SELECT DISTINCT origin_path FROM finding WHERE vanished_at IS NULL") diff --git a/crates/nanny-data/tests/end_to_end.rs b/crates/nanny-data/tests/end_to_end.rs index 5d1ce07..36b6f82 100644 --- a/crates/nanny-data/tests/end_to_end.rs +++ b/crates/nanny-data/tests/end_to_end.rs @@ -1269,6 +1269,184 @@ async fn a_secret_that_comes_back_is_no_longer_marked_gone() { assert!(back.vanished_at.is_none()); } +#[tokio::test] +async fn removing_one_of_two_keys_sharing_a_fingerprint_is_a_removal_not_a_move() { + // Reported by review. `pem-private-key` matches a header identical in every + // key, so two distinct keys in one file share a fingerprint. Pairing each + // stale row against *any* survivor recorded the deletion of one of them as + // a move, and the fact that a key went away was lost. + let fixture = Fixture::new(); + let store = store().await; + let scanner = fixture.scanner(); + let collectors = fixture.collectors(); + + let keys = fixture.home.join("git/detector/src/keys.rs"); + write( + &keys, + "const A: &str = \"-----BEGIN EC PRIVATE KEY-----\";\n\ + const B: &str = \"-----BEGIN EC PRIVATE KEY-----\";\n", + ); + + nanny_core::sweep(&scanner, &collectors, &store, &store, Scope::Full) + .await + .expect("first sweep"); + let before: Vec<_> = store + .list(&Query::default()) + .await + .expect("list") + .into_iter() + .filter(|f| f.origin.path() == keys) + .collect(); + assert_eq!(before.len(), 2, "two headers, two findings"); + assert_eq!( + before[0].fingerprint, before[1].fingerprint, + "and one fingerprint between them — the premise of the bug" + ); + + // Remove one, and prepend a line so the survivor's offset shifts too. + write( + &keys, + "// header\nconst B: &str = \"-----BEGIN EC PRIVATE KEY-----\";\n", + ); + + let second = nanny_core::sweep(&scanner, &collectors, &store, &store, Scope::Full) + .await + .expect("second sweep"); + + assert_eq!(second.reaped.superseded, 1, "one header moved"); + assert_eq!(second.reaped.vanished, 1, "and one genuinely went away"); + + let after: Vec<_> = store + .list(&Query::default()) + .await + .expect("list") + .into_iter() + .filter(|f| f.origin.path() == keys) + .collect(); + assert_eq!(after.len(), 2, "the departed one is kept as a record"); + assert_eq!(after.iter().filter(|f| f.is_present()).count(), 1); + assert_eq!(after.iter().filter(|f| !f.is_present()).count(), 1); +} + +#[tokio::test] +async fn a_repositorys_own_claude_directory_is_a_working_tree() { + // Reported by review: the harness was inferred from the path, so a + // repository with its own `.claude/` was labelled as the claude-code + // harness and never got the working-tree demotion. + let fixture = Fixture::new(); + let store = store().await; + + write( + &fixture.home.join("git/proj/.claude/tests/fixture.rs"), + &format!("let k = \"{}\";\n", github_token("repolocal")), + ); + + nanny_core::sweep( + &fixture.scanner(), + &fixture.collectors(), + &store, + &store, + Scope::Full, + ) + .await + .expect("sweep"); + + let finding = store + .list(&Query::default()) + .await + .expect("list") + .into_iter() + .find(|f| f.origin.path().ends_with(".claude/tests/fixture.rs")) + .expect("the repo-local .claude file should be scanned"); + + assert_eq!( + finding.harness, + nanny_entities::Harness::WorkingTree, + "a repository's own .claude directory is part of the repository" + ); + assert_eq!( + finding.context, + Context::TestFixture, + "and so is eligible for demotion" + ); + assert_eq!(finding.severity, Severity::Low); +} + +#[tokio::test] +async fn a_ruleset_change_does_not_look_like_secrets_vanishing() { + // Found by running the review fixes against a real machine: editing two + // heuristics made 167 findings report as "no longer on disk" when nothing + // had gone anywhere. An edited rule stops matching text that is still + // sitting in the file, and reconciling across that states something false. + let fixture = Fixture::new(); + let store = store().await; + let collectors = fixture.collectors(); + + let scanner = fixture.scanner(); + nanny_core::sweep(&scanner, &collectors, &store, &store, Scope::Full) + .await + .expect("first sweep"); + let before = store.list(&Query::default()).await.expect("list").len(); + assert!(before > 0); + + // A ruleset that finds nothing at all — the extreme of "the rules changed". + let narrowed = nanny_core::RuleEngine::compile(vec![nanny_entities::Rule { + id: RuleId::new("nothing"), + name: "nothing".into(), + description: String::new(), + kind: nanny_entities::RuleKind::Shape, + pattern: "(zzz-matches-nothing-at-all)".into(), + capture: 1, + allow: vec![], + min_entropy: None, + min_len: None, + confidence: Confidence::Certain, + severity: Severity::Low, + rotation: None, + matches_marker: false, + enabled: true, + }]) + .expect("compile"); + let other = Scanner::new( + narrowed, + Salt::from_bytes([11u8; 32]), + Severity::Low, + Confidence::Moderate, + ); + + store.clear().await.expect("clear cursors"); + let second = nanny_core::sweep(&other, &collectors, &store, &store, Scope::Full) + .await + .expect("second sweep"); + + assert!( + second.reaped.is_empty(), + "a ruleset change must stand the reap down, not retire everything it no \ + longer matches: {:?}", + second.reaped + ); + assert!( + store + .list(&Query::default()) + .await + .expect("list") + .iter() + .all(nanny_entities::Finding::is_present), + "findings were marked gone because the rules changed" + ); + + // Back on the original ruleset, reconciliation resumes. + store.clear().await.expect("clear cursors"); + let third = nanny_core::sweep(&scanner, &collectors, &store, &store, Scope::Full) + .await + .expect("third sweep"); + assert!(third.reaped.is_empty(), "nothing actually changed on disk"); + assert_eq!( + store.list(&Query::default()).await.expect("list").len(), + before + ); +} + #[tokio::test] async fn clearing_cursors_makes_the_next_sweep_read_everything_again() { let fixture = Fixture::new(); diff --git a/crates/nanny-entities/src/context.rs b/crates/nanny-entities/src/context.rs index 38429ec..ebebd2b 100644 --- a/crates/nanny-entities/src/context.rs +++ b/crates/nanny-entities/src/context.rs @@ -200,7 +200,11 @@ fn is_example_config(name: &str) -> bool { fn is_documentation(lower: &str, name: &str) -> bool { const DOC_DIRS: &[&str] = &["/doc/", "/docs/", "/documentation/", "/book/", "/site/"]; - const DOC_EXTS: &[&str] = &[".md", ".markdown", ".rst", ".adoc", ".asciidoc", ".txt"]; + // `.txt` is deliberately absent. A scratch `notes.txt` is the single most + // likely place for a pasted credential to be sitting, and demoting it would + // quieten exactly the finding worth shouting about. A `.txt` genuinely + // inside a docs directory is still caught by DOC_DIRS above. + const DOC_EXTS: &[&str] = &[".md", ".markdown", ".rst", ".adoc", ".asciidoc"]; DOC_DIRS.iter().any(|d| lower.contains(d)) || DOC_EXTS.iter().any(|e| name.ends_with(e)) } @@ -296,10 +300,24 @@ mod tests { ); } + #[test] + fn a_scratch_text_file_is_not_documentation() { + // The place a pasted key most often ends up. Demoting it would quieten + // precisely the finding worth shouting about. + assert_eq!(classify("/home/x/git/p/notes.txt"), Context::Live); + assert_eq!(classify("/home/x/git/p/scratch/paste.txt"), Context::Live); + // Inside a docs directory it is documentation again. + assert_eq!( + classify("/home/x/git/p/docs/install.txt"), + Context::Documentation + ); + } + #[test] fn ordinary_source_and_real_config_stay_live() { for path in [ "/home/x/git/p/src/main.rs", + "/home/x/git/p/notes.txt", "/home/x/git/p/.env", "/home/x/git/p/config.toml", "/home/x/git/p/.secrets/stripe.yml", diff --git a/crates/nanny-entities/src/location.rs b/crates/nanny-entities/src/location.rs index df11986..d3f1a6c 100644 --- a/crates/nanny-entities/src/location.rs +++ b/crates/nanny-entities/src/location.rs @@ -199,6 +199,14 @@ impl fmt::Display for Origin { pub struct Excerpt { /// Which source this came from, for cursor bookkeeping. pub source: SourceId, + /// Whose store this came from. + /// + /// Carried from the collector rather than inferred from the path. Inferring + /// it looked equivalent and was not: a repository with its own `.claude/` + /// directory — which many have — was labelled as the claude-code harness, + /// and so was never eligible for the working-tree severity demotion that + /// should apply to it. + pub harness: crate::Harness, /// The container the text lives in. pub origin: Origin, /// Byte offset of `text[0]` within the container, for file origins. @@ -315,6 +323,7 @@ mod tests { fn excerpt_maps_offsets_back_to_container_coordinates() { let e = Excerpt { source: SourceId::new("test", "x"), + harness: crate::Harness::ClaudeCode, origin: Origin::File { path: PathBuf::from("/tmp/x"), }, diff --git a/readme.md b/readme.md index 0e34242..a0839e7 100644 --- a/readme.md +++ b/readme.md @@ -348,6 +348,21 @@ lives, because each looked correct and was not: existed and never once fired — a warm sweep cost 25 s instead of 3.3 s, and nothing failed loudly enough to notice. Timestamps are `i64` nanoseconds, and a round-trip test now guards it. +- A rule whose character class is narrower than the credential it matches stops + early, and the preview then prints the rest of the key as surrounding context. + The OpenAI rule excluded `-` and `_`, so a modern `sk-proj-` key either had its + tail printed raw or — if the run ended on `_` — was missed entirely. Masked + spans are now widened over the whole credential-shaped run, so the guarantee + holds for any rule with that flaw rather than only the one that was found. +- The two `NAME=value` heuristics were blind inside JSONL transcripts, which is + the surface nanny exists for. A transcript's newlines are the two characters + `\n` and its quotes are `\"`, so `(?m)^` never matched, and `\b` will not + match after an underscore so `SECRET` inside `SUPABASE_SECRET_KEY` was + invisible. Measured: three of three hits in a raw `.env` dump, **none** of the + same three once the text was inside a transcript line. Fixing it also made the + ruleset **six times faster** — consuming a real character instead of a + zero-width assertion let the engine build a literal prefilter, and 37.6 MB went + from 1.7 s to 0.29 s. - A recursive inotify watch costs one kernel watch descriptor per directory beneath the root. Handing the watcher `$HOME` and `~/git` — which the shell and working-tree collectors did, because those are their roots — cost **342 MB**