Skip to main content

lean_ctx_cloud/knowledge/
screening.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The one mandatory path into the Cloud outbox for content.
3//!
4//! A text that carries a credential, personal data (email, phone, card,
5//! IBAN, national ids), anything the redaction rules would mask, a pattern
6//! the active egress policy forbids, or a local home path is dropped, never
7//! rewritten and sent. Every drop is counted for `engine_screening`.
8
9use lean_ctx_protocol::cloud::knowledge::EngineScreeningV1;
10
11/// Bumped whenever the rules below change meaning.
12pub const SCANNER_VERSION: u32 = 1;
13
14/// Why a text was dropped. Never carries the text itself.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Blocked {
17    Secret(String),
18    Pii(String),
19    Redaction,
20    Forbidden,
21    LocalPath,
22    /// A forbidden pattern of this installation does not compile: nothing
23    /// passes until it is fixed (fails closed, never silently unscreened).
24    BrokenRules(usize),
25}
26
27impl std::fmt::Display for Blocked {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        match self {
30            Self::Secret(kind) => write!(f, "credential ({kind})"),
31            Self::Pii(kind) => write!(f, "personal data ({kind})"),
32            Self::Redaction => f.write_str("matches a redaction rule"),
33            Self::Forbidden => f.write_str("matches a forbidden egress pattern or org filter"),
34            Self::LocalPath => f.write_str("contains a local home path"),
35            Self::BrokenRules(n) => write!(
36                f,
37                "cannot be screened: {n} egress forbidden pattern(s) of this machine do not compile, so nothing goes to LeanCTX Cloud until they are fixed (`lean-ctx policy` / `[egress] forbidden_patterns`)"
38            ),
39        }
40    }
41}
42
43/// Screening rules with their configuration resolved once.
44pub struct Screen {
45    custom_secret_patterns: Vec<String>,
46    redaction_excludes: std::sync::Arc<Vec<regex::Regex>>,
47    forbidden: Vec<regex::Regex>,
48    /// Forbidden patterns that did not compile: every text is refused.
49    broken: usize,
50    home: Option<String>,
51    counts: EngineScreeningV1,
52}
53
54impl Screen {
55    /// Rules of this installation (custom secret patterns, redaction
56    /// excludes, the active pack's `[egress] forbidden_patterns`). A pattern
57    /// that does not compile fails closed: the screen then refuses every
58    /// text ([`Blocked::BrokenRules`], [`Screen::problem`]).
59    pub fn for_installation() -> Self {
60        let config = lean_ctx::core::config::Config::load();
61        // The organization's Cloud filter packs (redact and block rules
62        // alike) keep a matching fact on this machine.
63        let cloud = crate::policy::installed_filter_rules();
64        let forbidden = lean_ctx::core::policy::runtime::active()
65            .map(|policy| policy.resolved.egress.forbidden_patterns.clone())
66            .unwrap_or_default()
67            .into_iter()
68            .chain(cloud.redaction.into_iter().map(|(_, pattern)| pattern))
69            .chain(cloud.blocked.into_iter().map(|(_, pattern)| pattern))
70            .map(|p| regex::Regex::new(&p))
71            .collect();
72        Self::with_compiled(
73            config.secret_detection.custom_patterns.clone(),
74            lean_ctx::core::redaction::config_exclude_patterns(),
75            forbidden,
76        )
77    }
78
79    /// [`Self::with_rules`] from compile results: an error counts as a
80    /// broken rule, never as no rule.
81    pub(crate) fn with_compiled(
82        custom_secret_patterns: Vec<String>,
83        redaction_excludes: std::sync::Arc<Vec<regex::Regex>>,
84        compiled: Vec<Result<regex::Regex, regex::Error>>,
85    ) -> Self {
86        let total = compiled.len();
87        let forbidden: Vec<regex::Regex> = compiled.into_iter().filter_map(Result::ok).collect();
88        let broken = total - forbidden.len();
89        if broken > 0 {
90            tracing::warn!("cloud screening: {broken} forbidden pattern(s) do not compile");
91        }
92        let mut screen = Self::with_rules(custom_secret_patterns, redaction_excludes, forbidden);
93        screen.broken = broken;
94        screen
95    }
96
97    /// Why this screen lets nothing pass (a broken rule), for status lines
98    /// and the callers that stop all Cloud content traffic on it.
99    pub fn problem(&self) -> Option<String> {
100        (self.broken > 0).then(|| {
101            format!(
102                "LeanCTX Cloud content traffic is paused: {}",
103                Blocked::BrokenRules(self.broken)
104            )
105        })
106    }
107
108    pub(crate) fn with_rules(
109        custom_secret_patterns: Vec<String>,
110        redaction_excludes: std::sync::Arc<Vec<regex::Regex>>,
111        forbidden: Vec<regex::Regex>,
112    ) -> Self {
113        let home = dirs::home_dir()
114            .map(|h| h.to_string_lossy().into_owned())
115            .filter(|h| h.len() > 1);
116        Self {
117            custom_secret_patterns,
118            redaction_excludes,
119            forbidden,
120            broken: 0,
121            home,
122            counts: EngineScreeningV1 {
123                scanner_version: SCANNER_VERSION,
124                secrets_removed: 0,
125                pii_removed: 0,
126                items_dropped: 0,
127            },
128        }
129    }
130
131    /// `Ok(())` when `text` may leave the machine; otherwise the reason, and
132    /// the drop is counted.
133    pub fn check(&mut self, text: &str) -> Result<(), Blocked> {
134        let verdict = self.verdict(text);
135        if let Err(reason) = &verdict {
136            self.counts.items_dropped += 1;
137            match reason {
138                Blocked::Secret(_) | Blocked::Redaction => self.counts.secrets_removed += 1,
139                Blocked::Pii(_) => self.counts.pii_removed += 1,
140                Blocked::Forbidden | Blocked::LocalPath | Blocked::BrokenRules(_) => {}
141            }
142        }
143        verdict
144    }
145
146    fn verdict(&self, text: &str) -> Result<(), Blocked> {
147        if self.broken > 0 {
148            return Err(Blocked::BrokenRules(self.broken));
149        }
150        // The owner's narrow exceptions (03.11.2026) run first, as in Cloud's
151        // screen; forbidden patterns still see the original text.
152        let original = text;
153        let neutral = super::screening_exceptions::neutralise(text);
154        let text: &str = &neutral;
155        if text.contains("[REDACTED") {
156            return Err(Blocked::Secret("masked in store".into()));
157        }
158        let findings = lean_ctx::core::secret_detection::detect_secrets_with_custom(
159            text,
160            &self.custom_secret_patterns,
161        );
162        if let Some(first) = findings.first() {
163            return Err(Blocked::Secret(first.pattern_name.to_string()));
164        }
165        if lean_ctx::core::redaction::redact_text_with_excludes(text, &self.redaction_excludes)
166            != text
167        {
168            return Err(Blocked::Redaction);
169        }
170        if let Some((class, _)) = lean_ctx::core::input_filters::pii::detect(text).first() {
171            return Err(Blocked::Pii((*class).to_string()));
172        }
173        if lean_ctx::core::sensitivity::classify_content(text)
174            >= lean_ctx::core::sensitivity::SensitivityLevel::Confidential
175        {
176            return Err(Blocked::Pii("card or account number".into()));
177        }
178        if self.forbidden.iter().any(|re| re.is_match(original)) {
179            return Err(Blocked::Forbidden);
180        }
181        if let Some(home) = &self.home
182            && text.contains(home.as_str())
183        {
184            return Err(Blocked::LocalPath);
185        }
186        Ok(())
187    }
188
189    /// The counts for `engine_screening`.
190    pub fn counts(&self) -> EngineScreeningV1 {
191        self.counts
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    fn screen() -> Screen {
200        Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new())
201    }
202
203    #[test]
204    fn canary_secrets_and_personal_data_never_pass() {
205        let mut s = screen();
206        for canary in [
207            concat!("deploy with AK", "IAIOSFODNN7EXAMPLE as key"),
208            concat!("token gh", "p_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789"),
209            "-----BEGIN RSA PRIVATE KEY-----\nMIIEow",
210            "mail jane.doe@example.com for access",
211            "card 4111 1111 1111 1111",
212        ] {
213            assert!(s.check(canary).is_err(), "{canary}");
214        }
215        assert!(s.check("LeanCTX Cloud never blocks a tool call.").is_ok());
216        let counts = s.counts();
217        assert_eq!(counts.items_dropped, 5);
218        assert!(counts.secrets_removed >= 3 && counts.pii_removed >= 1);
219    }
220
221    #[test]
222    fn forbidden_patterns_and_home_paths_are_dropped() {
223        let _home = lean_ctx::core::data_dir::test_env_lock();
224        let mut s = Screen::with_rules(
225            Vec::new(),
226            std::sync::Arc::new(Vec::new()),
227            vec![regex::Regex::new("project-falcon").unwrap()],
228        );
229        assert_eq!(s.check("codename project-falcon"), Err(Blocked::Forbidden));
230        if let Some(home) = dirs::home_dir().filter(|h| h.to_string_lossy().len() > 1) {
231            let text = format!("see {}/notes.txt", home.display());
232            assert_eq!(s.check(&text), Err(Blocked::LocalPath));
233        }
234    }
235
236    /// An invalid forbidden pattern never stops blocking silently: the
237    /// screen then lets nothing pass and says why.
238    #[test]
239    #[allow(clippy::invalid_regex)] // the broken rule is the point of the test
240    fn an_invalid_forbidden_pattern_fails_closed() {
241        let mut s = Screen::with_compiled(
242            Vec::new(),
243            std::sync::Arc::new(Vec::new()),
244            vec![regex::Regex::new("falcon"), regex::Regex::new("(unclosed")],
245        );
246        assert_eq!(
247            s.check("LeanCTX Cloud never blocks a tool call."),
248            Err(Blocked::BrokenRules(1))
249        );
250        let problem = s.problem().expect("named");
251        assert!(problem.contains("do not compile"), "{problem}");
252        let fine = Screen::with_compiled(
253            Vec::new(),
254            std::sync::Arc::new(Vec::new()),
255            vec![regex::Regex::new("falcon")],
256        );
257        assert_eq!(fine.problem(), None);
258    }
259}