Skip to content

Commit fc0378d

Browse files
Merge pull request #78 from alexsmolya/codex/issue-68-rules-file
feat(cli): load rules database from file
2 parents 5fb7d99 + 4e3abb4 commit fc0378d

7 files changed

Lines changed: 250 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ All notable changes to Diskern are documented here. The format follows
88

99
### Added
1010

11+
- `diskern scan --rules <file>` to test scans with an external rules database
1112
- Cancel a running scan from the desktop app
1213
- `diskern scan` prints the findings themselves — grouped by verdict and
1314
category, with `--top` to cap each group and `--verdict` to filter

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/diskern-cli/Cargo.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,6 @@ diskern-core = { path = "../diskern-core" }
1616
anyhow.workspace = true
1717
serde_json.workspace = true
1818
clap = { version = "4", features = ["derive"] }
19+
20+
[dev-dependencies]
21+
tempfile = "3"

‎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: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::Result;
1+
use anyhow::{Context, Result};
22
use clap::{Parser, Subcommand, ValueEnum};
33
use diskern_core::{report, rules::RulesDb, scanner, Category, Finding, Verdict};
44
use std::path::PathBuf;
@@ -29,6 +29,9 @@ enum Command {
2929
/// Only show findings with this verdict
3030
#[arg(long, value_enum)]
3131
verdict: Option<VerdictFilter>,
32+
/// Load rules from a JSON file instead of the embedded database
33+
#[arg(long, value_name = "FILE")]
34+
rules: Option<PathBuf>,
3235
},
3336
}
3437

@@ -183,6 +186,28 @@ fn print_findings(findings: &[&Finding], top: usize) {
183186
}
184187
}
185188

189+
fn load_rules(path: Option<&std::path::Path>) -> Result<RulesDb> {
190+
let Some(path) = path else {
191+
return Ok(RulesDb::embedded());
192+
};
193+
194+
let contents = std::fs::read(path).with_context(|| {
195+
format!(
196+
"could not read rules file '{}'; check that it exists and is readable",
197+
path.display()
198+
)
199+
})?;
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())
209+
}
210+
186211
fn main() -> Result<()> {
187212
let cli = Cli::parse();
188213
match cli.command {
@@ -191,19 +216,28 @@ fn main() -> Result<()> {
191216
json,
192217
top,
193218
verdict,
219+
rules,
194220
} => {
221+
let external_rules = rules.as_deref();
222+
let rules_db = load_rules(external_rules)?;
195223
let opts = scanner::ScanOptions {
196224
roots,
197225
..Default::default()
198226
};
199227
let progress = Arc::new(scanner::ScanProgress::default());
200228
let entries = scanner::scan(&opts, progress)?;
201-
let report = report::build(entries, &RulesDb::embedded());
229+
let report = report::build(entries, &rules_db);
202230

203231
if json {
232+
if let Some(path) = external_rules {
233+
eprintln!("Using external rules database: {}", path.display());
234+
}
204235
println!("{}", serde_json::to_string_pretty(&report)?);
205236
} else {
206237
println!("Scanned {} files.", report.files_scanned);
238+
if let Some(path) = external_rules {
239+
println!("Rules: external database — {}", path.display());
240+
}
207241
println!(
208242
"Reclaimable: {} across {} findings and {} duplicate sets.",
209243
human_bytes(report.total_reclaimable),
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
use serde_json::json;
2+
use std::fs;
3+
use std::process::Command;
4+
use tempfile::tempdir;
5+
6+
fn run_scan(root: &std::path::Path, rules: Option<&std::path::Path>) -> std::process::Output {
7+
let mut command = Command::new(env!("CARGO_BIN_EXE_diskern"));
8+
command.arg("scan").arg(root).arg("--top").arg("0");
9+
if let Some(rules) = rules {
10+
command.arg("--rules").arg(rules);
11+
}
12+
command.output().expect("diskern should start")
13+
}
14+
15+
fn write_rules(path: &std::path::Path, pattern: &str) {
16+
let rules = json!({
17+
"version": 1,
18+
"rules": [{
19+
"id": "test-rule",
20+
"patterns": [pattern],
21+
"category": "browser_cache",
22+
"verdict": "safe",
23+
"description": "Rule loaded from the test file."
24+
}]
25+
});
26+
fs::write(path, serde_json::to_vec(&rules).unwrap()).unwrap();
27+
}
28+
29+
#[test]
30+
fn scan_without_rules_uses_embedded_database() {
31+
let root = tempdir().unwrap();
32+
let cache = root.path().join(".cache/google-chrome/Default/Cache");
33+
fs::create_dir_all(&cache).unwrap();
34+
fs::write(cache.join("entry"), b"cached").unwrap();
35+
36+
let output = run_scan(root.path(), None);
37+
assert!(
38+
output.status.success(),
39+
"{}",
40+
String::from_utf8_lossy(&output.stderr)
41+
);
42+
let stdout = String::from_utf8_lossy(&output.stdout);
43+
assert!(stdout.contains("matched rule chrome-cache"), "{stdout}");
44+
}
45+
46+
#[test]
47+
fn scan_accepts_and_uses_external_rules_file() {
48+
let root = tempdir().unwrap();
49+
fs::write(root.path().join("sample.custom"), b"custom").unwrap();
50+
let rules = root.path().join("rules.json");
51+
write_rules(&rules, "**/*.custom");
52+
53+
let output = run_scan(root.path(), Some(&rules));
54+
assert!(
55+
output.status.success(),
56+
"{}",
57+
String::from_utf8_lossy(&output.stderr)
58+
);
59+
let stdout = String::from_utf8_lossy(&output.stdout);
60+
assert!(stdout.contains("Rules: external database"), "{stdout}");
61+
assert!(stdout.contains("matched rule test-rule"), "{stdout}");
62+
assert!(
63+
stdout.contains("Rule loaded from the test file."),
64+
"{stdout}"
65+
);
66+
}
67+
68+
#[test]
69+
fn missing_rules_file_fails_clearly() {
70+
let root = tempdir().unwrap();
71+
let missing = root.path().join("missing.json");
72+
let output = run_scan(root.path(), Some(&missing));
73+
74+
assert!(!output.status.success());
75+
let stderr = String::from_utf8_lossy(&output.stderr);
76+
assert!(stderr.contains("could not read rules file"), "{stderr}");
77+
assert!(stderr.contains("missing.json"), "{stderr}");
78+
}
79+
80+
#[test]
81+
fn malformed_rules_file_fails_clearly() {
82+
let root = tempdir().unwrap();
83+
let rules = root.path().join("malformed.json");
84+
fs::write(&rules, b"{ not json }").unwrap();
85+
let output = run_scan(root.path(), Some(&rules));
86+
87+
assert!(!output.status.success());
88+
let stderr = String::from_utf8_lossy(&output.stderr);
89+
assert!(stderr.contains("could not parse rules file"), "{stderr}");
90+
assert!(stderr.contains("malformed.json"), "{stderr}");
91+
}
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)