Skip to main content

ic_auth_protocol_types/
scope.rs

1//! Scope syntax shared by signed grants and unsigned requests.
2
3use std::{error::Error, fmt, str::FromStr};
4
5const MAX_BYTES: usize = 64;
6
7/// A scope syntax failure; lengths and offsets count UTF-8 bytes.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ScopeLabelError {
10    /// The label contains no bytes.
11    Empty,
12    /// The label exceeds the inclusive byte limit.
13    TooLong {
14        /// Supplied byte length.
15        bytes: usize,
16        /// Inclusive protocol limit.
17        max: usize,
18    },
19    /// A leading, repeated or trailing colon creates an empty segment.
20    EmptySegment,
21    /// A segment does not begin with an ASCII lowercase letter or digit.
22    InvalidSegmentStart {
23        /// Zero-based byte offset.
24        offset: usize,
25    },
26    /// A continuation byte is outside the ASCII scope grammar.
27    InvalidByte {
28        /// Zero-based byte offset.
29        offset: usize,
30    },
31}
32
33impl fmt::Display for ScopeLabelError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Self::Empty => f.write_str("scope is empty"),
37            Self::TooLong { bytes, max } => write!(f, "scope has {bytes} bytes; maximum is {max}"),
38            Self::EmptySegment => f.write_str("scope contains an empty segment"),
39            Self::InvalidSegmentStart { offset } => {
40                write!(f, "invalid scope segment start at byte {offset}")
41            }
42            Self::InvalidByte { offset } => write!(f, "invalid scope byte at offset {offset}"),
43        }
44    }
45}
46
47impl Error for ScopeLabelError {}
48
49/// An immutable, unnormalized 1–64-byte scope label.
50///
51/// Colon-separated segments start with `[a-z0-9]` and continue with
52/// `[a-z0-9_-]`. A valid label says nothing about which caller may use it.
53///
54/// ```compile_fail
55/// use ic_auth_protocol_types::ScopeLabel;
56/// let unchecked = ScopeLabel(String::from("Invalid"));
57/// ```
58#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
59pub struct ScopeLabel(String);
60
61impl ScopeLabel {
62    /// Check grammar without allocating or normalizing input.
63    ///
64    /// Length errors precede grammar errors; grammar reports the first invalid
65    /// segment or byte in input order.
66    pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
67        if text.is_empty() {
68            return Err(ScopeLabelError::Empty);
69        }
70        if text.len() > MAX_BYTES {
71            return Err(ScopeLabelError::TooLong {
72                bytes: text.len(),
73                max: MAX_BYTES,
74            });
75        }
76        let mut offset = 0;
77        for segment in text.split(':') {
78            let mut bytes = segment.bytes();
79            let first = bytes.next().ok_or(ScopeLabelError::EmptySegment)?;
80            if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
81                return Err(ScopeLabelError::InvalidSegmentStart { offset });
82            }
83            for (index, byte) in bytes.enumerate() {
84                if !byte.is_ascii_lowercase()
85                    && !byte.is_ascii_digit()
86                    && !matches!(byte, b'_' | b'-')
87                {
88                    return Err(ScopeLabelError::InvalidByte {
89                        offset: offset + index + 1,
90                    });
91                }
92            }
93            offset += segment.len() + 1;
94        }
95        Ok(())
96    }
97
98    /// Borrow the admitted spelling.
99    #[must_use]
100    pub fn as_str(&self) -> &str {
101        &self.0
102    }
103
104    /// Recover the original owned text without copying.
105    #[must_use]
106    pub fn into_string(self) -> String {
107        self.0
108    }
109}
110
111impl TryFrom<String> for ScopeLabel {
112    type Error = ScopeLabelError;
113
114    fn try_from(text: String) -> Result<Self, Self::Error> {
115        Self::validate(&text)?;
116        Ok(Self(text))
117    }
118}
119
120impl FromStr for ScopeLabel {
121    type Err = ScopeLabelError;
122
123    fn from_str(text: &str) -> Result<Self, Self::Err> {
124        Self::validate(text)?;
125        Ok(Self(text.to_owned()))
126    }
127}
128
129impl AsRef<str> for ScopeLabel {
130    fn as_ref(&self) -> &str {
131        self.as_str()
132    }
133}
134
135impl fmt::Display for ScopeLabel {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.write_str(self.as_str())
138    }
139}