Skip to main content

aitp_core/
aid.rs

1//! AITP Agent Identifier (AID).
2//!
3//! v0.2 accepts both the legacy v0.1 grammar
4//! (`aid:pubkey:<43-char-b64url>`, Ed25519 implicit) and the
5//! algorithm-tagged grammar
6//! (`aid:pubkey:<alg>:<identifier>` where `<alg>` is `ed25519` or
7//! `p256`). Per RFC-AITP-0001 §5.3 the legacy and the tagged-ed25519
8//! forms are *trust-equivalent* but not byte-equal in canonical
9//! signing bytes, so each AID lifecycle picks one form and stays
10//! with it.
11
12use crate::AID_PUBKEY_IDENTIFIER_LEN;
13use base64ct::{Base64UrlUnpadded, Encoding};
14use serde::{Deserialize, Serialize};
15use std::fmt;
16
17/// `aid:pubkey:` prefix — common to both legacy and tagged forms.
18const AID_PUBKEY_PREFIX: &str = "aid:pubkey:";
19
20/// Algorithm-tagged AID prefix for Ed25519.
21const AID_PUBKEY_ED25519_PREFIX: &str = "aid:pubkey:ed25519:";
22
23/// Algorithm-tagged AID prefix for ECDSA P-256.
24const AID_PUBKEY_P256_PREFIX: &str = "aid:pubkey:p256:";
25
26/// Identifier length for a SEC1-compressed P-256 public key
27/// (33 raw bytes → 44 unpadded base64url chars).
28const AID_P256_IDENTIFIER_LEN: usize = 44;
29
30/// Algorithm of the public key bound to an AID.
31///
32/// Marked `#[non_exhaustive]` so future suites (e.g. Ed448, post-quantum
33/// candidates) can be added in a minor release without forcing
34/// downstream code to upgrade.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum AidAlgorithm {
38    /// Ed25519 (RFC 8032). Identifier is the 32-byte raw public key.
39    Ed25519,
40    /// ECDSA on P-256 with SHA-256. Identifier is the 33-byte SEC1
41    /// compressed point.
42    P256,
43}
44
45impl AidAlgorithm {
46    /// Wire tag (`ed25519`, `p256`).
47    pub fn as_str(&self) -> &'static str {
48        match self {
49            AidAlgorithm::Ed25519 => "ed25519",
50            AidAlgorithm::P256 => "p256",
51        }
52    }
53}
54
55/// A validated AITP Agent Identifier.
56///
57/// Construct via [`Aid::parse`] or [`Aid::from_ed25519`]. Holding an `Aid` is
58/// proof that the value passed format validation: the string starts with
59/// `aid:pubkey:` and the identifier component is the expected length and
60/// alphabet for its algorithm.
61#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
62#[serde(try_from = "String", into = "String")]
63pub struct Aid(String);
64
65impl Aid {
66    /// Parse and validate an AID string. Accepts:
67    ///
68    /// - **Legacy v0.1 (untagged)**: `aid:pubkey:<43-char-b64url>` —
69    ///   interpreted as Ed25519.
70    /// - **v0.2 tagged Ed25519**: `aid:pubkey:ed25519:<43-char-b64url>`.
71    /// - **v0.2 tagged P-256**: `aid:pubkey:p256:<44-char-b64url>` (SEC1
72    ///   compressed point).
73    pub fn parse(s: &str) -> Result<Self, AidParseError> {
74        if let Some(identifier) = s.strip_prefix(AID_PUBKEY_ED25519_PREFIX) {
75            validate_ed25519_identifier(identifier)?;
76            return Ok(Self(s.to_string()));
77        }
78        if let Some(identifier) = s.strip_prefix(AID_PUBKEY_P256_PREFIX) {
79            validate_p256_identifier(identifier)?;
80            return Ok(Self(s.to_string()));
81        }
82        if let Some(identifier) = s.strip_prefix(AID_PUBKEY_PREFIX) {
83            // Legacy v0.1 form (untagged → Ed25519 implicit).
84            // identifier must NOT contain `:` (which would indicate a
85            // tag we didn't recognize above).
86            if identifier.contains(':') {
87                let (method, _) = identifier.split_once(':').unwrap();
88                return Err(AidParseError::UnsupportedMethod(format!("pubkey:{method}")));
89            }
90            validate_ed25519_identifier(identifier)?;
91            return Ok(Self(s.to_string()));
92        }
93        // Doesn't start with `aid:pubkey:` — surface the right error.
94        if let Some(rest) = s.strip_prefix("aid:") {
95            let method = rest.split(':').next().unwrap_or("");
96            return Err(AidParseError::UnsupportedMethod(method.to_string()));
97        }
98        Err(AidParseError::MissingScheme)
99    }
100
101    /// Construct a legacy (untagged) Ed25519 AID from a raw 32-byte public key.
102    /// Kept for backward-compat; new code should prefer
103    /// [`Aid::from_ed25519_tagged`] which emits the v0.2 algorithm-tagged
104    /// form.
105    pub fn from_ed25519(pubkey: &[u8; 32]) -> Self {
106        let identifier = Base64UrlUnpadded::encode_string(pubkey);
107        debug_assert_eq!(identifier.len(), AID_PUBKEY_IDENTIFIER_LEN);
108        Self(format!("{AID_PUBKEY_PREFIX}{identifier}"))
109    }
110
111    /// Construct an algorithm-tagged Ed25519 AID (v0.2 form).
112    pub fn from_ed25519_tagged(pubkey: &[u8; 32]) -> Self {
113        let identifier = Base64UrlUnpadded::encode_string(pubkey);
114        debug_assert_eq!(identifier.len(), AID_PUBKEY_IDENTIFIER_LEN);
115        Self(format!("{AID_PUBKEY_ED25519_PREFIX}{identifier}"))
116    }
117
118    /// Construct a P-256 AID from a 33-byte SEC1 compressed point.
119    pub fn from_p256(compressed_point: &[u8; 33]) -> Self {
120        let identifier = Base64UrlUnpadded::encode_string(compressed_point);
121        debug_assert_eq!(identifier.len(), AID_P256_IDENTIFIER_LEN);
122        Self(format!("{AID_PUBKEY_P256_PREFIX}{identifier}"))
123    }
124
125    /// Algorithm bound to this AID, derived from the prefix.
126    pub fn algorithm(&self) -> AidAlgorithm {
127        if self.0.starts_with(AID_PUBKEY_P256_PREFIX) {
128            AidAlgorithm::P256
129        } else {
130            AidAlgorithm::Ed25519
131        }
132    }
133
134    /// Return the identifier component (everything after the
135    /// algorithm prefix). For legacy AIDs this is everything after
136    /// `aid:pubkey:` (43 chars); for tagged AIDs it's everything
137    /// after `aid:pubkey:<alg>:`.
138    pub fn identifier(&self) -> &str {
139        if let Some(id) = self.0.strip_prefix(AID_PUBKEY_ED25519_PREFIX) {
140            id
141        } else if let Some(id) = self.0.strip_prefix(AID_PUBKEY_P256_PREFIX) {
142            id
143        } else {
144            &self.0[AID_PUBKEY_PREFIX.len()..]
145        }
146    }
147
148    /// Decode the identifier back to the raw 32-byte Ed25519 public key,
149    /// or `None` if this AID is not an Ed25519 AID. This is the only
150    /// accessor — there is no panicking form; callers on paths that may
151    /// receive an AID of attacker-controlled algorithm (e.g. handshake
152    /// verification) handle the `None` case explicitly.
153    pub fn try_to_ed25519_bytes(&self) -> Option<[u8; 32]> {
154        if !matches!(self.algorithm(), AidAlgorithm::Ed25519) {
155            return None;
156        }
157        let mut out = [0u8; 32];
158        Base64UrlUnpadded::decode(self.identifier(), &mut out)
159            .expect("Aid is validated on construction; identifier MUST decode to 32 bytes");
160        Some(out)
161    }
162
163    /// Decode the identifier back to the 33-byte SEC1 compressed P-256
164    /// public key, or `None` if this AID is not a P-256 AID.
165    pub fn try_to_p256_bytes(&self) -> Option<[u8; 33]> {
166        if !matches!(self.algorithm(), AidAlgorithm::P256) {
167            return None;
168        }
169        let mut out = [0u8; 33];
170        Base64UrlUnpadded::decode(self.identifier(), &mut out)
171            .expect("Aid is validated on construction; identifier MUST decode to 33 bytes");
172        Some(out)
173    }
174
175    /// Decode the identifier back to the AID's algorithm-agile
176    /// compressed public-key bytes — 32 bytes for Ed25519 (raw
177    /// pubkey) or 33 bytes for P-256 (SEC1-compressed). This is the
178    /// canonical encoding embedded in `TctBinding.cnf` /
179    /// `DelegationBinding.cnf` for algorithm-agile signing-key
180    /// bindings; callers verifying a `cnf` against an AID should
181    /// byte-compare against this value rather than the legacy
182    /// Ed25519-only [`Self::try_to_ed25519_bytes`].
183    pub fn pubkey_compressed_bytes(&self) -> Vec<u8> {
184        // Each arm's `try_*` is guarded by the matching `algorithm()`
185        // discriminant above, so the decode cannot return `None` here.
186        match self.algorithm() {
187            AidAlgorithm::Ed25519 => self
188                .try_to_ed25519_bytes()
189                .expect("Ed25519 arm guarded by algorithm()")
190                .to_vec(),
191            AidAlgorithm::P256 => self
192                .try_to_p256_bytes()
193                .expect("P-256 arm guarded by algorithm()")
194                .to_vec(),
195        }
196    }
197
198    /// Return the full AID string verbatim.
199    pub fn as_str(&self) -> &str {
200        &self.0
201    }
202}
203
204fn validate_ed25519_identifier(identifier: &str) -> Result<(), AidParseError> {
205    if identifier.len() != AID_PUBKEY_IDENTIFIER_LEN {
206        return Err(AidParseError::WrongLength(identifier.len()));
207    }
208    if !identifier.bytes().all(is_base64url_byte) {
209        return Err(AidParseError::InvalidChars);
210    }
211    let mut buf = [0u8; 32];
212    Base64UrlUnpadded::decode(identifier, &mut buf).map_err(|_| AidParseError::InvalidChars)?;
213    Ok(())
214}
215
216fn validate_p256_identifier(identifier: &str) -> Result<(), AidParseError> {
217    if identifier.len() != AID_P256_IDENTIFIER_LEN {
218        return Err(AidParseError::WrongLength(identifier.len()));
219    }
220    if !identifier.bytes().all(is_base64url_byte) {
221        return Err(AidParseError::InvalidChars);
222    }
223    let mut buf = [0u8; 33];
224    Base64UrlUnpadded::decode(identifier, &mut buf).map_err(|_| AidParseError::InvalidChars)?;
225    // SEC1 compressed-point byte MUST be 0x02 or 0x03 (sign bit on
226    // the y-coordinate). Anything else is malformed.
227    if buf[0] != 0x02 && buf[0] != 0x03 {
228        return Err(AidParseError::InvalidChars);
229    }
230    Ok(())
231}
232
233impl fmt::Display for Aid {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.write_str(&self.0)
236    }
237}
238
239impl TryFrom<String> for Aid {
240    type Error = AidParseError;
241    fn try_from(s: String) -> Result<Self, Self::Error> {
242        Aid::parse(&s)
243    }
244}
245
246impl From<Aid> for String {
247    fn from(a: Aid) -> String {
248        a.0
249    }
250}
251
252/// Reasons an AID string can be rejected.
253///
254/// Marked `#[non_exhaustive]`: new parse-failure modes added by future
255/// AID grammar revisions land as new variants without a major bump.
256#[derive(Debug, thiserror::Error, PartialEq, Eq)]
257#[non_exhaustive]
258pub enum AidParseError {
259    /// Missing the `aid:` URI scheme prefix.
260    #[error("AID does not start with 'aid:'")]
261    MissingScheme,
262
263    /// Method other than `pubkey` (e.g. `did`, `x509`) — not supported in v0.1.
264    #[error("AID method '{0}' is not supported in v0.1; expected 'pubkey'")]
265    UnsupportedMethod(String),
266
267    /// Identifier length is not 43 (raw Ed25519 base64url-unpadded).
268    #[error(
269        "AID identifier must be exactly {} characters; got {0}",
270        AID_PUBKEY_IDENTIFIER_LEN
271    )]
272    WrongLength(usize),
273
274    /// Identifier contains characters outside the base64url alphabet.
275    #[error("AID identifier contains non-base64url characters")]
276    InvalidChars,
277}
278
279fn is_base64url_byte(b: u8) -> bool {
280    matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_')
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn sample_pubkey() -> [u8; 32] {
288        let mut k = [0u8; 32];
289        for (i, b) in k.iter_mut().enumerate() {
290            *b = i as u8;
291        }
292        k
293    }
294
295    #[test]
296    fn rejects_missing_scheme() {
297        assert!(matches!(
298            Aid::parse("pubkey:abc"),
299            Err(AidParseError::MissingScheme)
300        ));
301    }
302
303    #[test]
304    fn rejects_unsupported_method() {
305        let s = format!("aid:did:{}", "A".repeat(AID_PUBKEY_IDENTIFIER_LEN));
306        assert!(matches!(
307            Aid::parse(&s),
308            Err(AidParseError::UnsupportedMethod(m)) if m == "did"
309        ));
310    }
311
312    #[test]
313    fn rejects_wrong_length() {
314        assert!(matches!(
315            Aid::parse(&format!("aid:pubkey:{}", "A".repeat(42))),
316            Err(AidParseError::WrongLength(42))
317        ));
318        assert!(matches!(
319            Aid::parse(&format!("aid:pubkey:{}", "A".repeat(44))),
320            Err(AidParseError::WrongLength(44))
321        ));
322    }
323
324    #[test]
325    fn rejects_padding() {
326        // 43 chars including a `=` is not valid base64url-unpadded.
327        let mut s = "A".repeat(42);
328        s.push('=');
329        assert!(matches!(
330            Aid::parse(&format!("aid:pubkey:{}", s)),
331            Err(AidParseError::InvalidChars)
332        ));
333    }
334
335    #[test]
336    fn rejects_invalid_chars() {
337        let mut id = "A".repeat(42);
338        id.push('!');
339        assert!(matches!(
340            Aid::parse(&format!("aid:pubkey:{}", id)),
341            Err(AidParseError::InvalidChars)
342        ));
343    }
344
345    #[test]
346    fn round_trips_pubkey_bytes() {
347        let pk = sample_pubkey();
348        let aid = Aid::from_ed25519(&pk);
349        assert!(aid.as_str().starts_with("aid:pubkey:"));
350        assert_eq!(aid.identifier().len(), AID_PUBKEY_IDENTIFIER_LEN);
351        assert_eq!(aid.try_to_ed25519_bytes().unwrap(), pk);
352    }
353
354    #[test]
355    fn parse_accepts_valid_aid() {
356        let aid = Aid::from_ed25519(&sample_pubkey());
357        let parsed = Aid::parse(aid.as_str()).unwrap();
358        assert_eq!(parsed, aid);
359    }
360
361    #[test]
362    fn serde_round_trip() {
363        let aid = Aid::from_ed25519(&sample_pubkey());
364        let json = serde_json::to_string(&aid).unwrap();
365        let back: Aid = serde_json::from_str(&json).unwrap();
366        assert_eq!(back, aid);
367    }
368
369    #[test]
370    fn parse_accepts_tagged_ed25519() {
371        let pk = sample_pubkey();
372        let tagged = Aid::from_ed25519_tagged(&pk);
373        assert!(tagged.as_str().starts_with("aid:pubkey:ed25519:"));
374        assert_eq!(tagged.algorithm(), AidAlgorithm::Ed25519);
375        let parsed = Aid::parse(tagged.as_str()).unwrap();
376        assert_eq!(parsed, tagged);
377        // The legacy untagged AID over the same pubkey is a
378        // different string — they're trust-equivalent but not
379        // byte-equal in canonical signing bytes (RFC-AITP-0001 §5.3).
380        let legacy = Aid::from_ed25519(&pk);
381        assert_ne!(tagged.as_str(), legacy.as_str());
382    }
383
384    #[test]
385    fn parse_accepts_p256_kat() {
386        // kat-keypair-005-p256: private_scalar = 0x05*32, pubkey =
387        // 0x0307810ea974cea5773e63b897f37e3be9a09e7a5fe9b971a44d1065ac2a3a9311
388        // (SEC1 compressed point).
389        let aid_str = "aid:pubkey:p256:AweBDql0zqV3PmO4l_N-O-mgnnpf6blxpE0QZawqOpMR";
390        let aid = Aid::parse(aid_str).unwrap();
391        assert_eq!(aid.algorithm(), AidAlgorithm::P256);
392        let pubkey = aid.try_to_p256_bytes().unwrap();
393        // First byte is the sign bit (0x02 or 0x03 for SEC1 compressed).
394        assert_eq!(pubkey[0], 0x03);
395    }
396
397    #[test]
398    fn p256_round_trip() {
399        let mut pubkey = [0u8; 33];
400        pubkey[0] = 0x02;
401        pubkey[1] = 0xAB;
402        let aid = Aid::from_p256(&pubkey);
403        let parsed = Aid::parse(aid.as_str()).unwrap();
404        assert_eq!(parsed.algorithm(), AidAlgorithm::P256);
405        assert_eq!(parsed.try_to_p256_bytes().unwrap(), pubkey);
406    }
407
408    #[test]
409    fn p256_rejects_wrong_sec1_tag() {
410        // 0x04 = uncompressed point — we only accept 0x02/0x03
411        // (compressed forms). 33 raw bytes encode to 44 b64url chars.
412        let mut pubkey = [0u8; 33];
413        pubkey[0] = 0x04;
414        let identifier = Base64UrlUnpadded::encode_string(&pubkey);
415        let aid_str = format!("aid:pubkey:p256:{identifier}");
416        assert!(Aid::parse(&aid_str).is_err());
417    }
418
419    #[test]
420    fn rejects_unknown_algorithm_tag() {
421        // `aid:pubkey:rsa4096:...` is not in the registry.
422        let identifier = Base64UrlUnpadded::encode_string(&[0xFFu8; 33]);
423        let aid_str = format!("aid:pubkey:rsa4096:{identifier}");
424        assert!(Aid::parse(&aid_str).is_err());
425    }
426}