mur_common/entitlements_pin/lock.rs
1//! One per-agent lock for every writer that advances the entitlement pin.
2//!
3//! The pin advance trusts the entitlements on disk at save time, so a writer
4//! that loaded the profile, then lost a race to another writer, would save its
5//! stale copy and move the pin onto it: a revoked grant comes back, pinned.
6//! Writers that advance the pin take this lock around their check-and-write
7//! (and `mur agent ssh` around its whole load–edit–save), so the check that
8//! the profile is still the one they loaded cannot be overtaken.
9//!
10//! The file lives in [`super::PINS_DIR`], which no agent sandbox may write, so
11//! an agent can neither hold the lock nor swap the file. It is never removed;
12//! dropping the guard, or the process dying, releases the `flock`.
13//!
14//! Not reentrant: `flock` is per open file, so a holder that takes it again in
15//! the same process waits on itself. Code that already holds it passes the
16//! guard down instead.
17
18use std::fs::{File, OpenOptions};
19use std::io;
20use std::path::{Path, PathBuf};
21
22use fs2::FileExt;
23
24use super::{PINS_DIR, PinError, checked_name};
25
26/// Suffix of the lock file beside `<agent>.json` in [`PINS_DIR`].
27const LOCK_SUFFIX: &str = "profile.lock";
28
29/// Held while a writer checks and writes `agent`'s profile and pin.
30#[derive(Debug)]
31pub struct ProfileLock {
32 _file: File,
33}
34
35/// `<mur_home>/entitlement-pins/<agent>.profile.lock`.
36pub fn lock_path(mur_home: &Path, agent: &str) -> PathBuf {
37 mur_home
38 .join(PINS_DIR)
39 .join(format!("{agent}.{LOCK_SUFFIX}"))
40}
41
42/// Take `agent`'s profile lock, waiting for the current holder. `on_wait` runs
43/// once, before blocking, only when another writer holds it (so a CLI can say
44/// why it paused). Holders never prompt, so the wait is one write long.
45pub fn lock_profile(
46 mur_home: &Path,
47 agent: &str,
48 on_wait: impl FnOnce(),
49) -> Result<ProfileLock, PinError> {
50 checked_name(agent)?;
51 let path = lock_path(mur_home, agent);
52 let io_err = |source: io::Error| PinError::Io {
53 path: path.clone(),
54 source,
55 };
56 std::fs::create_dir_all(mur_home.join(PINS_DIR)).map_err(io_err)?;
57 let file = OpenOptions::new()
58 .create(true)
59 .read(true)
60 .write(true)
61 .truncate(false)
62 .open(&path)
63 .map_err(io_err)?;
64 if file.try_lock_exclusive().is_err() {
65 on_wait();
66 file.lock_exclusive().map_err(io_err)?;
67 }
68 Ok(ProfileLock { _file: file })
69}