1use std::cell::RefCell;
27use std::sync::Mutex;
28
29use serde::{Deserialize, Serialize};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum SecurityKind {
35 SecretRedacted,
37 ShellBlocked,
39 PathBlocked,
41 InjectionFlagged,
43 PiiRedacted,
45 ContentWithheld,
47 CoverageIncomplete,
49}
50
51impl SecurityKind {
52 pub const fn as_str(self) -> &'static str {
54 match self {
55 Self::SecretRedacted => "secret_redacted",
56 Self::ShellBlocked => "shell_blocked",
57 Self::PathBlocked => "path_blocked",
58 Self::InjectionFlagged => "injection_flagged",
59 Self::PiiRedacted => "pii_redacted",
60 Self::ContentWithheld => "content_withheld",
61 Self::CoverageIncomplete => "coverage_incomplete",
62 }
63 }
64
65 fn audit_event_type(self) -> crate::core::audit_trail::AuditEventType {
68 use crate::core::audit_trail::AuditEventType;
69 match self {
70 Self::SecretRedacted | Self::PiiRedacted => AuditEventType::SecretDetected,
71 Self::ShellBlocked | Self::ContentWithheld => AuditEventType::ToolDenied,
72 Self::PathBlocked => AuditEventType::PathJailViolation,
73 Self::InjectionFlagged | Self::CoverageIncomplete => AuditEventType::SecurityViolation,
74 }
75 }
76
77 pub fn from_action(action: &str) -> Option<Self> {
79 let kind = action.split(':').next()?;
80 Self::ALL.into_iter().find(|k| k.as_str() == kind)
81 }
82
83 #[must_use]
86 pub const fn in_signed_tally(self) -> bool {
87 matches!(
88 self,
89 Self::SecretRedacted | Self::ShellBlocked | Self::PathBlocked | Self::InjectionFlagged
90 )
91 }
92
93 const ALL: [Self; 7] = [
94 Self::SecretRedacted,
95 Self::ShellBlocked,
96 Self::PathBlocked,
97 Self::InjectionFlagged,
98 Self::PiiRedacted,
99 Self::ContentWithheld,
100 Self::CoverageIncomplete,
101 ];
102}
103
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
111#[serde(default)]
112pub struct SecurityCounts {
113 pub secrets_redacted: u64,
114 pub shell_blocked: u64,
115 pub path_blocked: u64,
116 pub injection_flagged: u64,
117 #[serde(skip_serializing_if = "is_zero")]
118 pub pii_redacted: u64,
119 #[serde(skip_serializing_if = "is_zero")]
120 pub content_withheld: u64,
121 #[serde(skip_serializing_if = "is_zero")]
122 pub coverage_incomplete: u64,
123}
124
125#[allow(clippy::trivially_copy_pass_by_ref)]
126fn is_zero(n: &u64) -> bool {
127 *n == 0
128}
129
130impl SecurityCounts {
131 #[must_use]
136 pub fn signed_tally_projection(&self) -> Self {
137 Self {
138 pii_redacted: 0,
139 content_withheld: 0,
140 coverage_incomplete: 0,
141 ..*self
142 }
143 }
144
145 pub const ZERO: Self = Self {
146 secrets_redacted: 0,
147 shell_blocked: 0,
148 path_blocked: 0,
149 injection_flagged: 0,
150 pii_redacted: 0,
151 content_withheld: 0,
152 coverage_incomplete: 0,
153 };
154
155 fn slot(&mut self, kind: SecurityKind) -> &mut u64 {
156 match kind {
157 SecurityKind::SecretRedacted => &mut self.secrets_redacted,
158 SecurityKind::ShellBlocked => &mut self.shell_blocked,
159 SecurityKind::PathBlocked => &mut self.path_blocked,
160 SecurityKind::InjectionFlagged => &mut self.injection_flagged,
161 SecurityKind::PiiRedacted => &mut self.pii_redacted,
162 SecurityKind::ContentWithheld => &mut self.content_withheld,
163 SecurityKind::CoverageIncomplete => &mut self.coverage_incomplete,
164 }
165 }
166
167 fn get(&self, kind: SecurityKind) -> u64 {
168 match kind {
169 SecurityKind::SecretRedacted => self.secrets_redacted,
170 SecurityKind::ShellBlocked => self.shell_blocked,
171 SecurityKind::PathBlocked => self.path_blocked,
172 SecurityKind::InjectionFlagged => self.injection_flagged,
173 SecurityKind::PiiRedacted => self.pii_redacted,
174 SecurityKind::ContentWithheld => self.content_withheld,
175 SecurityKind::CoverageIncomplete => self.coverage_incomplete,
176 }
177 }
178
179 pub fn add(&mut self, kind: SecurityKind, n: u64) {
180 let slot = self.slot(kind);
181 *slot = slot.saturating_add(n);
182 }
183
184 pub fn merge(&mut self, other: &Self) {
185 for kind in SecurityKind::ALL {
186 self.add(kind, other.get(kind));
187 }
188 }
189
190 #[must_use]
192 pub fn since(&self, base: &Self) -> Self {
193 let mut out = Self::ZERO;
194 for kind in SecurityKind::ALL {
195 *out.slot(kind) = self.get(kind).saturating_sub(base.get(kind));
196 }
197 out
198 }
199
200 pub fn total(&self) -> u64 {
201 SecurityKind::ALL
202 .into_iter()
203 .fold(0u64, |sum, kind| sum.saturating_add(self.get(kind)))
204 }
205
206 pub fn is_empty(&self) -> bool {
207 self.total() == 0
208 }
209
210 fn iter(&self) -> impl Iterator<Item = (SecurityKind, u64)> + '_ {
211 SecurityKind::ALL
212 .into_iter()
213 .map(|kind| (kind, self.get(kind)))
214 .filter(|(_, n)| *n > 0)
215 }
216}
217
218thread_local! {
219 static COLLECTOR: RefCell<Option<SecurityCounts>> = const { RefCell::new(None) };
220}
221
222pub fn note(kind: SecurityKind, n: usize) {
225 if n == 0 {
226 return;
227 }
228 COLLECTOR.with(|c| {
229 if let Some(counts) = c.borrow_mut().as_mut() {
230 counts.add(kind, n as u64);
231 }
232 });
233}
234
235pub fn collect<T>(f: impl FnOnce() -> T) -> (T, SecurityCounts) {
238 let outer = COLLECTOR.with(|c| c.borrow_mut().replace(SecurityCounts::default()));
239 let value = f();
240 let tally = COLLECTOR
241 .with(|c| std::mem::replace(&mut *c.borrow_mut(), outer))
242 .unwrap_or_default();
243 if let Some(mut outer) = outer {
244 outer.merge(&tally);
245 COLLECTOR.with(|c| *c.borrow_mut() = Some(outer));
246 }
247 (value, tally)
248}
249
250static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts::ZERO);
252
253pub fn record(tool: &str, agent_id: &str, counts: &SecurityCounts) {
256 if counts.is_empty() {
257 return;
258 }
259 let role = crate::core::roles::active_role_name();
260 let session = crate::core::value::current_session()
263 .map(|id| format!("|session={id}"))
264 .unwrap_or_default();
265 for (kind, n) in counts.iter() {
266 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
267 agent_id: agent_id.to_string(),
268 tool: tool.to_string(),
269 action: Some(format!("{}:{n}{session}", kind.as_str())),
270 input_hash: String::new(),
271 output_tokens: 0,
272 role: role.clone(),
273 event_type: kind.audit_event_type(),
274 });
275 }
276 if let Ok(mut pending) = PENDING.lock() {
277 pending.merge(counts);
278 }
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct InjectionFlag {
285 pub object_sha256: String,
287 pub patterns: u8,
289}
290
291const SEEN_INJECTIONS_CAPACITY: usize = 4096;
293
294static SEEN_INJECTIONS: Mutex<Option<lru::LruCache<String, ()>>> = Mutex::new(None);
296
297fn first_sighting(object_sha256: &str) -> bool {
302 let Ok(mut seen) = SEEN_INJECTIONS.lock() else {
303 return false;
305 };
306 let seen = seen.get_or_insert_with(|| {
307 lru::LruCache::new(
308 std::num::NonZeroUsize::new(SEEN_INJECTIONS_CAPACITY).expect("non-zero capacity"),
309 )
310 });
311 seen.put(object_sha256.to_owned(), ()).is_none()
312}
313
314fn injection_action(flag: &InjectionFlag, session: &str) -> String {
318 let prefix: String = flag.object_sha256.chars().take(12).collect();
319 format!(
320 "{}:1|pattern={}|object={prefix}{session}",
321 SecurityKind::InjectionFlagged.as_str(),
322 crate::core::output_sanitizer::InjectionCategory::describe(flag.patterns),
323 )
324}
325
326pub fn record_injections(tool: &str, agent_id: &str, flags: &[InjectionFlag]) -> u64 {
330 let fresh: Vec<&InjectionFlag> = flags
331 .iter()
332 .filter(|flag| first_sighting(&flag.object_sha256))
333 .collect();
334 if fresh.is_empty() {
335 return 0;
336 }
337 let role = crate::core::roles::active_role_name();
338 let session = crate::core::value::current_session()
339 .map(|id| format!("|session={id}"))
340 .unwrap_or_default();
341 for flag in &fresh {
342 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
343 agent_id: agent_id.to_string(),
344 tool: tool.to_string(),
345 action: Some(injection_action(flag, &session)),
346 input_hash: String::new(),
347 output_tokens: 0,
348 role: role.clone(),
349 event_type: SecurityKind::InjectionFlagged.audit_event_type(),
350 });
351 }
352 let recorded = fresh.len() as u64;
353 if let Ok(mut pending) = PENDING.lock() {
354 pending.add(SecurityKind::InjectionFlagged, recorded);
355 }
356 recorded
357}
358
359pub fn anchor_receipt(tool: &str, agent_id: &str, receipt_sha256_hex: &str) {
363 let session = crate::core::value::current_session()
364 .map(|id| format!("|session={id}"))
365 .unwrap_or_default();
366 crate::core::audit_trail::record(crate::core::audit_trail::AuditEntryData {
367 agent_id: agent_id.to_string(),
368 tool: tool.to_string(),
369 action: Some(format!("gateway_receipt:{receipt_sha256_hex}{session}")),
370 input_hash: String::new(),
371 output_tokens: 0,
372 role: crate::core::roles::active_role_name(),
373 event_type: crate::core::audit_trail::AuditEventType::ToolCall,
374 });
375}
376
377pub fn record_one(tool: &str, agent_id: &str, kind: SecurityKind) {
379 let mut counts = SecurityCounts::default();
380 counts.add(kind, 1);
381 record(tool, agent_id, &counts);
382}
383
384pub fn drain_pending() -> SecurityCounts {
387 PENDING
388 .lock()
389 .map(|mut pending| std::mem::take(&mut *pending))
390 .unwrap_or_default()
391}
392
393pub fn parse_action(action: &str) -> Option<(SecurityKind, u64, Option<&str>)> {
396 let kind = SecurityKind::from_action(action)?;
397 let rest = action.split_once(':').map_or("", |(_, rest)| rest);
398 let (head, session) = match rest.split_once("|session=") {
399 Some((head, session)) => (head, Some(session)),
400 None => (rest, None),
401 };
402 let n = head.split('|').next().unwrap_or(head);
403 Some((kind, n.parse().unwrap_or(1), session))
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 #[test]
411 fn note_outside_collector_is_dropped() {
412 note(SecurityKind::SecretRedacted, 3);
413 let ((), tally) = collect(|| {});
414 assert!(tally.is_empty());
415 }
416
417 #[test]
418 fn collect_counts_only_its_own_handler() {
419 let ((), tally) = collect(|| {
420 note(SecurityKind::SecretRedacted, 2);
421 note(SecurityKind::ShellBlocked, 1);
422 });
423 assert_eq!(tally.secrets_redacted, 2);
424 assert_eq!(tally.shell_blocked, 1);
425 assert_eq!(tally.total(), 3);
426
427 let ((), next) = collect(|| {});
428 assert!(
429 next.is_empty(),
430 "a collector never leaks into the next call"
431 );
432 }
433
434 #[test]
435 fn nested_collect_keeps_outer_total() {
436 let ((), outer) = collect(|| {
437 note(SecurityKind::PathBlocked, 1);
438 let ((), inner) = collect(|| note(SecurityKind::PathBlocked, 1));
439 assert_eq!(inner.path_blocked, 1);
440 });
441 assert_eq!(outer.path_blocked, 2);
442 }
443
444 #[test]
445 fn action_roundtrips_kind() {
446 for kind in [
447 SecurityKind::SecretRedacted,
448 SecurityKind::ShellBlocked,
449 SecurityKind::PathBlocked,
450 SecurityKind::InjectionFlagged,
451 ] {
452 let action = format!("{}:4", kind.as_str());
453 assert_eq!(SecurityKind::from_action(&action), Some(kind));
454 }
455 assert_eq!(SecurityKind::from_action("tool_call"), None);
456 }
457
458 #[test]
459 fn parse_action_reads_count_and_session() {
460 assert_eq!(
461 parse_action("secret_redacted:3|session=abc"),
462 Some((SecurityKind::SecretRedacted, 3, Some("abc")))
463 );
464 assert_eq!(
465 parse_action("shell_blocked:1"),
466 Some((SecurityKind::ShellBlocked, 1, None))
467 );
468 }
469
470 #[test]
471 fn a_flagged_object_is_recorded_once_per_process() {
472 let object = "f".repeat(63) + "1";
473 assert!(first_sighting(&object), "first delivery is recorded");
474 assert!(!first_sighting(&object), "a re-read is not a new finding");
475 assert!(first_sighting(&("f".repeat(63) + "2")));
476 }
477
478 #[test]
479 fn injection_action_explains_without_content_and_parses() {
480 let flag = InjectionFlag {
481 object_sha256: "0123456789abcdef".repeat(4),
482 patterns: crate::core::output_sanitizer::InjectionCategory::RoleMarker.bit(),
483 };
484 let action = injection_action(&flag, "|session=s1");
485 assert_eq!(
486 action,
487 "injection_flagged:1|pattern=role_marker|object=0123456789ab|session=s1"
488 );
489 assert_eq!(
490 parse_action(&action),
491 Some((SecurityKind::InjectionFlagged, 1, Some("s1")))
492 );
493 assert_eq!(
494 parse_action(&injection_action(&flag, "")),
495 Some((SecurityKind::InjectionFlagged, 1, None))
496 );
497 }
498
499 #[test]
500 fn old_session_json_loads_with_zero_counts() {
501 let counts: SecurityCounts = serde_json::from_str("{}").unwrap();
502 assert!(counts.is_empty());
503 }
504}