Skip to main content

mur_common/identity/
rotation.rs

1//! Key rotation attestations and chain verification.
2
3use super::*;
4
5// ---------------------------------------------------------------------------
6// RotationAttestation — proof that a key rotation was authorized by the
7// holder of the prior identity key.
8// ---------------------------------------------------------------------------
9
10use serde::{Deserialize, Serialize};
11
12/// Why a rotation happened. Free-form audit hint; does not affect verification
13/// rules other than `Emergency`, which permits an empty signature.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum RotationReason {
17    Scheduled,
18    SuspectCompromise,
19    OwnerChange,
20    Emergency,
21}
22
23/// Cryptographic proof of an identity-key rotation.
24///
25/// `signature` is multibase base58btc Ed25519 over `canonical_bytes()`
26/// (which serializes every field except `signature` itself).
27///
28/// For `reason = Emergency`, signature MAY be empty — those rotations
29/// require out-of-band admin approval to take effect.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct RotationAttestation {
32    /// Schema version. Always 1 for now.
33    pub schema: u32,
34    /// Agent UUIDv7 — stable across rotations.
35    pub uuid: String,
36    /// Signing algorithm. "ed25519" for now.
37    pub algorithm: String,
38    /// Outgoing pubkey (multibase). Empty string for the bootstrap entry only.
39    pub old_pubkey: String,
40    /// Incoming pubkey (multibase). Always present.
41    pub new_pubkey: String,
42    pub old_key_version: u32,
43    /// = old_key_version + 1 for non-emergency rotations.
44    pub new_key_version: u32,
45    /// RFC3339 timestamp.
46    pub rotated_at: String,
47    pub reason: RotationReason,
48    /// Multibase Ed25519 signature over canonical_bytes(). Empty for
49    /// Emergency reason or for the bootstrap entry.
50    #[serde(default, skip_serializing_if = "String::is_empty")]
51    pub signature: String,
52    /// True only for the create-time entry (no prior key existed).
53    #[serde(default, skip_serializing_if = "is_false")]
54    pub bootstrap: bool,
55}
56
57fn is_false(b: &bool) -> bool {
58    !*b
59}
60
61impl RotationAttestation {
62    /// Build a new (unsigned) attestation.
63    pub fn new(
64        uuid: impl Into<String>,
65        old_pubkey: impl Into<String>,
66        new_pubkey: impl Into<String>,
67        old_key_version: u32,
68        new_key_version: u32,
69        rotated_at: impl Into<String>,
70        reason: RotationReason,
71    ) -> Self {
72        Self {
73            schema: 1,
74            uuid: uuid.into(),
75            algorithm: "ed25519".into(),
76            old_pubkey: old_pubkey.into(),
77            new_pubkey: new_pubkey.into(),
78            old_key_version,
79            new_key_version,
80            rotated_at: rotated_at.into(),
81            reason,
82            signature: String::new(),
83            bootstrap: false,
84        }
85    }
86
87    /// Mark this attestation as the bootstrap entry written at agent
88    /// create time. Bootstrap entries have empty `old_pubkey` and empty
89    /// `signature`; they exist only to anchor the rotation chain.
90    pub fn into_bootstrap(mut self) -> Self {
91        self.bootstrap = true;
92        self.old_pubkey = String::new();
93        self.signature = String::new();
94        self
95    }
96
97    /// Canonical bytes used for signing. Serializes every field of `self`
98    /// EXCEPT `signature` (which is being computed) using JSON with sorted
99    /// keys and no whitespace.
100    pub fn canonical_bytes(&self) -> Vec<u8> {
101        let mut clone = self.clone();
102        clone.signature = String::new();
103        canonical_json(&clone)
104    }
105
106    /// Compute the Ed25519 signature using the given signing key and store
107    /// it in `self.signature`. Idempotent.
108    pub fn sign(&mut self, signing: &ed25519_dalek::SigningKey) {
109        use ed25519_dalek::Signer;
110        let sig = signing.sign(&self.canonical_bytes());
111        self.signature = multibase::encode(multibase::Base::Base58Btc, sig.to_bytes());
112    }
113
114    /// Verify `self.signature` against the supplied multibase-encoded
115    /// `old_pubkey`. Returns `Ok(())` on a valid signature.
116    ///
117    /// Bootstrap entries (`bootstrap = true`) are accepted unconditionally —
118    /// they have nothing to verify against.
119    /// Emergency entries (`reason = Emergency`) with empty signature are
120    /// REJECTED here; callers must use `verify_or_emergency` if they want
121    /// the emergency-allowed semantics.
122    pub fn verify(&self, old_pubkey: &str) -> Result<(), IdentityError> {
123        if self.bootstrap {
124            return Ok(());
125        }
126        if self.signature.is_empty() {
127            return Err(IdentityError::InvalidKey(
128                "attestation signature is empty".into(),
129            ));
130        }
131        let pub_bytes = decode_pubkey(old_pubkey)?;
132        let verifying = ed25519_dalek::VerifyingKey::from_bytes(&pub_bytes)
133            .map_err(|e| IdentityError::InvalidKey(format!("verifying key: {e}")))?;
134        let (_base, sig_bytes) = multibase::decode(&self.signature)?;
135        let sig_arr: [u8; 64] = sig_bytes
136            .as_slice()
137            .try_into()
138            .map_err(|_| IdentityError::InvalidKey("signature length != 64".into()))?;
139        let sig = ed25519_dalek::Signature::from_bytes(&sig_arr);
140        verifying
141            .verify_strict(&self.canonical_bytes(), &sig)
142            .map_err(|e| IdentityError::InvalidKey(format!("signature: {e}")))?;
143        Ok(())
144    }
145
146    /// Like `verify`, but accepts emergency rotations with empty signature.
147    /// Caller is responsible for the out-of-band approval check.
148    pub fn verify_or_emergency(&self, old_pubkey: &str) -> Result<(), IdentityError> {
149        if self.reason == RotationReason::Emergency && self.signature.is_empty() {
150            return Ok(());
151        }
152        self.verify(old_pubkey)
153    }
154}
155
156// ---------------------------------------------------------------------------
157// Chain verification — M5.1
158// ---------------------------------------------------------------------------
159
160/// Per-call options for `verify_chain`.
161#[derive(Debug, Clone, Copy, Default)]
162pub struct ChainOptions {
163    /// If true, accept emergency entries with empty signature (i.e. use
164    /// `verify_or_emergency` instead of strict `verify`). Commander code
165    /// that has out-of-band approval already should set this true; peer
166    /// code that is mirroring without approval should leave it false.
167    pub allow_emergency: bool,
168}
169
170/// Outcome of a successful chain verification.
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct ChainOutcome {
173    /// Highest key_version observed.
174    pub head_key_version: u32,
175    /// Pubkey at head_key_version.
176    pub head_pubkey: String,
177    /// Total entries (including bootstrap).
178    pub length: usize,
179}
180
181/// Errors from `verify_chain`.
182#[derive(Debug)]
183pub enum ChainError {
184    /// Chain is empty or first entry is not a bootstrap.
185    MissingBootstrap,
186    /// Chain skipped a key_version (e.g. went 1 -> 3).
187    VersionSkip { expected: u32, got: u32 },
188    /// `a[i].old_pubkey` does not match `a[i-1].new_pubkey`.
189    PubkeyDiscontinuity { at_version: u32 },
190    /// Same `new_key_version` appears twice in the chain.
191    DuplicateVersion(u32),
192    /// Bad Ed25519 signature on a non-bootstrap, non-emergency entry.
193    BadSignature { at_version: u32, detail: String },
194    /// Emergency entry encountered with `allow_emergency = false`.
195    EmergencyDisallowed { at_version: u32 },
196}
197
198impl std::fmt::Display for ChainError {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        match self {
201            Self::MissingBootstrap => {
202                write!(
203                    f,
204                    "chain must start with a bootstrap entry (bootstrap=true, key_version=0)"
205                )
206            }
207            Self::VersionSkip { expected, got } => {
208                write!(f, "version skip: expected {expected}, got {got}")
209            }
210            Self::PubkeyDiscontinuity { at_version } => {
211                write!(
212                    f,
213                    "pubkey discontinuity at key_version {at_version}: old_pubkey does not match prior new_pubkey"
214                )
215            }
216            Self::DuplicateVersion(v) => write!(f, "duplicate key_version {v}"),
217            Self::BadSignature { at_version, detail } => {
218                write!(f, "bad signature at key_version {at_version}: {detail}")
219            }
220            Self::EmergencyDisallowed { at_version } => {
221                write!(
222                    f,
223                    "emergency attestation at key_version {at_version} requires allow_emergency=true"
224                )
225            }
226        }
227    }
228}
229
230impl std::error::Error for ChainError {}
231
232/// Walk the chain top-to-bottom and verify it forms a valid history.
233/// Returns the head pubkey + version on success.
234pub fn verify_chain(
235    chain: &[RotationAttestation],
236    opts: ChainOptions,
237) -> std::result::Result<ChainOutcome, ChainError> {
238    if chain.is_empty() {
239        return Err(ChainError::MissingBootstrap);
240    }
241    let first = &chain[0];
242    if !first.bootstrap || first.new_key_version != 0 {
243        return Err(ChainError::MissingBootstrap);
244    }
245
246    let mut prev_pubkey = first.new_pubkey.clone();
247    let mut prev_version = 0u32;
248    let mut seen_versions = std::collections::HashSet::new();
249    seen_versions.insert(0u32);
250
251    for (i, a) in chain.iter().enumerate().skip(1) {
252        // No duplicate versions
253        if !seen_versions.insert(a.new_key_version) {
254            return Err(ChainError::DuplicateVersion(a.new_key_version));
255        }
256        // Strict +1 succession
257        let expected = prev_version + 1;
258        if a.old_key_version != prev_version || a.new_key_version != expected {
259            return Err(ChainError::VersionSkip {
260                expected,
261                got: a.new_key_version,
262            });
263        }
264        // Pubkey continuity
265        if a.old_pubkey != prev_pubkey {
266            return Err(ChainError::PubkeyDiscontinuity {
267                at_version: a.new_key_version,
268            });
269        }
270        // Signature (or emergency allowance)
271        if a.reason == RotationReason::Emergency {
272            if !opts.allow_emergency {
273                return Err(ChainError::EmergencyDisallowed {
274                    at_version: a.new_key_version,
275                });
276            }
277            // Lenient verify: empty signature is fine for emergency
278            if let Err(e) = a.verify_or_emergency(&a.old_pubkey) {
279                return Err(ChainError::BadSignature {
280                    at_version: a.new_key_version,
281                    detail: e.to_string(),
282                });
283            }
284        } else if let Err(e) = a.verify(&a.old_pubkey) {
285            return Err(ChainError::BadSignature {
286                at_version: a.new_key_version,
287                detail: e.to_string(),
288            });
289        }
290
291        prev_pubkey = a.new_pubkey.clone();
292        prev_version = a.new_key_version;
293        let _ = i; // silence unused
294    }
295
296    Ok(ChainOutcome {
297        head_key_version: prev_version,
298        head_pubkey: prev_pubkey,
299        length: chain.len(),
300    })
301}
302
303/// Canonical JSON: sorted keys, no whitespace. Used so that signers and
304/// verifiers compute identical byte sequences regardless of language /
305/// serializer choices.
306fn canonical_json<T: serde::Serialize>(value: &T) -> Vec<u8> {
307    // serde_json with a BTreeMap-like ordering. The simplest approach: round-trip
308    // through a `serde_json::Value`, then walk it depth-first emitting bytes.
309    let v: serde_json::Value =
310        serde_json::to_value(value).expect("serialize should not fail for our types");
311    let mut out = Vec::new();
312    write_canonical(&mut out, &v);
313    out
314}
315
316fn write_canonical(out: &mut Vec<u8>, v: &serde_json::Value) {
317    use serde_json::Value;
318    match v {
319        Value::Null => out.extend_from_slice(b"null"),
320        Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
321        Value::Number(n) => out.extend_from_slice(n.to_string().as_bytes()),
322        Value::String(s) => {
323            // serde_json::to_string handles escaping for us
324            let escaped = serde_json::to_string(s).unwrap();
325            out.extend_from_slice(escaped.as_bytes());
326        }
327        Value::Array(arr) => {
328            out.push(b'[');
329            for (i, item) in arr.iter().enumerate() {
330                if i > 0 {
331                    out.push(b',');
332                }
333                write_canonical(out, item);
334            }
335            out.push(b']');
336        }
337        Value::Object(map) => {
338            // Sort keys for deterministic output
339            let mut keys: Vec<&String> = map.keys().collect();
340            keys.sort();
341            out.push(b'{');
342            for (i, k) in keys.iter().enumerate() {
343                if i > 0 {
344                    out.push(b',');
345                }
346                let kesc = serde_json::to_string(k).unwrap();
347                out.extend_from_slice(kesc.as_bytes());
348                out.push(b':');
349                write_canonical(out, &map[*k]);
350            }
351            out.push(b'}');
352        }
353    }
354}