Skip to main content

lean_ctx_cloud/
link.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx cloud link <workspace>/<vault>[@<server>]`: link a git
3//! repository to a vault.
4//!
5//! Writes `.lean-ctx-cloud.json` at the repository root, next to
6//! `.lean-ctx-id`. A hosted vault keeps link v1 (`{"schema", "repo": {"ns",
7//! "name"}}`), which every engine in the team reads; a self-hosted one needs
8//! link v2 (`{"schema": "leanctx.cloud.link/v2", "vault": "<address>"}`, C0
9//! 2.0 `link.schema.json`). Both are read; v1 is a hosted address.
10//! Resolution sends the vault on first sight; Cloud binds it when this
11//! instance may contribute there. A repository without any identity marker
12//! gets a random `.lean-ctx-id` so its identity survives moves; one with a
13//! git origin never does (the origin is the identity of every checkout,
14//! [`super::vault::project_identity`]).
15
16use std::path::{Path, PathBuf};
17
18use serde::{Deserialize, Serialize};
19
20use super::CloudError;
21use super::vault_address::VaultAddress;
22use lean_ctx_protocol::cloud::vault::VaultRefV1;
23
24/// The one name of the link file. Every released Instance (3.12.0 on)
25/// writes it under this name; the Atlas-era name was dropped without an
26/// alias (owner: Cloud starts fresh), so there is no second name to read.
27pub const LINK_FILE: &str = ".lean-ctx-cloud.json";
28
29/// True when `root` holds a link file.
30pub fn has_link_file(root: &Path) -> bool {
31    root.join(LINK_FILE).exists()
32}
33pub const LINK_SCHEMA: &str = "leanctx.cloud.link/v1";
34pub const LINK_SCHEMA_V2: &str = "leanctx.cloud.link/v2";
35const IDENTITY_FILE: &str = ".lean-ctx-id";
36
37/// A link as read: the vault plus, for a self-hosted one, its server.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct VaultLink {
40    pub schema: String,
41    pub vault: VaultRefV1,
42    /// Self-hosted server (`host[:port]`); `None` = hosted Cloud.
43    pub server: Option<String>,
44}
45
46impl VaultLink {
47    /// The vault address `<ws>/<vault>[@<server>]`.
48    pub fn address(&self) -> VaultAddress {
49        VaultAddress {
50            ws: self.vault.ns.clone(),
51            vault: self.vault.name.clone(),
52            server: self.server.clone(),
53        }
54    }
55
56    /// True when this link names the Cloud at `origin`.
57    pub fn is_for(&self, origin: &str) -> bool {
58        lean_ctx_protocol::cloud::same_cloud_origin(&self.address().origin(), origin)
59    }
60}
61
62/// Link v1 on disk.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65struct LinkV1 {
66    schema: String,
67    /// On disk as `repo` (pre-VA name): the file is committed, and engines
68    /// before the rename (they refuse unknown fields) read it in the same
69    /// team.
70    #[serde(rename = "repo", alias = "vault")]
71    vault: VaultRefV1,
72}
73
74/// Link v2 on disk.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77struct LinkV2 {
78    schema: String,
79    vault: String,
80}
81
82/// What `link` did.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct LinkOutcome {
85    pub file: PathBuf,
86    /// A `.lean-ctx-id` had to be created.
87    pub created_identity: bool,
88}
89
90/// The link of the project at `root`, if any. A linked git worktree without
91/// its own link file uses the one of its main checkout: the same repository
92/// (one git dir, one remote), so the same vault.
93pub fn read_link(root: &Path) -> Result<Option<VaultLink>, CloudError> {
94    if let Some(link) = read_link_file(root)? {
95        return Ok(Some(link));
96    }
97    match main_worktree_root(root) {
98        Some(main) => read_link_file(&main),
99        None => Ok(None),
100    }
101}
102
103pub use lean_ctx::core::git_worktree::main_worktree_root;
104
105fn read_link_file(root: &Path) -> Result<Option<VaultLink>, CloudError> {
106    let path = root.join(LINK_FILE);
107    match std::fs::read_to_string(&path) {
108        Ok(text) => parse(&path, &text).map(Some),
109        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
110        Err(e) => Err(CloudError::Local(format!("read {}: {e}", path.display()))),
111    }
112}
113
114fn parse(path: &Path, text: &str) -> Result<VaultLink, CloudError> {
115    parse_link(text).map_err(|why| CloudError::Local(format!("{} {why}", path.display())))
116}
117
118/// Link v1 or v2 text → the link, or why it is refused.
119fn parse_link(text: &str) -> Result<VaultLink, String> {
120    let value: serde_json::Value =
121        serde_json::from_str(text).map_err(|e| format!("is damaged: {e}"))?;
122    match value["schema"].as_str() {
123        Some(LINK_SCHEMA) => {
124            let link: LinkV1 =
125                serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
126            link.vault.validate().map_err(|e| format!(": {e}"))?;
127            Ok(VaultLink {
128                schema: link.schema,
129                vault: link.vault,
130                server: None,
131            })
132        }
133        Some(LINK_SCHEMA_V2) => {
134            let link: LinkV2 =
135                serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
136            let address = VaultAddress::parse(&link.vault).map_err(|e| format!(": {e}"))?;
137            let vault = VaultRefV1 {
138                ns: address.ws,
139                name: address.vault,
140            };
141            vault.validate().map_err(|e| format!(": {e}"))?;
142            Ok(VaultLink {
143                schema: link.schema,
144                vault,
145                server: address.server,
146            })
147        }
148        _ => Err("has an unknown schema".into()),
149    }
150}
151
152/// The file text of a link: v1 for a hosted vault, v2 for a self-hosted one.
153fn link_text(address: &VaultAddress) -> Result<String, CloudError> {
154    let value = if address.is_hosted() {
155        serde_json::to_value(LinkV1 {
156            schema: LINK_SCHEMA.into(),
157            vault: VaultRefV1 {
158                ns: address.ws.clone(),
159                name: address.vault.clone(),
160            },
161        })
162    } else {
163        serde_json::to_value(LinkV2 {
164            schema: LINK_SCHEMA_V2.into(),
165            vault: address.to_string(),
166        })
167    }
168    .map_err(|e| CloudError::Local(e.to_string()))?;
169    let mut text =
170        serde_json::to_string_pretty(&value).map_err(|e| CloudError::Local(e.to_string()))?;
171    text.push('\n');
172    Ok(text)
173}
174
175/// Link the repository at `root` to `vault` (`<workspace>/<vault>[@<server>]`).
176pub fn link(root: &Path, vault: &str) -> Result<LinkOutcome, CloudError> {
177    let address = VaultAddress::parse(vault).map_err(|e| CloudError::Config(e.to_string()))?;
178    VaultRefV1 {
179        ns: address.ws.clone(),
180        name: address.vault.clone(),
181    }
182    .validate()
183    .map_err(|e| CloudError::Config(e.to_string()))?;
184    let root_str = root.to_string_lossy();
185    let created_identity = lean_ctx::core::project_hash::project_identity(&root_str).is_none();
186    if created_identity {
187        let mut bytes = [0u8; 16];
188        getrandom::fill(&mut bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
189        write_file(
190            &root.join(IDENTITY_FILE),
191            format!("{}\n", hex::encode(bytes)).as_bytes(),
192        )?;
193    }
194    let text = link_text(&address)?;
195    let file = root.join(LINK_FILE);
196    write_file(&file, text.as_bytes())?;
197    Ok(LinkOutcome {
198        file,
199        created_identity,
200    })
201}
202
203/// Write `path` in a checkout someone else may have prepared: the bytes are
204/// staged in a fresh, never pre-existing temp file (create_new, random
205/// name) and renamed over `path`, so a planted symlink at the temp or the
206/// final name is replaced, never written through (RB8).
207fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CloudError> {
208    lean_ctx::core::atomic_fs::try_atomic_write(path, bytes, None)
209        .map_err(|e| CloudError::Local(format!("write {}: {e}", path.display())))
210}
211
212/// A main checkout and a linked worktree laid out as `git worktree add`
213/// writes them: `<main>/.git/worktrees/wt/{gitdir,commondir}` and
214/// `<wt>/.git` (a file).
215#[cfg(test)]
216pub(crate) fn worktree_layout(base: &Path) -> (PathBuf, PathBuf) {
217    let main = base.join("main");
218    let wt = base.join("wt");
219    let admin = main.join(".git").join("worktrees").join("wt");
220    std::fs::create_dir_all(&admin).unwrap();
221    std::fs::create_dir_all(&wt).unwrap();
222    std::fs::write(wt.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap();
223    std::fs::write(
224        admin.join("gitdir"),
225        format!("{}\n", wt.join(".git").display()),
226    )
227    .unwrap();
228    std::fs::write(admin.join("commondir"), "../..\n").unwrap();
229    (main, wt)
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    /// RB8: a cloned repo with planted symlinks at the files `link` writes
237    /// (or at their old temp names) never gets a file outside it changed.
238    #[cfg(unix)]
239    #[test]
240    fn link_never_writes_through_a_planted_symlink() {
241        let outside = tempfile::tempdir().unwrap();
242        let victim = outside.path().join("authorized_keys");
243        std::fs::write(&victim, "ssh-ed25519 KEEP\n").unwrap();
244        let repo = tempfile::tempdir().unwrap();
245        for name in [
246            LINK_FILE,
247            IDENTITY_FILE,
248            ".lean-ctx-cloud.tmp",
249            ".lean-ctx-id.tmp",
250        ] {
251            std::os::unix::fs::symlink(&victim, repo.path().join(name)).unwrap();
252        }
253        link(repo.path(), "acme/payments").unwrap();
254        assert_eq!(
255            std::fs::read_to_string(&victim).unwrap(),
256            "ssh-ed25519 KEEP\n"
257        );
258        let written = std::fs::symlink_metadata(repo.path().join(LINK_FILE)).unwrap();
259        assert!(written.is_file(), "the link file replaced the symlink");
260        assert!(read_link(repo.path()).unwrap().is_some());
261    }
262
263    #[test]
264    fn link_writes_the_repo_and_an_identity_when_missing() {
265        let dir = tempfile::tempdir().unwrap();
266        let outcome = link(dir.path(), "acme/payments").unwrap();
267        assert!(outcome.created_identity);
268        assert!(dir.path().join(IDENTITY_FILE).exists());
269        let link_back = read_link(dir.path()).unwrap().unwrap();
270        assert_eq!(
271            (link_back.vault.ns.as_str(), link_back.vault.name.as_str()),
272            ("acme", "payments")
273        );
274
275        let again = link(dir.path(), "acme/billing").unwrap();
276        assert!(!again.created_identity, "the identity is kept");
277        assert_eq!(
278            read_link(dir.path()).unwrap().unwrap().vault.name,
279            "billing"
280        );
281    }
282
283    /// Dogfood 5.11.: two checkouts of one origin, both linked, are one
284    /// repository. A git origin never gets a random id, and one an earlier
285    /// `cloud link` wrote gives way to the origin; without an origin the
286    /// random id stays the identity.
287    #[test]
288    fn two_linked_checkouts_of_one_origin_keep_one_identity() {
289        use crate::vault::project_identity;
290        let base = tempfile::tempdir().unwrap();
291        let checkout = |name: &str| {
292            let root = base.path().join(name);
293            std::fs::create_dir_all(&root).unwrap();
294            // A real repository: identity v2 asks git for the origin.
295            for args in [
296                &["init", "-q"][..],
297                &[
298                    "remote",
299                    "add",
300                    "origin",
301                    "git@github.com:yves/leanctx-cloud.git",
302                ][..],
303            ] {
304                let out = std::process::Command::new("git")
305                    .arg("-C")
306                    .arg(&root)
307                    .args(args)
308                    .env("GIT_CONFIG_GLOBAL", "/dev/null")
309                    .env("GIT_CONFIG_NOSYSTEM", "1")
310                    .output()
311                    .unwrap();
312                assert!(out.status.success(), "git {args:?}: {out:?}");
313            }
314            root
315        };
316        let (mac, pounce) = (checkout("mac"), checkout("pounce"));
317        assert!(!link(&mac, "yves/leanctx-cloud").unwrap().created_identity);
318        assert!(!mac.join(IDENTITY_FILE).exists(), "an origin needs no id");
319        // pounce still has the random id an earlier engine's link wrote.
320        std::fs::write(
321            pounce.join(IDENTITY_FILE),
322            "0dfac5e1b2c3d4e5f60718293a4b5c6d\n",
323        )
324        .unwrap();
325        assert!(
326            !link(&pounce, "yves/leanctx-cloud")
327                .unwrap()
328                .created_identity
329        );
330        let origin = Some("git:github.com/yves/leanctx-cloud".to_string());
331        assert_eq!(project_identity(&mac), origin);
332        assert_eq!(project_identity(&pounce), origin, "the random id gives way");
333        let parts = |root: &Path| crate::identity_v2::read_parts(root).stable();
334        assert_eq!(parts(&mac), parts(&pounce), "and in identity v2");
335
336        // A hand-written id is a deliberate name and stays the identity.
337        std::fs::write(pounce.join(IDENTITY_FILE), "billing-service\n").unwrap();
338        assert_eq!(
339            project_identity(&pounce).as_deref(),
340            Some("explicit:billing-service")
341        );
342
343        // Without an origin a random id is the only identity there is.
344        let bare = base.path().join("bare");
345        std::fs::create_dir_all(&bare).unwrap();
346        assert!(link(&bare, "yves/notes").unwrap().created_identity);
347        let id = std::fs::read_to_string(bare.join(IDENTITY_FILE)).unwrap();
348        assert!(crate::vault::link_made_id(id.trim()));
349        assert_eq!(
350            project_identity(&bare),
351            Some(format!("explicit:{}", id.trim()))
352        );
353    }
354
355    #[test]
356    fn projects_with_an_identity_get_no_new_id_file() {
357        let dir = tempfile::tempdir().unwrap();
358        std::fs::write(
359            dir.path().join("Cargo.toml"),
360            "[package]\nname = \"demo\"\n",
361        )
362        .unwrap();
363        assert!(!link(dir.path(), "acme/demo").unwrap().created_identity);
364        assert!(!dir.path().join(IDENTITY_FILE).exists());
365    }
366
367    /// `ProjectLink` of the engine before the VA rename.
368    #[derive(Deserialize)]
369    #[serde(deny_unknown_fields)]
370    #[allow(dead_code)]
371    struct PreVaLink {
372        schema: String,
373        repo: VaultRefV1,
374    }
375
376    #[test]
377    fn the_link_file_keeps_repo_so_older_engines_in_the_team_read_it() {
378        let old = r#"{"schema":"leanctx.cloud.link/v1","repo":{"ns":"acme","name":"payments"}}"#;
379        let read =
380            crate::vault::assert_pre_va_round_trip::<LinkV1, PreVaLink>(old, "repo", "vault");
381        assert_eq!(
382            (read.vault.ns.as_str(), read.vault.name.as_str()),
383            ("acme", "payments")
384        );
385
386        let dir = tempfile::tempdir().unwrap();
387        link(dir.path(), "acme/payments").unwrap();
388        let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
389        serde_json::from_str::<PreVaLink>(&text).expect("an engine before the rename reads it");
390        let back = read_link(dir.path()).unwrap().unwrap();
391        assert_eq!((back.vault, back.server), (read.vault, None));
392    }
393
394    #[test]
395    fn a_worktree_without_a_link_uses_the_main_checkouts() {
396        let base = tempfile::tempdir().unwrap();
397        let (main, wt) = worktree_layout(base.path());
398        assert_eq!(
399            main_worktree_root(&wt).unwrap(),
400            main.canonicalize().unwrap()
401        );
402        assert!(main_worktree_root(&main).is_none(), "the main checkout");
403        assert!(read_link(&wt).unwrap().is_none(), "nothing linked yet");
404
405        link(&main, "acme/payments").unwrap();
406        assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "payments");
407        // The worktree's own link wins.
408        link(&wt, "acme/billing").unwrap();
409        assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "billing");
410        // A damaged link of the main checkout is still refused.
411        std::fs::remove_file(wt.join(LINK_FILE)).unwrap();
412        std::fs::write(main.join(LINK_FILE), "{").unwrap();
413        assert!(read_link(&wt).is_err());
414    }
415
416    #[test]
417    fn a_dot_git_file_that_git_does_not_back_is_not_followed() {
418        let base = tempfile::tempdir().unwrap();
419        let (main, wt) = worktree_layout(base.path());
420        link(&main, "acme/payments").unwrap();
421        // A second checkout claims the same worktree admin dir: its back
422        // pointer names the other checkout, so it gets nothing.
423        let impostor = base.path().join("impostor");
424        std::fs::create_dir_all(&impostor).unwrap();
425        std::fs::copy(wt.join(".git"), impostor.join(".git")).unwrap();
426        assert!(main_worktree_root(&impostor).is_none());
427        assert!(read_link(&impostor).unwrap().is_none());
428        // A bare common dir has no main checkout.
429        let admin = main.join(".git/worktrees/wt");
430        std::fs::write(admin.join("commondir"), "..\n").unwrap();
431        assert!(main_worktree_root(&wt).is_none());
432    }
433
434    #[test]
435    fn malformed_vault_names_are_refused() {
436        let dir = tempfile::tempdir().unwrap();
437        assert!(link(dir.path(), "payments").is_err());
438        assert!(link(dir.path(), "acme/../etc").is_err());
439        assert!(link(dir.path(), "acme/payments@localhost").is_err());
440    }
441
442    fn fixture(name: &str) -> String {
443        std::fs::read_to_string(format!(
444            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/{name}",
445            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
446        ))
447        .unwrap()
448    }
449
450    /// C0 2.0 `link/`: v2 carries the address, v1 is read as hosted, and
451    /// every invalid case is refused.
452    #[test]
453    fn link_files_match_the_contract_fixtures() {
454        let hosted = parse_link(&fixture("lean-ctx-cloud.hosted.json")).unwrap();
455        assert_eq!(hosted.address().to_string(), "acme/payments");
456        assert!(hosted.is_for("https://cloud.leanctx.com"));
457        assert!(hosted.is_for("https://cloud.leanctx.com/"));
458        let own = parse_link(&fixture("lean-ctx-cloud.self_hosted.json")).unwrap();
459        assert_eq!(own.server.as_deref(), Some("cloud.acme.example:8443"));
460        assert!(own.is_for("https://cloud.acme.example:8443/"));
461        assert!(!own.is_for("https://cloud.leanctx.com"));
462        let v1 = parse_link(&fixture("lean-ctx-cloud.v1.json")).unwrap();
463        assert_eq!((v1.vault, v1.server), (hosted.vault.clone(), None));
464        let dir = format!(
465            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/invalid",
466            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
467        );
468        let mut refused = 0;
469        for entry in std::fs::read_dir(dir).unwrap() {
470            let case: serde_json::Value =
471                serde_json::from_str(&std::fs::read_to_string(entry.unwrap().path()).unwrap())
472                    .unwrap();
473            let base = case["base"]
474                .as_str()
475                .unwrap()
476                .strip_prefix("link/")
477                .unwrap();
478            let mut doc: serde_json::Value = serde_json::from_str(&fixture(base)).unwrap();
479            for op in case["patch"].as_array().unwrap() {
480                assert_eq!(op["op"], "replace", "{case}");
481                *doc.pointer_mut(op["path"].as_str().unwrap()).unwrap() = op["value"].clone();
482            }
483            assert!(parse_link(&doc.to_string()).is_err(), "{case}");
484            refused += 1;
485        }
486        assert!(refused > 0);
487    }
488
489    #[test]
490    fn a_self_hosted_vault_is_written_as_link_v2() {
491        let dir = tempfile::tempdir().unwrap();
492        link(dir.path(), "acme/payments@Cloud.Acme.Example:8443").unwrap();
493        let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
494        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
495        assert_eq!(
496            value,
497            serde_json::json!({"schema": LINK_SCHEMA_V2, "vault": "acme/payments@cloud.acme.example:8443"})
498        );
499        link(dir.path(), "acme/payments@cloud.leanctx.com").unwrap();
500        let back = read_link(dir.path()).unwrap().unwrap();
501        assert_eq!((back.schema.as_str(), back.server), (LINK_SCHEMA, None));
502    }
503}