1use 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 pub effective: Vec<String>,
21 pub path: Vec<Anchor>,
23 pub roles: Vec<String>,
25 pub overrides: Vec<OverrideStep>,
26 pub grants: Vec<GrantTrace>,
28 pub strategy: String,
29 pub decision: Decision,
30}
31
32impl Explanation {
33 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 Excepted,
60 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(tag = "kind", rename_all = "snake_case")]
79pub enum Verdict {
80 Candidate,
82 CandidateFailSafe {
84 problem: String,
85 },
86 PermissionUnrelated,
88 OutOfScope,
90 TargetNotOnPath,
92 SubjectMismatch,
93 SubjectUnresolved {
95 problem: String,
96 },
97 ConditionFalse,
98 ConditionUnresolved {
100 problem: String,
101 },
102 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 #[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 Skipped,
133}
134
135#[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
178pub 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, ®istry);
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}