1use std::path::Path;
10
11use hmac::{Hmac, KeyInit as _, Mac as _};
12use sha2::Sha256;
13
14use super::CloudError;
15use super::link::read_link;
16use lean_ctx_protocol::cloud::vault::{
17 VAULT_RESOLVE_REQUEST_SCHEMA, VaultResolveRequestV1, stable_identity,
18};
19
20pub use lean_ctx::core::vault_map::{VaultMap, VaultRecord};
21
22pub fn normalize_git_url(url: &str) -> String {
25 let url = url.trim();
26 let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
27 let authority_end = without_scheme.find('/').unwrap_or(without_scheme.len());
29 let without_user = without_scheme[..authority_end]
30 .rfind('@')
31 .map_or(without_scheme, |at| &without_scheme[at + 1..]);
32 let path_form = match without_user.split_once(':') {
34 Some((host, rest)) if !rest.starts_with(|c: char| c.is_ascii_digit()) => {
35 format!("{host}/{rest}")
36 }
37 Some((host, rest)) => {
38 let rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
39 format!("{host}{rest}")
40 }
41 None => without_user.to_string(),
42 };
43 let trimmed = path_form.trim_end_matches('/');
44 let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed);
45 match trimmed.split_once('/') {
46 Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
47 None => trimmed.to_ascii_lowercase(),
48 }
49}
50
51pub fn project_identity(root: &Path) -> Option<String> {
58 let root_str = root.to_string_lossy();
59 let mut identity = lean_ctx::core::project_hash::project_identity(&root_str)?;
60 if let Some(id) = identity.strip_prefix("explicit:")
61 && link_made_id(id)
62 && let Some(origin) = lean_ctx::core::project_hash::origin_identity(&root_str)
63 {
64 identity = origin;
65 }
66 Some(match identity.strip_prefix("git:") {
67 Some(url) => format!("git:{}", normalize_git_url(url)),
68 None => identity,
69 })
70}
71
72pub fn link_made_id(id: &str) -> bool {
75 id.len() == 32
76 && id
77 .bytes()
78 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
79}
80
81pub fn identity_digest(salt: &[u8], stable: &str) -> String {
83 let mut mac = Hmac::<Sha256>::new_from_slice(salt).expect("HMAC takes any key length");
84 mac.update(stable.as_bytes());
85 hex::encode(mac.finalize().into_bytes())
86}
87
88pub fn resolve_request(
90 root: &Path,
91 org_salt_id: &str,
92 salt: &[u8],
93 with_label: bool,
94) -> Result<(String, VaultResolveRequestV1), CloudError> {
95 let identity = project_identity(root).ok_or_else(|| {
96 CloudError::Config(format!(
97 "{} has no stable identity (no git origin or manifest); run `lean-ctx cloud link <workspace>/<vault>` there",
98 root.display()
99 ))
100 })?;
101 let stable = stable_identity(&identity);
102 let label = with_label
103 .then(|| {
104 root.file_name()
105 .map(|n| n.to_string_lossy().chars().take(64).collect::<String>())
106 })
107 .flatten()
108 .filter(|l: &String| !l.trim().is_empty() && !l.chars().any(char::is_control));
109 let request = VaultResolveRequestV1 {
110 schema: VAULT_RESOLVE_REQUEST_SCHEMA.into(),
111 org_salt_id: org_salt_id.into(),
112 identity_digest: identity_digest(salt, &stable),
113 label,
114 vault: read_link(root)?.map(|link| link.vault),
115 };
116 Ok((stable, request))
117}
118
119#[cfg(test)]
124pub(crate) fn assert_pre_va_round_trip<T, Old>(old: &str, old_key: &str, new_key: &str) -> T
125where
126 T: serde::Serialize + serde::de::DeserializeOwned,
127 Old: serde::de::DeserializeOwned,
128{
129 let (old_key, new_key) = (format!("\"{old_key}\""), format!("\"{new_key}\""));
130 let read: T = serde_json::from_str(old).expect("reads the pre-VA form");
131 let written = serde_json::to_string(&read).expect("writes");
132 assert!(
133 written.contains(&old_key) && !written.contains(&new_key),
134 "{written}"
135 );
136 serde_json::from_str::<Old>(&written).expect("an engine before the rename reads it");
137 serde_json::from_str::<T>(&old.replace(&old_key, &new_key)).expect("reads the new spelling");
138 read
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use std::collections::BTreeMap;
145
146 use serde::Deserialize;
147
148 #[test]
149 fn git_urls_lose_credentials_and_spelling() {
150 let expected = "github.com/acme/payments";
151 for url in [
152 "https://github.com/acme/payments.git",
153 concat!("https://ci-bot:gh", "p_secret123@github.com/acme/payments"),
154 "git@github.com:acme/payments.git",
155 "ssh://git@GitHub.com/acme/payments/",
156 "ssh://git@github.com:22/acme/payments.git",
157 ] {
158 assert_eq!(normalize_git_url(url), expected, "{url}");
159 }
160 assert_eq!(
161 normalize_git_url("https://github.com/acme/pkg@v1"),
162 "github.com/acme/pkg@v1",
163 "an @ in the path is not a credential"
164 );
165 }
166
167 #[test]
168 fn the_identity_is_the_same_for_every_checkout() {
169 let a = tempfile::tempdir().unwrap();
170 let b = tempfile::tempdir().unwrap();
171 for (dir, url) in [
172 (a.path(), "https://user:token@github.com/acme/payments.git"),
173 (b.path(), "git@github.com:acme/payments.git"),
174 ] {
175 std::fs::create_dir_all(dir.join(".git")).unwrap();
176 std::fs::write(
177 dir.join(".git/config"),
178 format!("[remote \"origin\"]\n\turl = {url}\n"),
179 )
180 .unwrap();
181 }
182 let ia = project_identity(a.path()).unwrap();
183 assert_eq!(ia, project_identity(b.path()).unwrap());
184 assert!(!ia.contains("token") && !ia.contains("user"));
185 let (stable, request) = resolve_request(a.path(), "salt_1", &[0x0a; 32], false).unwrap();
186 assert_eq!(stable, stable_identity("git:github.com/acme/payments"));
187 assert!(request.validate().is_ok());
188 assert!(request.label.is_none());
189 }
190
191 #[test]
192 fn a_linked_worktree_finds_the_vault_of_its_main_checkout() {
193 let base = tempfile::tempdir().unwrap();
194 let (main, wt) = super::super::link::worktree_layout(base.path());
195 let other = base.path().join("other");
196 std::fs::create_dir_all(&other).unwrap();
197 let mut map = VaultMap::default();
198 map.vaults.insert(
199 "s1".into(),
200 VaultRecord {
201 vault_id: "v1".into(),
202 ns: "acme".into(),
203 name: "payments".into(),
204 sealed: false,
205 roots: vec![main.to_string_lossy().into_owned()],
206 },
207 );
208 let found = |root: &Path| {
209 map.for_root(&root.to_string_lossy())
210 .map(|r| r.vault_id.clone())
211 };
212 assert_eq!(found(&main).as_deref(), Some("v1"));
213 assert_eq!(found(&wt).as_deref(), Some("v1"), "the worktree");
214 assert_eq!(found(&other), None, "an unrelated directory");
215 }
216
217 #[derive(Deserialize)]
219 struct PreVaMap {
220 #[allow(dead_code)]
221 projects: BTreeMap<String, PreVaRecord>,
222 }
223 #[derive(Deserialize)]
224 #[allow(dead_code)]
225 struct PreVaRecord {
226 project_id: String,
227 ns: String,
228 name: String,
229 sealed: bool,
230 #[serde(default)]
231 roots: Vec<String>,
232 }
233
234 #[test]
235 fn the_vault_map_stays_in_projects_json_with_pre_va_names() {
236 let vault_id = "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42";
237 let old = format!(
238 r#"{{"projects":{{"s1":{{"project_id":"{vault_id}","ns":"acme","name":"payments","sealed":true,"roots":["/w/payments"]}}}}}}"#
239 );
240 let map: VaultMap =
241 assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "project_id", "vault_id");
242 assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "projects", "vaults");
243 let record = &map.vaults["s1"];
244 assert_eq!((record.vault_id.as_str(), record.sealed), (vault_id, true));
245
246 let data = tempfile::tempdir().unwrap();
247 std::fs::write(data.path().join("projects.json"), &old).unwrap();
248 let loaded = VaultMap::load(data.path());
249 assert_eq!(loaded, map);
250 loaded.save(data.path()).unwrap();
251 let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
252 serde_json::from_str::<PreVaMap>(&text).expect("an engine before the rename reads it");
253 assert!(!data.path().join("vaults.json").exists());
254 }
255}