1use std::fmt;
23use std::str::FromStr;
24
25use serde::{Deserialize, Deserializer, Serialize, Serializer};
26
27const SEP: char = ':';
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42#[non_exhaustive]
43pub enum Issuer {
44 Idp,
46 Nostr,
48 ApiKey,
50 Oidc,
54 Key,
58}
59
60impl Issuer {
61 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 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 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 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 Self::Nostr => lower_hex_64(subject).map_err(|reason| {
112 PrincipalParseError::InvalidNostrPubkey { subject: subject.to_string(), reason }
113 }),
114
115 Self::Key => lower_hex_64(subject).map_err(|reason| {
118 PrincipalParseError::InvalidKeyPubkey { subject: subject.to_string(), reason }
119 }),
120
121 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 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
162fn 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
173pub(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#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum PrincipalParseError {
195 MissingSeparator(String),
197
198 UnknownIssuer(String),
200
201 EmptySubject(Issuer),
203
204 SubjectContainsSeparator(Issuer),
206
207 InvalidUuid(String),
209
210 InvalidNostrPubkey {
212 subject: String,
214 reason: &'static str,
216 },
217
218 InvalidApiKeyId(String),
220
221 InvalidOidcSubject {
227 subject: String,
229 reason: &'static str,
231 },
232
233 InvalidKeyPubkey {
237 subject: String,
239 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
310pub struct Principal {
311 issuer: Issuer,
312 subject: String,
313}
314
315impl Principal {
316 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 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 pub fn idp(uuid: &uuid::Uuid) -> Self {
348 Self::new(Issuer::Idp, uuid.hyphenated().to_string())
352 .expect("a canonical Uuid is always a valid idp subject")
353 }
354
355 pub fn from_legacy_user_id(user_id: &str) -> Option<Self> {
370 Self::new(Issuer::Idp, user_id).ok()
371 }
372
373 pub fn issuer(&self) -> Issuer {
375 self.issuer
376 }
377
378 pub fn subject(&self) -> &str {
380 &self.subject
381 }
382
383 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 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 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 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 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 const REJECTED: &[&str] = &[
559 "idp",
561 "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
562 "",
563 "ldap:someone",
565 "IDP:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
566 "Nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
567 ":x",
568 "idp:",
570 "nostr:",
571 "apikey:",
572 "idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8:extra",
574 "apikey:ak:live",
575 "idp:not-a-uuid",
577 "idp:6ba7b8109dad11d180b400c04fd430c8",
578 "idp:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
579 "idp:6BA7B810-9DAD-11D1-80B4-00C04FD430C8",
580 "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459",
582 "nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459da",
583 "nostr:3BF0C63FCB93463407AF97A5E5EE64FA883D107EF9E558472C4EB9AAAEFA459D",
584 "nostr:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
585 "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 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 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", "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", "6BA7B810-9DAD-11D1-80B4-00C04FD430C8", ] {
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}