Skip to content

Commit 752d2b7

Browse files
wagnerioclaude
andcommitted
Split monolithic main.rs into 11 focused modules
Decompose src/main.rs from 5,985 lines into 12 files organized by responsibility: analysis, static_analysis, config, network, audit, cache, container, sandbox, provider, helpers, and commands. Tests move with their code. All cross-module items use pub(crate) visibility. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 78e482e commit 752d2b7

File tree

12 files changed

+5939
-5748
lines changed

12 files changed

+5939
-5748
lines changed

src/analysis.rs

Lines changed: 634 additions & 0 deletions
Large diffs are not rendered by default.

src/audit.rs

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
use colored::*;
2+
use std::fs;
3+
use std::io::Write;
4+
use std::time::{Duration, SystemTime};
5+
6+
use crate::config::Config;
7+
use crate::container::{classify_alert, AlertSeverity, ContainerResult, FalcoAlert};
8+
9+
// ============================================================================
10+
// Audit Log
11+
// ============================================================================
12+
13+
#[allow(clippy::too_many_arguments)]
14+
pub(crate) fn write_audit_log(
15+
url: &str,
16+
script_hash: &str,
17+
script_size: usize,
18+
static_finding_count: usize,
19+
has_critical: bool,
20+
has_prompt_injection: bool,
21+
ai_risk_level: &str,
22+
ai_raw_response: &str,
23+
decision: &str,
24+
sandboxed: bool,
25+
container_result: Option<&ContainerResult>,
26+
falco_alerts: &[FalcoAlert],
27+
runtime_ai_verdict: Option<&str>,
28+
) {
29+
let log_result = (|| -> anyhow::Result<()> {
30+
let dir = Config::config_dir()?;
31+
fs::create_dir_all(&dir)?;
32+
33+
let log_path = dir.join("audit.log");
34+
35+
// Rotate audit log if it exceeds 10 MB
36+
const MAX_AUDIT_LOG_BYTES: u64 = 10 * 1024 * 1024;
37+
if log_path.exists() {
38+
if let Ok(meta) = fs::metadata(&log_path) {
39+
if meta.len() > MAX_AUDIT_LOG_BYTES {
40+
let rotated = dir.join("audit.log.1");
41+
let _ = fs::rename(&log_path, &rotated);
42+
}
43+
}
44+
}
45+
46+
// Get ISO 8601 timestamp
47+
let now = SystemTime::now()
48+
.duration_since(SystemTime::UNIX_EPOCH)
49+
.unwrap_or(Duration::from_secs(0));
50+
let secs = now.as_secs();
51+
// Simple ISO 8601 without external crate: seconds since epoch
52+
// Format: YYYY-MM-DDTHH:MM:SSZ (compute from epoch)
53+
let days = secs / 86400;
54+
let time_of_day = secs % 86400;
55+
let hours = time_of_day / 3600;
56+
let minutes = (time_of_day % 3600) / 60;
57+
let seconds = time_of_day % 60;
58+
59+
// Compute date from days since epoch (1970-01-01)
60+
let (year, month, day) = days_to_date(days);
61+
62+
let timestamp = format!(
63+
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
64+
year, month, day, hours, minutes, seconds
65+
);
66+
67+
// Escape JSON string values
68+
let url_escaped = url.replace('\\', "\\\\").replace('"', "\\\"");
69+
let response_escaped = ai_raw_response
70+
.replace('\\', "\\\\")
71+
.replace('"', "\\\"")
72+
.replace('\n', "\\n")
73+
.replace('\r', "\\r")
74+
.replace('\t', "\\t");
75+
76+
let mut entry = format!(
77+
"{{\"timestamp\":\"{}\",\"url\":\"{}\",\"sha256\":\"{}\",\"size_bytes\":{},\"static_findings\":{},\"has_critical\":{},\"has_prompt_injection\":{},\"ai_risk_level\":\"{}\",\"ai_raw_response\":\"{}\",\"decision\":\"{}\",\"sandboxed\":{}",
78+
timestamp, url_escaped, script_hash, script_size, static_finding_count, has_critical, has_prompt_injection, ai_risk_level, response_escaped, decision, sandboxed
79+
);
80+
81+
// Append container observation fields if present
82+
if let Some(cr) = container_result {
83+
entry.push_str(&format!(
84+
",\"container_id\":\"{}\",\"runtime_duration_ms\":{},\"container_timed_out\":{},\"container_exit_code\":{},\"killed_by_monitor\":{},\"filesystem_changes\":{}",
85+
cr.container_id.replace('"', "\\\""),
86+
cr.duration_ms,
87+
cr.timed_out,
88+
cr.exit_code.map(|c| c.to_string()).unwrap_or_else(|| "null".to_string()),
89+
cr.killed_by_monitor,
90+
cr.filesystem_diff.len(),
91+
));
92+
}
93+
94+
// Append Falco alert summary
95+
if !falco_alerts.is_empty() {
96+
let highest = falco_alerts
97+
.iter()
98+
.map(classify_alert)
99+
.min_by_key(|s| match s {
100+
AlertSeverity::Critical => 0,
101+
AlertSeverity::Suspicious => 1,
102+
AlertSeverity::Anomaly => 2,
103+
})
104+
.unwrap_or(AlertSeverity::Anomaly);
105+
let highest_str = match highest {
106+
AlertSeverity::Critical => "critical",
107+
AlertSeverity::Suspicious => "suspicious",
108+
AlertSeverity::Anomaly => "anomaly",
109+
};
110+
111+
let rules: Vec<String> = falco_alerts
112+
.iter()
113+
.map(|a| a.rule.replace('"', "\\\""))
114+
.collect();
115+
116+
entry.push_str(&format!(
117+
",\"falco_alert_count\":{},\"falco_highest_severity\":\"{}\",\"falco_rules\":[{}]",
118+
falco_alerts.len(),
119+
highest_str,
120+
rules
121+
.iter()
122+
.map(|r| format!("\"{}\"", r))
123+
.collect::<Vec<_>>()
124+
.join(","),
125+
));
126+
}
127+
128+
// Append runtime AI re-review verdict if available
129+
if let Some(verdict) = runtime_ai_verdict {
130+
entry.push_str(&format!(
131+
",\"runtime_ai_verdict\":\"{}\"",
132+
verdict.replace('"', "\\\"")
133+
));
134+
}
135+
136+
entry.push_str("}\n");
137+
138+
use std::fs::OpenOptions;
139+
let mut file = OpenOptions::new()
140+
.create(true)
141+
.append(true)
142+
.open(&log_path)?;
143+
144+
// Set permissions to 0600
145+
#[cfg(unix)]
146+
{
147+
use std::os::unix::fs::PermissionsExt;
148+
fs::set_permissions(&log_path, fs::Permissions::from_mode(0o600))?;
149+
}
150+
151+
file.write_all(entry.as_bytes())?;
152+
Ok(())
153+
})();
154+
155+
if let Err(e) = log_result {
156+
eprintln!("{} Failed to write audit log: {}", "⚠".yellow(), e);
157+
}
158+
}
159+
160+
/// Convert days since Unix epoch to (year, month, day)
161+
pub(crate) fn days_to_date(days: u64) -> (u64, u64, u64) {
162+
// Algorithm from http://howardhinnant.github.io/date_algorithms.html
163+
let z = days + 719468;
164+
let era = z / 146097;
165+
let doe = z - era * 146097;
166+
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
167+
let y = yoe + era * 400;
168+
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
169+
let mp = (5 * doy + 2) / 153;
170+
let d = doy - (153 * mp + 2) / 5 + 1;
171+
let m = if mp < 10 { mp + 3 } else { mp - 9 };
172+
let y = if m <= 2 { y + 1 } else { y };
173+
(y, m, d)
174+
}
175+
176+
#[cfg(test)]
177+
mod tests {
178+
use super::*;
179+
180+
#[test]
181+
fn test_audit_log_format() {
182+
// Verify days_to_date produces correct results
183+
// 2024-01-01 is day 19723 since epoch
184+
let (y, m, d) = days_to_date(19723);
185+
assert_eq!(y, 2024);
186+
assert_eq!(m, 1);
187+
assert_eq!(d, 1);
188+
189+
// 1970-01-01 is day 0
190+
let (y, m, d) = days_to_date(0);
191+
assert_eq!(y, 1970);
192+
assert_eq!(m, 1);
193+
assert_eq!(d, 1);
194+
}
195+
196+
#[test]
197+
fn test_days_to_date_leap_year() {
198+
// 2024-02-29 (leap day) — day 19782 since epoch
199+
let (y, m, d) = days_to_date(19782);
200+
assert_eq!((y, m, d), (2024, 2, 29));
201+
}
202+
203+
#[test]
204+
fn test_days_to_date_year_2000() {
205+
// 2000-01-01 = day 10957
206+
let (y, m, d) = days_to_date(10957);
207+
assert_eq!((y, m, d), (2000, 1, 1));
208+
}
209+
210+
#[test]
211+
fn test_days_to_date_end_of_year() {
212+
// 2024-12-31 = day 20088
213+
let (y, m, d) = days_to_date(20088);
214+
assert_eq!((y, m, d), (2024, 12, 31));
215+
}
216+
}

0 commit comments

Comments
 (0)