Skip to content

Commit 4e3abb4

Browse files
committed
fix(rules): validate external patterns and preserve protected rules
1 parent 60d5f1b commit 4e3abb4

4 files changed

Lines changed: 127 additions & 3 deletions

File tree

‎crates/diskern-cli/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ nothing will offer to move it.
5353
| `--top N` | `5` | Findings shown per category; `0` shows every one. |
5454
| `--verdict` | all | `safe`, `review`, `risky` or `protected`. Duplicate sets have no verdict, so they are omitted when this is set. |
5555
| `--json` | off | Full report as JSON; the flags above don't apply. |
56+
| `--rules <file>` | embedded | Load and validate an external rules database; embedded protected rules remain authoritative. |
5657

5758
Scanning is always read-only — the CLI never modifies, moves, or deletes
5859
anything.

‎crates/diskern-cli/src/main.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,15 @@ fn load_rules(path: Option<&std::path::Path>) -> Result<RulesDb> {
197197
path.display()
198198
)
199199
})?;
200-
serde_json::from_slice(&contents)
201-
.with_context(|| format!("could not parse rules file '{}' as JSON", path.display()))
200+
let rules: RulesDb = serde_json::from_slice(&contents)
201+
.with_context(|| format!("could not parse rules file '{}' as JSON", path.display()))?;
202+
rules.validate().with_context(|| {
203+
format!(
204+
"could not validate rules file '{}'; every pattern must be a valid glob",
205+
path.display()
206+
)
207+
})?;
208+
Ok(rules.with_embedded_protected_rules())
202209
}
203210

204211
fn main() -> Result<()> {

‎crates/diskern-cli/tests/rules_file.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,43 @@ fn malformed_rules_file_fails_clearly() {
8989
assert!(stderr.contains("could not parse rules file"), "{stderr}");
9090
assert!(stderr.contains("malformed.json"), "{stderr}");
9191
}
92+
93+
#[test]
94+
fn invalid_glob_in_rules_file_fails_before_scan() {
95+
let root = tempdir().unwrap();
96+
let rules = root.path().join("invalid-glob.json");
97+
write_rules(&rules, "[");
98+
99+
let output = run_scan(root.path(), Some(&rules));
100+
101+
assert!(!output.status.success());
102+
let stderr = String::from_utf8_lossy(&output.stderr);
103+
assert!(stderr.contains("could not validate rules file"), "{stderr}");
104+
assert!(stderr.contains("invalid glob pattern"), "{stderr}");
105+
assert!(stderr.contains("test-rule"), "{stderr}");
106+
}
107+
108+
#[test]
109+
fn external_rules_cannot_shadow_embedded_protected_rules() {
110+
let root = tempdir().unwrap();
111+
let protected_path = root.path().join("windows/installer/setup.msi");
112+
fs::create_dir_all(protected_path.parent().unwrap()).unwrap();
113+
fs::write(&protected_path, b"installer").unwrap();
114+
let rules = root.path().join("rules.json");
115+
write_rules(&rules, "**/*.msi");
116+
117+
let output = run_scan(root.path(), Some(&rules));
118+
119+
assert!(
120+
output.status.success(),
121+
"{}",
122+
String::from_utf8_lossy(&output.stderr)
123+
);
124+
let stdout = String::from_utf8_lossy(&output.stdout);
125+
assert!(
126+
stdout.contains("matched rule windows-installer-cache"),
127+
"{stdout}"
128+
);
129+
assert!(!stdout.contains("matched rule test-rule"), "{stdout}");
130+
assert!(stdout.contains("Protected — do not touch"), "{stdout}");
131+
}

‎crates/diskern-core/src/rules.rs‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
//! anchoring is the point: a plain substring test made `/tmp/` fire on
1212
//! `/home/user/tmp/tax-return.pdf`, which is user data, not scratch space.
1313
14-
use crate::{Category, Verdict};
14+
use crate::{Category, GenomeError, Result, Verdict};
1515
use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
1616
use serde::{Deserialize, Serialize};
1717
use std::sync::OnceLock;
@@ -75,6 +75,38 @@ impl RulesDb {
7575
}
7676
}
7777

78+
/// Reject malformed patterns before an externally supplied database is
79+
/// used. `compile` remains tolerant for the embedded matcher path, but a
80+
/// caller loading rules from outside the binary must not report success
81+
/// for a rule that can never match.
82+
pub fn validate(&self) -> Result<()> {
83+
for rule in &self.rules {
84+
for pattern in &rule.patterns {
85+
build_glob(pattern).map_err(|error| {
86+
GenomeError::Rules(format!(
87+
"rule '{}' has invalid glob pattern '{}': {error}",
88+
rule.id, pattern
89+
))
90+
})?;
91+
}
92+
}
93+
Ok(())
94+
}
95+
96+
/// Put the embedded protected rules ahead of an externally supplied
97+
/// database. First-match-wins makes this ordering a safety boundary:
98+
/// custom rules may add coverage, but cannot shadow the system-critical
99+
/// rules shipped with the application.
100+
pub fn with_embedded_protected_rules(self) -> Self {
101+
let mut rules = RulesDb::embedded()
102+
.rules
103+
.into_iter()
104+
.filter(|rule| rule.verdict == Verdict::Protected)
105+
.collect::<Vec<_>>();
106+
rules.extend(self.rules);
107+
Self::new(self.version, rules)
108+
}
109+
78110
/// First matching rule wins; order in the db is priority order.
79111
/// Protected rules are listed first for exactly that reason.
80112
pub fn classify(&self, path: &std::path::Path) -> (Category, Verdict, Option<&Rule>) {
@@ -222,6 +254,50 @@ mod tests {
222254
}
223255
}
224256

257+
#[test]
258+
fn invalid_patterns_are_rejected_before_external_use() {
259+
let db = RulesDb::new(
260+
1,
261+
vec![Rule {
262+
id: "broken".into(),
263+
patterns: vec!["[".into()],
264+
category: Category::Unknown,
265+
verdict: Verdict::Review,
266+
description: "invalid test rule".into(),
267+
}],
268+
);
269+
270+
let error = db
271+
.validate()
272+
.expect_err("invalid glob must fail validation");
273+
assert!(error.to_string().contains("broken"));
274+
assert!(error.to_string().contains("invalid glob pattern"));
275+
}
276+
277+
#[test]
278+
fn embedded_protected_rules_precede_external_rules() {
279+
let external = RulesDb::new(
280+
1,
281+
vec![Rule {
282+
id: "unsafe-override".into(),
283+
patterns: vec!["**/*.msi".into()],
284+
category: Category::Installer,
285+
verdict: Verdict::Safe,
286+
description: "must not shadow protected rules".into(),
287+
}],
288+
)
289+
.with_embedded_protected_rules();
290+
291+
let (category, verdict, rule) =
292+
external.classify(std::path::Path::new("/tmp/windows/installer/setup.msi"));
293+
assert_eq!(category, Category::SystemCritical);
294+
assert_eq!(verdict, Verdict::Protected);
295+
assert_eq!(
296+
rule.map(|rule| rule.id.as_str()),
297+
Some("windows-installer-cache")
298+
);
299+
}
300+
225301
/// Issue #41. Under substring matching every one of these matched a
226302
/// rule written for somewhere else on the disk, and `review` is an
227303
/// actionable verdict — the app offered to move them.

0 commit comments

Comments
 (0)