Skip to main content

lean_ctx/core/hive/compute/
bundle.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The input bundle of a compute job: exactly the files the job names from
3//! this checkout, as one deterministic, content-addressed tar.
4//!
5//! Rules, in order (a file must pass all of them):
6//!
7//! 1. The checkout root is a project, never the home directory or a parent
8//!    of it; every requested path is jailed to the root (PathJail, enforced
9//!    even when the tool jail is relaxed) and must exist.
10//! 2. The walk starts at the root, so `.gitignore` (and `.git/info/exclude`)
11//!    applies to every requested path; `.git/` and `.lean-ctx/` are never
12//!    walked; symlinks are never followed or packed.
13//! 3. A file the effective Hive policy excludes (`security.excluded_paths`
14//!    of this vault, gitignore globs) is left out.
15//! 4. A secret-like path (`.env`, keys, `.ssh/`, credential files:
16//!    [`crate::core::io_boundary::is_secret_like`]) is left out.
17//! 5. Every remaining file is screened with the secret detectors (the
18//!    built-in rules and `[secret_detection] custom_patterns`) and for this
19//!    machine's home path. One finding refuses the whole bundle; nothing is
20//!    uploaded and the findings name only paths and rule names.
21//! 6. At most [`MAX_BUNDLE_BYTES`] in all (the tar itself).
22//!
23//! The tar lists the files under `app/` sorted bytewise by path, with
24//! mtime 0, uid/gid 0, no user names and mode 0644 (0755 when executable),
25//! so the same files give the same bytes and the same digest on every
26//! machine.
27
28use std::path::{Path, PathBuf};
29
30use ignore::gitignore::{Gitignore, GitignoreBuilder};
31
32use crate::core::hive::HiveError;
33use lean_ctx_protocol::hive::compute::{BundleRefV1, MAX_BUNDLE_BYTES, content_digest};
34
35/// The bundle's name in the job (`/work/in/src.tar`).
36pub const BUNDLE_NAME: &str = "src.tar";
37/// Directory the files sit under inside the tar.
38pub const TAR_PREFIX: &str = "app";
39/// Findings listed in a refusal; the rest are counted.
40const MAX_LISTED: usize = 10;
41/// Directories never walked (engine state and git internals).
42const NEVER_WALKED: [&str; 2] = [".git", ".lean-ctx"];
43
44/// What decides which files may leave.
45#[derive(Debug, Clone, Default)]
46pub struct BundleRules {
47    /// `security.excluded_paths` of the effective policy (gitignore globs).
48    pub excluded: Vec<String>,
49    /// `[secret_detection] custom_patterns`.
50    pub custom_secret_patterns: Vec<String>,
51    /// This machine's home directory; content naming it is refused.
52    pub home: Option<PathBuf>,
53}
54
55impl BundleRules {
56    /// The rules of this installation for `excluded` policy globs.
57    pub fn for_installation(excluded: Vec<String>) -> Self {
58        Self {
59            excluded,
60            custom_secret_patterns: crate::core::config::Config::load()
61                .secret_detection
62                .custom_patterns
63                .clone(),
64            home: dirs::home_dir(),
65        }
66    }
67}
68
69/// What was left out, for the person.
70#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct BundleReport {
72    pub files: usize,
73    /// Files the effective policy excludes.
74    pub excluded_by_policy: Vec<String>,
75    /// Secret-like paths, with the rule that matched.
76    pub secret_paths: Vec<(String, &'static str)>,
77    /// Symlinks and paths that are not UTF-8.
78    pub skipped: usize,
79}
80
81/// A built bundle.
82#[derive(Debug, Clone)]
83pub struct Bundle {
84    pub bytes: Vec<u8>,
85    pub reference: BundleRefV1,
86    pub report: BundleReport,
87}
88
89fn refused(text: impl Into<String>) -> HiveError {
90    HiveError::Refused(text.into())
91}
92
93fn canonical(path: &Path) -> Result<PathBuf, HiveError> {
94    crate::core::pathutil::canonicalize_secure(path)
95        .map_err(|e| refused(format!("{}: {e}", path.display())))
96}
97
98/// The jailed, canonical start points of `paths` below `root` (default:
99/// the whole checkout).
100fn starts(root: &Path, paths: &[String]) -> Result<Vec<PathBuf>, HiveError> {
101    if paths.is_empty() {
102        return Ok(vec![root.to_path_buf()]);
103    }
104    let mut out = Vec::new();
105    for path in paths {
106        let candidate = Path::new(path);
107        let candidate = if candidate.is_absolute() {
108            candidate.to_path_buf()
109        } else {
110            root.join(candidate)
111        };
112        let jailed = crate::core::pathjail::jail_path_enforced(&candidate, root)
113            .map_err(|e| refused(format!("path_refused: {path}: {e}")))?;
114        let jailed = crate::core::pathutil::canonicalize_secure(&jailed)
115            .map_err(|_| refused(format!("path_refused: {path} does not exist")))?;
116        if !jailed.starts_with(root) {
117            return Err(refused(format!(
118                "path_refused: {path} is outside this checkout"
119            )));
120        }
121        out.push(jailed);
122    }
123    out.sort();
124    out.dedup();
125    Ok(out)
126}
127
128fn excluded_matcher(root: &Path, globs: &[String]) -> Result<Gitignore, HiveError> {
129    let mut builder = GitignoreBuilder::new(root);
130    for glob in globs {
131        builder.add_line(None, glob).map_err(|e| {
132            refused(format!(
133                "the policy's excluded path {glob:?} is invalid: {e}"
134            ))
135        })?;
136    }
137    builder
138        .build()
139        .map_err(|e| refused(format!("the policy's excluded paths are invalid: {e}")))
140}
141
142/// `a/b/c` of `path` below `root`, `None` when a part is not UTF-8.
143fn relative(root: &Path, path: &Path) -> Option<String> {
144    let rel = path.strip_prefix(root).ok()?;
145    let mut parts = Vec::new();
146    for part in rel.components() {
147        match part {
148            std::path::Component::Normal(name) => parts.push(name.to_str()?.to_owned()),
149            _ => return None,
150        }
151    }
152    (!parts.is_empty()).then(|| parts.join("/"))
153}
154
155#[cfg(unix)]
156fn executable(meta: &std::fs::Metadata) -> bool {
157    use std::os::unix::fs::PermissionsExt as _;
158    meta.permissions().mode() & 0o111 != 0
159}
160
161#[cfg(not(unix))]
162fn executable(_meta: &std::fs::Metadata) -> bool {
163    false
164}
165
166/// The checkout must be a project, not the home directory or above it.
167fn check_root(root: &Path, home: Option<&Path>) -> Result<(), HiveError> {
168    if root.parent().is_none() {
169        return Err(refused(
170            "path_refused: the filesystem root is not a checkout",
171        ));
172    }
173    if let Some(home) = home.and_then(|h| canonical(h).ok())
174        && home.starts_with(root)
175    {
176        return Err(refused(
177            "path_refused: a compute bundle is never built from your home directory or above it; run it in the project's checkout",
178        ));
179    }
180    Ok(())
181}
182
183/// Build the bundle of `paths` (relative to `root`, or absolute inside it;
184/// empty = the whole checkout) under `rules`.
185pub fn build(root: &Path, paths: &[String], rules: &BundleRules) -> Result<Bundle, HiveError> {
186    let root = canonical(root)?;
187    check_root(&root, rules.home.as_deref())?;
188    let starts = starts(&root, paths)?;
189    let excluded = excluded_matcher(&root, &rules.excluded)?;
190    let wanted = |path: &Path| starts.iter().any(|s| path.starts_with(s));
191    let on_the_way = |path: &Path| starts.iter().any(|s| s.starts_with(path));
192
193    let mut report = BundleReport::default();
194    let mut files: Vec<(String, PathBuf)> = Vec::new();
195    let prune = starts.clone();
196    let walker = ignore::WalkBuilder::new(&root)
197        .standard_filters(false)
198        .git_ignore(true)
199        .git_exclude(true)
200        .git_global(false)
201        .ignore(false)
202        .parents(true)
203        .require_git(false)
204        .hidden(false)
205        .follow_links(false)
206        .filter_entry(move |entry| {
207            if entry.depth() == 0 || !entry.file_type().is_some_and(|t| t.is_dir()) {
208                return true;
209            }
210            let name = entry.file_name().to_string_lossy();
211            let path = entry.path();
212            !NEVER_WALKED.contains(&name.as_ref())
213                && prune
214                    .iter()
215                    .any(|s| path.starts_with(s) || s.starts_with(path))
216        })
217        .build();
218    for entry in walker {
219        let entry = entry.map_err(|e| refused(format!("walk {}: {e}", root.display())))?;
220        let path = entry.path();
221        let Some(kind) = entry.file_type() else {
222            continue;
223        };
224        if kind.is_dir() || !(wanted(path) || on_the_way(path)) {
225            continue;
226        }
227        if kind.is_symlink() || !kind.is_file() {
228            if wanted(path) {
229                report.skipped += 1;
230            }
231            continue;
232        }
233        if !wanted(path) {
234            continue;
235        }
236        let Some(rel) = relative(&root, path) else {
237            report.skipped += 1;
238            continue;
239        };
240        if excluded
241            .matched_path_or_any_parents(Path::new(&rel), false)
242            .is_ignore()
243        {
244            report.excluded_by_policy.push(rel);
245            continue;
246        }
247        if let Some(why) = crate::core::io_boundary::is_secret_like(Path::new(&rel)) {
248            report.secret_paths.push((rel, why));
249            continue;
250        }
251        files.push((rel, path.to_path_buf()));
252    }
253    files.sort();
254    files.dedup();
255    report.excluded_by_policy.sort();
256    report.secret_paths.sort();
257    if files.is_empty() {
258        return Err(refused(
259            "bundle_empty: no file of the requested paths may leave this machine",
260        ));
261    }
262
263    let home = rules
264        .home
265        .as_ref()
266        .map(|h| h.to_string_lossy().into_owned())
267        .filter(|h| h.len() > 1);
268    let mut findings: Vec<String> = Vec::new();
269    let mut builder = tar::Builder::new(Vec::new());
270    let mut total: u64 = 0;
271    for (rel, path) in &files {
272        let meta =
273            std::fs::symlink_metadata(path).map_err(|e| HiveError::Local(format!("{rel}: {e}")))?;
274        if !meta.is_file() {
275            report.skipped += 1;
276            continue;
277        }
278        // 512 bytes of header plus the padded content, before reading it.
279        total = total.saturating_add(512 + meta.len().div_ceil(512) * 512);
280        if total > MAX_BUNDLE_BYTES {
281            return Err(too_large());
282        }
283        let bytes = std::fs::read(path).map_err(|e| HiveError::Local(format!("{rel}: {e}")))?;
284        let text = String::from_utf8_lossy(&bytes);
285        let secrets = crate::core::secret_detection::detect_secrets_with_custom(
286            &text,
287            &rules.custom_secret_patterns,
288        );
289        if let Some(first) = secrets.first() {
290            findings.push(format!("{rel} ({})", first.pattern_name));
291            continue;
292        }
293        if let Some(home) = &home
294            && text.contains(home.as_str())
295        {
296            findings.push(format!("{rel} (local home path)"));
297            continue;
298        }
299        if !findings.is_empty() {
300            // Refused anyway; keep screening, stop packing.
301            continue;
302        }
303        let mut header = tar::Header::new_gnu();
304        header.set_entry_type(tar::EntryType::Regular);
305        header.set_size(bytes.len() as u64);
306        header.set_mode(if executable(&meta) { 0o755 } else { 0o644 });
307        header.set_mtime(0);
308        header.set_uid(0);
309        header.set_gid(0);
310        builder
311            .append_data(&mut header, format!("{TAR_PREFIX}/{rel}"), bytes.as_slice())
312            .map_err(|e| HiveError::Local(format!("bundle {rel}: {e}")))?;
313        if builder.get_ref().len() as u64 > MAX_BUNDLE_BYTES {
314            return Err(too_large());
315        }
316        report.files += 1;
317    }
318    if !findings.is_empty() {
319        let more = findings.len().saturating_sub(MAX_LISTED);
320        let listed = findings
321            .iter()
322            .take(MAX_LISTED)
323            .cloned()
324            .collect::<Vec<_>>()
325            .join(", ");
326        return Err(refused(format!(
327            "secret_found: {} file(s) look like they carry a credential or a local home path, so nothing was uploaded: {listed}{}. Remove them, or narrow the bundle with --path.",
328            findings.len(),
329            if more > 0 {
330                format!(" and {more} more")
331            } else {
332                String::new()
333            }
334        )));
335    }
336    let bytes = builder
337        .into_inner()
338        .map_err(|e| HiveError::Local(format!("bundle: {e}")))?;
339    if bytes.len() as u64 > MAX_BUNDLE_BYTES {
340        return Err(too_large());
341    }
342    let reference = BundleRefV1 {
343        name: BUNDLE_NAME.into(),
344        digest: content_digest(&bytes),
345        size_bytes: bytes.len() as u64,
346    };
347    Ok(Bundle {
348        bytes,
349        reference,
350        report,
351    })
352}
353
354fn too_large() -> HiveError {
355    refused("bundle_too_large: the input bundle would pass 64 MiB; narrow it with --path")
356}