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