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
114/// The link file of `root` itself (no main-checkout fallback), for
115/// [`crate::unlink`].
116pub(crate) fn read_link_file_at(root: &Path) -> Result<Option<VaultLink>, CloudError> {
117    read_link_file(root)
118}
119
120fn parse(path: &Path, text: &str) -> Result<VaultLink, CloudError> {
121    parse_link(text).map_err(|why| CloudError::Local(format!("{} {why}", path.display())))
122}
123
124/// Link v1 or v2 text → the link, or why it is refused.
125fn parse_link(text: &str) -> Result<VaultLink, String> {
126    let value: serde_json::Value =
127        serde_json::from_str(text).map_err(|e| format!("is damaged: {e}"))?;
128    match value["schema"].as_str() {
129        Some(LINK_SCHEMA) => {
130            let link: LinkV1 =
131                serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
132            link.vault.validate().map_err(|e| format!(": {e}"))?;
133            Ok(VaultLink {
134                schema: link.schema,
135                vault: link.vault,
136                server: None,
137            })
138        }
139        Some(LINK_SCHEMA_V2) => {
140            let link: LinkV2 =
141                serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
142            let address = VaultAddress::parse(&link.vault).map_err(|e| format!(": {e}"))?;
143            let vault = VaultRefV1 {
144                ns: address.ws,
145                name: address.vault,
146            };
147            vault.validate().map_err(|e| format!(": {e}"))?;
148            Ok(VaultLink {
149                schema: link.schema,
150                vault,
151                server: address.server,
152            })
153        }
154        _ => Err("has an unknown schema".into()),
155    }
156}
157
158/// The file text of a link: v1 for a hosted vault, v2 for a self-hosted one.
159fn link_text(address: &VaultAddress) -> Result<String, CloudError> {
160    let value = if address.is_hosted() {
161        serde_json::to_value(LinkV1 {
162            schema: LINK_SCHEMA.into(),
163            vault: VaultRefV1 {
164                ns: address.ws.clone(),
165                name: address.vault.clone(),
166            },
167        })
168    } else {
169        serde_json::to_value(LinkV2 {
170            schema: LINK_SCHEMA_V2.into(),
171            vault: address.to_string(),
172        })
173    }
174    .map_err(|e| CloudError::Local(e.to_string()))?;
175    let mut text =
176        serde_json::to_string_pretty(&value).map_err(|e| CloudError::Local(e.to_string()))?;
177    text.push('\n');
178    Ok(text)
179}
180
181/// Link the repository at `root` to `vault` (`<workspace>/<vault>[@<server>]`).
182pub fn link(root: &Path, vault: &str) -> Result<LinkOutcome, CloudError> {
183    let address = VaultAddress::parse(vault).map_err(|e| CloudError::Config(e.to_string()))?;
184    VaultRefV1 {
185        ns: address.ws.clone(),
186        name: address.vault.clone(),
187    }
188    .validate()
189    .map_err(|e| CloudError::Config(e.to_string()))?;
190    let root_str = root.to_string_lossy();
191    let created_identity = lean_ctx::core::project_hash::project_identity(&root_str).is_none();
192    if created_identity {
193        let mut bytes = [0u8; 16];
194        getrandom::fill(&mut bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
195        write_file(
196            &root.join(IDENTITY_FILE),
197            format!("{}\n", hex::encode(bytes)).as_bytes(),
198        )?;
199    }
200    let text = link_text(&address)?;
201    let file = root.join(LINK_FILE);
202    write_file(&file, text.as_bytes())?;
203    Ok(LinkOutcome {
204        file,
205        created_identity,
206    })
207}
208
209/// The bytes of `root`'s own link file for [`undo`], when it is a regular
210/// file (a planted symlink is never read through).
211pub fn prior_link(root: &Path) -> Option<Vec<u8>> {
212    let path = root.join(LINK_FILE);
213    let meta = std::fs::symlink_metadata(&path).ok()?;
214    if !meta.is_file() {
215        return None;
216    }
217    std::fs::read(&path).ok()
218}
219
220/// Undo a [`link`] whose vault Cloud refused (rc4-56): the link file gets
221/// back `prior` (its bytes before; `None`: there was none) and a
222/// `.lean-ctx-id` the link created is removed, so a refused link leaves
223/// the checkout as it was.
224pub fn undo(root: &Path, outcome: &LinkOutcome, prior: Option<&[u8]>) -> Result<(), CloudError> {
225    match prior {
226        Some(bytes) => write_file(&outcome.file, bytes)?,
227        None => remove_if_present(&outcome.file)?,
228    }
229    if outcome.created_identity {
230        remove_if_present(&root.join(IDENTITY_FILE))?;
231    }
232    Ok(())
233}
234
235fn remove_if_present(path: &Path) -> Result<(), CloudError> {
236    match std::fs::remove_file(path) {
237        Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
238            Err(CloudError::Local(format!("remove {}: {e}", path.display())))
239        }
240        _ => Ok(()),
241    }
242}
243
244/// Write `path` in a checkout someone else may have prepared: the bytes are
245/// staged in a fresh, never pre-existing temp file (create_new, random
246/// name) and renamed over `path`, so a planted symlink at the temp or the
247/// final name is replaced, never written through (RB8).
248fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CloudError> {
249    lean_ctx::core::atomic_fs::try_atomic_write(path, bytes, None)
250        .map_err(|e| CloudError::Local(format!("write {}: {e}", path.display())))
251}
252
253/// A main checkout and a linked worktree laid out as `git worktree add`
254/// writes them; the shared fixture [`crate::unlinked::fake_worktree`].
255#[cfg(test)]
256pub(crate) fn worktree_layout(base: &Path) -> (PathBuf, PathBuf) {
257    crate::unlinked::fake_worktree(base)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    /// RB8: a cloned repo with planted symlinks at the files `link` writes
265    /// (or at their old temp names) never gets a file outside it changed.
266    #[cfg(unix)]
267    #[test]
268    fn link_never_writes_through_a_planted_symlink() {
269        let outside = tempfile::tempdir().unwrap();
270        let victim = outside.path().join("authorized_keys");
271        std::fs::write(&victim, "ssh-ed25519 KEEP\n").unwrap();
272        let repo = tempfile::tempdir().unwrap();
273        for name in [
274            LINK_FILE,
275            IDENTITY_FILE,
276            ".lean-ctx-cloud.tmp",
277            ".lean-ctx-id.tmp",
278        ] {
279            std::os::unix::fs::symlink(&victim, repo.path().join(name)).unwrap();
280        }
281        link(repo.path(), "acme/payments").unwrap();
282        assert_eq!(
283            std::fs::read_to_string(&victim).unwrap(),
284            "ssh-ed25519 KEEP\n"
285        );
286        let written = std::fs::symlink_metadata(repo.path().join(LINK_FILE)).unwrap();
287        assert!(written.is_file(), "the link file replaced the symlink");
288        assert!(read_link(repo.path()).unwrap().is_some());
289    }
290
291    #[test]
292    fn link_writes_the_repo_and_an_identity_when_missing() {
293        let dir = tempfile::tempdir().unwrap();
294        let outcome = link(dir.path(), "acme/payments").unwrap();
295        assert!(outcome.created_identity);
296        assert!(dir.path().join(IDENTITY_FILE).exists());
297        let link_back = read_link(dir.path()).unwrap().unwrap();
298        assert_eq!(
299            (link_back.vault.ns.as_str(), link_back.vault.name.as_str()),
300            ("acme", "payments")
301        );
302
303        let again = link(dir.path(), "acme/billing").unwrap();
304        assert!(!again.created_identity, "the identity is kept");
305        assert_eq!(
306            read_link(dir.path()).unwrap().unwrap().vault.name,
307            "billing"
308        );
309    }
310
311    /// Dogfood 5.11.: two checkouts of one origin, both linked, are one
312    /// repository. A git origin never gets a random id, and one an earlier
313    /// `cloud link` wrote gives way to the origin; without an origin the
314    /// random id stays the identity.
315    #[test]
316    fn two_linked_checkouts_of_one_origin_keep_one_identity() {
317        use crate::vault::project_identity;
318        let base = tempfile::tempdir().unwrap();
319        let checkout = |name: &str| {
320            let root = base.path().join(name);
321            std::fs::create_dir_all(&root).unwrap();
322            // A real repository: identity v2 asks git for the origin.
323            for args in [
324                &["init", "-q"][..],
325                &[
326                    "remote",
327                    "add",
328                    "origin",
329                    "git@github.com:yves/leanctx-cloud.git",
330                ][..],
331            ] {
332                let out = std::process::Command::new("git")
333                    .arg("-C")
334                    .arg(&root)
335                    .args(args)
336                    .env("GIT_CONFIG_GLOBAL", "/dev/null")
337                    .env("GIT_CONFIG_NOSYSTEM", "1")
338                    .output()
339                    .unwrap();
340                assert!(out.status.success(), "git {args:?}: {out:?}");
341            }
342            root
343        };
344        let (mac, pounce) = (checkout("mac"), checkout("pounce"));
345        assert!(!link(&mac, "yves/leanctx-cloud").unwrap().created_identity);
346        assert!(!mac.join(IDENTITY_FILE).exists(), "an origin needs no id");
347        // pounce still has the random id an earlier engine's link wrote.
348        std::fs::write(
349            pounce.join(IDENTITY_FILE),
350            "0dfac5e1b2c3d4e5f60718293a4b5c6d\n",
351        )
352        .unwrap();
353        assert!(
354            !link(&pounce, "yves/leanctx-cloud")
355                .unwrap()
356                .created_identity
357        );
358        let origin = Some("git:github.com/yves/leanctx-cloud".to_string());
359        assert_eq!(project_identity(&mac), origin);
360        assert_eq!(project_identity(&pounce), origin, "the random id gives way");
361        let parts = |root: &Path| crate::identity_v2::read_parts(root).stable();
362        assert_eq!(parts(&mac), parts(&pounce), "and in identity v2");
363
364        // A hand-written id is a deliberate name and stays the identity.
365        std::fs::write(pounce.join(IDENTITY_FILE), "billing-service\n").unwrap();
366        assert_eq!(
367            project_identity(&pounce).as_deref(),
368            Some("explicit:billing-service")
369        );
370
371        // Without an origin a random id is the only identity there is.
372        let bare = base.path().join("bare");
373        std::fs::create_dir_all(&bare).unwrap();
374        assert!(link(&bare, "yves/notes").unwrap().created_identity);
375        let id = std::fs::read_to_string(bare.join(IDENTITY_FILE)).unwrap();
376        assert!(crate::vault::link_made_id(id.trim()));
377        assert_eq!(
378            project_identity(&bare),
379            Some(format!("explicit:{}", id.trim()))
380        );
381    }
382
383    #[test]
384    fn projects_with_an_identity_get_no_new_id_file() {
385        let dir = tempfile::tempdir().unwrap();
386        std::fs::write(
387            dir.path().join("Cargo.toml"),
388            "[package]\nname = \"demo\"\n",
389        )
390        .unwrap();
391        assert!(!link(dir.path(), "acme/demo").unwrap().created_identity);
392        assert!(!dir.path().join(IDENTITY_FILE).exists());
393    }
394
395    /// `ProjectLink` of the engine before the VA rename.
396    #[derive(Deserialize)]
397    #[serde(deny_unknown_fields)]
398    #[allow(dead_code)]
399    struct PreVaLink {
400        schema: String,
401        repo: VaultRefV1,
402    }
403
404    #[test]
405    fn the_link_file_keeps_repo_so_older_engines_in_the_team_read_it() {
406        let old = r#"{"schema":"leanctx.cloud.link/v1","repo":{"ns":"acme","name":"payments"}}"#;
407        let read =
408            crate::vault::assert_pre_va_round_trip::<LinkV1, PreVaLink>(old, "repo", "vault");
409        assert_eq!(
410            (read.vault.ns.as_str(), read.vault.name.as_str()),
411            ("acme", "payments")
412        );
413
414        let dir = tempfile::tempdir().unwrap();
415        link(dir.path(), "acme/payments").unwrap();
416        let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
417        serde_json::from_str::<PreVaLink>(&text).expect("an engine before the rename reads it");
418        let back = read_link(dir.path()).unwrap().unwrap();
419        assert_eq!((back.vault, back.server), (read.vault, None));
420    }
421
422    #[test]
423    fn a_worktree_without_a_link_uses_the_main_checkouts() {
424        let base = tempfile::tempdir().unwrap();
425        let (main, wt) = worktree_layout(base.path());
426        assert_eq!(
427            main_worktree_root(&wt).unwrap(),
428            main.canonicalize().unwrap()
429        );
430        assert!(main_worktree_root(&main).is_none(), "the main checkout");
431        assert!(read_link(&wt).unwrap().is_none(), "nothing linked yet");
432
433        link(&main, "acme/payments").unwrap();
434        assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "payments");
435        // The worktree's own link wins.
436        link(&wt, "acme/billing").unwrap();
437        assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "billing");
438        // A damaged link of the main checkout is still refused.
439        std::fs::remove_file(wt.join(LINK_FILE)).unwrap();
440        std::fs::write(main.join(LINK_FILE), "{").unwrap();
441        assert!(read_link(&wt).is_err());
442    }
443
444    #[test]
445    fn a_dot_git_file_that_git_does_not_back_is_not_followed() {
446        let base = tempfile::tempdir().unwrap();
447        let (main, wt) = worktree_layout(base.path());
448        link(&main, "acme/payments").unwrap();
449        // A second checkout claims the same worktree admin dir: its back
450        // pointer names the other checkout, so it gets nothing.
451        let impostor = base.path().join("impostor");
452        std::fs::create_dir_all(&impostor).unwrap();
453        std::fs::copy(wt.join(".git"), impostor.join(".git")).unwrap();
454        assert!(main_worktree_root(&impostor).is_none());
455        assert!(read_link(&impostor).unwrap().is_none());
456        // A bare common dir has no main checkout.
457        let admin = main.join(".git/worktrees/wt");
458        std::fs::write(admin.join("commondir"), "..\n").unwrap();
459        assert!(main_worktree_root(&wt).is_none());
460    }
461
462    #[test]
463    fn malformed_vault_names_are_refused() {
464        let dir = tempfile::tempdir().unwrap();
465        assert!(link(dir.path(), "payments").is_err());
466        assert!(link(dir.path(), "acme/../etc").is_err());
467        assert!(link(dir.path(), "acme/payments@localhost").is_err());
468    }
469
470    fn fixture(name: &str) -> String {
471        std::fs::read_to_string(format!(
472            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/{name}",
473            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
474        ))
475        .unwrap()
476    }
477
478    /// C0 2.0 `link/`: v2 carries the address, v1 is read as hosted, and
479    /// every invalid case is refused.
480    #[test]
481    fn link_files_match_the_contract_fixtures() {
482        let hosted = parse_link(&fixture("lean-ctx-cloud.hosted.json")).unwrap();
483        assert_eq!(hosted.address().to_string(), "acme/payments");
484        assert!(hosted.is_for("https://cloud.leanctx.com"));
485        assert!(hosted.is_for("https://cloud.leanctx.com/"));
486        let own = parse_link(&fixture("lean-ctx-cloud.self_hosted.json")).unwrap();
487        assert_eq!(own.server.as_deref(), Some("cloud.acme.example:8443"));
488        assert!(own.is_for("https://cloud.acme.example:8443/"));
489        assert!(!own.is_for("https://cloud.leanctx.com"));
490        let v1 = parse_link(&fixture("lean-ctx-cloud.v1.json")).unwrap();
491        assert_eq!((v1.vault, v1.server), (hosted.vault.clone(), None));
492        let dir = format!(
493            "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/invalid",
494            concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
495        );
496        let mut refused = 0;
497        for entry in std::fs::read_dir(dir).unwrap() {
498            let case: serde_json::Value =
499                serde_json::from_str(&std::fs::read_to_string(entry.unwrap().path()).unwrap())
500                    .unwrap();
501            let base = case["base"]
502                .as_str()
503                .unwrap()
504                .strip_prefix("link/")
505                .unwrap();
506            let mut doc: serde_json::Value = serde_json::from_str(&fixture(base)).unwrap();
507            for op in case["patch"].as_array().unwrap() {
508                assert_eq!(op["op"], "replace", "{case}");
509                *doc.pointer_mut(op["path"].as_str().unwrap()).unwrap() = op["value"].clone();
510            }
511            assert!(parse_link(&doc.to_string()).is_err(), "{case}");
512            refused += 1;
513        }
514        assert!(refused > 0);
515    }
516
517    #[test]
518    fn a_self_hosted_vault_is_written_as_link_v2() {
519        let dir = tempfile::tempdir().unwrap();
520        link(dir.path(), "acme/payments@Cloud.Acme.Example:8443").unwrap();
521        let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
522        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
523        assert_eq!(
524            value,
525            serde_json::json!({"schema": LINK_SCHEMA_V2, "vault": "acme/payments@cloud.acme.example:8443"})
526        );
527        link(dir.path(), "acme/payments@cloud.leanctx.com").unwrap();
528        let back = read_link(dir.path()).unwrap().unwrap();
529        assert_eq!((back.schema.as_str(), back.server), (LINK_SCHEMA, None));
530    }
531}