interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-aegis / src / scanner.rs

485 lines · 18131 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16// spark-aegis Deep Scanner
17// Scans files, directories, and git diffs for secrets, slop, and dangerous commands
18
19use crate::byte_scan;
20use anyhow::Result;
21use regex::Regex;
22use serde::{Deserialize, Serialize};
23use std::fs;
24use std::path::{Path, PathBuf};
25use std::sync::LazyLock;
26use std::time::Instant;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29pub enum ViolationCategory {
30 PlaintextSecret,
31 AntiSlop,
32 DangerousCommand,
33 ProhibitedFile,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37pub enum ViolationSeverity {
38 Critical,
39 High,
40 Medium,
41 Low,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct Violation {
46 pub category: ViolationCategory,
47 pub severity: ViolationSeverity,
48 pub rule: String,
49 pub file_path: PathBuf,
50 pub line_number: Option<usize>,
51 pub column: Option<usize>,
52 pub matched_text: String,
53 pub remediation: String,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct ScanReport {
58 pub target: String,
59 pub scanned_files_count: usize,
60 pub violations: Vec<Violation>,
61 pub passed: bool,
62 pub blake3_hash: String,
63 pub elapsed_ms: f64,
64}
65
66struct SecretRule {
67 name: &'static str,
68 regex: LazyLock<Regex>,
69 severity: ViolationSeverity,
70 remediation: &'static str,
71}
72
73struct SlopRule {
74 name: &'static str,
75 regex: LazyLock<Regex>,
76 remediation: &'static str,
77}
78
79struct DangerousCommandRule {
80 name: &'static str,
81 regex: LazyLock<Regex>,
82 severity: ViolationSeverity,
83 remediation: &'static str,
84}
85
86static SECRET_RULES: LazyLock<Vec<SecretRule>> = LazyLock::new(|| {
87 vec![
88 SecretRule {
89 name: "AWS Access Key ID",
90 regex: LazyLock::new(|| Regex::new(r"\bAKIA[0-9A-Z]{16}\b").unwrap()),
91 severity: ViolationSeverity::Critical,
92 remediation: "Store AWS credentials in the hardware TPM key vault.",
93 },
94 SecretRule {
95 name: "GitHub Personal Access Token",
96 regex: LazyLock::new(|| {
97 Regex::new(r"\b(?:ghp|gho|ghu|ghs|ghr)_[0-9a-zA-Z]{36}\b|\bgithub_pat_[0-9a-zA-Z_]{22,82}\b").unwrap()
98 }),
99 severity: ViolationSeverity::Critical,
100 remediation: "Store GitHub token in the hardware TPM vault (atlas-vault add).",
101 },
102 SecretRule {
103 name: "Slack Token",
104 regex: LazyLock::new(|| Regex::new(r"\bxox[baprs]-[0-9a-zA-Z]{10,48}\b").unwrap()),
105 severity: ViolationSeverity::Critical,
106 remediation: "Store Slack token in the hardware TPM vault.",
107 },
108 SecretRule {
109 name: "Private Key Header",
110 regex: LazyLock::new(|| {
111 Regex::new(
112 r"-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----",
113 )
114 .unwrap()
115 }),
116 severity: ViolationSeverity::Critical,
117 remediation: "Remove private key from filesystem. Use TPM-bound keys.",
118 },
119 SecretRule {
120 name: "Generic Hardcoded Secret Assignment",
121 regex: LazyLock::new(|| {
122 Regex::new(r#"(?i)\b(?:api[_-]?key|secret[_-]?key|auth[_-]?token|access[_-]?token)\s*[:=]\s*['"][0-9a-zA-Z_\-]{16,}['"]"#).unwrap()
123 }),
124 severity: ViolationSeverity::High,
125 remediation: "Resolve secret dynamically in memory via atlas-vault get.",
126 },
127 ]
128});
129
130static SLOP_RULES: LazyLock<Vec<SlopRule>> = LazyLock::new(|| {
131 vec![
132 SlopRule {
133 name: "Forbidden Em Dash",
134 regex: LazyLock::new(|| Regex::new("\u{2014}").unwrap()),
135 remediation: "Replace em dash with comma, colon, parentheses, or period.",
136 },
137 SlopRule {
138 name: "Forbidden En Dash",
139 regex: LazyLock::new(|| Regex::new("\u{2013}").unwrap()),
140 remediation: "Replace en dash with hyphen or rewrite clause.",
141 },
142 SlopRule {
143 name: "Banned AI Buzzword",
144 regex: LazyLock::new(|| {
145 Regex::new(r"(?i)\b(delve[a-z]*|tapestr[a-z]*|testament[a-z]*|beacon[a-z]*|crucial[a-z]*|pivotal[a-z]*|elevat[a-z]+|game-changer|unleash[a-z]*|harness[a-z]*|seamless[a-z]*)\b").unwrap()
146 }),
147 remediation: "Remove banned AI cliché. State technical facts directly.",
148 },
149 SlopRule {
150 name: "Banned Transitional Fluff",
151 regex: LazyLock::new(|| {
152 Regex::new(r"(?i)\b(furthermore|moreover|in conclusion|at its core)\b").unwrap()
153 }),
154 remediation: "Omit transitional filler. Lead immediately with evidence or code.",
155 },
156 SlopRule {
157 name: "Banned Antithesis Trope",
158 regex: LazyLock::new(|| {
159 Regex::new(r"(?i)\b(?:not only\b[^\n.!?]{1,60}\bbut also|it's not\b[^\n.!?]{1,60}\bit's)\b").unwrap()
160 }),
161 remediation: "Omit rhetorical antithesis trope. State facts directly.",
162 },
163 ]
164});
165
166static DANGEROUS_COMMAND_RULES: LazyLock<Vec<DangerousCommandRule>> = LazyLock::new(|| {
167 vec![
168 DangerousCommandRule {
169 name: "Destructive Root Filesystem Removal",
170 regex: LazyLock::new(|| {
171 Regex::new(r#"rm\s+-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r)\s+(?:/|/\*|~|~/\*)(?:\s|$)"#).unwrap()
172 }),
173 severity: ViolationSeverity::Critical,
174 remediation: "Command removes root or home directory. Abort immediately.",
175 },
176 DangerousCommandRule {
177 name: "Unsandboxed Pipe to Shell",
178 regex: LazyLock::new(|| {
179 Regex::new(r#"(?:curl|wget)\s+[^|\n]+?\|\s*(?:ba)?sh\b"#).unwrap()
180 }),
181 severity: ViolationSeverity::High,
182 remediation: "Download file, inspect Blake3 checksum, and execute in isolation.",
183 },
184 DangerousCommandRule {
185 name: "Fork Bomb Pattern",
186 regex: LazyLock::new(|| Regex::new(r#":\(\)\s*\{\s*:\|:&\s*\};:"#).unwrap()),
187 severity: ViolationSeverity::Critical,
188 remediation: "Malicious fork bomb detected. Isolate process immediately.",
189 },
190 DangerousCommandRule {
191 name: "Unrestricted Global Permissions",
192 regex: LazyLock::new(|| {
193 Regex::new(r#"chmod\s+(?:-R\s+)?777\s+(?:/|~)(?:\s|$)"#).unwrap()
194 }),
195 severity: ViolationSeverity::Critical,
196 remediation: "Do not apply 777 permissions to root or home directory.",
197 },
198 DangerousCommandRule {
199 name: "Raw Sudo Command in Script",
200 regex: LazyLock::new(|| {
201 Regex::new(r#"(?m)^\s*sudo\s+(?:rm|chmod|chown|dd|mkfs)\b"#).unwrap()
202 }),
203 severity: ViolationSeverity::High,
204 remediation: "Explicit privilege escalation requires audited sandbox confinement.",
205 },
206 ]
207});
208
209pub fn is_prohibited_filename(path: &Path) -> Option<(&'static str, &'static str)> {
210 if let Some(file_name) = path.file_name().and_then(|f| f.to_str()) {
211 if file_name == ".env" || file_name.starts_with(".env.") {
212 return Some((
213 "Plaintext .env Environment File",
214 "Zero Disk Secrets invariant violated. Remove .env and use hardware TPM vault.",
215 ));
216 }
217 if file_name.ends_with(".pem") || file_name.ends_with(".key") {
218 return Some((
219 "Unencrypted Private Key File",
220 "Zero Disk Secrets invariant violated. Store keys in TPM vault.",
221 ));
222 }
223 if file_name == "id_rsa" || file_name == "id_ed25519" || file_name == "id_ecdsa" {
224 return Some((
225 "Raw SSH Private Key in Workspace",
226 "Move SSH keys to ~/.ssh or hardware security token.",
227 ));
228 }
229 }
230 None
231}
232
233pub fn scan_content(path: &Path, content: &str) -> Vec<Violation> {
234 let mut violations = Vec::new();
235
236 // Check prohibited filename
237 if let Some((rule, remediation)) = is_prohibited_filename(path) {
238 violations.push(Violation {
239 category: ViolationCategory::ProhibitedFile,
240 severity: ViolationSeverity::Critical,
241 rule: rule.to_string(),
242 file_path: path.to_path_buf(),
243 line_number: None,
244 column: None,
245 matched_text: path.display().to_string(),
246 remediation: remediation.to_string(),
247 });
248 }
249
250 // Fast check for em and en dashes: skip the per-line scan when no E2 lead byte exists
251 let bytes = content.as_bytes();
252 // Em dash UTF-8: E2 80 94 (226, 128, 148)
253 // En dash UTF-8: E2 80 93 (226, 128, 147)
254 let has_utf8_prefix = byte_scan::scan_byte(bytes, 0xE2).is_some();
255
256 for (line_idx, line) in content.lines().enumerate() {
257 let line_num = line_idx + 1;
258
259 // 1. Plaintext Secrets
260 for rule in SECRET_RULES.iter() {
261 for mat in rule.regex.find_iter(line) {
262 violations.push(Violation {
263 category: ViolationCategory::PlaintextSecret,
264 severity: rule.severity,
265 rule: rule.name.to_string(),
266 file_path: path.to_path_buf(),
267 line_number: Some(line_num),
268 column: Some(mat.start() + 1),
269 matched_text: "[REDACTED_BY_ATLAS_VAULT]".to_string(),
270 remediation: rule.remediation.to_string(),
271 });
272 }
273 }
274
275 // 2. Anti-Slop Violations
276 if has_utf8_prefix || line.contains('\u{2014}') || line.contains('\u{2013}') {
277 for rule in &SLOP_RULES[0..2] {
278 for mat in rule.regex.find_iter(line) {
279 violations.push(Violation {
280 category: ViolationCategory::AntiSlop,
281 severity: ViolationSeverity::Medium,
282 rule: rule.name.to_string(),
283 file_path: path.to_path_buf(),
284 line_number: Some(line_num),
285 column: Some(mat.start() + 1),
286 matched_text: mat.as_str().to_string(),
287 remediation: rule.remediation.to_string(),
288 });
289 }
290 }
291 }
292
293 for rule in &SLOP_RULES[2..] {
294 for mat in rule.regex.find_iter(line) {
295 violations.push(Violation {
296 category: ViolationCategory::AntiSlop,
297 severity: ViolationSeverity::Medium,
298 rule: rule.name.to_string(),
299 file_path: path.to_path_buf(),
300 line_number: Some(line_num),
301 column: Some(mat.start() + 1),
302 matched_text: mat.as_str().to_string(),
303 remediation: rule.remediation.to_string(),
304 });
305 }
306 }
307
308 // 3. Dangerous Commands
309 for rule in DANGEROUS_COMMAND_RULES.iter() {
310 for mat in rule.regex.find_iter(line) {
311 violations.push(Violation {
312 category: ViolationCategory::DangerousCommand,
313 severity: rule.severity,
314 rule: rule.name.to_string(),
315 file_path: path.to_path_buf(),
316 line_number: Some(line_num),
317 column: Some(mat.start() + 1),
318 matched_text: mat.as_str().to_string(),
319 remediation: rule.remediation.to_string(),
320 });
321 }
322 }
323 }
324
325 violations
326}
327
328pub fn scan_path(target_path: &Path) -> Result<ScanReport> {
329 let start = Instant::now();
330 let mut files_scanned = 0;
331 let mut violations = Vec::new();
332 let mut hasher = blake3::Hasher::new();
333
334 if target_path.is_file() {
335 files_scanned += 1;
336 let content = fs::read_to_string(target_path).unwrap_or_default();
337 hasher.update(content.as_bytes());
338 violations.extend(scan_content(target_path, &content));
339 } else if target_path.is_dir() {
340 let mut dirs = vec![target_path.to_path_buf()];
341 while let Some(dir) = dirs.pop() {
342 let entries = match fs::read_dir(&dir) {
343 Ok(e) => e,
344 Err(_) => continue,
345 };
346 for entry in entries.flatten() {
347 let p = entry.path();
348 let file_name = match p.file_name().and_then(|f| f.to_str()) {
349 Some(s) => s,
350 None => continue,
351 };
352
353 // Skip version control and build directories
354 if file_name == ".git" || file_name == "target" || file_name == "node_modules" {
355 continue;
356 }
357
358 if p.is_dir() {
359 dirs.push(p);
360 } else if p.is_file() {
361 files_scanned += 1;
362 if let Some((rule, remediation)) = is_prohibited_filename(&p) {
363 violations.push(Violation {
364 category: ViolationCategory::ProhibitedFile,
365 severity: ViolationSeverity::Critical,
366 rule: rule.to_string(),
367 file_path: p.clone(),
368 line_number: None,
369 column: None,
370 matched_text: p.display().to_string(),
371 remediation: remediation.to_string(),
372 });
373 }
374 if let Ok(content) = fs::read_to_string(&p) {
375 hasher.update(content.as_bytes());
376 violations.extend(scan_content(&p, &content));
377 }
378 }
379 }
380 }
381 } else {
382 anyhow::bail!("Target path {:?} does not exist", target_path);
383 }
384
385 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
386 let digest = hasher.finalize().to_hex().to_string();
387 let passed = violations.is_empty();
388
389 Ok(ScanReport {
390 target: target_path.display().to_string(),
391 scanned_files_count: files_scanned,
392 violations,
393 passed,
394 blake3_hash: digest,
395 elapsed_ms: elapsed,
396 })
397}
398
399pub fn scan_diff(diff_content: &str) -> Result<ScanReport> {
400 let start = Instant::now();
401 let mut violations = Vec::new();
402 let mut current_file = PathBuf::from("diff");
403 let mut line_counter: usize = 0;
404
405 for line in diff_content.lines() {
406 if let Some(path_str) = line.strip_prefix("+++ b/") {
407 current_file = PathBuf::from(path_str);
408 if let Some((rule, remediation)) = is_prohibited_filename(&current_file) {
409 violations.push(Violation {
410 category: ViolationCategory::ProhibitedFile,
411 severity: ViolationSeverity::Critical,
412 rule: rule.to_string(),
413 file_path: current_file.clone(),
414 line_number: None,
415 column: None,
416 matched_text: current_file.display().to_string(),
417 remediation: remediation.to_string(),
418 });
419 }
420 continue;
421 }
422
423 if line.starts_with('+') && !line.starts_with("+++") {
424 line_counter += 1;
425 let added_text = &line[1..];
426 let line_violations = scan_content(&current_file, added_text);
427 for mut v in line_violations {
428 v.line_number = Some(line_counter);
429 violations.push(v);
430 }
431 }
432 }
433
434 let elapsed = start.elapsed().as_secs_f64() * 1000.0;
435 let digest = blake3::hash(diff_content.as_bytes()).to_hex().to_string();
436 let passed = violations.is_empty();
437
438 Ok(ScanReport {
439 target: "git-diff".to_string(),
440 scanned_files_count: 1,
441 violations,
442 passed,
443 blake3_hash: digest,
444 elapsed_ms: elapsed,
445 })
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 #[test]
453 fn test_secret_detection() {
454 let fake_aws = "export AWS_KEY=AKIAIOSFODNN7EXAMPLE\n";
455 let v = scan_content(Path::new("test.sh"), fake_aws);
456 assert_eq!(v.len(), 1);
457 assert_eq!(v[0].category, ViolationCategory::PlaintextSecret);
458 assert_eq!(v[0].matched_text, "[REDACTED_BY_ATLAS_VAULT]");
459 }
460
461 #[test]
462 fn test_slop_detection_em_dash() {
463 let bad_line = "This is a feature \u{2014} it elevates throughput.\n";
464 let v = scan_content(Path::new("doc.md"), bad_line);
465 assert!(v.iter().any(|item| item.rule == "Forbidden Em Dash"));
466 assert!(v.iter().any(|item| item.rule == "Banned AI Buzzword"));
467 }
468
469 #[test]
470 fn test_dangerous_command_detection() {
471 let dangerous = "rm -rf /\n";
472 let v = scan_content(Path::new("script.sh"), dangerous);
473 assert_eq!(v.len(), 1);
474 assert_eq!(v[0].category, ViolationCategory::DangerousCommand);
475 }
476
477 #[test]
478 fn test_prohibited_env_file() {
479 let path = Path::new("/workspace/.env");
480 let v = scan_content(path, "FOO=BAR\n");
481 assert!(v
482 .iter()
483 .any(|item| item.category == ViolationCategory::ProhibitedFile));
484 }
485}