Skip to main content

plexus_auth_core/identity/
principal.rs

1//! [`Principal`] — an issuer-namespaced subject.
2//!
3//! This is the **subject-name** half of the two-`Principal` split documented
4//! in [`crate::identity`]. It answers *which* identity, and *who vouches for
5//! it*; [`crate::principal::Principal`] answers *what kind of actor* is on
6//! the other end of the call.
7//!
8//! # Relationship to `plexus_core::identity::Principal`
9//!
10//! They are the **same type**. PLX-75 originally landed a type of the same
11//! name, grammar, and wire form in `plexus-core`; PLX-82 discovered that
12//! `plexus-core` depends on `plexus-auth-core` and never the reverse, so
13//! `AuthContext` (which lives here) could not name it, and wrote a mirror
14//! here kept in sync by an equivalence test. PLX-87 collapsed the two:
15//! **this is the one definition**, and `plexus_core::identity` is a
16//! `pub use` of this module's items, so `plexus_core::identity::Principal`
17//! keeps working for every consumer PLX-75 wrote for. There is nothing left
18//! to keep in sync, so the equivalence test
19//! (`plexus-idp/tests/principal_equivalence.rs`) was deleted with the
20//! duplication it guarded.
21
22use std::fmt;
23use std::str::FromStr;
24
25use serde::{Deserialize, Deserializer, Serialize, Serializer};
26
27/// The separator between issuer and subject in a principal's string form.
28const SEP: char = ':';
29
30/// Who vouches for a [`Principal`]'s subject.
31///
32/// The set is deliberately **open for extension but closed for guessing**:
33///
34/// - `#[non_exhaustive]` lets a later build add an authenticator (NIP-05,
35///   WebAuthn, mTLS, …) without it being a breaking change for downstream
36///   `match` arms; but
37/// - [`Issuer::parse`] has an explicit arm per known issuer and *rejects*
38///   anything else. An unknown prefix is a [`PrincipalParseError::UnknownIssuer`],
39///   never a silently-accepted opaque string. Adding an issuer therefore
40///   requires adding its validation rule in the same commit.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42#[non_exhaustive]
43pub enum Issuer {
44    /// plexus-idp: a server-minted UUID v4 (`plexus-idp/src/core.rs`).
45    Idp,
46    /// A self-sovereign nostr identity: a 32-byte secp256k1 x-only pubkey.
47    Nostr,
48    /// A machine credential minted as an API key.
49    ApiKey,
50    /// A subject an OIDC provider other than plexus-idp vouches for, behind a
51    /// provider adapter: `oidc:<provider>/<sub>` (IDENTITY-13). The provider
52    /// is the adapter's configured name (`auth0`), never the issuer URL.
53    Oidc,
54    /// An Ed25519 public key an agent holds (IDENTITY-41): `key:<64 hex>`,
55    /// the 32-byte key in lowercase hex. A key proof (`plexus-key.…`,
56    /// `adapters::KeyProofAdapter`) proves it.
57    Key,
58}
59
60impl Issuer {
61    /// The issuer's wire prefix.
62    pub const fn as_str(self) -> &'static str {
63        match self {
64            Self::Idp => "idp",
65            Self::Nostr => "nostr",
66            Self::ApiKey => "apikey",
67            Self::Oidc => "oidc",
68            Self::Key => "key",
69        }
70    }
71
72    /// Parse an issuer prefix. Unknown prefixes are an error, not a new issuer.
73    pub fn parse(s: &str) -> Result<Self, PrincipalParseError> {
74        match s {
75            "idp" => Ok(Self::Idp),
76            "nostr" => Ok(Self::Nostr),
77            "apikey" => Ok(Self::ApiKey),
78            "oidc" => Ok(Self::Oidc),
79            "key" => Ok(Self::Key),
80            other => Err(PrincipalParseError::UnknownIssuer(other.to_string())),
81        }
82    }
83
84    /// Validate a subject against this issuer's rules.
85    fn validate(self, subject: &str) -> Result<(), PrincipalParseError> {
86        if subject.is_empty() {
87            return Err(PrincipalParseError::EmptySubject(self));
88        }
89        if subject.contains(SEP) {
90            return Err(PrincipalParseError::SubjectContainsSeparator(self));
91        }
92
93        match self {
94            // A canonical lowercase hyphenated UUID, exactly as idp mints it
95            // (`Uuid::new_v4().to_string()`). Braced/URN/simple forms are
96            // rejected so that one identity has exactly one rendering and
97            // `Display`/`FromStr` round-trip byte-for-byte.
98            Self::Idp => {
99                let parsed = uuid::Uuid::parse_str(subject)
100                    .map_err(|_| PrincipalParseError::InvalidUuid(subject.to_string()))?;
101                if parsed.hyphenated().to_string() != subject {
102                    return Err(PrincipalParseError::InvalidUuid(subject.to_string()));
103                }
104                Ok(())
105            }
106
107            // 64 lowercase hex characters — the x-only pubkey encoding every
108            // nostr implementation uses. Uppercase is rejected rather than
109            // normalized: normalizing would break the exact round-trip and
110            // give one key two principals.
111            Self::Nostr => lower_hex_64(subject).map_err(|reason| {
112                PrincipalParseError::InvalidNostrPubkey { subject: subject.to_string(), reason }
113            }),
114
115            // IDENTITY-41: the Ed25519 public key, 64 lowercase hex
116            // characters — uppercase refused for the same reason as nostr's.
117            Self::Key => lower_hex_64(subject).map_err(|reason| {
118                PrincipalParseError::InvalidKeyPubkey { subject: subject.to_string(), reason }
119            }),
120
121            // An opaque key id. Constrained to printable, non-whitespace ASCII
122            // so a principal is always safely renderable in a log line, a URL
123            // segment, or a header value.
124            Self::ApiKey => {
125                if subject
126                    .bytes()
127                    .any(|b| !b.is_ascii_graphic() || b == b'"' || b == b'\\')
128                {
129                    return Err(PrincipalParseError::InvalidApiKeyId(subject.to_string()));
130                }
131                Ok(())
132            }
133
134            // `<provider>/<sub>`: a provider name of 1–32 lowercase letters,
135            // digits and hyphens, then the provider's subject as
136            // `Principal::oidc` encoded it — printable ASCII with `:`, `%`,
137            // quotes and backslashes percent-encoded, so every subject a
138            // provider can mint has exactly one rendering.
139            Self::Oidc => {
140                let invalid = |reason: &'static str| PrincipalParseError::InvalidOidcSubject {
141                    subject: subject.to_string(),
142                    reason,
143                };
144                let (provider, sub) = subject
145                    .split_once('/')
146                    .ok_or_else(|| invalid("expected `<provider>/<sub>`"))?;
147                if !valid_provider_name(provider) {
148                    return Err(invalid("the provider name must be 1-32 of a-z, 0-9 and -"));
149                }
150                if sub.is_empty() {
151                    return Err(invalid("the provider's subject is empty"));
152                }
153                if sub.bytes().any(|b| !b.is_ascii_graphic() || b == b'"' || b == b'\\') {
154                    return Err(invalid("the provider's subject is not percent-encoded"));
155                }
156                Ok(())
157            }
158        }
159    }
160}
161
162/// 64 lowercase hex characters (a 32-byte key), or which rule broke.
163fn lower_hex_64(subject: &str) -> Result<(), &'static str> {
164    if subject.len() != 64 {
165        return Err("expected exactly 64 hex characters");
166    }
167    if !subject.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
168        return Err("expected lowercase hex only");
169    }
170    Ok(())
171}
172
173/// An OIDC adapter's provider name: 1–32 of `a-z`, `0-9` and `-`.
174pub(crate) fn valid_provider_name(name: &str) -> bool {
175    !name.is_empty()
176        && name.len() <= 32
177        && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
178}
179
180impl fmt::Display for Issuer {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.write_str(self.as_str())
183    }
184}
185
186/// Why a string is not a valid [`Principal`].
187///
188/// Intentionally **not** `#[non_exhaustive]`: `plexus_core::identity::`
189/// `PrincipalParseError` re-exports this type (PLX-87), and PLX-75's original
190/// was exhaustive, so downstream `match` arms written against the plexus-core
191/// path keep compiling. The `Display` strings are byte-identical to PLX-75's
192/// for the same reason.
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum PrincipalParseError {
195    /// No `:` separator at all.
196    MissingSeparator(String),
197
198    /// The prefix is not a known issuer.
199    UnknownIssuer(String),
200
201    /// The subject was empty.
202    EmptySubject(Issuer),
203
204    /// The subject contained a second `:`, making the rendering ambiguous.
205    SubjectContainsSeparator(Issuer),
206
207    /// `idp:` subject was not a canonical hyphenated UUID.
208    InvalidUuid(String),
209
210    /// `nostr:` subject was not a 64-character lowercase hex pubkey.
211    InvalidNostrPubkey {
212        /// The rejected subject.
213        subject: String,
214        /// Which rule it broke.
215        reason: &'static str,
216    },
217
218    /// `apikey:` subject contained non-printable or quoting characters.
219    InvalidApiKeyId(String),
220
221    /// `oidc:` subject was not `<provider>/<sub>` (IDENTITY-13).
222    ///
223    /// Added after the enum was pinned exhaustive for PLX-87's re-export: a
224    /// downstream `match` with no wildcard arm needs this arm. No crate in
225    /// the workspace has one.
226    InvalidOidcSubject {
227        /// The rejected subject.
228        subject: String,
229        /// Which rule it broke.
230        reason: &'static str,
231    },
232
233    /// `key:` subject was not a 64-character lowercase hex Ed25519 public
234    /// key (IDENTITY-41). Added after the enum was pinned exhaustive, as
235    /// `InvalidOidcSubject` was.
236    InvalidKeyPubkey {
237        /// The rejected subject.
238        subject: String,
239        /// Which rule it broke.
240        reason: &'static str,
241    },
242}
243
244impl fmt::Display for PrincipalParseError {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        match self {
247            Self::MissingSeparator(s) => write!(
248                f,
249                "principal `{s}` has no `{SEP}` separator; expected `<issuer>{SEP}<subject>`"
250            ),
251            Self::UnknownIssuer(s) => write!(
252                f,
253                "unknown principal issuer `{s}`; known issuers: idp, nostr, apikey, oidc, key"
254            ),
255            Self::EmptySubject(i) => write!(f, "principal issuer `{i}` has an empty subject"),
256            Self::SubjectContainsSeparator(i) => write!(
257                f,
258                "principal subject for issuer `{i}` contains a `{SEP}`, which is ambiguous"
259            ),
260            Self::InvalidUuid(s) => {
261                write!(f, "principal subject `{s}` is not a canonical hyphenated UUID")
262            }
263            Self::InvalidNostrPubkey { subject, reason } => write!(
264                f,
265                "principal subject `{subject}` is not a valid nostr pubkey: {reason}"
266            ),
267            Self::InvalidApiKeyId(s) => {
268                write!(f, "principal subject `{s}` is not a valid api key id")
269            }
270            Self::InvalidOidcSubject { subject, reason } => write!(
271                f,
272                "principal subject `{subject}` is not a valid oidc subject: {reason}"
273            ),
274            Self::InvalidKeyPubkey { subject, reason } => write!(
275                f,
276                "principal subject `{subject}` is not a valid Ed25519 public key: {reason}"
277            ),
278        }
279    }
280}
281
282impl std::error::Error for PrincipalParseError {}
283
284/// An issuer-namespaced subject: `idp:<uuid>`, `nostr:<64-hex>`, `apikey:<id>`.
285///
286/// # Invariants
287///
288/// The fields are private and both constructors ([`Principal::new`] and
289/// [`FromStr`]) validate, so *every* `Principal` value in existence satisfies
290/// its issuer's rules. `Deserialize` goes through `FromStr`, so a JSON document
291/// cannot smuggle in an invalid one either.
292///
293/// [`Display`](fmt::Display) and [`FromStr`] round-trip **exactly** — no
294/// normalization is performed anywhere, because normalizing would let one
295/// subject have two renderings and therefore two unequal `Principal`s.
296///
297/// # Wire form
298///
299/// A plain JSON string (`"idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8"`), not an
300/// object — implemented by hand rather than with `#[serde(transparent)]` so
301/// that deserialization can enforce validation.
302///
303/// # This is a name, not a proof
304///
305/// Holding a `Principal` proves nothing about authentication: it is data,
306/// parsed from a string. The *proof* is [`Authenticated`](super::Authenticated),
307/// which only an [`Authenticator`](super::Authenticator) produces, and whose
308/// principal field was populated from verified material.
309#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
310pub struct Principal {
311    issuer: Issuer,
312    subject: String,
313}
314
315impl Principal {
316    /// Build a principal, validating the subject against the issuer's rules.
317    ///
318    /// # Errors
319    ///
320    /// See [`PrincipalParseError`].
321    pub fn new(issuer: Issuer, subject: impl Into<String>) -> Result<Self, PrincipalParseError> {
322        let subject = subject.into();
323        issuer.validate(&subject)?;
324        Ok(Self { issuer, subject })
325    }
326
327    /// The principal an OIDC provider adapter mints: `oidc:<provider>/<sub>`.
328    ///
329    /// `provider` is the adapter's configured name (`auth0`). `sub` is the
330    /// provider's subject exactly as its token carries it; any `:`, `%`,
331    /// quote, backslash or non-printable byte is percent-encoded, so
332    /// `auth0|64f1` stays `auth0|64f1` and a colon-bearing subject still
333    /// has one rendering that round-trips through `Display` and `FromStr`.
334    pub fn oidc(provider: &str, sub: &str) -> Result<Self, PrincipalParseError> {
335        let mut encoded = String::with_capacity(sub.len());
336        for b in sub.bytes() {
337            if b.is_ascii_graphic() && !matches!(b, b':' | b'%' | b'"' | b'\\') {
338                encoded.push(b as char);
339            } else {
340                encoded.push_str(&format!("%{b:02X}"));
341            }
342        }
343        Self::new(Issuer::Oidc, format!("{provider}/{encoded}"))
344    }
345
346    /// An idp-minted principal from a UUID.
347    pub fn idp(uuid: &uuid::Uuid) -> Self {
348        // A `Uuid` always renders as a canonical hyphenated string, so this
349        // cannot fail — but it still goes through the validating constructor
350        // so there is exactly one path that builds a `Principal`.
351        Self::new(Issuer::Idp, uuid.hyphenated().to_string())
352            .expect("a canonical Uuid is always a valid idp subject")
353    }
354
355    /// Interpret a legacy bare `user_id` as an idp principal.
356    ///
357    /// This is the bridge that makes [`AuthContext::principal`] and
358    /// [`AuthContext::user_id`] agree by construction: today's `user_id` is
359    /// a plexus-idp-minted UUID v4 reused verbatim as the JWT `sub`, so
360    /// `idp:<user_id>` is the same identity under a namespaced name.
361    ///
362    /// Returns `None` for anything that is not a canonical hyphenated UUID —
363    /// notably `"anonymous"`, and any `user_id` minted by a system that is
364    /// not plexus-idp. A `None` here means "this context has no principal we
365    /// can name", never "this context is authenticated as something else".
366    ///
367    /// [`AuthContext::principal`]: crate::AuthContext::principal
368    /// [`AuthContext::user_id`]: crate::AuthContext#structfield.user_id
369    pub fn from_legacy_user_id(user_id: &str) -> Option<Self> {
370        Self::new(Issuer::Idp, user_id).ok()
371    }
372
373    /// Who vouches for this subject.
374    pub fn issuer(&self) -> Issuer {
375        self.issuer
376    }
377
378    /// The issuer-scoped subject, without the prefix.
379    pub fn subject(&self) -> &str {
380        &self.subject
381    }
382
383    /// The value this principal contributes to the legacy
384    /// [`AuthContext::user_id`](crate::AuthContext#structfield.user_id)
385    /// field.
386    ///
387    /// For `idp:` principals this is the bare subject — byte-identical to
388    /// what plexus-idp writes today, so nothing that reads `user_id`
389    /// observes any change. For every other issuer it is the **full**
390    /// namespaced string (`nostr:abc…`), because a nostr pubkey and an idp
391    /// UUID share no namespace and must never collide in a column that
392    /// callers treat as a unique user key.
393    pub fn as_legacy_user_id(&self) -> String {
394        match self.issuer {
395            Issuer::Idp => self.subject.clone(),
396            _ => self.to_string(),
397        }
398    }
399}
400
401impl fmt::Display for Principal {
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        write!(f, "{}{}{}", self.issuer.as_str(), SEP, self.subject)
404    }
405}
406
407impl FromStr for Principal {
408    type Err = PrincipalParseError;
409
410    fn from_str(s: &str) -> Result<Self, Self::Err> {
411        // Split on the FIRST separator; `Issuer::validate` then rejects any
412        // further `:` in the remainder, so `idp:a:b` is an error rather than a
413        // principal with a colon-bearing subject.
414        let (prefix, subject) = s
415            .split_once(SEP)
416            .ok_or_else(|| PrincipalParseError::MissingSeparator(s.to_string()))?;
417        let issuer = Issuer::parse(prefix)?;
418        issuer.validate(subject)?;
419        Ok(Self {
420            issuer,
421            subject: subject.to_string(),
422        })
423    }
424}
425
426impl Serialize for Principal {
427    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
428        s.collect_str(self)
429    }
430}
431
432impl<'de> Deserialize<'de> for Principal {
433    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
434        let raw = String::deserialize(d)?;
435        raw.parse().map_err(serde::de::Error::custom)
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
444    const PUBKEY: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
445
446    fn samples() -> Vec<&'static str> {
447        vec![
448            "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
449            "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
450            "apikey:ak_live_01HQ8ZQK",
451        ]
452    }
453
454    #[test]
455    fn display_fromstr_round_trip_exactly() {
456        for s in samples() {
457            let p: Principal = s.parse().expect(s);
458            assert_eq!(p.to_string(), s);
459            let again: Principal = p.to_string().parse().unwrap();
460            assert_eq!(p, again);
461        }
462    }
463
464    #[test]
465    fn serde_round_trips_as_a_plain_string() {
466        for s in samples() {
467            let p: Principal = s.parse().unwrap();
468            let json = serde_json::to_string(&p).unwrap();
469            assert_eq!(json, format!("\"{s}\""));
470            let back: Principal = serde_json::from_str(&json).unwrap();
471            assert_eq!(p, back);
472        }
473    }
474
475    #[test]
476    fn deserialization_enforces_validation() {
477        assert!(serde_json::from_str::<Principal>("\"ldap:someone\"").is_err());
478        assert!(serde_json::from_str::<Principal>("\"nostr:NOTHEX\"").is_err());
479    }
480
481    #[test]
482    fn rejects_unknown_issuer_and_missing_separator() {
483        assert!(matches!(
484            "ldap:someone".parse::<Principal>(),
485            Err(PrincipalParseError::UnknownIssuer(i)) if i == "ldap"
486        ));
487        assert!(matches!(
488            "idp".parse::<Principal>(),
489            Err(PrincipalParseError::MissingSeparator(_))
490        ));
491    }
492
493    #[test]
494    fn rejects_malformed_subjects_per_issuer() {
495        assert!(format!("idp:{}", "not-a-uuid").parse::<Principal>().is_err());
496        assert!(format!("nostr:{}", PUBKEY.to_uppercase())
497            .parse::<Principal>()
498            .is_err());
499        assert!("apikey:ak live".parse::<Principal>().is_err());
500        assert!("idp:".parse::<Principal>().is_err());
501        assert!(format!("idp:{UUID}:extra").parse::<Principal>().is_err());
502    }
503
504    #[test]
505    fn from_legacy_user_id_round_trips_todays_user_ids() {
506        let p = Principal::from_legacy_user_id(UUID).unwrap();
507        assert_eq!(p.to_string(), format!("idp:{UUID}"));
508        assert_eq!(p.as_legacy_user_id(), UUID);
509        // The anonymous sentinel is not a principal.
510        assert!(Principal::from_legacy_user_id("anonymous").is_none());
511    }
512
513    #[test]
514    fn non_idp_principals_keep_their_namespace_in_the_legacy_field() {
515        let p: Principal = format!("nostr:{PUBKEY}").parse().unwrap();
516        assert_eq!(p.as_legacy_user_id(), format!("nostr:{PUBKEY}"));
517        // and that string is not mistakable for an idp user_id
518        assert!(Principal::from_legacy_user_id(&p.as_legacy_user_id()).is_none());
519    }
520
521    #[test]
522    fn principals_from_different_issuers_never_collide() {
523        let a = Principal::new(Issuer::ApiKey, UUID).unwrap();
524        let b = Principal::new(Issuer::Idp, UUID).unwrap();
525        assert_ne!(a, b);
526        assert_ne!(a.to_string(), b.to_string());
527    }
528
529    #[test]
530    fn idp_helper_matches_manual_construction() {
531        let u = uuid::Uuid::parse_str(UUID).unwrap();
532        assert_eq!(Principal::idp(&u), Principal::new(Issuer::Idp, UUID).unwrap());
533        assert_eq!(Principal::idp(&u).to_string(), format!("idp:{UUID}"));
534    }
535
536    // ---------------------------------------------------------------------
537    // PLX-87: coverage folded in from the two things this type replaced —
538    // `plexus_core::identity::principal`'s unit tests (PLX-75), now deleted
539    // because plexus-core re-exports this module, and the accepted/rejected
540    // corpus from `plexus-idp/tests/principal_equivalence.rs` (PLX-82), also
541    // deleted because there is no longer a second implementation to equate.
542    // The assertions below are the *union* of what those two files asserted
543    // about this grammar; none of that coverage was dropped in the collapse.
544    // ---------------------------------------------------------------------
545
546    /// Every form both former implementations were required to accept.
547    const ACCEPTED: &[&str] = &[
548        "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
549        "idp:00000000-0000-4000-8000-000000000001",
550        "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
551        "nostr:0000000000000000000000000000000000000000000000000000000000000000",
552        "apikey:ak_live_01HQ8ZQK",
553        "apikey:a",
554        "apikey:!#$%&'()*+,-./",
555    ];
556
557    /// Every form both former implementations were required to reject.
558    const REJECTED: &[&str] = &[
559        // no separator
560        "idp",
561        "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
562        "",
563        // unknown issuer
564        "ldap:someone",
565        "IDP:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
566        "Nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
567        ":x",
568        // empty subject
569        "idp:",
570        "nostr:",
571        "apikey:",
572        // second separator
573        "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8:extra",
574        "apikey:ak:live",
575        // non-canonical uuid
576        "idp:not-a-uuid",
577        "idp:6ba7b8109dad11d180b400c04fd430c8",
578        "idp:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
579        "idp:6BA7B810-9DAD-11D1-80B4-00C04FD430C8",
580        // bad nostr pubkeys
581        "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459",
582        "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459da",
583        "nostr:3BF0C63FCB93463407AF97A5E5EE64FA883D107EF9E558472C4EB9AAAEFA459D",
584        "nostr:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
585        // bad api key ids
586        "apikey:ak live",
587        "apikey:ak\tlive",
588        "apikey:ak\"live",
589        "apikey:ak\\live",
590    ];
591
592    #[test]
593    fn accepts_the_whole_accepted_corpus_and_round_trips_it_exactly() {
594        for s in ACCEPTED {
595            let p: Principal = s
596                .parse()
597                .unwrap_or_else(|e| panic!("`{s}` should be accepted: {e}"));
598            assert_eq!(p.to_string(), *s, "must round-trip `{s}` exactly");
599            let json = serde_json::to_string(&p).unwrap();
600            assert_eq!(json, format!("\"{s}\""), "wire form must be a bare string");
601            assert_eq!(serde_json::from_str::<Principal>(&json).unwrap(), p);
602        }
603    }
604
605    #[test]
606    fn rejects_the_whole_rejected_corpus_at_both_entry_points() {
607        for s in REJECTED {
608            assert!(s.parse::<Principal>().is_err(), "`{s:?}` must be rejected");
609            // Deserialization must not be a back door around FromStr.
610            let doc = serde_json::to_string(s).unwrap();
611            assert!(
612                serde_json::from_str::<Principal>(&doc).is_err(),
613                "`{s:?}` must be rejected by Deserialize too"
614            );
615        }
616    }
617
618    #[test]
619    fn issuer_and_subject_are_split_correctly() {
620        let p: Principal = format!("idp:{UUID}").parse().unwrap();
621        assert_eq!(p.issuer(), Issuer::Idp);
622        assert_eq!(p.subject(), UUID);
623
624        let p: Principal = format!("nostr:{PUBKEY}").parse().unwrap();
625        assert_eq!(p.issuer(), Issuer::Nostr);
626        assert_eq!(p.subject(), PUBKEY);
627
628        let p: Principal = "apikey:ak_live_01HQ8ZQK".parse().unwrap();
629        assert_eq!(p.issuer(), Issuer::ApiKey);
630        assert_eq!(p.subject(), "ak_live_01HQ8ZQK");
631    }
632
633    #[test]
634    fn deserialization_error_text_names_the_rule_that_was_broken() {
635        let err = serde_json::from_str::<Principal>("\"ldap:someone\"").unwrap_err();
636        assert!(err.to_string().contains("unknown principal issuer"), "{err}");
637
638        let err = serde_json::from_str::<Principal>("\"nostr:NOTHEX\"").unwrap_err();
639        assert!(err.to_string().contains("nostr pubkey"), "{err}");
640    }
641
642    #[test]
643    fn rejects_unknown_issuer_including_wrong_case() {
644        assert!(matches!(
645            "ldap:someone".parse::<Principal>(),
646            Err(PrincipalParseError::UnknownIssuer(i)) if i == "ldap"
647        ));
648        // Capitalization of the issuer is not a known issuer either.
649        assert!(matches!(
650            "IDP:6ba7b810-9dad-11d1-80b4-00c04fd430c8".parse::<Principal>(),
651            Err(PrincipalParseError::UnknownIssuer(_))
652        ));
653    }
654
655    #[test]
656    fn rejects_empty_subject_for_every_issuer() {
657        for issuer in ["idp", "nostr", "apikey"] {
658            let s = format!("{issuer}:");
659            assert!(
660                matches!(
661                    s.parse::<Principal>(),
662                    Err(PrincipalParseError::EmptySubject(_))
663                ),
664                "{s} should be rejected"
665            );
666        }
667    }
668
669    #[test]
670    fn rejects_missing_separator() {
671        assert!(matches!(
672            "idp".parse::<Principal>(),
673            Err(PrincipalParseError::MissingSeparator(_))
674        ));
675        assert!(matches!(
676            UUID.parse::<Principal>(),
677            Err(PrincipalParseError::MissingSeparator(_))
678        ));
679    }
680
681    #[test]
682    fn rejects_nostr_pubkey_of_wrong_length() {
683        let short = &PUBKEY[..63];
684        let long = format!("{PUBKEY}a");
685        assert_eq!(short.len(), 63);
686        assert_eq!(long.len(), 65);
687
688        for bad in [short.to_string(), long] {
689            let s = format!("nostr:{bad}");
690            match s.parse::<Principal>() {
691                Err(PrincipalParseError::InvalidNostrPubkey { reason, .. }) => {
692                    assert_eq!(reason, "expected exactly 64 hex characters");
693                }
694                other => panic!("{s} should be rejected, got {other:?}"),
695            }
696        }
697    }
698
699    #[test]
700    fn rejects_uppercase_nostr_hex() {
701        let upper = PUBKEY.to_uppercase();
702        assert_eq!(upper.len(), 64);
703        let s = format!("nostr:{upper}");
704        match s.parse::<Principal>() {
705            Err(PrincipalParseError::InvalidNostrPubkey { reason, .. }) => {
706                assert_eq!(reason, "expected lowercase hex only");
707            }
708            other => panic!("uppercase hex should be rejected, got {other:?}"),
709        }
710    }
711
712    #[test]
713    fn rejects_embedded_second_colon() {
714        for s in [
715            format!("idp:{UUID}:extra"),
716            format!("nostr:{PUBKEY}:extra"),
717            "apikey:ak:live".to_string(),
718        ] {
719            assert!(
720                matches!(
721                    s.parse::<Principal>(),
722                    Err(PrincipalParseError::SubjectContainsSeparator(_))
723                ),
724                "{s} should be rejected"
725            );
726        }
727    }
728
729    #[test]
730    fn rejects_non_canonical_uuid() {
731        for bad in [
732            "not-a-uuid",
733            "6ba7b8109dad11d180b400c04fd430c8",       // simple form
734            "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", // braced form
735            "6BA7B810-9DAD-11D1-80B4-00C04FD430C8",   // uppercase
736        ] {
737            let s = format!("idp:{bad}");
738            assert!(
739                matches!(
740                    s.parse::<Principal>(),
741                    Err(PrincipalParseError::InvalidUuid(_))
742                ),
743                "{s} should be rejected"
744            );
745        }
746    }
747
748    #[test]
749    fn rejects_unprintable_api_key_ids() {
750        for bad in ["ak live", "ak\tlive", "ak\"live", "ak\\live"] {
751            let s = format!("apikey:{bad}");
752            assert!(
753                matches!(
754                    s.parse::<Principal>(),
755                    Err(PrincipalParseError::InvalidApiKeyId(_))
756                ),
757                "{s:?} should be rejected"
758            );
759        }
760    }
761
762    #[test]
763    fn a_key_principal_is_64_lowercase_hex_and_round_trips() {
764        let s = format!("key:{PUBKEY}");
765        let p: Principal = s.parse().unwrap();
766        assert_eq!(p.issuer(), Issuer::Key);
767        assert_eq!(p.subject(), PUBKEY);
768        assert_eq!(p.to_string(), s);
769        assert_eq!(serde_json::to_string(&p).unwrap(), format!("\"{s}\""));
770        assert_eq!(serde_json::from_str::<Principal>(&format!("\"{s}\"")).unwrap(), p);
771        assert_eq!(p.as_legacy_user_id(), s, "keeps its namespace");
772        assert_ne!(p, Principal::new(Issuer::Nostr, PUBKEY).unwrap(), "one key, two issuers: two principals");
773        match format!("key:{}", PUBKEY.to_uppercase()).parse::<Principal>() {
774            Err(PrincipalParseError::InvalidKeyPubkey { reason, .. }) => assert_eq!(reason, "expected lowercase hex only"),
775            other => panic!("uppercase must be refused: {other:?}"),
776        }
777        for bad in [&PUBKEY[..63], &format!("{PUBKEY}0")[..], "", "zz"] {
778            assert!(format!("key:{bad}").parse::<Principal>().is_err(), "{bad}");
779        }
780        assert!(format!("key:{PUBKEY}:x").parse::<Principal>().is_err());
781        assert!(format!("KEY:{PUBKEY}").parse::<Principal>().is_err());
782    }
783
784    #[test]
785    fn new_validates_like_from_str() {
786        assert!(Principal::new(Issuer::Idp, UUID).is_ok());
787        assert!(Principal::new(Issuer::Idp, "nope").is_err());
788        assert!(Principal::new(Issuer::Nostr, PUBKEY).is_ok());
789        assert!(Principal::new(Issuer::Nostr, "").is_err());
790    }
791}