vault_core/pool.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The key-pool state file: `pools.json`.
4//!
5//! A key pool is several interchangeable credentials for one service. Which one
6//! to hand out next, which are cooling after a rate limit, and how often each
7//! has been used are **per-machine** facts, so they are kept here rather than in
8//! the vault. Three reasons, worst failure first:
9//!
10//! 1. [`save_vault`](crate::save_vault) appends a `vault_audit` row on every
11//! update. A CI loop calling `unv exec` would grow the hash-chained log
12//! without bound - the same reason read events stopped being audited.
13//! 2. `save_vault` is a compare-and-swap. Concurrent reads against one vault
14//! would collide and start returning conflicts for *reads*.
15//! 3. A vault is shared; a rotation cursor is not. Two CI runners pulling from
16//! one remote vault want independent cursors.
17//!
18//! # Why this lives in vault-core
19//!
20//! Two programs read this file: `unv` and the desktop app. The app's
21//! `app_data_dir` and the CLI's `dirs::data_dir()/io.unenverse` resolve to the
22//! same directory, so one vault produces the same [`local_vault_key`] in both -
23//! report a key rate limited from CI and the desktop shows it cooling.
24//!
25//! That only holds while both agree on the file's shape, its path, and the
26//! cooldown arithmetic. This project has been bitten by two implementations of
27//! one format drifting apart often enough to have a convention about it, so
28//! there is exactly one implementation and both callers use it.
29//!
30//! # Shape
31//!
32//! ```json
33//! {
34//! "version": 1,
35//! "vaults": {
36//! "local:/home/me/.local/share/io.unenverse/vault.db": {
37//! "github-ci": {
38//! "cursor": 1,
39//! "members": {
40//! "<entry_ck>": {
41//! "uses": 12,
42//! "last_used_at": "2026-08-25T11:02:31Z",
43//! "cooling_until": "2026-08-25T11:17:31Z"
44//! }
45//! }
46//! }
47//! }
48//! }
49//! }
50//! ```
51//!
52//! Members are keyed by [`entry_ck`](crate::entry_ck) - the same stable identity
53//! version history and audit attribution use - so renaming an entry keeps its
54//! pool state, and two entries sharing a provider never collapse into one.
55
56use serde_json::{json, Value};
57use std::path::PathBuf;
58
59/// Where `pools.json` lives.
60///
61/// `$XDG_STATE_HOME/unv/` on Unix, `%LOCALAPPDATA%\unv\` on Windows, falling
62/// back to `~/.local/state/unv/`. The same directory as the CLI's
63/// `sessions.json`.
64///
65/// Returns `None` rather than guessing when there is no home directory to work
66/// from (the CLI's `session::state_file` has no such escape and exits 7 there). There is deliberately no `.` fallback: a per-directory rotation cursor
67/// is its own quiet bug, where the same pool restarts at the first key every
68/// time you change directory.
69pub fn state_path() -> Option<PathBuf> {
70 if let Some(explicit) = std::env::var_os("UNV_POOL_FILE") {
71 return Some(PathBuf::from(explicit));
72 }
73 #[cfg(windows)]
74 {
75 // %LOCALAPPDATA% is per-user and excluded from roaming profiles, so a
76 // machine-local cursor cannot be synced onto another machine by a
77 // domain profile nobody thinks about.
78 if let Some(dir) = dirs::data_local_dir() {
79 return Some(dir.join("unv").join("pools.json"));
80 }
81 }
82 if let Some(dir) = std::env::var_os("XDG_STATE_HOME") {
83 return Some(PathBuf::from(dir).join("unv").join("pools.json"));
84 }
85 dirs::home_dir().map(|h| {
86 h.join(".local")
87 .join("state")
88 .join("unv")
89 .join("pools.json")
90 })
91}
92
93/// An empty state document.
94fn empty() -> Value {
95 json!({ "version": 1, "vaults": {} })
96}
97
98/// Read the state file, or an empty document.
99///
100/// A missing, unreadable or malformed file all yield the empty document rather
101/// than an error. This file is bookkeeping: refusing to work because it is
102/// corrupt would turn a cosmetic problem into an outage, and the next write
103/// repairs it.
104pub fn load() -> Value {
105 state_path()
106 .and_then(|p| std::fs::read_to_string(p).ok())
107 .and_then(|raw| serde_json::from_str(&raw).ok())
108 .unwrap_or_else(empty)
109}
110
111/// Write the state file, creating its directory and restricting it to its owner.
112///
113/// Atomic: written beside the target and renamed over it, so a reader never sees a
114/// half-written file. It used to truncate and write in place, and a concurrent
115/// `load()` that parsed the torn text fell back to an empty document, which the next
116/// save then wrote out, erasing every cursor and cooldown on the machine.
117pub fn save(state: &Value) -> Result<(), String> {
118 let path = state_path().ok_or_else(|| {
119 "Cannot determine a home directory for per-user state (no $HOME on Unix, \
120 no %USERPROFILE% on Windows). Set UNV_POOL_FILE to choose the location."
121 .to_string()
122 })?;
123 if let Some(parent) = path.parent() {
124 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
125 }
126 let mut tmp_name = path
127 .file_name()
128 .map(|n| n.to_os_string())
129 .unwrap_or_default();
130 tmp_name.push(format!(".{}.tmp", std::process::id()));
131 let tmp = path.with_file_name(tmp_name);
132 std::fs::write(
133 &tmp,
134 serde_json::to_string_pretty(state).unwrap_or_default(),
135 )
136 .map_err(|e| format!("Cannot write {}: {e}", tmp.display()))?;
137 restrict(&tmp)?;
138 crate::platform::replace_file(&tmp, &path).map_err(|e| {
139 let _ = std::fs::remove_file(&tmp);
140 format!("Cannot replace {}: {e}", path.display())
141 })
142}
143
144/// Read, change and write the state under an exclusive lock.
145///
146/// Two runners (two `unv exec --pool`, the app beside the CLI) each did `load()`,
147/// picked a member, `record_use` and `save()`: the second save erased the first's
148/// cursor move and use count, so two callers were handed the same key and a cooldown
149/// set by one was lost, handing a just-rate-limited key out again. Holding the lock
150/// from the read to the rename makes each runner see the previous one's result.
151/// Returns the closure's value and, if the write failed, why.
152pub fn update<T>(f: impl FnOnce(&mut Value) -> T) -> Result<(T, Option<String>), String> {
153 let path = state_path().ok_or_else(|| {
154 "Cannot determine a home directory for per-user state (no $HOME on Unix, \
155 no %USERPROFILE% on Windows). Set UNV_POOL_FILE to choose the location."
156 .to_string()
157 })?;
158 if let Some(parent) = path.parent() {
159 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
160 }
161 let mut lock_name = path
162 .file_name()
163 .map(|n| n.to_os_string())
164 .unwrap_or_default();
165 lock_name.push(".lock");
166 let lock = std::fs::OpenOptions::new()
167 .create(true)
168 .truncate(false)
169 .write(true)
170 .open(path.with_file_name(lock_name))
171 .map_err(|e| format!("Cannot open the pool lock: {e}"))?;
172 lock.lock()
173 .map_err(|e| format!("Cannot lock the pool state: {e}"))?;
174 let mut state = load();
175 let out = f(&mut state);
176 // A failed write is reported next to the value, not instead of it: a caller that
177 // already chose a credential must still be able to hand it over.
178 let saved = save(&state).err();
179 Ok((out, saved)) // the lock is released when `lock` drops
180}
181
182/// Restrict the state file to its owner.
183///
184/// It holds no secret, but it records which credentials this machine uses and
185/// how often - a usage map of the vault, which is the kind of thing the audit
186/// design already treats as sensitive. Same 0600 treatment as the session file.
187///
188/// The body is `#[cfg(unix)]`, so on Windows `path` genuinely is unused, and the
189/// workspace builds with warnings denied. Silenced only on the target where that
190/// is true, so a real unused binding added here later still fails on Linux.
191#[cfg_attr(not(unix), allow(unused_variables))]
192fn restrict(path: &std::path::Path) -> Result<(), String> {
193 #[cfg(unix)]
194 {
195 use std::os::unix::fs::PermissionsExt;
196 let mut perms = std::fs::metadata(path)
197 .map_err(|e| e.to_string())?
198 .permissions();
199 perms.set_mode(0o600);
200 std::fs::set_permissions(path, perms).map_err(|e| e.to_string())?;
201 }
202 Ok(())
203}
204
205/// State is filed per vault, so connecting to a different server does not
206/// inherit the last one's cursor - the same reasoning as resetting view state on
207/// a vault switch in the app.
208pub fn local_vault_key(db_path: &std::path::Path) -> String {
209 format!("local:{}", db_path.display())
210}
211
212/// The remote counterpart of [`local_vault_key`].
213pub fn remote_vault_key(base_url: &str) -> String {
214 format!("remote:{base_url}")
215}
216
217/// One member's stored state.
218#[derive(Debug, Clone, Default, PartialEq, Eq)]
219pub struct MemberState {
220 pub uses: u64,
221 pub last_used_at: Option<String>,
222 pub cooling_until: Option<String>,
223}
224
225/// Read one member's state out of a loaded document.
226pub fn member_state(state: &Value, vault_key: &str, pool: &str, ck: &str) -> MemberState {
227 let slot = &state["vaults"][vault_key][pool]["members"][ck];
228 MemberState {
229 uses: slot["uses"].as_u64().unwrap_or(0),
230 last_used_at: slot["last_used_at"].as_str().map(str::to_string),
231 cooling_until: slot["cooling_until"].as_str().map(str::to_string),
232 }
233}
234
235/// The cursor for a pool, or 0.
236pub fn cursor(state: &Value, vault_key: &str, pool: &str) -> usize {
237 state["vaults"][vault_key][pool]["cursor"]
238 .as_u64()
239 .unwrap_or(0) as usize
240}
241
242/// Ensure `vaults.<key>.<pool>` exists so the writers below can index into it.
243fn ensure(state: &mut Value, vault_key: &str, pool: &str) {
244 if !state["vaults"][vault_key][pool].is_object() {
245 state["vaults"][vault_key][pool] = json!({ "cursor": 0, "members": {} });
246 }
247}
248
249/// Record that a member was handed out, and where the cursor moves to.
250pub fn record_use(
251 state: &mut Value,
252 vault_key: &str,
253 pool: &str,
254 ck: &str,
255 next_cursor: usize,
256 now: i64,
257) {
258 ensure(state, vault_key, pool);
259 let uses = member_state(state, vault_key, pool, ck).uses;
260 state["vaults"][vault_key][pool]["cursor"] = json!(next_cursor as u64);
261 state["vaults"][vault_key][pool]["members"][ck]["uses"] = json!(uses + 1);
262 state["vaults"][vault_key][pool]["members"][ck]["last_used_at"] = json!(iso_at(now));
263}
264
265/// Put a member on cooldown until `until_ts`, or clear its cooldown with `None`.
266pub fn set_cooldown(
267 state: &mut Value,
268 vault_key: &str,
269 pool: &str,
270 ck: &str,
271 until_ts: Option<i64>,
272) {
273 ensure(state, vault_key, pool);
274 let slot = &mut state["vaults"][vault_key][pool]["members"][ck];
275 match until_ts {
276 Some(ts) => slot["cooling_until"] = json!(iso_at(ts)),
277 None => {
278 if let Some(obj) = slot.as_object_mut() {
279 obj.remove("cooling_until");
280 }
281 }
282 }
283}
284
285/// Round-robin over the members that are not cooling, starting at `cursor`.
286///
287/// The cursor indexes the **full** member list rather than a filtered one, so
288/// a member going on cooldown does not shift every other member's position
289/// and make the next call skip an unrelated key. `None` when every member is
290/// cooling. Shared by `unv pool next`/`unv get --pool` (`unv-app/src/pool.rs`)
291/// and the desktop card's Copy button (`pool_next` in `src-tauri`) — two
292/// callers picking a member by two different rules is exactly the shape that
293/// hands one caller a key the other just put on cooldown.
294pub fn pick_index(cooling: &[bool], cursor: usize) -> Option<usize> {
295 let n = cooling.len();
296 if n == 0 {
297 return None;
298 }
299 (0..n).map(|off| (cursor + off) % n).find(|i| !cooling[*i])
300}
301
302/// Forget a pool's cursor, cooldowns and counts for one vault.
303pub fn forget(state: &mut Value, vault_key: &str, pool: &str) {
304 if let Some(obj) = state["vaults"][vault_key].as_object_mut() {
305 obj.remove(pool);
306 }
307}
308
309/// Is this member cooling at `now`?
310///
311/// A `cooling_until` that is not a timestamp is treated as **not** cooling.
312/// `pools.json` is a plain file a user can edit and a half-written one is a real
313/// state; reading garbage as "cooling forever" would take a key out of service
314/// with nothing on screen explaining why.
315pub fn is_cooling(cooling_until: Option<&str>, now: i64) -> bool {
316 cooling_until
317 .and_then(parse_rfc3339)
318 .is_some_and(|t| t > now)
319}
320
321/// Seconds since the epoch, now.
322pub fn now_ts() -> i64 {
323 time::OffsetDateTime::now_utc().unix_timestamp()
324}
325
326/// RFC 3339 for an arbitrary instant.
327///
328/// Hand-formatted rather than `OffsetDateTime::format`, because the workspace
329/// pins `time` without its `formatting` feature. [`iso_now`](crate::iso_now)
330/// does the same for "now"; keeping the shape identical matters because these
331/// strings sit beside `last_rotated_at` and friends written by that function.
332pub fn iso_at(ts: i64) -> String {
333 let Ok(t) = time::OffsetDateTime::from_unix_timestamp(ts) else {
334 return String::new();
335 };
336 format!(
337 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
338 t.year(),
339 t.month() as u8,
340 t.day(),
341 t.hour(),
342 t.minute(),
343 t.second()
344 )
345}
346
347/// Read one of the timestamps [`iso_at`] writes: exactly `YYYY-MM-DDTHH:MM:SSZ`.
348///
349/// Hand-parsed rather than via `OffsetDateTime::parse`, which needs the `time`
350/// crate's `parsing` feature that vault-core deliberately does not enable — the
351/// same reasoning as [`iso_at`] not using `format`. Nothing is lost by being
352/// strict here: this only ever reads back a string this module wrote, and
353/// anything else must be rejected anyway, because `pools.json` is a plain file
354/// a user can edit and [`is_cooling`] has to treat garbage as "not cooling"
355/// rather than "cooling forever".
356pub fn parse_rfc3339(s: &str) -> Option<i64> {
357 let b = s.as_bytes();
358 if b.len() != 20
359 || b[4] != b'-'
360 || b[7] != b'-'
361 || b[10] != b'T'
362 || b[13] != b':'
363 || b[16] != b':'
364 || b[19] != b'Z'
365 {
366 return None;
367 }
368 let num = |from: usize, to: usize| s.get(from..to)?.parse::<u32>().ok();
369 let year = num(0, 4)? as i32;
370 let month = time::Month::try_from(num(5, 7)? as u8).ok()?;
371 let day = num(8, 10)? as u8;
372 let (h, m, sec) = (num(11, 13)? as u8, num(14, 16)? as u8, num(17, 19)? as u8);
373
374 let date = time::Date::from_calendar_date(year, month, day).ok()?;
375 let time_of_day = time::Time::from_hms(h, m, sec).ok()?;
376 Some(
377 time::PrimitiveDateTime::new(date, time_of_day)
378 .assume_utc()
379 .unix_timestamp(),
380 )
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386
387 const NOW: i64 = 1_700_000_000;
388 const A: &str = "id-aaa";
389 const B: &str = "id-bbb";
390
391 #[test]
392 fn cooling_reads_a_future_timestamp() {
393 assert!(is_cooling(Some(&iso_at(NOW + 60)), NOW));
394 }
395
396 #[test]
397 fn an_expired_cooldown_is_not_a_cooldown() {
398 assert!(!is_cooling(Some(&iso_at(NOW - 1)), NOW));
399 }
400
401 #[test]
402 fn garbage_is_not_a_cooldown() {
403 // A hand-edited or half-written pools.json must not take a key out of
404 // service with nothing on screen explaining why.
405 assert!(!is_cooling(Some("not a date"), NOW));
406 assert!(!is_cooling(Some(""), NOW));
407 assert!(!is_cooling(None, NOW));
408 }
409
410 #[test]
411 fn iso_at_round_trips_and_matches_iso_now_shape() {
412 let s = iso_at(NOW);
413 assert_eq!(s.len(), 20, "YYYY-MM-DDTHH:MM:SSZ");
414 assert!(s.ends_with('Z'));
415 assert_eq!(parse_rfc3339(&s), Some(NOW));
416 }
417
418 #[test]
419 fn use_and_cooldown_accumulate_on_the_right_member() {
420 let mut st = empty();
421 let vk = "local:/tmp/v.db";
422 record_use(&mut st, vk, "p", A, 1, NOW);
423 record_use(&mut st, vk, "p", A, 0, NOW);
424 record_use(&mut st, vk, "p", B, 1, NOW);
425
426 assert_eq!(member_state(&st, vk, "p", A).uses, 2);
427 assert_eq!(member_state(&st, vk, "p", B).uses, 1);
428 assert_eq!(cursor(&st, vk, "p"), 1);
429
430 set_cooldown(&mut st, vk, "p", A, Some(NOW + 900));
431 assert!(is_cooling(
432 member_state(&st, vk, "p", A).cooling_until.as_deref(),
433 NOW
434 ));
435 assert!(
436 !is_cooling(member_state(&st, vk, "p", B).cooling_until.as_deref(), NOW),
437 "cooling one member must not cool another"
438 );
439
440 set_cooldown(&mut st, vk, "p", A, None);
441 assert_eq!(
442 member_state(&st, vk, "p", A).cooling_until,
443 None,
444 "clearing removes the key rather than writing a past timestamp"
445 );
446 assert_eq!(
447 member_state(&st, vk, "p", A).uses,
448 2,
449 "clearing a cooldown must not reset the use count"
450 );
451 }
452
453 #[test]
454 fn state_is_partitioned_by_vault() {
455 // Connecting to a different vault must not inherit the last one's
456 // cursor - the same reasoning as resetting view state on a switch.
457 let mut st = empty();
458 record_use(&mut st, "local:/a.db", "p", A, 3, NOW);
459 assert_eq!(cursor(&st, "local:/a.db", "p"), 3);
460 assert_eq!(cursor(&st, "remote:https://host", "p"), 0);
461 assert_eq!(member_state(&st, "remote:https://host", "p", A).uses, 0);
462 }
463
464 #[test]
465 fn forget_clears_one_pool_and_leaves_the_others() {
466 let mut st = empty();
467 let vk = "local:/a.db";
468 record_use(&mut st, vk, "keep", A, 1, NOW);
469 record_use(&mut st, vk, "drop", B, 1, NOW);
470 forget(&mut st, vk, "drop");
471 assert_eq!(member_state(&st, vk, "drop", B).uses, 0);
472 assert_eq!(member_state(&st, vk, "keep", A).uses, 1);
473 }
474}