Skip to main content

lean_ctx/core/policy/
cloud_io.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The I/O members of the Cloud effective policy (ent2-3):
3//! `security.readable_roots` and `security.never_send`.
4//!
5//! - `readable_roots` (path globs, `{project}` and a leading `~` expanded,
6//!   `x-merge: intersect`): LeanCTX tools and hooked native reads may read a
7//!   path only when it, or one of its ancestors, matches a root. An empty
8//!   list allows nothing.
9//! - `never_send` (gitignore globs, `x-merge: union`): a matching path is
10//!   never read into context, never indexed and never sent to a model or to
11//!   Cloud. Patterns are matched relative to the project; a path outside it is
12//!   matched by its components, so an unanchored pattern (`*.pem`, `.env*`,
13//!   `secrets/`) applies everywhere.
14//!
15//! Both are read from the installed floor ([`super::cloud_floor`]) for the
16//! vault linked to the project. Fail-closed: a damaged, missing-but-required
17//! or older floor, or a pattern that does not compile, refuses every read
18//! instead of dropping the rules. Neither the role (`allow_secret_paths`)
19//! nor the warn boundary mode loosens them: the Cloud policy is a floor a
20//! local setting may only tighten.
21//!
22//! Monolith: it needs the installed floor, the vault map and the data
23//! directory, all engine state (`core::policy::cloud_floor`).
24
25use std::path::{Component, Path, PathBuf};
26
27use ignore::gitignore::{Gitignore, GitignoreBuilder};
28
29use super::cloud_floor;
30
31/// The I/O rules of the Cloud policy in force for one project.
32#[derive(Debug)]
33pub struct IoRules {
34    project: PathBuf,
35    /// `None` = the policy sets no readable roots (everything the other
36    /// gates allow is readable); `Some(empty)` = nothing is readable.
37    roots: Option<Vec<glob::Pattern>>,
38    never_send: Option<Gitignore>,
39}
40
41/// Why a path is refused.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Refusal {
44    /// The path lies outside every readable root.
45    OutsideRoots,
46    /// The path matches a `never_send` pattern.
47    NeverSend(String),
48}
49
50/// The I/O rules for `project` from the floor installed in this data
51/// directory. `Ok(None)` when no Cloud policy is installed or it sets neither
52/// member; `Err` (fail closed) when the installed policy cannot be trusted.
53pub fn rules_for(project: &Path) -> Result<Option<IoRules>, String> {
54    let Some(dir) = cloud_floor::floor_dir() else {
55        return Ok(None);
56    };
57    rules_in(&dir, project)
58}
59
60/// [`rules_for`] with the floor directory given (`<cloud data>/policy/effective`).
61pub fn rules_in(floor_dir: &Path, project: &Path) -> Result<Option<IoRules>, String> {
62    let (floor, required) = cloud_floor::read(floor_dir)?;
63    let Some(checked) = cloud_floor::check(floor.as_deref(), required.as_deref())? else {
64        return Ok(None);
65    };
66    let project = canonical_or_given(project);
67    let vault = floor.as_deref().and_then(|text| {
68        let cloud_data = floor_dir.parent()?.parent()?;
69        cloud_floor::vault_for(text, cloud_data, &project)
70    });
71    let security = &checked.policy.for_vault(vault.as_deref()).security;
72    compile(
73        &project,
74        security.readable_roots.as_deref(),
75        security.never_send.as_deref(),
76    )
77}
78
79/// Compile both members for `project` (absolute). `Ok(None)` when neither is set.
80pub fn compile(
81    project: &Path,
82    roots: Option<&[String]>,
83    never_send: Option<&[String]>,
84) -> Result<Option<IoRules>, String> {
85    if roots.is_none() && never_send.is_none() {
86        return Ok(None);
87    }
88    let roots = roots
89        .map(|roots| {
90            roots
91                .iter()
92                .map(|root| root_pattern(project, root))
93                .collect::<Result<Vec<_>, _>>()
94        })
95        .transpose()?;
96    let never_send = never_send
97        .map(|patterns| {
98            let mut builder = GitignoreBuilder::new(project);
99            for pattern in patterns {
100                builder.add_line(None, pattern).map_err(|_| {
101                    format!(
102                        "the LeanCTX Cloud policy never_send pattern {pattern:?} does not compile"
103                    )
104                })?;
105            }
106            builder.build().map_err(|_| {
107                "the LeanCTX Cloud policy never_send patterns do not compile".to_string()
108            })
109        })
110        .transpose()?;
111    Ok(Some(IoRules {
112        project: project.to_path_buf(),
113        roots,
114        never_send,
115    }))
116}
117
118/// A readable root as an absolute glob: `{project}` becomes the project
119/// directory, a leading `~` the home directory, a relative root is relative
120/// to the project. Literal parts are escaped, so a `[` in a directory name
121/// stays literal.
122fn root_pattern(project: &Path, root: &str) -> Result<glob::Pattern, String> {
123    let escape = |p: &Path| glob::Pattern::escape(&p.to_string_lossy());
124    let mut expanded = root.replace("{project}", &escape(project));
125    if expanded == "~" || expanded.starts_with("~/") {
126        let home = dirs::home_dir().ok_or_else(|| {
127            format!("the LeanCTX Cloud policy readable root {root:?} needs a home")
128        })?;
129        expanded = format!("{}{}", escape(&canonical_or_given(&home)), &expanded[1..]);
130    }
131    if !Path::new(&expanded).is_absolute() {
132        expanded = format!("{}/{expanded}", escape(project));
133    }
134    let trimmed = expanded.trim_end_matches('/');
135    let expanded = if trimmed.is_empty() { "/" } else { trimmed };
136    glob::Pattern::new(expanded)
137        .map_err(|_| format!("the LeanCTX Cloud policy readable root {root:?} does not compile"))
138}
139
140impl IoRules {
141    /// Whether the policy restricts readable roots at all.
142    pub fn has_roots(&self) -> bool {
143        self.roots.is_some()
144    }
145
146    /// Whether the policy sets `never_send` patterns.
147    pub fn has_never_send(&self) -> bool {
148        self.never_send.is_some()
149    }
150
151    /// The refusal for reading `path`, or `None` when it may be read.
152    /// A relative `path` is taken relative to the project.
153    pub fn refusal(&self, path: &Path) -> Option<Refusal> {
154        let path = self.absolute(path);
155        if let Some(pattern) = self.never_send_hit(&path) {
156            return Some(Refusal::NeverSend(pattern));
157        }
158        (!self.inside_roots(&path)).then_some(Refusal::OutsideRoots)
159    }
160
161    /// The `never_send` pattern `path` matches (only that member).
162    pub fn never_send_hit(&self, path: &Path) -> Option<String> {
163        let gitignore = self.never_send.as_ref()?;
164        let path = self.absolute(path);
165        let relative = match path.strip_prefix(&self.project) {
166            Ok(rel) if !rel.as_os_str().is_empty() => rel.to_path_buf(),
167            Ok(_) => return None,
168            // Outside the project: match by components (unanchored patterns).
169            Err(_) => path
170                .components()
171                .filter(|c| matches!(c, Component::Normal(_)))
172                .collect(),
173        };
174        if relative.as_os_str().is_empty() {
175            return None;
176        }
177        let matched = gitignore.matched_path_or_any_parents(&relative, path.is_dir());
178        matched
179            .is_ignore()
180            .then(|| matched.inner().map(|g| g.original().to_string()))
181            .flatten()
182    }
183
184    /// Whether `path` (or an ancestor) matches a readable root.
185    pub fn inside_roots(&self, path: &Path) -> bool {
186        let Some(roots) = &self.roots else {
187            return true;
188        };
189        let path = self.absolute(path);
190        let options = glob::MatchOptions {
191            case_sensitive: !cfg!(windows),
192            require_literal_separator: true,
193            require_literal_leading_dot: false,
194        };
195        path.ancestors().any(|candidate| {
196            roots
197                .iter()
198                .any(|root| root.matches_path_with(candidate, options))
199        })
200    }
201
202    fn absolute(&self, path: &Path) -> PathBuf {
203        let joined = if path.is_absolute() {
204            path.to_path_buf()
205        } else {
206            self.project.join(path)
207        };
208        lexical(&joined)
209    }
210}
211
212impl Refusal {
213    /// One line for the refusal message.
214    pub fn describe(&self) -> String {
215        match self {
216            Self::OutsideRoots => "outside the readable roots of the LeanCTX Cloud policy".into(),
217            Self::NeverSend(pattern) => {
218                format!("matches the LeanCTX Cloud policy never_send pattern {pattern:?}")
219            }
220        }
221    }
222}
223
224/// `..` and `.` resolved without touching the file system.
225fn lexical(path: &Path) -> PathBuf {
226    let mut out = PathBuf::new();
227    for component in path.components() {
228        match component {
229            Component::CurDir => {}
230            Component::ParentDir => {
231                out.pop();
232            }
233            other => out.push(other),
234        }
235    }
236    out
237}
238
239fn canonical_or_given(path: &Path) -> PathBuf {
240    crate::core::pathutil::canonicalize_secure(path).unwrap_or_else(|_| lexical(path))
241}
242
243#[cfg(all(test, unix))]
244mod tests {
245    use super::*;
246    use serde_json::json;
247
248    fn strings(items: &[&str]) -> Vec<String> {
249        items.iter().map(|s| (*s).to_string()).collect()
250    }
251
252    #[test]
253    fn readable_roots_admit_inside_and_refuse_outside() {
254        let project = Path::new("/work/app");
255        let rules = compile(
256            project,
257            Some(&strings(&["{project}", "/opt/shared/*/docs"])),
258            None,
259        )
260        .unwrap()
261        .unwrap();
262        for inside in [
263            "/work/app",
264            "/work/app/src/main.rs",
265            "src/lib.rs",
266            "/opt/shared/team/docs/a.md",
267        ] {
268            assert_eq!(rules.refusal(Path::new(inside)), None, "{inside}");
269        }
270        for outside in [
271            "/work/other/x.rs",
272            "/work/app-evil/x.rs",
273            "/work/app/../other/x.rs",
274            "../../etc/passwd",
275            "/opt/shared/team/src/a.rs",
276        ] {
277            assert_eq!(
278                rules.refusal(Path::new(outside)),
279                Some(Refusal::OutsideRoots),
280                "{outside}"
281            );
282        }
283        // An empty list allows nothing.
284        let none = compile(project, Some(&[]), None).unwrap().unwrap();
285        assert_eq!(
286            none.refusal(Path::new("/work/app/a.rs")),
287            Some(Refusal::OutsideRoots)
288        );
289    }
290
291    #[test]
292    fn never_send_refuses_inside_and_outside_the_project() {
293        let project = Path::new("/work/app");
294        let rules = compile(
295            project,
296            None,
297            Some(&strings(&[
298                "*.pem",
299                ".env*",
300                "secrets/",
301                "/config/prod.toml",
302            ])),
303        )
304        .unwrap()
305        .unwrap();
306        for (path, pattern) in [
307            ("/work/app/tls/server.pem", "*.pem"),
308            ("/work/app/.env.local", ".env*"),
309            ("/work/app/secrets/token.txt", "secrets/"),
310            ("/work/app/config/prod.toml", "/config/prod.toml"),
311            ("/home/u/other/key.pem", "*.pem"),
312        ] {
313            assert_eq!(
314                rules.refusal(Path::new(path)),
315                Some(Refusal::NeverSend(pattern.into())),
316                "{path}"
317            );
318        }
319        for path in [
320            "/work/app/src/main.rs",
321            "/work/app/sub/config/prod.toml",
322            "/work/app",
323        ] {
324            assert_eq!(rules.refusal(Path::new(path)), None, "{path}");
325        }
326    }
327
328    #[test]
329    fn unset_policy_has_no_rules_and_a_damaged_floor_fails_closed() {
330        let dir = tempfile::tempdir().unwrap();
331        let floor_dir = dir.path().join("cloud").join("policy").join("effective");
332        std::fs::create_dir_all(&floor_dir).unwrap();
333        let project = dir.path();
334        // Nothing installed: no rules.
335        assert!(rules_in(&floor_dir, project).unwrap().is_none());
336        let floor = |security: serde_json::Value| {
337            json!({
338                "schema": cloud_floor::FLOOR_SCHEMA, "version": 2,
339                "digest": format!("sha256:{}", "a".repeat(64)),
340                "not_after": "2099-01-01T00:00:00Z",
341                "policy": {"effective": {
342                    "schema": "leanctx.cloud.policy/v1",
343                    "security": security, "context": {}, "sharing": {}
344                }, "vaults": []}
345            })
346            .to_string()
347        };
348        std::fs::write(
349            floor_dir.join(cloud_floor::REQUIRED_FILE),
350            r#"{"version":2}"#,
351        )
352        .unwrap();
353        // A policy without the members: no rules.
354        std::fs::write(
355            floor_dir.join(cloud_floor::FLOOR_FILE),
356            floor(json!({"pii": "redact"})),
357        )
358        .unwrap();
359        assert!(rules_in(&floor_dir, project).unwrap().is_none());
360        // With them: the project's own root applies.
361        std::fs::write(
362            floor_dir.join(cloud_floor::FLOOR_FILE),
363            floor(json!({"readable_roots": ["{project}"], "never_send": ["*.pem"]})),
364        )
365        .unwrap();
366        let rules = rules_in(&floor_dir, project).unwrap().unwrap();
367        assert!(rules.inside_roots(&canonical_or_given(project).join("a.rs")));
368        assert!(!rules.inside_roots(Path::new("/elsewhere/a.rs")));
369        // Damaged or missing while required: fail closed.
370        std::fs::write(floor_dir.join(cloud_floor::FLOOR_FILE), "{").unwrap();
371        assert!(rules_in(&floor_dir, project).is_err());
372        std::fs::remove_file(floor_dir.join(cloud_floor::FLOOR_FILE)).unwrap();
373        assert!(rules_in(&floor_dir, project).is_err());
374    }
375}