1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use std::fmt::Write as _;
19use std::io::{self, Read as _, Write as _};
20use std::os::fd::OwnedFd;
21use std::os::unix::ffi::OsStrExt as _;
22use std::os::unix::fs::MetadataExt as _;
23use std::path::{Path, PathBuf};
24use std::process::Stdio;
25use std::time::Duration;
26
27use rustix::fs::{self, AtFlags, FileType, Mode, OFlags};
28use sha2::{Digest as _, Sha256};
29
30use super::cargo_lockfile::{LockedPackage, Lockfile};
31use super::sandbox::CommandSandbox;
32
33const PROJECT_KEY_LENGTH: usize = 32;
36const VARIANT_LENGTH: usize = 16;
38const HOME_DIRECTORY: &str = "home";
41const WORK_PREFIX: &str = "agentty-cargo-fetch-";
44const TARGET_DIRECTORY: &str = "target";
47const GENERATION_FILE: &str = "generation";
49const GENERATION_HEADER: &str = "agentty-cargo-cache 3";
51const SESSION_GENERATION_FILE: &str = ".agentty-cache-generation";
54const PARTIAL_SUFFIX: &str = ".agentty-partial";
56const CARGO_HOME_CONFIGURATION: [&str; 4] =
59 ["config.toml", "config", "credentials.toml", "credentials"];
60const ANCESTOR_CONFIGURATION: [&str; 4] = [
63 ".cargo/config.toml",
64 ".cargo/config",
65 "rust-toolchain.toml",
66 "rust-toolchain",
67];
68const CARGO_TIMEOUT: Duration = Duration::from_secs(300);
70const REGISTRY_CACHE: &str = "registry/cache";
72const REGISTRY_INDEX: &str = "registry/index";
74const INDEX_CONFIG: &str = "config.json";
76const MAX_INDEX_CONFIG_BYTES: u64 = 64 * 1024;
78const CRATES_IO_DIRECTORY_PREFIX: &str = "index.crates.io-";
80const CRATES_IO_DOWNLOADS: &str = "https://static.crates.io/crates";
82const ALLOWED_VARIABLES: [&str; 14] = [
86 "CARGO_HTTP_CAINFO",
87 "CARGO_HTTP_PROXY",
88 "HOME",
89 "HTTPS_PROXY",
90 "HTTP_PROXY",
91 "NO_PROXY",
92 "PATH",
93 "RUSTUP_HOME",
94 "RUSTUP_TOOLCHAIN",
95 "SSL_CERT_DIR",
96 "SSL_CERT_FILE",
97 "http_proxy",
98 "https_proxy",
99 "no_proxy",
100];
101
102#[derive(Clone, Debug, Eq, PartialEq)]
104pub struct TrustedCargoCache {
105 cache_root: PathBuf,
107 root: PathBuf,
109}
110
111impl TrustedCargoCache {
112 pub fn for_project(cache_root: &Path, main_checkout: &Path) -> Self {
115 let digest = hex::encode(Sha256::digest(main_checkout.as_os_str().as_bytes()));
116
117 Self {
118 cache_root: cache_root.to_path_buf(),
119 root: cache_root.join(&digest[..PROJECT_KEY_LENGTH]),
120 }
121 }
122
123 pub async fn refresh(
150 &self,
151 cargo: &str,
152 worktree: &Path,
153 environment: &BTreeMap<String, String>,
154 on_fetch: impl FnOnce() + Send,
155 ) -> io::Result<()> {
156 let lockfile_worktree = worktree.to_path_buf();
157 let lockfile = tokio::task::spawn_blocking(move || Lockfile::read(&lockfile_worktree))
158 .await
159 .map_err(io::Error::other)?;
160 let Some(lockfile) = lockfile.filter(|lockfile| !lockfile.packages.is_empty()) else {
161 return Ok(());
162 };
163 let home = self.root.join(HOME_DIRECTORY);
164 tokio::fs::create_dir_all(&home).await?;
165 for name in CARGO_HOME_CONFIGURATION {
166 match tokio::fs::remove_file(home.join(name)).await {
167 Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
168 _ => {}
169 }
170 }
171 let candidates = ["XDG_RUNTIME_DIR", "TMPDIR"]
172 .iter()
173 .filter_map(|name| environment.get(*name).map(PathBuf::from))
174 .collect::<Vec<_>>();
175 let work = tokio::task::spawn_blocking(move || {
176 let Some(parent) = candidates
177 .into_iter()
178 .find(|parent| Self::is_private(parent))
179 else {
180 return io::Result::Ok(None);
181 };
182 let work = tempfile::Builder::new()
183 .prefix(WORK_PREFIX)
184 .tempdir_in(parent)?;
185
186 Ok((!Self::reads_configuration(work.path())).then_some(work))
187 })
188 .await
189 .map_err(io::Error::other)??;
190 let Some(work) = work else {
191 tracing::debug!("No private directory free of Cargo configuration; not caching");
192
193 return Ok(());
194 };
195 let fetch_environment = self.fetch_environment(environment, work.path());
196 let variant = Self::variant(cargo, work.path(), &fetch_environment).await?;
197 let previous = Generation::load(&self.root).await;
198 let covered = previous
199 .as_ref()
200 .filter(|generation| generation.variant == variant)
201 .map(|generation| generation.missing.clone());
202 if let Some(missing) = covered
203 && Self::uncached(&home, &lockfile.packages, &missing)
204 .await
205 .is_empty()
206 {
207 return Ok(());
208 }
209
210 on_fetch();
211 Self::fetch(cargo, &lockfile, work.path(), &fetch_environment).await?;
212 let missing = Self::uncached(&home, &lockfile.packages, &[]).await;
213 let scan_home = home.clone();
214 let requested = lockfile.packages.clone();
215 let mut files =
216 tokio::task::spawn_blocking(move || Generation::scan(&scan_home, &requested))
217 .await
218 .map_err(io::Error::other)?;
219 let number = previous.as_ref().map_or(0, |generation| generation.number) + 1;
220 let earlier = previous.filter(|generation| generation.variant == variant);
221 files.extend(earlier.into_iter().flat_map(|generation| generation.files));
222 files.sort();
223 files.dedup();
224 Generation {
225 files,
226 missing: missing.clone(),
227 number,
228 variant,
229 }
230 .write(&self.root)
231 .await?;
232 if !missing.is_empty() {
233 return Err(io::Error::other(format!(
234 "cargo fetch left {} packages uncached",
235 missing.len()
236 )));
237 }
238
239 Ok(())
240 }
241
242 pub(crate) fn hidden_path(&self) -> &Path {
246 &self.cache_root
247 }
248
249 pub(crate) fn copy_into(&self, cargo: &OwnedFd, worktree: &Path) {
264 let Some(generation) = Generation::read(&self.root) else {
265 return;
266 };
267 let Some(lockfile) = Lockfile::read(worktree) else {
268 return;
269 };
270 let marker = format!("{}\n{}", generation.number, lockfile.digest);
271 if Self::session_generation(cargo).as_deref() == Some(marker.as_str()) {
272 return;
273 }
274 let home = self.root.join(HOME_DIRECTORY);
275 let recorded = generation
276 .files
277 .iter()
278 .map(String::as_str)
279 .collect::<HashSet<_>>();
280 let mut archives = HashMap::<&str, Vec<(&str, &str)>>::new();
281 let mut indexes = BTreeSet::new();
282 for file in &generation.files {
283 if file.starts_with(REGISTRY_CACHE)
284 && let Some((parent, name)) = file.rsplit_once('/')
285 {
286 archives.entry(name).or_default().push((file, parent));
287 }
288 if let Some(index) = file.strip_prefix(REGISTRY_INDEX)
289 && let Some(directory) = index.trim_start_matches('/').split('/').next()
290 {
291 indexes.insert(directory);
292 }
293 }
294 let mut wanted = indexes
295 .iter()
296 .map(|index| format!("{REGISTRY_INDEX}/{index}/{INDEX_CONFIG}"))
297 .collect::<Vec<_>>();
298 let mut directories = SessionDirectories::new(cargo);
299 for package in &lockfile.packages {
300 let name = package.archive_name();
301 for (file, parent) in archives.get(name.as_str()).into_iter().flatten() {
302 if let Some(directory) = directories.open(parent) {
303 let _ =
304 Self::copy_archive(&home.join(file), directory, &name, &package.checksum);
305 }
306 }
307 wanted.extend(
308 indexes
309 .iter()
310 .map(|index| format!("{REGISTRY_INDEX}/{index}/{}", package.index_entry())),
311 );
312 }
313 for file in wanted
314 .iter()
315 .filter(|file| recorded.contains(file.as_str()))
316 {
317 if let Some((parent, name)) = file.rsplit_once('/')
318 && let Some(directory) = directories.open(parent)
319 {
320 let _ = Self::copy_absent(&home.join(file), directory, name);
321 }
322 }
323 let _ = Self::record_session_generation(cargo, &marker);
324 }
325
326 fn fetch_environment(
330 &self,
331 environment: &BTreeMap<String, String>,
332 work: &Path,
333 ) -> BTreeMap<String, String> {
334 let mut fetch_environment = environment
335 .iter()
336 .filter(|(name, _)| ALLOWED_VARIABLES.contains(&name.as_str()))
337 .map(|(name, value)| (name.clone(), value.clone()))
338 .collect::<BTreeMap<_, _>>();
339 fetch_environment.insert(
340 "CARGO_HOME".to_string(),
341 self.root.join(HOME_DIRECTORY).display().to_string(),
342 );
343 fetch_environment.insert(
344 "CARGO_TARGET_DIR".to_string(),
345 work.join(TARGET_DIRECTORY).display().to_string(),
346 );
347
348 fetch_environment
349 }
350
351 fn is_private(directory: &Path) -> bool {
356 let Ok(directory) = std::fs::canonicalize(directory) else {
357 return false;
358 };
359 let user = rustix::process::geteuid().as_raw();
360
361 directory.ancestors().all(|ancestor| {
362 std::fs::metadata(ancestor).is_ok_and(|metadata| {
363 (metadata.uid() == 0 || metadata.uid() == user) && metadata.mode() & 0o022 == 0
364 })
365 })
366 }
367
368 fn reads_configuration(work: &Path) -> bool {
372 work.ancestors().any(|directory| {
373 ANCESTOR_CONFIGURATION
374 .iter()
375 .any(|name| std::fs::symlink_metadata(directory.join(name)).is_ok())
376 })
377 }
378
379 async fn variant(
386 cargo: &str,
387 directory: &Path,
388 environment: &BTreeMap<String, String>,
389 ) -> io::Result<String> {
390 let version = Self::run_cargo(cargo, "-V", directory, environment).await?;
391
392 Ok(hex::encode(Sha256::digest(&version))[..VARIANT_LENGTH].to_string())
393 }
394
395 async fn uncached(home: &Path, packages: &[LockedPackage], missing: &[String]) -> Vec<String> {
398 let home = home.to_path_buf();
399 let wanted = packages
400 .iter()
401 .map(LockedPackage::archive_name)
402 .filter(|archive| !missing.contains(archive))
403 .collect::<Vec<_>>();
404
405 tokio::task::spawn_blocking(move || {
406 let registries = Generation::crates_io_directories(&home);
407 wanted
408 .into_iter()
409 .filter(|archive| {
410 !registries.iter().any(|registry| {
411 std::fs::symlink_metadata(
412 home.join(REGISTRY_CACHE).join(registry).join(archive),
413 )
414 .is_ok_and(|metadata| metadata.is_file())
415 })
416 })
417 .collect()
418 })
419 .await
420 .unwrap_or_default()
421 }
422
423 async fn fetch(
436 cargo: &str,
437 lockfile: &Lockfile,
438 work: &Path,
439 environment: &BTreeMap<String, String>,
440 ) -> io::Result<()> {
441 tokio::fs::write(work.join("Cargo.toml"), lockfile.synthetic_manifest()).await?;
442 tokio::fs::write(work.join("Cargo.lock"), lockfile.synthetic_lockfile()).await?;
443 tokio::fs::write(work.join("lib.rs"), "").await?;
444
445 Self::run_cargo(cargo, "fetch", work, environment)
446 .await
447 .map(drop)
448 }
449
450 async fn run_cargo(
457 cargo: &str,
458 command: &str,
459 directory: &Path,
460 environment: &BTreeMap<String, String>,
461 ) -> io::Result<Vec<u8>> {
462 let output = tokio::process::Command::new(cargo)
463 .arg(command)
464 .current_dir(directory)
465 .env_clear()
466 .envs(environment)
467 .stdin(Stdio::null())
468 .stderr(Stdio::null())
469 .kill_on_drop(true)
470 .output();
471 let output = tokio::time::timeout(CARGO_TIMEOUT, output)
472 .await
473 .map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;
474 if !output.status.success() {
475 return Err(io::Error::other(format!(
476 "cargo {command} failed with {}",
477 output.status
478 )));
479 }
480
481 Ok(output.stdout)
482 }
483
484 fn copy_archive(
491 source: &Path,
492 directory: &OwnedFd,
493 name: &str,
494 checksum: &str,
495 ) -> io::Result<()> {
496 if fs::statat(directory, name, AtFlags::SYMLINK_NOFOLLOW).is_ok() {
497 return Ok(());
498 }
499 let partial = format!(".{name}{PARTIAL_SUFFIX}");
500 let _ = fs::unlinkat(directory, partial.as_str(), AtFlags::empty());
501 let mut source = std::fs::File::open(source)?;
502 let mut destination = std::fs::File::from(fs::openat(
503 directory,
504 partial.as_str(),
505 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
506 Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::ROTH,
507 )?);
508 let mut hasher = Sha256::new();
509 let mut buffer = vec![0; 64 * 1024];
510 loop {
511 let read = source.read(&mut buffer)?;
512 if read == 0 {
513 break;
514 }
515 hasher.update(&buffer[..read]);
516 destination.write_all(&buffer[..read])?;
517 }
518 drop(destination);
519 let verified = hex::encode(hasher.finalize()) == checksum;
520 let linked = if verified {
521 fs::linkat(
522 directory,
523 partial.as_str(),
524 directory,
525 name,
526 AtFlags::empty(),
527 )
528 .map_err(io::Error::from)
529 } else {
530 Err(io::Error::from(io::ErrorKind::InvalidData))
531 };
532 let _ = fs::unlinkat(directory, partial.as_str(), AtFlags::empty());
533
534 linked
535 }
536
537 fn session_generation(cargo: &OwnedFd) -> Option<String> {
539 let descriptor = fs::openat(
540 cargo,
541 SESSION_GENERATION_FILE,
542 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
543 Mode::empty(),
544 )
545 .ok()?;
546 let mut contents = String::new();
547 std::fs::File::from(descriptor)
548 .take(256)
549 .read_to_string(&mut contents)
550 .ok()?;
551
552 Some(contents)
553 }
554
555 fn record_session_generation(cargo: &OwnedFd, marker: &str) -> io::Result<()> {
560 let descriptor = fs::openat(
563 cargo,
564 SESSION_GENERATION_FILE,
565 OFlags::WRONLY | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
566 Mode::RUSR | Mode::WUSR,
567 )?;
568 if !FileType::from_raw_mode(fs::fstat(&descriptor)?.st_mode).is_file() {
569 return Err(io::Error::from(io::ErrorKind::InvalidInput));
570 }
571 fs::ftruncate(&descriptor, 0)?;
572
573 std::fs::File::from(descriptor).write_all(marker.as_bytes())
574 }
575
576 fn copy_absent(source: &Path, directory: &OwnedFd, name: &str) -> io::Result<()> {
582 let mut source = std::fs::File::open(source)?;
583 let descriptor = fs::openat(
584 directory,
585 name,
586 OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
587 Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::ROTH,
588 )?;
589 io::copy(&mut source, &mut std::fs::File::from(descriptor))?;
590
591 Ok(())
592 }
593}
594
595#[derive(Debug, Eq, PartialEq)]
597struct Generation {
598 files: Vec<String>,
600 missing: Vec<String>,
602 number: u64,
604 variant: String,
606}
607
608impl Generation {
609 fn read(root: &Path) -> Option<Self> {
612 Self::parse(&std::fs::read_to_string(root.join(GENERATION_FILE)).ok()?)
613 }
614
615 async fn load(root: &Path) -> Option<Self> {
617 Self::parse(
618 &tokio::fs::read_to_string(root.join(GENERATION_FILE))
619 .await
620 .ok()?,
621 )
622 }
623
624 fn parse(contents: &str) -> Option<Self> {
626 let mut lines = contents.lines();
627 if lines.next()? != GENERATION_HEADER {
628 return None;
629 }
630 let number = lines.next()?.parse().ok()?;
631 let variant = lines.next()?.to_string();
632 let mut files = Vec::new();
633 let mut missing = Vec::new();
634 for line in lines {
635 if let Some(file) = line.strip_prefix("file ")
636 && Self::is_relative_file(file)
637 {
638 files.push(file.to_string());
639 } else if let Some(archive) = line.strip_prefix("missing ") {
640 missing.push(archive.to_string());
641 }
642 }
643
644 Some(Self {
645 files,
646 missing,
647 number,
648 variant,
649 })
650 }
651
652 fn scan(home: &Path, requested: &[LockedPackage]) -> Vec<String> {
657 let mut files = Vec::new();
658 for registry in Self::crates_io_directories(home) {
659 let archives = home.join(REGISTRY_CACHE).join(®istry);
660 let index = home.join(REGISTRY_INDEX).join(®istry);
661 files.push(index.join(INDEX_CONFIG));
662 for package in requested {
663 files.push(archives.join(package.archive_name()));
664 files.push(index.join(package.index_entry()));
665 }
666 }
667 files.retain(|file| {
668 std::fs::symlink_metadata(file).is_ok_and(|metadata| metadata.is_file())
669 });
670
671 let mut relative = files
672 .iter()
673 .filter_map(|file| file.strip_prefix(home).ok()?.to_str())
674 .filter(|file| Self::is_relative_file(file))
675 .map(str::to_string)
676 .collect::<Vec<_>>();
677 relative.sort();
678
679 relative
680 }
681
682 fn crates_io_directories(home: &Path) -> Vec<String> {
687 std::fs::read_dir(home.join(REGISTRY_INDEX))
688 .into_iter()
689 .flatten()
690 .flatten()
691 .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
692 .filter_map(|entry| entry.file_name().into_string().ok())
693 .filter(|name| {
694 name.starts_with(CRATES_IO_DIRECTORY_PREFIX) && Self::is_relative_file(name)
695 })
696 .filter(|name| {
697 let config = home.join(REGISTRY_INDEX).join(name).join(INDEX_CONFIG);
698 let mut contents = Vec::new();
699 let read = std::fs::File::open(config)
700 .and_then(|file| file.take(MAX_INDEX_CONFIG_BYTES).read_to_end(&mut contents));
701
702 read.is_ok()
703 && serde_json::from_slice::<serde_json::Value>(&contents).is_ok_and(|config| {
704 config.get("dl").and_then(serde_json::Value::as_str)
705 == Some(CRATES_IO_DOWNLOADS)
706 && config
707 .get("auth-required")
708 .is_none_or(|required| required == &serde_json::Value::Bool(false))
709 })
710 })
711 .collect()
712 }
713
714 fn is_relative_file(file: &str) -> bool {
717 !file.is_empty()
718 && !file.contains('\n')
719 && file
720 .split('/')
721 .all(|component| !component.is_empty() && component != "." && component != "..")
722 }
723
724 async fn write(&self, root: &Path) -> io::Result<()> {
731 let mut contents = format!("{GENERATION_HEADER}\n{}\n{}\n", self.number, self.variant);
732 for file in &self.files {
733 let _ = writeln!(contents, "file {file}");
734 }
735 for archive in &self.missing {
736 let _ = writeln!(contents, "missing {archive}");
737 }
738 let root = root.to_path_buf();
739
740 tokio::task::spawn_blocking(move || {
741 let mut pending = tempfile::NamedTempFile::new_in(&root)?;
742 pending.write_all(contents.as_bytes())?;
743 pending
744 .persist(root.join(GENERATION_FILE))
745 .map(drop)
746 .map_err(io::Error::from)
747 })
748 .await
749 .map_err(io::Error::other)?
750 }
751}
752
753struct SessionDirectories<'a> {
756 cargo: &'a OwnedFd,
757 opened: HashMap<String, OwnedFd>,
758}
759
760impl<'a> SessionDirectories<'a> {
761 fn new(cargo: &'a OwnedFd) -> Self {
763 Self {
764 cargo,
765 opened: HashMap::new(),
766 }
767 }
768
769 fn open(&mut self, relative: &str) -> Option<&OwnedFd> {
772 let mut prefix_end = 0_usize;
773 for component in relative.split('/') {
774 let parent_prefix = &relative[..prefix_end.saturating_sub(1)];
775 prefix_end += component.len() + 1;
776 let prefix = &relative[..prefix_end - 1];
777 if self.opened.contains_key(prefix) {
778 continue;
779 }
780 let parent = if parent_prefix.is_empty() {
781 self.cargo
782 } else {
783 self.opened.get(parent_prefix)?
784 };
785 let _ = fs::mkdirat(parent, component, Mode::RWXU);
787 let opened = fs::openat(
788 parent,
789 component,
790 CommandSandbox::directory_flags(),
791 Mode::empty(),
792 )
793 .ok()?;
794 self.opened.insert(prefix.to_string(), opened);
795 }
796
797 self.opened.get(relative)
798 }
799}
800
801#[cfg(test)]
802#[path = "cargo_cache_test.rs"]
803mod tests;