Skip to main content

lean_ctx_cloud/
state.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Durable Cloud state on this machine.
3//!
4//! `<config_dir>/cloud/` (directory 0700, files 0600, written atomically):
5//! `instance.key`, `kx.key`, `instance.json`, `lease.json` (re-verified on
6//! every load), `keys.json`, `token.json` (never logged).
7//! `<data_dir>/cloud/`: `activity.json` and, with later packages, project
8//! maps, cursors and the outbox.
9
10use std::collections::BTreeMap;
11use std::fmt;
12use std::path::{Path, PathBuf};
13
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18use super::CloudError;
19
20pub(crate) const INSTANCE_KEY_FILE: &str = "instance.key";
21pub(crate) const KX_KEY_FILE: &str = "kx.key";
22pub(crate) const INSTANCE_FILE: &str = "instance.json";
23pub(crate) const LEASE_FILE: &str = "lease.json";
24pub(crate) const KEYS_FILE: &str = "keys.json";
25pub(crate) const TOKEN_FILE: &str = "token.json";
26pub(crate) const ACTIVITY_FILE: &str = "activity.json";
27/// The person's sharing answer at connect (`super::connect`).
28pub(crate) const SHARING_FILE: &str = "sharing.json";
29/// When the enrolled Cloud last answered that it has no match route
30/// (`super::mapping`).
31pub(crate) const MATCH_FILE: &str = "vault-match.json";
32/// Who `<data>/cloud` belongs to (3.12.8 account scope, [`DataScope`]).
33pub(crate) const SCOPE_FILE: &str = "scope.json";
34
35/// Every entry of `<config>/cloud` (rc4-274). In a single-dir layout (a
36/// legacy `~/.lean-ctx`, a custom `LEAN_CTX_DATA_DIR`) `<config>/cloud` and
37/// `<data>/cloud` are one directory: removing the data there keeps these,
38/// with their `.damaged-<n>` copies and in-flight temporary files. Every
39/// name written through [`CloudStore::write_config`] must be listed (checked
40/// in debug builds); an entry not listed counts as data and is removed.
41const CONFIG_ENTRIES: &[&str] = &[
42    INSTANCE_KEY_FILE,
43    KX_KEY_FILE,
44    INSTANCE_FILE,
45    LEASE_FILE,
46    KEYS_FILE,
47    TOKEN_FILE,
48    SHARING_FILE,
49    MATCH_FILE,
50    super::keyset_v3::KEYS_V3_FILE,
51    super::root_cert::CERT_FILE,
52    super::revoked::REVOKED_FILE,
53    super::disconnect::PENDING_FILE,
54    super::session_ref::CAPABILITIES_FILE,
55    super::company_bound::FILE,
56    super::bus::relay_v2::PROTOCOL_FILE,
57    super::consent::chat_key::CHAT_KEY_FILE,
58    super::consent::optin_key::OPTIN_KEY_FILE,
59    super::consent::task_key::TASK_KEY_FILE,
60    super::consent::broker::PRESENCE_KEY_FILE,
61    super::consent::broker::ACCOUNT_FILE,
62    super::consent::broker::KEY_FILE,
63    super::consent::broker::DIR,
64    // `replica::crypt::master_key`: the replica master key, when no
65    // keychain holds it.
66    "replica.key",
67];
68
69/// `bring_local` ledgers, one per checkout: `bring-local-<hash>.json`.
70const CONFIG_PREFIX_BRING_LOCAL: &str = "bring-local-";
71
72/// Whether `name`, an entry of `<config>/cloud`, belongs to the config
73/// (rc4-274). Lock files always do: a lock file removed while held no
74/// longer orders anything, and an empty lock of the data costs nothing.
75fn is_config_entry(name: &str) -> bool {
76    if Path::new(name).extension().is_some_and(|ext| ext == "lock") {
77        return true;
78    }
79    let base = name
80        .strip_prefix('.')
81        .and_then(|n| n.split_once(".tmp."))
82        .map_or(name, |(base, _)| base);
83    let base = base.split_once(".damaged-").map_or(base, |(base, _)| base);
84    CONFIG_ENTRIES.contains(&base) || base.starts_with(CONFIG_PREFIX_BRING_LOCAL)
85}
86
87/// The enrolled instance.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89pub struct InstanceRecord {
90    pub instance_id: String,
91    pub org_id: String,
92    pub org_name: String,
93    pub label: String,
94    /// Origin the instance is enrolled with.
95    pub url: String,
96    pub org_salt_id: String,
97    pub enrolled_at: String,
98    /// Origin of the Cloud web app, when enrollment named one (1.3).
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub web_url: Option<String>,
101    /// `personal` | `team`, when enrollment named it (Cloud C line).
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub org_kind: Option<String>,
104    /// The company the team belongs to, when enrollment named one.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub company_name: Option<String>,
107}
108
109impl InstanceRecord {
110    /// Where the instance is enrolled, as people read it (owner decision
111    /// 26.10.: Personal, Team, Company): `Company Acme · Team Platform`,
112    /// `Team Platform`, `Personal (Ada)`; an older server's record keeps
113    /// the plain name.
114    pub fn workspace_label(&self) -> String {
115        let name = &self.org_name;
116        match (self.company_name.as_deref(), self.org_kind.as_deref()) {
117            (Some(company), _) => format!("Company {company} · Team {name}"),
118            (None, Some("team")) => format!("Team {name}"),
119            (None, Some("personal")) => format!("Personal ({name})"),
120            _ => name.clone(),
121        }
122    }
123}
124
125/// The last verified lease, as received, plus the service clock offset.
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127pub struct LeaseRecord {
128    pub envelope: Value,
129    /// `server_time - local time` when the lease arrived, in seconds.
130    pub offset_seconds: i64,
131    pub received_at: String,
132}
133
134/// A cached access token. `Debug` never shows the token.
135#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
136pub struct TokenRecord {
137    pub access_token: String,
138    /// Unix seconds (service clock).
139    pub expires_at: i64,
140}
141
142impl fmt::Debug for TokenRecord {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.debug_struct("TokenRecord")
145            .field("access_token", &"<redacted>")
146            .field("expires_at", &self.expires_at)
147            .finish()
148    }
149}
150
151/// When Cloud last answered, per channel.
152#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
153pub struct ActivityRecord {
154    pub last_seen: Option<String>,
155    #[serde(default)]
156    pub last_success: BTreeMap<String, String>,
157    pub last_error: Option<String>,
158    /// Why Cloud last refused this workspace as locked (`trial_ended`,
159    /// `plan_ended`); cleared by the next lease Cloud issues.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub locked: Option<String>,
162    /// Why the last lease renewal failed; kept until a renewal succeeds
163    /// (unlike `last_error`, which the next success of any channel clears).
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub renew_error: Option<String>,
166}
167
168/// Paths of the Cloud state; [`CloudStore::open`] for this machine,
169/// [`CloudStore::at`] for tests and embedders.
170#[derive(Debug, Clone)]
171pub struct CloudStore {
172    config: PathBuf,
173    data: PathBuf,
174}
175
176impl CloudStore {
177    /// `<config_dir>/cloud` and `<data_dir>/cloud` of this installation. Opening
178    /// only resolves the paths: a read-only config directory keeps its mode (the
179    /// Cloud's own directories are made private when something is written there).
180    pub fn open() -> Result<Self, CloudError> {
181        let config = lean_ctx::core::paths::config_dir_read_only().map_err(CloudError::Local)?;
182        let data = lean_ctx::core::paths::data_dir().map_err(CloudError::Local)?;
183        Ok(Self::at(config.join("cloud"), data.join("cloud")))
184    }
185
186    /// State rooted at explicit directories.
187    pub fn at(config_dir: impl Into<PathBuf>, data_dir: impl Into<PathBuf>) -> Self {
188        Self {
189            config: config_dir.into(),
190            data: data_dir.into(),
191        }
192    }
193
194    pub fn config_dir(&self) -> &Path {
195        &self.config
196    }
197
198    pub fn data_dir(&self) -> &Path {
199        &self.data
200    }
201
202    pub(crate) fn read_config_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, CloudError> {
203        read_optional(&self.config.join(name))
204    }
205
206    pub(crate) fn write_config_bytes(&self, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
207        debug_assert!(is_config_entry(name), "{name} is missing in CONFIG_ENTRIES");
208        write_private(&self.config, name, bytes)
209    }
210
211    pub(crate) fn read_config<T: DeserializeOwned>(
212        &self,
213        name: &str,
214    ) -> Result<Option<T>, CloudError> {
215        read_json(&self.config.join(name))
216    }
217
218    pub(crate) fn write_config<T: Serialize>(
219        &self,
220        name: &str,
221        value: &T,
222    ) -> Result<(), CloudError> {
223        debug_assert!(is_config_entry(name), "{name} is missing in CONFIG_ENTRIES");
224        write_private(&self.config, name, &to_json(value)?)
225    }
226
227    pub(crate) fn remove_config(&self, name: &str) -> Result<(), CloudError> {
228        remove_optional(&self.config.join(name))
229    }
230
231    pub fn activity(&self) -> ActivityRecord {
232        read_json(&self.data.join(ACTIVITY_FILE))
233            .ok()
234            .flatten()
235            .unwrap_or_default()
236    }
237
238    /// Record a successful exchange on `channel` at `when` (RFC 3339).
239    pub(crate) fn record_success(&self, channel: &str, when: &str) {
240        let mut activity = self.activity();
241        activity.last_seen = Some(when.to_string());
242        activity
243            .last_success
244            .insert(channel.to_string(), when.to_string());
245        activity.last_error = None;
246        // Activity is informational; failing to record it never fails the exchange.
247        if let Ok(bytes) = to_json(&activity) {
248            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
249        }
250    }
251
252    /// Record (`Some`) or clear (`None`) a locked workspace (E9).
253    pub fn record_locked(&self, reason: Option<&str>) {
254        let mut activity = self.activity();
255        if activity.locked.as_deref() == reason {
256            return;
257        }
258        activity.locked = reason.map(str::to_string);
259        if let Ok(bytes) = to_json(&activity) {
260            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
261        }
262    }
263
264    /// Record (`Some`) or clear (`None`) why the lease renewal failed.
265    pub(crate) fn record_renew_error(&self, message: Option<&str>) {
266        let mut activity = self.activity();
267        if activity.renew_error.as_deref() == message {
268            return;
269        }
270        activity.renew_error = message.map(str::to_string);
271        if let Ok(bytes) = to_json(&activity) {
272            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
273        }
274    }
275
276    pub(crate) fn record_error(&self, message: &str) {
277        let mut activity = self.activity();
278        activity.last_error = Some(message.to_string());
279        if let Ok(bytes) = to_json(&activity) {
280            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
281        }
282    }
283
284    /// Whether this engine may record anything for Cloud now: connected (an
285    /// instance record) and not revoked. Two file checks; the recording
286    /// paths call it on every record (K2 review 2, N1).
287    pub(crate) fn may_record(&self) -> bool {
288        self.config.join(INSTANCE_FILE).is_file()
289            && !self.config.join(super::revoked::REVOKED_FILE).is_file()
290    }
291
292    /// The slower half of the recording check (K2 review 3, NEW-3): the
293    /// `[cloud]` switches allow engine metrics and the stored lease has not
294    /// lapsed (read from the local copy; a lease that cannot be read counts
295    /// as lapsed).
296    pub(crate) fn recording_allowed(&self, config: &super::config::CloudConfig) -> bool {
297        config.enabled != Some(false) && config.metrics_upload && self.lease_live()
298    }
299
300    fn lease_live(&self) -> bool {
301        use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, LeaseState};
302        let Ok(Some(record)) = self.read_config::<LeaseRecord>(LEASE_FILE) else {
303            return false;
304        };
305        let Ok(lease) = serde_json::from_value::<CloudLeaseV1>(record.envelope["lease"].clone())
306        else {
307            return false;
308        };
309        let service_now = (lean_ctx_time::UtcDateTime::now()
310            + lean_ctx_time::Duration::seconds(record.offset_seconds))
311        .fixed_offset();
312        matches!(
313            lease.state_at(service_now),
314            Ok(LeaseState::Valid | LeaseState::Grace)
315        )
316    }
317
318    /// Who `<data>/cloud` belongs to, when stamped (3.12.8 account scope).
319    #[cfg(test)]
320    fn scope(&self) -> Option<DataScope> {
321        self.read_scope().ok().flatten()
322    }
323
324    /// The stamp of `<data>/cloud`; `Err` when it cannot be read, which
325    /// counts as another account's.
326    fn read_scope(&self) -> Result<Option<DataScope>, ()> {
327        read_json(&self.data.join(SCOPE_FILE)).map_err(|_| ())
328    }
329
330    fn stamp_scope(&self, instance: &InstanceRecord) -> Result<(), CloudError> {
331        write_private(&self.data, SCOPE_FILE, &to_json(&DataScope::of(instance))?)
332    }
333
334    /// Remove `<data>/cloud` in one step: renamed aside first, so no reader
335    /// sees half of it, then deleted. The replica master key lives in the
336    /// config directory and stays. When the config directory is the data
337    /// directory or lies inside it (a single-dir layout, rc4-274), only the
338    /// data entries are moved aside: the enrolment, its keys and its lease
339    /// stay.
340    fn wipe_data(&self) -> Result<(), CloudError> {
341        if !self.data.exists() {
342            return Ok(());
343        }
344        let name = self
345            .data
346            .file_name()
347            .map_or_else(|| "cloud".into(), |n| n.to_string_lossy().into_owned());
348        let aside = self
349            .data
350            .with_file_name(format!("{name}.wiped-{}", std::process::id()));
351        let _ = std::fs::remove_dir_all(&aside);
352        let move_aside = |e: std::io::Error| {
353            CloudError::Local(format!("move {} aside: {e}", self.data.display()))
354        };
355        match self.config_in_data() {
356            None => std::fs::rename(&self.data, &aside).map_err(move_aside)?,
357            Some(config) => {
358                // The entry of `<data>/cloud` that holds the config directory,
359                // or none when the two are the same directory.
360                let holder = config.components().next().map(|c| c.as_os_str().to_owned());
361                private_dir(&aside)?;
362                for entry in std::fs::read_dir(&self.data).map_err(move_aside)? {
363                    let entry = entry.map_err(move_aside)?;
364                    let entry_name = entry.file_name();
365                    let keep = match &holder {
366                        Some(holder) => *holder == entry_name,
367                        None => is_config_entry(&entry_name.to_string_lossy()),
368                    };
369                    if !keep {
370                        std::fs::rename(entry.path(), aside.join(&entry_name))
371                            .map_err(move_aside)?;
372                    }
373                }
374            }
375        }
376        std::fs::remove_dir_all(&aside)
377            .map_err(|e| CloudError::Local(format!("remove {}: {e}", aside.display())))?;
378        self.sweep_wiped(&name);
379        Ok(())
380    }
381
382    /// Where the config directory lies inside the data directory, relative
383    /// to it (empty: the same directory), or `None` when it lies elsewhere
384    /// (the XDG split). Compared as resolved paths, so a symlinked root is
385    /// seen as well.
386    fn config_in_data(&self) -> Option<PathBuf> {
387        let resolve = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
388        let (config, data) = (resolve(&self.config), resolve(&self.data));
389        config.strip_prefix(&data).ok().map(Path::to_path_buf)
390    }
391
392    /// Copies an earlier removal moved aside but did not finish deleting
393    /// (killed process); best effort.
394    fn sweep_wiped(&self, name: &str) {
395        let Some(parent) = self.data.parent() else {
396            return;
397        };
398        let prefix = format!("{name}.wiped-");
399        let Ok(entries) = std::fs::read_dir(parent) else {
400            return;
401        };
402        for entry in entries.flatten() {
403            let is_copy = entry.file_name().to_string_lossy().starts_with(&prefix);
404            let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
405            if is_copy && is_dir {
406                let _ = std::fs::remove_dir_all(entry.path());
407            }
408        }
409    }
410
411    /// Remove another account's local Cloud data: first the knowledge
412    /// pulled from it into project knowledge (the vault map that finds the
413    /// checkouts goes with the data), then `<data>/cloud`. Both fail
414    /// closed: nothing is removed half while its knowledge stays findable.
415    fn purge_data(&self) -> Result<(), CloudError> {
416        self.remove_pulled_knowledge().map_err(|failed| {
417            CloudError::Local(format!(
418                "the knowledge pulled from LeanCTX Cloud could not be removed from {failed}. Until it is, nothing of LeanCTX Cloud is used on this computer. Try again; if it keeps failing, run `lean-ctx cloud disconnect` in a terminal."
419            ))
420        })?;
421        self.wipe_data()
422    }
423
424    /// The lock that orders scope decisions (wipe and stamp) between
425    /// processes; held in the config directory, which a wipe leaves alone.
426    fn lock_scope(&self) -> Result<StateLock, CloudError> {
427        lock_state(&self.config, SCOPE_FILE)
428    }
429
430    /// Before a new enrolment is stored: the local Cloud data of another
431    /// server or team goes (fail closed, 3.12.8 cross-account leak); data
432    /// of the same server and team stays (a reconnect kept with
433    /// `--keep-local`). Data without a stamp is of an unknown account and
434    /// goes as well.
435    pub(crate) fn scope_to_enrollment(&self, next: &InstanceRecord) -> Result<(), CloudError> {
436        let _lock = self.lock_scope()?;
437        let keep = matches!(
438            self.read_scope(),
439            Ok(Some(s)) if s.server == next.url && s.org_id == next.org_id
440        );
441        if !keep {
442            self.purge_data()?;
443        }
444        self.stamp_scope(next)
445    }
446
447    /// The enrolled instance. `<data>/cloud` is made to belong to it first
448    /// (3.12.8 account scope): every reader of local Cloud data (replicas,
449    /// vault map, drafts, docs, tasks, status) asks here, so data stamped
450    /// for another server or team is removed before anything of it is read.
451    /// Another instance of the same server and team (a reconnect, whose
452    /// enrolment already decided what stays) only moves the stamp, so a
453    /// reader racing an enrolment never removes kept data. Data from before
454    /// the stamp existed is adopted by the connected instance.
455    pub fn instance(&self) -> Result<Option<InstanceRecord>, CloudError> {
456        let Some(instance) = self.read_config::<InstanceRecord>(INSTANCE_FILE)? else {
457            return Ok(None);
458        };
459        let now = DataScope::of(&instance);
460        if matches!(self.read_scope(), Ok(Some(ref scope)) if *scope == now) {
461            return Ok(Some(instance));
462        }
463        // Decided again under the lock: an enrolment or another reader may
464        // have moved the stamp meanwhile. Only the removal fails closed; a
465        // stamp that cannot be written (a read-only data directory) is
466        // written by the next reader.
467        let _lock = self.lock_scope()?;
468        match self.read_scope() {
469            Ok(Some(scope)) if scope == now => {}
470            Ok(Some(scope)) if scope.server == now.server && scope.org_id == now.org_id => {
471                let _ = self.stamp_scope(&instance);
472            }
473            Ok(None) if !self.data.exists() => {}
474            Ok(None) => {
475                let _ = self.stamp_scope(&instance);
476            }
477            Ok(Some(_)) | Err(()) => {
478                self.purge_data()?;
479                let _ = self.stamp_scope(&instance);
480            }
481        }
482        Ok(Some(instance))
483    }
484
485    /// Facts pulled from Cloud into the project knowledge of every checkout
486    /// the vault map knows. Every checkout and every store is tried; the
487    /// ones that failed are returned, each with its folder and store file.
488    fn remove_pulled_knowledge(&self) -> Result<(), String> {
489        let map = super::vault::VaultMap::load(&self.data);
490        let mut roots: Vec<&String> = map.vaults.values().flat_map(|r| &r.roots).collect();
491        roots.sort();
492        roots.dedup();
493        let failed: Vec<String> = roots
494            .into_iter()
495            .filter_map(|root| {
496                super::knowledge::learn::remove_all_pulled(root)
497                    .err()
498                    .map(|e| format!("the folder {root}: {e}"))
499            })
500            .collect();
501        if failed.is_empty() {
502            Ok(())
503        } else {
504            Err(failed.join("; "))
505        }
506    }
507
508    /// The enrolled instance as stored, without the account-scope check of
509    /// [`instance`](Self::instance). Only for a disconnect, which must work
510    /// when that check cannot remove another account's pulled knowledge
511    /// (a damaged store): it ends the enrolment it names.
512    pub fn enrolled_instance(&self) -> Result<Option<InstanceRecord>, CloudError> {
513        self.read_config::<InstanceRecord>(INSTANCE_FILE)
514    }
515
516    /// Remove credentials, lease and keys; with `keep_local` the data
517    /// directory (outbox, replicas, activity) stays, but nothing keeps
518    /// recording for Cloud (metrics, signals, receipts). Knowledge pulled
519    /// into project knowledge always goes (3.12.8 account scope), from every
520    /// store that can be cleaned; a store that cannot (damaged) is named
521    /// after everything else is removed.
522    pub fn forget(&self, keep_local: bool) -> Result<(), CloudError> {
523        let knowledge = self.remove_pulled_knowledge().map_err(|failed| {
524            CloudError::Local(format!(
525                "LeanCTX Cloud is disconnected on this computer, but the knowledge pulled from it could not be removed from {failed}. Delete that knowledge.json (it holds that folder's local knowledge; a damaged one cannot be read anyway), then connect again."
526            ))
527        });
528        super::receipts::stop_local_recording(&self.data);
529        for name in [
530            TOKEN_FILE,
531            LEASE_FILE,
532            KEYS_FILE,
533            INSTANCE_FILE,
534            KX_KEY_FILE,
535            INSTANCE_KEY_FILE,
536            SHARING_FILE,
537            MATCH_FILE,
538            super::revoked::REVOKED_FILE,
539            super::disconnect::PENDING_FILE,
540        ] {
541            self.remove_config(name)?;
542        }
543        if !keep_local {
544            // Not `remove_dir_all`: in a single-dir layout that would take
545            // the rest of the config with it (rc4-274).
546            self.wipe_data()?;
547        }
548        knowledge
549    }
550}
551
552/// `<data>/cloud/scope.json`: the server, team and instance the local Cloud
553/// data was made for (3.12.8 account scope).
554#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
555struct DataScope {
556    server: String,
557    org_id: String,
558    instance_id: String,
559}
560
561impl DataScope {
562    fn of(instance: &InstanceRecord) -> Self {
563        Self {
564            server: instance.url.clone(),
565            org_id: instance.org_id.clone(),
566            instance_id: instance.instance_id.clone(),
567        }
568    }
569}
570
571fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CloudError> {
572    let mut bytes =
573        serde_json::to_vec_pretty(value).map_err(|e| CloudError::Local(format!("encode: {e}")))?;
574    bytes.push(b'\n');
575    Ok(bytes)
576}
577
578fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, CloudError> {
579    match std::fs::read(path) {
580        Ok(bytes) => Ok(Some(bytes)),
581        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
582        Err(e) => Err(CloudError::Local(format!("read {}: {e}", path.display()))),
583    }
584}
585
586fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, CloudError> {
587    let Some(bytes) = read_optional(path)? else {
588        return Ok(None);
589    };
590    serde_json::from_slice(&bytes)
591        .map(Some)
592        .map_err(|e| CloudError::Local(format!("{} is damaged: {e}", path.display())))
593}
594
595fn remove_optional(path: &Path) -> Result<(), CloudError> {
596    match std::fs::remove_file(path) {
597        Ok(()) => Ok(()),
598        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
599        Err(e) => Err(CloudError::Local(format!("remove {}: {e}", path.display()))),
600    }
601}
602
603/// Write `dir/name` so that it is never readable by others and never seen
604/// half-written: a 0700 directory and the shared 0600 atomic writer.
605pub(crate) fn write_private(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
606    lean_ctx::core::secure_fs::write_private(dir, name, bytes)
607        .map_err(|e| CloudError::Local(e.to_string()))
608}
609
610fn private_dir(dir: &Path) -> Result<(), CloudError> {
611    lean_ctx::core::secure_fs::private_dir(dir).map_err(|e| CloudError::Local(e.to_string()))
612}
613
614/// Copies of a damaged state file kept beside it (`<name>.damaged-<n>`);
615/// older ones are removed (RB8 M14).
616pub(crate) const DAMAGED_KEPT: usize = 3;
617
618/// Load the JSON state file `path` (RB8 M12). Missing: `Ok(None)`. A file
619/// that does not parse, or that `accept` refuses (a version this build does
620/// not know), is moved aside to `<name>.damaged-<n>` and reported as an
621/// error: no caller silently starts again from empty state, each decides
622/// how it fails closed. A file that cannot be read stays where it is.
623pub(crate) fn load_or_quarantine<T: DeserializeOwned>(
624    path: &Path,
625    accept: impl FnOnce(&T) -> bool,
626) -> Result<Option<T>, CloudError> {
627    let Some(bytes) = read_optional(path)? else {
628        return Ok(None);
629    };
630    let why = match serde_json::from_slice::<T>(&bytes) {
631        Ok(value) if accept(&value) => return Ok(Some(value)),
632        Ok(_) => "a version this build does not know".to_string(),
633        Err(e) => e.to_string(),
634    };
635    let moved = quarantine(path)?;
636    Err(CloudError::Local(format!(
637        "{} is damaged ({why}); moved to {}",
638        path.display(),
639        moved.display()
640    )))
641}
642
643/// Move `path` to `<name>.damaged-<n>` (the next free number) and keep only
644/// the newest [`DAMAGED_KEPT`] such copies.
645pub(crate) fn quarantine(path: &Path) -> Result<PathBuf, CloudError> {
646    let local =
647        |e: std::io::Error| CloudError::Local(format!("quarantine {}: {e}", path.display()));
648    let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
649        return Err(CloudError::Local(format!("{} has no name", path.display())));
650    };
651    let prefix = format!("{name}.damaged-");
652    let mut copies: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
653        .map_err(local)?
654        .filter_map(Result::ok)
655        .filter_map(|e| {
656            let n = e
657                .file_name()
658                .to_str()?
659                .strip_prefix(&prefix)?
660                .parse()
661                .ok()?;
662            Some((n, e.path()))
663        })
664        .collect();
665    copies.sort_unstable();
666    let next = copies.last().map_or(1, |(n, _)| n + 1);
667    let moved = dir.join(format!("{prefix}{next}"));
668    std::fs::rename(path, &moved).map_err(local)?;
669    copies.push((next, moved.clone()));
670    let excess = copies.len().saturating_sub(DAMAGED_KEPT);
671    for (_, old) in copies.drain(..excess) {
672        let _ = std::fs::remove_file(old);
673    }
674    Ok(moved)
675}
676
677/// How long a state lock is waited for before the caller gets an error.
678const STATE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
679
680/// An exclusive lock on `<dir>/<name>.lock` for one read-modify-write of a
681/// state file shared by processes (RB8 E5: the tool calls and the relay).
682/// Held only around local file work, never across a network request.
683pub(crate) struct StateLock(std::fs::File);
684
685impl Drop for StateLock {
686    fn drop(&mut self) {
687        let _ = fs2::FileExt::unlock(&self.0);
688    }
689}
690
691/// Take the lock for the state file `dir/name`, waiting at most
692/// [`STATE_LOCK_WAIT`]; symlinks are refused.
693pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, CloudError> {
694    lock_state_within(dir, name, STATE_LOCK_WAIT)
695}
696
697/// [`lock_state`] waiting at most `wait` (zero: only when free right now).
698pub(crate) fn lock_state_within(
699    dir: &Path,
700    name: &str,
701    wait: std::time::Duration,
702) -> Result<StateLock, CloudError> {
703    private_dir(dir)?;
704    let path = dir.join(format!("{name}.lock"));
705    let local = |what: &str| CloudError::Local(format!("{what} {}", path.display()));
706    let mut options = std::fs::OpenOptions::new();
707    options.read(true).write(true).create(true).truncate(false);
708    #[cfg(unix)]
709    {
710        use std::os::unix::fs::OpenOptionsExt as _;
711        options
712            .mode(0o600)
713            .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
714    }
715    let file = options
716        .open(&path)
717        .map_err(|e| local(&format!("open ({e})")))?;
718    lean_ctx::core::file_lock::acquire_exclusive_timeout(&file, wait)
719        .map_err(|e| local(&format!("lock ({e})")))?;
720    Ok(StateLock(file))
721}
722
723#[cfg(test)]
724mod tests {
725    use super::*;
726
727    /// Personal, Team, Company (Cloud C line): the record says where the
728    /// engine is enrolled; a record from before keeps the plain name.
729    #[test]
730    fn workspace_label_names_personal_team_and_company() {
731        let mut r = InstanceRecord {
732            instance_id: "inst_1".into(),
733            org_id: "org_1".into(),
734            org_name: "Platform".into(),
735            label: "mbp".into(),
736            url: "https://cloud.example".into(),
737            org_salt_id: "s".into(),
738            enrolled_at: "2026-10-26T10:00:00Z".into(),
739            web_url: None,
740            org_kind: None,
741            company_name: None,
742        };
743        assert_eq!(r.workspace_label(), "Platform");
744        r.org_kind = Some("team".into());
745        assert_eq!(r.workspace_label(), "Team Platform");
746        r.company_name = Some("Acme".into());
747        assert_eq!(r.workspace_label(), "Company Acme · Team Platform");
748        r.company_name = None;
749        r.org_kind = Some("personal".into());
750        assert_eq!(r.workspace_label(), "Personal (Platform)");
751        // an old record without the new fields still reads
752        let old: InstanceRecord = serde_json::from_value(serde_json::json!({
753            "instance_id": "i", "org_id": "o", "org_name": "Acme", "label": "l", "url": "u",
754            "org_salt_id": "s", "enrolled_at": "t"
755        }))
756        .unwrap();
757        assert_eq!((old.org_kind, old.company_name), (None, None));
758    }
759
760    #[test]
761    fn private_files_are_atomic_and_owner_only() {
762        let dir = tempfile::tempdir().unwrap();
763        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
764        let token = TokenRecord {
765            access_token: "atl_secret".into(),
766            expires_at: 1,
767        };
768        store.write_config(TOKEN_FILE, &token).unwrap();
769        assert_eq!(
770            store.read_config::<TokenRecord>(TOKEN_FILE).unwrap(),
771            Some(token.clone())
772        );
773        assert!(!format!("{token:?}").contains("atl_secret"));
774        #[cfg(unix)]
775        {
776            use std::os::unix::fs::PermissionsExt as _;
777            let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
778            assert_eq!(mode(store.config_dir()), 0o700);
779            assert_eq!(mode(&store.config_dir().join(TOKEN_FILE)), 0o600);
780        }
781        let leftovers: Vec<_> = std::fs::read_dir(store.config_dir())
782            .unwrap()
783            .filter_map(Result::ok)
784            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
785            .collect();
786        assert!(leftovers.is_empty());
787    }
788
789    #[test]
790    fn damaged_state_is_moved_aside_and_only_three_copies_stay() {
791        let dir = tempfile::tempdir().unwrap();
792        let path = dir.path().join("state.json");
793        let load = |accept: bool| load_or_quarantine::<Value>(&path, |_| accept);
794        assert_eq!(load(true).unwrap(), None, "missing");
795        std::fs::write(&path, b"{\"ok\": 1}").unwrap();
796        assert_eq!(load(true).unwrap(), Some(serde_json::json!({"ok": 1})));
797        // Refused by the caller (an unknown version): moved, an error.
798        let error = load(false).unwrap_err().to_string();
799        assert!(error.contains("damaged-1"), "{error}");
800        assert!(!path.exists());
801        for n in 0..4 {
802            std::fs::write(&path, format!("broken {n}")).unwrap();
803            assert!(load(true).is_err());
804        }
805        let mut kept: Vec<String> = std::fs::read_dir(dir.path())
806            .unwrap()
807            .filter_map(|e| e.ok()?.file_name().into_string().ok())
808            .collect();
809        kept.sort();
810        assert_eq!(
811            kept,
812            [
813                "state.json.damaged-3",
814                "state.json.damaged-4",
815                "state.json.damaged-5"
816            ]
817        );
818        assert_eq!(
819            std::fs::read(dir.path().join("state.json.damaged-5")).unwrap(),
820            b"broken 3",
821            "the newest copy is the last damaged file"
822        );
823    }
824
825    #[test]
826    fn a_held_state_lock_is_not_taken_twice() {
827        let dir = tempfile::tempdir().unwrap();
828        let held = lock_state(dir.path(), "leases.json").unwrap();
829        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_err());
830        drop(held);
831        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_ok());
832        #[cfg(unix)]
833        {
834            use std::os::unix::fs::PermissionsExt as _;
835            let mode = std::fs::metadata(dir.path().join("leases.json.lock"))
836                .unwrap()
837                .permissions()
838                .mode();
839            assert_eq!(mode & 0o777, 0o600);
840        }
841    }
842
843    #[test]
844    fn forget_keeps_local_data_on_request() {
845        let dir = tempfile::tempdir().unwrap();
846        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
847        store
848            .write_config(TOKEN_FILE, &serde_json::json!({}))
849            .unwrap();
850        store.record_success("lease", "2026-10-20T12:00:00Z");
851        store.forget(true).unwrap();
852        assert!(store.read_config_bytes(TOKEN_FILE).unwrap().is_none());
853        assert_eq!(
854            store.activity().last_seen.as_deref(),
855            Some("2026-10-20T12:00:00Z")
856        );
857        store.forget(false).unwrap();
858        assert!(store.activity().last_seen.is_none());
859    }
860}
861
862/// 3.12.8 cross-account leak: `<data>/cloud` belongs to one server and team.
863#[cfg(test)]
864mod scope_tests {
865    use super::*;
866
867    fn instance(server: &str, org: &str, id: &str) -> InstanceRecord {
868        InstanceRecord {
869            instance_id: id.into(),
870            org_id: org.into(),
871            org_name: org.into(),
872            label: "mbp".into(),
873            url: server.into(),
874            org_salt_id: "s".into(),
875            enrolled_at: "2026-11-23T10:00:00Z".into(),
876            web_url: None,
877            org_kind: None,
878            company_name: None,
879        }
880    }
881
882    /// A's vault map and an unsent draft of A.
883    fn data_of_a(store: &CloudStore) {
884        write_private(store.data_dir(), "projects.json", b"{\"projects\":{}}").unwrap();
885        let drafts = store.data_dir().join("outbox").join("knowledge");
886        std::fs::create_dir_all(&drafts).unwrap();
887        std::fs::write(drafts.join("d1.json"), b"{}").unwrap();
888    }
889
890    fn has_data_of_a(store: &CloudStore) -> bool {
891        store.data_dir().join("projects.json").exists()
892            && store.data_dir().join("outbox/knowledge/d1.json").exists()
893    }
894
895    fn connect(store: &CloudStore, record: &InstanceRecord) {
896        store.write_config(INSTANCE_FILE, record).unwrap();
897    }
898
899    #[test]
900    fn enrolling_another_team_or_server_removes_the_local_data() {
901        let dir = tempfile::tempdir().unwrap();
902        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
903        let a = instance("https://cloud.example", "org_a", "inst_1");
904        store.scope_to_enrollment(&a).unwrap();
905        data_of_a(&store);
906
907        // A reconnect to the same server and team (kept with --keep-local)
908        store
909            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_2"))
910            .unwrap();
911        assert!(has_data_of_a(&store), "same team keeps its drafts");
912        assert_eq!(store.scope().unwrap().instance_id, "inst_2");
913
914        // B: another team on the same server
915        let b = instance("https://cloud.example", "org_b", "inst_3");
916        store.scope_to_enrollment(&b).unwrap();
917        assert!(!has_data_of_a(&store), "nothing of A stays for B");
918        assert_eq!(store.scope(), Some(DataScope::of(&b)));
919
920        // the same team id on another server is another account too
921        data_of_a(&store);
922        store
923            .scope_to_enrollment(&instance("https://staging.example", "org_b", "inst_4"))
924            .unwrap();
925        assert!(!has_data_of_a(&store));
926    }
927
928    #[test]
929    fn data_without_a_stamp_is_removed_at_enrolment() {
930        let dir = tempfile::tempdir().unwrap();
931        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
932        data_of_a(&store); // left by an older version with --keep-local
933        store
934            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
935            .unwrap();
936        assert!(!has_data_of_a(&store));
937    }
938
939    #[test]
940    fn readers_get_nothing_while_disconnected_or_of_another_account() {
941        let dir = tempfile::tempdir().unwrap();
942        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
943        let a = instance("https://cloud.example", "org_a", "inst_1");
944        store.scope_to_enrollment(&a).unwrap();
945        data_of_a(&store);
946
947        // not connected (disconnect --keep-local): no instance, nothing read
948        assert_eq!(store.instance().unwrap(), None);
949        assert!(has_data_of_a(&store), "kept for a reconnect, not read");
950
951        // connected to the stamped instance: read as before
952        connect(&store, &a);
953        assert_eq!(store.instance().unwrap(), Some(a.clone()));
954        assert!(has_data_of_a(&store));
955
956        // another instance of the same team only moves the stamp
957        let a2 = instance("https://cloud.example", "org_a", "inst_2");
958        connect(&store, &a2);
959        assert_eq!(store.instance().unwrap(), Some(a2.clone()));
960        assert!(has_data_of_a(&store));
961        assert_eq!(store.scope(), Some(DataScope::of(&a2)));
962
963        // an instance of another team the enrolment did not scope: A's data
964        // is removed before anything reads it
965        let b = instance("https://cloud.example", "org_b", "inst_3");
966        connect(&store, &b);
967        assert_eq!(store.instance().unwrap(), Some(b.clone()));
968        assert!(!has_data_of_a(&store));
969        assert_eq!(store.scope(), Some(DataScope::of(&b)));
970    }
971
972    #[test]
973    fn data_from_before_the_stamp_is_adopted_by_the_connected_instance() {
974        let dir = tempfile::tempdir().unwrap();
975        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
976        let a = instance("https://cloud.example", "org_a", "inst_1");
977        data_of_a(&store);
978        connect(&store, &a);
979        assert_eq!(store.instance().unwrap(), Some(a.clone()));
980        assert!(has_data_of_a(&store), "an upgrade keeps the drafts");
981        assert_eq!(store.scope(), Some(DataScope::of(&a)));
982    }
983
984    /// A checkout of team A with one fact pulled from A and one own fact,
985    /// found through A's vault map in `store`.
986    fn knowledge_of_a(store: &CloudStore, root: &str) {
987        use lean_ctx::core::knowledge::ProjectKnowledge;
988        use lean_ctx_protocol::cloud::knowledge::{FactV1, ResearchContextDocumentV1};
989        let doc = ResearchContextDocumentV1 {
990            facts: vec![FactV1 {
991                id: "f1".into(),
992                statement: "Team A pulled claim here.".into(),
993                kind: "observation".into(),
994                applies_to: vec![],
995                sources: vec![],
996                from_contributions: vec![],
997                anchors: vec![],
998            }],
999            ..ResearchContextDocumentV1::default()
1000        };
1001        super::super::knowledge::learn::sync_into_knowledge(root, "acme", "pay", 1, &doc).unwrap();
1002        let policy = lean_ctx::core::memory_policy::MemoryPolicy::default();
1003        ProjectKnowledge::mutate_locked(root, |k| {
1004            k.remember("arch", "own", "My own claim stays here.", "s", 0.9, &policy);
1005        })
1006        .unwrap();
1007        let mut map = super::super::vault::VaultMap::default();
1008        map.vaults.insert(
1009            "stable".into(),
1010            super::super::vault::VaultRecord {
1011                vault_id: "v1".into(),
1012                ns: "acme".into(),
1013                name: "pay".into(),
1014                sealed: false,
1015                roots: vec![root.to_string()],
1016            },
1017        );
1018        map.save(store.data_dir()).unwrap();
1019    }
1020
1021    /// (pulled fact of A still there, own fact still there)
1022    fn knowledge_left(root: &str) -> (bool, bool) {
1023        let values: Vec<String> = lean_ctx::core::knowledge::ProjectKnowledge::load(root)
1024            .unwrap()
1025            .facts
1026            .iter()
1027            .map(|f| f.value.clone())
1028            .collect();
1029        (
1030            values.iter().any(|v| v.contains("Team A pulled")),
1031            values.iter().any(|v| v.contains("My own claim")),
1032        )
1033    }
1034
1035    /// Disconnect always removes the facts pulled into project knowledge,
1036    /// also with --keep-local; the person's own facts stay.
1037    #[test]
1038    fn forget_removes_pulled_knowledge_also_when_keeping_local_data() {
1039        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1040        let dir = tempfile::tempdir().unwrap();
1041        let repo = tempfile::tempdir().unwrap();
1042        let root = repo.path().to_string_lossy().into_owned();
1043        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1044        let a = instance("https://cloud.example", "org_a", "inst_1");
1045        store.scope_to_enrollment(&a).unwrap();
1046        connect(&store, &a);
1047        knowledge_of_a(&store, &root);
1048
1049        store.forget(true).unwrap();
1050        assert_eq!(knowledge_left(&root), (false, true));
1051        assert!(
1052            store.data_dir().join("projects.json").exists(),
1053            "--keep-local"
1054        );
1055        assert_eq!(store.instance().unwrap(), None);
1056    }
1057
1058    /// 3.12.7 disconnect --keep-local left A's pulled facts behind; enrolling
1059    /// B removes them with A's data, or B's agents would recall them.
1060    #[test]
1061    fn enrolling_another_team_removes_the_knowledge_pulled_from_the_old_one() {
1062        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1063        let dir = tempfile::tempdir().unwrap();
1064        let repo = tempfile::tempdir().unwrap();
1065        let root = repo.path().to_string_lossy().into_owned();
1066        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1067        knowledge_of_a(&store, &root); // unstamped, as 3.12.7 left it
1068
1069        store
1070            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1071            .unwrap();
1072        assert_eq!(knowledge_left(&root), (false, true));
1073        assert!(!store.data_dir().join("projects.json").exists());
1074    }
1075
1076    /// The same for a reader that finds data stamped for another team.
1077    #[test]
1078    fn a_reader_removes_the_knowledge_pulled_from_another_team() {
1079        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1080        let dir = tempfile::tempdir().unwrap();
1081        let repo = tempfile::tempdir().unwrap();
1082        let root = repo.path().to_string_lossy().into_owned();
1083        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1084        store
1085            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1086            .unwrap();
1087        knowledge_of_a(&store, &root);
1088
1089        connect(
1090            &store,
1091            &instance("https://cloud.example", "org_b", "inst_2"),
1092        );
1093        assert!(store.instance().unwrap().is_some());
1094        assert_eq!(knowledge_left(&root), (false, true));
1095    }
1096
1097    #[test]
1098    fn a_damaged_stamp_counts_as_another_account() {
1099        let dir = tempfile::tempdir().unwrap();
1100        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1101        let a = instance("https://cloud.example", "org_a", "inst_1");
1102        store.scope_to_enrollment(&a).unwrap();
1103        data_of_a(&store);
1104        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1105        connect(&store, &a);
1106        assert_eq!(store.instance().unwrap(), Some(a.clone()));
1107        assert!(!has_data_of_a(&store));
1108        assert_eq!(store.scope(), Some(DataScope::of(&a)));
1109
1110        // also at enrolment of the same team
1111        data_of_a(&store);
1112        std::fs::write(store.data_dir().join(SCOPE_FILE), b"{not json").unwrap();
1113        store.scope_to_enrollment(&a).unwrap();
1114        assert!(!has_data_of_a(&store));
1115    }
1116
1117    #[test]
1118    fn copies_left_by_an_interrupted_removal_are_swept() {
1119        let dir = tempfile::tempdir().unwrap();
1120        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1121        let left = dir.path().join("data.wiped-4242");
1122        std::fs::create_dir_all(left.join("outbox")).unwrap();
1123        std::fs::write(left.join("outbox/d.json"), b"{}").unwrap();
1124        data_of_a(&store);
1125        store
1126            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_1"))
1127            .unwrap();
1128        assert!(!left.exists());
1129        assert!(!has_data_of_a(&store));
1130    }
1131
1132    /// A checkout removed since (a deleted worktree) does not block the
1133    /// enrolment of another team: its pulled knowledge goes all the same.
1134    #[test]
1135    fn a_removed_checkout_does_not_block_enrolling_another_team() {
1136        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1137        let dir = tempfile::tempdir().unwrap();
1138        let repo = tempfile::tempdir().unwrap();
1139        let root = repo.path().to_string_lossy().into_owned();
1140        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1141        knowledge_of_a(&store, &root);
1142        let store_dir = lean_ctx::core::knowledge::knowledge_dir_of(&root).unwrap();
1143        drop(repo);
1144        assert!(!std::path::Path::new(&root).exists());
1145
1146        store
1147            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1148            .unwrap();
1149        let stored = std::fs::read_to_string(store_dir.join("knowledge.json")).unwrap();
1150        assert!(!stored.contains("Team A pulled"), "{stored}");
1151        assert!(stored.contains("My own claim"), "{stored}");
1152    }
1153
1154    /// An MCP request bound to another project still removes the knowledge
1155    /// pulled into every checkout (a removal needs no policy admission).
1156    #[test]
1157    fn a_request_bound_to_another_project_still_removes_pulled_knowledge() {
1158        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1159        let dir = tempfile::tempdir().unwrap();
1160        let repo = tempfile::tempdir().unwrap();
1161        let other = tempfile::tempdir().unwrap();
1162        let root = repo.path().to_string_lossy().into_owned();
1163        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1164        knowledge_of_a(&store, &root);
1165
1166        let (config, data) = (dir.path().join("config"), dir.path().join("data"));
1167        lean_ctx::core::policy::runtime::spawn_for_project(other.path().to_path_buf(), move || {
1168            CloudStore::at(config, data)
1169                .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1170                .unwrap();
1171        })
1172        .join()
1173        .unwrap();
1174        assert_eq!(knowledge_left(&root), (false, true));
1175    }
1176
1177    /// A damaged store keeps readers out (fail closed), but a disconnect
1178    /// still gets out: it cleans every readable store, ends the enrolment
1179    /// and names the damaged store's file.
1180    #[test]
1181    fn a_damaged_store_never_locks_the_disconnect_out() {
1182        let _data = lean_ctx::core::data_dir::isolated_data_dir();
1183        let dir = tempfile::tempdir().unwrap();
1184        let (healthy, damaged) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
1185        let healthy = healthy.path().to_string_lossy().into_owned();
1186        let damaged_root = damaged.path().to_string_lossy().into_owned();
1187        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
1188        store
1189            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1190            .unwrap();
1191        knowledge_of_a(&store, &damaged_root);
1192        knowledge_of_a(&store, &healthy);
1193        let mut map = super::super::vault::VaultMap::load(store.data_dir());
1194        for record in map.vaults.values_mut() {
1195            record.roots = vec![healthy.clone(), damaged_root.clone()];
1196        }
1197        map.save(store.data_dir()).unwrap();
1198        let broken = lean_ctx::core::knowledge::knowledge_dir_of(&damaged_root)
1199            .unwrap()
1200            .join("knowledge.json");
1201        std::fs::write(&broken, b"{ damaged").unwrap();
1202
1203        // connected to team B now: A's knowledge cannot all go, nothing is read
1204        let b = instance("https://cloud.example", "org_b", "inst_2");
1205        connect(&store, &b);
1206        assert!(store.instance().is_err());
1207        assert_eq!(store.enrolled_instance().unwrap(), Some(b));
1208
1209        // the disconnect's local side
1210        let error = store.forget(false).unwrap_err().to_string();
1211        assert!(error.contains(&broken.display().to_string()), "{error}");
1212        assert_eq!(knowledge_left(&healthy), (false, true));
1213        assert_eq!(store.enrolled_instance().unwrap(), None);
1214        assert_eq!(store.instance().unwrap(), None);
1215    }
1216
1217    /// The config of a single-dir layout: one of every kind of entry.
1218    const SINGLE_DIR_CONFIG: &[&str] = &[
1219        INSTANCE_KEY_FILE,
1220        KX_KEY_FILE,
1221        LEASE_FILE,
1222        KEYS_FILE,
1223        "keys_v3.json",
1224        "chat_key.json",
1225        "bring-local-0123abcd.json",
1226        "consent.key",
1227        "consent/offer-1.json",
1228        "replica.key",
1229        "scope.json.lock",
1230        "lease.json.damaged-1",
1231        ".keys.json.tmp.4242.0",
1232    ];
1233
1234    fn single_dir_config(cloud: &Path) {
1235        for name in SINGLE_DIR_CONFIG {
1236            let path = cloud.join(name);
1237            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1238            std::fs::write(path, b"{}").unwrap();
1239        }
1240    }
1241
1242    fn missing_config(cloud: &Path) -> Vec<&'static str> {
1243        SINGLE_DIR_CONFIG
1244            .iter()
1245            .copied()
1246            .filter(|name| !cloud.join(name).exists())
1247            .collect()
1248    }
1249
1250    /// rc4-274: a legacy `~/.lean-ctx` or a custom `LEAN_CTX_DATA_DIR` puts
1251    /// `<config>/cloud` and `<data>/cloud` in one directory. Enrolling
1252    /// another account removes only the data there; the config (keys,
1253    /// lease, consent, locks) stays and nothing is left beside it.
1254    #[test]
1255    fn a_single_dir_layout_keeps_the_config_when_the_data_goes() {
1256        let dir = tempfile::tempdir().unwrap();
1257        let cloud = dir.path().join("cloud");
1258        let store = CloudStore::at(&cloud, &cloud);
1259        single_dir_config(&cloud);
1260        data_of_a(&store);
1261        std::fs::write(cloud.join(ACTIVITY_FILE), b"{}").unwrap();
1262
1263        let b = instance("https://cloud.example", "org_b", "inst_2");
1264        store.scope_to_enrollment(&b).unwrap();
1265        assert!(!has_data_of_a(&store), "nothing of A stays for B");
1266        assert!(!cloud.join(ACTIVITY_FILE).exists());
1267        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1268        assert_eq!(store.scope(), Some(DataScope::of(&b)));
1269        let beside: Vec<_> = std::fs::read_dir(dir.path())
1270            .unwrap()
1271            .map(|e| e.unwrap().file_name())
1272            .collect();
1273        assert_eq!(beside, ["cloud"], "no copy left beside it");
1274
1275        // A reader connected to another team later: the same.
1276        data_of_a(&store);
1277        connect(
1278            &store,
1279            &instance("https://cloud.example", "org_c", "inst_3"),
1280        );
1281        assert!(store.instance().unwrap().is_some());
1282        assert!(!has_data_of_a(&store));
1283        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1284        assert!(cloud.join(INSTANCE_FILE).exists());
1285    }
1286
1287    /// rc4-274: the config directory reached through a symlink, or lying
1288    /// inside the data directory, is kept as well.
1289    #[cfg(unix)]
1290    #[test]
1291    fn a_config_dir_behind_a_symlink_or_inside_the_data_stays() {
1292        let dir = tempfile::tempdir().unwrap();
1293        let cloud = dir.path().join("cloud");
1294        std::fs::create_dir_all(&cloud).unwrap();
1295        std::os::unix::fs::symlink(&cloud, dir.path().join("linked")).unwrap();
1296        let store = CloudStore::at(dir.path().join("linked"), &cloud);
1297        single_dir_config(&cloud);
1298        data_of_a(&store);
1299        store
1300            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1301            .unwrap();
1302        assert!(!has_data_of_a(&store));
1303        assert_eq!(missing_config(&cloud), Vec::<&str>::new());
1304
1305        let data = dir.path().join("data");
1306        let config = data.join("config").join("cloud");
1307        let store = CloudStore::at(&config, &data);
1308        single_dir_config(&config);
1309        data_of_a(&store);
1310        store
1311            .scope_to_enrollment(&instance("https://cloud.example", "org_b", "inst_2"))
1312            .unwrap();
1313        assert!(!has_data_of_a(&store));
1314        assert_eq!(missing_config(&config), Vec::<&str>::new());
1315    }
1316
1317    /// rc4-274: a disconnect without `--keep-local` in a single-dir layout
1318    /// removes the data and the enrolment, but not the rest of the config
1319    /// (as in the XDG split, where `<config>/cloud` is never removed whole).
1320    #[test]
1321    fn a_single_dir_disconnect_removes_the_data_but_not_the_config_dir() {
1322        let dir = tempfile::tempdir().unwrap();
1323        let cloud = dir.path().join("cloud");
1324        let store = CloudStore::at(&cloud, &cloud);
1325        store
1326            .scope_to_enrollment(&instance("https://cloud.example", "org_a", "inst_1"))
1327            .unwrap();
1328        connect(
1329            &store,
1330            &instance("https://cloud.example", "org_a", "inst_1"),
1331        );
1332        data_of_a(&store);
1333        std::fs::write(cloud.join("consent.key"), b"k").unwrap();
1334        store.forget(false).unwrap();
1335        assert!(!has_data_of_a(&store));
1336        assert!(!cloud.join(INSTANCE_FILE).exists());
1337        assert!(!cloud.join(SCOPE_FILE).exists());
1338        assert!(cloud.join("consent.key").exists());
1339    }
1340
1341    /// Every name in the list is one a module writes (a renamed constant
1342    /// cannot leave a stale entry), and data names are not in it.
1343    #[test]
1344    fn config_entries_name_the_config_only() {
1345        for name in CONFIG_ENTRIES {
1346            assert!(is_config_entry(name), "{name}");
1347            assert!(is_config_entry(&format!(".{name}.tmp.1.0")), "{name}");
1348            assert!(is_config_entry(&format!("{name}.damaged-2")), "{name}");
1349        }
1350        for data in [
1351            ACTIVITY_FILE,
1352            SCOPE_FILE,
1353            "projects.json",
1354            "outbox",
1355            "bus",
1356            "replicas",
1357            ".projects.json.tmp.1.0",
1358        ] {
1359            assert!(!is_config_entry(data), "{data}");
1360        }
1361    }
1362}