Skip to main content

mur_common/
identity_pin.rs

1//! Out-of-tree pin of an agent's public identity (#2318).
2//!
3//! `identity.pub` and `rotations.jsonl` live in the agent's own home, which
4//! the agent's sandbox grants write to whole. macOS re-denies those two files
5//! in SBPL; Landlock (Linux) cannot carve a single file out of a granted
6//! directory, so there the agent's `bash` can rewrite them. `verify_chain` has
7//! no trust anchor of its own, so a chain the agent forged from a key it
8//! generated would verify, and every verifier would accept that key as the
9//! agent's identity.
10//!
11//! The pin is the anchor. Trusted writers (`mur agent create`, import, clone,
12//! and the runtime's pre-seal trust-on-first-use) copy the identity to
13//! `<mur_home>/identity-pins/<name>.json`, a directory no agent sandbox may
14//! write (see `LaunchChain::deny_paths`). Verifiers of a pinned
15//! agent read the pin and never the agent's own copies, so a forged chain or a
16//! rewritten `identity.pub` changes nothing anyone trusts. `mur agent rekey`
17//! never re-reads the disk chain: it extends the pin with the one rotation it
18//! just signed (`extend_pin`), so a history the agent forged is never imported.
19//! A runtime that cannot pin on first use writes a fail-closed pin and refuses
20//! to start, so the legacy read-from-disk fallback is never left open.
21//!
22//! Same mechanism and the same trust-on-first-use caveat as the entitlement
23//! pin (`crate::entitlements_pin`, #712).
24
25use std::io;
26use std::path::{Path, PathBuf};
27
28use crate::identity::{ChainOptions, RotationAttestation, verify_chain};
29
30/// Directory under `<mur_home>` holding one identity pin per agent.
31pub const IDENTITY_PINS_DIR: &str = "identity-pins";
32
33/// The agent-home files the pin is taken from.
34pub const PUBKEY_FILE: &str = "identity.pub";
35pub const CHAIN_FILE: &str = "rotations.jsonl";
36
37const PIN_EXT: &str = "json";
38const PIN_VERSION: u32 = 1;
39
40/// The pinned identity: the trusted current key and the trusted chain that
41/// leads to it (empty for an identity minted without one, e.g. an import).
42#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
43pub struct IdentityPin {
44    pub version: u32,
45    pub pubkey: String,
46    pub key_version: u32,
47    pub chain: Vec<RotationAttestation>,
48    /// Fail-closed marker: the runtime could not establish a trusted identity
49    /// (no key on disk, or an inconsistent one), so verifiers trust no key at
50    /// all rather than the agent's own files. Cleared only by
51    /// `mur agent rekey --emergency`.
52    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
53    pub fail_closed: bool,
54}
55
56#[derive(Debug, thiserror::Error)]
57pub enum IdentityPinError {
58    #[error("io error on {path}: {source}")]
59    Io { path: PathBuf, source: io::Error },
60    #[error("invalid identity pin {path}: {msg}")]
61    Invalid { path: PathBuf, msg: String },
62    #[error("identity of '{agent}' is inconsistent: {msg}")]
63    Inconsistent { agent: String, msg: String },
64    #[error("invalid agent name '{0}'")]
65    Name(String),
66    #[error("rotation of '{agent}' does not extend its pinned identity: {msg}")]
67    NotAnExtension { agent: String, msg: String },
68}
69
70/// What a verifier should trust for one agent.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct TrustedIdentity {
73    /// The trusted current pubkey (multibase).
74    pub head_pubkey: String,
75    pub head_key_version: u32,
76    /// A strictly-verified chain covering `head_key_version`, when one exists.
77    /// `None` means only the head key is known (no chain, or the pinned chain
78    /// itself does not verify strictly, e.g. an unapproved emergency rekey).
79    pub chain: Option<Vec<RotationAttestation>>,
80}
81
82/// `<mur_home>/identity-pins/<name>.json`.
83pub fn pin_path(mur_home: &Path, agent: &str) -> PathBuf {
84    mur_home
85        .join(IDENTITY_PINS_DIR)
86        .join(format!("{agent}.{PIN_EXT}"))
87}
88
89fn checked_name(agent: &str) -> Result<(), IdentityPinError> {
90    crate::agent_name::validate_agent_name(agent)
91        .map_err(|_| IdentityPinError::Name(agent.to_string()))
92}
93
94/// `(mur_home, name)` when `agent_home` is `<mur_home>/agents/<name>`. Only an
95/// installed agent has a pin; any other directory (an embedded runtime's cache
96/// dir, a test fixture) keeps the legacy read-from-disk behavior.
97pub fn split_agent_home(agent_home: &Path) -> Option<(&Path, &str)> {
98    let parent = agent_home.parent()?;
99    if parent.file_name()? != "agents" {
100        return None;
101    }
102    let name = agent_home.file_name()?.to_str()?;
103    crate::agent_name::validate_agent_name(name).ok()?;
104    Some((parent.parent()?, name))
105}
106
107/// Parse `rotations.jsonl` text strictly: one bad line rejects the whole file.
108pub fn parse_chain(text: &str) -> Option<Vec<RotationAttestation>> {
109    text.lines()
110        .filter(|l| !l.trim().is_empty())
111        .map(serde_json::from_str)
112        .collect::<Result<_, _>>()
113        .ok()
114}
115
116/// Pin the identity currently on disk in `<mur_home>/agents/<agent>`.
117///
118/// Only trusted writers call this: the CLI right after it minted or rotated
119/// the key, and the runtime before its sandbox seals. A chain whose head does
120/// not match `identity.pub` is refused rather than pinned.
121pub fn pin_from_disk(mur_home: &Path, agent: &str) -> Result<IdentityPin, IdentityPinError> {
122    checked_name(agent)?;
123    let home = mur_home.join("agents").join(agent);
124    let pub_path = home.join(PUBKEY_FILE);
125    let pubkey = std::fs::read_to_string(&pub_path)
126        .map_err(|source| IdentityPinError::Io {
127            path: pub_path.clone(),
128            source,
129        })?
130        .trim()
131        .to_string();
132    let chain_path = home.join(CHAIN_FILE);
133    let chain = match std::fs::read_to_string(&chain_path) {
134        Ok(text) => parse_chain(&text).ok_or_else(|| IdentityPinError::Invalid {
135            path: chain_path.clone(),
136            msg: "unparseable rotation attestation".into(),
137        })?,
138        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
139        Err(source) => {
140            return Err(IdentityPinError::Io {
141                path: chain_path,
142                source,
143            });
144        }
145    };
146    let key_version = match chain.last() {
147        Some(head) if head.new_pubkey != pubkey => {
148            return Err(IdentityPinError::Inconsistent {
149                agent: agent.to_string(),
150                msg: format!("{CHAIN_FILE} head is not {PUBKEY_FILE}"),
151            });
152        }
153        Some(head) => head.new_key_version,
154        None => 0,
155    };
156    let pin = IdentityPin {
157        version: PIN_VERSION,
158        pubkey,
159        key_version,
160        chain,
161        fail_closed: false,
162    };
163    write_pin(mur_home, agent, &pin)?;
164    Ok(pin)
165}
166
167/// A pin that knows only the new head key, with no trusted history.
168fn pin_head_only(
169    mur_home: &Path,
170    agent: &str,
171    rotation: &RotationAttestation,
172) -> Result<IdentityPin, IdentityPinError> {
173    let pin = IdentityPin {
174        version: PIN_VERSION,
175        pubkey: rotation.new_pubkey.clone(),
176        key_version: rotation.new_key_version,
177        chain: Vec::new(),
178        fail_closed: false,
179    };
180    write_pin(mur_home, agent, &pin)?;
181    Ok(pin)
182}
183
184/// Mark `agent` fail-closed: verifiers trust no key for it, and never fall
185/// back to its own writable files. Used when trust on first use cannot pin a
186/// consistent identity.
187pub fn write_fail_closed(mur_home: &Path, agent: &str) -> Result<(), IdentityPinError> {
188    checked_name(agent)?;
189    let pin = IdentityPin {
190        version: PIN_VERSION,
191        pubkey: String::new(),
192        key_version: 0,
193        chain: Vec::new(),
194        fail_closed: true,
195    };
196    write_pin(mur_home, agent, &pin)
197}
198
199/// Extend the existing pin with one rotation the CLI just generated.
200///
201/// History comes from the pin only — never from the agent's `rotations.jsonl`,
202/// which the agent can rewrite. The rotation must continue the pinned head:
203/// same old key and version, version + 1, and (unless emergency) signed by the
204/// pinned key. A fail-closed pin accepts only an emergency rotation, which
205/// starts a fresh head with no trusted history.
206pub fn extend_pin(
207    mur_home: &Path,
208    agent: &str,
209    rotation: &RotationAttestation,
210) -> Result<IdentityPin, IdentityPinError> {
211    let Some(mut pin) = load_pin(mur_home, agent)? else {
212        // Never pinned (rekeyed before its first start since #2318): pin only
213        // the new head. The on-disk history is agent-writable, so none of it
214        // is imported.
215        return pin_head_only(mur_home, agent, rotation);
216    };
217    let refuse = |msg: String| IdentityPinError::NotAnExtension {
218        agent: agent.to_string(),
219        msg,
220    };
221    let emergency = rotation.reason == crate::identity::RotationReason::Emergency;
222    if pin.fail_closed {
223        if !emergency {
224            return Err(refuse(
225                "the pin is fail-closed; only an emergency rekey resets it".into(),
226            ));
227        }
228        return pin_head_only(mur_home, agent, rotation);
229    }
230    if rotation.bootstrap {
231        return Err(refuse("a bootstrap cannot extend a pin".into()));
232    }
233    if rotation.old_pubkey != pin.pubkey {
234        return Err(refuse("old key is not the pinned key".into()));
235    }
236    if rotation.old_key_version != pin.key_version
237        || Some(rotation.new_key_version) != pin.key_version.checked_add(1)
238    {
239        return Err(refuse(format!(
240            "version {} -> {} does not follow pinned version {}",
241            rotation.old_key_version, rotation.new_key_version, pin.key_version
242        )));
243    }
244    rotation
245        .verify_or_emergency(&pin.pubkey)
246        .map_err(|e| refuse(format!("not signed by the pinned key: {e}")))?;
247    pin.pubkey = rotation.new_pubkey.clone();
248    pin.key_version = rotation.new_key_version;
249    pin.chain.push(rotation.clone());
250    write_pin(mur_home, agent, &pin)?;
251    Ok(pin)
252}
253
254/// Temp file + rename, so a crash never leaves a torn pin.
255fn write_pin(mur_home: &Path, agent: &str, pin: &IdentityPin) -> Result<(), IdentityPinError> {
256    let dir = mur_home.join(IDENTITY_PINS_DIR);
257    let path = pin_path(mur_home, agent);
258    let io_err = |source| IdentityPinError::Io {
259        path: path.clone(),
260        source,
261    };
262    std::fs::create_dir_all(&dir).map_err(io_err)?;
263    let bytes = crate::jcs::to_jcs_for(pin);
264    let mut tmp = tempfile::NamedTempFile::new_in(&dir).map_err(io_err)?;
265    io::Write::write_all(&mut tmp, &bytes).map_err(io_err)?;
266    tmp.persist(&path).map_err(|e| io_err(e.error))?;
267    Ok(())
268}
269
270/// The pin for `agent`, or `None` when there is none yet.
271pub fn load_pin(mur_home: &Path, agent: &str) -> Result<Option<IdentityPin>, IdentityPinError> {
272    checked_name(agent)?;
273    let path = pin_path(mur_home, agent);
274    let raw = match std::fs::read(&path) {
275        Ok(b) => b,
276        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
277        Err(source) => return Err(IdentityPinError::Io { path, source }),
278    };
279    let invalid = |msg: String| IdentityPinError::Invalid {
280        path: path.clone(),
281        msg,
282    };
283    let pin: IdentityPin = serde_json::from_slice(&raw).map_err(|e| invalid(e.to_string()))?;
284    if pin.version != PIN_VERSION {
285        return Err(invalid(format!("unsupported version {}", pin.version)));
286    }
287    Ok(Some(pin))
288}
289
290/// Drop `agent`'s pin (purge, re-seed). Missing is not an error.
291pub fn remove_pin(mur_home: &Path, agent: &str) -> Result<(), IdentityPinError> {
292    checked_name(agent)?;
293    let path = pin_path(mur_home, agent);
294    match std::fs::remove_file(&path) {
295        Ok(()) => Ok(()),
296        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
297        Err(source) => Err(IdentityPinError::Io { path, source }),
298    }
299}
300
301/// Carry the pin across `mur agent rename`. No pin to move is not an error.
302pub fn rename_pin(mur_home: &Path, old: &str, new: &str) -> Result<(), IdentityPinError> {
303    checked_name(old)?;
304    checked_name(new)?;
305    let (from, to) = (pin_path(mur_home, old), pin_path(mur_home, new));
306    match std::fs::rename(&from, &to) {
307        Ok(()) => Ok(()),
308        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
309        Err(source) => Err(IdentityPinError::Io { path: from, source }),
310    }
311}
312
313fn strict() -> ChainOptions {
314    ChainOptions {
315        allow_emergency: false,
316    }
317}
318
319/// What to trust for the agent at `agent_home`, or `None` when it has no pin
320/// (not an installed agent, or not pinned yet): the caller then falls back to
321/// the legacy read of the agent's own files.
322///
323/// With a pin, the agent's own `identity.pub` / `rotations.jsonl` are not read
324/// at all. Every legitimate change to them (create, rekey, import, clone)
325/// re-pins in the same command, so a disk copy that differs from the pin was
326/// written by something else.
327///
328/// An unreadable or invalid pin is present-but-unusable: resolving nothing
329/// fails closed, where falling back to disk would hand the decision back to
330/// the agent.
331pub fn resolve(agent_home: &Path) -> Option<Option<TrustedIdentity>> {
332    let (mur_home, name) = split_agent_home(agent_home)?;
333    let pin = match load_pin(mur_home, name) {
334        Ok(Some(pin)) => pin,
335        Ok(None) => return None,
336        Err(e) => {
337            tracing::warn!(agent = name, error = %e, "identity pin unusable; trusting no key");
338            return Some(None);
339        }
340    };
341    if pin.fail_closed {
342        return Some(None);
343    }
344    let chain = (!pin.chain.is_empty() && verify_chain(&pin.chain, strict()).is_ok())
345        .then(|| pin.chain.clone());
346    Some(Some(TrustedIdentity {
347        head_pubkey: pin.pubkey,
348        head_key_version: pin.key_version,
349        chain,
350    }))
351}
352
353#[cfg(test)]
354mod tests;