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.
19//!
20//! The audit trail's `event_type` enum is **not** extended: an older binary
21//! verifying a trail that contains an unknown variant would report it as
22//! tampered. The kind is committed in the (hashed) `action` field instead.
23
24use std::cell::RefCell;
25use std::sync::Mutex;
26
27use serde::{Deserialize, Serialize};
28
29/// What a protection did. The wording each kind renders with is part of the
30/// honesty contract: injections are *flagged*, never "neutralized".
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum SecurityKind {
33    /// A secret was replaced by `[REDACTED:…]` before the model saw it.
34    SecretRedacted,
35    /// A shell command was refused by the allowlist / dangerous-pattern gate.
36    ShellBlocked,
37    /// A path outside the project jail was refused.
38    PathBlocked,
39    /// Tool output matched prompt-injection patterns and was flagged.
40    InjectionFlagged,
41    /// A checksum-validated PII value was masked by the context gateway.
42    PiiRedacted,
43    /// The context gateway withheld a source entirely.
44    ContentWithheld,
45    /// A source was delivered although a detector did not inspect all of it.
46    CoverageIncomplete,
47}
48
49impl SecurityKind {
50    /// Stable identifier committed into the audit trail's `action` field.
51    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    /// Existing trail event types only: an unknown variant would read as
64    /// tampering to an older verifier, so the kind lives in `action`.
65    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    /// Parses the `action` prefix written by [`record`] back into a kind.
76    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    /// Kinds a signed savings-batch tally carries; server mirrors verify the
82    /// tally field by field and predate the context-gateway kinds.
83    #[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/// Per-kind event counts. Persisted inside `SessionStats`, so every field is
103/// `serde(default)` and old session files load unchanged.
104///
105/// The context-gateway kinds are written only when non-zero: every count
106/// serialized before they existed keeps its exact bytes (signed tallies, see
107/// [`Self::signed_tally_projection`]).
108#[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    /// The counts a signed savings-batch tally carries. Server mirrors verify
130    /// the tally field by field and do not know the gateway kinds yet, so they
131    /// are left out (zero, hence not serialized) instead of breaking the
132    /// signature; the audit trail still proves them locally.
133    #[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    /// Events since `base` (a counter never goes below zero).
189    #[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
220/// Notes `n` firings of `kind` into the collector of the tool call running on
221/// this thread. A no-op outside [`collect`] — see the module docs for why.
222pub 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
233/// Runs `f` (one synchronous tool handler) with a fresh collector and returns
234/// what it noted. Nested calls keep the outer collector's tally intact.
235pub 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
248/// Counts recorded since the MCP server last drained them into its session.
249static PENDING: Mutex<SecurityCounts> = Mutex::new(SecurityCounts::ZERO);
250
251/// Records one tool result's security tally: one audit-trail entry per kind
252/// (the proof) plus the pending session counters (the display).
253pub 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    // The session id rides in the hashed `action` field (the trail's timestamp
259    // is not hashed), so per-session security claims are chain-backed.
260    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
279/// Anchors a Context Gateway receipt in the signed, hash-chained audit trail:
280/// the digest in the hashed `action` binds the stored receipt to the chain.
281/// Not a counted kind (`parse_action` ignores it), so nothing is counted twice.
282pub 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
297/// Convenience for a single event recorded outside a handler (dispatch layer).
298pub 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
304/// Takes the counts recorded since the last drain (the MCP server folds them
305/// into the current session's stats).
306pub fn drain_pending() -> SecurityCounts {
307    PENDING
308        .lock()
309        .map(|mut pending| std::mem::take(&mut *pending))
310        .unwrap_or_default()
311}
312
313/// Splits a recorded `action` (`<kind>:<n>[|session=<id>]`) into its parts.
314pub 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}