Skip to content

Commit

Permalink
expose Template json syntax converters (#458)
Browse files Browse the repository at this point in the history
Co-authored-by: Victor Moreno <[email protected]>
  • Loading branch information
Swolebrain and Victor Moreno authored Nov 22, 2023
1 parent 13e3eed commit 019a9ab
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
1 change: 1 addition & 0 deletions cedar-policy/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Marked the `Template::from_json` and `Template::to_json` apis as public
- New APIs to `Entities` to make it easy to add a collection of entities to an
existing `Entities` structure. (#276)
- Export the `cedar_policy_core::evaluator::{EvaluationError, EvaluationErrorKind}` and
Expand Down
6 changes: 2 additions & 4 deletions cedar-policy/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2298,8 +2298,7 @@ impl Template {
/// If `id` is Some, the policy will be given that Policy Id.
/// If `id` is None, then "JSON policy" will be used.
/// The behavior around None may change in the future.
#[allow(dead_code)] // planned to be a public method in the future
fn from_json(
pub fn from_json(
id: Option<PolicyId>,
json: serde_json::Value,
) -> Result<Self, cedar_policy_core::est::FromJsonError> {
Expand All @@ -2312,8 +2311,7 @@ impl Template {
}

/// Get the JSON representation of this `Template`.
#[allow(dead_code)] // planned to be a public method in the future
fn to_json(&self) -> Result<serde_json::Value, impl std::error::Error> {
pub fn to_json(&self) -> Result<serde_json::Value, impl std::error::Error> {
let est = self.lossless.est()?;
let json = serde_json::to_value(est)?;
Ok::<_, PolicyToJsonError>(json)
Expand Down
25 changes: 25 additions & 0 deletions cedar-policy/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2726,3 +2726,28 @@ mod schema_based_parsing_tests {
);
}
}

mod template_tests {
use crate::Template;

#[test]
fn test_policy_template_to_json() {
let template = Template::parse(
None,
"permit(principal == ?principal, action, resource in ?resource);",
);
assert_eq!(
template.unwrap().to_json().unwrap().to_string(),
r#"{"effect":"permit","principal":{"op":"==","slot":"?principal"},"action":{"op":"All"},"resource":{"op":"in","slot":"?resource"},"conditions":[]}"#
);
}

#[test]
fn test_policy_template_from_json() {
let template = Template::from_json(None, serde_json::from_str(r#"{"effect":"permit","principal":{"op":"==","slot":"?principal"},"action":{"op":"All"},"resource":{"op":"in","slot":"?resource"},"conditions":[]}"#).unwrap());
assert_eq!(
template.unwrap().to_string(),
"permit(principal == ?principal, action, resource in ?resource);".to_string()
);
}
}

0 comments on commit 019a9ab

Please sign in to comment.