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