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