1use std::path::{Path, PathBuf};
6
7use anyhow::{Result, bail};
8
9#[derive(Debug, Clone)]
11pub struct RepoRef {
12 pub name: String,
15 pub upstream_url: String,
17 pub cache_dir: PathBuf,
19}
20
21pub fn repo_name_from_path(path: &str, suffix: &str) -> Option<String> {
24 let repo = path
25 .trim_start_matches('/')
26 .strip_suffix(suffix.trim_start_matches('/'))?;
27 Some(repo.trim_end_matches('/').to_string())
28}
29
30pub fn resolve(name: &str, upstream_base: &str, cache_root: &Path) -> Result<RepoRef> {
33 if name.is_empty() || name.contains('\0') || name.starts_with('/') {
34 bail!("invalid repo path: {name:?}");
35 }
36 for comp in name.split('/') {
37 if comp.is_empty() || comp == "." || comp == ".." {
38 bail!("invalid repo path component in {name:?}");
39 }
40 }
41 let cache_dir = cache_root.join(name);
42 if !cache_dir.starts_with(cache_root) {
44 bail!("repo path escapes cache root: {name:?}");
45 }
46 let upstream_url = format!("{}/{}", upstream_base.trim_end_matches('/'), name);
47 Ok(RepoRef {
48 name: name.to_string(),
49 upstream_url,
50 cache_dir,
51 })
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57
58 #[test]
59 fn strips_suffixes() {
60 assert_eq!(
61 repo_name_from_path("/group/team/foo.git/info/refs", "/info/refs").as_deref(),
62 Some("group/team/foo.git")
63 );
64 assert_eq!(
65 repo_name_from_path("/a/b.git/git-upload-pack", "/git-upload-pack").as_deref(),
66 Some("a/b.git")
67 );
68 assert_eq!(repo_name_from_path("/nope", "/info/refs"), None);
69 }
70
71 #[test]
72 fn rejects_traversal() {
73 let root = Path::new("/cache");
74 assert!(resolve("../etc/passwd", "https://up", root).is_err());
75 assert!(resolve("a/../../b", "https://up", root).is_err());
76 assert!(resolve("/abs", "https://up", root).is_err());
77 let ok = resolve("g/r.git", "https://up/", root).unwrap();
78 assert_eq!(ok.upstream_url, "https://up/g/r.git");
79 assert_eq!(ok.cache_dir, Path::new("/cache/g/r.git"));
80 }
81}