Skip to main content

themis/
spec.rs

1//! Declarative configuration of the engine and of governance, in JSON, TOML or YAML.
2//!
3//! Use it to load the policy from a file and for the bindings (`themis-node`), which cannot
4//! pass Rust closures. Everything the spec builds can be extended later in code:
5//! [`EngineSpec::builder`] returns the [`EngineBuilder`] to add condition functions,
6//! custom overrides or another strategy.
7
8use serde::{Deserialize, Serialize};
9
10use crate::catalog::{Catalog, CatalogErrors, CatalogExport};
11use crate::engine::{Engine, EngineBuilder, EngineError};
12use crate::governance::{CatalogConformance, Forbid, Governance, NoLockout, NoSelfManagement, RequirePermission};
13use crate::grant::SubjectMatcher;
14use crate::overrides::{PermissionHolder, ResourceOwner};
15use crate::rbac::{RbacError, RoleGraph};
16use crate::rebac::{RelationSchema, Rewrite};
17use crate::resource::Resource;
18use crate::strategy::{DenyOverrides, FirstApplicable, MostSpecific, PermitOverrides};
19use crate::subject::Subject;
20
21#[derive(Debug, thiserror::Error)]
22pub enum SpecError {
23    #[error(transparent)]
24    Catalog(#[from] CatalogErrors),
25    #[error(transparent)]
26    Roles(#[from] RbacError),
27    #[error(transparent)]
28    Engine(#[from] EngineError),
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
32#[serde(rename_all = "camelCase", deny_unknown_fields)]
33pub struct EngineSpec {
34    pub catalog: CatalogExport,
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub roles: Vec<RoleSpec>,
37    /// `None` turns ReBAC off; `Some(vec![])` turns it on with every relation holding only its own
38    /// tuples.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub relations: Option<Vec<RelationSpec>>,
41    #[serde(default)]
42    pub strategy: StrategySpec,
43    #[serde(default, skip_serializing_if = "Vec::is_empty")]
44    pub overrides: Vec<OverrideSpec>,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub max_relation_depth: Option<usize>,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(deny_unknown_fields)]
51pub struct RoleSpec {
52    pub role: String,
53    pub inherits: Vec<String>,
54}
55
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct RelationSpec {
59    pub kind: String,
60    pub relation: String,
61    pub rewrite: Rewrite,
62}
63
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "snake_case")]
66pub enum StrategySpec {
67    #[default]
68    MostSpecific,
69    DenyOverrides,
70    PermitOverrides,
71    FirstApplicable,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(tag = "kind", rename_all = "snake_case")]
76pub enum OverrideRule {
77    /// [`ResourceOwner`]: the subject's id is in the resource's `attr` attribute.
78    ResourceOwner { attr: String },
79    /// [`PermissionHolder`]: the subject has `permission` on the resource.
80    PermissionHolder { permission: String },
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct OverrideSpec {
85    #[serde(flatten)]
86    pub rule: OverrideRule,
87    /// Permissions (and the ones they grant) outside the reach of this override.
88    #[serde(default, skip_serializing_if = "Vec::is_empty")]
89    pub except: Vec<String>,
90}
91
92impl EngineSpec {
93    pub fn builder(&self) -> Result<EngineBuilder, SpecError> {
94        let catalog = Catalog::from_export(self.catalog.clone())?;
95        let mut roles = RoleGraph::builder();
96        for spec in &self.roles {
97            for parent in &spec.inherits {
98                roles = roles.inherit(spec.role.clone(), parent.clone());
99            }
100        }
101        let mut builder = Engine::builder(catalog).roles(roles.build()?);
102        if let Some(relations) = &self.relations {
103            let schema = relations.iter().fold(RelationSchema::new(), |schema, r| {
104                schema.relation(r.kind.clone(), r.relation.clone(), r.rewrite.clone())
105            });
106            builder = builder.relations(schema);
107        }
108        builder = match self.strategy {
109            StrategySpec::MostSpecific => builder.strategy(MostSpecific),
110            StrategySpec::DenyOverrides => builder.strategy(DenyOverrides),
111            StrategySpec::PermitOverrides => builder.strategy(PermitOverrides),
112            StrategySpec::FirstApplicable => builder.strategy(FirstApplicable),
113        };
114        for spec in &self.overrides {
115            let except = spec.except.clone();
116            builder = match &spec.rule {
117                OverrideRule::ResourceOwner { attr } => builder.override_except(ResourceOwner::new(attr), except),
118                OverrideRule::PermissionHolder { permission } => {
119                    builder.override_except(PermissionHolder::new(permission), except)
120                }
121            };
122        }
123        if let Some(depth) = self.max_relation_depth {
124            builder = builder.max_relation_depth(depth);
125        }
126        Ok(builder)
127    }
128
129    pub fn build(&self) -> Result<Engine, SpecError> {
130        Ok(self.builder()?.build()?)
131    }
132}
133
134/// Ready-made governance invariants, in declarative form.
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
136#[serde(tag = "kind", rename_all = "snake_case")]
137pub enum InvariantSpec {
138    CatalogConformance,
139    NoSelfManagement,
140    RequirePermission {
141        permission: String,
142        resource: Resource,
143    },
144    NoLockout {
145        permissions: Vec<String>,
146        members: Vec<Subject>,
147        resource: Resource,
148    },
149    Forbid {
150        subject: SubjectMatcher,
151        permissions: Vec<String>,
152    },
153}
154
155impl InvariantSpec {
156    pub fn add_to(&self, governance: Governance) -> Governance {
157        match self.clone() {
158            InvariantSpec::CatalogConformance => governance.with(CatalogConformance),
159            InvariantSpec::NoSelfManagement => governance.with(NoSelfManagement),
160            InvariantSpec::RequirePermission { permission, resource } => {
161                governance.with(RequirePermission::new(permission, resource))
162            }
163            InvariantSpec::NoLockout {
164                permissions,
165                members,
166                resource,
167            } => governance.with(NoLockout::new(permissions, members, resource)),
168            InvariantSpec::Forbid { subject, permissions } => governance.with(Forbid::new(subject, permissions)),
169        }
170    }
171}
172
173impl<'a> FromIterator<&'a InvariantSpec> for Governance {
174    fn from_iter<I: IntoIterator<Item = &'a InvariantSpec>>(iter: I) -> Self {
175        iter.into_iter().fold(Governance::new(), |g, spec| spec.add_to(g))
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::{Context, Grant, Request, TargetSelector};
183
184    const SPEC: &str = r#"{
185        "catalog": {
186            "targetKinds": ["project", "document"],
187            "broadTargets": ["org"],
188            "permissions": [
189                {"key": "project.view", "targets": ["project"]},
190                {"key": "project.delete", "targets": ["project"]},
191                {"key": "document.view", "targets": ["project", "document"], "impliedBy": ["project.view"]}
192            ]
193        },
194        "roles": [{"role": "admin", "inherits": ["member"]}],
195        "relations": [
196            {"kind": "project", "relation": "viewer",
197             "rewrite": {"rewrite": "union", "of": [{"rewrite": "this"}, {"rewrite": "computed", "relation": "owner"}]}}
198        ],
199        "strategy": "deny_overrides",
200        "overrides": [{"kind": "resource_owner", "attr": "owner", "except": ["project.delete"]}],
201        "maxRelationDepth": 8
202    }"#;
203
204    #[test]
205    fn builds_engine_from_json() {
206        let spec: EngineSpec = serde_json::from_str(SPEC).unwrap();
207        let engine = spec.build().unwrap();
208        let grants = vec![Grant::allow(
209            "g",
210            SubjectMatcher::role("member"),
211            "project.view",
212            TargetSelector::kind("project"),
213        )];
214        let admin = Subject::user("a").with_role("admin");
215        let doc = Resource::new("document", "d1").within("project", "p1");
216        assert!(engine.check(&Context::new(&grants), &Request::new(&admin, "document.view", &doc)));
217
218        let owned = Resource::new("project", "p1").with_attr("owner", "o");
219        let owner = Subject::user("o");
220        let none: Vec<Grant> = Vec::new();
221        assert!(engine.check(&Context::new(&none), &Request::new(&owner, "project.view", &owned)));
222        assert!(!engine.check(&Context::new(&none), &Request::new(&owner, "project.delete", &owned)));
223
224        let back: EngineSpec = serde_json::from_str(&serde_json::to_string(&spec).unwrap()).unwrap();
225        assert_eq!(back, spec);
226    }
227
228    #[test]
229    fn invariants_from_json() {
230        let specs: Vec<InvariantSpec> = serde_json::from_str(
231            r#"[{"kind": "catalog_conformance"}, {"kind": "forbid", "subject": {"kind": "any"}, "permissions": ["project.delete"]}]"#,
232        )
233        .unwrap();
234        let governance: Governance = specs.iter().collect();
235        assert_eq!(governance.len(), 2);
236    }
237}