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)]
59#[cfg_attr(
60    feature = "stable-records",
61    derive(serde::Serialize, serde::Deserialize)
62)]
63#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
64pub struct ScopeLabel(String);
65
66impl ScopeLabel {
67    /// Check grammar without allocating or normalizing input.
68    ///
69    /// Length errors precede grammar errors; grammar reports the first invalid
70    /// segment or byte in input order.
71    pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
72        if text.is_empty() {
73            return Err(ScopeLabelError::Empty);
74        }
75        if text.len() > MAX_BYTES {
76            return Err(ScopeLabelError::TooLong {
77                bytes: text.len(),
78                max: MAX_BYTES,
79            });
80        }
81        let mut offset = 0;
82        for segment in text.split(':') {
83            let mut bytes = segment.bytes();
84            let first = bytes.next().ok_or(ScopeLabelError::EmptySegment)?;
85            if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
86                return Err(ScopeLabelError::InvalidSegmentStart { offset });
87            }
88            for (index, byte) in bytes.enumerate() {
89                if !byte.is_ascii_lowercase()
90                    && !byte.is_ascii_digit()
91                    && !matches!(byte, b'_' | b'-')
92                {
93                    return Err(ScopeLabelError::InvalidByte {
94                        offset: offset + index + 1,
95                    });
96                }
97            }
98            offset += segment.len() + 1;
99        }
100        Ok(())
101    }
102
103    /// Borrow the admitted spelling.
104    #[must_use]
105    pub fn as_str(&self) -> &str {
106        &self.0
107    }
108
109    /// Recover the original owned text without copying.
110    #[must_use]
111    pub fn into_string(self) -> String {
112        self.0
113    }
114}
115
116impl TryFrom<String> for ScopeLabel {
117    type Error = ScopeLabelError;
118
119    fn try_from(text: String) -> Result<Self, Self::Error> {
120        Self::validate(&text)?;
121        Ok(Self(text))
122    }
123}
124
125impl FromStr for ScopeLabel {
126    type Err = ScopeLabelError;
127
128    fn from_str(text: &str) -> Result<Self, Self::Err> {
129        Self::validate(text)?;
130        Ok(Self(text.to_owned()))
131    }
132}
133
134impl AsRef<str> for ScopeLabel {
135    fn as_ref(&self) -> &str {
136        self.as_str()
137    }
138}
139
140impl fmt::Display for ScopeLabel {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str(self.as_str())
143    }
144}