1use serde::{Deserialize, Serialize};
2
3pub const KEY_RECORD_VERSION: u32 = 1;
4pub const KEY_ID_BYTES: usize = 8;
5pub const VERIFYING_KEY_BYTES: usize = 32;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
8#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
9#[serde(rename_all = "snake_case")]
10pub enum KeyKind {
11 Agent,
12 Operator,
13}
14
15#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
17pub struct KeyRecord {
18 pub v: u32,
19 pub principal: String,
20 #[cfg_attr(
21 feature = "schemars",
22 schemars(schema_with = "crate::encoding::bytes_schema")
23 )]
24 #[serde(with = "crate::encoding::bin_bytes")]
25 pub key_id: Vec<u8>,
26 #[cfg_attr(
27 feature = "schemars",
28 schemars(schema_with = "crate::encoding::bytes_schema")
29 )]
30 #[serde(with = "crate::encoding::bin_bytes")]
31 pub verifying_key: Vec<u8>,
32 pub kind: KeyKind,
33 pub valid_from_micros: u64,
34 pub valid_to_micros: Option<u64>,
35 pub revoked: bool,
36}
37
38impl KeyRecord {
39 #[must_use]
40 pub fn new(
41 principal: impl Into<String>,
42 key_id: Vec<u8>,
43 verifying_key: Vec<u8>,
44 kind: KeyKind,
45 ) -> Self {
46 Self {
47 v: KEY_RECORD_VERSION,
48 principal: principal.into(),
49 key_id,
50 verifying_key,
51 kind,
52 valid_from_micros: 0,
53 valid_to_micros: None,
54 revoked: false,
55 }
56 }
57
58 pub fn validate(&self) -> Result<(), &'static str> {
59 if self.v != KEY_RECORD_VERSION {
60 return Err("unsupported key record version");
61 }
62 if self.principal.is_empty() {
63 return Err("key principal must not be empty");
64 }
65 if self.key_id.len() != KEY_ID_BYTES {
66 return Err("Ed25519 key id must be 8 bytes");
67 }
68 if self.verifying_key.len() != VERIFYING_KEY_BYTES {
69 return Err("Ed25519 public key must be 32 bytes");
70 }
71 if self
72 .valid_to_micros
73 .is_some_and(|end| end <= self.valid_from_micros)
74 {
75 return Err("key validity end must be after its start");
76 }
77 Ok(())
78 }
79}
80
81#[cfg(all(test, feature = "cbor"))]
82mod tests {
83 use super::*;
84 use crate::framing::{decode_named, encode_named};
85
86 #[test]
87 fn given_a_key_record_when_round_tripped_then_should_preserve_its_lifecycle() {
88 let record = KeyRecord {
89 v: KEY_RECORD_VERSION,
90 principal: "operator-1".to_owned(),
91 key_id: vec![3; KEY_ID_BYTES],
92 verifying_key: vec![7; VERIFYING_KEY_BYTES],
93 kind: KeyKind::Operator,
94 valid_from_micros: 100,
95 valid_to_micros: Some(200),
96 revoked: true,
97 };
98
99 let encoded = encode_named(&record).expect("key record encodes");
100 let decoded: KeyRecord = decode_named(&encoded).expect("key record decodes");
101
102 assert_eq!(decoded, record);
103 assert!(decoded.validate().is_ok());
104 }
105}