Skip to main content

lean_ctx/core/
security_events.rs

1//! Provable security events for the value surface.
2//!
3//! lean-ctx's default-on protections (secret redaction, the shell allowlist,
4//! the path jail, prompt-injection screening) used to act silently: nothing a
5//! user could later point to. This module turns each firing into
6//!
7//! 1. a hash-chained, signed [`crate::core::audit_trail`] entry — the proof, and
8//! 2. a session counter ([`SecurityCounts`]) — what the status line shows.
9//!
10//! Counting is **once per tool result**. Deep code (redaction, allowlist) calls
11//! [`note`], which only lands in the collector that
12//! [`collect`] opens around one MCP tool handler; the dispatch layer then
13//! records the tally for that single result. `note` outside a collector (CLI,
14//! hooks, config loading) is deliberately dropped, so a secret redacted twice
15//! on its way through nested passes, or a re-rendered cache entry outside a
16//! tool call, never inflates the count. Undercounting is acceptable; claiming
17//! more than happened is not.
18//!
19//! The audit trail's `event_type` enum is **not** extended: an older binary
20//! verifying a trail that contains an unknown variant would report it as
21//! tampered. The kind is committed in the (hashed) `action` field instead.
22
23use std::cell::RefCell;
24use std::sync::Mutex;
25
26use serde::{Deserialize, Serialize};
27
28/// What a protection did. The wording each kind renders with is part of the
29/// honesty contract: injections are *flagged*, never "neutralized".
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SecurityKind {
32    /// A secret was replaced by `[REDACTED:…]` before the model saw it.
33    SecretRedacted,
34    /// A shell command was refused by the allowlist / dangerous-pattern gate.
35    ShellBlocked,
36    /// A path outside the project jail was refused.
37    PathBlocked,
38    /// Tool output matched prompt-injection patterns and was flagged.
39    InjectionFlagged,
40}
41
42impl SecurityKind {
43    /// Stable identifier committed into the audit trail's `action` field.
44    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    /// Parses the `action` prefix written by [`record`] back into a kind.
64    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/// Per-kind event counts. Persisted inside `SessionStats`, so every field is
78/// `serde(default)` and old session files load unchanged.
79#[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    /// Events since `base` (a counter never goes below zero).
109    #[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
148/// Notes `n` firings of `kind` into the collector of the tool call running on
149/// this thread. A no-op outside [`collect`] — see the module docs for why.
150pub 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
161/// Runs `f` (one synchronous tool handler) with a fresh collector and returns
162/// what it noted. Nested calls keep the outer collector's tally intact.
163pub 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
176/// Counts recorded since the MCP server last drained them into its session.
177static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts {
178    secrets_redacted: 0,
179    shell_blocked: 0,
180    path_blocked: 0,
181    injection_flagged: 0,
182});
183
184/// Records one tool result's security tally: one audit-trail entry per kind
185/// (the proof) plus the pending session counters (the display).
186pub 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    // The session id rides in the hashed `action` field (the trail's timestamp
192    // is not hashed), so per-session security claims are chain-backed.
193    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
212/// Convenience for a single event recorded outside a handler (dispatch layer).
213pub 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
219/// Takes the counts recorded since the last drain (the MCP server folds them
220/// into the current session's stats).
221pub fn drain_pending() -> SecurityCounts {
222    PENDING
223        .lock()
224        .map(|mut pending| std::mem::take(&mut *pending))
225        .unwrap_or_default()
226}
227
228/// Splits a recorded `action` (`<kind>:<n>[|session=<id>]`) into its parts.
229pub 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}