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 at_segment_start = true;
90        for (offset, byte) in text.bytes().enumerate() {
91            match byte {
92                b'a'..=b'z' | b'0'..=b'9' => at_segment_start = false,
93                b':' if at_segment_start => return Err(ScopeLabelError::EmptySegment),
94                b':' => at_segment_start = true,
95                _ if at_segment_start => {
96                    return Err(ScopeLabelError::InvalidSegmentStart { offset });
97                }
98                b'_' | b'-' => {}
99                _ => return Err(ScopeLabelError::InvalidByte { offset }),
100            }
101        }
102        if at_segment_start {
103            return Err(ScopeLabelError::EmptySegment);
104        }
105        Ok(())
106    }
107
108    /// Borrow the admitted spelling.
109    #[must_use]
110    pub fn as_str(&self) -> &str {
111        &self.0
112    }
113
114    /// Recover the original owned text without copying.
115    #[must_use]
116    pub fn into_string(self) -> String {
117        self.0
118    }
119}
120
121impl TryFrom<String> for ScopeLabel {
122    type Error = ScopeLabelError;
123
124    fn try_from(text: String) -> Result<Self, Self::Error> {
125        Self::validate(&text)?;
126        Ok(Self(text))
127    }
128}
129
130impl FromStr for ScopeLabel {
131    type Err = ScopeLabelError;
132
133    fn from_str(text: &str) -> Result<Self, Self::Err> {
134        Self::validate(text)?;
135        Ok(Self(text.to_owned()))
136    }
137}
138
139impl AsRef<str> for ScopeLabel {
140    fn as_ref(&self) -> &str {
141        self.as_str()
142    }
143}
144
145impl fmt::Display for ScopeLabel {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.write_str(self.as_str())
148    }
149}