use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::CloudError;
use super::vault_address::VaultAddress;
use lean_ctx_protocol::cloud::vault::VaultRefV1;
pub const LINK_FILE: &str = ".lean-ctx-cloud.json";
pub fn has_link_file(root: &Path) -> bool {
root.join(LINK_FILE).exists()
}
pub const LINK_SCHEMA: &str = "leanctx.cloud.link/v1";
pub const LINK_SCHEMA_V2: &str = "leanctx.cloud.link/v2";
const IDENTITY_FILE: &str = ".lean-ctx-id";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VaultLink {
pub schema: String,
pub vault: VaultRefV1,
pub server: Option<String>,
}
impl VaultLink {
pub fn address(&self) -> VaultAddress {
VaultAddress {
ws: self.vault.ns.clone(),
vault: self.vault.name.clone(),
server: self.server.clone(),
}
}
pub fn is_for(&self, origin: &str) -> bool {
lean_ctx_protocol::cloud::same_cloud_origin(&self.address().origin(), origin)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct LinkV1 {
schema: String,
#[serde(rename = "repo", alias = "vault")]
vault: VaultRefV1,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct LinkV2 {
schema: String,
vault: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkOutcome {
pub file: PathBuf,
pub created_identity: bool,
}
pub fn read_link(root: &Path) -> Result<Option<VaultLink>, CloudError> {
if let Some(link) = read_link_file(root)? {
return Ok(Some(link));
}
match main_worktree_root(root) {
Some(main) => read_link_file(&main),
None => Ok(None),
}
}
pub use lean_ctx::core::git_worktree::main_worktree_root;
fn read_link_file(root: &Path) -> Result<Option<VaultLink>, CloudError> {
let path = root.join(LINK_FILE);
match std::fs::read_to_string(&path) {
Ok(text) => parse(&path, &text).map(Some),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(CloudError::Local(format!("read {}: {e}", path.display()))),
}
}
pub(crate) fn read_link_file_at(root: &Path) -> Result<Option<VaultLink>, CloudError> {
read_link_file(root)
}
fn parse(path: &Path, text: &str) -> Result<VaultLink, CloudError> {
parse_link(text).map_err(|why| CloudError::Local(format!("{} {why}", path.display())))
}
fn parse_link(text: &str) -> Result<VaultLink, String> {
let value: serde_json::Value =
serde_json::from_str(text).map_err(|e| format!("is damaged: {e}"))?;
match value["schema"].as_str() {
Some(LINK_SCHEMA) => {
let link: LinkV1 =
serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
link.vault.validate().map_err(|e| format!(": {e}"))?;
Ok(VaultLink {
schema: link.schema,
vault: link.vault,
server: None,
})
}
Some(LINK_SCHEMA_V2) => {
let link: LinkV2 =
serde_json::from_value(value).map_err(|e| format!("is damaged: {e}"))?;
let address = VaultAddress::parse(&link.vault).map_err(|e| format!(": {e}"))?;
let vault = VaultRefV1 {
ns: address.ws,
name: address.vault,
};
vault.validate().map_err(|e| format!(": {e}"))?;
Ok(VaultLink {
schema: link.schema,
vault,
server: address.server,
})
}
_ => Err("has an unknown schema".into()),
}
}
fn link_text(address: &VaultAddress) -> Result<String, CloudError> {
let value = if address.is_hosted() {
serde_json::to_value(LinkV1 {
schema: LINK_SCHEMA.into(),
vault: VaultRefV1 {
ns: address.ws.clone(),
name: address.vault.clone(),
},
})
} else {
serde_json::to_value(LinkV2 {
schema: LINK_SCHEMA_V2.into(),
vault: address.to_string(),
})
}
.map_err(|e| CloudError::Local(e.to_string()))?;
let mut text =
serde_json::to_string_pretty(&value).map_err(|e| CloudError::Local(e.to_string()))?;
text.push('\n');
Ok(text)
}
pub fn link(root: &Path, vault: &str) -> Result<LinkOutcome, CloudError> {
let address = VaultAddress::parse(vault).map_err(|e| CloudError::Config(e.to_string()))?;
VaultRefV1 {
ns: address.ws.clone(),
name: address.vault.clone(),
}
.validate()
.map_err(|e| CloudError::Config(e.to_string()))?;
let root_str = root.to_string_lossy();
let created_identity = lean_ctx::core::project_hash::project_identity(&root_str).is_none();
if created_identity {
let mut bytes = [0u8; 16];
getrandom::fill(&mut bytes).map_err(|e| CloudError::Local(format!("random: {e}")))?;
write_file(
&root.join(IDENTITY_FILE),
format!("{}\n", hex::encode(bytes)).as_bytes(),
)?;
}
let text = link_text(&address)?;
let file = root.join(LINK_FILE);
write_file(&file, text.as_bytes())?;
Ok(LinkOutcome {
file,
created_identity,
})
}
pub fn prior_link(root: &Path) -> Option<Vec<u8>> {
let path = root.join(LINK_FILE);
let meta = std::fs::symlink_metadata(&path).ok()?;
if !meta.is_file() {
return None;
}
std::fs::read(&path).ok()
}
pub fn undo(root: &Path, outcome: &LinkOutcome, prior: Option<&[u8]>) -> Result<(), CloudError> {
match prior {
Some(bytes) => write_file(&outcome.file, bytes)?,
None => remove_if_present(&outcome.file)?,
}
if outcome.created_identity {
remove_if_present(&root.join(IDENTITY_FILE))?;
}
Ok(())
}
fn remove_if_present(path: &Path) -> Result<(), CloudError> {
match std::fs::remove_file(path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
Err(CloudError::Local(format!("remove {}: {e}", path.display())))
}
_ => Ok(()),
}
}
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CloudError> {
lean_ctx::core::atomic_fs::try_atomic_write(path, bytes, None)
.map_err(|e| CloudError::Local(format!("write {}: {e}", path.display())))
}
#[cfg(test)]
pub(crate) fn worktree_layout(base: &Path) -> (PathBuf, PathBuf) {
crate::unlinked::fake_worktree(base)
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn link_never_writes_through_a_planted_symlink() {
let outside = tempfile::tempdir().unwrap();
let victim = outside.path().join("authorized_keys");
std::fs::write(&victim, "ssh-ed25519 KEEP\n").unwrap();
let repo = tempfile::tempdir().unwrap();
for name in [
LINK_FILE,
IDENTITY_FILE,
".lean-ctx-cloud.tmp",
".lean-ctx-id.tmp",
] {
std::os::unix::fs::symlink(&victim, repo.path().join(name)).unwrap();
}
link(repo.path(), "acme/payments").unwrap();
assert_eq!(
std::fs::read_to_string(&victim).unwrap(),
"ssh-ed25519 KEEP\n"
);
let written = std::fs::symlink_metadata(repo.path().join(LINK_FILE)).unwrap();
assert!(written.is_file(), "the link file replaced the symlink");
assert!(read_link(repo.path()).unwrap().is_some());
}
#[test]
fn link_writes_the_repo_and_an_identity_when_missing() {
let dir = tempfile::tempdir().unwrap();
let outcome = link(dir.path(), "acme/payments").unwrap();
assert!(outcome.created_identity);
assert!(dir.path().join(IDENTITY_FILE).exists());
let link_back = read_link(dir.path()).unwrap().unwrap();
assert_eq!(
(link_back.vault.ns.as_str(), link_back.vault.name.as_str()),
("acme", "payments")
);
let again = link(dir.path(), "acme/billing").unwrap();
assert!(!again.created_identity, "the identity is kept");
assert_eq!(
read_link(dir.path()).unwrap().unwrap().vault.name,
"billing"
);
}
#[test]
fn two_linked_checkouts_of_one_origin_keep_one_identity() {
use crate::vault::project_identity;
let base = tempfile::tempdir().unwrap();
let checkout = |name: &str| {
let root = base.path().join(name);
std::fs::create_dir_all(&root).unwrap();
for args in [
&["init", "-q"][..],
&[
"remote",
"add",
"origin",
"git@github.com:yves/leanctx-cloud.git",
][..],
] {
let out = std::process::Command::new("git")
.arg("-C")
.arg(&root)
.args(args)
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_NOSYSTEM", "1")
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}: {out:?}");
}
root
};
let (mac, pounce) = (checkout("mac"), checkout("pounce"));
assert!(!link(&mac, "yves/leanctx-cloud").unwrap().created_identity);
assert!(!mac.join(IDENTITY_FILE).exists(), "an origin needs no id");
std::fs::write(
pounce.join(IDENTITY_FILE),
"0dfac5e1b2c3d4e5f60718293a4b5c6d\n",
)
.unwrap();
assert!(
!link(&pounce, "yves/leanctx-cloud")
.unwrap()
.created_identity
);
let origin = Some("git:github.com/yves/leanctx-cloud".to_string());
assert_eq!(project_identity(&mac), origin);
assert_eq!(project_identity(&pounce), origin, "the random id gives way");
let parts = |root: &Path| crate::identity_v2::read_parts(root).stable();
assert_eq!(parts(&mac), parts(&pounce), "and in identity v2");
std::fs::write(pounce.join(IDENTITY_FILE), "billing-service\n").unwrap();
assert_eq!(
project_identity(&pounce).as_deref(),
Some("explicit:billing-service")
);
let bare = base.path().join("bare");
std::fs::create_dir_all(&bare).unwrap();
assert!(link(&bare, "yves/notes").unwrap().created_identity);
let id = std::fs::read_to_string(bare.join(IDENTITY_FILE)).unwrap();
assert!(crate::vault::link_made_id(id.trim()));
assert_eq!(
project_identity(&bare),
Some(format!("explicit:{}", id.trim()))
);
}
#[test]
fn projects_with_an_identity_get_no_new_id_file() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nname = \"demo\"\n",
)
.unwrap();
assert!(!link(dir.path(), "acme/demo").unwrap().created_identity);
assert!(!dir.path().join(IDENTITY_FILE).exists());
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct PreVaLink {
schema: String,
repo: VaultRefV1,
}
#[test]
fn the_link_file_keeps_repo_so_older_engines_in_the_team_read_it() {
let old = r#"{"schema":"leanctx.cloud.link/v1","repo":{"ns":"acme","name":"payments"}}"#;
let read =
crate::vault::assert_pre_va_round_trip::<LinkV1, PreVaLink>(old, "repo", "vault");
assert_eq!(
(read.vault.ns.as_str(), read.vault.name.as_str()),
("acme", "payments")
);
let dir = tempfile::tempdir().unwrap();
link(dir.path(), "acme/payments").unwrap();
let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
serde_json::from_str::<PreVaLink>(&text).expect("an engine before the rename reads it");
let back = read_link(dir.path()).unwrap().unwrap();
assert_eq!((back.vault, back.server), (read.vault, None));
}
#[test]
fn a_worktree_without_a_link_uses_the_main_checkouts() {
let base = tempfile::tempdir().unwrap();
let (main, wt) = worktree_layout(base.path());
assert_eq!(
main_worktree_root(&wt).unwrap(),
main.canonicalize().unwrap()
);
assert!(main_worktree_root(&main).is_none(), "the main checkout");
assert!(read_link(&wt).unwrap().is_none(), "nothing linked yet");
link(&main, "acme/payments").unwrap();
assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "payments");
link(&wt, "acme/billing").unwrap();
assert_eq!(read_link(&wt).unwrap().unwrap().vault.name, "billing");
std::fs::remove_file(wt.join(LINK_FILE)).unwrap();
std::fs::write(main.join(LINK_FILE), "{").unwrap();
assert!(read_link(&wt).is_err());
}
#[test]
fn a_dot_git_file_that_git_does_not_back_is_not_followed() {
let base = tempfile::tempdir().unwrap();
let (main, wt) = worktree_layout(base.path());
link(&main, "acme/payments").unwrap();
let impostor = base.path().join("impostor");
std::fs::create_dir_all(&impostor).unwrap();
std::fs::copy(wt.join(".git"), impostor.join(".git")).unwrap();
assert!(main_worktree_root(&impostor).is_none());
assert!(read_link(&impostor).unwrap().is_none());
let admin = main.join(".git/worktrees/wt");
std::fs::write(admin.join("commondir"), "..\n").unwrap();
assert!(main_worktree_root(&wt).is_none());
}
#[test]
fn malformed_vault_names_are_refused() {
let dir = tempfile::tempdir().unwrap();
assert!(link(dir.path(), "payments").is_err());
assert!(link(dir.path(), "acme/../etc").is_err());
assert!(link(dir.path(), "acme/payments@localhost").is_err());
}
fn fixture(name: &str) -> String {
std::fs::read_to_string(format!(
"{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/{name}",
concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
))
.unwrap()
}
#[test]
fn link_files_match_the_contract_fixtures() {
let hosted = parse_link(&fixture("lean-ctx-cloud.hosted.json")).unwrap();
assert_eq!(hosted.address().to_string(), "acme/payments");
assert!(hosted.is_for("https://cloud.leanctx.com"));
assert!(hosted.is_for("https://cloud.leanctx.com/"));
let own = parse_link(&fixture("lean-ctx-cloud.self_hosted.json")).unwrap();
assert_eq!(own.server.as_deref(), Some("cloud.acme.example:8443"));
assert!(own.is_for("https://cloud.acme.example:8443/"));
assert!(!own.is_for("https://cloud.leanctx.com"));
let v1 = parse_link(&fixture("lean-ctx-cloud.v1.json")).unwrap();
assert_eq!((v1.vault, v1.server), (hosted.vault.clone(), None));
let dir = format!(
"{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/link/invalid",
concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
);
let mut refused = 0;
for entry in std::fs::read_dir(dir).unwrap() {
let case: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(entry.unwrap().path()).unwrap())
.unwrap();
let base = case["base"]
.as_str()
.unwrap()
.strip_prefix("link/")
.unwrap();
let mut doc: serde_json::Value = serde_json::from_str(&fixture(base)).unwrap();
for op in case["patch"].as_array().unwrap() {
assert_eq!(op["op"], "replace", "{case}");
*doc.pointer_mut(op["path"].as_str().unwrap()).unwrap() = op["value"].clone();
}
assert!(parse_link(&doc.to_string()).is_err(), "{case}");
refused += 1;
}
assert!(refused > 0);
}
#[test]
fn a_self_hosted_vault_is_written_as_link_v2() {
let dir = tempfile::tempdir().unwrap();
link(dir.path(), "acme/payments@Cloud.Acme.Example:8443").unwrap();
let text = std::fs::read_to_string(dir.path().join(LINK_FILE)).unwrap();
let value: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(
value,
serde_json::json!({"schema": LINK_SCHEMA_V2, "vault": "acme/payments@cloud.acme.example:8443"})
);
link(dir.path(), "acme/payments@cloud.leanctx.com").unwrap();
let back = read_link(dir.path()).unwrap().unwrap();
assert_eq!((back.schema.as_str(), back.server), (LINK_SCHEMA, None));
}
}