Skip to content

Commit

Permalink
added cst to est conversion
Browse files Browse the repository at this point in the history
Signed-off-by: Shaobo He <[email protected]>
  • Loading branch information
shaobo-he-aws committed Nov 27, 2024
1 parent ce31264 commit 07ed080
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 5 deletions.
71 changes: 71 additions & 0 deletions cedar-policy-core/src/est.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4485,6 +4485,77 @@ mod test {
);
}
}

#[test]
fn extended_has() {
let policy_text = r#"
permit(principal, action, resource) when
{ principal has a.b.c };"#;
let cst = parser::text_to_cst::parse_policy(policy_text).unwrap();
let est: Policy = cst.node.unwrap().try_into().unwrap();
assert_eq!(
est,
serde_json::from_value(json!({
"effect": "permit",
"principal": { "op": "All" },
"action": { "op": "All" },
"resource": { "op": "All" },
"conditions": [
{
"kind": "when",
"body": {
"&&": {
"left": {
"&&": {
"left": {
"has": {
"left": {
"Var": "principal",
},
"attr": "a"
}
},
"right": {
"has": {
"left": {
".": {
"left": {
"Var": "principal",
},
"attr": "a",
},
},
"attr": "b"
}
},
}
},
"right": {
"has": {
"left": {
".": {
"left": {
".": {
"left": {
"Var": "principal",
},
"attr": "a"
}
},
"attr": "b",
}
},
"attr": "c",
}
},
},
},
}
]
}))
.unwrap()
);
}
}

#[cfg(test)]
Expand Down
23 changes: 18 additions & 5 deletions cedar-policy-core/src/est/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use crate::parser::util::flatten_tuple_2;
use crate::parser::{Loc, Node};
use either::Either;
use itertools::Itertools;
use nonempty::nonempty;
use serde::{de::Visitor, Deserialize, Serialize};
use serde_with::serde_as;
use smol_str::{SmolStr, ToSmolStr};
Expand Down Expand Up @@ -1170,11 +1171,23 @@ impl TryFrom<&Node<Option<cst::Relation>>> for Expr {
Ok(expr)
}
cst::Relation::Has { target, field } => {
let target_expr = target.try_into()?;
field
.to_expr_or_special()?
.into_valid_attr()
.map(|attr| Expr::has_attr(target_expr, attr))
let target_expr: Expr = target.try_into()?;
let attrs = match field.to_has_rhs()? {
Either::Left(attr) => nonempty![attr],
Either::Right(ids) => ids.map(|id| id.to_smolstr()),
};
let (first, rest) = attrs.split_first();
let has_expr = Expr::has_attr(target_expr.clone(), first.clone());
let get_expr = Expr::get_attr(target_expr, first.clone());
Ok(rest
.iter()
.fold((has_expr, get_expr), |(has_expr, get_expr), attr| {
(
Expr::and(has_expr, Expr::has_attr(get_expr.clone(), attr.to_owned())),
Expr::get_attr(get_expr, attr.to_owned()),
)
})
.0)
}
cst::Relation::Like { target, pattern } => {
let target_expr = target.try_into()?;
Expand Down

0 comments on commit 07ed080

Please sign in to comment.