Skip to main content

lean_ctx_cloud/
vault.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Repository identity and the local map of resolved Cloud vaults.
3//!
4//! The identity Cloud sees is `stable_identity(project_identity(root))`
5//! salted by the org (`identity_digest`). It is the same for every checkout
6//! of a repository on every machine (`.lean-ctx-id` > git origin >
7//! manifests) and never contains a path, user name or credential.
8
9use 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, vault_scope};
21
22/// `github.com/acme/payments` for every spelling of the same remote:
23/// scheme, credentials, `.git` suffix, scp syntax and host case removed.
24pub 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    // Credentials sit in the authority only (before the first `/`).
28    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    // scp-like `host:org/repo` (no port digits right after the colon)
33    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
51/// The machine-independent identity of the project at `root`, if it has one.
52///
53/// A `.lean-ctx-id` that `cloud link` wrote ([`link_made_id`]) gives way to
54/// the git origin: earlier engines wrote one per checkout, so two checkouts
55/// of one origin had two identities and two vaults. Without an origin the
56/// id stays the identity; a hand-written id (a name) always does.
57pub 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
72/// Whether a `.lean-ctx-id` value has the shape `cloud link` writes: 32
73/// lowercase hex characters (16 random bytes).
74pub 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
81/// `hex(HMAC-SHA256(org_salt, stable_identity))`.
82pub 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
88/// The resolve request for the project at `root`.
89pub 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/// Load, change and save `projects.json` at `data_dir` under its state lock
120/// (rc3-81 S2), so a sync that resolves a checkout and an enrollment that
121/// switches the Cloud never write over each other. The file is written only
122/// when `change` changed the map; the lock is held for local file work only.
123pub fn update_map<R>(
124    data_dir: &Path,
125    change: impl FnOnce(&mut VaultMap) -> R,
126) -> Result<(R, VaultMap), CloudError> {
127    let _lock = super::state::lock_state(data_dir, lean_ctx::core::vault_map::VAULTS_FILE)?;
128    let before = VaultMap::load(data_dir);
129    let mut map = before.clone();
130    let out = change(&mut map);
131    if map != before {
132        map.save(data_dir)
133            .map_err(|e| CloudError::Local(format!("save the vault map: {e}")))?;
134    }
135    Ok((out, map))
136}
137
138/// The vault map of the store as the connected Cloud and account see it
139/// ([`VaultMap::for_scope`]): no records of another Cloud or account
140/// (rc3-81 S1, rc4-2).
141/// Not connected: the map as it is on disk.
142pub fn connected_map(store: &super::state::CloudStore) -> VaultMap {
143    for_connected(store, VaultMap::load(store.data_dir()))
144}
145
146/// [`connected_map`] for a `map` already loaded from the store.
147pub fn for_connected(store: &super::state::CloudStore, map: VaultMap) -> VaultMap {
148    in_scope(map, connected_scope(store).as_deref())
149}
150
151/// The scope ([`vault_scope`]) the store is connected to: `None` when it is
152/// not connected; an unreadable instance record gives a scope no stamped
153/// map matches (fail closed).
154pub fn connected_scope(store: &super::state::CloudStore) -> Option<String> {
155    match store.instance() {
156        Ok(Some(instance)) => Some(instance.vault_scope()),
157        Err(_) => Some(String::new()),
158        Ok(None) => None,
159    }
160}
161
162/// `map` as `scope` sees it ([`VaultMap::for_scope`]); `None` (not
163/// connected) leaves it as it is.
164pub fn in_scope(map: VaultMap, scope: Option<&str>) -> VaultMap {
165    match scope {
166        Some(scope) => map.for_scope(scope),
167        None => map,
168    }
169}
170
171/// The vault map as the Cloud and account at `scope` ([`vault_scope`]) see
172/// it, `None` when it belongs to another one (an enrollment elsewhere since
173/// the caller's session was loaded). A sender then sends nothing and keeps
174/// its queue for the scope it was queued in (rc3-81, bd 39791 M1/M2).
175pub fn map_in(data_dir: &Path, scope: &str) -> Option<VaultMap> {
176    let map = VaultMap::load(data_dir);
177    map.belongs_to(scope).then_some(map)
178}
179
180/// Put the records of the checkout `root` back as they were in `snapshot`
181/// (the map before a change that was refused), under one hold of the map's
182/// lock, and only while the map on disk and the snapshot belong to `scope`,
183/// the Cloud and account the snapshot was taken for (rc3-81, bd 39540 S-a,
184/// bd 39791 S1): records of other checkouts and an enrollment elsewhere
185/// since then are left as they are. Returns whether it was put back.
186pub fn restore_root(
187    data_dir: &Path,
188    snapshot: &VaultMap,
189    root: &str,
190    scope: &str,
191) -> Result<bool, CloudError> {
192    let same = |known: &String| lean_ctx::core::pathutil::same_project(known, root);
193    let (restored, _) = update_map(data_dir, |map| {
194        if !(map.belongs_to(scope) && snapshot.belongs_to(scope)) {
195            return false;
196        }
197        map.claim(scope);
198        map.vaults.retain(|_, record| {
199            let before = record.roots.len();
200            record.roots.retain(|known| !same(known));
201            record.roots.len() == before || !record.roots.is_empty()
202        });
203        for (stable, was) in &snapshot.vaults {
204            let roots: Vec<String> = was.roots.iter().filter(|r| same(r)).cloned().collect();
205            if roots.is_empty() {
206                continue;
207            }
208            // The record as it was, also over one a concurrent sync wrote
209            // under the same key meanwhile (its other roots are kept).
210            let entry = map
211                .vaults
212                .entry(stable.clone())
213                .or_insert_with(|| VaultRecord {
214                    roots: Vec::new(),
215                    ..was.clone()
216                });
217            entry.vault_id.clone_from(&was.vault_id);
218            entry.ns.clone_from(&was.ns);
219            entry.name.clone_from(&was.name);
220            entry.sealed = was.sealed;
221            for known in roots {
222                if !entry.roots.contains(&known) {
223                    entry.roots.push(known);
224                }
225            }
226        }
227        true
228    })?;
229    Ok(restored)
230}
231
232/// At enrollment with the Cloud and account at `scope`
233/// ([`lean_ctx::core::vault_map::vault_scope`]; rc3-81, rc4-2, rc4-6): only
234/// the vaults resolved there stay in `projects.json`; those of another
235/// Cloud or account are dropped (3.12.8 account scope: the enrollment has
236/// already removed the local Cloud data of another server or team). A file
237/// without an origin counts as resolved on `previous` (the scope this
238/// machine was enrolled with until now), else on the hosted Cloud, like a
239/// link file without a server, the account of `previous` included; a file
240/// stamped with a Cloud alone counts as resolved for the account of
241/// `previous` on that Cloud, else as a scope no account matches (fail
242/// closed, bd 39791 S2). Since every write
243/// while connected and every disconnect that keeps local data stamp the
244/// file, only a file written before origins were recorded (or saved again
245/// by an older engine) is unstamped. A missing or unreadable file is left as
246/// it is.
247pub(crate) fn enter_scope(
248    data_dir: &Path,
249    scope: &str,
250    previous: Option<&str>,
251) -> Result<(), CloudError> {
252    let legacy = previous.unwrap_or(lean_ctx_protocol::cloud::CLOUD_DEFAULT_URL);
253    update_map(data_dir, |map| {
254        if !map.vaults.is_empty() {
255            map.use_scope(scope, legacy);
256        }
257    })?;
258    Ok(())
259}
260
261/// At a disconnect that keeps the local data: stamp the map with `scope`,
262/// the Cloud and account being left, before their record is forgotten, so
263/// a later connect elsewhere drops these records instead of guessing
264/// (rc3-81, rc4-2). A map stamped with that Cloud alone gets the account
265/// added (it was written while enrolled with it); one of another Cloud or
266/// account is not changed.
267pub(crate) fn stamp_left_scope(data_dir: &Path, scope: &str) -> Result<(), CloudError> {
268    if !data_dir
269        .join(lean_ctx::core::vault_map::VAULTS_FILE)
270        .is_file()
271    {
272        return Ok(());
273    }
274    update_map(data_dir, |map| {
275        if !map.vaults.is_empty() {
276            map.claim_enrolled(scope);
277        }
278    })?;
279    Ok(())
280}
281
282/// Round trip of a local Cloud file across the VA rename. `T` reads `old`
283/// (the file as an engine before the rename wrote it) and the same file
284/// with `old_key` spelled `new_key`; what `T` writes keeps `old_key`, so
285/// `Old` (the struct definition of the engine before the rename) reads it.
286#[cfg(test)]
287pub(crate) fn assert_pre_va_round_trip<T, Old>(old: &str, old_key: &str, new_key: &str) -> T
288where
289    T: serde::Serialize + serde::de::DeserializeOwned,
290    Old: serde::de::DeserializeOwned,
291{
292    let (old_key, new_key) = (format!("\"{old_key}\""), format!("\"{new_key}\""));
293    let read: T = serde_json::from_str(old).expect("reads the pre-VA form");
294    let written = serde_json::to_string(&read).expect("writes");
295    assert!(
296        written.contains(&old_key) && !written.contains(&new_key),
297        "{written}"
298    );
299    serde_json::from_str::<Old>(&written).expect("an engine before the rename reads it");
300    serde_json::from_str::<T>(&old.replace(&old_key, &new_key)).expect("reads the new spelling");
301    read
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use std::collections::BTreeMap;
308
309    use serde::Deserialize;
310
311    #[test]
312    fn git_urls_lose_credentials_and_spelling() {
313        let expected = "github.com/acme/payments";
314        for url in [
315            "https://github.com/acme/payments.git",
316            concat!("https://ci-bot:gh", "p_secret123@github.com/acme/payments"),
317            "git@github.com:acme/payments.git",
318            "ssh://git@GitHub.com/acme/payments/",
319            "ssh://git@github.com:22/acme/payments.git",
320        ] {
321            assert_eq!(normalize_git_url(url), expected, "{url}");
322        }
323        assert_eq!(
324            normalize_git_url("https://github.com/acme/pkg@v1"),
325            "github.com/acme/pkg@v1",
326            "an @ in the path is not a credential"
327        );
328    }
329
330    #[test]
331    fn the_identity_is_the_same_for_every_checkout() {
332        let a = tempfile::tempdir().unwrap();
333        let b = tempfile::tempdir().unwrap();
334        for (dir, url) in [
335            (a.path(), "https://user:token@github.com/acme/payments.git"),
336            (b.path(), "git@github.com:acme/payments.git"),
337        ] {
338            std::fs::create_dir_all(dir.join(".git")).unwrap();
339            std::fs::write(
340                dir.join(".git/config"),
341                format!("[remote \"origin\"]\n\turl = {url}\n"),
342            )
343            .unwrap();
344        }
345        let ia = project_identity(a.path()).unwrap();
346        assert_eq!(ia, project_identity(b.path()).unwrap());
347        assert!(!ia.contains("token") && !ia.contains("user"));
348        let (stable, request) = resolve_request(a.path(), "salt_1", &[0x0a; 32], false).unwrap();
349        assert_eq!(stable, stable_identity("git:github.com/acme/payments"));
350        assert!(request.validate().is_ok());
351        assert!(request.label.is_none());
352    }
353
354    #[test]
355    fn a_linked_worktree_finds_the_vault_of_its_main_checkout() {
356        let base = tempfile::tempdir().unwrap();
357        let (main, wt) = super::super::link::worktree_layout(base.path());
358        let other = base.path().join("other");
359        std::fs::create_dir_all(&other).unwrap();
360        let mut map = VaultMap::default();
361        map.vaults.insert(
362            "s1".into(),
363            VaultRecord {
364                vault_id: "v1".into(),
365                ns: "acme".into(),
366                name: "payments".into(),
367                sealed: false,
368                roots: vec![main.to_string_lossy().into_owned()],
369            },
370        );
371        let found = |root: &Path| {
372            map.for_root(&root.to_string_lossy())
373                .map(|r| r.vault_id.clone())
374        };
375        assert_eq!(found(&main).as_deref(), Some("v1"));
376        assert_eq!(found(&wt).as_deref(), Some("v1"), "the worktree");
377        assert_eq!(found(&other), None, "an unrelated directory");
378    }
379
380    /// `ProjectMap`/`ProjectRecord` of the engine before the VA rename.
381    #[derive(Deserialize)]
382    struct PreVaMap {
383        #[allow(dead_code)]
384        projects: BTreeMap<String, PreVaRecord>,
385    }
386    #[derive(Deserialize)]
387    #[allow(dead_code)]
388    struct PreVaRecord {
389        project_id: String,
390        ns: String,
391        name: String,
392        sealed: bool,
393        #[serde(default)]
394        roots: Vec<String>,
395    }
396
397    #[test]
398    fn the_vault_map_stays_in_projects_json_with_pre_va_names() {
399        let vault_id = "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42";
400        let old = format!(
401            r#"{{"projects":{{"s1":{{"project_id":"{vault_id}","ns":"acme","name":"payments","sealed":true,"roots":["/w/payments"]}}}}}}"#
402        );
403        let map: VaultMap =
404            assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "project_id", "vault_id");
405        assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "projects", "vaults");
406        let record = &map.vaults["s1"];
407        assert_eq!((record.vault_id.as_str(), record.sealed), (vault_id, true));
408
409        let data = tempfile::tempdir().unwrap();
410        std::fs::write(data.path().join("projects.json"), &old).unwrap();
411        let loaded = VaultMap::load(data.path());
412        assert_eq!(loaded, map);
413        loaded.save(data.path()).unwrap();
414        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
415        serde_json::from_str::<PreVaMap>(&text).expect("an engine before the rename reads it");
416        assert!(!data.path().join("vaults.json").exists());
417    }
418
419    const STAGING: &str = "https://cloud-staging.leanctx.com";
420
421    fn one_vault(data: &Path, vault_id: &str) {
422        let mut map = VaultMap::default();
423        map.vaults.insert(
424            "s1".into(),
425            VaultRecord {
426                vault_id: vault_id.into(),
427                ns: "acme".into(),
428                name: "payments".into(),
429                sealed: false,
430                roots: vec!["/w/payments".into()],
431            },
432        );
433        map.save(data).unwrap();
434    }
435
436    /// rc3-81 legacy rule: a file without an origin belongs to the Cloud the
437    /// machine was enrolled with until now, else to the hosted Cloud.
438    #[test]
439    fn vault_origin_legacy_file_belongs_to_the_previous_or_hosted_cloud() {
440        let data = tempfile::tempdir().unwrap();
441        one_vault(data.path(), "v_staging");
442        enter_scope(data.path(), STAGING, Some(STAGING)).unwrap();
443        let map = VaultMap::load(data.path());
444        assert_eq!(map.origin.as_deref(), Some(STAGING), "stamped");
445        assert!(map.for_root("/w/payments").is_some(), "kept on its Cloud");
446
447        let data = tempfile::tempdir().unwrap();
448        one_vault(data.path(), "v_prod");
449        enter_scope(data.path(), STAGING, None).unwrap();
450        let map = VaultMap::load(data.path());
451        assert!(map.for_root("/w/payments").is_none(), "not on staging");
452        assert_eq!(map.origin.as_deref(), Some(STAGING));
453        // Gone for good: back on the hosted Cloud nothing comes back.
454        enter_scope(data.path(), "https://cloud.leanctx.com/", None).unwrap();
455        let map = VaultMap::load(data.path());
456        assert!(
457            map.for_root("/w/payments").is_none(),
458            "gone after the switch"
459        );
460
461        // The hosted Cloud under any spelling is the same scope (here
462        // without an account; real enrollments always carry one).
463        let data = tempfile::tempdir().unwrap();
464        one_vault(data.path(), "v_prod");
465        enter_scope(data.path(), "https://Cloud.leanctx.com:443/", None).unwrap();
466        let map = VaultMap::load(data.path());
467        assert_eq!(map.for_root("/w/payments").unwrap().vault_id, "v_prod");
468        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
469        serde_json::from_str::<PreVaMap>(&text).expect("an older engine still reads it");
470    }
471
472    /// Records resolved on one Cloud are never seen on another, and a
473    /// switch drops them; nothing is written for a machine without a map.
474    #[test]
475    fn vault_origin_records_of_each_cloud_stay_apart() {
476        let data = tempfile::tempdir().unwrap();
477        enter_scope(data.path(), STAGING, None).unwrap();
478        assert!(!data.path().join("projects.json").exists());
479
480        one_vault(data.path(), "v_prod");
481        enter_scope(data.path(), STAGING, None).unwrap();
482        let mut map = VaultMap::load(data.path());
483        map.vaults.insert(
484            "s1".into(),
485            VaultRecord {
486                vault_id: "v_staging".into(),
487                ns: "acme".into(),
488                name: "payments".into(),
489                sealed: false,
490                roots: vec!["/w/payments".into()],
491            },
492        );
493        map.save(data.path()).unwrap();
494        let vault_on = |origin: &str| {
495            enter_scope(data.path(), origin, None).unwrap();
496            VaultMap::load(data.path())
497                .for_root("/w/payments")
498                .map(|r| r.vault_id.clone())
499        };
500        assert_eq!(vault_on(STAGING).as_deref(), Some("v_staging"));
501        assert_eq!(vault_on("https://cloud.leanctx.com").as_deref(), None);
502        assert_eq!(vault_on("https://cloud.example").as_deref(), None);
503        assert_eq!(vault_on(STAGING).as_deref(), None, "gone after the switch");
504    }
505
506    /// rc3-81 review S1/M1/N2: a write while connected stamps an unstamped
507    /// map and is refused on a map of another Cloud; a reader that knows the
508    /// connected Cloud sees no records of another one; origins compare
509    /// after normalization (case, trailing slash, `:443`).
510    #[test]
511    fn vault_origin_writers_claim_and_readers_fail_closed() {
512        let data = tempfile::tempdir().unwrap();
513        one_vault(data.path(), "v_staging");
514        let (claimed, map) = update_map(data.path(), |map| {
515            map.claim("https://Cloud-Staging.leanctx.com:443/")
516        })
517        .unwrap();
518        assert!(claimed);
519        assert_eq!(map.origin.as_deref(), Some(STAGING), "stored normalized");
520        assert_eq!(VaultMap::load(data.path()), map, "saved under the lock");
521
522        let (claimed, _) = update_map(data.path(), |map| {
523            let claimed = map.claim("https://cloud.leanctx.com");
524            if claimed {
525                map.vaults.clear();
526            }
527            claimed
528        })
529        .unwrap();
530        assert!(!claimed, "a map of another Cloud is not written to");
531        let map = VaultMap::load(data.path());
532        assert_eq!(map.vaults["s1"].vault_id, "v_staging");
533
534        assert!(
535            map.clone()
536                .for_scope("https://cloud.leanctx.com")
537                .for_root("/w/payments")
538                .is_none(),
539            "fail closed for another Cloud"
540        );
541        assert!(
542            map.for_scope(&format!("{STAGING}/"))
543                .for_root("/w/payments")
544                .is_some()
545        );
546        let mut unstamped = VaultMap::load(data.path());
547        unstamped.origin = None;
548        assert!(
549            unstamped
550                .for_scope("https://cloud.leanctx.com")
551                .for_root("/w/payments")
552                .is_some(),
553            "an unstamped map is left to the enrollment rule"
554        );
555    }
556
557    /// rc3-81 review M1: a disconnect that keeps local data stamps the map
558    /// with the Cloud being left; an already stamped one is not changed.
559    #[test]
560    fn vault_origin_disconnect_stamps_the_cloud_it_leaves() {
561        let data = tempfile::tempdir().unwrap();
562        stamp_left_scope(data.path(), STAGING).unwrap();
563        assert!(!data.path().join("projects.json").exists());
564        one_vault(data.path(), "v_staging");
565        stamp_left_scope(data.path(), STAGING).unwrap();
566        assert_eq!(VaultMap::load(data.path()).origin.as_deref(), Some(STAGING));
567        stamp_left_scope(data.path(), "https://cloud.leanctx.com").unwrap();
568        assert_eq!(VaultMap::load(data.path()).origin.as_deref(), Some(STAGING));
569    }
570
571    const PROD: &str = "https://cloud.leanctx.com";
572
573    fn record(vault_id: &str, roots: &[&str]) -> VaultRecord {
574        VaultRecord {
575            vault_id: vault_id.into(),
576            ns: "acme".into(),
577            name: "payments".into(),
578            sealed: false,
579            roots: roots.iter().map(|root| (*root).to_string()).collect(),
580        }
581    }
582
583    /// rc4-2/rc4-6: vault ids are per account. A switch from account A to
584    /// account B on the same Cloud drops A's records (B sees none of them),
585    /// and a switch back to A finds none of B's.
586    #[test]
587    fn vault_origin_account_switch_on_the_same_cloud_drops_the_records() {
588        let data = tempfile::tempdir().unwrap();
589        let (a, b) = (vault_scope(PROD, "org_a"), vault_scope(PROD, "org_b"));
590        assert_eq!(a, "https://cloud.leanctx.com#org=org_a");
591        assert_eq!(vault_scope("https://Cloud.leanctx.com:443/", " org_a "), a);
592        assert_eq!(vault_scope(PROD, ""), PROD, "no account: the origin alone");
593
594        update_map(data.path(), |map| {
595            assert!(map.claim(&a));
596            map.vaults
597                .insert("s1".into(), record("v_a", &["/w/payments"]));
598        })
599        .unwrap();
600        let vault_of = |map: VaultMap| map.for_root("/w/payments").map(|r| r.vault_id.clone());
601
602        enter_scope(data.path(), &b, Some(&a)).unwrap();
603        let map = VaultMap::load(data.path());
604        assert_eq!(map.origin.as_deref(), Some(b.as_str()));
605        assert_eq!(vault_of(map.clone()), None, "B sees none of A's records");
606        assert!(map.vaults.is_empty(), "A's records dropped");
607        assert_eq!(vault_of(map.clone().for_scope(&b)), None);
608
609        // A stale reader for A sees nothing of B's map; a write for A is refused.
610        let (claimed, _) = update_map(data.path(), |map| map.claim(&a)).unwrap();
611        assert!(!claimed, "a map of another account is not written to");
612
613        update_map(data.path(), |map| {
614            assert!(map.claim(&b));
615            map.vaults
616                .insert("s1".into(), record("v_b", &["/w/payments"]));
617        })
618        .unwrap();
619        enter_scope(data.path(), &a, Some(&b)).unwrap();
620        let map = VaultMap::load(data.path());
621        assert_eq!(map.origin.as_deref(), Some(a.as_str()));
622        assert_eq!(vault_of(map.clone()), None, "A sees none of B's records");
623        assert!(map.vaults.is_empty(), "B's records dropped");
624        assert_eq!(vault_of(map.for_scope(&b)), None, "fail closed for B");
625    }
626
627    /// rc3-81 bd 39791 S2 (fail closed): a map stamped with a Cloud alone
628    /// (dev builds of rc3-81) matches no account until an enrollment
629    /// resolves it: to the account the machine was enrolled with on that
630    /// Cloud, never to another one. An unstamped map belongs to the
631    /// previous scope including its account.
632    #[test]
633    fn vault_origin_origin_only_stamp_belongs_only_to_the_legacy_account() {
634        let (a, b) = (vault_scope(PROD, "org_a"), vault_scope(PROD, "org_b"));
635        let mut map = VaultMap::default();
636        map.vaults
637            .insert("s1".into(), record("v_1", &["/w/payments"]));
638        map.origin = Some(format!("{PROD}/"));
639        for scope in [&a, &b, &vault_scope(STAGING, "org_a")] {
640            assert!(
641                map.clone()
642                    .for_scope(scope)
643                    .for_root("/w/payments")
644                    .is_none(),
645                "{scope}"
646            );
647            assert!(!map.clone().claim(scope), "{scope}");
648        }
649
650        // Enrolled with B, previously A on that Cloud: the records are A's.
651        let data = tempfile::tempdir().unwrap();
652        map.save(data.path()).unwrap();
653        enter_scope(data.path(), &b, Some(&a)).unwrap();
654        let after = VaultMap::load(data.path());
655        assert!(after.for_root("/w/payments").is_none(), "A's: dropped");
656        assert_eq!(after.origin.as_deref(), Some(b.as_str()));
657
658        // Enrolled again with A: they are A's and stay active, stamped.
659        let data = tempfile::tempdir().unwrap();
660        map.save(data.path()).unwrap();
661        enter_scope(data.path(), &a, Some(&a)).unwrap();
662        let after = VaultMap::load(data.path());
663        assert_eq!(after.origin.as_deref(), Some(a.as_str()));
664        assert!(after.for_root("/w/payments").is_some());
665
666        // Previously on another Cloud: a scope of its own, dropped.
667        let data = tempfile::tempdir().unwrap();
668        map.save(data.path()).unwrap();
669        enter_scope(data.path(), &a, Some(&vault_scope(STAGING, "org_s"))).unwrap();
670        let after = VaultMap::load(data.path());
671        assert!(after.for_root("/w/payments").is_none());
672        assert!(after.vaults.is_empty());
673
674        // Unstamped: the previous scope, its account included.
675        let mut legacy = map.clone();
676        legacy.origin = None;
677        let data = tempfile::tempdir().unwrap();
678        legacy.save(data.path()).unwrap();
679        enter_scope(data.path(), &b, Some(&a)).unwrap();
680        let after = VaultMap::load(data.path());
681        assert!(after.for_root("/w/payments").is_none(), "not B's");
682        assert!(after.vaults.is_empty());
683    }
684
685    /// A disconnect that keeps local data stamps the Cloud and the account.
686    #[test]
687    fn vault_origin_disconnect_stamps_cloud_and_account() {
688        let a = vault_scope(PROD, "org_a");
689        let data = tempfile::tempdir().unwrap();
690        one_vault(data.path(), "v_a");
691        stamp_left_scope(data.path(), &a).unwrap();
692        assert_eq!(
693            VaultMap::load(data.path()).origin.as_deref(),
694            Some(a.as_str())
695        );
696
697        let data = tempfile::tempdir().unwrap();
698        let mut map = VaultMap::default();
699        map.vaults
700            .insert("s1".into(), record("v_a", &["/w/payments"]));
701        map.origin = Some(PROD.into());
702        map.save(data.path()).unwrap();
703        stamp_left_scope(data.path(), &a).unwrap();
704        assert_eq!(
705            VaultMap::load(data.path()).origin.as_deref(),
706            Some(a.as_str()),
707            "a Cloud-alone stamp gets the account"
708        );
709        stamp_left_scope(data.path(), &vault_scope(PROD, "org_b")).unwrap();
710        assert_eq!(
711            VaultMap::load(data.path()).origin.as_deref(),
712            Some(a.as_str())
713        );
714    }
715
716    /// "Stop sharing" of a checkout: the root leaves the record (the record
717    /// goes when no roots remain). A `parked` block that rc3-81 builds wrote
718    /// is ignored when read and dropped at the next save.
719    #[test]
720    fn vault_origin_forget_root_and_parked_records_of_rc3_81_builds() {
721        let mut map = VaultMap {
722            origin: Some(vault_scope(PROD, "org_a")),
723            ..Default::default()
724        };
725        map.vaults
726            .insert("s1".into(), record("v_1", &["/w/payments"]));
727        map.vaults
728            .insert("s2".into(), record("v_2", &["/w/shop", "/w/shop-2"]));
729        map.vaults.insert("s3".into(), record("v_3", &[]));
730
731        let forgotten = map.forget_root("/w/payments/").unwrap();
732        assert_eq!(forgotten, record("v_1", &["/w/payments"]), "as it was");
733        assert!(!map.vaults.contains_key("s1"), "no roots left: dropped");
734        assert!(map.vaults.contains_key("s3"), "other records stay");
735        assert!(map.for_root("/w/payments").is_none());
736
737        let forgotten = map.forget_root("/w/shop").unwrap();
738        assert_eq!(forgotten.vault_id, "v_2");
739        assert_eq!(map.vaults["s2"].roots, vec!["/w/shop-2".to_string()]);
740        assert_eq!(map.forget_root("/w/elsewhere"), None);
741
742        let data = tempfile::tempdir().unwrap();
743        let a = vault_scope(PROD, "org_a");
744        let b = vault_scope(PROD, "org_b");
745        let old = format!(
746            r#"{{"projects":{{"s1":{{"vault_id":"v_a","ns":"acme","name":"payments","sealed":false,"roots":["/w/payments"]}}}},"origin":"{a}","parked":{{"{b}":{{"s1":{{"vault_id":"v_b","ns":"acme","name":"payments","sealed":false,"roots":["/w/payments"]}}}}}}}}"#
747        );
748        std::fs::write(data.path().join("projects.json"), &old).unwrap();
749        let loaded = VaultMap::load(data.path());
750        assert_eq!(loaded.vaults["s1"].vault_id, "v_a", "still readable");
751        loaded.save(data.path()).unwrap();
752        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
753        assert!(!text.contains("parked") && !text.contains("v_b"), "{text}");
754    }
755}