1mod cache;
17mod engine;
18pub mod external;
19pub mod rules;
20#[cfg(test)]
21mod tests;
22
23use std::borrow::Cow;
24use std::path::Path;
25
26use serde::{Deserialize, Serialize};
27
28use crate::error::{CoreError, ErrorCode};
29use crate::fs::Fs;
30use crate::paths::SurjectionHome;
31use crate::skills::{SkillFiles, content_hash};
32
33pub use cache::CACHE_DIR;
34use cache::Cache;
35pub use rules::{Rule, Rules, Target};
36
37pub const SCANNER: &str = "builtin";
39pub const RULES_OVERRIDE_FILE: &str = "scan-rules.toml";
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum Severity {
47 Info,
48 Warning,
49 Dangerous,
50}
51
52impl Severity {
53 pub const fn as_str(self) -> &'static str {
54 match self {
55 Severity::Info => "info",
56 Severity::Warning => "warning",
57 Severity::Dangerous => "dangerous",
58 }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
64#[serde(rename_all = "snake_case")]
65pub enum Verdict {
66 Clean,
67 Warning,
68 Dangerous,
69}
70
71impl Verdict {
72 pub const fn as_str(self) -> &'static str {
73 match self {
74 Verdict::Clean => "clean",
75 Verdict::Warning => "warning",
76 Verdict::Dangerous => "dangerous",
77 }
78 }
79
80 pub fn of(findings: &[Finding]) -> Self {
81 match findings.iter().map(|finding| finding.severity).max() {
82 Some(Severity::Dangerous) => Verdict::Dangerous,
83 Some(Severity::Warning) => Verdict::Warning,
84 Some(Severity::Info) | None => Verdict::Clean,
85 }
86 }
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Finding {
92 pub scanner: String,
94 pub rule: String,
96 pub severity: Severity,
97 pub file: Option<String>,
100 pub line: Option<u32>,
103 pub message: String,
104 pub excerpt: Option<String>,
107}
108
109impl Finding {
110 pub fn label(&self) -> String {
112 match (&self.file, self.line) {
113 (Some(file), Some(line)) => format!("{} ({file}:{line})", self.rule),
114 (Some(file), None) => format!("{} ({file})", self.rule),
115 _ => self.rule.clone(),
116 }
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct ScanReport {
123 pub verdict: Verdict,
124 pub findings: Vec<Finding>,
126 pub rules_version: u32,
128 pub content_hash: Option<String>,
131 #[serde(default, skip_serializing)]
133 pub cached: bool,
134 #[serde(default, skip_serializing)]
137 pub custom_rules: bool,
138 #[serde(default, skip_serializing)]
141 pub warnings: Vec<String>,
142}
143
144impl ScanReport {
145 fn new(rules_version: u32, content_hash: Option<String>, mut findings: Vec<Finding>) -> Self {
146 findings.sort_by(|a, b| (&a.file, a.line, &a.rule).cmp(&(&b.file, b.line, &b.rule)));
147 Self {
148 verdict: Verdict::of(&findings),
149 findings,
150 rules_version,
151 content_hash,
152 cached: false,
153 custom_rules: false,
154 warnings: Vec::new(),
155 }
156 }
157
158 pub fn merge(&mut self, other: ScanReport) {
161 let content_hash = match (self.content_hash.take(), other.content_hash) {
162 (Some(a), Some(b)) if a == b => Some(a),
163 (Some(hash), None) | (None, Some(hash)) => Some(hash),
164 _ => None,
165 };
166 let mut findings = std::mem::take(&mut self.findings);
167 findings.extend(other.findings);
168 let cached = self.cached && other.cached;
169 let custom_rules = self.custom_rules || other.custom_rules;
170 let mut warnings = std::mem::take(&mut self.warnings);
171 for warning in other.warnings {
172 if !warnings.contains(&warning) {
173 warnings.push(warning);
174 }
175 }
176 *self = ScanReport::new(
177 self.rules_version.max(other.rules_version),
178 content_hash,
179 findings,
180 );
181 self.cached = cached;
182 self.custom_rules = custom_rules;
183 self.warnings = warnings;
184 }
185
186 pub fn dangerous(&self) -> impl Iterator<Item = &Finding> {
188 self.findings
189 .iter()
190 .filter(|finding| finding.severity == Severity::Dangerous)
191 }
192}
193
194pub fn gate(report: &ScanReport, allow_dangerous: bool) -> Result<(), CoreError> {
197 if allow_dangerous || report.verdict != Verdict::Dangerous {
198 return Ok(());
199 }
200 let labels: Vec<String> = report.dangerous().map(Finding::label).collect();
201 let mut shown = labels
202 .iter()
203 .take(3)
204 .cloned()
205 .collect::<Vec<_>>()
206 .join(", ");
207 if labels.len() > 3 {
208 shown.push_str(&format!(" and {} more", labels.len() - 3));
209 }
210 let plural = if labels.len() == 1 { "" } else { "s" };
211 Err(CoreError::new(
212 ErrorCode::ScanBlocked,
213 format!(
214 "the built-in scan found {} dangerous finding{plural}: {shown}; review them, and install anyway only if you trust this content",
215 labels.len()
216 ),
217 ))
218}
219
220pub struct Scanner<'a> {
222 rules: Cow<'static, Rules>,
223 cache: Option<Cache<'a>>,
224 warnings: Vec<String>,
225}
226
227impl<'a> Scanner<'a> {
228 pub fn new(fs: &'a dyn Fs, home: &SurjectionHome) -> Self {
233 let (rules, warnings) = load_rules(fs, &home.state_dir().join(RULES_OVERRIDE_FILE));
234 Self {
235 rules,
236 cache: Some(Cache::new(fs, home.cache_dir().join(CACHE_DIR))),
237 warnings,
238 }
239 }
240
241 pub fn rules(&self) -> &Rules {
242 &self.rules
243 }
244
245 pub fn warnings(&self) -> &[String] {
247 &self.warnings
248 }
249
250 fn finish(&self, mut report: ScanReport) -> ScanReport {
251 report.custom_rules = self.rules.is_custom();
252 report.warnings.clone_from(&self.warnings);
253 report
254 }
255
256 pub fn scan_files(&self, files: &SkillFiles) -> ScanReport {
259 let hash = content_hash(files);
260 let key = self.cache.as_ref().map(|_| Cache::key(&self.rules, &hash));
261 if let (Some(cache), Some(key)) = (&self.cache, &key)
262 && let Some(report) = cache.get(key)
263 {
264 return self.finish(report);
265 }
266 let report = ScanReport::new(
267 self.rules.version(),
268 Some(hash),
269 engine::scan_files(&self.rules, files),
270 );
271 if let (Some(cache), Some(key)) = (&self.cache, &key) {
272 cache.put(key, &report);
273 }
274 self.finish(report)
275 }
276
277 pub fn scan_command(&self, command: &str, args: &[String]) -> ScanReport {
280 let mut line = command.to_owned();
281 for arg in args {
282 line.push(' ');
283 line.push_str(arg);
284 }
285 self.finish(ScanReport::new(
286 self.rules.version(),
287 None,
288 engine::scan_command(&self.rules, &line),
289 ))
290 }
291}
292
293impl Scanner<'static> {
294 pub fn builtin() -> Self {
296 Self::with_rules(Cow::Borrowed(Rules::builtin()))
297 }
298
299 pub fn with_rules(rules: Cow<'static, Rules>) -> Self {
301 Self {
302 rules,
303 cache: None,
304 warnings: Vec::new(),
305 }
306 }
307}
308
309fn load_rules(fs: &dyn Fs, path: &Path) -> (Cow<'static, Rules>, Vec<String>) {
312 let builtin = Rules::builtin();
313 if !fs.exists(path) {
314 return (Cow::Borrowed(builtin), Vec::new());
315 }
316 let merged = fs
317 .read_to_string(path)
318 .map_err(|err| CoreError::new(ErrorCode::IoError, err.to_string()))
319 .and_then(|text| builtin.with_custom(&text));
320 match merged {
321 Ok((rules, warnings)) => (Cow::Owned(rules), warnings),
322 Err(err) => (
323 Cow::Borrowed(builtin),
324 vec![format!(
325 "state/{RULES_OVERRIDE_FILE} is not used, only the built-in scan rules ran: {}",
326 err.message()
327 )],
328 ),
329 }
330}