Skip to main content

cedar_policy_core/est/
err.rs

1/*
2 * Copyright Cedar Contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::sync::Arc;
18
19use crate::ast;
20use crate::ast::PolicySetError;
21use crate::entities::JsonDeserializationError;
22use crate::parser::err::{parse_errors, ParseErrors};
23use crate::parser::{join_with_conjunction, unescape};
24use miette::Diagnostic;
25use nonempty::NonEmpty;
26use smol_str::SmolStr;
27use thiserror::Error;
28
29/// Errors arising while converting a policy from its JSON representation (aka EST) into an AST
30#[derive(Debug, Diagnostic, Error)]
31pub enum FromJsonError {
32    /// Error while deserializing JSON
33    #[error(transparent)]
34    #[diagnostic(transparent)]
35    JsonDeserializationError(#[from] JsonDeserializationError),
36    /// Tried to convert an EST representing a template to an AST representing a static policy
37    #[error(transparent)]
38    #[diagnostic(transparent)]
39    TemplateToPolicy(#[from] parse_errors::ExpectedStaticPolicy),
40    /// Tried to convert an EST representing a static policy to an AST representing a template
41    #[error(transparent)]
42    #[diagnostic(transparent)]
43    PolicyToTemplate(#[from] parse_errors::ExpectedTemplate),
44    /// Slot name was not valid for the position it was used in. (Currently, principal slots must
45    /// be named `?principal`, and resource slots must be named `?resource`.)
46    #[error("invalid slot name or slot used in wrong position")]
47    #[diagnostic(help(
48        "principal slots must be named `?principal` and resource slots must be named `?resource`"
49    ))]
50    InvalidSlotName,
51    /// EST contained a template slot for `action`. This is not currently allowed
52    #[error("slots are not allowed for actions")]
53    ActionSlot,
54    /// EST contained a template slot in policy condition
55    #[error("found template slot {slot} in a `{clausetype}` clause")]
56    #[diagnostic(help("slots are currently unsupported in `{clausetype}` clauses"))]
57    SlotsInConditionClause {
58        /// Slot that was found in a when/unless clause
59        slot: ast::SlotId,
60        /// Clause type, e.g. "when" or "unless"
61        clausetype: &'static str,
62    },
63    /// EST contained the empty JSON object `{}` where a key (operator) was expected
64    #[error("missing operator, found empty object")]
65    MissingOperator,
66    /// EST contained an object with multiple keys (operators) where a single operator was expected
67    #[error("found multiple operators where one was expected: {ops:?}")]
68    MultipleOperators {
69        /// the multiple operators that were found where one was expected
70        ops: Vec<SmolStr>,
71    },
72    /// At most one of the operands in `a * b * c * d * ...` can be a non-{constant int}
73    #[error(
74        "multiplication must be by a constant int: neither `{arg1}` nor `{arg2}` is a constant"
75    )]
76    MultiplicationByNonConstant {
77        /// First non-constant argument
78        arg1: ast::Expr,
79        /// Second non-constant argument
80        arg2: ast::Expr,
81    },
82    /// Error thrown while processing string escapes
83    // show just the first error in the main error message, like in [`ParseErrors`]; see #326 and discussion on #477
84    #[error("{}", match .0.first() { Some(err) => format!("{err}"), None => "invalid escape".into() })]
85    UnescapeError(#[related] Vec<unescape::UnescapeError>),
86    /// Error reported when the entity type tested by an `is` expression cannot be parsed.
87    #[error("invalid entity type: {0}")]
88    #[diagnostic(transparent)]
89    InvalidEntityType(ParseErrors),
90    /// Error reported when a policy set has duplicate ids
91    #[error("Error creating policy set: {0}")]
92    #[diagnostic(transparent)]
93    PolicySet(#[from] PolicySetError),
94    /// Error reported when attempting to create a template-link
95    #[error("Error linking policy set: {0}")]
96    #[diagnostic(transparent)]
97    Linking(#[from] ast::LinkingError),
98    /// Error reported when the extension function name is unknown
99    #[error("Invalid extension function name: `{0}`")]
100    UnknownExtFunc(ast::Name),
101    /// Returned when an Entity UID used as an action does not have the type `Action`
102    #[error(transparent)]
103    #[diagnostic(transparent)]
104    InvalidActionType(#[from] InvalidActionType),
105}
106
107/// Details about an `InvalidActionType` error.
108#[derive(Debug, Diagnostic, Error)]
109#[diagnostic(help("action entities must have type `Action`, optionally in a namespace"))]
110pub struct InvalidActionType {
111    pub(crate) euids: NonEmpty<Arc<crate::ast::EntityUID>>,
112}
113
114impl std::fmt::Display for InvalidActionType {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        write!(
117            f,
118            "expected that action entity uids would have the type `Action` but got "
119        )?;
120        join_with_conjunction(f, "and", self.euids.iter(), |f, e| write!(f, "`{e}`"))
121    }
122}
123
124/// Errors while instantiating a policy
125#[derive(Debug, PartialEq, Diagnostic, Error)]
126pub enum InstantiationError {
127    /// Template contains this slot, but a value wasn't provided for it
128    #[error("failed to instantiate template: no value provided for `{slot}`")]
129    MissedSlot {
130        /// Slot which didn't have a value provided for it
131        slot: ast::SlotId,
132    },
133}
134
135impl From<ast::UnexpectedSlotError> for FromJsonError {
136    fn from(err: ast::UnexpectedSlotError) -> Self {
137        Self::TemplateToPolicy(err.into())
138    }
139}