1use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use std::path::Path;
9
10#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, PartialOrd, Ord)]
11pub enum AuditSeverity {
12 Info,
13 Low,
14 Medium,
15 High,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
19pub struct AuditFinding {
20 pub id: String,
21 pub severity: AuditSeverity,
22 pub title: String,
23 pub description: String,
24 #[serde(default)]
25 pub file: Option<String>,
26 #[serde(default)]
27 pub line: Option<usize>,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
31pub struct SecurityAuditReport {
32 pub root: String,
33 pub findings: Vec<AuditFinding>,
34}
35
36impl SecurityAuditReport {
37 pub fn summary(&self) -> String {
38 let high = self
39 .findings
40 .iter()
41 .filter(|finding| finding.severity == AuditSeverity::High)
42 .count();
43 let medium = self
44 .findings
45 .iter()
46 .filter(|finding| finding.severity == AuditSeverity::Medium)
47 .count();
48 format!(
49 "{} finding(s), {} high, {} medium",
50 self.findings.len(),
51 high,
52 medium
53 )
54 }
55}
56
57pub fn audit_agent(root: &Path) -> anyhow::Result<SecurityAuditReport> {
58 let mut findings = Vec::new();
59 let files = collect_rust_files(root)?;
60
61 for file in files {
62 let content = std::fs::read_to_string(&file)?;
63 for (index, line) in content.lines().enumerate() {
64 let line_no = index + 1;
65 let trimmed = line.trim();
66
67 if trimmed.contains("Command::new(") || trimmed.contains("std::process::Command") {
68 findings.push(finding(
69 "unexpected-code-execution",
70 AuditSeverity::High,
71 "Process execution surface",
72 "Agent code starts external processes. Review command inputs, allowlists, and sandbox boundaries.",
73 &file,
74 line_no,
75 ));
76 }
77
78 if trimmed.contains("unsafe ") || trimmed == "unsafe" || trimmed.contains("unsafe{") {
79 findings.push(finding(
80 "unsafe-code",
81 AuditSeverity::Medium,
82 "Unsafe Rust block",
83 "Unsafe code increases the blast radius of agent-driven changes and should have a clear justification.",
84 &file,
85 line_no,
86 ));
87 }
88
89 if contains_secret_literal(trimmed) {
90 findings.push(finding(
91 "secret-literal",
92 AuditSeverity::High,
93 "Potential secret literal",
94 "A likely secret or token appears in source. Move secrets to environment or a managed secret store.",
95 &file,
96 line_no,
97 ));
98 }
99
100 if trimmed.contains("MCP") || trimmed.contains("mcp") || trimmed.contains("A2A") {
101 findings.push(finding(
102 "agent-interop-surface",
103 AuditSeverity::Low,
104 "Agent interop surface",
105 "MCP or A2A-style integration should validate tool schemas and trust boundaries before live execution.",
106 &file,
107 line_no,
108 ));
109 }
110 }
111 }
112
113 if findings.is_empty() {
114 findings.push(AuditFinding {
115 id: "baseline".to_string(),
116 severity: AuditSeverity::Info,
117 title: "No obvious static risks found".to_string(),
118 description: "Static audit found no process execution, unsafe code, obvious secret literals, or agent interop surfaces.".to_string(),
119 file: None,
120 line: None,
121 });
122 }
123
124 Ok(SecurityAuditReport {
125 root: root.display().to_string(),
126 findings,
127 })
128}
129
130fn collect_rust_files(root: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
131 let mut files = Vec::new();
132 collect_rust_files_inner(root, &mut files)?;
133 Ok(files)
134}
135
136fn collect_rust_files_inner(
137 root: &Path,
138 files: &mut Vec<std::path::PathBuf>,
139) -> anyhow::Result<()> {
140 if !root.exists() {
141 return Ok(());
142 }
143
144 for entry in std::fs::read_dir(root)? {
145 let entry = entry?;
146 let path = entry.path();
147 let name = entry.file_name();
148 let name = name.to_string_lossy();
149
150 if path.is_dir() {
151 if matches!(
152 name.as_ref(),
153 "target" | ".git" | ".worktrees" | ".mdx-rust"
154 ) {
155 continue;
156 }
157 collect_rust_files_inner(&path, files)?;
158 } else if path.extension().is_some_and(|extension| extension == "rs") {
159 files.push(path);
160 }
161 }
162
163 Ok(())
164}
165
166fn finding(
167 id: &str,
168 severity: AuditSeverity,
169 title: &str,
170 description: &str,
171 file: &Path,
172 line: usize,
173) -> AuditFinding {
174 AuditFinding {
175 id: id.to_string(),
176 severity,
177 title: title.to_string(),
178 description: description.to_string(),
179 file: Some(file.display().to_string()),
180 line: Some(line),
181 }
182}
183
184fn contains_secret_literal(line: &str) -> bool {
185 if line.contains("env::var(")
186 || line.contains("std::env::var(")
187 || line.contains("option_env!(")
188 {
189 return false;
190 }
191
192 let lower = line.to_lowercase();
193 let has_secret_name = ["api_key", "apikey", "secret", "token", "password"]
194 .iter()
195 .any(|needle| lower.contains(needle));
196 has_secret_name && line.contains('"') && line.contains('=')
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use tempfile::tempdir;
203
204 #[test]
205 fn audit_flags_process_execution_and_secret_literals() {
206 let dir = tempdir().unwrap();
207 let src = dir.path().join("src");
208 std::fs::create_dir_all(&src).unwrap();
209 std::fs::write(
210 src.join("main.rs"),
211 r#"
212 fn main() {
213 let api_key = "secret";
214 let _ = std::process::Command::new("sh");
215 }
216 "#,
217 )
218 .unwrap();
219
220 let report = audit_agent(dir.path()).unwrap();
221
222 assert!(report
223 .findings
224 .iter()
225 .any(|finding| finding.id == "unexpected-code-execution"));
226 assert!(report
227 .findings
228 .iter()
229 .any(|finding| finding.id == "secret-literal"));
230 }
231
232 #[test]
233 fn audit_does_not_flag_environment_variable_names_as_secret_literals() {
234 let dir = tempdir().unwrap();
235 let src = dir.path().join("src");
236 std::fs::create_dir_all(&src).unwrap();
237 std::fs::write(
238 src.join("main.rs"),
239 r#"
240 fn main() {
241 let api_key = std::env::var("OPENAI_API_KEY").ok();
242 }
243 "#,
244 )
245 .unwrap();
246
247 let report = audit_agent(dir.path()).unwrap();
248
249 assert!(!report
250 .findings
251 .iter()
252 .any(|finding| finding.id == "secret-literal"));
253 }
254}