1use std::path::{Component, Path, PathBuf};
26
27use ignore::gitignore::{Gitignore, GitignoreBuilder};
28
29use super::cloud_floor;
30
31#[derive(Debug)]
33pub struct IoRules {
34 project: PathBuf,
35 roots: Option<Vec<glob::Pattern>>,
38 never_send: Option<Gitignore>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Refusal {
44 OutsideRoots,
46 NeverSend(String),
48}
49
50pub 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
60pub 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
79pub 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!("the LeanCTX policy never_send pattern {pattern:?} does not compile")
102 })?;
103 }
104 builder
105 .build()
106 .map_err(|_| "the LeanCTX policy never_send patterns do not compile".to_string())
107 })
108 .transpose()?;
109 Ok(Some(IoRules {
110 project: project.to_path_buf(),
111 roots,
112 never_send,
113 }))
114}
115
116fn root_pattern(project: &Path, root: &str) -> Result<glob::Pattern, String> {
121 let escape = |p: &Path| glob::Pattern::escape(&p.to_string_lossy());
122 let mut expanded = root.replace("{project}", &escape(project));
123 if expanded == "~" || expanded.starts_with("~/") {
124 let home = dirs::home_dir()
125 .ok_or_else(|| format!("the LeanCTX policy readable root {root:?} needs a home"))?;
126 expanded = format!("{}{}", escape(&canonical_or_given(&home)), &expanded[1..]);
127 }
128 if !Path::new(&expanded).is_absolute() {
129 expanded = format!("{}/{expanded}", escape(project));
130 }
131 let trimmed = expanded.trim_end_matches('/');
132 let expanded = if trimmed.is_empty() { "/" } else { trimmed };
133 glob::Pattern::new(expanded)
134 .map_err(|_| format!("the LeanCTX policy readable root {root:?} does not compile"))
135}
136
137impl IoRules {
138 pub fn has_roots(&self) -> bool {
140 self.roots.is_some()
141 }
142
143 pub fn has_never_send(&self) -> bool {
145 self.never_send.is_some()
146 }
147
148 pub fn refusal(&self, path: &Path) -> Option<Refusal> {
151 let path = self.absolute(path);
152 if let Some(pattern) = self.never_send_hit(&path) {
153 return Some(Refusal::NeverSend(pattern));
154 }
155 (!self.inside_roots(&path)).then_some(Refusal::OutsideRoots)
156 }
157
158 pub fn never_send_hit(&self, path: &Path) -> Option<String> {
160 let gitignore = self.never_send.as_ref()?;
161 let path = self.absolute(path);
162 let relative = match path.strip_prefix(&self.project) {
163 Ok(rel) if !rel.as_os_str().is_empty() => rel.to_path_buf(),
164 Ok(_) => return None,
165 Err(_) => path
167 .components()
168 .filter(|c| matches!(c, Component::Normal(_)))
169 .collect(),
170 };
171 if relative.as_os_str().is_empty() {
172 return None;
173 }
174 let matched = gitignore.matched_path_or_any_parents(&relative, path.is_dir());
175 matched
176 .is_ignore()
177 .then(|| matched.inner().map(|g| g.original().to_string()))
178 .flatten()
179 }
180
181 pub fn inside_roots(&self, path: &Path) -> bool {
183 let Some(roots) = &self.roots else {
184 return true;
185 };
186 let path = self.absolute(path);
187 let options = glob::MatchOptions {
188 case_sensitive: !cfg!(windows),
189 require_literal_separator: true,
190 require_literal_leading_dot: false,
191 };
192 path.ancestors().any(|candidate| {
193 roots
194 .iter()
195 .any(|root| root.matches_path_with(candidate, options))
196 })
197 }
198
199 fn absolute(&self, path: &Path) -> PathBuf {
200 let joined = if path.is_absolute() {
201 path.to_path_buf()
202 } else {
203 self.project.join(path)
204 };
205 lexical(&joined)
206 }
207}
208
209impl Refusal {
210 pub fn describe(&self) -> String {
212 match self {
213 Self::OutsideRoots => "outside the readable roots of the LeanCTX policy".into(),
214 Self::NeverSend(pattern) => {
215 format!("matches the LeanCTX policy never_send pattern {pattern:?}")
216 }
217 }
218 }
219}
220
221fn lexical(path: &Path) -> PathBuf {
223 let mut out = PathBuf::new();
224 for component in path.components() {
225 match component {
226 Component::CurDir => {}
227 Component::ParentDir => {
228 out.pop();
229 }
230 other => out.push(other),
231 }
232 }
233 out
234}
235
236fn canonical_or_given(path: &Path) -> PathBuf {
237 crate::core::pathutil::canonicalize_secure(path).unwrap_or_else(|_| lexical(path))
238}
239
240#[cfg(all(test, unix))]
241mod tests {
242 use super::*;
243 use serde_json::json;
244
245 fn strings(items: &[&str]) -> Vec<String> {
246 items.iter().map(|s| (*s).to_string()).collect()
247 }
248
249 #[test]
250 fn readable_roots_admit_inside_and_refuse_outside() {
251 let project = Path::new("/work/app");
252 let rules = compile(
253 project,
254 Some(&strings(&["{project}", "/opt/shared/*/docs"])),
255 None,
256 )
257 .unwrap()
258 .unwrap();
259 for inside in [
260 "/work/app",
261 "/work/app/src/main.rs",
262 "src/lib.rs",
263 "/opt/shared/team/docs/a.md",
264 ] {
265 assert_eq!(rules.refusal(Path::new(inside)), None, "{inside}");
266 }
267 for outside in [
268 "/work/other/x.rs",
269 "/work/app-evil/x.rs",
270 "/work/app/../other/x.rs",
271 "../../etc/passwd",
272 "/opt/shared/team/src/a.rs",
273 ] {
274 assert_eq!(
275 rules.refusal(Path::new(outside)),
276 Some(Refusal::OutsideRoots),
277 "{outside}"
278 );
279 }
280 let none = compile(project, Some(&[]), None).unwrap().unwrap();
282 assert_eq!(
283 none.refusal(Path::new("/work/app/a.rs")),
284 Some(Refusal::OutsideRoots)
285 );
286 }
287
288 #[test]
289 fn never_send_refuses_inside_and_outside_the_project() {
290 let project = Path::new("/work/app");
291 let rules = compile(
292 project,
293 None,
294 Some(&strings(&[
295 "*.pem",
296 ".env*",
297 "secrets/",
298 "/config/prod.toml",
299 ])),
300 )
301 .unwrap()
302 .unwrap();
303 for (path, pattern) in [
304 ("/work/app/tls/server.pem", "*.pem"),
305 ("/work/app/.env.local", ".env*"),
306 ("/work/app/secrets/token.txt", "secrets/"),
307 ("/work/app/config/prod.toml", "/config/prod.toml"),
308 ("/home/u/other/key.pem", "*.pem"),
309 ] {
310 assert_eq!(
311 rules.refusal(Path::new(path)),
312 Some(Refusal::NeverSend(pattern.into())),
313 "{path}"
314 );
315 }
316 for path in [
317 "/work/app/src/main.rs",
318 "/work/app/sub/config/prod.toml",
319 "/work/app",
320 ] {
321 assert_eq!(rules.refusal(Path::new(path)), None, "{path}");
322 }
323 }
324
325 #[test]
326 fn unset_policy_has_no_rules_and_a_damaged_floor_fails_closed() {
327 let dir = tempfile::tempdir().unwrap();
328 let floor_dir = dir.path().join("cloud").join("policy").join("effective");
329 std::fs::create_dir_all(&floor_dir).unwrap();
330 let project = dir.path();
331 assert!(rules_in(&floor_dir, project).unwrap().is_none());
333 let floor = |security: serde_json::Value| {
334 json!({
335 "schema": cloud_floor::FLOOR_SCHEMA, "version": 2,
336 "digest": format!("sha256:{}", "a".repeat(64)),
337 "not_after": "2099-01-01T00:00:00Z",
338 "policy": {"effective": {
339 "schema": "leanctx.cloud.policy/v1",
340 "security": security, "context": {}, "sharing": {}
341 }, "vaults": []}
342 })
343 .to_string()
344 };
345 std::fs::write(
346 floor_dir.join(cloud_floor::REQUIRED_FILE),
347 r#"{"version":2}"#,
348 )
349 .unwrap();
350 std::fs::write(
352 floor_dir.join(cloud_floor::FLOOR_FILE),
353 floor(json!({"pii": "redact"})),
354 )
355 .unwrap();
356 assert!(rules_in(&floor_dir, project).unwrap().is_none());
357 std::fs::write(
359 floor_dir.join(cloud_floor::FLOOR_FILE),
360 floor(json!({"readable_roots": ["{project}"], "never_send": ["*.pem"]})),
361 )
362 .unwrap();
363 let rules = rules_in(&floor_dir, project).unwrap().unwrap();
364 assert!(rules.inside_roots(&canonical_or_given(project).join("a.rs")));
365 assert!(!rules.inside_roots(Path::new("/elsewhere/a.rs")));
366 std::fs::write(floor_dir.join(cloud_floor::FLOOR_FILE), "{").unwrap();
368 assert!(rules_in(&floor_dir, project).is_err());
369 std::fs::remove_file(floor_dir.join(cloud_floor::FLOOR_FILE)).unwrap();
370 assert!(rules_in(&floor_dir, project).is_err());
371 }
372}