Skip to main content

mur_common/
entitlements_pin.rs

1//! Out-of-tree pin of an agent's `entitlements` (#712, Linux).
2//!
3//! On Linux, Landlock is allow-only: the agent's own home is granted whole, so
4//! the agent's bash tool can rewrite its own `profile.yaml` — and with it the
5//! entitlements the next start seals. macOS denies that write in SBPL; Linux
6//! cannot express the carve-out. The pin closes it for both: the supervisor
7//! refuses to start when the profile's entitlements differ from the copy kept
8//! at `<mur_home>/entitlement-pins/<name>.json`, a directory no agent sandbox
9//! grants write to (see `LaunchChain::deny_paths`).
10//!
11//! Scope is `entitlements` only, not the whole profile: model, skills and
12//! companion fields are edited by hand and by many writers, and none of them
13//! widens what the kernel lets the agent do.
14//!
15//! The pin stores the canonical JSON, not a hash. Comparison re-reads the
16//! stored JSON through the CURRENT `Entitlements` schema, so a runtime upgrade
17//! that adds a defaulted field compares equal instead of bricking every agent.
18
19use std::io;
20use std::path::{Path, PathBuf};
21
22use crate::agent::{AgentProfile, Entitlements};
23
24mod lock;
25pub use lock::{ProfileLock, lock_path, lock_profile};
26
27/// Directory under `<mur_home>` holding one pin per agent.
28pub const PINS_DIR: &str = "entitlement-pins";
29
30const PIN_EXT: &str = "json";
31
32/// Pin file format version, for a future change of layout.
33const PIN_VERSION: u32 = 1;
34
35#[derive(serde::Serialize, serde::Deserialize)]
36struct PinFile {
37    version: u32,
38    entitlements: serde_json::Value,
39}
40
41/// `<mur_home>/entitlement-pins/<name>.json`.
42pub fn pin_path(mur_home: &Path, agent: &str) -> PathBuf {
43    mur_home.join(PINS_DIR).join(format!("{agent}.{PIN_EXT}"))
44}
45
46/// Outcome of comparing a profile against its pin.
47#[derive(Debug, PartialEq, Eq)]
48pub enum PinCheck {
49    /// The profile's entitlements equal the pinned ones.
50    Match,
51    /// No pin yet (install predates #712, or the pin was deleted).
52    Missing,
53    /// Entitlements differ. Lists the top-level entitlement keys that changed.
54    Mismatch { changed: Vec<String> },
55}
56
57#[derive(Debug, thiserror::Error)]
58pub enum PinError {
59    #[error("io error on {path}: {source}")]
60    Io { path: PathBuf, source: io::Error },
61    #[error("invalid pin file {path}: {msg}")]
62    Invalid { path: PathBuf, msg: String },
63    #[error("invalid profile {path}: {msg}")]
64    Profile { path: PathBuf, msg: String },
65    #[error("invalid agent name '{0}'")]
66    Name(String),
67}
68
69fn canonical(ent: &Entitlements) -> serde_json::Value {
70    // Entitlements holds only plain data; serialization cannot fail.
71    serde_json::to_value(ent).expect("Entitlements serializes to JSON")
72}
73
74fn checked_name(agent: &str) -> Result<(), PinError> {
75    crate::agent_name::validate_agent_name(agent).map_err(|_| PinError::Name(agent.to_string()))
76}
77
78/// Pin `ent` for `agent`. Temp file + rename, so a crash never leaves a torn
79/// pin that would block the next start.
80pub fn write_pin(mur_home: &Path, agent: &str, ent: &Entitlements) -> Result<(), PinError> {
81    checked_name(agent)?;
82    let path = pin_path(mur_home, agent);
83    let io_err = |source| PinError::Io {
84        path: path.clone(),
85        source,
86    };
87    let dir = mur_home.join(PINS_DIR);
88    std::fs::create_dir_all(&dir).map_err(io_err)?;
89    let body = PinFile {
90        version: PIN_VERSION,
91        entitlements: canonical(ent),
92    };
93    let bytes = crate::jcs::to_jcs_for(&body);
94    let mut tmp = tempfile::NamedTempFile::new_in(&dir).map_err(io_err)?;
95    io::Write::write_all(&mut tmp, &bytes).map_err(io_err)?;
96    tmp.persist(&path).map_err(|e| io_err(e.error))?;
97    Ok(())
98}
99
100/// Parse the entitlements out of raw (unexpanded) profile YAML.
101///
102/// Unexpanded on purpose: writers persist `{{agent_home}}` templates, and the
103/// pin must compare what is on disk, not a machine-specific expansion.
104pub fn entitlements_from_yaml(yaml: &str, path: &Path) -> Result<Entitlements, PinError> {
105    serde_yaml_ng::from_str::<AgentProfile>(yaml)
106        .map(|p| p.entitlements)
107        .map_err(|e| PinError::Profile {
108            path: path.to_path_buf(),
109            msg: e.to_string(),
110        })
111}
112
113/// Re-pin `agent` from its on-disk `profile.yaml`. Every trusted writer that
114/// changes entitlements calls this after its write lands; so does
115/// `mur agent perm reseal` after the user confirms a change.
116pub fn repin_from_profile(mur_home: &Path, agent: &str) -> Result<(), PinError> {
117    checked_name(agent)?;
118    let path = mur_home.join("agents").join(agent).join("profile.yaml");
119    let yaml = std::fs::read_to_string(&path).map_err(|source| PinError::Io {
120        path: path.clone(),
121        source,
122    })?;
123    let ent = entitlements_from_yaml(&yaml, &path)?;
124    write_pin(mur_home, agent, &ent)
125}
126
127/// Advance the pin after a trusted writer saved `new`, but only from a trusted
128/// state: the entitlements on disk BEFORE the write (`prior`) must match the
129/// pin, or there must be no pin yet. Otherwise a tampered profile would be
130/// laundered into the pin by the next unrelated save (`mur agent model set`
131/// reads the tampered file and writes it back); instead the pin stays stale and
132/// the next start refuses until the user runs `mur agent perm reseal`.
133///
134/// Returns whether the pin was advanced.
135pub fn advance_pin(
136    mur_home: &Path,
137    agent: &str,
138    prior: Option<&Entitlements>,
139    new: &Entitlements,
140) -> Result<bool, PinError> {
141    let trusted = match prior {
142        // Fresh profile (create / import): nothing on disk to have tampered.
143        None => true,
144        Some(p) => matches!(
145            check(mur_home, agent, p)?,
146            PinCheck::Match | PinCheck::Missing
147        ),
148    };
149    if trusted {
150        write_pin(mur_home, agent, new)?;
151    }
152    Ok(trusted)
153}
154
155/// Drop `agent`'s pin (purge), so a later agent of the same name starts clean
156/// instead of refusing on a stranger's pin. Missing is not an error.
157pub fn remove_pin(mur_home: &Path, agent: &str) -> Result<(), PinError> {
158    checked_name(agent)?;
159    let path = pin_path(mur_home, agent);
160    match std::fs::remove_file(&path) {
161        Ok(()) => Ok(()),
162        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
163        Err(source) => Err(PinError::Io { path, source }),
164    }
165}
166
167/// Carry the pin across `mur agent rename`. No pin to move is not an error.
168pub fn rename_pin(mur_home: &Path, old: &str, new: &str) -> Result<(), PinError> {
169    checked_name(old)?;
170    checked_name(new)?;
171    let (from, to) = (pin_path(mur_home, old), pin_path(mur_home, new));
172    match std::fs::rename(&from, &to) {
173        Ok(()) => Ok(()),
174        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
175        Err(source) => Err(PinError::Io { path: from, source }),
176    }
177}
178
179/// Compare `ent` against the pin for `agent`.
180pub fn check(mur_home: &Path, agent: &str, ent: &Entitlements) -> Result<PinCheck, PinError> {
181    checked_name(agent)?;
182    let path = pin_path(mur_home, agent);
183    let raw = match std::fs::read(&path) {
184        Ok(b) => b,
185        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(PinCheck::Missing),
186        Err(source) => return Err(PinError::Io { path, source }),
187    };
188    let invalid = |msg: String| PinError::Invalid {
189        path: path.clone(),
190        msg,
191    };
192    let file: PinFile = serde_json::from_slice(&raw).map_err(|e| invalid(e.to_string()))?;
193    if file.version != PIN_VERSION {
194        return Err(invalid(format!("unsupported version {}", file.version)));
195    }
196    // Round-trip through the current schema: fields added since the pin was
197    // written take their defaults on both sides and compare equal.
198    let pinned: Entitlements =
199        serde_json::from_value(file.entitlements).map_err(|e| invalid(e.to_string()))?;
200    let (a, b) = (canonical(&pinned), canonical(ent));
201    if a == b {
202        return Ok(PinCheck::Match);
203    }
204    Ok(PinCheck::Mismatch {
205        changed: changed_keys(&a, &b),
206    })
207}
208
209/// Top-level entitlement keys that differ between `a` and `b`, sorted.
210pub fn changed_entitlements(a: &Entitlements, b: &Entitlements) -> Vec<String> {
211    let (a, b) = (canonical(a), canonical(b));
212    if a == b {
213        return Vec::new();
214    }
215    changed_keys(&a, &b)
216}
217
218fn changed_keys(a: &serde_json::Value, b: &serde_json::Value) -> Vec<String> {
219    let (Some(a), Some(b)) = (a.as_object(), b.as_object()) else {
220        return vec!["entitlements".to_string()];
221    };
222    let mut keys: Vec<String> = a
223        .keys()
224        .chain(b.keys())
225        .filter(|k| a.get(*k) != b.get(*k))
226        .cloned()
227        .collect();
228    keys.sort();
229    keys.dedup();
230    keys
231}
232
233#[cfg(test)]
234mod tests;