Skip to main content

ic_auth_protocol_types/
role.rs

1//! Role labels have their own grammar, distinct from segmented scopes.
2
3use std::{error::Error, fmt, str::FromStr};
4
5/// A role is empty, over 64 bytes or contains a byte outside `[a-z0-9_:-]`.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub struct RoleError;
8
9impl fmt::Display for RoleError {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        f.write_str(
12            "role must contain 1..=64 bytes using only a-z, 0-9, underscore, colon or hyphen",
13        )
14    }
15}
16
17impl Error for RoleError {}
18
19/// Exact ASCII role spelling. This names a role but grants no permissions.
20///
21/// Unlike scopes, roles have no segment-start rules; punctuation-only labels
22/// remain valid under the signed protocol. No normalization is performed.
23#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub struct AuthRole(String);
25
26impl AuthRole {
27    /// Check role syntax without allocating.
28    pub fn validate(text: &str) -> Result<(), RoleError> {
29        if !(1..=64).contains(&text.len())
30            || !text
31                .bytes()
32                .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b':' | b'-'))
33        {
34            return Err(RoleError);
35        }
36        Ok(())
37    }
38
39    /// Borrow the original role spelling.
40    #[must_use]
41    pub fn as_str(&self) -> &str {
42        &self.0
43    }
44}
45
46impl FromStr for AuthRole {
47    type Err = RoleError;
48    fn from_str(text: &str) -> Result<Self, Self::Err> {
49        Self::validate(text)?;
50        Ok(Self(text.to_owned()))
51    }
52}
53
54impl TryFrom<String> for AuthRole {
55    type Error = RoleError;
56    fn try_from(text: String) -> Result<Self, Self::Error> {
57        Self::validate(&text)?;
58        Ok(Self(text))
59    }
60}