Skip to main content

themis/
engine.rs

1use std::collections::BTreeSet;
2use std::sync::Arc;
3
4use serde::{Deserialize, Serialize};
5
6use crate::attr::Attributes;
7use crate::catalog::Catalog;
8use crate::condition::{ConditionRegistry, EvalContext};
9use crate::decision::{Decision, Reason, Request};
10use crate::explain::{
11    ConditionTrace, Explanation, GrantTrace, OverrideOutcome, OverrideStep, Verdict, trace_condition,
12};
13use crate::grant::{Effect, Grant, GrantSource, SubjectMatcher};
14use crate::overrides::Override;
15use crate::rbac::RoleGraph;
16use crate::rebac::{RelationSchema, TupleStore};
17use crate::resource::{Anchor, Resource};
18use crate::strategy::{Candidate, MostSpecific, Strategy};
19use crate::subject::Subject;
20
21static EMPTY_ENV: Attributes = Attributes::new();
22
23#[derive(Default)]
24struct Recorder {
25    overrides: Vec<OverrideStep>,
26    grants: Vec<GrantTrace>,
27}
28
29struct Judged {
30    verdict: Verdict,
31    rank: Option<usize>,
32    anchor: Option<Anchor>,
33    condition: Option<ConditionTrace>,
34}
35
36const DEFAULT_MAX_RELATION_DEPTH: usize = 32;
37
38/// Data of a decision: grants, ReBAC tuples and environment attributes. The [`Engine`] only holds
39/// configuration; the data arrives with each call.
40#[derive(Clone, Copy)]
41pub struct Context<'a> {
42    pub grants: &'a dyn GrantSource,
43    pub tuples: Option<&'a dyn TupleStore>,
44    pub env: &'a Attributes,
45}
46
47impl<'a> Context<'a> {
48    pub fn new(grants: &'a dyn GrantSource) -> Self {
49        Self {
50            grants,
51            tuples: None,
52            env: &EMPTY_ENV,
53        }
54    }
55
56    pub fn with_tuples(mut self, tuples: &'a dyn TupleStore) -> Self {
57        self.tuples = Some(tuples);
58        self
59    }
60
61    pub fn with_env(mut self, env: &'a Attributes) -> Self {
62        self.env = env;
63        self
64    }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
68pub enum EngineError {
69    #[error("exceção de override cita permissão fora do catálogo: {0}")]
70    UnknownPermission(String),
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
74pub enum GrantError {
75    #[error("grant sem id")]
76    EmptyId,
77    #[error("permissão desconhecida: {0}")]
78    UnknownPermission(String),
79    #[error("tipo de alvo não registrado: {0}")]
80    UnknownTargetKind(String),
81    #[error("a permissão {permission} não aceita alvo {target}")]
82    TargetNotAllowed { permission: String, target: String },
83    #[error("grant por relação exige RelationSchema no motor")]
84    RelationsDisabled,
85    #[error("condição chama função não registrada: {0}")]
86    UnknownFunction(String),
87}
88
89struct OverrideEntry {
90    inner: Box<dyn Override>,
91    except: Vec<String>,
92}
93
94/// Decision engine. Immutable and shareable between threads once built.
95pub struct Engine {
96    catalog: Arc<Catalog>,
97    roles: RoleGraph,
98    relations: Option<RelationSchema>,
99    conditions: ConditionRegistry,
100    strategy: Box<dyn Strategy>,
101    overrides: Vec<OverrideEntry>,
102    max_relation_depth: usize,
103}
104
105pub struct EngineBuilder {
106    engine: Engine,
107}
108
109impl EngineBuilder {
110    pub fn roles(mut self, roles: RoleGraph) -> Self {
111        self.engine.roles = roles;
112        self
113    }
114
115    pub fn relations(mut self, schema: RelationSchema) -> Self {
116        self.engine.relations = Some(schema);
117        self
118    }
119
120    pub fn conditions(mut self, registry: ConditionRegistry) -> Self {
121        self.engine.conditions = registry;
122        self
123    }
124
125    pub fn strategy(mut self, strategy: impl Strategy + 'static) -> Self {
126        self.engine.strategy = Box::new(strategy);
127        self
128    }
129
130    pub fn override_with(self, rule: impl Override + 'static) -> Self {
131        self.override_except(rule, std::iter::empty::<String>())
132    }
133
134    /// Override that does not apply to the listed permissions or to the ones they grant
135    /// (for example, the organization administrator does not delete another owner's project).
136    pub fn override_except<I, S>(mut self, rule: impl Override + 'static, except: I) -> Self
137    where
138        I: IntoIterator<Item = S>,
139        S: Into<String>,
140    {
141        self.engine.overrides.push(OverrideEntry {
142            inner: Box::new(rule),
143            except: except.into_iter().map(Into::into).collect(),
144        });
145        self
146    }
147
148    pub fn max_relation_depth(mut self, depth: usize) -> Self {
149        self.engine.max_relation_depth = depth;
150        self
151    }
152
153    pub fn build(self) -> Result<Engine, EngineError> {
154        let engine = self.engine;
155        for key in engine.overrides.iter().flat_map(|o| &o.except) {
156            if !engine.catalog.contains(key) {
157                return Err(EngineError::UnknownPermission(key.clone()));
158            }
159        }
160        Ok(engine)
161    }
162}
163
164impl Engine {
165    pub fn builder(catalog: impl Into<Arc<Catalog>>) -> EngineBuilder {
166        EngineBuilder {
167            engine: Engine {
168                catalog: catalog.into(),
169                roles: RoleGraph::default(),
170                relations: None,
171                conditions: ConditionRegistry::default(),
172                strategy: Box::new(MostSpecific),
173                overrides: Vec::new(),
174                max_relation_depth: DEFAULT_MAX_RELATION_DEPTH,
175            },
176        }
177    }
178
179    pub fn catalog(&self) -> &Catalog {
180        &self.catalog
181    }
182
183    pub fn roles(&self) -> &RoleGraph {
184        &self.roles
185    }
186
187    pub fn check(&self, ctx: &Context<'_>, request: &Request<'_>) -> bool {
188        self.decide(ctx, request).is_allowed()
189    }
190
191    pub fn decide(&self, ctx: &Context<'_>, request: &Request<'_>) -> Decision {
192        self.decide_inner(ctx, request, true, None)
193    }
194
195    /// Decision by the grants only, without overrides. Used by overrides that depend on a permission.
196    pub fn decide_without_overrides(&self, ctx: &Context<'_>, request: &Request<'_>) -> Decision {
197        self.decide_inner(ctx, request, false, None)
198    }
199
200    /// The same decision as [`Engine::decide`], with the trace of each override and of each grant
201    /// delivered by the source. More expensive: it evaluates the condition tree and clones the grants.
202    pub fn explain(&self, ctx: &Context<'_>, request: &Request<'_>) -> Explanation {
203        let mut recorder = Recorder::default();
204        let decision = self.decide_inner(ctx, request, true, Some(&mut recorder));
205        if matches!(decision.reason, Reason::Override { .. }) {
206            ctx.grants.visit(request.subject, request.resource, &mut |grant| {
207                recorder.grants.push(GrantTrace {
208                    grant: grant.clone(),
209                    verdict: Verdict::NotReached,
210                    rank: None,
211                    anchor: None,
212                    condition: None,
213                });
214            });
215        }
216        Explanation {
217            subject: request.subject.clone(),
218            permission: request.permission.to_string(),
219            resource: request.resource.clone(),
220            effective: self
221                .catalog
222                .effective(request.permission)
223                .map(|set| set.iter().cloned().collect())
224                .unwrap_or_default(),
225            path: request.resource.anchors().map(|(_, a)| a.clone()).collect(),
226            roles: self
227                .roles
228                .expand(request.subject.roles_for(request.resource))
229                .into_iter()
230                .collect(),
231            overrides: recorder.overrides,
232            grants: recorder.grants,
233            strategy: self.strategy.name().to_string(),
234            decision,
235        }
236    }
237
238    fn decide_inner(
239        &self,
240        ctx: &Context<'_>,
241        request: &Request<'_>,
242        with_overrides: bool,
243        mut recorder: Option<&mut Recorder>,
244    ) -> Decision {
245        let Some(effective) = self.catalog.effective(request.permission) else {
246            return Decision::deny(Reason::UnknownPermission);
247        };
248
249        if with_overrides {
250            for entry in &self.overrides {
251                let name = entry.inner.name().to_string();
252                if entry.except.iter().any(|key| effective.contains(key)) {
253                    if let Some(r) = recorder.as_deref_mut() {
254                        r.overrides.push(OverrideStep {
255                            name,
256                            outcome: OverrideOutcome::Excepted,
257                        });
258                    }
259                    continue;
260                }
261                let outcome = entry.inner.evaluate(self, ctx, request);
262                if let Some(r) = recorder.as_deref_mut() {
263                    r.overrides.push(OverrideStep {
264                        name: name.clone(),
265                        outcome: outcome.into(),
266                    });
267                }
268                if let Some(effect) = outcome {
269                    return Decision {
270                        effect,
271                        reason: Reason::Override { name },
272                        matched: Vec::new(),
273                        warnings: Vec::new(),
274                    };
275                }
276            }
277        }
278
279        let mut warnings = Vec::new();
280        let candidates = self.collect(ctx, request, effective, &mut warnings, recorder);
281        let matched = candidates.iter().map(|c| c.grant.id.clone()).collect();
282        match self.strategy.combine(&candidates) {
283            Some(i) => {
284                let decisive = &candidates[i];
285                Decision {
286                    effect: decisive.grant.effect,
287                    reason: Reason::Grant {
288                        grant_id: decisive.grant.id.clone(),
289                        permission: decisive.grant.permission.clone(),
290                        rank: decisive.rank,
291                        strategy: self.strategy.name().to_string(),
292                    },
293                    matched,
294                    warnings,
295                }
296            }
297            None => Decision {
298                effect: Effect::Deny,
299                reason: Reason::NoApplicableGrant,
300                matched,
301                warnings,
302            },
303        }
304    }
305
306    /// Grants that apply to the request. When in doubt (a condition or relation that could not be
307    /// evaluated), a `deny` applies and an `allow` does not: an error never opens access.
308    fn collect(
309        &self,
310        ctx: &Context<'_>,
311        request: &Request<'_>,
312        effective: &BTreeSet<String>,
313        warnings: &mut Vec<String>,
314        mut recorder: Option<&mut Recorder>,
315    ) -> Vec<Candidate> {
316        let roles = self.roles.expand(request.subject.roles_for(request.resource));
317        let eval_ctx = EvalContext {
318            subject: request.subject,
319            resource: request.resource,
320            env: ctx.env,
321        };
322        let tracing = recorder.is_some();
323        let mut out = Vec::new();
324        ctx.grants.visit(request.subject, request.resource, &mut |grant| {
325            let judged = self.judge(ctx, request, effective, &roles, &eval_ctx, grant, warnings, tracing);
326            if let (true, Some(rank)) = (judged.verdict.is_candidate(), judged.rank) {
327                out.push(Candidate {
328                    grant: grant.clone(),
329                    rank,
330                });
331            }
332            if let Some(r) = recorder.as_deref_mut() {
333                r.grants.push(GrantTrace {
334                    grant: grant.clone(),
335                    verdict: judged.verdict,
336                    rank: judged.rank,
337                    anchor: judged.anchor,
338                    condition: judged.condition,
339                });
340            }
341        });
342        out
343    }
344
345    /// Checks a grant in order: permission, scope, target, subject, condition.
346    #[allow(clippy::too_many_arguments)]
347    fn judge(
348        &self,
349        ctx: &Context<'_>,
350        request: &Request<'_>,
351        effective: &BTreeSet<String>,
352        roles: &BTreeSet<String>,
353        eval_ctx: &EvalContext<'_>,
354        grant: &Grant,
355        warnings: &mut Vec<String>,
356        tracing: bool,
357    ) -> Judged {
358        let out = |verdict| Judged {
359            verdict,
360            rank: None,
361            anchor: None,
362            condition: None,
363        };
364        if !effective.contains(&grant.permission) {
365            return out(Verdict::PermissionUnrelated);
366        }
367        if grant
368            .scope
369            .as_ref()
370            .is_some_and(|scope| !request.resource.contains(scope))
371        {
372            return out(Verdict::OutOfScope);
373        }
374        let Some((rank, anchor)) = request.resource.locate(&grant.target) else {
375            return out(Verdict::TargetNotOnPath);
376        };
377        let mut judged = Judged {
378            verdict: Verdict::Candidate,
379            rank: Some(rank),
380            anchor: Some(anchor.clone()),
381            condition: None,
382        };
383        let fail_safe = grant.effect == Effect::Deny;
384        let mut problem = None;
385        match self.subject_matches(ctx, request.subject, roles, &grant.subject, anchor) {
386            Ok(true) => {}
387            Ok(false) => {
388                judged.verdict = Verdict::SubjectMismatch;
389                return judged;
390            }
391            Err(error) => {
392                warnings.push(format!("grant {}: {error}", grant.id));
393                if !fail_safe {
394                    judged.verdict = Verdict::SubjectUnresolved { problem: error };
395                    return judged;
396                }
397                problem = Some(error);
398            }
399        }
400        if let Some(condition) = &grant.condition {
401            if tracing {
402                judged.condition = Some(trace_condition(condition, eval_ctx, &self.conditions));
403            }
404            match condition.evaluate(eval_ctx, &self.conditions) {
405                Ok(true) => {}
406                Ok(false) => {
407                    judged.verdict = Verdict::ConditionFalse;
408                    return judged;
409                }
410                Err(error) => {
411                    warnings.push(format!("grant {}: {error}", grant.id));
412                    if !fail_safe {
413                        judged.verdict = Verdict::ConditionUnresolved {
414                            problem: error.to_string(),
415                        };
416                        return judged;
417                    }
418                    problem.get_or_insert(error.to_string());
419                }
420            }
421        }
422        if let Some(problem) = problem {
423            judged.verdict = Verdict::CandidateFailSafe { problem };
424        }
425        judged
426    }
427
428    fn subject_matches(
429        &self,
430        ctx: &Context<'_>,
431        subject: &Subject,
432        roles: &BTreeSet<String>,
433        matcher: &SubjectMatcher,
434        anchor: &Anchor,
435    ) -> Result<bool, String> {
436        match matcher {
437            SubjectMatcher::User { id } => Ok(subject.id.as_deref() == Some(id.as_str())),
438            SubjectMatcher::Role { id } => Ok(roles.contains(id)),
439            SubjectMatcher::Principal { name } => Ok(subject.has_principal(name)),
440            SubjectMatcher::Any => Ok(true),
441            SubjectMatcher::Relation { relation } => {
442                let schema = self.relations.as_ref().ok_or("ReBAC desligado no motor")?;
443                let store = ctx.tuples.ok_or("contexto sem TupleStore")?;
444                let (Some(object), Some(who)) = (anchor.object_ref(), subject.object_ref()) else {
445                    return Ok(false);
446                };
447                schema
448                    .check(store, &object, relation, &who, self.max_relation_depth)
449                    .map_err(|e| e.to_string())
450            }
451        }
452    }
453
454    /// Checks a grant against the catalog and the engine configuration before writing it.
455    pub fn validate_grant(&self, grant: &Grant) -> Result<(), GrantError> {
456        if grant.id.trim().is_empty() {
457            return Err(GrantError::EmptyId);
458        }
459        if !self.catalog.contains(&grant.permission) {
460            return Err(GrantError::UnknownPermission(grant.permission.clone()));
461        }
462        if !self.catalog.is_target_kind(&grant.target.kind) {
463            return Err(GrantError::UnknownTargetKind(grant.target.kind.clone()));
464        }
465        if !self.catalog.allows_target(&grant.permission, &grant.target.kind) {
466            return Err(GrantError::TargetNotAllowed {
467                permission: grant.permission.clone(),
468                target: grant.target.kind.clone(),
469            });
470        }
471        if matches!(grant.subject, SubjectMatcher::Relation { .. }) && self.relations.is_none() {
472            return Err(GrantError::RelationsDisabled);
473        }
474        if let Some(condition) = &grant.condition
475            && let Some(missing) = condition.functions().into_iter().find(|f| !self.conditions.contains(f))
476        {
477            return Err(GrantError::UnknownFunction(missing.to_string()));
478        }
479        Ok(())
480    }
481
482    /// Preloads, in one trip to the source, the grants that may hold for `subject` within
483    /// `scope`. The result is itself a [`GrantSource`] for repeated decisions (a WebSocket
484    /// connection, a page with many buttons) and serializes for the frontend.
485    pub fn capabilities(&self, ctx: &Context<'_>, subject: &Subject, scope: &Resource) -> CapabilitySet {
486        let roles = self.roles.expand(subject.roles_for(scope));
487        let mut grants = Vec::new();
488        ctx.grants.visit(subject, scope, &mut |grant| {
489            let concerns = match &grant.subject {
490                SubjectMatcher::User { id } => subject.id.as_deref() == Some(id.as_str()),
491                SubjectMatcher::Role { id } => roles.contains(id),
492                SubjectMatcher::Principal { name } => subject.has_principal(name),
493                SubjectMatcher::Relation { .. } | SubjectMatcher::Any => true,
494            };
495            if concerns {
496                grants.push(grant.clone());
497            }
498        });
499        CapabilitySet {
500            subject: subject.clone(),
501            grants,
502        }
503    }
504}
505
506/// Preloaded grants of a subject.
507#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
508pub struct CapabilitySet {
509    pub subject: Subject,
510    pub grants: Vec<Grant>,
511}
512
513impl GrantSource for CapabilitySet {
514    fn visit(&self, _: &Subject, _: &Resource, visitor: &mut dyn FnMut(&Grant)) {
515        for grant in &self.grants {
516            visitor(grant);
517        }
518    }
519}