Skip to main content

lean_ctx/core/
cloud_signals.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Engine signal counts (K10, K12, K13) and redacted-secret hits (K21),
3//! named where they happen: an output served truncated or fetched back, a
4//! rule that refused or would have, programs no rule covers, a secret the
5//! redaction path removed.
6//!
7//! This module only names what happened, as closed wire names
8//! (`FilterName`, `RuleId`, `UnregulatedName` of
9//! `lean_ctx_protocol::cloud::metrics_v2`), never a path, a command line or
10//! a mode argument. Where a record goes, and whether one is kept at all, is
11//! the Cloud connector's: it registers a [`SignalRecorder`] at start-up
12//! ([`register_signal_recorder`]). Without one (library use, tests)
13//! nothing is recorded. These are counts only; no refusal depends on them.
14
15use std::sync::OnceLock;
16
17use lean_ctx_protocol::cloud::metrics_v2::{
18    FilterName, KNOWN_PROGRAMS, OTHER, ReadMode, RuleId, UnregulatedName,
19};
20use serde::{Deserialize, Serialize};
21
22/// What one record counts.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum SignalKind {
26    Truncated,
27    Refetched,
28    Blocked,
29    WouldBlock,
30    UnregulatedProgram,
31    UnregulatedHost,
32    UnregulatedMcpServer,
33}
34
35/// Where signals and secret hits are recorded.
36#[derive(Clone, Copy)]
37pub struct SignalRecorder {
38    /// Whether anything is recorded now.
39    pub recording: fn() -> bool,
40    /// Record one count of `kind` per name.
41    pub record: fn(SignalKind, &[&str]),
42    /// Record redacted secrets by their redaction labels.
43    pub secrets: fn(&[&str]),
44}
45
46static RECORDER: OnceLock<SignalRecorder> = OnceLock::new();
47
48/// Register the signal recorder. The first registration wins.
49pub fn register_signal_recorder(recorder: SignalRecorder) {
50    let _ = RECORDER.set(recorder);
51}
52
53/// Whether anything is recorded now, so a caller can skip work whose only
54/// use is a record.
55pub fn recording() -> bool {
56    RECORDER.get().is_some_and(|r| (r.recording)())
57}
58
59pub fn record(kind: SignalKind, names: &[&str]) {
60    if let Some(recorder) = RECORDER.get() {
61        (recorder.record)(kind, names);
62    }
63}
64
65/// K21: secrets the redaction path removed, by their labels. Never sees the
66/// secret value; never fails the redaction.
67pub fn note_secrets(labels: &[&str]) {
68    if labels.is_empty() {
69        return;
70    }
71    if let Some(recorder) = RECORDER.get() {
72        (recorder.secrets)(labels);
73    }
74}
75
76/// The filter of a read mode (`lines:10-20` is `lines`).
77pub fn read_mode_filter(mode: &str) -> FilterName {
78    let mode = ReadMode::of(mode);
79    let wire = serde_json::to_value(mode)
80        .ok()
81        .and_then(|v| v.as_str().map(str::to_string))
82        .unwrap_or_else(|| OTHER.to_string());
83    FilterName::or_other(&wire)
84}
85
86/// The filter of a firewalled tool output.
87pub fn output_filter(tool: &str) -> FilterName {
88    FilterName::or_other(match tool {
89        "ctx_shell" | "ctx_execute" => "shell_output",
90        "ctx_search" => "search_output",
91        _ => OTHER,
92    })
93}
94
95/// A program as the known-program table names it, else `other`.
96pub fn program_name(base: &str) -> UnregulatedName {
97    let base = base.rsplit(['/', '\\']).next().unwrap_or(base);
98    let base = base.strip_suffix(".exe").unwrap_or(base);
99    UnregulatedName::new(base)
100        .filter(|_| KNOWN_PROGRAMS.contains(&base))
101        .unwrap_or_else(UnregulatedName::other)
102}
103
104/// The rule the path jail decides under.
105pub fn path_jail_rule() -> RuleId {
106    RuleId::or_other("gateway.path_jail")
107}
108
109/// The rule secret-like paths and secret filters decide under.
110pub fn secrets_rule() -> RuleId {
111    RuleId::or_other("security.block_secrets")
112}
113
114/// The rule the shell allowlist decides under.
115pub fn shell_rule() -> RuleId {
116    RuleId::or_other("gateway.security_violation")
117}
118
119/// The rules a withholding admission decision refused under, from its
120/// closed reason codes (never the destination or the content).
121pub fn admission_rules<'a>(reason_codes: impl IntoIterator<Item = &'a str>) -> Vec<RuleId> {
122    let mut rules: Vec<RuleId> = Vec::new();
123    for code in reason_codes {
124        let rule = match code {
125            "secret.blocked" => "security.block_secrets",
126            "pii.blocked" => "security.pii",
127            "classification.blocked" => "security.classification",
128            "destination.constraint_satisfied" | "destination.remote_allowed_once" => continue,
129            c if c.starts_with("destination.") => "gateway.destination",
130            c if c.starts_with("egress.") => "gateway.egress",
131            _ => continue,
132        };
133        let rule = RuleId::or_other(rule);
134        if !rules.contains(&rule) {
135            rules.push(rule);
136        }
137    }
138    rules
139}
140
141/// K10: an output served truncated, by filter.
142pub fn truncated(filter: &FilterName) {
143    record(SignalKind::Truncated, &[filter.as_str()]);
144}
145
146/// K10: a truncated output fetched back in full, by filter.
147pub fn refetched(filter: &FilterName) {
148    record(SignalKind::Refetched, &[filter.as_str()]);
149}
150
151/// K12: a refusal in force.
152pub fn blocked(rule: &RuleId) {
153    record(SignalKind::Blocked, &[rule.as_str()]);
154}
155
156/// K12: a refusal a rule in monitor mode would have made.
157pub fn would_block(rule: &RuleId) {
158    record(SignalKind::WouldBlock, &[rule.as_str()]);
159}
160
161/// K12: a refusal by `rule`, in force (`enforcing`) or in monitor mode.
162pub fn refused(rule: &RuleId, enforcing: bool) {
163    if enforcing {
164        blocked(rule);
165    } else {
166        would_block(rule);
167    }
168}
169
170/// K13: programs a command ran that no rule covers.
171pub fn unregulated_programs(programs: &[UnregulatedName]) {
172    let names: Vec<&str> = programs.iter().map(UnregulatedName::as_str).collect();
173    if !names.is_empty() {
174        record(SignalKind::UnregulatedProgram, &names);
175    }
176}
177
178/// K12: an admission decision that withheld content, by the rules it names.
179pub fn admission_refused<'a>(reason_codes: impl IntoIterator<Item = &'a str>) {
180    if !recording() {
181        return;
182    }
183    for rule in admission_rules(reason_codes) {
184        blocked(&rule);
185    }
186}