Skip to main content

mur_common/
identity.rs

1//! Per-agent Ed25519 identity keypair.
2//!
3//! Loaded from `<agent_home>/identity.key` (private, 0600) and
4//! `<agent_home>/identity.pub` (public, multibase-encoded text).
5
6use ed25519_dalek::{SECRET_KEY_LENGTH, SigningKey, VerifyingKey};
7use rand_core::OsRng;
8use std::fs;
9use std::io;
10use std::path::{Path, PathBuf};
11
12#[cfg(unix)]
13use std::os::unix::fs::PermissionsExt;
14
15#[derive(Debug, thiserror::Error)]
16pub enum IdentityError {
17    #[error("identity files not found")]
18    NotFound,
19    /// Refused to overwrite a key that is already there. `save` is
20    /// write-if-absent by contract: a private key has no `.prev` and no
21    /// rotation attestation behind it, so clobbering one is unrecoverable.
22    /// Callers that legitimately replace a key (`mur agent rekey`) write to a
23    /// scratch directory and rename.
24    #[error("refusing to overwrite an existing identity key at {0}")]
25    Exists(String),
26    /// The key is there but this process may not read it — a sandbox deny, or
27    /// wrong ownership. Distinct from `NotFound` on purpose: callers that treat
28    /// an absent key as "not signed yet" must NOT treat an unreadable one the
29    /// same way, or a deny silently downgrades signing to unsigned.
30    #[error("identity key exists but is not readable: {0}")]
31    Denied(String),
32    #[error("io error: {0}")]
33    Io(#[from] io::Error),
34    #[error("invalid key material: {0}")]
35    InvalidKey(String),
36    #[error("multibase decode error: {0}")]
37    Multibase(#[from] multibase::Error),
38}
39
40#[derive(Clone)]
41pub struct AgentIdentity {
42    signing: SigningKey,
43}
44
45impl std::fmt::Debug for AgentIdentity {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("AgentIdentity")
48            .field("verifying_key", &self.signing.verifying_key())
49            .finish()
50    }
51}
52
53/// Where an agent's PRIVATE key lives: `<mur_home>/keys/<name>/identity.key`
54/// for a directory of the form `<mur_home>/agents/<name>`, and `dir` itself for
55/// anything else.
56///
57/// #850 option (c). Both sandbox rules that protect or expose key material work
58/// by ENUMERATING `agents/*` — the sibling-key deny (#975) and the peer-public
59/// grant (#1006) — so both miss an agent created after the policy sealed.
60/// Neither backend can express "a file with this name under any agent home", so
61/// the rule has to become a subtree, and that means the private half cannot
62/// share a directory with the public half.
63///
64/// The narrow mapping is deliberate. Three callers pass a directory that is NOT
65/// under `agents/` and must be left alone. Each one's `identity.key` is covered
66/// as a fixed path by the sandbox's `credential_paths()` and
67/// `write_protected_paths()` (the directory itself is not):
68///
69/// - `<mur_home>/commander` (commander signing identity)
70/// - `<mur_home>/publisher` (skill publisher identity, #1013)
71/// - `<mur_home>` itself (the host key)
72///
73/// Keying off "parent is literally `agents`" is what keeps those out.
74///
75/// One more exact-match arm (at-mention phase 2, D-8): `<mur_home>/identity`,
76/// the human owner's PUBLIC directory, maps to `<mur_home>/keys/.human`.
77/// Without it `save(<mur_home>/identity)` would write the human's private key
78/// into a directory every agent may read.
79pub fn private_key_dir(dir: &Path) -> PathBuf {
80    if dir
81        .file_name()
82        .is_some_and(|n| n == human::HUMAN_IDENTITY_DIR)
83        && let Some(mur_home) = dir.parent()
84        && mur_home.file_name().is_none_or(|n| n != "agents")
85    {
86        return human::human_key_dir(mur_home);
87    }
88    let is_agent_home = dir
89        .parent()
90        .and_then(|p| p.file_name())
91        .is_some_and(|n| n == "agents");
92    if !is_agent_home {
93        return dir.to_path_buf();
94    }
95    let (Some(name), Some(mur_home)) = (dir.file_name(), dir.parent().and_then(|p| p.parent()))
96    else {
97        return dir.to_path_buf();
98    };
99    mur_home.join("keys").join(name)
100}
101
102/// Move one agent's private key out of the agents tree (#850 option (c), step 2).
103///
104/// Scoped to a SINGLE agent on purpose. Every agent runs this for its own key at
105/// startup, so 27 agents starting together never contend — no two of them touch
106/// the same file. A sweep that migrated everyone from whichever process got
107/// there first would have that race for no gain.
108///
109/// Runs at startup rather than from `mur update` because `mur update` is not the
110/// only upgrade path: `build.sh --install` + `mur agent restart --stale` never
111/// invokes it, and neither does `brew upgrade`. A migration hooked there simply
112/// would not run on those machines.
113///
114/// Refuses rather than overwrites when the destination already holds a
115/// DIFFERENT key. Silently picking one would change the agent's identity, which
116/// forges attribution on every channel it has ever written to, and there is no
117/// `.prev` and no rotation attestation to undo it with.
118///
119/// Returns `Ok(true)` when a key was moved. Idempotent: a second call finds
120/// nothing. Never an error for "nothing to migrate".
121pub fn migrate_private_key(agent_dir: &Path) -> Result<bool, IdentityError> {
122    let key_dir = private_key_dir(agent_dir);
123    if key_dir == agent_dir {
124        return Ok(false); // not an agent home — commander, publisher, host key
125    }
126    let legacy = agent_dir.join("identity.key");
127    let target = key_dir.join("identity.key");
128
129    let legacy_bytes = match fs::read(&legacy) {
130        Ok(b) => b,
131        // Nothing to move. Note this deliberately does NOT distinguish denied
132        // from absent: a migration that cannot read the source has nothing to
133        // do either way, and the load path (which does distinguish) is what
134        // reports the problem.
135        Err(_) => return Ok(false),
136    };
137
138    if let Ok(existing) = fs::read(&target) {
139        if existing == legacy_bytes {
140            // Already migrated, with a leftover copy behind. Remove the copy —
141            // leaving a private key in the agents tree is the exposure this
142            // whole change exists to remove.
143            let _ = fs::remove_file(&legacy);
144            return Ok(false);
145        }
146        return Err(IdentityError::Exists(format!(
147            "{} already holds a DIFFERENT key than {}; refusing to migrate —              resolve by hand, because picking one silently changes this agent's              identity",
148            target.display(),
149            legacy.display()
150        )));
151    }
152
153    fs::create_dir_all(&key_dir)?;
154    // Copy-then-remove rather than rename: `keys/` and `agents/` are both under
155    // mur_home so a rename would normally work, but a bind-mounted or symlinked
156    // agents dir would make it cross-device, and a failed rename there would
157    // leave the key nowhere.
158    fs::write(&target, &legacy_bytes)?;
159    #[cfg(unix)]
160    {
161        use std::os::unix::fs::PermissionsExt;
162        fs::set_permissions(&target, fs::Permissions::from_mode(0o600))?;
163    }
164    // Only now is it safe to drop the original.
165    fs::remove_file(&legacy)?;
166
167    // `.prev` follows its key if present; rekey writes it beside the private
168    // half, so leaving it behind would strand a usable old key in the tree.
169    let legacy_prev = agent_dir.join("identity.key.prev");
170    if let Ok(prev) = fs::read(&legacy_prev) {
171        let target_prev = key_dir.join("identity.key.prev");
172        if fs::metadata(&target_prev).is_err() {
173            fs::write(&target_prev, &prev)?;
174            #[cfg(unix)]
175            {
176                use std::os::unix::fs::PermissionsExt;
177                fs::set_permissions(&target_prev, fs::Permissions::from_mode(0o600))?;
178            }
179        }
180        let _ = fs::remove_file(&legacy_prev);
181    }
182    Ok(true)
183}
184
185/// Environment flag telling a spawned `mur` that its parent handed it a
186/// signing capability on stdin. Set only by `fleet_run`, only alongside the
187/// pipe that carries it.
188pub const SIGNING_HANDOFF_ENV: &str = "MUR_CHANNEL_SIGNING_STDIN";
189
190/// The signing capability a runtime hands to a child it sealed inside its own
191/// sandbox.
192///
193/// `<mur_home>/keys` is kernel-denied to every sandboxed process on purpose —
194/// a prompt-injected agent must not be able to exfiltrate its own signing key.
195/// The runtime escapes that only because it loads the key BEFORE the sandbox
196/// seals; a child spawned afterwards cannot, so every channel event such a
197/// child wrote was unsigned.
198///
199/// This travels on the child's **stdin pipe** — never argv, never the
200/// environment. `ps eww` shows another same-uid process's environment, so an
201/// env var here would hand the key straight back to the bash tool the sandbox
202/// exists to keep it away from. A pipe is readable only by the process holding
203/// the descriptor.
204///
205/// Design: `docs/superpowers/specs/2026-09-09-in-sandbox-channel-signing-design.md`.
206#[derive(serde::Serialize, serde::Deserialize)]
207pub struct SigningHandoff {
208    /// The agent this key signs as. The receiver uses it only when the event
209    /// it is writing names this same writer.
210    pub agent: String,
211    pub key_version: u32,
212    /// Raw Ed25519 secret, as a JSON array of bytes — no encoding dependency
213    /// stands between the two ends of the pipe.
214    pub secret: [u8; SECRET_KEY_LENGTH],
215}
216
217impl AgentIdentity {
218    /// Rebuild an identity from raw secret bytes.
219    ///
220    /// The only legitimate caller is the receiving end of a `SigningHandoff`.
221    /// Anything that can reach the key file uses `load`.
222    pub fn from_secret_bytes(secret: &[u8; SECRET_KEY_LENGTH]) -> Self {
223        Self {
224            signing: SigningKey::from_bytes(secret),
225        }
226    }
227
228    /// The raw secret, for building a `SigningHandoff` and nothing else.
229    ///
230    /// Named for its one use so a second one has to argue for itself: putting
231    /// these bytes anywhere they can be read back — a file, argv, an
232    /// environment variable — undoes the reason `keys/` is denied at all.
233    pub fn secret_bytes_for_handoff(&self) -> [u8; SECRET_KEY_LENGTH] {
234        self.signing.to_bytes()
235    }
236
237    /// Generate a fresh Ed25519 keypair using OS CSPRNG.
238    pub fn generate() -> Self {
239        Self {
240            signing: SigningKey::generate(&mut OsRng),
241        }
242    }
243
244    /// Write both halves of the keypair to the given directory.
245    /// Private key is mode 0600 on Unix.
246    ///
247    /// **Write-if-absent.** Refuses when `identity.key` already exists, because
248    /// `fs::write` truncates and a private key has nothing behind it to restore
249    /// from — no `.prev`, and no rotation attestation to bridge the swap, so
250    /// every event the old key signed silently stops attributing. A caller that
251    /// means to replace a key writes to a scratch directory and renames, which
252    /// is what `mur agent rekey` does.
253    ///
254    /// This is not hypothetical caution: `mur skill publish` guarded on
255    /// `publisher-identity.key` and wrote `identity.key`, so it overwrote the
256    /// host key on every machine that had one (#1011).
257    pub fn save(&self, dir: &Path) -> Result<(), IdentityError> {
258        // Private half goes to `keys/<name>/` for an agent home, `dir` itself
259        // otherwise (#850 option (c), step 1). Public half never moves — it is
260        // what peers read to verify, and `agents/` staying public-only is the
261        // whole point.
262        self.save_split(dir, &private_key_dir(dir))
263    }
264
265    /// `save` with the two halves' directories named explicitly: the public
266    /// key goes to `pub_dir/identity.pub`, the private key to
267    /// `key_dir/identity.key` (0600). Same write-if-absent contract as `save`.
268    ///
269    /// Exists for the human owner (D-8), whose halves live in two unrelated
270    /// trees (`identity/` and `keys/.human/`). Callers that can say where
271    /// each half goes should, rather than rely on `private_key_dir`'s mapping.
272    pub fn save_split(&self, pub_dir: &Path, key_dir: &Path) -> Result<(), IdentityError> {
273        fs::create_dir_all(pub_dir)?;
274        fs::create_dir_all(key_dir)?;
275        let priv_path = key_dir.join("identity.key");
276        let pub_path = pub_dir.join("identity.pub");
277
278        // `exists()` is the right call here despite #1010: a false from a
279        // denied stat means we are about to fail the write anyway, and the
280        // conservative reading (treat unknown as "might exist") would block
281        // legitimate first-time saves under a sandbox.
282        if priv_path.exists() {
283            return Err(IdentityError::Exists(priv_path.display().to_string()));
284        }
285
286        fs::write(&priv_path, self.signing.to_bytes())?;
287        #[cfg(unix)]
288        {
289            let mut perms = fs::metadata(&priv_path)?.permissions();
290            perms.set_mode(0o600);
291            fs::set_permissions(&priv_path, perms)?;
292        }
293
294        let pub_text = encode_pubkey(&self.signing.verifying_key());
295        fs::write(&pub_path, pub_text)?;
296        Ok(())
297    }
298
299    /// Load both halves from the given directory. Prefers the private key
300    /// (since we can derive pubkey from it); but also validates that a
301    /// present `identity.pub` matches.
302    pub fn load(dir: &Path) -> Result<Self, IdentityError> {
303        // One location only (#850 option (c) step 3). The legacy fallback is
304        // gone because the migration runs at startup, in the same binary,
305        // BEFORE this load — so a key still in `agents/` gets moved and then
306        // found here. A machine upgrading straight past step 2 is covered for
307        // the same reason: the migration is cumulative, not a one-release
308        // window.
309        //
310        // What this does change: if the migration could not move the key, the
311        // load now fails instead of quietly reading the old path. That is the
312        // intent — an unmigrated key is one that is still readable to every
313        // sibling, and it should be loud.
314        let priv_path = private_key_dir(dir).join("identity.key");
315        // `Path::exists()` cannot be used here: it answers false for ANY stat
316        // failure, so a sandbox deny is indistinguishable from a missing file
317        // and the caller's "no key yet" branch runs when the truth is "you may
318        // not read this key". Ask for the metadata and keep the error kind.
319        if let Err(e) = fs::metadata(&priv_path) {
320            return Err(match e.kind() {
321                io::ErrorKind::NotFound => IdentityError::NotFound,
322                _ => IdentityError::Denied(format!("{}: {e}", priv_path.display())),
323            });
324        }
325        let bytes = fs::read(&priv_path).map_err(|e| match e.kind() {
326            io::ErrorKind::NotFound => IdentityError::NotFound,
327            io::ErrorKind::PermissionDenied => {
328                IdentityError::Denied(format!("{}: {e}", priv_path.display()))
329            }
330            _ => IdentityError::Io(e),
331        })?;
332        if bytes.len() != SECRET_KEY_LENGTH {
333            return Err(IdentityError::InvalidKey(format!(
334                "expected {SECRET_KEY_LENGTH} bytes, got {}",
335                bytes.len()
336            )));
337        }
338        let arr: [u8; SECRET_KEY_LENGTH] = bytes.as_slice().try_into().unwrap();
339        let signing = SigningKey::from_bytes(&arr);
340
341        let pub_path = dir.join("identity.pub");
342        if pub_path.exists() {
343            let text = fs::read_to_string(&pub_path)?;
344            let loaded_pub = decode_pubkey(text.trim())?;
345            if loaded_pub != *signing.verifying_key().as_bytes() {
346                return Err(IdentityError::InvalidKey(
347                    "identity.pub does not match identity.key".into(),
348                ));
349            }
350        }
351
352        Ok(Self { signing })
353    }
354
355    /// Load ONLY the public key from `<dir>/identity.pub` — for verifiers
356    /// (inbox ingest, proposal review) that must not require the private key.
357    ///
358    /// An installed agent with an identity pin (#2318) answers with the pinned
359    /// head key, not whatever its (agent-writable) `identity.pub` says.
360    pub fn load_pubkey(dir: &Path) -> Result<[u8; 32], IdentityError> {
361        if let Some(trusted) = crate::identity_pin::resolve(dir) {
362            let t = trusted.ok_or_else(|| {
363                IdentityError::InvalidKey("identity pin is unusable; no key is trusted".into())
364            })?;
365            return decode_pubkey(&t.head_pubkey);
366        }
367        let path = dir.join("identity.pub");
368        if !path.exists() {
369            return Err(IdentityError::NotFound);
370        }
371        decode_pubkey(fs::read_to_string(&path)?.trim())
372    }
373
374    pub fn signing_key(&self) -> &SigningKey {
375        &self.signing
376    }
377
378    /// Sign `msg` with the Ed25519 private key and return the raw 64-byte
379    /// signature. Callers that only have a `&AgentIdentity` (and therefore
380    /// cannot import `ed25519_dalek::Signer` themselves) should use this
381    /// instead of calling `signing_key().sign()` directly.
382    pub fn sign_bytes(&self, msg: &[u8]) -> [u8; 64] {
383        use ed25519_dalek::Signer;
384        self.signing.sign(msg).to_bytes()
385    }
386
387    /// Sign `msg` and encode the signature as multibase Base58Btc — the exact
388    /// encoding `verify_bytes` decodes (mirrors mur-channel/src/sign.rs).
389    pub fn sign_multibase(&self, msg: &[u8]) -> String {
390        multibase::encode(multibase::Base::Base58Btc, self.sign_bytes(msg))
391    }
392
393    pub fn verifying_key(&self) -> VerifyingKey {
394        self.signing.verifying_key()
395    }
396
397    pub fn verifying_key_bytes(&self) -> [u8; 32] {
398        *self.signing.verifying_key().as_bytes()
399    }
400
401    pub fn pubkey_text(&self) -> String {
402        encode_pubkey(&self.signing.verifying_key())
403    }
404
405    /// Alias for `pubkey_text()` — returns the verifying key as multibase
406    /// base58btc (`z`-prefixed string), matching the `bridge_pubkey_multibase`
407    /// field used in signed envelopes.
408    pub fn public_key_multibase(&self) -> String {
409        encode_pubkey(&self.signing.verifying_key())
410    }
411
412    /// Derive the X25519 static secret usable by Noise XK.
413    ///
414    /// Ed25519 and X25519 both use Curve25519 underneath; the Ed25519
415    /// SigningKey scalar maps directly to an X25519 StaticSecret.
416    /// ed25519-dalek 2.x exposes `to_scalar_bytes()` for exactly this.
417    pub fn to_x25519_static_secret(&self) -> x25519_dalek::StaticSecret {
418        let scalar_bytes = self.signing.to_scalar_bytes();
419        x25519_dalek::StaticSecret::from(scalar_bytes)
420    }
421}
422
423/// Verify a multibase-encoded Ed25519 signature over `msg` against `pubkey`.
424/// Fail-closed: any decode/length/verify error returns false.
425pub fn verify_bytes(pubkey: &[u8; 32], msg: &[u8], sig_multibase: &str) -> bool {
426    let Ok((_, sig_bytes)) = multibase::decode(sig_multibase) else {
427        return false;
428    };
429    let Ok(sig_arr): Result<[u8; 64], _> = sig_bytes.try_into() else {
430        return false;
431    };
432    let Ok(vk) = ed25519_dalek::VerifyingKey::from_bytes(pubkey) else {
433        return false;
434    };
435    vk.verify_strict(msg, &ed25519_dalek::Signature::from_bytes(&sig_arr))
436        .is_ok()
437}
438
439/// True iff `bytes` is a valid Ed25519 verifying key (on-curve), not just 32 bytes.
440pub fn valid_ed25519_pubkey(bytes: &[u8; 32]) -> bool {
441    VerifyingKey::from_bytes(bytes).is_ok()
442}
443
444/// Encode an Ed25519 public key to multibase base58btc (`z` prefix).
445pub fn encode_pubkey(key: &VerifyingKey) -> String {
446    multibase::encode(multibase::Base::Base58Btc, key.as_bytes())
447}
448
449/// `encode_pubkey` for raw key bytes.
450pub fn encode_pubkey_bytes(bytes: &[u8; 32]) -> String {
451    multibase::encode(multibase::Base::Base58Btc, bytes)
452}
453
454/// Decode a multibase-encoded pubkey. Accepts any multibase variant.
455pub fn decode_pubkey(text: &str) -> Result<[u8; 32], IdentityError> {
456    let (_base, bytes) = multibase::decode(text)?;
457    if bytes.len() != 32 {
458        return Err(IdentityError::InvalidKey(format!(
459            "pubkey must be 32 bytes, got {}",
460            bytes.len()
461        )));
462    }
463    let mut out = [0u8; 32];
464    out.copy_from_slice(&bytes);
465    Ok(out)
466}
467
468/// Convert an Ed25519 public key to its X25519 (Montgomery `u`) public key.
469///
470/// Ed25519 and X25519 share Curve25519; an Ed25519 verifying key is an Edwards
471/// point whose Montgomery form is the corresponding X25519 public key. This is
472/// the public-key analogue of [`AgentIdentity::to_x25519_static_secret`], and
473/// lets us match a Noise-XK peer's authenticated static key against a peer's
474/// Ed25519 identity. Returns `None` if `ed_pub` is not a valid Edwards point.
475pub fn ed25519_pub_to_x25519(ed_pub: &[u8; 32]) -> Option<[u8; 32]> {
476    let compressed = curve25519_dalek::edwards::CompressedEdwardsY(*ed_pub);
477    let point = compressed.decompress()?;
478    Some(point.to_montgomery().to_bytes())
479}
480
481/// Decode a multibase Ed25519 pubkey and convert it to its X25519 public key.
482pub fn x25519_pub_from_multibase(text: &str) -> Result<[u8; 32], IdentityError> {
483    let ed = decode_pubkey(text)?;
484    ed25519_pub_to_x25519(&ed)
485        .ok_or_else(|| IdentityError::InvalidKey("pubkey is not a valid Edwards point".into()))
486}
487
488/// Default location: `<agent_home>/identity.{key,pub}`.
489pub fn default_dir(agent_home: &Path) -> PathBuf {
490    agent_home.to_path_buf()
491}
492
493pub mod human;
494mod rotation;
495pub use rotation::*;
496
497#[cfg(test)]
498mod identity_readability_tests;
499
500#[cfg(test)]
501mod identity_x25519_tests;