Skip to main content

cortexkit_bus_naming/
token.rs

1use std::error::Error;
2use std::fmt;
3
4/// The identity field being interpolated into a NATS name.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum TokenKind {
7    Account,
8    AgentId,
9    SessionId,
10    RoomId,
11    ModuleId,
12    RosterHostId,
13    CredentialPublic,
14    RootProvider,
15    /// The one-to-four-token `{event}` path of a module event subject.
16    EventName,
17    /// The `v{version}` token of a module event subject.
18    EventVersion,
19}
20
21impl TokenKind {
22    pub const fn label(self) -> &'static str {
23        match self {
24            Self::Account => "acct",
25            Self::AgentId => "agent_id",
26            Self::SessionId => "session_id",
27            Self::RoomId => "room_id",
28            Self::ModuleId => "module_id",
29            Self::RosterHostId => "roster_host_id",
30            Self::CredentialPublic => "credential_public",
31            Self::RootProvider => "root_provider",
32            Self::EventName => "event",
33            Self::EventVersion => "event_version",
34        }
35    }
36}
37
38/// A token that cannot be interpolated without changing or broadening identity.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct NamingError {
41    kind: TokenKind,
42    token: String,
43    reason: &'static str,
44}
45
46impl NamingError {
47    pub fn kind(&self) -> TokenKind {
48        self.kind
49    }
50
51    pub fn token(&self) -> &str {
52        &self.token
53    }
54
55    pub fn reason(&self) -> &'static str {
56        self.reason
57    }
58
59    fn new(kind: TokenKind, token: &str, reason: &'static str) -> Self {
60        Self {
61            kind,
62            token: token.to_owned(),
63            reason,
64        }
65    }
66}
67
68impl fmt::Display for NamingError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        write!(
71            f,
72            "invalid {} token {:?}: {}",
73            self.kind.label(),
74            self.token,
75            self.reason
76        )
77    }
78}
79
80impl Error for NamingError {}
81
82/// Validates the account-only lexicon `[a-z0-9][a-z0-9_]{0,62}`.
83pub fn validate_account_token(token: &str) -> Result<(), NamingError> {
84    validate_no_hyphen_token(
85        TokenKind::Account,
86        token,
87        "expected [a-z0-9][a-z0-9_]{0,62}; hyphens and normalization are forbidden",
88    )
89}
90
91/// Validates an event name with one to four dot-separated subject tokens,
92/// each `[a-z0-9][a-z0-9_]{0,62}`.
93///
94/// Version-shaped name levels (`v` followed by digits) are reserved so a name
95/// level cannot be confused with the subject's final version token.
96fn validate_event_name(token: &str) -> Result<(), NamingError> {
97    if !(1..=4).contains(&token.split('.').count()) {
98        return Err(NamingError::new(
99            TokenKind::EventName,
100            token,
101            "event name must contain one to four dot-separated tokens",
102        ));
103    }
104    for level in token.split('.') {
105        validate_no_hyphen_token(
106            TokenKind::EventName,
107            level,
108            "each event-name level must match [a-z0-9][a-z0-9_]{0,62}; hyphens, wildcards and whitespace are forbidden",
109        )
110        .map_err(|error| NamingError::new(TokenKind::EventName, token, error.reason()))?;
111        if level.strip_prefix('v').is_some_and(|digits| {
112            !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
113        }) {
114            return Err(NamingError::new(
115                TokenKind::EventName,
116                token,
117                "event-name levels must not be version-shaped (v followed by digits)",
118            ));
119        }
120    }
121    Ok(())
122}
123
124/// Parses the version token of an event subject, `v{n}` with `n >= 1`.
125///
126/// The number is plain decimal without leading zeros, so each version has
127/// exactly one spelling (`v1`, never `v01`) and two subjects for one version
128/// cannot exist.
129pub fn validate_event_version(token: &str) -> Result<u32, NamingError> {
130    let refuse = || {
131        NamingError::new(
132            TokenKind::EventVersion,
133            token,
134            "expected v{n} with n a decimal integer of at least 1 and no leading zero",
135        )
136    };
137    let digits = token.strip_prefix('v').ok_or_else(refuse)?;
138    if digits.is_empty()
139        || digits.starts_with('0')
140        || !digits.bytes().all(|byte| byte.is_ascii_digit())
141    {
142        return Err(refuse());
143    }
144    digits.parse::<u32>().map_err(|_| refuse())
145}
146
147/// The one-token lexicon without hyphens shared by accounts and event names.
148fn validate_no_hyphen_token(
149    kind: TokenKind,
150    token: &str,
151    reason: &'static str,
152) -> Result<(), NamingError> {
153    validate_len_and_first(kind, token)?;
154    if token
155        .bytes()
156        .skip(1)
157        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
158    {
159        Ok(())
160    } else {
161        Err(NamingError::new(kind, token, reason))
162    }
163}
164
165/// Validates the shared identity lexicon `[a-z0-9][a-z0-9_-]{0,62}`.
166///
167/// `CredentialPublic` is an inbox-prefix component rather than a registry token;
168/// it accepts ASCII letters because real NATS public nkeys are uppercase.
169/// `Account` and `EventName` use the narrower lexicon without the hyphen, and
170/// `EventVersion` accepts only `v{n}` (see [`validate_event_version`]).
171pub fn validate_token(kind: TokenKind, token: &str) -> Result<(), NamingError> {
172    match kind {
173        TokenKind::Account => return validate_account_token(token),
174        TokenKind::CredentialPublic => return validate_credential_public(token),
175        TokenKind::EventName => return validate_event_name(token),
176        TokenKind::EventVersion => return validate_event_version(token).map(|_| ()),
177        _ => {}
178    }
179
180    validate_len_and_first(kind, token)?;
181    if token.bytes().skip(1).all(|byte| {
182        byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-'
183    }) {
184        Ok(())
185    } else {
186        Err(NamingError::new(
187            kind,
188            token,
189            "expected [a-z0-9][a-z0-9_-]{0,62}; dots, wildcards, whitespace, and normalization are forbidden",
190        ))
191    }
192}
193
194fn validate_len_and_first(kind: TokenKind, token: &str) -> Result<(), NamingError> {
195    if token.is_empty() || token.len() > 63 {
196        return Err(NamingError::new(
197            kind,
198            token,
199            "token must contain between 1 and 63 ASCII bytes",
200        ));
201    }
202    let first = token.as_bytes()[0];
203    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
204        return Err(NamingError::new(
205            kind,
206            token,
207            "token must start with a lowercase ASCII letter or digit",
208        ));
209    }
210    Ok(())
211}
212
213fn validate_credential_public(token: &str) -> Result<(), NamingError> {
214    if token.is_empty() || token.len() > 63 {
215        return Err(NamingError::new(
216            TokenKind::CredentialPublic,
217            token,
218            "inbox component must contain between 1 and 63 ASCII bytes",
219        ));
220    }
221    if token
222        .bytes()
223        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
224    {
225        Ok(())
226    } else {
227        Err(NamingError::new(
228            TokenKind::CredentialPublic,
229            token,
230            "inbox component may contain only ASCII letters, digits, underscore, or hyphen",
231        ))
232    }
233}