Skip to main content

cedar_policy_cli/command/
evaluate.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 cedar_policy::{eval_expression, Entities, EvalResult, Expression};
18use clap::Args;
19use miette::WrapErr;
20use std::str::FromStr;
21
22use crate::{load_entities, CedarExitCode, OptionalSchemaArgs, RequestArgs};
23
24#[derive(Args, Debug)]
25pub struct EvaluateArgs {
26    /// Request args (incorporated by reference)
27    #[command(flatten)]
28    pub request: RequestArgs,
29    /// Schema args (incorporated by reference)
30    ///
31    /// Used to populate the store with action entities and for schema-based
32    /// parsing of entity hierarchy, if present
33    #[command(flatten)]
34    pub schema: OptionalSchemaArgs,
35    /// File containing JSON representation of the Cedar entity hierarchy.
36    /// This is optional; if not present, we'll just use the action entities
37    /// from the schema, or an empty hierarchy if there is no schema.
38    #[arg(long = "entities", value_name = "FILE")]
39    pub entities_file: Option<String>,
40    /// Expression to evaluate
41    #[arg(value_name = "EXPRESSION")]
42    pub expression: String,
43}
44
45pub fn evaluate(args: &EvaluateArgs) -> (CedarExitCode, EvalResult) {
46    println!();
47    let schema = match args.schema.get_schema() {
48        Ok(opt) => opt,
49        Err(e) => {
50            println!("{e:?}");
51            return (CedarExitCode::Failure, EvalResult::Bool(false));
52        }
53    };
54    let request = match args.request.get_request(schema.as_ref()) {
55        Ok(q) => q,
56        Err(e) => {
57            println!("{e:?}");
58            return (CedarExitCode::Failure, EvalResult::Bool(false));
59        }
60    };
61    let expr =
62        match Expression::from_str(&args.expression).wrap_err("failed to parse the expression") {
63            Ok(expr) => expr,
64            Err(e) => {
65                println!("{:?}", e.with_source_code(args.expression.clone()));
66                return (CedarExitCode::Failure, EvalResult::Bool(false));
67            }
68        };
69    let entities = match (&args.entities_file, schema.as_ref()) {
70        (Some(file), schema) => load_entities(file, schema),
71        (None, Some(schema)) => schema
72            .action_entities()
73            .wrap_err("failed to get the action entities from the schema"),
74        (None, None) => Ok(Entities::empty()),
75    };
76    let entities = match entities {
77        Ok(entities) => entities,
78        Err(e) => {
79            println!("{e:?}");
80            return (CedarExitCode::Failure, EvalResult::Bool(false));
81        }
82    };
83    match eval_expression(&request, &entities, &expr).wrap_err("failed to evaluate the expression")
84    {
85        Err(e) => {
86            println!("{e:?}");
87            (CedarExitCode::Failure, EvalResult::Bool(false))
88        }
89        Ok(result) => {
90            println!("{result}");
91            (CedarExitCode::Success, result)
92        }
93    }
94}