1use super::*;
4
5use serde::{Deserialize, Serialize};
11
12#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct RotationAttestation {
32 pub schema: u32,
34 pub uuid: String,
36 pub algorithm: String,
38 pub old_pubkey: String,
40 pub new_pubkey: String,
42 pub old_key_version: u32,
43 pub new_key_version: u32,
45 pub rotated_at: String,
47 pub reason: RotationReason,
48 #[serde(default, skip_serializing_if = "String::is_empty")]
51 pub signature: String,
52 #[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 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 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 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 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 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 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#[derive(Debug, Clone, Copy, Default)]
162pub struct ChainOptions {
163 pub allow_emergency: bool,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct ChainOutcome {
173 pub head_key_version: u32,
175 pub head_pubkey: String,
177 pub length: usize,
179}
180
181#[derive(Debug)]
183pub enum ChainError {
184 MissingBootstrap,
186 VersionSkip { expected: u32, got: u32 },
188 PubkeyDiscontinuity { at_version: u32 },
190 DuplicateVersion(u32),
192 BadSignature { at_version: u32, detail: String },
194 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
232pub 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 if !seen_versions.insert(a.new_key_version) {
254 return Err(ChainError::DuplicateVersion(a.new_key_version));
255 }
256 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 if a.old_pubkey != prev_pubkey {
266 return Err(ChainError::PubkeyDiscontinuity {
267 at_version: a.new_key_version,
268 });
269 }
270 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 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; }
295
296 Ok(ChainOutcome {
297 head_key_version: prev_version,
298 head_pubkey: prev_pubkey,
299 length: chain.len(),
300 })
301}
302
303fn canonical_json<T: serde::Serialize>(value: &T) -> Vec<u8> {
307 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 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 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}