lean-ctx-cloud 3.12.8

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Repository identity and the local map of resolved Cloud vaults.
//!
//! The identity Cloud sees is `stable_identity(project_identity(root))`
//! salted by the org (`identity_digest`). It is the same for every checkout
//! of a repository on every machine (`.lean-ctx-id` > git origin >
//! manifests) and never contains a path, user name or credential.

use std::path::Path;

use hmac::{Hmac, KeyInit as _, Mac as _};
use sha2::Sha256;

use super::CloudError;
use super::link::read_link;
use lean_ctx_protocol::cloud::vault::{
    VAULT_RESOLVE_REQUEST_SCHEMA, VaultResolveRequestV1, stable_identity,
};

pub use lean_ctx::core::vault_map::{VaultMap, VaultRecord};

/// `github.com/acme/payments` for every spelling of the same remote:
/// scheme, credentials, `.git` suffix, scp syntax and host case removed.
pub fn normalize_git_url(url: &str) -> String {
    let url = url.trim();
    let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    // Credentials sit in the authority only (before the first `/`).
    let authority_end = without_scheme.find('/').unwrap_or(without_scheme.len());
    let without_user = without_scheme[..authority_end]
        .rfind('@')
        .map_or(without_scheme, |at| &without_scheme[at + 1..]);
    // scp-like `host:org/repo` (no port digits right after the colon)
    let path_form = match without_user.split_once(':') {
        Some((host, rest)) if !rest.starts_with(|c: char| c.is_ascii_digit()) => {
            format!("{host}/{rest}")
        }
        Some((host, rest)) => {
            let rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
            format!("{host}{rest}")
        }
        None => without_user.to_string(),
    };
    let trimmed = path_form.trim_end_matches('/');
    let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed);
    match trimmed.split_once('/') {
        Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
        None => trimmed.to_ascii_lowercase(),
    }
}

/// The machine-independent identity of the project at `root`, if it has one.
///
/// A `.lean-ctx-id` that `cloud link` wrote ([`link_made_id`]) gives way to
/// the git origin: earlier engines wrote one per checkout, so two checkouts
/// of one origin had two identities and two vaults. Without an origin the
/// id stays the identity; a hand-written id (a name) always does.
pub fn project_identity(root: &Path) -> Option<String> {
    let root_str = root.to_string_lossy();
    let mut identity = lean_ctx::core::project_hash::project_identity(&root_str)?;
    if let Some(id) = identity.strip_prefix("explicit:")
        && link_made_id(id)
        && let Some(origin) = lean_ctx::core::project_hash::origin_identity(&root_str)
    {
        identity = origin;
    }
    Some(match identity.strip_prefix("git:") {
        Some(url) => format!("git:{}", normalize_git_url(url)),
        None => identity,
    })
}

/// Whether a `.lean-ctx-id` value has the shape `cloud link` writes: 32
/// lowercase hex characters (16 random bytes).
pub fn link_made_id(id: &str) -> bool {
    id.len() == 32
        && id
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// `hex(HMAC-SHA256(org_salt, stable_identity))`.
pub fn identity_digest(salt: &[u8], stable: &str) -> String {
    let mut mac = Hmac::<Sha256>::new_from_slice(salt).expect("HMAC takes any key length");
    mac.update(stable.as_bytes());
    hex::encode(mac.finalize().into_bytes())
}

/// The resolve request for the project at `root`.
pub fn resolve_request(
    root: &Path,
    org_salt_id: &str,
    salt: &[u8],
    with_label: bool,
) -> Result<(String, VaultResolveRequestV1), CloudError> {
    let identity = project_identity(root).ok_or_else(|| {
        CloudError::Config(format!(
            "{} has no stable identity (no git origin or manifest); run `lean-ctx cloud link <workspace>/<vault>` there",
            root.display()
        ))
    })?;
    let stable = stable_identity(&identity);
    let label = with_label
        .then(|| {
            root.file_name()
                .map(|n| n.to_string_lossy().chars().take(64).collect::<String>())
        })
        .flatten()
        .filter(|l: &String| !l.trim().is_empty() && !l.chars().any(char::is_control));
    let request = VaultResolveRequestV1 {
        schema: VAULT_RESOLVE_REQUEST_SCHEMA.into(),
        org_salt_id: org_salt_id.into(),
        identity_digest: identity_digest(salt, &stable),
        label,
        vault: read_link(root)?.map(|link| link.vault),
    };
    Ok((stable, request))
}

/// Round trip of a local Cloud file across the VA rename. `T` reads `old`
/// (the file as an engine before the rename wrote it) and the same file
/// with `old_key` spelled `new_key`; what `T` writes keeps `old_key`, so
/// `Old` (the struct definition of the engine before the rename) reads it.
#[cfg(test)]
pub(crate) fn assert_pre_va_round_trip<T, Old>(old: &str, old_key: &str, new_key: &str) -> T
where
    T: serde::Serialize + serde::de::DeserializeOwned,
    Old: serde::de::DeserializeOwned,
{
    let (old_key, new_key) = (format!("\"{old_key}\""), format!("\"{new_key}\""));
    let read: T = serde_json::from_str(old).expect("reads the pre-VA form");
    let written = serde_json::to_string(&read).expect("writes");
    assert!(
        written.contains(&old_key) && !written.contains(&new_key),
        "{written}"
    );
    serde_json::from_str::<Old>(&written).expect("an engine before the rename reads it");
    serde_json::from_str::<T>(&old.replace(&old_key, &new_key)).expect("reads the new spelling");
    read
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    use serde::Deserialize;

    #[test]
    fn git_urls_lose_credentials_and_spelling() {
        let expected = "github.com/acme/payments";
        for url in [
            "https://github.com/acme/payments.git",
            concat!("https://ci-bot:gh", "p_secret123@github.com/acme/payments"),
            "git@github.com:acme/payments.git",
            "ssh://git@GitHub.com/acme/payments/",
            "ssh://git@github.com:22/acme/payments.git",
        ] {
            assert_eq!(normalize_git_url(url), expected, "{url}");
        }
        assert_eq!(
            normalize_git_url("https://github.com/acme/pkg@v1"),
            "github.com/acme/pkg@v1",
            "an @ in the path is not a credential"
        );
    }

    #[test]
    fn the_identity_is_the_same_for_every_checkout() {
        let a = tempfile::tempdir().unwrap();
        let b = tempfile::tempdir().unwrap();
        for (dir, url) in [
            (a.path(), "https://user:token@github.com/acme/payments.git"),
            (b.path(), "git@github.com:acme/payments.git"),
        ] {
            std::fs::create_dir_all(dir.join(".git")).unwrap();
            std::fs::write(
                dir.join(".git/config"),
                format!("[remote \"origin\"]\n\turl = {url}\n"),
            )
            .unwrap();
        }
        let ia = project_identity(a.path()).unwrap();
        assert_eq!(ia, project_identity(b.path()).unwrap());
        assert!(!ia.contains("token") && !ia.contains("user"));
        let (stable, request) = resolve_request(a.path(), "salt_1", &[0x0a; 32], false).unwrap();
        assert_eq!(stable, stable_identity("git:github.com/acme/payments"));
        assert!(request.validate().is_ok());
        assert!(request.label.is_none());
    }

    #[test]
    fn a_linked_worktree_finds_the_vault_of_its_main_checkout() {
        let base = tempfile::tempdir().unwrap();
        let (main, wt) = super::super::link::worktree_layout(base.path());
        let other = base.path().join("other");
        std::fs::create_dir_all(&other).unwrap();
        let mut map = VaultMap::default();
        map.vaults.insert(
            "s1".into(),
            VaultRecord {
                vault_id: "v1".into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec![main.to_string_lossy().into_owned()],
            },
        );
        let found = |root: &Path| {
            map.for_root(&root.to_string_lossy())
                .map(|r| r.vault_id.clone())
        };
        assert_eq!(found(&main).as_deref(), Some("v1"));
        assert_eq!(found(&wt).as_deref(), Some("v1"), "the worktree");
        assert_eq!(found(&other), None, "an unrelated directory");
    }

    /// `ProjectMap`/`ProjectRecord` of the engine before the VA rename.
    #[derive(Deserialize)]
    struct PreVaMap {
        #[allow(dead_code)]
        projects: BTreeMap<String, PreVaRecord>,
    }
    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct PreVaRecord {
        project_id: String,
        ns: String,
        name: String,
        sealed: bool,
        #[serde(default)]
        roots: Vec<String>,
    }

    #[test]
    fn the_vault_map_stays_in_projects_json_with_pre_va_names() {
        let vault_id = "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42";
        let old = format!(
            r#"{{"projects":{{"s1":{{"project_id":"{vault_id}","ns":"acme","name":"payments","sealed":true,"roots":["/w/payments"]}}}}}}"#
        );
        let map: VaultMap =
            assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "project_id", "vault_id");
        assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "projects", "vaults");
        let record = &map.vaults["s1"];
        assert_eq!((record.vault_id.as_str(), record.sealed), (vault_id, true));

        let data = tempfile::tempdir().unwrap();
        std::fs::write(data.path().join("projects.json"), &old).unwrap();
        let loaded = VaultMap::load(data.path());
        assert_eq!(loaded, map);
        loaded.save(data.path()).unwrap();
        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
        serde_json::from_str::<PreVaMap>(&text).expect("an engine before the rename reads it");
        assert!(!data.path().join("vaults.json").exists());
    }
}