Skip to main content

ic_auth_protocol_types/
scope.rs

1//! Canonical application scope labels, independent of authentication or authority.
2use serde::{Deserialize, Deserializer, Serialize, de};
3use std::{fmt, str::FromStr};
4use thiserror::Error;
5
6/// A scope label's grammar failure. Offsets and lengths count UTF-8 bytes.
7#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
8pub enum ScopeLabelError {
9    #[error("scope is empty")]
10    Empty,
11    #[error("scope has {bytes} bytes; maximum is {max}")]
12    TooLong { bytes: usize, max: usize },
13    #[error("scope contains an empty segment")]
14    EmptySegment,
15    #[error("invalid scope segment start at byte {offset}")]
16    InvalidSegmentStart { offset: usize },
17    #[error("invalid scope byte at offset {offset}")]
18    InvalidByte { offset: usize },
19}
20
21/// Immutable 1..=64-byte scope label. Shape grants no authority.
22/// Colon-separated segments start with a lowercase ASCII letter or digit;
23/// subsequent bytes may also be underscore or hyphen. No normalization occurs.
24/// ```compile_fail
25/// use ic_auth_protocol_types::ScopeLabel;
26/// fn change(scope: &mut ScopeLabel) { scope.as_str().clear(); }
27/// ```
28#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
29#[serde(transparent)]
30pub struct ScopeLabel(String);
31
32impl ScopeLabel {
33    pub fn as_str(&self) -> &str {
34        &self.0
35    }
36    pub fn into_string(self) -> String {
37        self.0
38    }
39    /// Admit an owned sequence without sorting or imposing cardinality policy.
40    /// Callers admit their count bound first; the first grammar failure wins.
41    pub fn from_strings(values: Vec<String>) -> Result<Vec<Self>, ScopeLabelError> {
42        for value in &values {
43            Self::validate(value)?;
44        }
45        Ok(values.into_iter().map(Self).collect())
46    }
47    /// Allocation-free shape check, also usable by const and raw-proof callers.
48    pub const fn validate(scope: &str) -> Result<(), ScopeLabelError> {
49        let bytes = scope.as_bytes();
50        if bytes.is_empty() {
51            return Err(ScopeLabelError::Empty);
52        }
53        if bytes.len() > crate::limits::MAX_LABEL_BYTES {
54            return Err(ScopeLabelError::TooLong {
55                bytes: bytes.len(),
56                max: crate::limits::MAX_LABEL_BYTES,
57            });
58        }
59        let mut segment_start = true;
60        let mut offset = 0;
61        while offset < bytes.len() {
62            let byte = bytes[offset];
63            if byte == b':' {
64                if segment_start {
65                    return Err(ScopeLabelError::EmptySegment);
66                }
67                segment_start = true;
68            } else if segment_start {
69                if !byte.is_ascii_lowercase() && !byte.is_ascii_digit() {
70                    return Err(ScopeLabelError::InvalidSegmentStart { offset });
71                }
72                segment_start = false;
73            } else if !byte.is_ascii_lowercase()
74                && !byte.is_ascii_digit()
75                && byte != b'_'
76                && byte != b'-'
77            {
78                return Err(ScopeLabelError::InvalidByte { offset });
79            }
80            offset += 1;
81        }
82        if segment_start {
83            return Err(ScopeLabelError::EmptySegment);
84        }
85        Ok(())
86    }
87}
88impl FromStr for ScopeLabel {
89    type Err = ScopeLabelError;
90    fn from_str(value: &str) -> Result<Self, Self::Err> {
91        Self::validate(value)?;
92        Ok(Self(value.to_owned()))
93    }
94}
95impl TryFrom<String> for ScopeLabel {
96    type Error = ScopeLabelError;
97    fn try_from(value: String) -> Result<Self, Self::Error> {
98        Self::validate(&value)?;
99        Ok(Self(value))
100    }
101}
102impl AsRef<str> for ScopeLabel {
103    fn as_ref(&self) -> &str {
104        self.as_str()
105    }
106}
107impl fmt::Display for ScopeLabel {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str(self.as_str())
110    }
111}
112impl<'de> Deserialize<'de> for ScopeLabel {
113    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
114        Self::try_from(String::deserialize(deserializer)?).map_err(de::Error::custom)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn owned_scope_admission_preserves_bytes_allocation_and_exact_grammar() {
124        for text in ["read", "fleet:read_all-1", "0:1", "", "a::b", "Read", "é"] {
125            let mut supplied = String::with_capacity(128);
126            supplied.push_str(text);
127            let original = supplied.as_ptr();
128            let owned = ScopeLabel::try_from(supplied);
129            assert_eq!(owned, text.parse());
130            if let Ok(label) = owned {
131                assert_eq!(label.as_str(), text);
132                let recovered = label.into_string();
133                assert_eq!(recovered.as_ptr(), original);
134                assert_eq!(recovered, text);
135            }
136        }
137        assert!(ScopeLabel::try_from("a".repeat(64)).is_ok());
138        assert_eq!(
139            ScopeLabel::try_from("a".repeat(65)),
140            Err(ScopeLabelError::TooLong { bytes: 65, max: 64 })
141        );
142    }
143}