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
33/// The enrolled instance.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct InstanceRecord {
36    pub instance_id: String,
37    pub org_id: String,
38    pub org_name: String,
39    pub label: String,
40    /// Origin the instance is enrolled with.
41    pub url: String,
42    pub org_salt_id: String,
43    pub enrolled_at: String,
44    /// Origin of the Cloud web app, when enrollment named one (1.3).
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub web_url: Option<String>,
47    /// `personal` | `team`, when enrollment named it (Cloud C line).
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub org_kind: Option<String>,
50    /// The company the team belongs to, when enrollment named one.
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub company_name: Option<String>,
53}
54
55impl InstanceRecord {
56    /// Where the instance is enrolled, as people read it (owner decision
57    /// 26.10.: Personal, Team, Company): `Company Acme · Team Platform`,
58    /// `Team Platform`, `Personal (Ada)`; an older server's record keeps
59    /// the plain name.
60    pub fn workspace_label(&self) -> String {
61        let name = &self.org_name;
62        match (self.company_name.as_deref(), self.org_kind.as_deref()) {
63            (Some(company), _) => format!("Company {company} · Team {name}"),
64            (None, Some("team")) => format!("Team {name}"),
65            (None, Some("personal")) => format!("Personal ({name})"),
66            _ => name.clone(),
67        }
68    }
69}
70
71/// The last verified lease, as received, plus the service clock offset.
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub struct LeaseRecord {
74    pub envelope: Value,
75    /// `server_time - local time` when the lease arrived, in seconds.
76    pub offset_seconds: i64,
77    pub received_at: String,
78}
79
80/// A cached access token. `Debug` never shows the token.
81#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct TokenRecord {
83    pub access_token: String,
84    /// Unix seconds (service clock).
85    pub expires_at: i64,
86}
87
88impl fmt::Debug for TokenRecord {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_struct("TokenRecord")
91            .field("access_token", &"<redacted>")
92            .field("expires_at", &self.expires_at)
93            .finish()
94    }
95}
96
97/// When Cloud last answered, per channel.
98#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
99pub struct ActivityRecord {
100    pub last_seen: Option<String>,
101    #[serde(default)]
102    pub last_success: BTreeMap<String, String>,
103    pub last_error: Option<String>,
104    /// Why Cloud last refused this workspace as locked (`trial_ended`,
105    /// `plan_ended`); cleared by the next lease Cloud issues.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub locked: Option<String>,
108    /// Why the last lease renewal failed; kept until a renewal succeeds
109    /// (unlike `last_error`, which the next success of any channel clears).
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub renew_error: Option<String>,
112}
113
114/// Paths of the Cloud state; [`CloudStore::open`] for this machine,
115/// [`CloudStore::at`] for tests and embedders.
116#[derive(Debug, Clone)]
117pub struct CloudStore {
118    config: PathBuf,
119    data: PathBuf,
120}
121
122impl CloudStore {
123    /// `<config_dir>/cloud` and `<data_dir>/cloud` of this installation. Opening
124    /// only resolves the paths: a read-only config directory keeps its mode (the
125    /// Cloud's own directories are made private when something is written there).
126    pub fn open() -> Result<Self, CloudError> {
127        let config = lean_ctx::core::paths::config_dir_read_only().map_err(CloudError::Local)?;
128        let data = lean_ctx::core::paths::data_dir().map_err(CloudError::Local)?;
129        Ok(Self::at(config.join("cloud"), data.join("cloud")))
130    }
131
132    /// State rooted at explicit directories.
133    pub fn at(config_dir: impl Into<PathBuf>, data_dir: impl Into<PathBuf>) -> Self {
134        Self {
135            config: config_dir.into(),
136            data: data_dir.into(),
137        }
138    }
139
140    pub fn config_dir(&self) -> &Path {
141        &self.config
142    }
143
144    pub fn data_dir(&self) -> &Path {
145        &self.data
146    }
147
148    pub(crate) fn read_config_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, CloudError> {
149        read_optional(&self.config.join(name))
150    }
151
152    pub(crate) fn write_config_bytes(&self, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
153        write_private(&self.config, name, bytes)
154    }
155
156    pub(crate) fn read_config<T: DeserializeOwned>(
157        &self,
158        name: &str,
159    ) -> Result<Option<T>, CloudError> {
160        read_json(&self.config.join(name))
161    }
162
163    pub(crate) fn write_config<T: Serialize>(
164        &self,
165        name: &str,
166        value: &T,
167    ) -> Result<(), CloudError> {
168        write_private(&self.config, name, &to_json(value)?)
169    }
170
171    pub(crate) fn remove_config(&self, name: &str) -> Result<(), CloudError> {
172        remove_optional(&self.config.join(name))
173    }
174
175    pub fn instance(&self) -> Result<Option<InstanceRecord>, CloudError> {
176        self.read_config(INSTANCE_FILE)
177    }
178
179    pub fn activity(&self) -> ActivityRecord {
180        read_json(&self.data.join(ACTIVITY_FILE))
181            .ok()
182            .flatten()
183            .unwrap_or_default()
184    }
185
186    /// Record a successful exchange on `channel` at `when` (RFC 3339).
187    pub(crate) fn record_success(&self, channel: &str, when: &str) {
188        let mut activity = self.activity();
189        activity.last_seen = Some(when.to_string());
190        activity
191            .last_success
192            .insert(channel.to_string(), when.to_string());
193        activity.last_error = None;
194        // Activity is informational; failing to record it never fails the exchange.
195        if let Ok(bytes) = to_json(&activity) {
196            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
197        }
198    }
199
200    /// Record (`Some`) or clear (`None`) a locked workspace (E9).
201    pub fn record_locked(&self, reason: Option<&str>) {
202        let mut activity = self.activity();
203        if activity.locked.as_deref() == reason {
204            return;
205        }
206        activity.locked = reason.map(str::to_string);
207        if let Ok(bytes) = to_json(&activity) {
208            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
209        }
210    }
211
212    /// Record (`Some`) or clear (`None`) why the lease renewal failed.
213    pub(crate) fn record_renew_error(&self, message: Option<&str>) {
214        let mut activity = self.activity();
215        if activity.renew_error.as_deref() == message {
216            return;
217        }
218        activity.renew_error = message.map(str::to_string);
219        if let Ok(bytes) = to_json(&activity) {
220            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
221        }
222    }
223
224    pub(crate) fn record_error(&self, message: &str) {
225        let mut activity = self.activity();
226        activity.last_error = Some(message.to_string());
227        if let Ok(bytes) = to_json(&activity) {
228            let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
229        }
230    }
231
232    /// Whether this engine may record anything for Cloud now: connected (an
233    /// instance record) and not revoked. Two file checks; the recording
234    /// paths call it on every record (K2 review 2, N1).
235    pub(crate) fn may_record(&self) -> bool {
236        self.config.join(INSTANCE_FILE).is_file()
237            && !self.config.join(super::revoked::REVOKED_FILE).is_file()
238    }
239
240    /// The slower half of the recording check (K2 review 3, NEW-3): the
241    /// `[cloud]` switches allow engine metrics and the stored lease has not
242    /// lapsed (read from the local copy; a lease that cannot be read counts
243    /// as lapsed).
244    pub(crate) fn recording_allowed(&self, config: &super::config::CloudConfig) -> bool {
245        config.enabled != Some(false) && config.metrics_upload && self.lease_live()
246    }
247
248    fn lease_live(&self) -> bool {
249        use lean_ctx_protocol::cloud::lease::{CloudLeaseV1, LeaseState};
250        let Ok(Some(record)) = self.read_config::<LeaseRecord>(LEASE_FILE) else {
251            return false;
252        };
253        let Ok(lease) = serde_json::from_value::<CloudLeaseV1>(record.envelope["lease"].clone())
254        else {
255            return false;
256        };
257        let service_now = (lean_ctx_time::UtcDateTime::now()
258            + lean_ctx_time::Duration::seconds(record.offset_seconds))
259        .fixed_offset();
260        matches!(
261            lease.state_at(service_now),
262            Ok(LeaseState::Valid | LeaseState::Grace)
263        )
264    }
265
266    /// Remove credentials, lease and keys; with `keep_local` the data
267    /// directory (pulled knowledge, outbox, activity) stays, but nothing
268    /// keeps recording for Cloud (metrics, signals, receipts).
269    pub fn forget(&self, keep_local: bool) -> Result<(), CloudError> {
270        super::receipts::stop_local_recording(&self.data);
271        for name in [
272            TOKEN_FILE,
273            LEASE_FILE,
274            KEYS_FILE,
275            INSTANCE_FILE,
276            KX_KEY_FILE,
277            INSTANCE_KEY_FILE,
278            SHARING_FILE,
279            MATCH_FILE,
280            super::revoked::REVOKED_FILE,
281            super::disconnect::PENDING_FILE,
282        ] {
283            self.remove_config(name)?;
284        }
285        if !keep_local && self.data.exists() {
286            std::fs::remove_dir_all(&self.data)
287                .map_err(|e| CloudError::Local(format!("remove {}: {e}", self.data.display())))?;
288        }
289        Ok(())
290    }
291}
292
293fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, CloudError> {
294    let mut bytes =
295        serde_json::to_vec_pretty(value).map_err(|e| CloudError::Local(format!("encode: {e}")))?;
296    bytes.push(b'\n');
297    Ok(bytes)
298}
299
300fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, CloudError> {
301    match std::fs::read(path) {
302        Ok(bytes) => Ok(Some(bytes)),
303        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
304        Err(e) => Err(CloudError::Local(format!("read {}: {e}", path.display()))),
305    }
306}
307
308fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, CloudError> {
309    let Some(bytes) = read_optional(path)? else {
310        return Ok(None);
311    };
312    serde_json::from_slice(&bytes)
313        .map(Some)
314        .map_err(|e| CloudError::Local(format!("{} is damaged: {e}", path.display())))
315}
316
317fn remove_optional(path: &Path) -> Result<(), CloudError> {
318    match std::fs::remove_file(path) {
319        Ok(()) => Ok(()),
320        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
321        Err(e) => Err(CloudError::Local(format!("remove {}: {e}", path.display()))),
322    }
323}
324
325/// Write `dir/name` so that it is never readable by others and never seen
326/// half-written: a 0700 directory and the shared 0600 atomic writer.
327pub(crate) fn write_private(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), CloudError> {
328    lean_ctx::core::secure_fs::write_private(dir, name, bytes)
329        .map_err(|e| CloudError::Local(e.to_string()))
330}
331
332fn private_dir(dir: &Path) -> Result<(), CloudError> {
333    lean_ctx::core::secure_fs::private_dir(dir).map_err(|e| CloudError::Local(e.to_string()))
334}
335
336/// Copies of a damaged state file kept beside it (`<name>.damaged-<n>`);
337/// older ones are removed (RB8 M14).
338pub(crate) const DAMAGED_KEPT: usize = 3;
339
340/// Load the JSON state file `path` (RB8 M12). Missing: `Ok(None)`. A file
341/// that does not parse, or that `accept` refuses (a version this build does
342/// not know), is moved aside to `<name>.damaged-<n>` and reported as an
343/// error: no caller silently starts again from empty state, each decides
344/// how it fails closed. A file that cannot be read stays where it is.
345pub(crate) fn load_or_quarantine<T: DeserializeOwned>(
346    path: &Path,
347    accept: impl FnOnce(&T) -> bool,
348) -> Result<Option<T>, CloudError> {
349    let Some(bytes) = read_optional(path)? else {
350        return Ok(None);
351    };
352    let why = match serde_json::from_slice::<T>(&bytes) {
353        Ok(value) if accept(&value) => return Ok(Some(value)),
354        Ok(_) => "a version this build does not know".to_string(),
355        Err(e) => e.to_string(),
356    };
357    let moved = quarantine(path)?;
358    Err(CloudError::Local(format!(
359        "{} is damaged ({why}); moved to {}",
360        path.display(),
361        moved.display()
362    )))
363}
364
365/// Move `path` to `<name>.damaged-<n>` (the next free number) and keep only
366/// the newest [`DAMAGED_KEPT`] such copies.
367pub(crate) fn quarantine(path: &Path) -> Result<PathBuf, CloudError> {
368    let local =
369        |e: std::io::Error| CloudError::Local(format!("quarantine {}: {e}", path.display()));
370    let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
371        return Err(CloudError::Local(format!("{} has no name", path.display())));
372    };
373    let prefix = format!("{name}.damaged-");
374    let mut copies: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
375        .map_err(local)?
376        .filter_map(Result::ok)
377        .filter_map(|e| {
378            let n = e
379                .file_name()
380                .to_str()?
381                .strip_prefix(&prefix)?
382                .parse()
383                .ok()?;
384            Some((n, e.path()))
385        })
386        .collect();
387    copies.sort_unstable();
388    let next = copies.last().map_or(1, |(n, _)| n + 1);
389    let moved = dir.join(format!("{prefix}{next}"));
390    std::fs::rename(path, &moved).map_err(local)?;
391    copies.push((next, moved.clone()));
392    let excess = copies.len().saturating_sub(DAMAGED_KEPT);
393    for (_, old) in copies.drain(..excess) {
394        let _ = std::fs::remove_file(old);
395    }
396    Ok(moved)
397}
398
399/// How long a state lock is waited for before the caller gets an error.
400const STATE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
401
402/// An exclusive lock on `<dir>/<name>.lock` for one read-modify-write of a
403/// state file shared by processes (RB8 E5: the tool calls and the relay).
404/// Held only around local file work, never across a network request.
405pub(crate) struct StateLock(std::fs::File);
406
407impl Drop for StateLock {
408    fn drop(&mut self) {
409        let _ = fs2::FileExt::unlock(&self.0);
410    }
411}
412
413/// Take the lock for the state file `dir/name`, waiting at most
414/// [`STATE_LOCK_WAIT`]; symlinks are refused.
415pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, CloudError> {
416    lock_state_within(dir, name, STATE_LOCK_WAIT)
417}
418
419/// [`lock_state`] waiting at most `wait` (zero: only when free right now).
420pub(crate) fn lock_state_within(
421    dir: &Path,
422    name: &str,
423    wait: std::time::Duration,
424) -> Result<StateLock, CloudError> {
425    private_dir(dir)?;
426    let path = dir.join(format!("{name}.lock"));
427    let local = |what: &str| CloudError::Local(format!("{what} {}", path.display()));
428    let mut options = std::fs::OpenOptions::new();
429    options.read(true).write(true).create(true).truncate(false);
430    #[cfg(unix)]
431    {
432        use std::os::unix::fs::OpenOptionsExt as _;
433        options
434            .mode(0o600)
435            .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
436    }
437    let file = options
438        .open(&path)
439        .map_err(|e| local(&format!("open ({e})")))?;
440    lean_ctx::core::file_lock::acquire_exclusive_timeout(&file, wait)
441        .map_err(|e| local(&format!("lock ({e})")))?;
442    Ok(StateLock(file))
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    /// Personal, Team, Company (Cloud C line): the record says where the
450    /// engine is enrolled; a record from before keeps the plain name.
451    #[test]
452    fn workspace_label_names_personal_team_and_company() {
453        let mut r = InstanceRecord {
454            instance_id: "inst_1".into(),
455            org_id: "org_1".into(),
456            org_name: "Platform".into(),
457            label: "mbp".into(),
458            url: "https://cloud.example".into(),
459            org_salt_id: "s".into(),
460            enrolled_at: "2026-10-26T10:00:00Z".into(),
461            web_url: None,
462            org_kind: None,
463            company_name: None,
464        };
465        assert_eq!(r.workspace_label(), "Platform");
466        r.org_kind = Some("team".into());
467        assert_eq!(r.workspace_label(), "Team Platform");
468        r.company_name = Some("Acme".into());
469        assert_eq!(r.workspace_label(), "Company Acme · Team Platform");
470        r.company_name = None;
471        r.org_kind = Some("personal".into());
472        assert_eq!(r.workspace_label(), "Personal (Platform)");
473        // an old record without the new fields still reads
474        let old: InstanceRecord = serde_json::from_value(serde_json::json!({
475            "instance_id": "i", "org_id": "o", "org_name": "Acme", "label": "l", "url": "u",
476            "org_salt_id": "s", "enrolled_at": "t"
477        }))
478        .unwrap();
479        assert_eq!((old.org_kind, old.company_name), (None, None));
480    }
481
482    #[test]
483    fn private_files_are_atomic_and_owner_only() {
484        let dir = tempfile::tempdir().unwrap();
485        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
486        let token = TokenRecord {
487            access_token: "atl_secret".into(),
488            expires_at: 1,
489        };
490        store.write_config(TOKEN_FILE, &token).unwrap();
491        assert_eq!(
492            store.read_config::<TokenRecord>(TOKEN_FILE).unwrap(),
493            Some(token.clone())
494        );
495        assert!(!format!("{token:?}").contains("atl_secret"));
496        #[cfg(unix)]
497        {
498            use std::os::unix::fs::PermissionsExt as _;
499            let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
500            assert_eq!(mode(store.config_dir()), 0o700);
501            assert_eq!(mode(&store.config_dir().join(TOKEN_FILE)), 0o600);
502        }
503        let leftovers: Vec<_> = std::fs::read_dir(store.config_dir())
504            .unwrap()
505            .filter_map(Result::ok)
506            .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
507            .collect();
508        assert!(leftovers.is_empty());
509    }
510
511    #[test]
512    fn damaged_state_is_moved_aside_and_only_three_copies_stay() {
513        let dir = tempfile::tempdir().unwrap();
514        let path = dir.path().join("state.json");
515        let load = |accept: bool| load_or_quarantine::<Value>(&path, |_| accept);
516        assert_eq!(load(true).unwrap(), None, "missing");
517        std::fs::write(&path, b"{\"ok\": 1}").unwrap();
518        assert_eq!(load(true).unwrap(), Some(serde_json::json!({"ok": 1})));
519        // Refused by the caller (an unknown version): moved, an error.
520        let error = load(false).unwrap_err().to_string();
521        assert!(error.contains("damaged-1"), "{error}");
522        assert!(!path.exists());
523        for n in 0..4 {
524            std::fs::write(&path, format!("broken {n}")).unwrap();
525            assert!(load(true).is_err());
526        }
527        let mut kept: Vec<String> = std::fs::read_dir(dir.path())
528            .unwrap()
529            .filter_map(|e| e.ok()?.file_name().into_string().ok())
530            .collect();
531        kept.sort();
532        assert_eq!(
533            kept,
534            [
535                "state.json.damaged-3",
536                "state.json.damaged-4",
537                "state.json.damaged-5"
538            ]
539        );
540        assert_eq!(
541            std::fs::read(dir.path().join("state.json.damaged-5")).unwrap(),
542            b"broken 3",
543            "the newest copy is the last damaged file"
544        );
545    }
546
547    #[test]
548    fn a_held_state_lock_is_not_taken_twice() {
549        let dir = tempfile::tempdir().unwrap();
550        let held = lock_state(dir.path(), "leases.json").unwrap();
551        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_err());
552        drop(held);
553        assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_ok());
554        #[cfg(unix)]
555        {
556            use std::os::unix::fs::PermissionsExt as _;
557            let mode = std::fs::metadata(dir.path().join("leases.json.lock"))
558                .unwrap()
559                .permissions()
560                .mode();
561            assert_eq!(mode & 0o777, 0o600);
562        }
563    }
564
565    #[test]
566    fn forget_keeps_local_data_on_request() {
567        let dir = tempfile::tempdir().unwrap();
568        let store = CloudStore::at(dir.path().join("config"), dir.path().join("data"));
569        store
570            .write_config(TOKEN_FILE, &serde_json::json!({}))
571            .unwrap();
572        store.record_success("lease", "2026-10-20T12:00:00Z");
573        store.forget(true).unwrap();
574        assert!(store.read_config_bytes(TOKEN_FILE).unwrap().is_none());
575        assert_eq!(
576            store.activity().last_seen.as_deref(),
577            Some("2026-10-20T12:00:00Z")
578        );
579        store.forget(false).unwrap();
580        assert!(store.activity().last_seen.is_none());
581    }
582}