Skip to main content

lean_ctx_cloud/
identity_v2.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Project identity v2 (CHECKLIST 2.1.2, design
3//! `ee/delivery/cloud-v5-project-mapping.md`): the same repository has the
4//! same identity on every device, built from the committed `.lean-ctx-id`,
5//! the normalized origin remote and the root commit. Never the local path.
6//!
7//! Local only. Cloud sees each candidate as an org-salted digest
8//! ([`super::vault::identity_digest`]), like the v1 identity today. The
9//! identity is a signal for finding the vault, never an authorization:
10//! Cloud checks membership and vault rights.
11//!
12//! [`super::mapping`] sends them to `POST /v1/vaults/match` when the Cloud
13//! offers it; resolve keeps the v1 identity.
14
15use std::path::Path;
16use std::process::Command;
17
18use sha2::{Digest as _, Sha256};
19
20use super::vault::{normalize_git_url, project_identity};
21use lean_ctx_protocol::cloud::vault::stable_identity;
22
23/// Domain of the v2 canonical text (v1: `REPO_IDENTITY_DOMAIN`).
24pub const REPO_IDENTITY_V2_DOMAIN: &str = "leanctx.project-identity.v2\n";
25const IDENTITY_FILE: &str = ".lean-ctx-id";
26/// The longest `.lean-ctx-id` that counts (as `project_hash` reads it).
27const MAX_ID_CHARS: usize = 256;
28
29/// The parts of a v2 identity, each optional.
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct IdentityParts {
32    /// `.lean-ctx-id` at the checkout root, trimmed.
33    pub id: Option<String>,
34    /// The origin remote, normalized (no scheme, credentials, `.git`).
35    pub remote: Option<String>,
36    /// The smallest root commit of `HEAD`; `None` in a shallow clone.
37    pub root: Option<String>,
38}
39
40impl IdentityParts {
41    /// `leanctx.project-identity.v2\n` + `id:…\n` `remote:…\n` `root:…\n`
42    /// in this order, absent parts left out. `None` when every part is
43    /// absent or one holds a line break (the text would be ambiguous).
44    pub fn canonical_text(&self) -> Option<String> {
45        let parts = [
46            ("id", &self.id),
47            ("remote", &self.remote),
48            ("root", &self.root),
49        ];
50        if parts.iter().all(|(_, v)| v.is_none()) {
51            return None;
52        }
53        let mut text = String::from(REPO_IDENTITY_V2_DOMAIN);
54        for (key, value) in parts {
55            if let Some(value) = value {
56                if value.is_empty() || value.contains(['\n', '\r']) {
57                    return None;
58                }
59                text.push_str(key);
60                text.push(':');
61                text.push_str(value);
62                text.push('\n');
63            }
64        }
65        Some(text)
66    }
67
68    /// `sha256_hex(canonical_text)`.
69    pub fn stable(&self) -> Option<String> {
70        self.canonical_text()
71            .map(|text| hex::encode(Sha256::digest(text.as_bytes())))
72    }
73}
74
75/// How strongly a candidate names the repository.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum CandidateKind {
78    /// Every part this checkout has. A hit maps automatically.
79    Exact,
80    /// The v1 identity of engines before v5. A hit maps automatically,
81    /// because that is how those engines bound the vault.
82    Legacy,
83    /// The root commit alone, finds a moved remote. Forks share it, so a
84    /// hit is only a suggestion the person confirms.
85    History,
86}
87
88impl CandidateKind {
89    /// The `kind` of a match candidate on the wire.
90    pub fn as_str(self) -> &'static str {
91        match self {
92            Self::Exact => "exact",
93            Self::Legacy => "legacy",
94            Self::History => "history",
95        }
96    }
97}
98
99/// One stable identity to look up, before the org salt is applied.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Candidate {
102    pub kind: CandidateKind,
103    pub stable: String,
104}
105
106/// The candidates for the checkout at `root`, strongest first, without
107/// duplicates. Empty when the checkout has no identity at all.
108pub fn candidates(root: &Path) -> Vec<Candidate> {
109    candidates_from(&read_parts(root), project_identity(root).as_deref())
110}
111
112/// [`candidates`] from parts already read; `legacy` is the v1 identity.
113pub fn candidates_from(parts: &IdentityParts, legacy: Option<&str>) -> Vec<Candidate> {
114    let mut out: Vec<Candidate> = Vec::new();
115    let mut push = |kind, stable: Option<String>| {
116        if let Some(stable) = stable
117            && !out.iter().any(|c| c.stable == stable)
118        {
119            out.push(Candidate { kind, stable });
120        }
121    };
122    push(CandidateKind::Exact, parts.stable());
123    push(CandidateKind::Legacy, legacy.map(stable_identity));
124    if parts.remote.is_some() && parts.root.is_some() {
125        let history = IdentityParts {
126            root: parts.root.clone(),
127            ..IdentityParts::default()
128        };
129        push(CandidateKind::History, history.stable());
130    }
131    out
132}
133
134/// Whether the v1 identity is only a manifest name (`cargo:demo`,
135/// `npm:…`, …): no git remote and no identity file. Unrelated projects
136/// share such names across a workspace.
137pub fn weak_legacy(legacy: &str) -> bool {
138    !(legacy.starts_with("git:") || legacy.starts_with("explicit:"))
139}
140
141/// The candidates of the checkout at `root` that go to `POST
142/// /v1/vaults/match`: [`candidates`], without the legacy candidate when it
143/// is a [`weak_legacy`] manifest name and an exact candidate exists. A
144/// legacy hit maps automatically, so a crate name another project shares
145/// must not outrank this checkout's own identity; with no exact candidate
146/// the weak one is all there is and Cloud only suggests from it.
147pub fn match_candidates(root: &Path) -> Vec<Candidate> {
148    let legacy = project_identity(root);
149    sendable(
150        candidates_from(&read_parts(root), legacy.as_deref()),
151        legacy.as_deref(),
152    )
153}
154
155/// [`match_candidates`] from candidates already computed.
156pub fn sendable(mut candidates: Vec<Candidate>, legacy: Option<&str>) -> Vec<Candidate> {
157    if legacy.is_some_and(weak_legacy) && candidates.iter().any(|c| c.kind == CandidateKind::Exact)
158    {
159        candidates.retain(|c| c.kind != CandidateKind::Legacy);
160    }
161    candidates
162}
163
164/// Read the parts of the checkout at `root`. A linked worktree reads the
165/// remote and the commits of its repository (`git -C` follows `.git`).
166pub fn read_parts(root: &Path) -> IdentityParts {
167    let remote = origin_remote(root);
168    // A `.lean-ctx-id` an earlier `cloud link` wrote next to an origin is
169    // per checkout, not per repository: left out, like the v1 identity
170    // leaves it out ([`super::vault::project_identity`]).
171    let id = read_id_file(root).filter(|id| remote.is_none() || !super::vault::link_made_id(id));
172    IdentityParts {
173        id,
174        remote,
175        root: root_commit(root),
176    }
177}
178
179/// The origin remote of the checkout at `root`, normalized (no scheme,
180/// credentials or `.git`). Stays on this machine.
181pub fn origin_remote(root: &Path) -> Option<String> {
182    git(root, &["config", "--get", "remote.origin.url"]).and_then(|url| remote_part(&url))
183}
184
185/// The `remote` part of a remote URL; `None` when nothing is left.
186pub fn remote_part(url: &str) -> Option<String> {
187    Some(normalize_git_url(url)).filter(|url| !url.is_empty())
188}
189
190/// The `root` part: the smallest of `commits` that are 40 or 64 hex
191/// characters, lowercased; `None` for a shallow clone.
192pub fn root_part<'a>(commits: impl IntoIterator<Item = &'a str>, shallow: bool) -> Option<String> {
193    if shallow {
194        return None;
195    }
196    commits
197        .into_iter()
198        .map(str::trim)
199        .filter(|sha| matches!(sha.len(), 40 | 64) && sha.bytes().all(|b| b.is_ascii_hexdigit()))
200        .map(str::to_ascii_lowercase)
201        .min()
202}
203
204fn read_id_file(root: &Path) -> Option<String> {
205    let text = std::fs::read_to_string(root.join(IDENTITY_FILE)).ok()?;
206    let id = text.trim();
207    (!id.is_empty() && id.chars().count() <= MAX_ID_CHARS).then(|| id.to_string())
208}
209
210/// The smallest root commit of `HEAD`; `None` for a shallow clone, whose
211/// oldest commits depend on the fetch depth, and without git or commits.
212fn root_commit(root: &Path) -> Option<String> {
213    if git(root, &["rev-parse", "--is-shallow-repository"]).as_deref() != Some("false") {
214        return None;
215    }
216    let roots = git(root, &["rev-list", "--max-parents=0", "HEAD"])?;
217    root_part(roots.lines(), false)
218}
219
220pub fn git(root: &Path, args: &[&str]) -> Option<String> {
221    let out = Command::new("git")
222        .arg("-C")
223        .arg(root)
224        .args(args)
225        .env("GIT_TERMINAL_PROMPT", "0")
226        .stdin(std::process::Stdio::null())
227        .stderr(std::process::Stdio::null())
228        .output()
229        .ok()?;
230    out.status
231        .success()
232        .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
233}
234
235/// C0 `vectors/identity_v2.vectors.json` (the engine's byte-equal copy).
236#[cfg(test)]
237pub(crate) fn contract_vectors() -> serde_json::Value {
238    let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
239        .join("crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/identity_v2.vectors.json");
240    serde_json::from_slice(&std::fs::read(path).expect("identity_v2 vectors")).expect("json")
241}
242
243/// The parts a vector's `input` names.
244#[cfg(test)]
245pub(crate) fn vector_parts(input: &serde_json::Value) -> IdentityParts {
246    IdentityParts {
247        id: input["id"].as_str().map(str::to_string),
248        remote: input["remote_url"].as_str().and_then(remote_part),
249        root: root_part(
250            input["root_commits"]
251                .as_array()
252                .expect("root_commits")
253                .iter()
254                .filter_map(serde_json::Value::as_str),
255            input["shallow"].as_bool().expect("shallow"),
256        ),
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    /// Engines of every version and the server agree on the candidates:
265    /// each case of the C0 vectors, part by part.
266    #[test]
267    fn candidates_match_the_contract_vectors() {
268        use base64::Engine as _;
269        let vectors = contract_vectors();
270        let salt = base64::engine::general_purpose::STANDARD
271            .decode(vectors["salt"].as_str().unwrap())
272            .unwrap();
273        let cases = vectors["cases"].as_array().unwrap();
274        assert!(cases.len() >= 9);
275        for case in cases {
276            let (input, output) = (&case["input"], &case["output"]);
277            let name = case["name"].as_str().unwrap();
278            let parts = vector_parts(input);
279            assert_eq!(parts.remote.as_deref(), output["remote"].as_str(), "{name}");
280            assert_eq!(parts.root.as_deref(), output["root"].as_str(), "{name}");
281            assert_eq!(
282                parts.canonical_text().as_deref(),
283                output["canonical_text"].as_str(),
284                "{name}"
285            );
286            assert_eq!(
287                parts.stable().as_deref(),
288                output["stable_v2"].as_str(),
289                "{name}"
290            );
291            let got: Vec<serde_json::Value> =
292                candidates_from(&parts, input["legacy_identity"].as_str())
293                    .iter()
294                    .map(|c| {
295                        serde_json::json!({
296                            "kind": c.kind.as_str(),
297                            "stable": c.stable,
298                            "digest": super::super::vault::identity_digest(&salt, &c.stable),
299                        })
300                    })
301                    .collect();
302            assert_eq!(
303                serde_json::Value::Array(got),
304                output["candidates"],
305                "{name}"
306            );
307        }
308    }
309
310    /// The match request leaves a weak legacy candidate (a manifest name)
311    /// out next to an exact one; strong legacy identities (git remote,
312    /// identity file) and a weak one standing alone are still sent.
313    #[test]
314    fn a_weak_legacy_name_is_not_sent_next_to_an_exact_candidate() {
315        let vectors = contract_vectors();
316        let mut checked = 0;
317        for case in vectors["cases"].as_array().unwrap() {
318            let input = &case["input"];
319            let legacy = input["legacy_identity"].as_str();
320            let all = candidates_from(&vector_parts(input), legacy);
321            let has_exact = all.iter().any(|c| c.kind == CandidateKind::Exact);
322            let sent: Vec<&str> = sendable(all.clone(), legacy)
323                .iter()
324                .map(|c| c.kind.as_str())
325                .collect();
326            let expected: Vec<&str> = all
327                .iter()
328                .map(|c| c.kind.as_str())
329                .filter(|k| !(*k == "legacy" && has_exact && legacy.is_some_and(weak_legacy)))
330                .collect();
331            assert_eq!(sent, expected, "{}", case["name"]);
332            if legacy == Some("cargo:demo") {
333                checked += 1;
334                assert_eq!(
335                    sent,
336                    if has_exact {
337                        vec!["exact"]
338                    } else {
339                        vec!["legacy"]
340                    },
341                    "{}",
342                    case["name"]
343                );
344            }
345        }
346        assert_eq!(checked, 2, "both manifest-name vector cases are covered");
347        assert!(!weak_legacy("git:github.com/acme/payments"));
348        assert!(!weak_legacy("explicit:3f6c1e9a0b7d4c2e"));
349        assert!(weak_legacy("npm:demo"));
350
351        // A real checkout: a crate in a local repository without origin.
352        let base = tempfile::tempdir().unwrap();
353        let dir = base.path().join("demo");
354        std::fs::create_dir_all(&dir).unwrap();
355        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"demo\"\n").unwrap();
356        git_ok(&dir, &["init", "-q", "-b", "main"]);
357        git_ok(&dir, &["add", "."]);
358        git_ok(&dir, &["commit", "-q", "-m", "init"]);
359        let kinds: Vec<CandidateKind> = match_candidates(&dir).iter().map(|c| c.kind).collect();
360        assert_eq!(kinds, [CandidateKind::Exact]);
361        assert!(
362            candidates(&dir)
363                .iter()
364                .any(|c| c.kind == CandidateKind::Legacy),
365            "the contract candidates keep it"
366        );
367    }
368
369    fn git_ok(dir: &Path, args: &[&str]) -> String {
370        let out = Command::new("git")
371            .arg("-C")
372            .arg(dir)
373            .args(args)
374            .env("GIT_AUTHOR_NAME", "t")
375            .env("GIT_AUTHOR_EMAIL", "t@example.com")
376            .env("GIT_COMMITTER_NAME", "t")
377            .env("GIT_COMMITTER_EMAIL", "t@example.com")
378            .env("GIT_CONFIG_GLOBAL", "/dev/null")
379            .env("GIT_CONFIG_NOSYSTEM", "1")
380            .output()
381            .expect("git");
382        assert!(out.status.success(), "git {args:?}: {out:?}");
383        String::from_utf8_lossy(&out.stdout).trim().to_string()
384    }
385
386    /// A repository whose first commit holds `name`, so two of them never
387    /// share a root commit.
388    fn repo_with_remote(base: &Path, name: &str, url: &str) -> std::path::PathBuf {
389        let dir = base.join(name);
390        std::fs::create_dir_all(&dir).unwrap();
391        git_ok(&dir, &["init", "-q", "-b", "main"]);
392        std::fs::write(dir.join("README"), format!("{name}\n")).unwrap();
393        git_ok(&dir, &["add", "."]);
394        git_ok(&dir, &["commit", "-q", "-m", "init"]);
395        git_ok(&dir, &["remote", "add", "origin", url]);
396        dir
397    }
398
399    #[test]
400    fn the_canonical_text_is_fixed_and_rejects_ambiguous_parts() {
401        let parts = IdentityParts {
402            id: None,
403            remote: Some("github.com/acme/payments".into()),
404            root: Some("a".repeat(40)),
405        };
406        assert_eq!(
407            parts.canonical_text().unwrap(),
408            format!(
409                "leanctx.project-identity.v2\nremote:github.com/acme/payments\nroot:{}\n",
410                "a".repeat(40)
411            )
412        );
413        assert_eq!(parts.stable().unwrap().len(), 64);
414        assert!(IdentityParts::default().canonical_text().is_none());
415        let broken = IdentityParts {
416            id: Some("x\nroot:evil".into()),
417            ..IdentityParts::default()
418        };
419        assert!(
420            broken.canonical_text().is_none(),
421            "a line break would forge a part"
422        );
423        let v1 = stable_identity("git:github.com/acme/payments");
424        let remote_only = IdentityParts {
425            remote: Some("github.com/acme/payments".into()),
426            ..IdentityParts::default()
427        };
428        assert_ne!(remote_only.stable().unwrap(), v1, "v2 is domain separated");
429    }
430
431    #[test]
432    fn clones_with_different_remote_spellings_share_the_exact_identity() {
433        let base = tempfile::tempdir().unwrap();
434        let a = repo_with_remote(base.path(), "a", "git@github.com:acme/payments.git");
435        let b = base.path().join("b");
436        git_ok(
437            base.path(),
438            &["clone", "-q", a.to_str().unwrap(), b.to_str().unwrap()],
439        );
440        git_ok(
441            &b,
442            &[
443                "remote",
444                "set-url",
445                "origin",
446                "https://github.com/acme/payments",
447            ],
448        );
449        let (pa, pb) = (read_parts(&a), read_parts(&b));
450        assert_eq!(pa.remote.as_deref(), Some("github.com/acme/payments"));
451        assert!(pa.root.is_some());
452        assert_eq!(pa, pb);
453        let (ca, cb) = (candidates(&a), candidates(&b));
454        assert_eq!(ca, cb);
455        assert_eq!(ca[0].kind, CandidateKind::Exact);
456        assert!(!ca[0].stable.contains("acme"), "no remote text, a hash");
457
458        // Same remote, other history (a recreated repo): another identity,
459        // only the legacy v1 candidate agrees.
460        let c = repo_with_remote(base.path(), "c", "git@github.com:acme/payments.git");
461        let cc = candidates(&c);
462        assert_ne!(cc[0].stable, ca[0].stable);
463        let legacy = |cs: &[Candidate]| {
464            cs.iter()
465                .find(|c| c.kind == CandidateKind::Legacy)
466                .map(|c| c.stable.clone())
467        };
468        assert_eq!(legacy(&cc), legacy(&ca));
469    }
470
471    #[test]
472    fn a_moved_remote_keeps_the_history_candidate_and_a_worktree_reads_its_repo() {
473        let base = tempfile::tempdir().unwrap();
474        let a = repo_with_remote(base.path(), "a", "git@github.com:acme/payments.git");
475        let before = candidates(&a);
476        let wt = base.path().join("wt");
477        git_ok(&a, &["worktree", "add", "-q", wt.to_str().unwrap()]);
478        assert_eq!(read_parts(&wt), read_parts(&a), "a linked worktree");
479
480        git_ok(
481            &a,
482            &[
483                "remote",
484                "set-url",
485                "origin",
486                "git@gitlab.example.com:acme/payments.git",
487            ],
488        );
489        let after = candidates(&a);
490        let history = |cs: &[Candidate]| {
491            cs.iter()
492                .find(|c| c.kind == CandidateKind::History)
493                .map(|c| c.stable.clone())
494        };
495        assert_ne!(after[0].stable, before[0].stable);
496        assert!(history(&after).is_some());
497        assert_eq!(history(&after), history(&before));
498    }
499
500    #[test]
501    fn a_shallow_clone_has_no_root_and_a_plain_folder_only_its_v1_identity() {
502        let base = tempfile::tempdir().unwrap();
503        let a = repo_with_remote(base.path(), "a", "git@github.com:acme/payments.git");
504        std::fs::write(a.join("README"), "two\n").unwrap();
505        git_ok(&a, &["commit", "-q", "-am", "two"]);
506        let shallow = base.path().join("shallow");
507        git_ok(
508            base.path(),
509            &[
510                "clone",
511                "-q",
512                "--depth",
513                "1",
514                &format!("file://{}", a.display()),
515                shallow.to_str().unwrap(),
516            ],
517        );
518        assert!(read_parts(&shallow).root.is_none());
519
520        let plain = base.path().join("plain");
521        std::fs::create_dir_all(&plain).unwrap();
522        std::fs::write(plain.join("Cargo.toml"), "[package]\nname = \"demo\"\n").unwrap();
523        let cs = candidates(&plain);
524        assert_eq!(cs.len(), 1);
525        assert_eq!(
526            cs[0].kind,
527            CandidateKind::Legacy,
528            "weak: never auto-created"
529        );
530
531        std::fs::write(plain.join(IDENTITY_FILE), "3f6c1e9a0b7d4c2e\n").unwrap();
532        let with_id = candidates(&plain);
533        assert_eq!(with_id[0].kind, CandidateKind::Exact);
534        assert_eq!(read_parts(&plain).id.as_deref(), Some("3f6c1e9a0b7d4c2e"));
535        assert!(candidates(&base.path().join("missing")).is_empty());
536    }
537}