use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
const SEP: char = ':';
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Issuer {
Idp,
Nostr,
ApiKey,
Oidc,
Key,
}
impl Issuer {
pub const fn as_str(self) -> &'static str {
match self {
Self::Idp => "idp",
Self::Nostr => "nostr",
Self::ApiKey => "apikey",
Self::Oidc => "oidc",
Self::Key => "key",
}
}
pub fn parse(s: &str) -> Result<Self, PrincipalParseError> {
match s {
"idp" => Ok(Self::Idp),
"nostr" => Ok(Self::Nostr),
"apikey" => Ok(Self::ApiKey),
"oidc" => Ok(Self::Oidc),
"key" => Ok(Self::Key),
other => Err(PrincipalParseError::UnknownIssuer(other.to_string())),
}
}
fn validate(self, subject: &str) -> Result<(), PrincipalParseError> {
if subject.is_empty() {
return Err(PrincipalParseError::EmptySubject(self));
}
if subject.contains(SEP) {
return Err(PrincipalParseError::SubjectContainsSeparator(self));
}
match self {
Self::Idp => {
let parsed = uuid::Uuid::parse_str(subject)
.map_err(|_| PrincipalParseError::InvalidUuid(subject.to_string()))?;
if parsed.hyphenated().to_string() != subject {
return Err(PrincipalParseError::InvalidUuid(subject.to_string()));
}
Ok(())
}
Self::Nostr => lower_hex_64(subject).map_err(|reason| {
PrincipalParseError::InvalidNostrPubkey { subject: subject.to_string(), reason }
}),
Self::Key => lower_hex_64(subject).map_err(|reason| {
PrincipalParseError::InvalidKeyPubkey { subject: subject.to_string(), reason }
}),
Self::ApiKey => {
if subject
.bytes()
.any(|b| !b.is_ascii_graphic() || b == b'"' || b == b'\\')
{
return Err(PrincipalParseError::InvalidApiKeyId(subject.to_string()));
}
Ok(())
}
Self::Oidc => {
let invalid = |reason: &'static str| PrincipalParseError::InvalidOidcSubject {
subject: subject.to_string(),
reason,
};
let (provider, sub) = subject
.split_once('/')
.ok_or_else(|| invalid("expected `<provider>/<sub>`"))?;
if !valid_provider_name(provider) {
return Err(invalid("the provider name must be 1-32 of a-z, 0-9 and -"));
}
if sub.is_empty() {
return Err(invalid("the provider's subject is empty"));
}
if sub.bytes().any(|b| !b.is_ascii_graphic() || b == b'"' || b == b'\\') {
return Err(invalid("the provider's subject is not percent-encoded"));
}
Ok(())
}
}
}
}
fn lower_hex_64(subject: &str) -> Result<(), &'static str> {
if subject.len() != 64 {
return Err("expected exactly 64 hex characters");
}
if !subject.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return Err("expected lowercase hex only");
}
Ok(())
}
pub(crate) fn valid_provider_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 32
&& name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
impl fmt::Display for Issuer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PrincipalParseError {
MissingSeparator(String),
UnknownIssuer(String),
EmptySubject(Issuer),
SubjectContainsSeparator(Issuer),
InvalidUuid(String),
InvalidNostrPubkey {
subject: String,
reason: &'static str,
},
InvalidApiKeyId(String),
InvalidOidcSubject {
subject: String,
reason: &'static str,
},
InvalidKeyPubkey {
subject: String,
reason: &'static str,
},
}
impl fmt::Display for PrincipalParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingSeparator(s) => write!(
f,
"principal `{s}` has no `{SEP}` separator; expected `<issuer>{SEP}<subject>`"
),
Self::UnknownIssuer(s) => write!(
f,
"unknown principal issuer `{s}`; known issuers: idp, nostr, apikey, oidc, key"
),
Self::EmptySubject(i) => write!(f, "principal issuer `{i}` has an empty subject"),
Self::SubjectContainsSeparator(i) => write!(
f,
"principal subject for issuer `{i}` contains a `{SEP}`, which is ambiguous"
),
Self::InvalidUuid(s) => {
write!(f, "principal subject `{s}` is not a canonical hyphenated UUID")
}
Self::InvalidNostrPubkey { subject, reason } => write!(
f,
"principal subject `{subject}` is not a valid nostr pubkey: {reason}"
),
Self::InvalidApiKeyId(s) => {
write!(f, "principal subject `{s}` is not a valid api key id")
}
Self::InvalidOidcSubject { subject, reason } => write!(
f,
"principal subject `{subject}` is not a valid oidc subject: {reason}"
),
Self::InvalidKeyPubkey { subject, reason } => write!(
f,
"principal subject `{subject}` is not a valid Ed25519 public key: {reason}"
),
}
}
}
impl std::error::Error for PrincipalParseError {}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Principal {
issuer: Issuer,
subject: String,
}
impl Principal {
pub fn new(issuer: Issuer, subject: impl Into<String>) -> Result<Self, PrincipalParseError> {
let subject = subject.into();
issuer.validate(&subject)?;
Ok(Self { issuer, subject })
}
pub fn oidc(provider: &str, sub: &str) -> Result<Self, PrincipalParseError> {
let mut encoded = String::with_capacity(sub.len());
for b in sub.bytes() {
if b.is_ascii_graphic() && !matches!(b, b':' | b'%' | b'"' | b'\\') {
encoded.push(b as char);
} else {
encoded.push_str(&format!("%{b:02X}"));
}
}
Self::new(Issuer::Oidc, format!("{provider}/{encoded}"))
}
pub fn idp(uuid: &uuid::Uuid) -> Self {
Self::new(Issuer::Idp, uuid.hyphenated().to_string())
.expect("a canonical Uuid is always a valid idp subject")
}
pub fn from_legacy_user_id(user_id: &str) -> Option<Self> {
Self::new(Issuer::Idp, user_id).ok()
}
pub fn issuer(&self) -> Issuer {
self.issuer
}
pub fn subject(&self) -> &str {
&self.subject
}
pub fn as_legacy_user_id(&self) -> String {
match self.issuer {
Issuer::Idp => self.subject.clone(),
_ => self.to_string(),
}
}
}
impl fmt::Display for Principal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}{}", self.issuer.as_str(), SEP, self.subject)
}
}
impl FromStr for Principal {
type Err = PrincipalParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (prefix, subject) = s
.split_once(SEP)
.ok_or_else(|| PrincipalParseError::MissingSeparator(s.to_string()))?;
let issuer = Issuer::parse(prefix)?;
issuer.validate(subject)?;
Ok(Self {
issuer,
subject: subject.to_string(),
})
}
}
impl Serialize for Principal {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Principal {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
const UUID: &str = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
const PUBKEY: &str = "3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d";
fn samples() -> Vec<&'static str> {
vec![
"idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
"apikey:ak_live_01HQ8ZQK",
]
}
#[test]
fn display_fromstr_round_trip_exactly() {
for s in samples() {
let p: Principal = s.parse().expect(s);
assert_eq!(p.to_string(), s);
let again: Principal = p.to_string().parse().unwrap();
assert_eq!(p, again);
}
}
#[test]
fn serde_round_trips_as_a_plain_string() {
for s in samples() {
let p: Principal = s.parse().unwrap();
let json = serde_json::to_string(&p).unwrap();
assert_eq!(json, format!("\"{s}\""));
let back: Principal = serde_json::from_str(&json).unwrap();
assert_eq!(p, back);
}
}
#[test]
fn deserialization_enforces_validation() {
assert!(serde_json::from_str::<Principal>("\"ldap:someone\"").is_err());
assert!(serde_json::from_str::<Principal>("\"nostr:NOTHEX\"").is_err());
}
#[test]
fn rejects_unknown_issuer_and_missing_separator() {
assert!(matches!(
"ldap:someone".parse::<Principal>(),
Err(PrincipalParseError::UnknownIssuer(i)) if i == "ldap"
));
assert!(matches!(
"idp".parse::<Principal>(),
Err(PrincipalParseError::MissingSeparator(_))
));
}
#[test]
fn rejects_malformed_subjects_per_issuer() {
assert!(format!("idp:{}", "not-a-uuid").parse::<Principal>().is_err());
assert!(format!("nostr:{}", PUBKEY.to_uppercase())
.parse::<Principal>()
.is_err());
assert!("apikey:ak live".parse::<Principal>().is_err());
assert!("idp:".parse::<Principal>().is_err());
assert!(format!("idp:{UUID}:extra").parse::<Principal>().is_err());
}
#[test]
fn from_legacy_user_id_round_trips_todays_user_ids() {
let p = Principal::from_legacy_user_id(UUID).unwrap();
assert_eq!(p.to_string(), format!("idp:{UUID}"));
assert_eq!(p.as_legacy_user_id(), UUID);
assert!(Principal::from_legacy_user_id("anonymous").is_none());
}
#[test]
fn non_idp_principals_keep_their_namespace_in_the_legacy_field() {
let p: Principal = format!("nostr:{PUBKEY}").parse().unwrap();
assert_eq!(p.as_legacy_user_id(), format!("nostr:{PUBKEY}"));
assert!(Principal::from_legacy_user_id(&p.as_legacy_user_id()).is_none());
}
#[test]
fn principals_from_different_issuers_never_collide() {
let a = Principal::new(Issuer::ApiKey, UUID).unwrap();
let b = Principal::new(Issuer::Idp, UUID).unwrap();
assert_ne!(a, b);
assert_ne!(a.to_string(), b.to_string());
}
#[test]
fn idp_helper_matches_manual_construction() {
let u = uuid::Uuid::parse_str(UUID).unwrap();
assert_eq!(Principal::idp(&u), Principal::new(Issuer::Idp, UUID).unwrap());
assert_eq!(Principal::idp(&u).to_string(), format!("idp:{UUID}"));
}
const ACCEPTED: &[&str] = &[
"idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"idp:00000000-0000-4000-8000-000000000001",
"nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
"nostr:0000000000000000000000000000000000000000000000000000000000000000",
"apikey:ak_live_01HQ8ZQK",
"apikey:a",
"apikey:!#$%&'()*+,-./",
];
const REJECTED: &[&str] = &[
"idp",
"6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"",
"ldap:someone",
"IDP:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
"Nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
":x",
"idp:",
"nostr:",
"apikey:",
"idp:6ba7b810-9dad-11d1-80b4-00c04fd430c8:extra",
"apikey:ak:live",
"idp:not-a-uuid",
"idp:6ba7b8109dad11d180b400c04fd430c8",
"idp:{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
"idp:6BA7B810-9DAD-11D1-80B4-00C04FD430C8",
"nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459",
"nostr:3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459da",
"nostr:3BF0C63FCB93463407AF97A5E5EE64FA883D107EF9E558472C4EB9AAAEFA459D",
"nostr:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
"apikey:ak live",
"apikey:ak\tlive",
"apikey:ak\"live",
"apikey:ak\\live",
];
#[test]
fn accepts_the_whole_accepted_corpus_and_round_trips_it_exactly() {
for s in ACCEPTED {
let p: Principal = s
.parse()
.unwrap_or_else(|e| panic!("`{s}` should be accepted: {e}"));
assert_eq!(p.to_string(), *s, "must round-trip `{s}` exactly");
let json = serde_json::to_string(&p).unwrap();
assert_eq!(json, format!("\"{s}\""), "wire form must be a bare string");
assert_eq!(serde_json::from_str::<Principal>(&json).unwrap(), p);
}
}
#[test]
fn rejects_the_whole_rejected_corpus_at_both_entry_points() {
for s in REJECTED {
assert!(s.parse::<Principal>().is_err(), "`{s:?}` must be rejected");
let doc = serde_json::to_string(s).unwrap();
assert!(
serde_json::from_str::<Principal>(&doc).is_err(),
"`{s:?}` must be rejected by Deserialize too"
);
}
}
#[test]
fn issuer_and_subject_are_split_correctly() {
let p: Principal = format!("idp:{UUID}").parse().unwrap();
assert_eq!(p.issuer(), Issuer::Idp);
assert_eq!(p.subject(), UUID);
let p: Principal = format!("nostr:{PUBKEY}").parse().unwrap();
assert_eq!(p.issuer(), Issuer::Nostr);
assert_eq!(p.subject(), PUBKEY);
let p: Principal = "apikey:ak_live_01HQ8ZQK".parse().unwrap();
assert_eq!(p.issuer(), Issuer::ApiKey);
assert_eq!(p.subject(), "ak_live_01HQ8ZQK");
}
#[test]
fn deserialization_error_text_names_the_rule_that_was_broken() {
let err = serde_json::from_str::<Principal>("\"ldap:someone\"").unwrap_err();
assert!(err.to_string().contains("unknown principal issuer"), "{err}");
let err = serde_json::from_str::<Principal>("\"nostr:NOTHEX\"").unwrap_err();
assert!(err.to_string().contains("nostr pubkey"), "{err}");
}
#[test]
fn rejects_unknown_issuer_including_wrong_case() {
assert!(matches!(
"ldap:someone".parse::<Principal>(),
Err(PrincipalParseError::UnknownIssuer(i)) if i == "ldap"
));
assert!(matches!(
"IDP:6ba7b810-9dad-11d1-80b4-00c04fd430c8".parse::<Principal>(),
Err(PrincipalParseError::UnknownIssuer(_))
));
}
#[test]
fn rejects_empty_subject_for_every_issuer() {
for issuer in ["idp", "nostr", "apikey"] {
let s = format!("{issuer}:");
assert!(
matches!(
s.parse::<Principal>(),
Err(PrincipalParseError::EmptySubject(_))
),
"{s} should be rejected"
);
}
}
#[test]
fn rejects_missing_separator() {
assert!(matches!(
"idp".parse::<Principal>(),
Err(PrincipalParseError::MissingSeparator(_))
));
assert!(matches!(
UUID.parse::<Principal>(),
Err(PrincipalParseError::MissingSeparator(_))
));
}
#[test]
fn rejects_nostr_pubkey_of_wrong_length() {
let short = &PUBKEY[..63];
let long = format!("{PUBKEY}a");
assert_eq!(short.len(), 63);
assert_eq!(long.len(), 65);
for bad in [short.to_string(), long] {
let s = format!("nostr:{bad}");
match s.parse::<Principal>() {
Err(PrincipalParseError::InvalidNostrPubkey { reason, .. }) => {
assert_eq!(reason, "expected exactly 64 hex characters");
}
other => panic!("{s} should be rejected, got {other:?}"),
}
}
}
#[test]
fn rejects_uppercase_nostr_hex() {
let upper = PUBKEY.to_uppercase();
assert_eq!(upper.len(), 64);
let s = format!("nostr:{upper}");
match s.parse::<Principal>() {
Err(PrincipalParseError::InvalidNostrPubkey { reason, .. }) => {
assert_eq!(reason, "expected lowercase hex only");
}
other => panic!("uppercase hex should be rejected, got {other:?}"),
}
}
#[test]
fn rejects_embedded_second_colon() {
for s in [
format!("idp:{UUID}:extra"),
format!("nostr:{PUBKEY}:extra"),
"apikey:ak:live".to_string(),
] {
assert!(
matches!(
s.parse::<Principal>(),
Err(PrincipalParseError::SubjectContainsSeparator(_))
),
"{s} should be rejected"
);
}
}
#[test]
fn rejects_non_canonical_uuid() {
for bad in [
"not-a-uuid",
"6ba7b8109dad11d180b400c04fd430c8", "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", "6BA7B810-9DAD-11D1-80B4-00C04FD430C8", ] {
let s = format!("idp:{bad}");
assert!(
matches!(
s.parse::<Principal>(),
Err(PrincipalParseError::InvalidUuid(_))
),
"{s} should be rejected"
);
}
}
#[test]
fn rejects_unprintable_api_key_ids() {
for bad in ["ak live", "ak\tlive", "ak\"live", "ak\\live"] {
let s = format!("apikey:{bad}");
assert!(
matches!(
s.parse::<Principal>(),
Err(PrincipalParseError::InvalidApiKeyId(_))
),
"{s:?} should be rejected"
);
}
}
#[test]
fn a_key_principal_is_64_lowercase_hex_and_round_trips() {
let s = format!("key:{PUBKEY}");
let p: Principal = s.parse().unwrap();
assert_eq!(p.issuer(), Issuer::Key);
assert_eq!(p.subject(), PUBKEY);
assert_eq!(p.to_string(), s);
assert_eq!(serde_json::to_string(&p).unwrap(), format!("\"{s}\""));
assert_eq!(serde_json::from_str::<Principal>(&format!("\"{s}\"")).unwrap(), p);
assert_eq!(p.as_legacy_user_id(), s, "keeps its namespace");
assert_ne!(p, Principal::new(Issuer::Nostr, PUBKEY).unwrap(), "one key, two issuers: two principals");
match format!("key:{}", PUBKEY.to_uppercase()).parse::<Principal>() {
Err(PrincipalParseError::InvalidKeyPubkey { reason, .. }) => assert_eq!(reason, "expected lowercase hex only"),
other => panic!("uppercase must be refused: {other:?}"),
}
for bad in [&PUBKEY[..63], &format!("{PUBKEY}0")[..], "", "zz"] {
assert!(format!("key:{bad}").parse::<Principal>().is_err(), "{bad}");
}
assert!(format!("key:{PUBKEY}:x").parse::<Principal>().is_err());
assert!(format!("KEY:{PUBKEY}").parse::<Principal>().is_err());
}
#[test]
fn new_validates_like_from_str() {
assert!(Principal::new(Issuer::Idp, UUID).is_ok());
assert!(Principal::new(Issuer::Idp, "nope").is_err());
assert!(Principal::new(Issuer::Nostr, PUBKEY).is_ok());
assert!(Principal::new(Issuer::Nostr, "").is_err());
}
}