Skip to main content

git_cache_proxy/
repo.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Request-path -> (upstream URL, on-disk cache dir) resolution, hardened
3//! against path traversal.
4
5use std::path::{Path, PathBuf};
6
7use anyhow::{Result, bail};
8
9/// A resolved repository: where to fetch it from and where it is cached.
10#[derive(Debug, Clone)]
11pub struct RepoRef {
12    /// Normalised repo path, e.g. `group/team/foo.git`. Used as the cache key
13    /// and as the sub-path under the cache root.
14    pub name: String,
15    /// Full upstream clone URL.
16    pub upstream_url: String,
17    /// On-disk bare mirror directory.
18    pub cache_dir: PathBuf,
19}
20
21/// Strip a smart-HTTP endpoint suffix (`/info/refs`, `/git-upload-pack`) from a
22/// request path and return the repo name. `None` if the suffix isn't present.
23pub 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
30/// Validate a repo path (no traversal / absolute / NUL) and resolve it against
31/// the upstream base and cache root.
32pub 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    // Defence in depth against traversal that slipped past the component checks.
43    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}