Skip to main content

lean_ctx/core/
vault_map.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `<data_dir>/cloud/projects.json`: the vaults Cloud resolved for this machine's repositories
3//! and the local checkouts seen for each. Written when a checkout is resolved; read wherever a
4//! checkout's vault matters (bus, sync, and the per-vault policy floor).
5
6use std::collections::BTreeMap;
7use std::path::Path;
8
9use serde::{Deserialize, Serialize};
10
11use lean_ctx_protocol::cloud::vault::VaultV1;
12
13/// The file keeps its pre-VA name, like the field names in it: an older
14/// engine (downgrade, or a teammate's machine) still reads it.
15pub const VAULTS_FILE: &str = "projects.json";
16
17/// A vault as Cloud resolved it, plus the local checkouts seen for it.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct VaultRecord {
20    /// On disk as `project_id` (pre-VA name) for downgrades and mixed-version teams.
21    #[serde(rename = "project_id", alias = "vault_id")]
22    pub vault_id: String,
23    pub ns: String,
24    pub name: String,
25    /// Always `false` (sealed vaults are not supported); `projects.json`
26    /// carries the field.
27    pub sealed: bool,
28    #[serde(default)]
29    pub roots: Vec<String>,
30}
31
32/// `<data_dir>/cloud/projects.json`: stable identity → resolved vault.
33///
34/// A vault id is only valid on the Cloud and for the account (org) that
35/// resolved it (rc3-81; rc4-2/rc4-6 for an account switch on the same
36/// Cloud): the active records (`projects`) belong to the scope in `origin`
37/// ([`vault_scope`]: `<origin>#org=<org_id>`). A connect to another Cloud
38/// or account drops them (3.12.8 account scope: the enrollment removes the
39/// local Cloud data of another server or team, and [`VaultMap::use_scope`]
40/// applies the same rule to a map that is still there), so a connect
41/// elsewhere never shows or syncs them; a connect back resolves anew.
42///
43/// Who sets `origin`:
44/// - enrollment switches the map to the new Cloud and account
45///   ([`VaultMap::use_scope`]);
46/// - every write while connected stamps the map with the connected Cloud
47///   and account and refuses a map of another one ([`VaultMap::claim`]);
48/// - a disconnect that keeps the local data stamps the map with the Cloud
49///   and account it leaves, before their record is forgotten.
50///
51/// Readers that know the connected Cloud and account use
52/// [`VaultMap::for_scope`], which shows no records of another one (fail
53/// closed).
54///
55/// A stamp without an account (only dev builds of rc3-81 wrote one) matches
56/// no account (fail closed) until an enrollment resolves it to the account
57/// the machine was enrolled with on that Cloud ([`VaultMap::use_scope`]).
58///
59/// Downgrade: an older engine reads the file but drops `origin` when it
60/// saves it. The file is then unstamped again (the legacy rule of
61/// [`VaultMap::use_scope`] applies) until the next write of a newer engine
62/// stamps it with the connected scope. The `parked` records that rc3-81
63/// builds wrote are ignored when read and dropped at the next save.
64#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
65pub struct VaultMap {
66    /// On disk as `projects` (pre-VA name) for downgrades and mixed-version teams.
67    #[serde(default, rename = "projects", alias = "vaults")]
68    pub vaults: BTreeMap<String, VaultRecord>,
69    /// The scope (Cloud and account, [`vault_scope`]) `vaults` was resolved
70    /// in; the Cloud origin alone in a file stamped before accounts were
71    /// recorded; `None` in a file written before origins were recorded (see
72    /// [`VaultMap::use_scope`]).
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub origin: Option<String>,
75}
76
77impl VaultMap {
78    pub fn load(data_dir: &Path) -> Self {
79        std::fs::read(data_dir.join(VAULTS_FILE))
80            .ok()
81            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
82            .unwrap_or_default()
83    }
84
85    /// The vault of the local checkout `root`: the one recorded for it, else
86    /// (a linked git worktree never synced itself) the one of its main
87    /// checkout, which is the same repository.
88    pub fn for_root(&self, root: &str) -> Option<&VaultRecord> {
89        let find = |root: &str| {
90            self.vaults.values().find(|record| {
91                record
92                    .roots
93                    .iter()
94                    .any(|known| crate::core::pathutil::same_project(known, root))
95            })
96        };
97        find(root).or_else(|| {
98            let main = crate::core::git_worktree::main_worktree_root(Path::new(root))?;
99            find(&main.to_string_lossy())
100        })
101    }
102
103    pub fn save(&self, data_dir: &Path) -> std::io::Result<()> {
104        let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
105        crate::core::secure_fs::write_private(data_dir, VAULTS_FILE, &bytes)
106    }
107
108    /// Record a resolve answer for `stable`, remembering `root`.
109    pub fn record(&mut self, stable: &str, vault: &VaultV1, root: &Path) {
110        let root = root.to_string_lossy().into_owned();
111        let entry = self
112            .vaults
113            .entry(stable.to_string())
114            .or_insert_with(|| VaultRecord {
115                vault_id: vault.vault_id.clone(),
116                ns: vault.vault.ns.clone(),
117                name: vault.vault.name.clone(),
118                sealed: false,
119                roots: Vec::new(),
120            });
121        entry.vault_id.clone_from(&vault.vault_id);
122        entry.ns.clone_from(&vault.vault.ns);
123        entry.name.clone_from(&vault.vault.name);
124        entry.sealed = false;
125        if !entry.roots.contains(&root) {
126            entry.roots.push(root);
127        }
128    }
129
130    /// Stamp the map with `scope` ([`vault_scope`]), the Cloud and account
131    /// this machine is connected to while it writes: an unstamped map gets
132    /// it. `false` when the map belongs to another Cloud or account: the
133    /// caller records nothing (enrollment is the one switch).
134    pub fn claim(&mut self, scope: &str) -> bool {
135        match &self.origin {
136            None => {
137                self.origin = Some(stored_scope(scope));
138                true
139            }
140            Some(own) => same_scope(own, scope),
141        }
142    }
143
144    /// This map as the Cloud and account at `connected` ([`vault_scope`])
145    /// see it: without any records when they were resolved on another Cloud
146    /// or for another account (fail closed). A view for reading; never saved.
147    #[must_use]
148    pub fn for_scope(mut self, connected: &str) -> Self {
149        if !self.belongs_to(connected) {
150            self.vaults.clear();
151        }
152        self
153    }
154
155    /// [`Self::claim`] for the scope this machine was enrolled with until
156    /// now (at a disconnect): a stamp with that Cloud alone (dev builds of
157    /// rc3-81) was written for this account and gets it added.
158    pub fn claim_enrolled(&mut self, scope: &str) -> bool {
159        if let Some(own) = self.origin.as_deref()
160            && split_scope(own).1.is_none()
161            && same_origin(split_scope(own).0, split_scope(scope).0)
162        {
163            self.origin = Some(stored_scope(scope));
164            return true;
165        }
166        self.claim(scope)
167    }
168
169    /// Whether the active records may be used in `scope` ([`vault_scope`]):
170    /// the map is unstamped (written before scopes were recorded; every
171    /// enrollment stamps it, so it belongs to the scope this machine is
172    /// still connected to) or stamped with exactly that Cloud and account.
173    pub fn belongs_to(&self, scope: &str) -> bool {
174        self.origin
175            .as_deref()
176            .is_none_or(|own| same_scope(own, scope))
177    }
178
179    /// Make the map belong to the Cloud and account at `scope`
180    /// ([`vault_scope`]): the active records of another scope are dropped
181    /// (3.12.8 account scope; nothing is kept for a connect back). A file
182    /// without an origin (written before origins were recorded) counts as
183    /// resolved on `legacy_scope`, its account included (fail closed:
184    /// another account on the same Cloud is another scope). A file stamped
185    /// with a Cloud alone (only dev builds of rc3-81 wrote one) counts as
186    /// resolved for the account of `legacy_scope` when that names the same
187    /// Cloud, else as a scope of its own that no account matches. Returns
188    /// whether anything changed.
189    pub fn use_scope(&mut self, scope: &str, legacy_scope: &str) -> bool {
190        let current = match self.origin.as_deref() {
191            None => stored_scope(legacy_scope),
192            Some(own)
193                if split_scope(own).1.is_none()
194                    && same_origin(split_scope(own).0, split_scope(legacy_scope).0) =>
195            {
196                stored_scope(legacy_scope)
197            }
198            Some(own) => stored_scope(own),
199        };
200        if same_scope(&current, scope) {
201            let changed = self.origin.as_deref() != Some(current.as_str());
202            self.origin = Some(current);
203            return changed;
204        }
205        self.vaults.clear();
206        self.origin = Some(stored_scope(scope));
207        true
208    }
209
210    /// Forget the local checkout `root`: it leaves the record that lists it
211    /// (a record without roots left is dropped). Returns that record, as it
212    /// was before.
213    pub fn forget_root(&mut self, root: &str) -> Option<VaultRecord> {
214        let found = self
215            .vaults
216            .values()
217            .find(|record| {
218                record
219                    .roots
220                    .iter()
221                    .any(|known| crate::core::pathutil::same_project(known, root))
222            })
223            .cloned();
224        self.vaults.retain(|_, record| {
225            let before = record.roots.len();
226            record
227                .roots
228                .retain(|known| !crate::core::pathutil::same_project(known, root));
229            record.roots.len() == before || !record.roots.is_empty()
230        });
231        found
232    }
233}
234
235/// Separates the account from the Cloud origin in a scope.
236const ORG_MARK: &str = "#org=";
237
238/// The scope a vault id is valid in (rc3-81, rc4-2, rc4-6): the Cloud at
239/// `origin` and the account (org) `org_id` on it, as one string so
240/// `projects.json` keeps its shape (the `origin` field):
241/// `<origin>#org=<org_id>`, the origin normalized like `stored_origin`.
242/// An empty `org_id` gives the origin alone.
243pub fn vault_scope(origin: &str, org_id: &str) -> String {
244    let origin = stored_origin(origin);
245    match org_id.trim() {
246        "" => origin,
247        org => format!("{origin}{ORG_MARK}{org}"),
248    }
249}
250
251/// `(origin, org)` of a scope; a scope without an account (an origin as
252/// older code stamped it) has `None`.
253fn split_scope(scope: &str) -> (&str, Option<&str>) {
254    match scope.split_once(ORG_MARK) {
255        Some((origin, org)) if !org.trim().is_empty() => (origin, Some(org.trim())),
256        Some((origin, _)) => (origin, None),
257        None => (scope, None),
258    }
259}
260
261/// `scope` as the map stores it (see [`vault_scope`]).
262fn stored_scope(scope: &str) -> String {
263    let (origin, org) = split_scope(scope);
264    vault_scope(origin, org.unwrap_or(""))
265}
266
267/// Whether `a` and `b` are the same scope: the same Cloud (after
268/// `stored_origin`) and the same account (fail closed, rc3-81 bd 39791
269/// S2: a scope without an account matches only another without one).
270fn same_scope(a: &str, b: &str) -> bool {
271    let ((a_origin, a_org), (b_origin, b_org)) = (split_scope(a), split_scope(b));
272    same_origin(a_origin, b_origin) && a_org == b_org
273}
274
275/// `origin` as the map stores it: trimmed, without a trailing slash or the
276/// default https port, lower case. Origins come normalized from the
277/// connect path; this keeps a hand-edited or older spelling comparable.
278fn stored_origin(origin: &str) -> String {
279    let origin = origin.trim().trim_end_matches('/').to_ascii_lowercase();
280    match origin.strip_suffix(":443") {
281        Some(bare) if bare.starts_with("https://") => bare.to_string(),
282        _ => origin,
283    }
284}
285
286/// Whether `a` and `b` name the same Cloud, after `stored_origin`.
287fn same_origin(a: &str, b: &str) -> bool {
288    lean_ctx_protocol::cloud::same_cloud_origin(&stored_origin(a), &stored_origin(b))
289}