Skip to main content

stateknot_core/
scope.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded OAuth-compatible authorization scopes and deterministic scope sets.
5
6use std::{
7    borrow::Borrow,
8    collections::{BTreeSet, btree_set},
9    fmt,
10    str::FromStr,
11};
12
13use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
14use serde::{
15    Deserialize, Deserializer, Serialize, Serializer,
16    de::{self, SeqAccess},
17};
18use thiserror::Error;
19
20const SCOPE_PATTERN: &str = r"^[\u0021\u0023-\u005B\u005D-\u007E]{1,256}$";
21
22/// A bounded, case-sensitive OAuth 2.0 scope token.
23///
24/// The grammar is RFC 6749 `scope-token`: visible ASCII other than space,
25/// double quote, and backslash. `StateKnot` additionally limits one token to
26/// 256 bytes so remote authorization data cannot create unbounded domain
27/// values.
28#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
29pub struct Scope(Box<str>);
30
31impl Scope {
32    /// Maximum encoded length in bytes.
33    pub const MAX_LEN: usize = 256;
34
35    /// Validates and constructs a scope without copying a `String`.
36    ///
37    /// # Errors
38    ///
39    /// Returns [`ScopeError`] when `value` is empty, too long, or does not
40    /// conform to the RFC 6749 `scope-token` grammar.
41    pub fn new(value: impl Into<String>) -> Result<Self, ScopeError> {
42        let value = value.into();
43        validate_scope(&value)?;
44        Ok(Self(value.into_boxed_str()))
45    }
46
47    /// Returns the exact, case-sensitive scope token.
48    #[must_use]
49    pub fn as_str(&self) -> &str {
50        &self.0
51    }
52}
53
54impl AsRef<str> for Scope {
55    fn as_ref(&self) -> &str {
56        self.as_str()
57    }
58}
59
60impl Borrow<str> for Scope {
61    fn borrow(&self) -> &str {
62        self.as_str()
63    }
64}
65
66impl fmt::Debug for Scope {
67    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68        formatter
69            .debug_tuple("Scope")
70            .field(&self.as_str())
71            .finish()
72    }
73}
74
75impl fmt::Display for Scope {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        formatter.write_str(self.as_str())
78    }
79}
80
81impl FromStr for Scope {
82    type Err = ScopeError;
83
84    fn from_str(value: &str) -> Result<Self, Self::Err> {
85        Self::new(value)
86    }
87}
88
89impl TryFrom<String> for Scope {
90    type Error = ScopeError;
91
92    fn try_from(value: String) -> Result<Self, Self::Error> {
93        Self::new(value)
94    }
95}
96
97impl TryFrom<&str> for Scope {
98    type Error = ScopeError;
99
100    fn try_from(value: &str) -> Result<Self, Self::Error> {
101        Self::new(value)
102    }
103}
104
105impl From<Scope> for String {
106    fn from(value: Scope) -> Self {
107        value.0.into()
108    }
109}
110
111impl Serialize for Scope {
112    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
113    where
114        S: Serializer,
115    {
116        serializer.serialize_str(self.as_str())
117    }
118}
119
120impl<'de> Deserialize<'de> for Scope {
121    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
122    where
123        D: Deserializer<'de>,
124    {
125        deserializer.deserialize_string(ScopeVisitor)
126    }
127}
128
129struct ScopeVisitor;
130
131impl de::Visitor<'_> for ScopeVisitor {
132    type Value = Scope;
133
134    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135        formatter.write_str("a bounded RFC 6749 scope token")
136    }
137
138    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
139    where
140        E: de::Error,
141    {
142        Scope::try_from(value).map_err(E::custom)
143    }
144
145    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
146    where
147        E: de::Error,
148    {
149        Scope::try_from(value).map_err(E::custom)
150    }
151}
152
153impl JsonSchema for Scope {
154    fn schema_name() -> std::borrow::Cow<'static, str> {
155        "Scope".into()
156    }
157
158    fn schema_id() -> std::borrow::Cow<'static, str> {
159        concat!(module_path!(), "::Scope").into()
160    }
161
162    fn json_schema(_: &mut SchemaGenerator) -> Schema {
163        json_schema!({
164            "type": "string",
165            "minLength": 1,
166            "maxLength": 256,
167            "pattern": SCOPE_PATTERN
168        })
169    }
170
171    fn inline_schema() -> bool {
172        true
173    }
174}
175
176/// Validation failure for a [`Scope`].
177#[derive(Clone, Debug, Eq, Error, PartialEq)]
178#[non_exhaustive]
179pub enum ScopeError {
180    /// The scope contained no bytes.
181    #[error("scope must not be empty")]
182    Empty,
183
184    /// The scope exceeded [`Scope::MAX_LEN`].
185    #[error("scope is {actual} bytes; maximum is {max}")]
186    TooLong {
187        /// Maximum accepted byte length.
188        max: usize,
189        /// Observed byte length.
190        actual: usize,
191    },
192
193    /// A byte did not belong to the RFC 6749 `scope-token` grammar.
194    #[error("scope contains an invalid byte at offset {index}")]
195    InvalidByte {
196        /// Zero-based byte offset of the first invalid byte.
197        index: usize,
198    },
199}
200
201fn validate_scope(value: &str) -> Result<(), ScopeError> {
202    if value.is_empty() {
203        return Err(ScopeError::Empty);
204    }
205    if value.len() > Scope::MAX_LEN {
206        return Err(ScopeError::TooLong {
207            max: Scope::MAX_LEN,
208            actual: value.len(),
209        });
210    }
211
212    if let Some((index, _)) = value
213        .bytes()
214        .enumerate()
215        .find(|(_, byte)| !matches!(byte, 0x21 | 0x23..=0x5b | 0x5d..=0x7e))
216    {
217        return Err(ScopeError::InvalidByte { index });
218    }
219
220    Ok(())
221}
222
223/// A bounded set of unique scopes with deterministic canonical ordering.
224///
225/// The JSON wire form is an array sorted by exact ASCII byte order. Duplicate
226/// input is rejected rather than silently deduplicated. These properties make
227/// authorization decisions, audit records, and canonical hashes reproducible.
228#[derive(Clone, Debug, Default, Eq, PartialEq)]
229pub struct ScopeSet(BTreeSet<Scope>);
230
231impl ScopeSet {
232    /// Maximum number of distinct scopes in one set.
233    pub const MAX_LEN: usize = 128;
234
235    /// Returns an empty scope set.
236    #[must_use]
237    pub const fn empty() -> Self {
238        Self(BTreeSet::new())
239    }
240
241    /// Constructs a set from already validated scopes.
242    ///
243    /// # Errors
244    ///
245    /// Returns [`ScopeSetError`] on the first duplicate or when more than
246    /// [`ScopeSet::MAX_LEN`] distinct entries are observed. Iteration stops at
247    /// that point, so an unbounded iterator cannot cause unbounded work.
248    pub fn try_new<I>(scopes: I) -> Result<Self, ScopeSetError>
249    where
250        I: IntoIterator<Item = Scope>,
251    {
252        let mut set = BTreeSet::new();
253        for scope in scopes {
254            if set.contains(&scope) {
255                return Err(ScopeSetError::Duplicate { scope });
256            }
257            if set.len() == Self::MAX_LEN {
258                return Err(ScopeSetError::TooMany {
259                    max: Self::MAX_LEN,
260                    observed: Self::MAX_LEN + 1,
261                });
262            }
263            set.insert(scope);
264        }
265        Ok(Self(set))
266    }
267
268    /// Returns the number of scopes.
269    #[must_use]
270    pub fn len(&self) -> usize {
271        self.0.len()
272    }
273
274    /// Returns `true` when no authority is represented.
275    #[must_use]
276    pub fn is_empty(&self) -> bool {
277        self.0.is_empty()
278    }
279
280    /// Returns `true` when the exact, case-sensitive scope is present.
281    #[must_use]
282    pub fn contains(&self, scope: &Scope) -> bool {
283        self.0.contains(scope)
284    }
285
286    /// Returns scopes in deterministic ASCII byte order.
287    pub fn iter(&self) -> btree_set::Iter<'_, Scope> {
288        self.0.iter()
289    }
290
291    /// Returns `true` when every scope in this set is present in `other`.
292    #[must_use]
293    pub fn is_subset(&self, other: &Self) -> bool {
294        self.0.is_subset(&other.0)
295    }
296
297    /// Returns the scopes granted by both sets.
298    ///
299    /// Intersection can only narrow authority and cannot exceed either input's
300    /// validated size bound.
301    #[must_use]
302    pub fn intersection(&self, other: &Self) -> Self {
303        Self(self.0.intersection(&other.0).cloned().collect())
304    }
305}
306
307impl<'a> IntoIterator for &'a ScopeSet {
308    type Item = &'a Scope;
309    type IntoIter = btree_set::Iter<'a, Scope>;
310
311    fn into_iter(self) -> Self::IntoIter {
312        self.iter()
313    }
314}
315
316impl TryFrom<Vec<Scope>> for ScopeSet {
317    type Error = ScopeSetError;
318
319    fn try_from(scopes: Vec<Scope>) -> Result<Self, Self::Error> {
320        Self::try_new(scopes)
321    }
322}
323
324impl Serialize for ScopeSet {
325    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
326    where
327        S: Serializer,
328    {
329        serializer.collect_seq(self.iter())
330    }
331}
332
333impl<'de> Deserialize<'de> for ScopeSet {
334    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
335    where
336        D: Deserializer<'de>,
337    {
338        deserializer.deserialize_seq(ScopeSetVisitor)
339    }
340}
341
342struct ScopeSetVisitor;
343
344impl<'de> de::Visitor<'de> for ScopeSetVisitor {
345    type Value = ScopeSet;
346
347    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
348        write!(
349            formatter,
350            "an array containing at most {} unique scopes",
351            ScopeSet::MAX_LEN
352        )
353    }
354
355    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
356    where
357        A: SeqAccess<'de>,
358    {
359        let mut scopes = BTreeSet::new();
360        while let Some(scope) = sequence.next_element::<Scope>()? {
361            if scopes.contains(&scope) {
362                return Err(de::Error::custom(ScopeSetError::Duplicate { scope }));
363            }
364            if scopes.len() == ScopeSet::MAX_LEN {
365                return Err(de::Error::custom(ScopeSetError::TooMany {
366                    max: ScopeSet::MAX_LEN,
367                    observed: ScopeSet::MAX_LEN + 1,
368                }));
369            }
370            scopes.insert(scope);
371        }
372        Ok(ScopeSet(scopes))
373    }
374}
375
376impl JsonSchema for ScopeSet {
377    fn schema_name() -> std::borrow::Cow<'static, str> {
378        "ScopeSet".into()
379    }
380
381    fn schema_id() -> std::borrow::Cow<'static, str> {
382        concat!(module_path!(), "::ScopeSet").into()
383    }
384
385    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
386        json_schema!({
387            "type": "array",
388            "items": generator.subschema_for::<Scope>(),
389            "maxItems": 128,
390            "uniqueItems": true
391        })
392    }
393}
394
395/// Construction or deserialization failure for a [`ScopeSet`].
396#[derive(Clone, Debug, Eq, Error, PartialEq)]
397#[non_exhaustive]
398pub enum ScopeSetError {
399    /// The input repeated a scope.
400    #[error("scope set contains duplicate scope {scope:?}")]
401    Duplicate {
402        /// Repeated scope.
403        scope: Scope,
404    },
405
406    /// The input exceeded [`ScopeSet::MAX_LEN`].
407    #[error("scope set contains at least {observed} distinct scopes; maximum is {max}")]
408    TooMany {
409        /// Maximum accepted number of distinct scopes.
410        max: usize,
411        /// Minimum number of distinct scopes observed before validation stopped.
412        observed: usize,
413    },
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use proptest::prelude::*;
420    use serde_json::{Value, from_value, json, to_value};
421
422    fn scope_set_from_bits(bits: u64) -> ScopeSet {
423        ScopeSet::try_new(
424            (0..u64::BITS)
425                .filter(|index| bits & (1_u64 << index) != 0)
426                .map(|index| format!("scope:{index:02}").parse::<Scope>().unwrap()),
427        )
428        .unwrap()
429    }
430
431    #[test]
432    fn scopes_accept_exactly_the_bounded_rfc_6749_grammar() {
433        let all_allowed = (0x21_u8..=0x7e)
434            .filter(|byte| !matches!(byte, b'"' | b'\\'))
435            .map(char::from)
436            .collect::<String>();
437        let scope = all_allowed.parse::<Scope>().unwrap();
438        assert_eq!(scope.as_str(), all_allowed);
439
440        for value in [
441            "read",
442            "ops:restart",
443            "https://api.example.com/auth/data.read",
444            "Read",
445        ] {
446            let scope = value.parse::<Scope>().unwrap();
447            assert_eq!(scope.as_str(), value);
448            assert_eq!(to_value(&scope).unwrap(), Value::from(value));
449        }
450
451        let maximum = "a".repeat(Scope::MAX_LEN);
452        assert_eq!(maximum.parse::<Scope>().unwrap().as_str(), maximum);
453    }
454
455    #[test]
456    fn scopes_reject_out_of_contract_input() {
457        assert_eq!("".parse::<Scope>(), Err(ScopeError::Empty));
458        assert_eq!(
459            "a".repeat(Scope::MAX_LEN + 1).parse::<Scope>(),
460            Err(ScopeError::TooLong {
461                max: Scope::MAX_LEN,
462                actual: Scope::MAX_LEN + 1,
463            })
464        );
465
466        for (value, index) in [
467            ("data read", 4),
468            ("data\"read", 4),
469            ("data\\read", 4),
470            ("data\nread", 4),
471            ("读取", 0),
472        ] {
473            assert_eq!(
474                value.parse::<Scope>(),
475                Err(ScopeError::InvalidByte { index }),
476                "accepted {value:?}"
477            );
478        }
479
480        for byte in 0_u8..=0x7f {
481            if matches!(byte, 0x21 | 0x23..=0x5b | 0x5d..=0x7e) {
482                continue;
483            }
484            let value = String::from_utf8(vec![byte]).unwrap();
485            assert_eq!(
486                value.parse::<Scope>(),
487                Err(ScopeError::InvalidByte { index: 0 }),
488                "accepted ASCII byte 0x{byte:02x}"
489            );
490        }
491    }
492
493    #[test]
494    fn scope_serde_and_schema_enforce_the_wire_contract() {
495        let scope = "ops:restart".parse::<Scope>().unwrap();
496        assert_eq!(from_value::<Scope>(json!(scope.as_str())).unwrap(), scope);
497        assert!(from_value::<Scope>(json!(42)).is_err());
498        assert!(from_value::<Scope>(Value::Null).is_err());
499
500        let schema = to_value(schemars::schema_for!(Scope)).unwrap();
501        assert_eq!(schema["type"], "string");
502        assert_eq!(schema["minLength"], 1);
503        assert_eq!(schema["maxLength"], Scope::MAX_LEN);
504        assert_eq!(schema["pattern"], SCOPE_PATTERN);
505    }
506
507    #[test]
508    fn scope_sets_reject_duplicates_and_stop_at_the_limit() {
509        let read = "read".parse::<Scope>().unwrap();
510        assert_eq!(
511            ScopeSet::try_new([read.clone(), read.clone()]),
512            Err(ScopeSetError::Duplicate { scope: read })
513        );
514
515        let maximum = ScopeSet::try_new(
516            (0..ScopeSet::MAX_LEN).map(|index| format!("scope:{index}").parse().unwrap()),
517        )
518        .unwrap();
519        assert_eq!(maximum.len(), ScopeSet::MAX_LEN);
520
521        let oversized =
522            (0..=ScopeSet::MAX_LEN).map(|index| format!("scope:{index}").parse().unwrap());
523        assert_eq!(
524            ScopeSet::try_new(oversized),
525            Err(ScopeSetError::TooMany {
526                max: ScopeSet::MAX_LEN,
527                observed: ScopeSet::MAX_LEN + 1,
528            })
529        );
530
531        let oversized_wire = Value::Array(
532            (0..=ScopeSet::MAX_LEN)
533                .map(|index| Value::from(format!("scope:{index}")))
534                .collect(),
535        );
536        assert!(from_value::<ScopeSet>(oversized_wire).is_err());
537    }
538
539    #[test]
540    fn scope_sets_have_a_sorted_strict_wire_form() {
541        let set = ScopeSet::try_new(
542            ["write", "admin", "read"].map(|value| value.parse::<Scope>().unwrap()),
543        )
544        .unwrap();
545
546        assert_eq!(to_value(&set).unwrap(), json!(["admin", "read", "write"]));
547        assert_eq!(
548            from_value::<ScopeSet>(json!(["write", "admin", "read"])).unwrap(),
549            set
550        );
551        assert!(from_value::<ScopeSet>(json!(["read", "read"])).is_err());
552        assert!(from_value::<ScopeSet>(json!("read write")).is_err());
553        assert!(from_value::<ScopeSet>(Value::Null).is_err());
554
555        let schema = to_value(schemars::schema_for!(ScopeSet)).unwrap();
556        assert_eq!(schema["type"], "array");
557        assert_eq!(schema["maxItems"], ScopeSet::MAX_LEN);
558        assert_eq!(schema["uniqueItems"], true);
559        assert_eq!(schema["items"]["type"], "string");
560        assert_eq!(schema["items"]["pattern"], SCOPE_PATTERN);
561    }
562
563    proptest! {
564        #[test]
565        fn intersection_is_commutative_and_never_widens(left in any::<u64>(), right in any::<u64>()) {
566            let left = scope_set_from_bits(left);
567            let right = scope_set_from_bits(right);
568            let intersection = left.intersection(&right);
569
570            prop_assert!(intersection.is_subset(&left));
571            prop_assert!(intersection.is_subset(&right));
572            prop_assert_eq!(&intersection, &right.intersection(&left));
573            prop_assert_eq!(&left.intersection(&left), &left);
574        }
575    }
576}