1use std::cmp::Ordering;
2use std::collections::HashMap;
3use std::fmt;
4use std::sync::Arc;
5
6use serde::{Deserialize, Serialize};
7
8use crate::attr::{Attributes, Value};
9use crate::resource::Resource;
10use crate::subject::Subject;
11
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(untagged)]
19pub enum Operand {
20 Attr { attr: String },
21 Lit(Value),
22}
23
24impl Operand {
25 pub fn attr(path: impl Into<String>) -> Self {
26 Self::Attr { attr: path.into() }
27 }
28
29 pub fn lit(value: impl Into<Value>) -> Self {
30 Self::Lit(value.into())
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36#[serde(tag = "op", rename_all = "snake_case")]
37pub enum Condition {
38 Eq {
39 left: Operand,
40 right: Operand,
41 },
42 Ne {
43 left: Operand,
44 right: Operand,
45 },
46 Lt {
47 left: Operand,
48 right: Operand,
49 },
50 Le {
51 left: Operand,
52 right: Operand,
53 },
54 Gt {
55 left: Operand,
56 right: Operand,
57 },
58 Ge {
59 left: Operand,
60 right: Operand,
61 },
62 In {
64 item: Operand,
65 set: Operand,
66 },
67 Exists {
69 attr: String,
70 },
71 All {
72 of: Vec<Condition>,
73 },
74 Any {
75 of: Vec<Condition>,
76 },
77 Not {
78 cond: Box<Condition>,
79 },
80 Call {
82 func: String,
83 #[serde(default)]
84 args: Vec<Operand>,
85 },
86}
87
88impl Condition {
89 pub fn eq(left: Operand, right: Operand) -> Self {
90 Self::Eq { left, right }
91 }
92
93 pub fn ne(left: Operand, right: Operand) -> Self {
94 Self::Ne { left, right }
95 }
96
97 pub fn lt(left: Operand, right: Operand) -> Self {
98 Self::Lt { left, right }
99 }
100
101 pub fn le(left: Operand, right: Operand) -> Self {
102 Self::Le { left, right }
103 }
104
105 pub fn gt(left: Operand, right: Operand) -> Self {
106 Self::Gt { left, right }
107 }
108
109 pub fn ge(left: Operand, right: Operand) -> Self {
110 Self::Ge { left, right }
111 }
112
113 pub fn is_in(item: Operand, set: Operand) -> Self {
114 Self::In { item, set }
115 }
116
117 pub fn exists(attr: impl Into<String>) -> Self {
118 Self::Exists { attr: attr.into() }
119 }
120
121 pub fn all(of: impl IntoIterator<Item = Condition>) -> Self {
122 Self::All {
123 of: of.into_iter().collect(),
124 }
125 }
126
127 pub fn any(of: impl IntoIterator<Item = Condition>) -> Self {
128 Self::Any {
129 of: of.into_iter().collect(),
130 }
131 }
132
133 #[allow(clippy::should_implement_trait)]
134 pub fn not(cond: Condition) -> Self {
135 Self::Not { cond: Box::new(cond) }
136 }
137
138 pub fn call(func: impl Into<String>, args: impl IntoIterator<Item = Operand>) -> Self {
139 Self::Call {
140 func: func.into(),
141 args: args.into_iter().collect(),
142 }
143 }
144
145 pub fn functions(&self) -> Vec<&str> {
147 let mut out = Vec::new();
148 self.collect_functions(&mut out);
149 out
150 }
151
152 fn collect_functions<'a>(&'a self, out: &mut Vec<&'a str>) {
153 match self {
154 Condition::Call { func, .. } => out.push(func),
155 Condition::All { of } | Condition::Any { of } => of.iter().for_each(|c| c.collect_functions(out)),
156 Condition::Not { cond } => cond.collect_functions(out),
157 _ => {}
158 }
159 }
160
161 pub fn evaluate(&self, ctx: &EvalContext<'_>, registry: &ConditionRegistry) -> Result<bool, ConditionError> {
162 match self {
163 Condition::Eq { left, right } => Ok(ctx.operand(left)?.loosely_eq(&ctx.operand(right)?)),
164 Condition::Ne { left, right } => Ok(!ctx.operand(left)?.loosely_eq(&ctx.operand(right)?)),
165 Condition::Lt { left, right } => ctx.order("lt", left, right, |o| o == Ordering::Less),
166 Condition::Le { left, right } => ctx.order("le", left, right, |o| o != Ordering::Greater),
167 Condition::Gt { left, right } => ctx.order("gt", left, right, |o| o == Ordering::Greater),
168 Condition::Ge { left, right } => ctx.order("ge", left, right, |o| o != Ordering::Less),
169 Condition::In { item, set } => match ctx.operand(set)? {
170 Value::List(values) => {
171 let item = ctx.operand(item)?;
172 Ok(values.iter().any(|v| v.loosely_eq(&item)))
173 }
174 _ => Err(ConditionError::TypeMismatch(
175 "in: o conjunto precisa ser lista".to_string(),
176 )),
177 },
178 Condition::Exists { attr } => Ok(ctx.resolve(attr)?.is_some()),
179 Condition::All { of } => {
180 for cond in of {
181 if !cond.evaluate(ctx, registry)? {
182 return Ok(false);
183 }
184 }
185 Ok(true)
186 }
187 Condition::Any { of } => {
188 for cond in of {
189 if cond.evaluate(ctx, registry)? {
190 return Ok(true);
191 }
192 }
193 Ok(false)
194 }
195 Condition::Not { cond } => Ok(!cond.evaluate(ctx, registry)?),
196 Condition::Call { func, args } => {
197 let f = registry
198 .get(func)
199 .ok_or_else(|| ConditionError::UnknownFunction(func.clone()))?;
200 let values = args.iter().map(|a| ctx.operand(a)).collect::<Result<Vec<_>, _>>()?;
201 f(&values)
202 }
203 }
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
208pub enum ConditionError {
209 #[error("atributo ausente: {0}")]
210 MissingAttribute(String),
211 #[error("caminho de atributo inválido: {0}")]
212 BadPath(String),
213 #[error("tipos incompatíveis: {0}")]
214 TypeMismatch(String),
215 #[error("função não registrada: {0}")]
216 UnknownFunction(String),
217 #[error("{0}")]
218 Function(String),
219}
220
221#[derive(Clone, Copy)]
223pub struct EvalContext<'a> {
224 pub subject: &'a Subject,
225 pub resource: &'a Resource,
226 pub env: &'a Attributes,
227}
228
229impl EvalContext<'_> {
230 pub fn resolve(&self, path: &str) -> Result<Option<Value>, ConditionError> {
231 let (root, name) = path
232 .split_once('.')
233 .ok_or_else(|| ConditionError::BadPath(path.to_string()))?;
234 let value = match (root, name) {
235 ("subject", "id") => self.subject.id.clone().map(Value::Str),
236 ("subject", "kind") => Some(Value::Str(self.subject.kind.clone())),
237 ("subject", _) => self.subject.attrs.get(name).cloned(),
238 ("resource", "id") => self.resource.primary().and_then(|a| a.id.clone()).map(Value::Str),
239 ("resource", "kind") => self.resource.primary().map(|a| Value::Str(a.kind.clone())),
240 ("resource", _) => self.resource.attrs.get(name).cloned(),
241 ("env", _) => self.env.get(name).cloned(),
242 _ => return Err(ConditionError::BadPath(path.to_string())),
243 };
244 Ok(value)
245 }
246
247 fn operand(&self, operand: &Operand) -> Result<Value, ConditionError> {
248 match operand {
249 Operand::Lit(value) => Ok(value.clone()),
250 Operand::Attr { attr } => self
251 .resolve(attr)?
252 .ok_or_else(|| ConditionError::MissingAttribute(attr.clone())),
253 }
254 }
255
256 fn order(
257 &self,
258 op: &str,
259 left: &Operand,
260 right: &Operand,
261 accept: impl Fn(Ordering) -> bool,
262 ) -> Result<bool, ConditionError> {
263 let (l, r) = (self.operand(left)?, self.operand(right)?);
264 l.compare(&r)
265 .map(accept)
266 .ok_or_else(|| ConditionError::TypeMismatch(format!("{op}: {l:?} e {r:?} não se comparam")))
267 }
268}
269
270pub type ConditionFn = Arc<dyn Fn(&[Value]) -> Result<bool, ConditionError> + Send + Sync>;
271
272#[derive(Clone, Default)]
274pub struct ConditionRegistry {
275 fns: HashMap<String, ConditionFn>,
276}
277
278impl ConditionRegistry {
279 pub fn new() -> Self {
280 Self::default()
281 }
282
283 pub fn register(
284 mut self,
285 name: impl Into<String>,
286 f: impl Fn(&[Value]) -> Result<bool, ConditionError> + Send + Sync + 'static,
287 ) -> Self {
288 self.fns.insert(name.into(), Arc::new(f));
289 self
290 }
291
292 pub fn get(&self, name: &str) -> Option<&ConditionFn> {
293 self.fns.get(name)
294 }
295
296 pub fn contains(&self, name: &str) -> bool {
297 self.fns.contains_key(name)
298 }
299}
300
301impl fmt::Debug for ConditionRegistry {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 let mut names: Vec<_> = self.fns.keys().collect();
304 names.sort();
305 f.debug_struct("ConditionRegistry").field("fns", &names).finish()
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 fn eval(
314 cond: &Condition,
315 subject: &Subject,
316 resource: &Resource,
317 env: &Attributes,
318 ) -> Result<bool, ConditionError> {
319 let registry = ConditionRegistry::new().register("starts_with", |args| match args {
320 [Value::Str(s), Value::Str(prefix)] => Ok(s.starts_with(prefix.as_str())),
321 _ => Err(ConditionError::Function("starts_with(str, str)".to_string())),
322 });
323 cond.evaluate(&EvalContext { subject, resource, env }, ®istry)
324 }
325
326 #[test]
327 fn compares_subject_and_resource_attributes() {
328 let s = Subject::user("u").with_attr("clearance", 3);
329 let r = Resource::new("doc", "d").with_attr("level", 2);
330 let cond = Condition::ge(Operand::attr("subject.clearance"), Operand::attr("resource.level"));
331 assert!(eval(&cond, &s, &r, &Attributes::new()).unwrap());
332 }
333
334 #[test]
335 fn missing_attribute_is_an_error_but_exists_is_false() {
336 let s = Subject::user("u");
337 let r = Resource::new("doc", "d");
338 let env = Attributes::new();
339 let cond = Condition::eq(Operand::attr("subject.dept"), Operand::lit("eng"));
340 assert_eq!(
341 eval(&cond, &s, &r, &env),
342 Err(ConditionError::MissingAttribute("subject.dept".to_string()))
343 );
344 assert!(!eval(&Condition::exists("subject.dept"), &s, &r, &env).unwrap());
345 }
346
347 #[test]
348 fn in_and_custom_function() {
349 let s = Subject::user("u").with_attr("dept", "eng");
350 let r = Resource::new("doc", "draft-1");
351 let mut env = Attributes::new();
352 env.insert("depts".to_string(), Value::from(vec!["eng", "ops"]));
353 let cond = Condition::all([
354 Condition::is_in(Operand::attr("subject.dept"), Operand::attr("env.depts")),
355 Condition::call("starts_with", [Operand::attr("resource.id"), Operand::lit("draft")]),
356 ]);
357 assert!(eval(&cond, &s, &r, &env).unwrap());
358 assert_eq!(cond.functions(), ["starts_with"]);
359 }
360
361 #[test]
362 fn json_shape() {
363 let cond: Condition = serde_json::from_str(
364 r#"{"op":"any","of":[{"op":"eq","left":{"attr":"subject.id"},"right":"alice"},{"op":"not","cond":{"op":"exists","attr":"resource.locked"}}]}"#,
365 )
366 .unwrap();
367 let s = Subject::user("bob");
368 assert!(eval(&cond, &s, &Resource::new("doc", "d"), &Attributes::new()).unwrap());
369 }
370}