1use std::cell::RefCell;
25use std::sync::Mutex;
26
27use serde::{Deserialize, Serialize};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum SecurityKind {
33 SecretRedacted,
35 ShellBlocked,
37 PathBlocked,
39 InjectionFlagged,
41 PiiRedacted,
43 ContentWithheld,
45 CoverageIncomplete,
47}
48
49impl SecurityKind {
50 pub const fn as_str(self) -> &'static str {
52 match self {
53 Self::SecretRedacted => "secret_redacted",
54 Self::ShellBlocked => "shell_blocked",
55 Self::PathBlocked => "path_blocked",
56 Self::InjectionFlagged => "injection_flagged",
57 Self::PiiRedacted => "pii_redacted",
58 Self::ContentWithheld => "content_withheld",
59 Self::CoverageIncomplete => "coverage_incomplete",
60 }
61 }
62
63 fn audit_event_type(self) -> crate::core::audit_trail::AuditEventType {
66 use crate::core::audit_trail::AuditEventType;
67 match self {
68 Self::SecretRedacted | Self::PiiRedacted => AuditEventType::SecretDetected,
69 Self::ShellBlocked | Self::ContentWithheld => AuditEventType::ToolDenied,
70 Self::PathBlocked => AuditEventType::PathJailViolation,
71 Self::InjectionFlagged | Self::CoverageIncomplete => AuditEventType::SecurityViolation,
72 }
73 }
74
75 pub fn from_action(action: &str) -> Option<Self> {
77 let kind = action.split(':').next()?;
78 Self::ALL.into_iter().find(|k| k.as_str() == kind)
79 }
80
81 #[must_use]
84 pub const fn in_signed_tally(self) -> bool {
85 matches!(
86 self,
87 Self::SecretRedacted | Self::ShellBlocked | Self::PathBlocked | Self::InjectionFlagged
88 )
89 }
90
91 const ALL: [Self; 7] = [
92 Self::SecretRedacted,
93 Self::ShellBlocked,
94 Self::PathBlocked,
95 Self::InjectionFlagged,
96 Self::PiiRedacted,
97 Self::ContentWithheld,
98 Self::CoverageIncomplete,
99 ];
100}
101
102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(default)]
110pub struct SecurityCounts {
111 pub secrets_redacted: u64,
112 pub shell_blocked: u64,
113 pub path_blocked: u64,
114 pub injection_flagged: u64,
115 #[serde(skip_serializing_if = "is_zero")]
116 pub pii_redacted: u64,
117 #[serde(skip_serializing_if = "is_zero")]
118 pub content_withheld: u64,
119 #[serde(skip_serializing_if = "is_zero")]
120 pub coverage_incomplete: u64,
121}
122
123#[allow(clippy::trivially_copy_pass_by_ref)]
124fn is_zero(n: &u64) -> bool {
125 *n == 0
126}
127
128impl SecurityCounts {
129 #[must_use]
134 pub fn signed_tally_projection(&self) -> Self {
135 Self {
136 pii_redacted: 0,
137 content_withheld: 0,
138 coverage_incomplete: 0,
139 ..*self
140 }
141 }
142
143 pub const ZERO: Self = Self {
144 secrets_redacted: 0,
145 shell_blocked: 0,
146 path_blocked: 0,
147 injection_flagged: 0,
148 pii_redacted: 0,
149 content_withheld: 0,
150 coverage_incomplete: 0,
151 };
152
153 fn slot(&mut self, kind: SecurityKind) -> &mut u64 {
154 match kind {
155 SecurityKind::SecretRedacted => &mut self.secrets_redacted,
156 SecurityKind::ShellBlocked => &mut self.shell_blocked,
157 SecurityKind::PathBlocked => &mut self.path_blocked,
158 SecurityKind::InjectionFlagged => &mut self.injection_flagged,
159 SecurityKind::PiiRedacted => &mut self.pii_redacted,
160 SecurityKind::ContentWithheld => &mut self.content_withheld,
161 SecurityKind::CoverageIncomplete => &mut self.coverage_incomplete,
162 }
163 }
164
165 fn get(&self, kind: SecurityKind) -> u64 {
166 match kind {
167 SecurityKind::SecretRedacted => self.secrets_redacted,
168 SecurityKind::ShellBlocked => self.shell_blocked,
169 SecurityKind::PathBlocked => self.path_blocked,
170 SecurityKind::InjectionFlagged => self.injection_flagged,
171 SecurityKind::PiiRedacted => self.pii_redacted,
172 SecurityKind::ContentWithheld => self.content_withheld,
173 SecurityKind::CoverageIncomplete => self.coverage_incomplete,
174 }
175 }
176
177 pub fn add(&mut self, kind: SecurityKind, n: u64) {
178 let slot = self.slot(kind);
179 *slot = slot.saturating_add(n);
180 }
181
182 pub fn merge(&mut self, other: &Self) {
183 for kind in SecurityKind::ALL {
184 self.add(kind, other.get(kind));
185 }
186 }
187
188 #[must_use]
190 pub fn since(&self, base: &Self) -> Self {
191 let mut out = Self::ZERO;
192 for kind in SecurityKind::ALL {
193 *out.slot(kind) = self.get(kind).saturating_sub(base.get(kind));
194 }
195 out
196 }
197
198 pub fn total(&self) -> u64 {
199 SecurityKind::ALL
200 .into_iter()
201 .fold(0u64, |sum, kind| sum.saturating_add(self.get(kind)))
202 }
203
204 pub fn is_empty(&self) -> bool {
205 self.total() == 0
206 }
207
208 fn iter(&self) -> impl Iterator<Item = (SecurityKind, u64)> + '_ {
209 SecurityKind::ALL
210 .into_iter()
211 .map(|kind| (kind, self.get(kind)))
212 .filter(|(_, n)| *n > 0)
213 }
214}
215
216thread_local! {
217 static COLLECTOR: RefCell<Option<SecurityCounts>> = const { RefCell::new(None) };
218}
219
220pub fn note(kind: SecurityKind, n: usize) {
223 if n == 0 {
224 return;
225 }
226 COLLECTOR.with(|c| {
227 if let Some(counts) = c.borrow_mut().as_mut() {
228 counts.add(kind, n as u64);
229 }
230 });
231}
232
233pub fn collect<T>(f: impl FnOnce() -> T) -> (T, SecurityCounts) {
236 let outer = COLLECTOR.with(|c| c.borrow_mut().replace(SecurityCounts::default()));
237 let value = f();
238 let tally = COLLECTOR
239 .with(|c| std::mem::replace(&mut *c.borrow_mut(), outer))
240 .unwrap_or_default();
241 if let Some(mut outer) = outer {
242 outer.merge(&tally);
243 COLLECTOR.with(|c| *c.borrow_mut() = Some(outer));
244 }
245 (value, tally)
246}
247
248static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts::ZERO);
250
251pub fn record(tool: &str, agent_id: &str, counts: &SecurityCounts) {
254 if counts.is_empty() {
255 return;
256 }
257 let role = crate::core::roles::active_role_name();
258 let session = crate::core::value::current_session()
261 .map(|id| format!("|session={id}"))
262 .unwrap_or_default();
263 for (kind, n) in counts.iter() {
264 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
265 agent_id: agent_id.to_string(),
266 tool: tool.to_string(),
267 action: Some(format!("{}:{n}{session}", kind.as_str())),
268 input_hash: String::new(),
269 output_tokens: 0,
270 role: role.clone(),
271 event_type: kind.audit_event_type(),
272 });
273 }
274 if let Ok(mut pending) = PENDING.lock() {
275 pending.merge(counts);
276 }
277}
278
279pub fn anchor_receipt(tool: &str, agent_id: &str, receipt_sha256_hex: &str) {
283 let session = crate::core::value::current_session()
284 .map(|id| format!("|session={id}"))
285 .unwrap_or_default();
286 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
287 agent_id: agent_id.to_string(),
288 tool: tool.to_string(),
289 action: Some(format!("gateway_receipt:{receipt_sha256_hex}{session}")),
290 input_hash: String::new(),
291 output_tokens: 0,
292 role: crate::core::roles::active_role_name(),
293 event_type: crate::core::audit_trail::AuditEventType::ToolCall,
294 });
295}
296
297pub fn record_one(tool: &str, agent_id: &str, kind: SecurityKind) {
299 let mut counts = SecurityCounts::default();
300 counts.add(kind, 1);
301 record(tool, agent_id, &counts);
302}
303
304pub fn drain_pending() -> SecurityCounts {
307 PENDING
308 .lock()
309 .map(|mut pending| std::mem::take(&mut *pending))
310 .unwrap_or_default()
311}
312
313pub fn parse_action(action: &str) -> Option<(SecurityKind, u64, Option<&str>)> {
315 let kind = SecurityKind::from_action(action)?;
316 let rest = action.split_once(':').map_or("", |(_, rest)| rest);
317 let (n, session) = match rest.split_once("|session=") {
318 Some((n, session)) => (n, Some(session)),
319 None => (rest, None),
320 };
321 Some((kind, n.parse().unwrap_or(1), session))
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 #[test]
329 fn note_outside_collector_is_dropped() {
330 note(SecurityKind::SecretRedacted, 3);
331 let ((), tally) = collect(|| {});
332 assert!(tally.is_empty());
333 }
334
335 #[test]
336 fn collect_counts_only_its_own_handler() {
337 let ((), tally) = collect(|| {
338 note(SecurityKind::SecretRedacted, 2);
339 note(SecurityKind::ShellBlocked, 1);
340 });
341 assert_eq!(tally.secrets_redacted, 2);
342 assert_eq!(tally.shell_blocked, 1);
343 assert_eq!(tally.total(), 3);
344
345 let ((), next) = collect(|| {});
346 assert!(
347 next.is_empty(),
348 "a collector never leaks into the next call"
349 );
350 }
351
352 #[test]
353 fn nested_collect_keeps_outer_total() {
354 let ((), outer) = collect(|| {
355 note(SecurityKind::PathBlocked, 1);
356 let ((), inner) = collect(|| note(SecurityKind::PathBlocked, 1));
357 assert_eq!(inner.path_blocked, 1);
358 });
359 assert_eq!(outer.path_blocked, 2);
360 }
361
362 #[test]
363 fn action_roundtrips_kind() {
364 for kind in [
365 SecurityKind::SecretRedacted,
366 SecurityKind::ShellBlocked,
367 SecurityKind::PathBlocked,
368 SecurityKind::InjectionFlagged,
369 ] {
370 let action = format!("{}:4", kind.as_str());
371 assert_eq!(SecurityKind::from_action(&action), Some(kind));
372 }
373 assert_eq!(SecurityKind::from_action("tool_call"), None);
374 }
375
376 #[test]
377 fn parse_action_reads_count_and_session() {
378 assert_eq!(
379 parse_action("secret_redacted:3|session=abc"),
380 Some((SecurityKind::SecretRedacted, 3, Some("abc")))
381 );
382 assert_eq!(
383 parse_action("shell_blocked:1"),
384 Some((SecurityKind::ShellBlocked, 1, None))
385 );
386 }
387
388 #[test]
389 fn old_session_json_loads_with_zero_counts() {
390 let counts: SecurityCounts = serde_json::from_str("{}").unwrap();
391 assert!(counts.is_empty());
392 }
393}