Skip to main content

cbcl_core/
keyid.rs

1//! Canonical suite-typed key identity (SPEC-015 REQ-708).
2//!
3//! Key material carries a signature-suite identifier as part of its
4//! identity: the surface spelling is `@[suite:]name` (CON-700), an omitted
5//! suite normalises to `ed25519` at parse, and equality is over the
6//! (suite, name) pair — never the surface spelling — so `@alice` and
7//! `@ed25519:alice` are one identity. Spelling aliases can therefore
8//! neither evade the equivocation predicate (REQ-705) nor spuriously fail
9//! cast conformance.
10//!
11//! A suite this implementation does not know is still *representable*
12//! (two keys identical in bytes but differing in suite are distinct
13//! identities), but every sign/verify dispatch on it is a typed rejection
14//! in `attest.rs` — never a skipped check, never a fallback guess
15//! (LangSec discipline: reject, don't repair).
16//!
17//! This module is deliberately independent of the cast machinery in
18//! `role.rs`; [`KeyId::parse`] is the pure canonicalisation function cast
19//! code can adopt when it moves to suite-typed identity.
20
21#![forbid(unsafe_code)]
22
23use alloc::string::String;
24use core::fmt;
25
26/// Name of the v2 default (and unmarked legacy) signature suite (REQ-708).
27pub const DEFAULT_SUITE_NAME: &str = "ed25519";
28
29/// A signature suite named in key identity and attestation preimages.
30///
31/// `Other` keeps unimplemented suites representable so identity comparison
32/// works across them; it is *not* a licence to verify — see
33/// [`crate::attest::AttestError::UnknownSuite`].
34// SIMPLIFY: single implemented suite. Adding one (post-quantum,
35// deployment-specific) is a variant here plus a dispatch arm in
36// `attest.rs` — a registry entry, not a discipline version bump (REQ-708).
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub enum SignatureSuite {
40    /// Ed25519 — the v2 default and the unmarked legacy reading.
41    Ed25519,
42    /// A syntactically well-formed suite name this implementation does not
43    /// implement. Sign/verify dispatch on it yields a typed rejection.
44    Other(String),
45}
46
47impl SignatureSuite {
48    /// Parse a suite name. Anything other than the registered names maps
49    /// to `Other` (distinct identity, unverifiable here).
50    pub fn parse(s: &str) -> Self {
51        if s == DEFAULT_SUITE_NAME {
52            SignatureSuite::Ed25519
53        } else {
54            SignatureSuite::Other(String::from(s))
55        }
56    }
57
58    /// The canonical suite name as it appears in attestation preimages.
59    pub fn as_str(&self) -> &str {
60        match self {
61            SignatureSuite::Ed25519 => DEFAULT_SUITE_NAME,
62            SignatureSuite::Other(s) => s.as_str(),
63        }
64    }
65
66    /// Whether this implementation can sign/verify under the suite.
67    pub fn is_implemented(&self) -> bool {
68        matches!(self, SignatureSuite::Ed25519)
69    }
70}
71
72impl fmt::Display for SignatureSuite {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(self.as_str())
75    }
76}
77
78/// Typed rejection for a malformed key spelling (fail closed — a key that
79/// does not parse is never coerced into one that does).
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum KeyIdError {
82    /// The spelling does not start with the `@` sigil.
83    MissingSigil,
84    /// `@:name` — an explicit-but-empty suite marker.
85    EmptySuite,
86    /// `@` or `@suite:` — no key name.
87    EmptyName,
88}
89
90impl fmt::Display for KeyIdError {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        match self {
93            KeyIdError::MissingSigil => f.write_str("key identifier must start with '@'"),
94            KeyIdError::EmptySuite => f.write_str("key identifier has an empty suite marker"),
95            KeyIdError::EmptyName => f.write_str("key identifier has an empty name"),
96        }
97    }
98}
99
100/// Canonical key identity: the (suite, name) pair (REQ-708).
101///
102/// Constructed via [`KeyId::parse`], which normalises the surface spelling;
103/// derived equality/ordering are therefore over canonical identity, and the
104/// original spelling is never retained.
105#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
107pub struct KeyId {
108    pub suite: SignatureSuite,
109    pub name: String,
110}
111
112impl KeyId {
113    /// Explicit opt-in conversion from public Multikey material to a signing
114    /// identity. Existing parsed principals and attestation preimages are not
115    /// reinterpreted. Recognition does not establish possession or host trust.
116    pub fn from_multikey(
117        key: &crate::multikey::Multikey,
118    ) -> Result<Self, crate::multikey::MultikeyError> {
119        if key.codec() != crate::multikey::PublicKeyCodec::Ed25519 {
120            return Err(crate::multikey::MultikeyError::UnsupportedSigningCodec(
121                key.codec().code(),
122            ));
123        }
124        Ok(Self {
125            suite: SignatureSuite::Ed25519,
126            name: key.to_multibase(),
127        })
128    }
129
130    /// Parse `@[suite:]name` into canonical identity (CON-700).
131    ///
132    /// An omitted suite normalises to `ed25519` here, at parse — no later
133    /// consumer ever sees an "unmarked" key. This is the pure
134    /// canonicalisation function cast code can adopt (SPEC-015 review
135    /// finding 4).
136    pub fn parse(spelling: &str) -> Result<Self, KeyIdError> {
137        let rest = spelling.strip_prefix('@').ok_or(KeyIdError::MissingSigil)?;
138        let (suite, name) = match rest.split_once(':') {
139            Some(("", _)) => return Err(KeyIdError::EmptySuite),
140            Some((s, n)) => (SignatureSuite::parse(s), n),
141            None => (SignatureSuite::Ed25519, rest),
142        };
143        if name.is_empty() {
144            return Err(KeyIdError::EmptyName);
145        }
146        Ok(KeyId {
147            suite,
148            name: String::from(name),
149        })
150    }
151
152    /// The canonical spelling, suite always explicit: `@<suite>:<name>`.
153    ///
154    /// Attestation preimages use this form so both verifier classes
155    /// (envelope holder, full-message holder) reconstruct identical bytes
156    /// regardless of how the sender spelled the key (REQ-701).
157    pub fn canonical_spelling(&self) -> String {
158        use alloc::format;
159        format!("@{}:{}", self.suite.as_str(), self.name)
160    }
161}
162
163impl fmt::Display for KeyId {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        write!(f, "@{}:{}", self.suite.as_str(), self.name)
166    }
167}
168
169// ---------------------------------------------------------------------------
170// Tests (TEST-708 — identity half)
171// ---------------------------------------------------------------------------
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use alloc::collections::BTreeSet;
177    use alloc::string::ToString;
178
179    #[test]
180    fn omitted_suite_normalises_to_ed25519() {
181        let k = KeyId::parse("@alice").unwrap();
182        assert_eq!(k.suite, SignatureSuite::Ed25519);
183        assert_eq!(k.name, "alice");
184    }
185
186    /// TEST-708: `@alice` and `@ed25519:alice` are one identity.
187    #[test]
188    fn alias_spellings_are_one_identity() {
189        let bare = KeyId::parse("@alice").unwrap();
190        let explicit = KeyId::parse("@ed25519:alice").unwrap();
191        assert_eq!(bare, explicit);
192
193        // …and they dedupe in a canonical set (the equivocation predicate
194        // and cast conformance both compare through such sets).
195        let mut set = BTreeSet::new();
196        set.insert(bare);
197        set.insert(explicit);
198        assert_eq!(set.len(), 1);
199    }
200
201    /// TEST-708: same key bytes under two suites are distinct identities.
202    #[test]
203    fn same_name_different_suite_is_distinct() {
204        let ed = KeyId::parse("@ed25519:alice").unwrap();
205        let pq = KeyId::parse("@pq-frodo:alice").unwrap();
206        assert_ne!(ed, pq);
207        assert_eq!(pq.suite, SignatureSuite::Other("pq-frodo".to_string()));
208        assert!(!pq.suite.is_implemented());
209    }
210
211    #[test]
212    fn canonical_spelling_is_suite_explicit() {
213        let k = KeyId::parse("@alice").unwrap();
214        assert_eq!(k.canonical_spelling(), "@ed25519:alice");
215        assert_eq!(alloc::format!("{k}"), "@ed25519:alice");
216    }
217
218    #[test]
219    fn malformed_spellings_are_typed_rejections() {
220        assert_eq!(KeyId::parse("alice"), Err(KeyIdError::MissingSigil));
221        assert_eq!(KeyIdError::MissingSigil, KeyId::parse("").unwrap_err());
222        assert_eq!(KeyId::parse("@:alice"), Err(KeyIdError::EmptySuite));
223        assert_eq!(KeyId::parse("@"), Err(KeyIdError::EmptyName));
224        assert_eq!(KeyId::parse("@ed25519:"), Err(KeyIdError::EmptyName));
225    }
226
227    #[test]
228    fn name_may_contain_further_colons() {
229        // Only the first ':' separates suite from name (did:crdt-style
230        // typed identifiers keep their internal structure).
231        let k = KeyId::parse("@ed25519:did:crdt:xyz").unwrap();
232        assert_eq!(k.name, "did:crdt:xyz");
233    }
234
235    #[test]
236    fn suite_parse_roundtrip() {
237        assert_eq!(SignatureSuite::parse("ed25519"), SignatureSuite::Ed25519);
238        assert_eq!(SignatureSuite::parse("ed25519").as_str(), "ed25519");
239        let other = SignatureSuite::parse("sphincs+");
240        assert_eq!(other.as_str(), "sphincs+");
241        assert!(!other.is_implemented());
242    }
243}