pub mod cst;
mod cst_to_ast;
pub mod err;
mod fmt;
mod loc;
pub use loc::Loc;
mod node;
pub use node::Node;
pub mod text_to_cst;
pub mod unescape;
use smol_str::SmolStr;
use std::collections::HashMap;
use crate::ast;
use crate::ast::RestrictedExprParseError;
use crate::est;
pub fn parse_policyset(text: &str) -> Result<ast::PolicySet, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_policies(text)?;
let Some(ast) = cst.to_policyset(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub fn parse_policyset_and_also_return_policy_text(
text: &str,
) -> Result<(HashMap<ast::PolicyID, &str>, ast::PolicySet), err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_policies(text)?;
let Some(pset) = cst.to_policyset(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
#[allow(clippy::expect_used)]
#[allow(clippy::indexing_slicing)]
let texts = cst
.with_generated_policyids()
.expect("shouldn't be None since parse_policies() and to_policyset() didn't return Err")
.map(|(id, policy)| (id, &text[policy.loc.start()..policy.loc.end()]))
.collect::<HashMap<ast::PolicyID, &str>>();
Ok((texts, pset))
} else {
Err(errs)
}
}
pub fn parse_policyset_to_ests_and_pset(
text: &str,
) -> Result<(HashMap<ast::PolicyID, est::Policy>, ast::PolicySet), err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_policies(text)?;
let Some(pset) = cst.to_policyset(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
#[allow(clippy::expect_used)]
let ests = cst
.with_generated_policyids()
.expect("missing policy set node")
.map(|(id, policy)| {
let p = policy.node.as_ref().expect("missing policy node").clone();
Ok((id, p.try_into()?))
})
.collect::<Result<HashMap<ast::PolicyID, est::Policy>, err::ParseErrors>>()?;
Ok((ests, pset))
} else {
Err(errs)
}
}
pub fn parse_policy_template(
id: Option<String>,
text: &str,
) -> Result<ast::Template, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let id = match id {
Some(id) => ast::PolicyID::from_string(id),
None => ast::PolicyID::from_string("policy0"),
};
let cst = text_to_cst::parse_policy(text)?;
let Some(ast) = cst.to_policy_template(id, &mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub fn parse_policy_template_to_est_and_ast(
id: Option<String>,
text: &str,
) -> Result<(est::Policy, ast::Template), err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let id = match id {
Some(id) => ast::PolicyID::from_string(id),
None => ast::PolicyID::from_string("policy0"),
};
let cst = text_to_cst::parse_policy(text)?;
let (Some(ast), Some(cst_node)) = (cst.to_policy_template(id, &mut errs), cst.node) else {
return Err(errs);
};
if errs.is_empty() {
let est = cst_node.try_into()?;
Ok((est, ast))
} else {
Err(errs)
}
}
pub fn parse_policy(id: Option<String>, text: &str) -> Result<ast::StaticPolicy, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let id = match id {
Some(id) => ast::PolicyID::from_string(id),
None => ast::PolicyID::from_string("policy0"),
};
let cst = text_to_cst::parse_policy(text)?;
let Some(ast) = cst.to_policy(id, &mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub fn parse_policy_to_est_and_ast(
id: Option<String>,
text: &str,
) -> Result<(est::Policy, ast::StaticPolicy), err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let id = match id {
Some(id) => ast::PolicyID::from_string(id),
None => ast::PolicyID::from_string("policy0"),
};
let cst = text_to_cst::parse_policy(text)?;
let (Some(ast), Some(cst_node)) = (cst.to_policy(id, &mut errs), cst.node) else {
return Err(errs);
};
if errs.is_empty() {
let est = cst_node.try_into()?;
Ok((est, ast))
} else {
Err(errs)
}
}
pub fn parse_policy_or_template_to_est(text: &str) -> Result<est::Policy, err::ParseErrors> {
let cst = text_to_cst::parse_policy(text)?;
#[allow(clippy::expect_used)]
let cst_node = cst.node.expect("missing policy or template node");
cst_node.try_into()
}
pub(crate) fn parse_expr(ptext: &str) -> Result<ast::Expr, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_expr(ptext)?;
let Some(ast) = cst.to_expr(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub(crate) fn parse_restrictedexpr(
ptext: &str,
) -> Result<ast::RestrictedExpr, RestrictedExprParseError> {
let expr = parse_expr(ptext)?;
Ok(ast::RestrictedExpr::new(expr)?)
}
pub(crate) fn parse_euid(euid: &str) -> Result<ast::EntityUID, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_ref(euid)?;
let Some(ast) = cst.to_ref(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub(crate) fn parse_name(name: &str) -> Result<ast::Name, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_name(name)?;
let Some(ast) = cst.to_name(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub(crate) fn parse_literal(val: &str) -> Result<ast::Literal, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_primary(val)?;
let Some(ast) = cst.to_expr(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
match ast.into_expr_kind() {
ast::ExprKind::Lit(v) => Ok(v),
_ => Err(
err::ParseError::ParseLiteral(err::ParseLiteralError::ParseLiteral(
val.to_string(),
))
.into(),
),
}
} else {
Err(errs)
}
}
pub fn parse_internal_string(val: &str) -> Result<SmolStr, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_primary(&format!(r#""{val}""#))?;
let Some(ast) = cst.to_string_literal(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub(crate) fn parse_ident(id: &str) -> Result<ast::Id, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_ident(id)?;
let Some(ast) = cst.to_valid_ident(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
pub(crate) fn parse_anyid(id: &str) -> Result<ast::AnyId, err::ParseErrors> {
let mut errs = err::ParseErrors::new();
let cst = text_to_cst::parse_ident(id)?;
let Some(ast) = cst.to_any_ident(&mut errs) else {
return Err(errs);
};
if errs.is_empty() {
Ok(ast)
} else {
Err(errs)
}
}
#[cfg(test)]
pub(crate) mod test_utils {
use super::err::ParseErrors;
use crate::test_utils::*;
#[track_caller] pub fn expect_some_error_matches(
src: &str,
errs: &ParseErrors,
msg: &ExpectedErrorMessage<'_>,
) {
assert!(
!errs.is_empty(),
"for the following input:\n{src}\nexpected an error, but the `ParseErrors` was empty"
);
assert!(
errs.iter().any(|e| msg.matches(e)),
"for the following input:\n{src}\nexpected some error to match the following:\n{msg}\nbut actual errors were:\n{:?}", miette::Report::new(errs.clone()),
);
}
#[track_caller] pub fn expect_exactly_one_error(src: &str, errs: &ParseErrors, msg: &ExpectedErrorMessage<'_>) {
match errs.len() {
0 => panic!("for the following input:\n{src}\nexpected an error, but the `ParseErrors` was empty"),
1 => {
let err = errs.iter().next().expect("already checked that len was 1");
assert!(
msg.matches(err),
"for the following input:\n{src}\nexpected the error to match the following:\n{msg}\nbut actual error was:\n{:?}", miette::Report::new(err.clone()),
)
}
n => panic!(
"for the following input:\n{src}\nexpected only one error, but got {n}. Expected to match the following:\n{msg}\nbut actual errors were:\n{:?}", miette::Report::new(errs.clone()),
)
}
}
}
#[allow(clippy::panic)]
#[cfg(test)]
mod test {
use super::*;
use crate::ast::{test_generators::*, Template};
use cool_asserts::assert_matches;
use std::collections::HashSet;
#[test]
fn test_template_parsing() {
for template in all_templates().map(Template::from) {
let id = template.id();
let src = format!("{template}");
let parsed = parse_policy_template(Some(id.to_string()), &src).unwrap();
assert_eq!(
parsed.slots().collect::<HashSet<_>>(),
template.slots().collect::<HashSet<_>>()
);
assert_eq!(parsed.id(), template.id());
assert_eq!(parsed.effect(), template.effect());
assert_eq!(
parsed.principal_constraint(),
template.principal_constraint()
);
assert_eq!(parsed.action_constraint(), template.action_constraint());
assert_eq!(parsed.resource_constraint(), template.resource_constraint());
assert!(
parsed
.non_head_constraints()
.eq_shape(template.non_head_constraints()),
"{:?} and {:?} should have the same shape.",
parsed.non_head_constraints(),
template.non_head_constraints()
);
}
}
#[test]
fn test_error_out() {
assert_matches!(parse_policyset(
r#"
permit(principal:p,action:a,resource:r)
when{w or if c but not z} // expr error
unless{u if c else d or f} // expr error
advice{"doit"};
permit(principality in Group::"jane_friends", // policy error
action in [PhotoOp::"view", PhotoOp::"comment"],
resource in Album::"jane_trips");
forbid(principal, action, resource)
when { "private" in resource.tags }
unless { resource in principal.account };
"#,
), Err(e) => assert!(e.len() >= 3, "expected at least 3 errors, but actual errors were:\n{:?}", miette::Report::new(e)) );
}
}
#[cfg(test)]
mod eval_tests {
use super::err::{ParseErrors, ToASTErrorKind};
use super::*;
use crate::evaluator as eval;
use crate::extensions::Extensions;
use crate::parser::err::ParseError;
use std::sync::Arc;
#[test]
fn entity_literals1() {
let src = r#"Test::{ test : "Test" }"#;
let ParseErrors(errs) = parse_euid(src).err().unwrap();
assert_eq!(errs.len(), 1);
let expected = ToASTErrorKind::UnsupportedEntityLiterals;
assert!(errs
.iter()
.any(|e| matches!(e, ParseError::ToAST(e) if e.kind() == &expected)));
}
#[test]
fn entity_literals2() {
let src = r#"permit(principal == Test::{ test : "Test" }, action, resource);"#;
let ParseErrors(errs) = parse_policy(None, src).err().unwrap();
assert_eq!(errs.len(), 1);
let expected = ToASTErrorKind::UnsupportedEntityLiterals;
assert!(errs
.iter()
.any(|e| matches!(e, ParseError::ToAST(e) if e.kind() == &expected)));
}
#[test]
fn interpret_exprs() {
let request = eval::test::basic_request();
let entities = eval::test::basic_entities();
let exts = Extensions::none();
let evaluator = eval::Evaluator::new(request, &entities, &exts);
let src = "false";
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(false));
assert_eq!(val.source_loc(), Some(&Loc::new(0..5, Arc::from(src))));
let src = "true && true";
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(0..12, Arc::from(src))));
let src = "!true || false && !true";
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(false));
assert_eq!(val.source_loc(), Some(&Loc::new(0..23, Arc::from(src))));
let src = "!!!!true";
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(0..8, Arc::from(src))));
let src = r#"
if false || true != 4 then
600
else
-200
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(600));
assert_eq!(val.source_loc(), Some(&Loc::new(9..81, Arc::from(src))));
}
#[test]
fn interpret_membership() {
let request = eval::test::basic_request();
let entities = eval::test::rich_entities();
let exts = Extensions::none();
let evaluator = eval::Evaluator::new(request, &entities, &exts);
let src = r#"
test_entity_type::"child" in
test_entity_type::"unrelated"
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(false));
assert_eq!(val.source_loc(), Some(&Loc::new(10..80, Arc::from(src))));
assert_eq!(
val.source_loc().unwrap().snippet(),
Some(
r#"test_entity_type::"child" in
test_entity_type::"unrelated""#
)
);
let src = r#"
test_entity_type::"child" in
test_entity_type::"child"
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(10..76, Arc::from(src))));
assert_eq!(
val.source_loc().unwrap().snippet(),
Some(
r#"test_entity_type::"child" in
test_entity_type::"child""#
)
);
let src = r#"
other_type::"other_child" in
test_entity_type::"parent"
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(10..77, Arc::from(src))));
assert_eq!(
val.source_loc().unwrap().snippet(),
Some(
r#"other_type::"other_child" in
test_entity_type::"parent""#
)
);
let src = r#"
test_entity_type::"child" in
test_entity_type::"grandparent"
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(10..82, Arc::from(src))));
assert_eq!(
val.source_loc().unwrap().snippet(),
Some(
r#"test_entity_type::"child" in
test_entity_type::"grandparent""#
)
);
}
#[test]
fn interpret_relation() {
let request = eval::test::basic_request();
let entities = eval::test::basic_entities();
let exts = Extensions::none();
let evaluator = eval::Evaluator::new(request, &entities, &exts);
let src = r#"
3 < 2 || 2 > 3
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(false));
assert_eq!(val.source_loc(), Some(&Loc::new(14..28, Arc::from(src))));
assert_eq!(val.source_loc().unwrap().snippet(), Some("3 < 2 || 2 > 3"));
let src = r#"
7 <= 7 && 4 != 5
"#;
let expr = parse_expr(src).unwrap();
let val = evaluator.interpret_inline_policy(&expr).unwrap();
assert_eq!(val, ast::Value::from(true));
assert_eq!(val.source_loc(), Some(&Loc::new(14..30, Arc::from(src))));
assert_eq!(
val.source_loc().unwrap().snippet(),
Some("7 <= 7 && 4 != 5")
);
}
}
#[cfg(test)]
mod parse_tests {
use super::test_utils::*;
use super::*;
use crate::test_utils::*;
use cool_asserts::assert_matches;
use miette::Diagnostic;
#[test]
fn parse_exists() {
let result = parse_policyset(
r#"
permit(principal, action, resource)
when{ true };
"#,
);
assert!(!result.expect("parse error").is_empty());
}
#[test]
fn test_parse_policyset() {
use crate::ast::PolicyID;
let multiple_policies = r#"
permit(principal, action, resource)
when { principal == resource.owner };
forbid(principal, action == Action::"modify", resource) // a comment
when { resource . highSecurity }; // intentionally not conforming to our formatter
"#;
let pset = parse_policyset(multiple_policies).expect("Should parse");
assert_eq!(pset.policies().count(), 2);
assert_eq!(pset.static_policies().count(), 2);
let (texts, pset) =
parse_policyset_and_also_return_policy_text(multiple_policies).expect("Should parse");
assert_eq!(pset.policies().count(), 2);
assert_eq!(pset.static_policies().count(), 2);
assert_eq!(texts.len(), 2);
assert_eq!(
texts.get(&PolicyID::from_string("policy0")),
Some(
&r#"permit(principal, action, resource)
when { principal == resource.owner };"#
)
);
assert_eq!(
texts.get(&PolicyID::from_string("policy1")),
Some(
&r#"forbid(principal, action == Action::"modify", resource) // a comment
when { resource . highSecurity };"#
)
);
}
#[test]
fn test_parse_string() {
assert_eq!(
ast::Eid::new(parse_internal_string(r"a\nblock\nid").expect("should parse"))
.to_string(),
r"a\nblock\nid",
);
parse_internal_string(r#"oh, no, a '! "#).expect("single quote should be fine");
parse_internal_string(r#"oh, no, a "! "#).expect_err("double quote not allowed");
parse_internal_string(r#"oh, no, a \"! and a \'! "#).expect("escaped quotes should parse");
}
#[test]
fn good_cst_bad_ast() {
let src = r#"
permit(principal, action, resource) when { principal.name.like == "3" };
"#;
let p = parse_policyset_to_ests_and_pset(src);
assert_matches!(p, Err(e) => expect_err(src, &e, &ExpectedErrorMessage::error("this identifier is reserved and cannot be used: `like`")));
}
#[test]
fn no_slots_in_condition() {
let src = r#"
permit(principal, action, resource) when {
resource == ?resource
};
"#;
let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?resource in a `when` clause",
"slots are currently unsupported in `when` clauses",
);
let unexpected_template = ExpectedErrorMessage::error_and_help(
"expected a static policy, got a template containing the slot ?resource",
"try removing the template slot(s) from this policy",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
let src = r#"
permit(principal, action, resource) when {
resource == ?principal
};
"#;
let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?principal in a `when` clause",
"slots are currently unsupported in `when` clauses",
);
let unexpected_template = ExpectedErrorMessage::error_and_help(
"expected a static policy, got a template containing the slot ?principal",
"try removing the template slot(s) from this policy",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
});
let src = r#"
permit(principal, action, resource) when {
resource == ?blah
};
"#;
let error = ExpectedErrorMessage::error_and_help(
"`?blah` is not a valid template slot",
"a template slot may only be `?principal` or `?resource`",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
let src = r#"
permit(principal, action, resource) unless {
resource == ?resource
};
"#;
let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?resource in a `unless` clause",
"slots are currently unsupported in `unless` clauses",
);
let unexpected_template = ExpectedErrorMessage::error_and_help(
"expected a static policy, got a template containing the slot ?resource",
"try removing the template slot(s) from this policy",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
let src = r#"
permit(principal, action, resource) unless {
resource == ?principal
};
"#;
let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?principal in a `unless` clause",
"slots are currently unsupported in `unless` clauses",
);
let unexpected_template = ExpectedErrorMessage::error_and_help(
"expected a static policy, got a template containing the slot ?principal",
"try removing the template slot(s) from this policy",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
let src = r#"
permit(principal, action, resource) unless {
resource == ?blah
};
"#;
let error = ExpectedErrorMessage::error_and_help(
"`?blah` is not a valid template slot",
"a template slot may only be `?principal` or `?resource`",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &error);
});
let src = r#"
permit(principal, action, resource) unless {
resource == ?resource
} when {
resource == ?resource
};
"#;
let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?resource in a `when` clause",
"slots are currently unsupported in `when` clauses",
);
let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
"found template slot ?resource in a `unless` clause",
"slots are currently unsupported in `unless` clauses",
);
let unexpected_template = ExpectedErrorMessage::error_and_help(
"expected a static policy, got a template containing the slot ?resource",
"try removing the template slot(s) from this policy",
);
assert_matches!(parse_policy(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
expect_some_error_matches(src, &e, &unexpected_template);
});
assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
expect_some_error_matches(src, &e, &slot_in_when_clause);
expect_some_error_matches(src, &e, &slot_in_unless_clause);
});
}
#[test]
fn record_literals() {
let src = r#"permit(principal, action, resource) when { context.foo == { foo: 2, bar: "baz" } };"#;
assert_matches!(parse_policy(None, src), Ok(_));
let src = r#"permit(principal, action, resource) when { context.foo == { "foo": 2, "hi mom it's 🦀": "baz" } };"#;
assert_matches!(parse_policy(None, src), Ok(_));
let src = r#"permit(principal, action, resource) when { context.foo == { "spam": -341, foo: 2, "🦀": true, foo: "baz" } };"#;
assert_matches!(parse_policy(None, src), Err(e) => {
expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate key `foo` in record literal"));
});
}
#[test]
fn annotation_errors() {
let src = r#"
@foo("1")
@foo("2")
permit(principal, action, resource);
"#;
assert_matches!(parse_policy(None, src), Err(e) => {
expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
let expected_span = 35..44;
assert_eq!(&src[expected_span.clone()], r#"@foo("2")"#);
itertools::assert_equal(e.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
});
let src = r#"
@foo("1")
@foo("1")
permit(principal, action, resource);
"#;
assert_matches!(parse_policy(None, src), Err(e) => {
expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
let expected_span = 35..44;
assert_eq!(&src[expected_span.clone()], r#"@foo("1")"#);
itertools::assert_equal(e.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
});
let src = r#"
@foo("1")
@bar("yellow")
@foo("abc")
@hello("goodbye")
@bar("123")
@foo("def")
permit(principal, action, resource);
"#;
assert_matches!(parse_policy(None, src), Err(e) => {
assert_eq!(e.len(), 3); expect_some_error_matches(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
expect_some_error_matches(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @bar"));
for ((err, expected_span), expected_snippet) in e.iter().zip([62..73, 116..127, 140..151]).zip([r#"@foo("abc")"#, r#"@bar("123")"#, r#"@foo("def")"#]) {
assert_eq!(&src[expected_span.clone()], expected_snippet);
itertools::assert_equal(err.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
}
})
}
}