lean-ctx-cloud 3.12.12

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// SPDX-License-Identifier: Apache-2.0
//! Repository identity and the local map of resolved Cloud vaults.
//!
//! The identity Cloud sees is `stable_identity(project_identity(root))`
//! salted by the org (`identity_digest`). It is the same for every checkout
//! of a repository on every machine (`.lean-ctx-id` > git origin >
//! manifests) and never contains a path, user name or credential.

use std::path::Path;

use hmac::{Hmac, KeyInit as _, Mac as _};
use sha2::Sha256;

use super::CloudError;
use super::link::read_link;
use lean_ctx_protocol::cloud::vault::{
    VAULT_RESOLVE_REQUEST_SCHEMA, VaultResolveRequestV1, stable_identity,
};

pub use lean_ctx::core::vault_map::{VaultMap, VaultRecord, vault_scope};

/// `github.com/acme/payments` for every spelling of the same remote:
/// scheme, credentials, `.git` suffix, scp syntax and host case removed.
pub fn normalize_git_url(url: &str) -> String {
    let url = url.trim();
    let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    // Credentials sit in the authority only (before the first `/`).
    let authority_end = without_scheme.find('/').unwrap_or(without_scheme.len());
    let without_user = without_scheme[..authority_end]
        .rfind('@')
        .map_or(without_scheme, |at| &without_scheme[at + 1..]);
    // scp-like `host:org/repo` (no port digits right after the colon)
    let path_form = match without_user.split_once(':') {
        Some((host, rest)) if !rest.starts_with(|c: char| c.is_ascii_digit()) => {
            format!("{host}/{rest}")
        }
        Some((host, rest)) => {
            let rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
            format!("{host}{rest}")
        }
        None => without_user.to_string(),
    };
    let trimmed = path_form.trim_end_matches('/');
    let trimmed = trimmed.strip_suffix(".git").unwrap_or(trimmed);
    match trimmed.split_once('/') {
        Some((host, path)) => format!("{}/{path}", host.to_ascii_lowercase()),
        None => trimmed.to_ascii_lowercase(),
    }
}

/// The machine-independent identity of the project at `root`, if it has one.
///
/// A `.lean-ctx-id` that `cloud link` wrote ([`link_made_id`]) gives way to
/// the git origin: earlier engines wrote one per checkout, so two checkouts
/// of one origin had two identities and two vaults. Without an origin the
/// id stays the identity; a hand-written id (a name) always does.
pub fn project_identity(root: &Path) -> Option<String> {
    let root_str = root.to_string_lossy();
    let mut identity = lean_ctx::core::project_hash::project_identity(&root_str)?;
    if let Some(id) = identity.strip_prefix("explicit:")
        && link_made_id(id)
        && let Some(origin) = lean_ctx::core::project_hash::origin_identity(&root_str)
    {
        identity = origin;
    }
    Some(match identity.strip_prefix("git:") {
        Some(url) => format!("git:{}", normalize_git_url(url)),
        None => identity,
    })
}

/// Whether a `.lean-ctx-id` value has the shape `cloud link` writes: 32
/// lowercase hex characters (16 random bytes).
pub fn link_made_id(id: &str) -> bool {
    id.len() == 32
        && id
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// `hex(HMAC-SHA256(org_salt, stable_identity))`.
pub fn identity_digest(salt: &[u8], stable: &str) -> String {
    let mut mac = Hmac::<Sha256>::new_from_slice(salt).expect("HMAC takes any key length");
    mac.update(stable.as_bytes());
    hex::encode(mac.finalize().into_bytes())
}

/// The resolve request for the project at `root`.
pub fn resolve_request(
    root: &Path,
    org_salt_id: &str,
    salt: &[u8],
    with_label: bool,
) -> Result<(String, VaultResolveRequestV1), CloudError> {
    let identity = project_identity(root).ok_or_else(|| {
        CloudError::Config(format!(
            "{} has no stable identity (no git origin or manifest); run `lean-ctx cloud link <workspace>/<vault>` there",
            root.display()
        ))
    })?;
    let stable = stable_identity(&identity);
    let label = with_label
        .then(|| {
            root.file_name()
                .map(|n| n.to_string_lossy().chars().take(64).collect::<String>())
        })
        .flatten()
        .filter(|l: &String| !l.trim().is_empty() && !l.chars().any(char::is_control));
    let request = VaultResolveRequestV1 {
        schema: VAULT_RESOLVE_REQUEST_SCHEMA.into(),
        org_salt_id: org_salt_id.into(),
        identity_digest: identity_digest(salt, &stable),
        label,
        vault: read_link(root)?.map(|link| link.vault),
    };
    Ok((stable, request))
}

/// Load, change and save `projects.json` at `data_dir` under its state lock
/// (rc3-81 S2), so a sync that resolves a checkout and an enrollment that
/// switches the Cloud never write over each other. The file is written only
/// when `change` changed the map; the lock is held for local file work only.
pub fn update_map<R>(
    data_dir: &Path,
    change: impl FnOnce(&mut VaultMap) -> R,
) -> Result<(R, VaultMap), CloudError> {
    let _lock = super::state::lock_state(data_dir, lean_ctx::core::vault_map::VAULTS_FILE)?;
    let before = VaultMap::load(data_dir);
    let mut map = before.clone();
    let out = change(&mut map);
    if map != before {
        map.save(data_dir)
            .map_err(|e| CloudError::Local(format!("save the vault map: {e}")))?;
    }
    Ok((out, map))
}

/// The vault map of the store as the connected Cloud and account see it
/// ([`VaultMap::for_scope`]): no records of another Cloud or account
/// (rc3-81 S1, rc4-2).
/// Not connected: the map as it is on disk.
pub fn connected_map(store: &super::state::CloudStore) -> VaultMap {
    for_connected(store, VaultMap::load(store.data_dir()))
}

/// [`connected_map`] for a `map` already loaded from the store.
pub fn for_connected(store: &super::state::CloudStore, map: VaultMap) -> VaultMap {
    in_scope(map, connected_scope(store).as_deref())
}

/// The scope ([`vault_scope`]) the store is connected to: `None` when it is
/// not connected; an unreadable instance record gives a scope no stamped
/// map matches (fail closed).
pub fn connected_scope(store: &super::state::CloudStore) -> Option<String> {
    match store.instance() {
        Ok(Some(instance)) => Some(instance.vault_scope()),
        Err(_) => Some(String::new()),
        Ok(None) => None,
    }
}

/// `map` as `scope` sees it ([`VaultMap::for_scope`]); `None` (not
/// connected) leaves it as it is.
pub fn in_scope(map: VaultMap, scope: Option<&str>) -> VaultMap {
    match scope {
        Some(scope) => map.for_scope(scope),
        None => map,
    }
}

/// The vault map as the Cloud and account at `scope` ([`vault_scope`]) see
/// it, `None` when it belongs to another one (an enrollment elsewhere since
/// the caller's session was loaded). A sender then sends nothing and keeps
/// its queue for the scope it was queued in (rc3-81, bd 39791 M1/M2).
pub fn map_in(data_dir: &Path, scope: &str) -> Option<VaultMap> {
    let map = VaultMap::load(data_dir);
    map.belongs_to(scope).then_some(map)
}

/// Put the records of the checkout `root` back as they were in `snapshot`
/// (the map before a change that was refused), under one hold of the map's
/// lock, and only while the map on disk and the snapshot belong to `scope`,
/// the Cloud and account the snapshot was taken for (rc3-81, bd 39540 S-a,
/// bd 39791 S1): records of other checkouts and an enrollment elsewhere
/// since then are left as they are. Returns whether it was put back.
pub fn restore_root(
    data_dir: &Path,
    snapshot: &VaultMap,
    root: &str,
    scope: &str,
) -> Result<bool, CloudError> {
    let same = |known: &String| lean_ctx::core::pathutil::same_project(known, root);
    let (restored, _) = update_map(data_dir, |map| {
        if !(map.belongs_to(scope) && snapshot.belongs_to(scope)) {
            return false;
        }
        map.claim(scope);
        map.vaults.retain(|_, record| {
            let before = record.roots.len();
            record.roots.retain(|known| !same(known));
            record.roots.len() == before || !record.roots.is_empty()
        });
        for (stable, was) in &snapshot.vaults {
            let roots: Vec<String> = was.roots.iter().filter(|r| same(r)).cloned().collect();
            if roots.is_empty() {
                continue;
            }
            // The record as it was, also over one a concurrent sync wrote
            // under the same key meanwhile (its other roots are kept).
            let entry = map
                .vaults
                .entry(stable.clone())
                .or_insert_with(|| VaultRecord {
                    roots: Vec::new(),
                    ..was.clone()
                });
            entry.vault_id.clone_from(&was.vault_id);
            entry.ns.clone_from(&was.ns);
            entry.name.clone_from(&was.name);
            entry.sealed = was.sealed;
            for known in roots {
                if !entry.roots.contains(&known) {
                    entry.roots.push(known);
                }
            }
        }
        true
    })?;
    Ok(restored)
}

/// At enrollment with the Cloud and account at `scope`
/// ([`lean_ctx::core::vault_map::vault_scope`]; rc3-81, rc4-2, rc4-6): only
/// the vaults resolved there stay in `projects.json`; those of another
/// Cloud or account are dropped (3.12.8 account scope: the enrollment has
/// already removed the local Cloud data of another server or team). A file
/// without an origin counts as resolved on `previous` (the scope this
/// machine was enrolled with until now), else on the hosted Cloud, like a
/// link file without a server, the account of `previous` included; a file
/// stamped with a Cloud alone counts as resolved for the account of
/// `previous` on that Cloud, else as a scope no account matches (fail
/// closed, bd 39791 S2). Since every write
/// while connected and every disconnect that keeps local data stamp the
/// file, only a file written before origins were recorded (or saved again
/// by an older engine) is unstamped. A missing or unreadable file is left as
/// it is.
pub(crate) fn enter_scope(
    data_dir: &Path,
    scope: &str,
    previous: Option<&str>,
) -> Result<(), CloudError> {
    let legacy = previous.unwrap_or(lean_ctx_protocol::cloud::CLOUD_DEFAULT_URL);
    update_map(data_dir, |map| {
        if !map.vaults.is_empty() {
            map.use_scope(scope, legacy);
        }
    })?;
    Ok(())
}

/// At a disconnect that keeps the local data: stamp the map with `scope`,
/// the Cloud and account being left, before their record is forgotten, so
/// a later connect elsewhere drops these records instead of guessing
/// (rc3-81, rc4-2). A map stamped with that Cloud alone gets the account
/// added (it was written while enrolled with it); one of another Cloud or
/// account is not changed.
pub(crate) fn stamp_left_scope(data_dir: &Path, scope: &str) -> Result<(), CloudError> {
    if !data_dir
        .join(lean_ctx::core::vault_map::VAULTS_FILE)
        .is_file()
    {
        return Ok(());
    }
    update_map(data_dir, |map| {
        if !map.vaults.is_empty() {
            map.claim_enrolled(scope);
        }
    })?;
    Ok(())
}

/// Round trip of a local Cloud file across the VA rename. `T` reads `old`
/// (the file as an engine before the rename wrote it) and the same file
/// with `old_key` spelled `new_key`; what `T` writes keeps `old_key`, so
/// `Old` (the struct definition of the engine before the rename) reads it.
#[cfg(test)]
pub(crate) fn assert_pre_va_round_trip<T, Old>(old: &str, old_key: &str, new_key: &str) -> T
where
    T: serde::Serialize + serde::de::DeserializeOwned,
    Old: serde::de::DeserializeOwned,
{
    let (old_key, new_key) = (format!("\"{old_key}\""), format!("\"{new_key}\""));
    let read: T = serde_json::from_str(old).expect("reads the pre-VA form");
    let written = serde_json::to_string(&read).expect("writes");
    assert!(
        written.contains(&old_key) && !written.contains(&new_key),
        "{written}"
    );
    serde_json::from_str::<Old>(&written).expect("an engine before the rename reads it");
    serde_json::from_str::<T>(&old.replace(&old_key, &new_key)).expect("reads the new spelling");
    read
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    use serde::Deserialize;

    #[test]
    fn git_urls_lose_credentials_and_spelling() {
        let expected = "github.com/acme/payments";
        for url in [
            "https://github.com/acme/payments.git",
            concat!("https://ci-bot:gh", "p_secret123@github.com/acme/payments"),
            "git@github.com:acme/payments.git",
            "ssh://git@GitHub.com/acme/payments/",
            "ssh://git@github.com:22/acme/payments.git",
        ] {
            assert_eq!(normalize_git_url(url), expected, "{url}");
        }
        assert_eq!(
            normalize_git_url("https://github.com/acme/pkg@v1"),
            "github.com/acme/pkg@v1",
            "an @ in the path is not a credential"
        );
    }

    #[test]
    fn the_identity_is_the_same_for_every_checkout() {
        let a = tempfile::tempdir().unwrap();
        let b = tempfile::tempdir().unwrap();
        for (dir, url) in [
            (a.path(), "https://user:token@github.com/acme/payments.git"),
            (b.path(), "git@github.com:acme/payments.git"),
        ] {
            std::fs::create_dir_all(dir.join(".git")).unwrap();
            std::fs::write(
                dir.join(".git/config"),
                format!("[remote \"origin\"]\n\turl = {url}\n"),
            )
            .unwrap();
        }
        let ia = project_identity(a.path()).unwrap();
        assert_eq!(ia, project_identity(b.path()).unwrap());
        assert!(!ia.contains("token") && !ia.contains("user"));
        let (stable, request) = resolve_request(a.path(), "salt_1", &[0x0a; 32], false).unwrap();
        assert_eq!(stable, stable_identity("git:github.com/acme/payments"));
        assert!(request.validate().is_ok());
        assert!(request.label.is_none());
    }

    #[test]
    fn a_linked_worktree_finds_the_vault_of_its_main_checkout() {
        let base = tempfile::tempdir().unwrap();
        let (main, wt) = super::super::link::worktree_layout(base.path());
        let other = base.path().join("other");
        std::fs::create_dir_all(&other).unwrap();
        let mut map = VaultMap::default();
        map.vaults.insert(
            "s1".into(),
            VaultRecord {
                vault_id: "v1".into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec![main.to_string_lossy().into_owned()],
            },
        );
        let found = |root: &Path| {
            map.for_root(&root.to_string_lossy())
                .map(|r| r.vault_id.clone())
        };
        assert_eq!(found(&main).as_deref(), Some("v1"));
        assert_eq!(found(&wt).as_deref(), Some("v1"), "the worktree");
        assert_eq!(found(&other), None, "an unrelated directory");
    }

    /// `ProjectMap`/`ProjectRecord` of the engine before the VA rename.
    #[derive(Deserialize)]
    struct PreVaMap {
        #[allow(dead_code)]
        projects: BTreeMap<String, PreVaRecord>,
    }
    #[derive(Deserialize)]
    #[allow(dead_code)]
    struct PreVaRecord {
        project_id: String,
        ns: String,
        name: String,
        sealed: bool,
        #[serde(default)]
        roots: Vec<String>,
    }

    #[test]
    fn the_vault_map_stays_in_projects_json_with_pre_va_names() {
        let vault_id = "3f6c1e9a0b7d4c2e8f5a1b6c9d0e7f42";
        let old = format!(
            r#"{{"projects":{{"s1":{{"project_id":"{vault_id}","ns":"acme","name":"payments","sealed":true,"roots":["/w/payments"]}}}}}}"#
        );
        let map: VaultMap =
            assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "project_id", "vault_id");
        assert_pre_va_round_trip::<VaultMap, PreVaMap>(&old, "projects", "vaults");
        let record = &map.vaults["s1"];
        assert_eq!((record.vault_id.as_str(), record.sealed), (vault_id, true));

        let data = tempfile::tempdir().unwrap();
        std::fs::write(data.path().join("projects.json"), &old).unwrap();
        let loaded = VaultMap::load(data.path());
        assert_eq!(loaded, map);
        loaded.save(data.path()).unwrap();
        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
        serde_json::from_str::<PreVaMap>(&text).expect("an engine before the rename reads it");
        assert!(!data.path().join("vaults.json").exists());
    }

    const STAGING: &str = "https://cloud-staging.leanctx.com";

    fn one_vault(data: &Path, vault_id: &str) {
        let mut map = VaultMap::default();
        map.vaults.insert(
            "s1".into(),
            VaultRecord {
                vault_id: vault_id.into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec!["/w/payments".into()],
            },
        );
        map.save(data).unwrap();
    }

    /// rc3-81 legacy rule: a file without an origin belongs to the Cloud the
    /// machine was enrolled with until now, else to the hosted Cloud.
    #[test]
    fn vault_origin_legacy_file_belongs_to_the_previous_or_hosted_cloud() {
        let data = tempfile::tempdir().unwrap();
        one_vault(data.path(), "v_staging");
        enter_scope(data.path(), STAGING, Some(STAGING)).unwrap();
        let map = VaultMap::load(data.path());
        assert_eq!(map.origin.as_deref(), Some(STAGING), "stamped");
        assert!(map.for_root("/w/payments").is_some(), "kept on its Cloud");

        let data = tempfile::tempdir().unwrap();
        one_vault(data.path(), "v_prod");
        enter_scope(data.path(), STAGING, None).unwrap();
        let map = VaultMap::load(data.path());
        assert!(map.for_root("/w/payments").is_none(), "not on staging");
        assert_eq!(map.origin.as_deref(), Some(STAGING));
        // Gone for good: back on the hosted Cloud nothing comes back.
        enter_scope(data.path(), "https://cloud.leanctx.com/", None).unwrap();
        let map = VaultMap::load(data.path());
        assert!(
            map.for_root("/w/payments").is_none(),
            "gone after the switch"
        );

        // The hosted Cloud under any spelling is the same scope (here
        // without an account; real enrollments always carry one).
        let data = tempfile::tempdir().unwrap();
        one_vault(data.path(), "v_prod");
        enter_scope(data.path(), "https://Cloud.leanctx.com:443/", None).unwrap();
        let map = VaultMap::load(data.path());
        assert_eq!(map.for_root("/w/payments").unwrap().vault_id, "v_prod");
        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
        serde_json::from_str::<PreVaMap>(&text).expect("an older engine still reads it");
    }

    /// Records resolved on one Cloud are never seen on another, and a
    /// switch drops them; nothing is written for a machine without a map.
    #[test]
    fn vault_origin_records_of_each_cloud_stay_apart() {
        let data = tempfile::tempdir().unwrap();
        enter_scope(data.path(), STAGING, None).unwrap();
        assert!(!data.path().join("projects.json").exists());

        one_vault(data.path(), "v_prod");
        enter_scope(data.path(), STAGING, None).unwrap();
        let mut map = VaultMap::load(data.path());
        map.vaults.insert(
            "s1".into(),
            VaultRecord {
                vault_id: "v_staging".into(),
                ns: "acme".into(),
                name: "payments".into(),
                sealed: false,
                roots: vec!["/w/payments".into()],
            },
        );
        map.save(data.path()).unwrap();
        let vault_on = |origin: &str| {
            enter_scope(data.path(), origin, None).unwrap();
            VaultMap::load(data.path())
                .for_root("/w/payments")
                .map(|r| r.vault_id.clone())
        };
        assert_eq!(vault_on(STAGING).as_deref(), Some("v_staging"));
        assert_eq!(vault_on("https://cloud.leanctx.com").as_deref(), None);
        assert_eq!(vault_on("https://cloud.example").as_deref(), None);
        assert_eq!(vault_on(STAGING).as_deref(), None, "gone after the switch");
    }

    /// rc3-81 review S1/M1/N2: a write while connected stamps an unstamped
    /// map and is refused on a map of another Cloud; a reader that knows the
    /// connected Cloud sees no records of another one; origins compare
    /// after normalization (case, trailing slash, `:443`).
    #[test]
    fn vault_origin_writers_claim_and_readers_fail_closed() {
        let data = tempfile::tempdir().unwrap();
        one_vault(data.path(), "v_staging");
        let (claimed, map) = update_map(data.path(), |map| {
            map.claim("https://Cloud-Staging.leanctx.com:443/")
        })
        .unwrap();
        assert!(claimed);
        assert_eq!(map.origin.as_deref(), Some(STAGING), "stored normalized");
        assert_eq!(VaultMap::load(data.path()), map, "saved under the lock");

        let (claimed, _) = update_map(data.path(), |map| {
            let claimed = map.claim("https://cloud.leanctx.com");
            if claimed {
                map.vaults.clear();
            }
            claimed
        })
        .unwrap();
        assert!(!claimed, "a map of another Cloud is not written to");
        let map = VaultMap::load(data.path());
        assert_eq!(map.vaults["s1"].vault_id, "v_staging");

        assert!(
            map.clone()
                .for_scope("https://cloud.leanctx.com")
                .for_root("/w/payments")
                .is_none(),
            "fail closed for another Cloud"
        );
        assert!(
            map.for_scope(&format!("{STAGING}/"))
                .for_root("/w/payments")
                .is_some()
        );
        let mut unstamped = VaultMap::load(data.path());
        unstamped.origin = None;
        assert!(
            unstamped
                .for_scope("https://cloud.leanctx.com")
                .for_root("/w/payments")
                .is_some(),
            "an unstamped map is left to the enrollment rule"
        );
    }

    /// rc3-81 review M1: a disconnect that keeps local data stamps the map
    /// with the Cloud being left; an already stamped one is not changed.
    #[test]
    fn vault_origin_disconnect_stamps_the_cloud_it_leaves() {
        let data = tempfile::tempdir().unwrap();
        stamp_left_scope(data.path(), STAGING).unwrap();
        assert!(!data.path().join("projects.json").exists());
        one_vault(data.path(), "v_staging");
        stamp_left_scope(data.path(), STAGING).unwrap();
        assert_eq!(VaultMap::load(data.path()).origin.as_deref(), Some(STAGING));
        stamp_left_scope(data.path(), "https://cloud.leanctx.com").unwrap();
        assert_eq!(VaultMap::load(data.path()).origin.as_deref(), Some(STAGING));
    }

    const PROD: &str = "https://cloud.leanctx.com";

    fn record(vault_id: &str, roots: &[&str]) -> VaultRecord {
        VaultRecord {
            vault_id: vault_id.into(),
            ns: "acme".into(),
            name: "payments".into(),
            sealed: false,
            roots: roots.iter().map(|root| (*root).to_string()).collect(),
        }
    }

    /// rc4-2/rc4-6: vault ids are per account. A switch from account A to
    /// account B on the same Cloud drops A's records (B sees none of them),
    /// and a switch back to A finds none of B's.
    #[test]
    fn vault_origin_account_switch_on_the_same_cloud_drops_the_records() {
        let data = tempfile::tempdir().unwrap();
        let (a, b) = (vault_scope(PROD, "org_a"), vault_scope(PROD, "org_b"));
        assert_eq!(a, "https://cloud.leanctx.com#org=org_a");
        assert_eq!(vault_scope("https://Cloud.leanctx.com:443/", " org_a "), a);
        assert_eq!(vault_scope(PROD, ""), PROD, "no account: the origin alone");

        update_map(data.path(), |map| {
            assert!(map.claim(&a));
            map.vaults
                .insert("s1".into(), record("v_a", &["/w/payments"]));
        })
        .unwrap();
        let vault_of = |map: VaultMap| map.for_root("/w/payments").map(|r| r.vault_id.clone());

        enter_scope(data.path(), &b, Some(&a)).unwrap();
        let map = VaultMap::load(data.path());
        assert_eq!(map.origin.as_deref(), Some(b.as_str()));
        assert_eq!(vault_of(map.clone()), None, "B sees none of A's records");
        assert!(map.vaults.is_empty(), "A's records dropped");
        assert_eq!(vault_of(map.clone().for_scope(&b)), None);

        // A stale reader for A sees nothing of B's map; a write for A is refused.
        let (claimed, _) = update_map(data.path(), |map| map.claim(&a)).unwrap();
        assert!(!claimed, "a map of another account is not written to");

        update_map(data.path(), |map| {
            assert!(map.claim(&b));
            map.vaults
                .insert("s1".into(), record("v_b", &["/w/payments"]));
        })
        .unwrap();
        enter_scope(data.path(), &a, Some(&b)).unwrap();
        let map = VaultMap::load(data.path());
        assert_eq!(map.origin.as_deref(), Some(a.as_str()));
        assert_eq!(vault_of(map.clone()), None, "A sees none of B's records");
        assert!(map.vaults.is_empty(), "B's records dropped");
        assert_eq!(vault_of(map.for_scope(&b)), None, "fail closed for B");
    }

    /// rc3-81 bd 39791 S2 (fail closed): a map stamped with a Cloud alone
    /// (dev builds of rc3-81) matches no account until an enrollment
    /// resolves it: to the account the machine was enrolled with on that
    /// Cloud, never to another one. An unstamped map belongs to the
    /// previous scope including its account.
    #[test]
    fn vault_origin_origin_only_stamp_belongs_only_to_the_legacy_account() {
        let (a, b) = (vault_scope(PROD, "org_a"), vault_scope(PROD, "org_b"));
        let mut map = VaultMap::default();
        map.vaults
            .insert("s1".into(), record("v_1", &["/w/payments"]));
        map.origin = Some(format!("{PROD}/"));
        for scope in [&a, &b, &vault_scope(STAGING, "org_a")] {
            assert!(
                map.clone()
                    .for_scope(scope)
                    .for_root("/w/payments")
                    .is_none(),
                "{scope}"
            );
            assert!(!map.clone().claim(scope), "{scope}");
        }

        // Enrolled with B, previously A on that Cloud: the records are A's.
        let data = tempfile::tempdir().unwrap();
        map.save(data.path()).unwrap();
        enter_scope(data.path(), &b, Some(&a)).unwrap();
        let after = VaultMap::load(data.path());
        assert!(after.for_root("/w/payments").is_none(), "A's: dropped");
        assert_eq!(after.origin.as_deref(), Some(b.as_str()));

        // Enrolled again with A: they are A's and stay active, stamped.
        let data = tempfile::tempdir().unwrap();
        map.save(data.path()).unwrap();
        enter_scope(data.path(), &a, Some(&a)).unwrap();
        let after = VaultMap::load(data.path());
        assert_eq!(after.origin.as_deref(), Some(a.as_str()));
        assert!(after.for_root("/w/payments").is_some());

        // Previously on another Cloud: a scope of its own, dropped.
        let data = tempfile::tempdir().unwrap();
        map.save(data.path()).unwrap();
        enter_scope(data.path(), &a, Some(&vault_scope(STAGING, "org_s"))).unwrap();
        let after = VaultMap::load(data.path());
        assert!(after.for_root("/w/payments").is_none());
        assert!(after.vaults.is_empty());

        // Unstamped: the previous scope, its account included.
        let mut legacy = map.clone();
        legacy.origin = None;
        let data = tempfile::tempdir().unwrap();
        legacy.save(data.path()).unwrap();
        enter_scope(data.path(), &b, Some(&a)).unwrap();
        let after = VaultMap::load(data.path());
        assert!(after.for_root("/w/payments").is_none(), "not B's");
        assert!(after.vaults.is_empty());
    }

    /// A disconnect that keeps local data stamps the Cloud and the account.
    #[test]
    fn vault_origin_disconnect_stamps_cloud_and_account() {
        let a = vault_scope(PROD, "org_a");
        let data = tempfile::tempdir().unwrap();
        one_vault(data.path(), "v_a");
        stamp_left_scope(data.path(), &a).unwrap();
        assert_eq!(
            VaultMap::load(data.path()).origin.as_deref(),
            Some(a.as_str())
        );

        let data = tempfile::tempdir().unwrap();
        let mut map = VaultMap::default();
        map.vaults
            .insert("s1".into(), record("v_a", &["/w/payments"]));
        map.origin = Some(PROD.into());
        map.save(data.path()).unwrap();
        stamp_left_scope(data.path(), &a).unwrap();
        assert_eq!(
            VaultMap::load(data.path()).origin.as_deref(),
            Some(a.as_str()),
            "a Cloud-alone stamp gets the account"
        );
        stamp_left_scope(data.path(), &vault_scope(PROD, "org_b")).unwrap();
        assert_eq!(
            VaultMap::load(data.path()).origin.as_deref(),
            Some(a.as_str())
        );
    }

    /// "Stop sharing" of a checkout: the root leaves the record (the record
    /// goes when no roots remain). A `parked` block that rc3-81 builds wrote
    /// is ignored when read and dropped at the next save.
    #[test]
    fn vault_origin_forget_root_and_parked_records_of_rc3_81_builds() {
        let mut map = VaultMap {
            origin: Some(vault_scope(PROD, "org_a")),
            ..Default::default()
        };
        map.vaults
            .insert("s1".into(), record("v_1", &["/w/payments"]));
        map.vaults
            .insert("s2".into(), record("v_2", &["/w/shop", "/w/shop-2"]));
        map.vaults.insert("s3".into(), record("v_3", &[]));

        let forgotten = map.forget_root("/w/payments/").unwrap();
        assert_eq!(forgotten, record("v_1", &["/w/payments"]), "as it was");
        assert!(!map.vaults.contains_key("s1"), "no roots left: dropped");
        assert!(map.vaults.contains_key("s3"), "other records stay");
        assert!(map.for_root("/w/payments").is_none());

        let forgotten = map.forget_root("/w/shop").unwrap();
        assert_eq!(forgotten.vault_id, "v_2");
        assert_eq!(map.vaults["s2"].roots, vec!["/w/shop-2".to_string()]);
        assert_eq!(map.forget_root("/w/elsewhere"), None);

        let data = tempfile::tempdir().unwrap();
        let a = vault_scope(PROD, "org_a");
        let b = vault_scope(PROD, "org_b");
        let old = format!(
            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"]}}}}}}}}"#
        );
        std::fs::write(data.path().join("projects.json"), &old).unwrap();
        let loaded = VaultMap::load(data.path());
        assert_eq!(loaded.vaults["s1"].vault_id, "v_a", "still readable");
        loaded.save(data.path()).unwrap();
        let text = std::fs::read_to_string(data.path().join("projects.json")).unwrap();
        assert!(!text.contains("parked") && !text.contains("v_b"), "{text}");
    }
}