Skip to main content

hyprstream_rpc/auth/
scope.rs

1//! Structured scope for fine-grained authorization.
2//!
3//! Format: action:resource:identifier
4//! The identifier may contain one `:<ref>` suffix for model resources; the
5//! parser preserves the full identifier so `model:<name>:<ref>` stays exact.
6//! Examples:
7//!   infer:model:qwen-7b     - Specific model inference
8//!   subscribe:stream:abc    - Specific stream subscription
9//!   read:model:*            - Read any model (explicit wildcard)
10//!   manage:*:*              - Manage all resources
11
12use crate::capnp::{FromCapnp, ToCapnp};
13use crate::common_capnp;
14use anyhow::{anyhow, Result};
15use serde::{Deserialize, Serialize};
16use std::fmt;
17
18/// Structured scope for fine-grained authorization.
19///
20/// Format: action:resource:identifier
21/// A model identifier may carry one ref suffix (`<name>:<ref>`). The first
22/// two separators are structural; the complete remainder is the identifier.
23/// Examples:
24///   infer:model:qwen-7b     - Specific model inference
25///   subscribe:stream:abc    - Specific stream subscription
26///   read:model:*            - Read any model (explicit wildcard)
27///   manage:*:*              - Manage all resources
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Scope {
30    pub action: String,
31    pub resource: String,
32    pub identifier: String,
33}
34
35impl ToCapnp for Scope {
36    type Builder<'a> = common_capnp::scope::Builder<'a>;
37
38    fn write_to(&self, builder: &mut Self::Builder<'_>) {
39        builder.set_action(&self.action);
40        builder.set_resource(&self.resource);
41        builder.set_identifier(&self.identifier);
42    }
43}
44
45impl FromCapnp for Scope {
46    type Reader<'a> = common_capnp::scope::Reader<'a>;
47
48    fn read_from(reader: Self::Reader<'_>) -> Result<Self> {
49        Ok(Self {
50            action: reader.get_action()?.to_str()?.to_owned(),
51            resource: reader.get_resource()?.to_str()?.to_owned(),
52            identifier: reader.get_identifier()?.to_str()?.to_owned(),
53        })
54    }
55}
56
57impl fmt::Display for Scope {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "{}:{}:{}", self.action, self.resource, self.identifier)
60    }
61}
62
63impl Scope {
64    /// Create a new scope.
65    pub fn new(action: String, resource: String, identifier: String) -> Self {
66        Self {
67            action,
68            resource,
69            identifier,
70        }
71    }
72
73    /// Parse the canonical `action:resource:identifier` form.
74    ///
75    /// The first two separators delimit action and resource type. A model
76    /// identifier may contain exactly one additional separator to encode its
77    /// ref, as in `infer:model:qwen2.5-0.5b-instruct:main`. No components are
78    /// discarded, and other resource identifiers cannot contain separators.
79    pub fn parse(s: &str) -> Result<Self> {
80        let (action, tail) = s
81            .split_once(':')
82            .ok_or_else(|| anyhow!("Invalid scope format: {}", s))?;
83        let (resource, identifier) = tail
84            .split_once(':')
85            .ok_or_else(|| anyhow!("Invalid scope format: {}", s))?;
86        if action.is_empty() || resource.is_empty() || identifier.is_empty() {
87            return Err(anyhow!("Invalid scope format: {}", s));
88        }
89        if identifier.contains(':') {
90            let (model, reference) = identifier
91                .split_once(':')
92                .ok_or_else(|| anyhow!("Invalid scope format: {}", s))?;
93            if resource != "model"
94                || model.is_empty()
95                || reference.is_empty()
96                || reference.contains(':')
97            {
98                return Err(anyhow!("Invalid scope format: {}", s));
99            }
100        }
101        Ok(Self::new(
102            action.to_owned(),
103            resource.to_owned(),
104            identifier.to_owned(),
105        ))
106    }
107
108    /// Return the exact Policy resource represented by this scope.
109    pub fn policy_resource(&self) -> String {
110        format!("{}:{}", self.resource, self.identifier)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn test_scope_parse() -> Result<()> {
120        let scope = Scope::parse("infer:model:qwen-7b")?;
121        assert_eq!(scope.action, "infer");
122        assert_eq!(scope.resource, "model");
123        assert_eq!(scope.identifier, "qwen-7b");
124        Ok(())
125    }
126
127    #[test]
128    fn model_ref_scope_preserves_the_entire_dispatch_resource() -> Result<()> {
129        const MODEL_REF: &str = "qwen2.5-0.5b-instruct:main";
130        let scope = Scope::parse("infer:model:qwen2.5-0.5b-instruct:main")?;
131        assert_eq!(scope.action, "infer");
132        assert_eq!(scope.resource, "model");
133        assert_eq!(scope.identifier, MODEL_REF);
134        assert_eq!(scope.to_string(), "infer:model:qwen2.5-0.5b-instruct:main");
135        assert_eq!(scope.policy_resource(), format!("model:{MODEL_REF}"));
136        Ok(())
137    }
138
139    #[test]
140    fn malformed_or_ambiguous_scope_separators_are_rejected() {
141        for scope in [
142            "infer:model",
143            "infer::qwen:main",
144            "infer:model:",
145            "infer:model:qwen::main",
146            "infer:model:qwen:main:other",
147            "infer:registry:repo:main",
148            ":model:qwen:main",
149        ] {
150            assert!(
151                Scope::parse(scope).is_err(),
152                "accepted malformed scope {scope}"
153            );
154        }
155    }
156
157    #[test]
158    fn test_scope_to_string() {
159        let scope = Scope::new("infer".to_owned(), "model".to_owned(), "qwen-7b".to_owned());
160        assert_eq!(scope.to_string(), "infer:model:qwen-7b");
161    }
162}