Skip to main content

themis/
subject.rs

1use serde::{Deserialize, Serialize};
2
3use crate::attr::{Attributes, Value};
4use crate::resource::{Anchor, ObjectRef, Resource};
5
6/// Principal of every identified user.
7pub const AUTHENTICATED: &str = "authenticated";
8/// Principal of whoever arrives without an identity.
9pub const ANONYMOUS: &str = "anonymous";
10
11/// Role assigned to a subject, optionally restricted to a scope (a role in an organization
12/// holds only for resources whose path goes through it).
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct RoleAssignment {
15    pub role: String,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub scope: Option<Anchor>,
18}
19
20/// Who requests the access.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct Subject {
23    pub kind: String,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub id: Option<String>,
26    #[serde(default, skip_serializing_if = "Vec::is_empty")]
27    pub roles: Vec<RoleAssignment>,
28    #[serde(default, skip_serializing_if = "Vec::is_empty")]
29    pub principals: Vec<String>,
30    #[serde(default, skip_serializing_if = "Attributes::is_empty")]
31    pub attrs: Attributes,
32}
33
34impl Subject {
35    /// Identified user, with the principal [`AUTHENTICATED`].
36    pub fn user(id: impl Into<String>) -> Self {
37        Self::of_kind("user", id).with_principal(AUTHENTICATED)
38    }
39
40    /// Visitor without an identity, with the principal [`ANONYMOUS`].
41    pub fn anonymous() -> Self {
42        Self {
43            kind: "user".to_string(),
44            id: None,
45            roles: Vec::new(),
46            principals: vec![ANONYMOUS.to_string()],
47            attrs: Attributes::new(),
48        }
49    }
50
51    /// Subject of another kind (service account, device), with no principal.
52    pub fn of_kind(kind: impl Into<String>, id: impl Into<String>) -> Self {
53        Self {
54            kind: kind.into(),
55            id: Some(id.into()),
56            roles: Vec::new(),
57            principals: Vec::new(),
58            attrs: Attributes::new(),
59        }
60    }
61
62    pub fn with_role(mut self, role: impl Into<String>) -> Self {
63        self.roles.push(RoleAssignment {
64            role: role.into(),
65            scope: None,
66        });
67        self
68    }
69
70    pub fn with_role_in(mut self, role: impl Into<String>, scope: Anchor) -> Self {
71        self.roles.push(RoleAssignment {
72            role: role.into(),
73            scope: Some(scope),
74        });
75        self
76    }
77
78    pub fn with_principal(mut self, principal: impl Into<String>) -> Self {
79        self.principals.push(principal.into());
80        self
81    }
82
83    pub fn with_attr(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
84        self.attrs.insert(key.into(), value.into());
85        self
86    }
87
88    pub fn object_ref(&self) -> Option<ObjectRef> {
89        self.id.as_ref().map(|id| ObjectRef::new(self.kind.clone(), id.clone()))
90    }
91
92    /// Direct roles that hold for the resource: unscoped, or with a scope in its path.
93    pub fn roles_for<'a>(&'a self, resource: &'a Resource) -> impl Iterator<Item = &'a str> {
94        self.roles
95            .iter()
96            .filter(|r| r.scope.as_ref().is_none_or(|scope| resource.contains(scope)))
97            .map(|r| r.role.as_str())
98    }
99
100    pub fn has_principal(&self, principal: &str) -> bool {
101        self.principals.iter().any(|p| p == principal)
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn scoped_role_applies_only_inside_scope() {
111        let s = Subject::user("u")
112            .with_role_in("editor", Anchor::new("org", "o1"))
113            .with_role("viewer");
114        let inside = Resource::new("project", "p").within("org", "o1");
115        let outside = Resource::new("project", "p").within("org", "o2");
116        assert_eq!(s.roles_for(&inside).collect::<Vec<_>>(), ["editor", "viewer"]);
117        assert_eq!(s.roles_for(&outside).collect::<Vec<_>>(), ["viewer"]);
118    }
119}