Skip to main content

lean_ctx/core/hive/knowledge/
screening.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The one mandatory path into the Hive 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::hive::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}
23
24impl std::fmt::Display for Blocked {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Self::Secret(kind) => write!(f, "credential ({kind})"),
28            Self::Pii(kind) => write!(f, "personal data ({kind})"),
29            Self::Redaction => f.write_str("matches a redaction rule"),
30            Self::Forbidden => f.write_str("matches a forbidden egress pattern or org filter"),
31            Self::LocalPath => f.write_str("contains a local home path"),
32        }
33    }
34}
35
36/// Screening rules with their configuration resolved once.
37pub struct Screen {
38    custom_secret_patterns: Vec<String>,
39    redaction_excludes: std::sync::Arc<Vec<regex::Regex>>,
40    forbidden: Vec<regex::Regex>,
41    home: Option<String>,
42    counts: EngineScreeningV1,
43}
44
45impl Screen {
46    /// Rules of this installation (custom secret patterns, redaction
47    /// excludes, the active pack's `[egress] forbidden_patterns`).
48    pub fn for_installation() -> Self {
49        let config = crate::core::config::Config::load();
50        // The organization's Hive filter packs (redact and block rules
51        // alike) keep a matching fact on this machine.
52        let hive = crate::core::hive::policy::installed_filter_rules();
53        let forbidden = crate::core::policy::runtime::active()
54            .map(|policy| policy.resolved.egress.forbidden_patterns.clone())
55            .unwrap_or_default()
56            .into_iter()
57            .chain(hive.redaction.into_iter().map(|(_, pattern)| pattern))
58            .chain(hive.blocked.into_iter().map(|(_, pattern)| pattern))
59            .filter_map(|p| regex::Regex::new(&p).ok())
60            .collect();
61        Self::with_rules(
62            config.secret_detection.custom_patterns.clone(),
63            crate::core::redaction::config_exclude_patterns(),
64            forbidden,
65        )
66    }
67
68    pub(crate) fn with_rules(
69        custom_secret_patterns: Vec<String>,
70        redaction_excludes: std::sync::Arc<Vec<regex::Regex>>,
71        forbidden: Vec<regex::Regex>,
72    ) -> Self {
73        let home = dirs::home_dir()
74            .map(|h| h.to_string_lossy().into_owned())
75            .filter(|h| h.len() > 1);
76        Self {
77            custom_secret_patterns,
78            redaction_excludes,
79            forbidden,
80            home,
81            counts: EngineScreeningV1 {
82                scanner_version: SCANNER_VERSION,
83                secrets_removed: 0,
84                pii_removed: 0,
85                items_dropped: 0,
86            },
87        }
88    }
89
90    /// `Ok(())` when `text` may leave the machine; otherwise the reason, and
91    /// the drop is counted.
92    pub fn check(&mut self, text: &str) -> Result<(), Blocked> {
93        let verdict = self.verdict(text);
94        if let Err(reason) = &verdict {
95            self.counts.items_dropped += 1;
96            match reason {
97                Blocked::Secret(_) | Blocked::Redaction => self.counts.secrets_removed += 1,
98                Blocked::Pii(_) => self.counts.pii_removed += 1,
99                Blocked::Forbidden | Blocked::LocalPath => {}
100            }
101        }
102        verdict
103    }
104
105    fn verdict(&self, text: &str) -> Result<(), Blocked> {
106        if text.contains("[REDACTED") {
107            return Err(Blocked::Secret("masked in store".into()));
108        }
109        let findings = crate::core::secret_detection::detect_secrets_with_custom(
110            text,
111            &self.custom_secret_patterns,
112        );
113        if let Some(first) = findings.first() {
114            return Err(Blocked::Secret(first.pattern_name.to_string()));
115        }
116        if crate::core::redaction::redact_text_with_excludes(text, &self.redaction_excludes) != text
117        {
118            return Err(Blocked::Redaction);
119        }
120        if let Some((class, _)) = crate::core::input_filters::pii::detect(text).first() {
121            return Err(Blocked::Pii((*class).to_string()));
122        }
123        if crate::core::sensitivity::classify_content(text)
124            >= crate::core::sensitivity::SensitivityLevel::Confidential
125        {
126            return Err(Blocked::Pii("card or account number".into()));
127        }
128        if self.forbidden.iter().any(|re| re.is_match(text)) {
129            return Err(Blocked::Forbidden);
130        }
131        if let Some(home) = &self.home
132            && text.contains(home.as_str())
133        {
134            return Err(Blocked::LocalPath);
135        }
136        Ok(())
137    }
138
139    /// The counts for `engine_screening`.
140    pub fn counts(&self) -> EngineScreeningV1 {
141        self.counts
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    fn screen() -> Screen {
150        Screen::with_rules(Vec::new(), std::sync::Arc::new(Vec::new()), Vec::new())
151    }
152
153    #[test]
154    fn canary_secrets_and_personal_data_never_pass() {
155        let mut s = screen();
156        for canary in [
157            concat!("deploy with AK", "IAIOSFODNN7EXAMPLE as key"),
158            concat!("token gh", "p_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789"),
159            "-----BEGIN RSA PRIVATE KEY-----\nMIIEow",
160            "mail jane.doe@example.com for access",
161            "card 4111 1111 1111 1111",
162        ] {
163            assert!(s.check(canary).is_err(), "{canary}");
164        }
165        assert!(s.check("Hive never blocks a tool call.").is_ok());
166        let counts = s.counts();
167        assert_eq!(counts.items_dropped, 5);
168        assert!(counts.secrets_removed >= 3 && counts.pii_removed >= 1);
169    }
170
171    #[test]
172    fn forbidden_patterns_and_home_paths_are_dropped() {
173        let mut s = Screen::with_rules(
174            Vec::new(),
175            std::sync::Arc::new(Vec::new()),
176            vec![regex::Regex::new("project-falcon").unwrap()],
177        );
178        assert_eq!(s.check("codename project-falcon"), Err(Blocked::Forbidden));
179        if let Some(home) = dirs::home_dir().filter(|h| h.to_string_lossy().len() > 1) {
180            let text = format!("see {}/notes.txt", home.display());
181            assert_eq!(s.check(&text), Err(Blocked::LocalPath));
182        }
183    }
184}