Skip to main content

themis/
explain.rs

1//! Full trace of a decision: why each grant got in or stayed out, what each override answered
2//! and how the strategy chose. [`crate::Engine::explain`] returns the same [`Decision`] as
3//! [`crate::Engine::decide`], plus the path that led to it.
4
5use serde::{Deserialize, Serialize};
6
7use crate::attr::Value;
8use crate::condition::{Condition, ConditionRegistry, EvalContext, Operand};
9use crate::decision::Decision;
10use crate::grant::{Effect, Grant};
11use crate::resource::{Anchor, Resource};
12use crate::subject::Subject;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct Explanation {
16    pub subject: Subject,
17    pub permission: String,
18    pub resource: Resource,
19    /// The requested permission and the ones that grant it. Empty if the permission is not in the catalog.
20    pub effective: Vec<String>,
21    /// Steps of the resource with the implicit `global` at the end. The position is the `rank`.
22    pub path: Vec<Anchor>,
23    /// Roles of the subject that hold for the resource, including inherited ones.
24    pub roles: Vec<String>,
25    pub overrides: Vec<OverrideStep>,
26    /// All the grants the source delivered, in its order.
27    pub grants: Vec<GrantTrace>,
28    pub strategy: String,
29    pub decision: Decision,
30}
31
32impl Explanation {
33    /// The grant that decided, if a grant did.
34    pub fn decisive(&self) -> Option<&GrantTrace> {
35        match &self.decision.reason {
36            crate::Reason::Grant { grant_id, .. } => self
37                .grants
38                .iter()
39                .find(|g| &g.grant.id == grant_id && g.verdict.is_candidate()),
40            _ => None,
41        }
42    }
43
44    pub fn candidates(&self) -> impl Iterator<Item = &GrantTrace> {
45        self.grants.iter().filter(|g| g.verdict.is_candidate())
46    }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct OverrideStep {
51    pub name: String,
52    pub outcome: OverrideOutcome,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum OverrideOutcome {
58    /// The permission is in the override's exceptions; it was not even consulted.
59    Excepted,
60    /// Consulted, did not rule.
61    Abstained,
62    Allowed,
63    Denied,
64}
65
66impl From<Option<Effect>> for OverrideOutcome {
67    fn from(effect: Option<Effect>) -> Self {
68        match effect {
69            None => OverrideOutcome::Abstained,
70            Some(Effect::Allow) => OverrideOutcome::Allowed,
71            Some(Effect::Deny) => OverrideOutcome::Denied,
72        }
73    }
74}
75
76/// The fate of a grant during collection, in the order the engine checks.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(tag = "kind", rename_all = "snake_case")]
79pub enum Verdict {
80    /// Became a candidate.
81    Candidate,
82    /// `deny` that became a candidate even though the subject or the condition could not be evaluated.
83    CandidateFailSafe {
84        problem: String,
85    },
86    /// The grant's permission is not the requested one and does not grant it.
87    PermissionUnrelated,
88    /// The grant's scope is not in the resource path.
89    OutOfScope,
90    /// The grant's target matches no step of the path.
91    TargetNotOnPath,
92    SubjectMismatch,
93    /// `allow` discarded because the subject could not be evaluated (ReBAC without tuples, depth).
94    SubjectUnresolved {
95        problem: String,
96    },
97    ConditionFalse,
98    /// `allow` discarded because the condition could not be evaluated.
99    ConditionUnresolved {
100        problem: String,
101    },
102    /// An override decided before collection.
103    NotReached,
104}
105
106impl Verdict {
107    pub fn is_candidate(&self) -> bool {
108        matches!(self, Verdict::Candidate | Verdict::CandidateFailSafe { .. })
109    }
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
113pub struct GrantTrace {
114    pub grant: Grant,
115    pub verdict: Verdict,
116    /// Position of the step matched by the target (0 = most specific).
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub rank: Option<usize>,
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub anchor: Option<Anchor>,
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub condition: Option<ConditionTrace>,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(tag = "kind", content = "detail", rename_all = "snake_case")]
127pub enum TraceResult {
128    True,
129    False,
130    Error(String),
131    /// Not evaluated: an earlier sibling already decided the `all`/`any`.
132    Skipped,
133}
134
135/// Evaluation of a condition, node by node, with the resolved values in the label.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct ConditionTrace {
138    pub label: String,
139    pub result: TraceResult,
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub children: Vec<ConditionTrace>,
142}
143
144fn show_value(value: &Value) -> String {
145    serde_json::to_string(value).unwrap_or_else(|_| format!("{value:?}"))
146}
147
148fn show_operand(ctx: &EvalContext<'_>, operand: &Operand) -> String {
149    match operand {
150        Operand::Lit(value) => show_value(value),
151        Operand::Attr { attr } => match ctx.resolve(attr) {
152            Ok(Some(value)) => format!("{attr} ({})", show_value(&value)),
153            Ok(None) => format!("{attr} (ausente)"),
154            Err(_) => format!("{attr} (caminho inválido)"),
155        },
156    }
157}
158
159fn result_of(outcome: &Result<bool, crate::ConditionError>) -> TraceResult {
160    match outcome {
161        Ok(true) => TraceResult::True,
162        Ok(false) => TraceResult::False,
163        Err(error) => TraceResult::Error(error.to_string()),
164    }
165}
166
167fn skipped(condition: &Condition, ctx: &EvalContext<'_>, registry: &ConditionRegistry) -> ConditionTrace {
168    let mut node = trace_condition(condition, ctx, registry);
169    mark_skipped(&mut node);
170    node
171}
172
173fn mark_skipped(node: &mut ConditionTrace) {
174    node.result = TraceResult::Skipped;
175    node.children.iter_mut().for_each(mark_skipped);
176}
177
178/// Evaluates `condition` the way the engine does (with short-circuiting) and returns the tree.
179pub fn trace_condition(condition: &Condition, ctx: &EvalContext<'_>, registry: &ConditionRegistry) -> ConditionTrace {
180    let binary = |op: &str, left: &Operand, right: &Operand| {
181        format!("{} {op} {}", show_operand(ctx, left), show_operand(ctx, right))
182    };
183    let leaf = |label: String| ConditionTrace {
184        label,
185        result: result_of(&condition.evaluate(ctx, registry)),
186        children: Vec::new(),
187    };
188    match condition {
189        Condition::Eq { left, right } => leaf(binary("=", left, right)),
190        Condition::Ne { left, right } => leaf(binary("≠", left, right)),
191        Condition::Lt { left, right } => leaf(binary("<", left, right)),
192        Condition::Le { left, right } => leaf(binary("≤", left, right)),
193        Condition::Gt { left, right } => leaf(binary(">", left, right)),
194        Condition::Ge { left, right } => leaf(binary("≥", left, right)),
195        Condition::In { item, set } => leaf(binary("∈", item, set)),
196        Condition::Exists { attr } => leaf(format!("existe {}", show_operand(ctx, &Operand::attr(attr.clone())))),
197        Condition::Call { func, args } => {
198            let args: Vec<String> = args.iter().map(|a| show_operand(ctx, a)).collect();
199            leaf(format!("{func}({})", args.join(", ")))
200        }
201        Condition::Not { cond } => ConditionTrace {
202            label: "não".into(),
203            result: result_of(&condition.evaluate(ctx, registry)),
204            children: vec![trace_condition(cond, ctx, registry)],
205        },
206        Condition::All { of } | Condition::Any { of } => {
207            let stop_on = matches!(condition, Condition::Any { .. });
208            let mut children = Vec::with_capacity(of.len());
209            let mut done = false;
210            for child in of {
211                if done {
212                    children.push(skipped(child, ctx, registry));
213                    continue;
214                }
215                let node = trace_condition(child, ctx, registry);
216                done = match node.result {
217                    TraceResult::True => stop_on,
218                    TraceResult::False => !stop_on,
219                    _ => true,
220                };
221                children.push(node);
222            }
223            ConditionTrace {
224                label: if stop_on { "qualquer um" } else { "todos" }.into(),
225                result: result_of(&condition.evaluate(ctx, registry)),
226                children,
227            }
228        }
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use crate::attr::Attributes;
236
237    #[test]
238    fn condition_tree_matches_evaluation_and_short_circuits() {
239        let subject = Subject::user("u").with_attr("plan", "free");
240        let resource = Resource::new("doc", "d");
241        let env = Attributes::new();
242        let ctx = EvalContext {
243            subject: &subject,
244            resource: &resource,
245            env: &env,
246        };
247        let cond = Condition::all([
248            Condition::eq(Operand::attr("subject.plan"), Operand::lit("pro")),
249            Condition::exists("subject.missing"),
250        ]);
251        let registry = ConditionRegistry::new();
252        let tree = trace_condition(&cond, &ctx, &registry);
253        assert_eq!(tree.result, TraceResult::False);
254        assert_eq!(tree.children[0].label, r#"subject.plan ("free") = "pro""#);
255        assert_eq!(tree.children[0].result, TraceResult::False);
256        assert_eq!(tree.children[1].result, TraceResult::Skipped);
257    }
258}