1use 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";
27pub(crate) const SHARING_FILE: &str = "sharing.json";
29pub(crate) const MATCH_FILE: &str = "vault-match.json";
32
33#[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 pub url: String,
42 pub org_salt_id: String,
43 pub enrolled_at: String,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub web_url: Option<String>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub org_kind: Option<String>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub company_name: Option<String>,
53}
54
55impl InstanceRecord {
56 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub struct LeaseRecord {
74 pub envelope: Value,
75 pub offset_seconds: i64,
77 pub received_at: String,
78}
79
80#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct TokenRecord {
83 pub access_token: String,
84 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#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub locked: Option<String>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub renew_error: Option<String>,
112}
113
114#[derive(Debug, Clone)]
117pub struct CloudStore {
118 config: PathBuf,
119 data: PathBuf,
120}
121
122impl CloudStore {
123 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 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 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 if let Ok(bytes) = to_json(&activity) {
196 let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
197 }
198 }
199
200 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 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 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 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 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
325pub(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
336pub(crate) const DAMAGED_KEPT: usize = 3;
339
340pub(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
365pub(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
399const STATE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
401
402pub(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
413pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, CloudError> {
416 lock_state_within(dir, name, STATE_LOCK_WAIT)
417}
418
419pub(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 #[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 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 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}