lean_ctx/core/hive/compute/
bundle.rs1use 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
35pub const BUNDLE_NAME: &str = "src.tar";
37pub const TAR_PREFIX: &str = "app";
39const MAX_LISTED: usize = 10;
41const NEVER_WALKED: [&str; 2] = [".git", ".lean-ctx"];
43
44#[derive(Debug, Clone, Default)]
46pub struct BundleRules {
47 pub excluded: Vec<String>,
49 pub custom_secret_patterns: Vec<String>,
51 pub home: Option<PathBuf>,
53}
54
55impl BundleRules {
56 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct BundleReport {
72 pub files: usize,
73 pub excluded_by_policy: Vec<String>,
75 pub secret_paths: Vec<(String, &'static str)>,
77 pub skipped: usize,
79}
80
81#[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
98fn 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
142fn 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
166fn 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
183pub 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 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 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}