Skip to main content

code_system_graph_core/
registry.rs

1use std::collections::{BTreeMap, HashMap};
2use std::path::{Path, PathBuf};
3use std::process::Command;
4use std::sync::{LazyLock, Mutex};
5use std::time::{Duration, SystemTime};
6
7use code_system_graph_model::{
8    CheckoutId, NativePath, NativePathEncoding, RepoId, RepositoryRecord, WorkspaceId, WorkspaceRecord, stable_id, stable_id_bytes
9};
10use thiserror::Error;
11use url::Url;
12
13use crate::WorkspaceManifest;
14use crate::parallel::map_ordered;
15
16/// Upper bound on concurrent per-repository Git inspections during registration.
17const MAX_REGISTRATION_WORKERS: usize = 8;
18
19/// A cached remote is trusted only when its Git config was last written at least this long ago,
20/// so a same-timestamp rewrite after caching always changes the observed metadata.
21const REMOTE_CACHE_RACY_WINDOW: Duration = Duration::from_secs(2);
22
23/// Modification time and length of a Git config file.
24type ConfigStamp = (SystemTime, u64);
25
26/// `origin` remotes keyed by Git config path, each validated by the stamp it was read under.
27type RemoteCache = HashMap<PathBuf, (ConfigStamp, Option<String>)>;
28
29/// Process-wide remote cache shared by every registration in this process.
30static REMOTE_CACHE: LazyLock<Mutex<RemoteCache>> = LazyLock::new(|| Mutex::new(HashMap::new()));
31
32/// Validated workspace record plus native paths used by scanners.
33#[derive(Debug, Clone)]
34pub struct RegisteredWorkspace {
35    /// Serializable registry record suitable for persistence.
36    pub record: WorkspaceRecord,
37    checkout_paths: BTreeMap<String, PathBuf>,
38}
39
40impl RegisteredWorkspace {
41    /// Returns the canonical checkout path for a registered alias.
42    #[must_use]
43    pub fn checkout_path(&self, alias: &str) -> Option<&Path> {
44        self.checkout_paths.get(alias).map(PathBuf::as_path)
45    }
46}
47
48/// Error returned while resolving a workspace registry.
49#[derive(Debug, Error)]
50pub enum RegistryError {
51    /// The manifest path has no parent directory.
52    #[error("workspace manifest path `{0}` has no parent directory")]
53    ManifestParentMissing(PathBuf),
54    /// A configured path could not be canonicalized.
55    #[error("failed to canonicalize `{path}`: {source}")]
56    Canonicalize {
57        /// Path supplied or derived from the manifest.
58        path: PathBuf,
59        /// Underlying filesystem error.
60        source: std::io::Error,
61    },
62    /// A repository resolves outside every configured root.
63    #[error(
64        "repository `{alias}` resolves outside allowed roots: `{path}`; \
65         add an explicit `allowedRoots` entry"
66    )]
67    OutsideAllowedRoots {
68        /// Repository alias.
69        alias: String,
70        /// Canonical path rejected by policy.
71        path: PathBuf,
72    },
73}
74
75/// Resolves canonical repository and linked-worktree identities without modifying Git state.
76///
77/// The manifest directory is always an allowed root. Additional roots must be declared through
78/// `allowedRoots`. Repository IDs prefer a credential-free normalized remote and otherwise use
79/// the Git common directory or canonical checkout path. Checkout IDs always include the concrete
80/// worktree path.
81///
82/// # Errors
83///
84/// Returns [`RegistryError`] when configured paths do not exist, cannot be canonicalized, or
85/// escape the root allowlist.
86pub fn register_workspace(
87    config_path: &Path,
88    manifest_source: &str,
89    manifest: &WorkspaceManifest,
90) -> Result<RegisteredWorkspace, RegistryError> {
91    let canonical_config = canonicalize(config_path)?;
92    let config_directory = canonical_config
93        .parent()
94        .ok_or_else(|| RegistryError::ManifestParentMissing(config_path.to_path_buf()))?;
95    let config_directory = config_directory.to_path_buf();
96    let mut allowed_roots = vec![config_directory.clone()];
97    for configured_root in &manifest.allowed_roots {
98        let root = resolve_path(&config_directory, Path::new(configured_root));
99        allowed_roots.push(canonicalize(&root)?);
100    }
101    allowed_roots.sort();
102    allowed_roots.dedup();
103
104    let configured = manifest
105        .repos
106        .iter()
107        .map(|(alias, repository)| (alias.as_str(), repository.path.as_str()))
108        .collect::<Vec<_>>();
109    let workers = std::thread::available_parallelism()
110        .map_or(1, std::num::NonZeroUsize::get)
111        .min(MAX_REGISTRATION_WORKERS);
112    let mut records = Vec::with_capacity(configured.len());
113    let mut checkout_paths = BTreeMap::new();
114    for registered in map_ordered(&configured, workers, |(alias, path)| {
115        register_repository(alias, path, &config_directory, &allowed_roots)
116    }) {
117        let (record, checkout_path) = registered?;
118        checkout_paths.insert(record.alias.clone(), checkout_path);
119        records.push(record);
120    }
121    records.sort_by(|left, right| left.alias.cmp(&right.alias));
122
123    let config_native = encode_native_path(&config_directory);
124    let workspace_id = WorkspaceId::new(stable_id(
125        "workspace",
126        &format!(
127            "{}:{}",
128            manifest.name,
129            native_path_fingerprint(&config_native)
130        ),
131    ));
132    Ok(RegisteredWorkspace {
133        record: WorkspaceRecord {
134            id: workspace_id,
135            name: manifest.name.clone(),
136            manifest_hash: stable_id("manifest", manifest_source),
137            config_path: Some(encode_native_path(&canonical_config)),
138            repositories: records,
139        },
140        checkout_paths,
141    })
142}
143
144fn register_repository(
145    alias: &str,
146    configured_path: &str,
147    config_directory: &Path,
148    allowed_roots: &[PathBuf],
149) -> Result<(RepositoryRecord, PathBuf), RegistryError> {
150    let configured_path = resolve_path(config_directory, Path::new(configured_path));
151    let configured_path = canonicalize(&configured_path)?;
152    let git_root = configured_path
153        .join(".git")
154        .exists()
155        .then(|| git_path(&configured_path, &["rev-parse", "--show-toplevel"]))
156        .flatten()
157        .and_then(|path| canonicalize(&path).ok())
158        .filter(|path| path == &configured_path);
159    let is_git_repository = git_root.is_some();
160    let checkout_path = git_root.unwrap_or(configured_path);
161    ensure_allowed(alias, &checkout_path, allowed_roots)?;
162
163    let git_common_dir = is_git_repository
164        .then(|| git_common_directory(&checkout_path))
165        .flatten();
166    if let Some(common_dir) = &git_common_dir {
167        ensure_allowed(alias, common_dir, allowed_roots)?;
168    }
169    let normalized_remote = is_git_repository
170        .then(|| origin_remote(&checkout_path, git_common_dir.as_deref()))
171        .flatten()
172        .map(|remote| normalize_remote(&remote));
173    let head_commit = is_git_repository
174        .then(|| git_text(&checkout_path, &["rev-parse", "HEAD"]))
175        .flatten();
176    let working_tree_dirty = is_git_repository
177        && git_output(
178            &checkout_path,
179            &["status", "--porcelain", "--untracked-files=normal"],
180        )
181        .is_some_and(|output| !output.is_empty());
182    let native_checkout = encode_native_path(&checkout_path);
183    let native_common = git_common_dir.as_deref().map(encode_native_path);
184    let repository_key = normalized_remote.as_ref().map_or_else(
185        || {
186            native_common.as_ref().map_or_else(
187                || format!("path:{}", native_path_fingerprint(&native_checkout)),
188                |common| format!("git:{}", native_path_fingerprint(common)),
189            )
190        },
191        |remote| format!("remote:{remote}"),
192    );
193    let repo_id = RepoId::new(stable_id("repo", &repository_key));
194    let checkout_id = CheckoutId::new(stable_id(
195        "checkout",
196        &format!(
197            "{}:{}",
198            repo_id.as_str(),
199            native_path_fingerprint(&native_checkout)
200        ),
201    ));
202    let is_linked_worktree = checkout_path.join(".git").is_file();
203    let record = RepositoryRecord {
204        id: repo_id,
205        checkout_id,
206        alias: alias.to_owned(),
207        canonical_path: native_checkout,
208        git_common_dir: native_common,
209        normalized_remote,
210        head_commit,
211        is_linked_worktree,
212        working_tree_dirty,
213    };
214    Ok((record, checkout_path))
215}
216
217/// Returns the raw `origin` URL, reusing the cached value while the Git config is unchanged.
218fn origin_remote(checkout_path: &Path, common_dir: Option<&Path>) -> Option<String> {
219    let config_path = common_dir.map_or_else(
220        || checkout_path.join(".git").join("config"),
221        |common| common.join("config"),
222    );
223    let stamp = std::fs::metadata(&config_path)
224        .ok()
225        .and_then(|metadata| Some((metadata.modified().ok()?, metadata.len())))
226        .filter(|(modified, _)| {
227            SystemTime::now()
228                .duration_since(*modified)
229                .is_ok_and(|age| age >= REMOTE_CACHE_RACY_WINDOW)
230        });
231    if let Some(stamp) = stamp
232        && let Ok(cache) = REMOTE_CACHE.lock()
233        && let Some((cached_stamp, remote)) = cache.get(&config_path)
234        && *cached_stamp == stamp
235    {
236        return remote.clone();
237    }
238    let remote = git_text(checkout_path, &["remote", "get-url", "origin"]);
239    if let Some(stamp) = stamp
240        && let Ok(mut cache) = REMOTE_CACHE.lock()
241    {
242        cache.insert(config_path, (stamp, remote.clone()));
243    }
244    remote
245}
246
247/// Encodes a native path without requiring UTF-8.
248#[must_use]
249pub fn encode_native_path(path: &Path) -> NativePath {
250    NativePath {
251        encoding: native_path_encoding(),
252        bytes: native_path_bytes(path),
253        display: path.to_string_lossy().into_owned(),
254    }
255}
256
257fn canonicalize(path: &Path) -> Result<PathBuf, RegistryError> {
258    std::fs::canonicalize(path).map_err(|source| RegistryError::Canonicalize {
259        path: path.to_path_buf(),
260        source,
261    })
262}
263
264fn ensure_allowed(
265    alias: &str,
266    path: &Path,
267    allowed_roots: &[PathBuf],
268) -> Result<(), RegistryError> {
269    if allowed_roots.iter().any(|root| path.starts_with(root)) {
270        return Ok(());
271    }
272    Err(RegistryError::OutsideAllowedRoots {
273        alias: alias.to_owned(),
274        path: path.to_path_buf(),
275    })
276}
277
278fn resolve_path(base: &Path, path: &Path) -> PathBuf {
279    if path.is_absolute() {
280        path.to_path_buf()
281    } else {
282        base.join(path)
283    }
284}
285
286fn git_common_directory(checkout_path: &Path) -> Option<PathBuf> {
287    git_path(
288        checkout_path,
289        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
290    )
291    .or_else(|| {
292        git_path(checkout_path, &["rev-parse", "--git-common-dir"])
293            .map(|path| resolve_path(checkout_path, &path))
294    })
295    .and_then(|path| std::fs::canonicalize(path).ok())
296}
297
298fn git_path(checkout_path: &Path, arguments: &[&str]) -> Option<PathBuf> {
299    git_output(checkout_path, arguments).map(path_from_git_output)
300}
301
302fn git_text(checkout_path: &Path, arguments: &[&str]) -> Option<String> {
303    git_output(checkout_path, arguments)
304        .map(|bytes| String::from_utf8_lossy(&bytes).trim().to_owned())
305        .filter(|value| !value.is_empty())
306}
307
308fn git_output(checkout_path: &Path, arguments: &[&str]) -> Option<Vec<u8>> {
309    let output = Command::new("git")
310        .arg("-C")
311        .arg(checkout_path)
312        .args(arguments)
313        .env("GIT_OPTIONAL_LOCKS", "0")
314        .output()
315        .ok()?;
316    output.status.success().then_some(trim_ascii(output.stdout))
317}
318
319fn trim_ascii(mut bytes: Vec<u8>) -> Vec<u8> {
320    while bytes.last().is_some_and(u8::is_ascii_whitespace) {
321        bytes.pop();
322    }
323    bytes
324}
325
326fn normalize_remote(remote: &str) -> String {
327    let trimmed = remote.trim();
328    if let Some((authority, path)) = scp_remote_parts(trimmed) {
329        return format!(
330            "{}/{}",
331            authority.to_ascii_lowercase(),
332            clean_remote_path(path)
333        );
334    }
335    if let Ok(url) = Url::parse(trimmed) {
336        if let Some(host) = url.host_str() {
337            return format!(
338                "{}/{}",
339                host.to_ascii_lowercase(),
340                clean_remote_path(url.path())
341            );
342        }
343        return format!("{}:{}", url.scheme(), clean_remote_path(url.path()));
344    }
345    clean_remote_path(trimmed)
346}
347
348fn scp_remote_parts(remote: &str) -> Option<(&str, &str)> {
349    if remote.contains("://") {
350        return None;
351    }
352    let (authority, path) = remote.split_once(':')?;
353    let host = authority
354        .rsplit_once('@')
355        .map_or(authority, |(_, host)| host);
356    (!host.is_empty() && !path.is_empty()).then_some((host, path))
357}
358
359fn clean_remote_path(path: &str) -> String {
360    path.trim()
361        .trim_matches('/')
362        .trim_end_matches(".git")
363        .replace('\\', "/")
364}
365
366fn native_path_fingerprint(path: &NativePath) -> String {
367    let namespace = match path.encoding {
368        NativePathEncoding::UnixBytes => "path-unix",
369        NativePathEncoding::WindowsWide => "path-windows",
370        NativePathEncoding::Utf8 => "path-utf8",
371    };
372    stable_id_bytes(namespace, &path.bytes)
373}
374
375#[cfg(unix)]
376fn native_path_encoding() -> NativePathEncoding {
377    NativePathEncoding::UnixBytes
378}
379
380#[cfg(windows)]
381fn native_path_encoding() -> NativePathEncoding {
382    NativePathEncoding::WindowsWide
383}
384
385#[cfg(not(any(unix, windows)))]
386fn native_path_encoding() -> NativePathEncoding {
387    NativePathEncoding::Utf8
388}
389
390#[cfg(unix)]
391fn native_path_bytes(path: &Path) -> Vec<u8> {
392    use std::os::unix::ffi::OsStrExt;
393
394    path.as_os_str().as_bytes().to_vec()
395}
396
397#[cfg(windows)]
398fn native_path_bytes(path: &Path) -> Vec<u8> {
399    use std::os::windows::ffi::OsStrExt;
400
401    path.as_os_str()
402        .encode_wide()
403        .flat_map(u16::to_le_bytes)
404        .collect()
405}
406
407#[cfg(not(any(unix, windows)))]
408fn native_path_bytes(path: &Path) -> Vec<u8> {
409    path.to_string_lossy().as_bytes().to_vec()
410}
411
412#[cfg(unix)]
413fn path_from_git_output(bytes: Vec<u8>) -> PathBuf {
414    use std::os::unix::ffi::OsStringExt;
415
416    PathBuf::from(std::ffi::OsString::from_vec(bytes))
417}
418
419#[cfg(not(unix))]
420fn path_from_git_output(bytes: Vec<u8>) -> PathBuf {
421    PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
422}
423
424#[cfg(test)]
425mod tests {
426    use std::fs;
427    use std::path::Path;
428    use std::process::Command;
429
430    use super::{normalize_remote, register_workspace};
431    use crate::parse_manifest;
432
433    #[test]
434    fn normalize_remote_should_remove_credentials_protocol_and_git_suffix() {
435        let https = normalize_remote("https://token@example.com/team/api.git");
436        let ssh = normalize_remote("git@example.com:team/api.git");
437
438        assert_eq!(https, ssh);
439    }
440
441    #[cfg(unix)]
442    #[test]
443    fn encode_native_path_should_preserve_non_utf8_bytes() {
444        use std::ffi::OsString;
445        use std::os::unix::ffi::OsStringExt;
446
447        let path =
448            std::path::PathBuf::from(OsString::from_vec(vec![b'/', b't', b'm', b'p', b'/', 0xff]));
449        let encoded = super::encode_native_path(&path);
450
451        assert_eq!(encoded.bytes, vec![b'/', b't', b'm', b'p', b'/', 0xff]);
452    }
453
454    #[test]
455    fn register_workspace_should_reject_symlink_escape() -> Result<(), Box<dyn std::error::Error>> {
456        let temporary = tempfile::tempdir()?;
457        let workspace = temporary.path().join("workspace");
458        let outside = temporary.path().join("outside");
459        fs::create_dir_all(&workspace)?;
460        fs::create_dir_all(&outside)?;
461        #[cfg(unix)]
462        std::os::unix::fs::symlink(&outside, workspace.join("escaped"))?;
463        #[cfg(windows)]
464        std::os::windows::fs::symlink_dir(&outside, workspace.join("escaped"))?;
465        let manifest_path = workspace.join("code-system-graph.yaml");
466        fs::write(&manifest_path, "")?;
467        let source = "version: 1\nname: test\nrepos:\n  escaped:\n    path: escaped\n";
468        let manifest = parse_manifest(source)?;
469        let result = register_workspace(&manifest_path, source, &manifest);
470
471        assert!(matches!(
472            result,
473            Err(super::RegistryError::OutsideAllowedRoots { .. })
474        ));
475        Ok(())
476    }
477
478    #[test]
479    fn register_workspace_should_share_repo_id_across_linked_worktrees()
480    -> Result<(), Box<dyn std::error::Error>> {
481        let temporary = tempfile::tempdir()?;
482        let repository = temporary.path().join("repository");
483        let linked = temporary.path().join("linked");
484        fs::create_dir_all(&repository)?;
485        git(&repository, &["init"])?;
486        git(&repository, &["config", "core.autocrlf", "false"])?;
487        fs::write(repository.join("README.md"), "fixture")?;
488        git(&repository, &["add", "README.md"])?;
489        git(
490            &repository,
491            &[
492                "-c",
493                "user.name=Code System Graph Test",
494                "-c",
495                "user.email=code-system-graph@example.invalid",
496                "commit",
497                "-m",
498                "fixture",
499            ],
500        )?;
501        git(
502            &repository,
503            &[
504                "worktree",
505                "add",
506                "-b",
507                "linked-fixture",
508                linked.to_string_lossy().as_ref(),
509            ],
510        )?;
511        let manifest_path = temporary.path().join("code-system-graph.yaml");
512        let source = "version: 1\nname: test\nrepos:\n  main:\n    path: repository\n  linked:\n    path: linked\n";
513        fs::write(&manifest_path, source)?;
514        let manifest = parse_manifest(source)?;
515        let registry = register_workspace(&manifest_path, source, &manifest)?;
516        let main = registry
517            .record
518            .repositories
519            .iter()
520            .find(|record| record.alias == "main")
521            .ok_or_else(|| std::io::Error::other("main record missing"))?;
522        let worktree = registry
523            .record
524            .repositories
525            .iter()
526            .find(|record| record.alias == "linked")
527            .ok_or_else(|| std::io::Error::other("linked record missing"))?;
528
529        assert_eq!(
530            (
531                main.id.clone(),
532                main.checkout_id == worktree.checkout_id,
533                worktree.id.clone(),
534                worktree.is_linked_worktree,
535            ),
536            (worktree.id.clone(), false, main.id.clone(), true)
537        );
538        Ok(())
539    }
540
541    fn git(repository: &Path, arguments: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
542        let output = Command::new("git")
543            .arg("-C")
544            .arg(repository)
545            .args(arguments)
546            .output()?;
547        if output.status.success() {
548            return Ok(());
549        }
550        Err(std::io::Error::other(String::from_utf8_lossy(&output.stderr)).into())
551    }
552}