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)]
24#[cfg_attr(
25    feature = "stable-records",
26    derive(serde::Serialize, serde::Deserialize)
27)]
28#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
29pub struct AuthRole(String);
30
31impl AuthRole {
32    /// Check role syntax without allocating.
33    pub fn validate(text: &str) -> Result<(), RoleError> {
34        if !(1..=64).contains(&text.len())
35            || !text
36                .bytes()
37                .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b':' | b'-'))
38        {
39            return Err(RoleError);
40        }
41        Ok(())
42    }
43
44    /// Borrow the original role spelling.
45    #[must_use]
46    pub fn as_str(&self) -> &str {
47        &self.0
48    }
49}
50
51impl FromStr for AuthRole {
52    type Err = RoleError;
53    fn from_str(text: &str) -> Result<Self, Self::Err> {
54        Self::validate(text)?;
55        Ok(Self(text.to_owned()))
56    }
57}
58
59impl TryFrom<String> for AuthRole {
60    type Error = RoleError;
61    fn try_from(text: String) -> Result<Self, Self::Error> {
62        Self::validate(&text)?;
63        Ok(Self(text))
64    }
65}