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::HiveError;
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}
109
110#[derive(Debug, Clone)]
113pub struct HiveStore {
114 config: PathBuf,
115 data: PathBuf,
116}
117
118impl HiveStore {
119 pub fn open() -> Result<Self, HiveError> {
123 let config = crate::core::paths::config_dir_read_only().map_err(HiveError::Local)?;
124 let data = crate::core::paths::data_dir().map_err(HiveError::Local)?;
125 Ok(Self::at(config.join("hive"), data.join("hive")))
126 }
127
128 pub fn at(config_dir: impl Into<PathBuf>, data_dir: impl Into<PathBuf>) -> Self {
130 Self {
131 config: config_dir.into(),
132 data: data_dir.into(),
133 }
134 }
135
136 pub fn config_dir(&self) -> &Path {
137 &self.config
138 }
139
140 pub fn data_dir(&self) -> &Path {
141 &self.data
142 }
143
144 pub(crate) fn read_config_bytes(&self, name: &str) -> Result<Option<Vec<u8>>, HiveError> {
145 read_optional(&self.config.join(name))
146 }
147
148 pub(crate) fn write_config_bytes(&self, name: &str, bytes: &[u8]) -> Result<(), HiveError> {
149 write_private(&self.config, name, bytes)
150 }
151
152 pub(crate) fn read_config<T: DeserializeOwned>(
153 &self,
154 name: &str,
155 ) -> Result<Option<T>, HiveError> {
156 read_json(&self.config.join(name))
157 }
158
159 pub(crate) fn write_config<T: Serialize>(
160 &self,
161 name: &str,
162 value: &T,
163 ) -> Result<(), HiveError> {
164 write_private(&self.config, name, &to_json(value)?)
165 }
166
167 pub(crate) fn remove_config(&self, name: &str) -> Result<(), HiveError> {
168 remove_optional(&self.config.join(name))
169 }
170
171 pub fn instance(&self) -> Result<Option<InstanceRecord>, HiveError> {
172 self.read_config(INSTANCE_FILE)
173 }
174
175 pub fn activity(&self) -> ActivityRecord {
176 read_json(&self.data.join(ACTIVITY_FILE))
177 .ok()
178 .flatten()
179 .unwrap_or_default()
180 }
181
182 pub(crate) fn record_success(&self, channel: &str, when: &str) {
184 let mut activity = self.activity();
185 activity.last_seen = Some(when.to_string());
186 activity
187 .last_success
188 .insert(channel.to_string(), when.to_string());
189 activity.last_error = None;
190 if let Ok(bytes) = to_json(&activity) {
192 let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
193 }
194 }
195
196 pub(crate) fn record_locked(&self, reason: Option<&str>) {
198 let mut activity = self.activity();
199 if activity.locked.as_deref() == reason {
200 return;
201 }
202 activity.locked = reason.map(str::to_string);
203 if let Ok(bytes) = to_json(&activity) {
204 let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
205 }
206 }
207
208 pub(crate) fn record_error(&self, message: &str) {
209 let mut activity = self.activity();
210 activity.last_error = Some(message.to_string());
211 if let Ok(bytes) = to_json(&activity) {
212 let _ = write_private(&self.data, ACTIVITY_FILE, &bytes);
213 }
214 }
215
216 pub(crate) fn may_record(&self) -> bool {
220 self.config.join(INSTANCE_FILE).is_file()
221 && !self.config.join(super::revoked::REVOKED_FILE).is_file()
222 }
223
224 pub(crate) fn recording_allowed(&self, config: &super::config::HiveConfig) -> bool {
229 config.enabled != Some(false) && config.metrics_upload && self.lease_live()
230 }
231
232 fn lease_live(&self) -> bool {
233 use lean_ctx_protocol::hive::lease::{HiveLeaseV1, LeaseState};
234 let Ok(Some(record)) = self.read_config::<LeaseRecord>(LEASE_FILE) else {
235 return false;
236 };
237 let Ok(lease) = serde_json::from_value::<HiveLeaseV1>(record.envelope["lease"].clone())
238 else {
239 return false;
240 };
241 let service_now =
242 (chrono::Utc::now() + chrono::Duration::seconds(record.offset_seconds)).fixed_offset();
243 matches!(
244 lease.state_at(service_now),
245 Ok(LeaseState::Valid | LeaseState::Grace)
246 )
247 }
248
249 pub fn forget(&self, keep_local: bool) -> Result<(), HiveError> {
253 super::receipts::stop_local_recording(&self.data);
254 for name in [
255 TOKEN_FILE,
256 LEASE_FILE,
257 KEYS_FILE,
258 INSTANCE_FILE,
259 KX_KEY_FILE,
260 INSTANCE_KEY_FILE,
261 SHARING_FILE,
262 MATCH_FILE,
263 super::revoked::REVOKED_FILE,
264 super::disconnect::PENDING_FILE,
265 ] {
266 self.remove_config(name)?;
267 }
268 if !keep_local && self.data.exists() {
269 std::fs::remove_dir_all(&self.data)
270 .map_err(|e| HiveError::Local(format!("remove {}: {e}", self.data.display())))?;
271 }
272 Ok(())
273 }
274}
275
276fn to_json<T: Serialize>(value: &T) -> Result<Vec<u8>, HiveError> {
277 let mut bytes =
278 serde_json::to_vec_pretty(value).map_err(|e| HiveError::Local(format!("encode: {e}")))?;
279 bytes.push(b'\n');
280 Ok(bytes)
281}
282
283fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, HiveError> {
284 match std::fs::read(path) {
285 Ok(bytes) => Ok(Some(bytes)),
286 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
287 Err(e) => Err(HiveError::Local(format!("read {}: {e}", path.display()))),
288 }
289}
290
291fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, HiveError> {
292 let Some(bytes) = read_optional(path)? else {
293 return Ok(None);
294 };
295 serde_json::from_slice(&bytes)
296 .map(Some)
297 .map_err(|e| HiveError::Local(format!("{} is damaged: {e}", path.display())))
298}
299
300fn remove_optional(path: &Path) -> Result<(), HiveError> {
301 match std::fs::remove_file(path) {
302 Ok(()) => Ok(()),
303 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
304 Err(e) => Err(HiveError::Local(format!("remove {}: {e}", path.display()))),
305 }
306}
307
308pub(crate) fn write_private(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), HiveError> {
311 private_dir(dir)?;
312 crate::core::secure_fs::write_secret_file(&dir.join(name), bytes)
313 .map_err(|e| HiveError::Local(format!("write {name} in {}: {e}", dir.display())))
314}
315
316fn private_dir(dir: &Path) -> Result<(), HiveError> {
317 let local =
318 |what: &str, e: std::io::Error| HiveError::Local(format!("{what} {}: {e}", dir.display()));
319 std::fs::create_dir_all(dir).map_err(|e| local("create", e))?;
320 #[cfg(unix)]
321 {
322 use std::os::unix::fs::PermissionsExt as _;
323 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
324 .map_err(|e| local("restrict", e))?;
325 }
326 Ok(())
327}
328
329pub(crate) const DAMAGED_KEPT: usize = 3;
332
333pub(crate) fn load_or_quarantine<T: DeserializeOwned>(
339 path: &Path,
340 accept: impl FnOnce(&T) -> bool,
341) -> Result<Option<T>, HiveError> {
342 let Some(bytes) = read_optional(path)? else {
343 return Ok(None);
344 };
345 let why = match serde_json::from_slice::<T>(&bytes) {
346 Ok(value) if accept(&value) => return Ok(Some(value)),
347 Ok(_) => "a version this build does not know".to_string(),
348 Err(e) => e.to_string(),
349 };
350 let moved = quarantine(path)?;
351 Err(HiveError::Local(format!(
352 "{} is damaged ({why}); moved to {}",
353 path.display(),
354 moved.display()
355 )))
356}
357
358fn quarantine(path: &Path) -> Result<PathBuf, HiveError> {
361 let local = |e: std::io::Error| HiveError::Local(format!("quarantine {}: {e}", path.display()));
362 let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
363 return Err(HiveError::Local(format!("{} has no name", path.display())));
364 };
365 let prefix = format!("{name}.damaged-");
366 let mut copies: Vec<(u64, PathBuf)> = std::fs::read_dir(dir)
367 .map_err(local)?
368 .filter_map(Result::ok)
369 .filter_map(|e| {
370 let n = e
371 .file_name()
372 .to_str()?
373 .strip_prefix(&prefix)?
374 .parse()
375 .ok()?;
376 Some((n, e.path()))
377 })
378 .collect();
379 copies.sort_unstable();
380 let next = copies.last().map_or(1, |(n, _)| n + 1);
381 let moved = dir.join(format!("{prefix}{next}"));
382 std::fs::rename(path, &moved).map_err(local)?;
383 copies.push((next, moved.clone()));
384 let excess = copies.len().saturating_sub(DAMAGED_KEPT);
385 for (_, old) in copies.drain(..excess) {
386 let _ = std::fs::remove_file(old);
387 }
388 Ok(moved)
389}
390
391const STATE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
393
394pub(crate) struct StateLock(std::fs::File);
398
399impl Drop for StateLock {
400 fn drop(&mut self) {
401 let _ = fs2::FileExt::unlock(&self.0);
402 }
403}
404
405pub(crate) fn lock_state(dir: &Path, name: &str) -> Result<StateLock, HiveError> {
408 lock_state_within(dir, name, STATE_LOCK_WAIT)
409}
410
411pub(crate) fn lock_state_within(
413 dir: &Path,
414 name: &str,
415 wait: std::time::Duration,
416) -> Result<StateLock, HiveError> {
417 private_dir(dir)?;
418 let path = dir.join(format!("{name}.lock"));
419 let local = |what: &str| HiveError::Local(format!("{what} {}", path.display()));
420 let mut options = std::fs::OpenOptions::new();
421 options.read(true).write(true).create(true).truncate(false);
422 #[cfg(unix)]
423 {
424 use std::os::unix::fs::OpenOptionsExt as _;
425 options
426 .mode(0o600)
427 .custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
428 }
429 let file = options
430 .open(&path)
431 .map_err(|e| local(&format!("open ({e})")))?;
432 crate::core::file_lock::acquire_exclusive_timeout(&file, wait)
433 .map_err(|e| local(&format!("lock ({e})")))?;
434 Ok(StateLock(file))
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
444 fn workspace_label_names_personal_team_and_company() {
445 let mut r = InstanceRecord {
446 instance_id: "inst_1".into(),
447 org_id: "org_1".into(),
448 org_name: "Platform".into(),
449 label: "mbp".into(),
450 url: "https://hive.example".into(),
451 org_salt_id: "s".into(),
452 enrolled_at: "2026-10-26T10:00:00Z".into(),
453 web_url: None,
454 org_kind: None,
455 company_name: None,
456 };
457 assert_eq!(r.workspace_label(), "Platform");
458 r.org_kind = Some("team".into());
459 assert_eq!(r.workspace_label(), "Team Platform");
460 r.company_name = Some("Acme".into());
461 assert_eq!(r.workspace_label(), "Company Acme · Team Platform");
462 r.company_name = None;
463 r.org_kind = Some("personal".into());
464 assert_eq!(r.workspace_label(), "Personal (Platform)");
465 let old: InstanceRecord = serde_json::from_value(serde_json::json!({
467 "instance_id": "i", "org_id": "o", "org_name": "Acme", "label": "l", "url": "u",
468 "org_salt_id": "s", "enrolled_at": "t"
469 }))
470 .unwrap();
471 assert_eq!((old.org_kind, old.company_name), (None, None));
472 }
473
474 #[test]
475 fn private_files_are_atomic_and_owner_only() {
476 let dir = tempfile::tempdir().unwrap();
477 let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
478 let token = TokenRecord {
479 access_token: "atl_secret".into(),
480 expires_at: 1,
481 };
482 store.write_config(TOKEN_FILE, &token).unwrap();
483 assert_eq!(
484 store.read_config::<TokenRecord>(TOKEN_FILE).unwrap(),
485 Some(token.clone())
486 );
487 assert!(!format!("{token:?}").contains("atl_secret"));
488 #[cfg(unix)]
489 {
490 use std::os::unix::fs::PermissionsExt as _;
491 let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
492 assert_eq!(mode(store.config_dir()), 0o700);
493 assert_eq!(mode(&store.config_dir().join(TOKEN_FILE)), 0o600);
494 }
495 let leftovers: Vec<_> = std::fs::read_dir(store.config_dir())
496 .unwrap()
497 .filter_map(Result::ok)
498 .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
499 .collect();
500 assert!(leftovers.is_empty());
501 }
502
503 #[test]
504 fn damaged_state_is_moved_aside_and_only_three_copies_stay() {
505 let dir = tempfile::tempdir().unwrap();
506 let path = dir.path().join("state.json");
507 let load = |accept: bool| load_or_quarantine::<Value>(&path, |_| accept);
508 assert_eq!(load(true).unwrap(), None, "missing");
509 std::fs::write(&path, b"{\"ok\": 1}").unwrap();
510 assert_eq!(load(true).unwrap(), Some(serde_json::json!({"ok": 1})));
511 let error = load(false).unwrap_err().to_string();
513 assert!(error.contains("damaged-1"), "{error}");
514 assert!(!path.exists());
515 for n in 0..4 {
516 std::fs::write(&path, format!("broken {n}")).unwrap();
517 assert!(load(true).is_err());
518 }
519 let mut kept: Vec<String> = std::fs::read_dir(dir.path())
520 .unwrap()
521 .filter_map(|e| e.ok()?.file_name().into_string().ok())
522 .collect();
523 kept.sort();
524 assert_eq!(
525 kept,
526 [
527 "state.json.damaged-3",
528 "state.json.damaged-4",
529 "state.json.damaged-5"
530 ]
531 );
532 assert_eq!(
533 std::fs::read(dir.path().join("state.json.damaged-5")).unwrap(),
534 b"broken 3",
535 "the newest copy is the last damaged file"
536 );
537 }
538
539 #[test]
540 fn a_held_state_lock_is_not_taken_twice() {
541 let dir = tempfile::tempdir().unwrap();
542 let held = lock_state(dir.path(), "leases.json").unwrap();
543 assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_err());
544 drop(held);
545 assert!(lock_state_within(dir.path(), "leases.json", std::time::Duration::ZERO).is_ok());
546 #[cfg(unix)]
547 {
548 use std::os::unix::fs::PermissionsExt as _;
549 let mode = std::fs::metadata(dir.path().join("leases.json.lock"))
550 .unwrap()
551 .permissions()
552 .mode();
553 assert_eq!(mode & 0o777, 0o600);
554 }
555 }
556
557 #[test]
558 fn forget_keeps_local_data_on_request() {
559 let dir = tempfile::tempdir().unwrap();
560 let store = HiveStore::at(dir.path().join("config"), dir.path().join("data"));
561 store
562 .write_config(TOKEN_FILE, &serde_json::json!({}))
563 .unwrap();
564 store.record_success("lease", "2026-10-20T12:00:00Z");
565 store.forget(true).unwrap();
566 assert!(store.read_config_bytes(TOKEN_FILE).unwrap().is_none());
567 assert_eq!(
568 store.activity().last_seen.as_deref(),
569 Some("2026-10-20T12:00:00Z")
570 );
571 store.forget(false).unwrap();
572 assert!(store.activity().last_seen.is_none());
573 }
574}