Skip to content

Commit d3658b6

Browse files
Add get_entity_literals to api.rs (#1149)
Signed-off-by: Andrew Wells <[email protected]>
1 parent 6c3811e commit d3658b6

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

cedar-policy/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Cedar Language Version: TBD
1414

1515
### Added
1616

17+
- Added `get_entity_literals` API (#1149).
1718
- Implemented [RFC 82](https://github.com/cedar-policy/rfcs/pull/82), adding
1819
entity tags to the Cedar language under experimental flag `entity-tags` (#1204, #1207, more coming)
1920
- Implemented [RFC 74](https://github.com/cedar-policy/rfcs/pull/74): A new experimental API (`compute_entity_manifest`)

cedar-policy/src/api.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2919,6 +2919,23 @@ impl Policy {
29192919
get_valid_request_envs(self.ast.template(), s)
29202920
}
29212921

2922+
/// Get all entity literals occuring in a `Policy`
2923+
pub fn entity_literals(&self) -> Vec<EntityUid> {
2924+
self.ast
2925+
.condition()
2926+
.subexpressions()
2927+
.filter_map(|e| match e.expr_kind() {
2928+
cedar_policy_core::ast::ExprKind::Lit(l) => match l {
2929+
cedar_policy_core::ast::Literal::EntityUID(euid) => {
2930+
Some(EntityUid((*euid).as_ref().clone()))
2931+
}
2932+
_ => None,
2933+
},
2934+
_ => None,
2935+
})
2936+
.collect()
2937+
}
2938+
29222939
fn from_est(id: Option<PolicyId>, est: est::Policy) -> Result<Self, PolicyFromJsonError> {
29232940
Ok(Self {
29242941
ast: est.clone().try_into_ast_policy(id.map(PolicyId::into))?,

cedar-policy/src/tests.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5715,3 +5715,29 @@ mod context_tests {
57155715
);
57165716
}
57175717
}
5718+
5719+
mod policy_manipulation_functions_tests {
5720+
use super::*;
5721+
5722+
#[test]
5723+
fn empty_policy() {
5724+
let policy_str = r###"permit(principal, action, resource);
5725+
"###;
5726+
let policy = Policy::from_str(policy_str).expect("should succeed");
5727+
assert_eq!(policy.entity_literals(), vec![]);
5728+
}
5729+
5730+
#[test]
5731+
fn non_empty_policy() {
5732+
let policy_str = r###"permit(principal == User::"Bob", action == Action::"view", resource) when {
5733+
!resource.private && resource.owner != User::"Alice"
5734+
};
5735+
"###;
5736+
let policy = Policy::from_str(policy_str).expect("should succeed");
5737+
let res = policy.entity_literals();
5738+
assert_eq!(res.len(), 3);
5739+
assert!(res.contains(&EntityUid::from_str("User::\"Bob\"").expect("should parse")));
5740+
assert!(res.contains(&EntityUid::from_str("Action::\"view\"").expect("should parse")));
5741+
assert!(res.contains(&EntityUid::from_str("User::\"Alice\"").expect("should parse")));
5742+
}
5743+
}

0 commit comments

Comments
 (0)