Skip to main content

lean_ctx/core/
security_events.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Provable security events for the value surface.
3//!
4//! lean-ctx's default-on protections (secret redaction, the shell allowlist,
5//! the path jail, prompt-injection screening) used to act silently: nothing a
6//! user could later point to. This module turns each firing into
7//!
8//! 1. a hash-chained, signed [`crate::core::audit_trail`] entry — the proof, and
9//! 2. a session counter ([`SecurityCounts`]) — what the status line shows.
10//!
11//! Counting is **once per tool result**. Deep code (redaction, allowlist) calls
12//! [`note`], which only lands in the collector that
13//! [`collect`] opens around one MCP tool handler; the dispatch layer then
14//! records the tally for that single result. `note` outside a collector (CLI,
15//! hooks, config loading) is deliberately dropped, so a secret redacted twice
16//! on its way through nested passes, or a re-rendered cache entry outside a
17//! tool call, never inflates the count. Undercounting is acceptable; claiming
18//! more than happened is not. Prompt-injection flags go further: one per
19//! flagged object per process ([`record_injections`]), however often the same
20//! object is delivered again.
21//!
22//! The audit trail's `event_type` enum is **not** extended: an older binary
23//! verifying a trail that contains an unknown variant would report it as
24//! tampered. The kind is committed in the (hashed) `action` field instead.
25
26use std::cell::RefCell;
27use std::sync::Mutex;
28
29use serde::{Deserialize, Serialize};
30
31/// What a protection did. The wording each kind renders with is part of the
32/// honesty contract: injections are *flagged*, never "neutralized".
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum SecurityKind {
35    /// A secret was replaced by `[REDACTED:…]` before the model saw it.
36    SecretRedacted,
37    /// A shell command was refused by the allowlist / dangerous-pattern gate.
38    ShellBlocked,
39    /// A path outside the project jail was refused.
40    PathBlocked,
41    /// Tool output matched prompt-injection patterns and was flagged.
42    InjectionFlagged,
43    /// A checksum-validated PII value was masked by the context gateway.
44    PiiRedacted,
45    /// The context gateway withheld a source entirely.
46    ContentWithheld,
47    /// A source was delivered although a detector did not inspect all of it.
48    CoverageIncomplete,
49}
50
51impl SecurityKind {
52    /// Stable identifier committed into the audit trail's `action` field.
53    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    /// Existing trail event types only: an unknown variant would read as
66    /// tampering to an older verifier, so the kind lives in `action`.
67    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    /// Parses the `action` prefix written by [`record`] back into a kind.
78    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    /// Kinds a signed savings-batch tally carries; server mirrors verify the
84    /// tally field by field and predate the context-gateway kinds.
85    #[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/// Per-kind event counts. Persisted inside `SessionStats`, so every field is
105/// `serde(default)` and old session files load unchanged.
106///
107/// The context-gateway kinds are written only when non-zero: every count
108/// serialized before they existed keeps its exact bytes (signed tallies, see
109/// [`Self::signed_tally_projection`]).
110#[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    /// The counts a signed savings-batch tally carries. Server mirrors verify
132    /// the tally field by field and do not know the gateway kinds yet, so they
133    /// are left out (zero, hence not serialized) instead of breaking the
134    /// signature; the audit trail still proves them locally.
135    #[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    /// Events since `base` (a counter never goes below zero).
191    #[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
222/// Notes `n` firings of `kind` into the collector of the tool call running on
223/// this thread. A no-op outside [`collect`] — see the module docs for why.
224pub 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
235/// Runs `f` (one synchronous tool handler) with a fresh collector and returns
236/// what it noted. Nested calls keep the outer collector's tally intact.
237pub 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
250/// Counts recorded since the MCP server last drained them into its session.
251static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts::ZERO);
252
253/// Records one tool result's security tally: one audit-trail entry per kind
254/// (the proof) plus the pending session counters (the display).
255pub 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    // The session id rides in the hashed `action` field (the trail's timestamp
261    // is not hashed), so per-session security claims are chain-backed.
262    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/// One object the prompt-injection heuristic flagged: which pattern families
282/// matched and the object's SHA-256 — never its content.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct InjectionFlag {
285    /// Lowercase hex SHA-256 of the flagged object.
286    pub object_sha256: String,
287    /// [`crate::core::output_sanitizer::InjectionCategory`] bits.
288    pub patterns: u8,
289}
290
291/// Flagged objects remembered per process (a few hundred KiB at most).
292const SEEN_INJECTIONS_CAPACITY: usize = 4096;
293
294/// Digests of flagged objects recorded by this process, bounded LRU.
295static SEEN_INJECTIONS: Mutex<Option<lru::LruCache<String, ()>>> = Mutex::new(None);
296
297/// Whether this process records `object_sha256` for the first time. The
298/// proxy re-admits the unchanged history of every turn and agents re-read the
299/// same files: the object is one finding, not one per delivery. Receipts
300/// still carry the per-delivery signal.
301fn first_sighting(object_sha256: &str) -> bool {
302    let Ok(mut seen) = SEEN_INJECTIONS.lock() else {
303        // Undercounting is acceptable; claiming more than happened is not.
304        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
314/// The audit `action` of one flagged object: the count first (older readers
315/// parse `<kind>:<n>` up to the session), then what matched and a short
316/// object digest prefix, then the session.
317fn 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
326/// Records flagged objects: one audit-trail entry per object this process has
327/// not recorded yet (with the pattern kinds and a digest prefix, never
328/// content) plus the pending session counter. Returns how many were recorded.
329pub 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
359/// Anchors a Context Gateway receipt in the signed, hash-chained audit trail:
360/// the digest in the hashed `action` binds the stored receipt to the chain.
361/// Not a counted kind (`parse_action` ignores it), so nothing is counted twice.
362pub 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
377/// Convenience for a single event recorded outside a handler (dispatch layer).
378pub 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
384/// Takes the counts recorded since the last drain (the MCP server folds them
385/// into the current session's stats).
386pub fn drain_pending() -> SecurityCounts {
387    PENDING
388        .lock()
389        .map(|mut pending| std::mem::take(&mut *pending))
390        .unwrap_or_default()
391}
392
393/// Splits a recorded `action` (`<kind>:<n>[|<detail>…][|session=<id>]`) into
394/// its parts; details (an injection flag's pattern kinds) are skipped.
395pub 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}