1use std::cell::RefCell;
24use std::sync::Mutex;
25
26use serde::{Deserialize, Serialize};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SecurityKind {
32 SecretRedacted,
34 ShellBlocked,
36 PathBlocked,
38 InjectionFlagged,
40}
41
42impl SecurityKind {
43 pub const fn as_str(self) -> &'static str {
45 match self {
46 Self::SecretRedacted => "secret_redacted",
47 Self::ShellBlocked => "shell_blocked",
48 Self::PathBlocked => "path_blocked",
49 Self::InjectionFlagged => "injection_flagged",
50 }
51 }
52
53 fn audit_event_type(self) -> crate::core::audit_trail::AuditEventType {
54 use crate::core::audit_trail::AuditEventType;
55 match self {
56 Self::SecretRedacted => AuditEventType::SecretDetected,
57 Self::ShellBlocked => AuditEventType::ToolDenied,
58 Self::PathBlocked => AuditEventType::PathJailViolation,
59 Self::InjectionFlagged => AuditEventType::SecurityViolation,
60 }
61 }
62
63 pub fn from_action(action: &str) -> Option<Self> {
65 let kind = action.split(':').next()?;
66 [
67 Self::SecretRedacted,
68 Self::ShellBlocked,
69 Self::PathBlocked,
70 Self::InjectionFlagged,
71 ]
72 .into_iter()
73 .find(|k| k.as_str() == kind)
74 }
75}
76
77#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(default)]
81pub struct SecurityCounts {
82 pub secrets_redacted: u64,
83 pub shell_blocked: u64,
84 pub path_blocked: u64,
85 pub injection_flagged: u64,
86}
87
88impl SecurityCounts {
89 pub fn add(&mut self, kind: SecurityKind, n: u64) {
90 let slot = match kind {
91 SecurityKind::SecretRedacted => &mut self.secrets_redacted,
92 SecurityKind::ShellBlocked => &mut self.shell_blocked,
93 SecurityKind::PathBlocked => &mut self.path_blocked,
94 SecurityKind::InjectionFlagged => &mut self.injection_flagged,
95 };
96 *slot = slot.saturating_add(n);
97 }
98
99 pub fn merge(&mut self, other: &Self) {
100 self.secrets_redacted = self.secrets_redacted.saturating_add(other.secrets_redacted);
101 self.shell_blocked = self.shell_blocked.saturating_add(other.shell_blocked);
102 self.path_blocked = self.path_blocked.saturating_add(other.path_blocked);
103 self.injection_flagged = self
104 .injection_flagged
105 .saturating_add(other.injection_flagged);
106 }
107
108 #[must_use]
110 pub fn since(&self, base: &Self) -> Self {
111 Self {
112 secrets_redacted: self.secrets_redacted.saturating_sub(base.secrets_redacted),
113 shell_blocked: self.shell_blocked.saturating_sub(base.shell_blocked),
114 path_blocked: self.path_blocked.saturating_sub(base.path_blocked),
115 injection_flagged: self
116 .injection_flagged
117 .saturating_sub(base.injection_flagged),
118 }
119 }
120
121 pub fn total(&self) -> u64 {
122 self.secrets_redacted
123 .saturating_add(self.shell_blocked)
124 .saturating_add(self.path_blocked)
125 .saturating_add(self.injection_flagged)
126 }
127
128 pub fn is_empty(&self) -> bool {
129 self.total() == 0
130 }
131
132 fn iter(&self) -> impl Iterator<Item = (SecurityKind, u64)> {
133 [
134 (SecurityKind::SecretRedacted, self.secrets_redacted),
135 (SecurityKind::ShellBlocked, self.shell_blocked),
136 (SecurityKind::PathBlocked, self.path_blocked),
137 (SecurityKind::InjectionFlagged, self.injection_flagged),
138 ]
139 .into_iter()
140 .filter(|(_, n)| *n > 0)
141 }
142}
143
144thread_local! {
145 static COLLECTOR: RefCell<Option<SecurityCounts>> = const { RefCell::new(None) };
146}
147
148pub fn note(kind: SecurityKind, n: usize) {
151 if n == 0 {
152 return;
153 }
154 COLLECTOR.with(|c| {
155 if let Some(counts) = c.borrow_mut().as_mut() {
156 counts.add(kind, n as u64);
157 }
158 });
159}
160
161pub fn collect<T>(f: impl FnOnce() -> T) -> (T, SecurityCounts) {
164 let outer = COLLECTOR.with(|c| c.borrow_mut().replace(SecurityCounts::default()));
165 let value = f();
166 let tally = COLLECTOR
167 .with(|c| std::mem::replace(&mut *c.borrow_mut(), outer))
168 .unwrap_or_default();
169 if let Some(mut outer) = outer {
170 outer.merge(&tally);
171 COLLECTOR.with(|c| *c.borrow_mut() = Some(outer));
172 }
173 (value, tally)
174}
175
176static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts {
178 secrets_redacted: 0,
179 shell_blocked: 0,
180 path_blocked: 0,
181 injection_flagged: 0,
182});
183
184pub fn record(tool: &str, agent_id: &str, counts: &SecurityCounts) {
187 if counts.is_empty() {
188 return;
189 }
190 let role = crate::core::roles::active_role_name();
191 let session = crate::core::value::current_session()
194 .map(|id| format!("|session={id}"))
195 .unwrap_or_default();
196 for (kind, n) in counts.iter() {
197 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
198 agent_id: agent_id.to_string(),
199 tool: tool.to_string(),
200 action: Some(format!("{}:{n}{session}", kind.as_str())),
201 input_hash: String::new(),
202 output_tokens: 0,
203 role: role.clone(),
204 event_type: kind.audit_event_type(),
205 });
206 }
207 if let Ok(mut pending) = PENDING.lock() {
208 pending.merge(counts);
209 }
210}
211
212pub fn record_one(tool: &str, agent_id: &str, kind: SecurityKind) {
214 let mut counts = SecurityCounts::default();
215 counts.add(kind, 1);
216 record(tool, agent_id, &counts);
217}
218
219pub fn drain_pending() -> SecurityCounts {
222 PENDING
223 .lock()
224 .map(|mut pending| std::mem::take(&mut *pending))
225 .unwrap_or_default()
226}
227
228pub fn parse_action(action: &str) -> Option<(SecurityKind, u64, Option<&str>)> {
230 let kind = SecurityKind::from_action(action)?;
231 let rest = action.split_once(':').map_or("", |(_, rest)| rest);
232 let (n, session) = match rest.split_once("|session=") {
233 Some((n, session)) => (n, Some(session)),
234 None => (rest, None),
235 };
236 Some((kind, n.parse().unwrap_or(1), session))
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 #[test]
244 fn note_outside_collector_is_dropped() {
245 note(SecurityKind::SecretRedacted, 3);
246 let ((), tally) = collect(|| {});
247 assert!(tally.is_empty());
248 }
249
250 #[test]
251 fn collect_counts_only_its_own_handler() {
252 let ((), tally) = collect(|| {
253 note(SecurityKind::SecretRedacted, 2);
254 note(SecurityKind::ShellBlocked, 1);
255 });
256 assert_eq!(tally.secrets_redacted, 2);
257 assert_eq!(tally.shell_blocked, 1);
258 assert_eq!(tally.total(), 3);
259
260 let ((), next) = collect(|| {});
261 assert!(
262 next.is_empty(),
263 "a collector never leaks into the next call"
264 );
265 }
266
267 #[test]
268 fn nested_collect_keeps_outer_total() {
269 let ((), outer) = collect(|| {
270 note(SecurityKind::PathBlocked, 1);
271 let ((), inner) = collect(|| note(SecurityKind::PathBlocked, 1));
272 assert_eq!(inner.path_blocked, 1);
273 });
274 assert_eq!(outer.path_blocked, 2);
275 }
276
277 #[test]
278 fn action_roundtrips_kind() {
279 for kind in [
280 SecurityKind::SecretRedacted,
281 SecurityKind::ShellBlocked,
282 SecurityKind::PathBlocked,
283 SecurityKind::InjectionFlagged,
284 ] {
285 let action = format!("{}:4", kind.as_str());
286 assert_eq!(SecurityKind::from_action(&action), Some(kind));
287 }
288 assert_eq!(SecurityKind::from_action("tool_call"), None);
289 }
290
291 #[test]
292 fn parse_action_reads_count_and_session() {
293 assert_eq!(
294 parse_action("secret_redacted:3|session=abc"),
295 Some((SecurityKind::SecretRedacted, 3, Some("abc")))
296 );
297 assert_eq!(
298 parse_action("shell_blocked:1"),
299 Some((SecurityKind::ShellBlocked, 1, None))
300 );
301 }
302
303 #[test]
304 fn old_session_json_loads_with_zero_counts() {
305 let counts: SecurityCounts = serde_json::from_str("{}").unwrap();
306 assert!(counts.is_empty());
307 }
308}