-
Notifications
You must be signed in to change notification settings - Fork 143
Split CLI lib.rs into modules
#2290
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /* | ||
| * Copyright Cedar Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| use clap::Subcommand; | ||
|
|
||
| mod authorize; | ||
| pub use authorize::*; | ||
| mod evaluate; | ||
| pub use evaluate::*; | ||
| mod validate; | ||
| pub use validate::*; | ||
| mod check_parse; | ||
| pub use check_parse::*; | ||
| mod symcc; | ||
| pub use symcc::*; | ||
| mod tpe; | ||
| pub use tpe::*; | ||
| mod partial_eval; | ||
| pub use partial_eval::*; | ||
| mod run_test; | ||
| pub use run_test::*; | ||
| mod link; | ||
| pub use link::*; | ||
| mod format; | ||
| pub use format::*; | ||
| mod translate_policy; | ||
| pub use translate_policy::*; | ||
| mod translate_schema; | ||
| pub use translate_schema::*; | ||
| mod visualize; | ||
| pub use visualize::*; | ||
| mod new; | ||
| pub use new::*; | ||
| mod language_version; | ||
| pub use language_version::*; | ||
|
|
||
| #[derive(Subcommand, Debug)] | ||
| pub enum Commands { | ||
| /// Evaluate an authorization request | ||
| Authorize(AuthorizeArgs), | ||
| /// Evaluate a Cedar expression | ||
| Evaluate(EvaluateArgs), | ||
| /// Validate a policy set against a schema | ||
| Validate(ValidateArgs), | ||
| /// Check that policies, expressions, schema, and/or entities successfully parse. | ||
| /// (All arguments are optional; this checks that whatever is provided parses) | ||
| /// | ||
| /// If no arguments are provided, reads policies from stdin and checks that they parse. | ||
| CheckParse(CheckParseArgs), | ||
| /// Link a template | ||
| Link(LinkArgs), | ||
| /// Format a policy set | ||
| Format(FormatArgs), | ||
| /// Translate Cedar policy syntax to JSON policy syntax (except comments) | ||
| TranslatePolicy(TranslatePolicyArgs), | ||
| /// Translate Cedar schema syntax to JSON schema syntax and vice versa (except comments) | ||
| TranslateSchema(TranslateSchemaArgs), | ||
| /// Visualize a set of JSON entities to the graphviz format. | ||
| /// Warning: Entity visualization is best-effort and not well tested. | ||
| Visualize(VisualizeArgs), | ||
| /// Create a Cedar project | ||
| New(NewArgs), | ||
| /// Partially evaluate an authorization request | ||
| PartiallyAuthorize(PartiallyAuthorizeArgs), | ||
| /// Partially evaluate an authorization request in a type-aware manner | ||
| Tpe(TpeArgs), | ||
| /// Run test cases on a policy set | ||
| /// | ||
| /// Tests are defined in a JSON array of objects with the following fields: | ||
| /// - name: optional test name string | ||
| /// - request: object using the same format as the `--request-json` argument for authorization | ||
| /// - entities: array of entity JSON objects in the same format expected by `--entities` argument for authorization | ||
| /// - decision: the string "allow" or "deny" | ||
| /// - reason: array of policy ID strings expected to contribute to the authorization decision | ||
| /// - num_errors: expected number of erroring policies | ||
| #[clap(verbatim_doc_comment)] // stops clap from dropping newlines in bulleted list | ||
| RunTests(RunTestsArgs), | ||
| /// Symbolic analysis of Cedar policies using SymCC | ||
| Symcc(SymccArgs), | ||
| /// Print Cedar language version | ||
| LanguageVersion, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| /* | ||
| * Copyright Cedar Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| use std::{path::Path, time::Instant}; | ||
|
|
||
| use cedar_policy::{Authorizer, Decision, Entities, PolicySet, Response}; | ||
| use clap::Args; | ||
| use miette::Report; | ||
|
|
||
| use crate::{load_entities, CedarExitCode, OptionalSchemaArgs, PoliciesArgs, RequestArgs}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct AuthorizeArgs { | ||
| /// Request args (incorporated by reference) | ||
| #[command(flatten)] | ||
| pub request: RequestArgs, | ||
| /// Policies args (incorporated by reference) | ||
| #[command(flatten)] | ||
| pub policies: PoliciesArgs, | ||
| /// Schema args (incorporated by reference) | ||
| /// | ||
| /// Used to populate the store with action entities and for schema-based | ||
| /// parsing of entity hierarchy, if present | ||
| #[command(flatten)] | ||
| pub schema: OptionalSchemaArgs, | ||
| /// File containing JSON representation of the Cedar entity hierarchy | ||
| #[arg(long = "entities", value_name = "FILE")] | ||
| pub entities_file: String, | ||
| /// More verbose output. (For instance, indicate which policies applied to the request, if any.) | ||
| #[arg(short, long)] | ||
| pub verbose: bool, | ||
| /// Time authorization and report timing information | ||
| #[arg(short, long)] | ||
| pub timing: bool, | ||
| } | ||
|
|
||
| pub fn authorize(args: &AuthorizeArgs) -> CedarExitCode { | ||
| println!(); | ||
| let ans = execute_request( | ||
| &args.request, | ||
| &args.policies, | ||
| &args.entities_file, | ||
| &args.schema, | ||
| args.timing, | ||
| ); | ||
| match ans { | ||
| Ok(ans) => { | ||
| let status = match ans.decision() { | ||
| Decision::Allow => { | ||
| println!("ALLOW"); | ||
| CedarExitCode::Success | ||
| } | ||
| Decision::Deny => { | ||
| println!("DENY"); | ||
| CedarExitCode::AuthorizeDeny | ||
| } | ||
| }; | ||
| if ans.diagnostics().errors().peekable().peek().is_some() { | ||
| println!(); | ||
| for err in ans.diagnostics().errors() { | ||
| println!("{err}"); | ||
| } | ||
| } | ||
| if args.verbose { | ||
| println!(); | ||
| if ans.diagnostics().reason().peekable().peek().is_none() { | ||
| println!("note: no policies applied to this request"); | ||
| } else { | ||
| println!("note: this decision was due to the following policies:"); | ||
| for reason in ans.diagnostics().reason() { | ||
| println!(" {reason}"); | ||
| } | ||
| println!(); | ||
| } | ||
| } | ||
| status | ||
| } | ||
| Err(errs) => { | ||
| for err in errs { | ||
| println!("{err:?}"); | ||
| } | ||
| CedarExitCode::Failure | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// This uses the Cedar API to call the authorization engine. | ||
| fn execute_request( | ||
| request: &RequestArgs, | ||
| policies: &PoliciesArgs, | ||
| entities_filename: impl AsRef<Path>, | ||
| schema: &OptionalSchemaArgs, | ||
| compute_duration: bool, | ||
| ) -> Result<Response, Vec<Report>> { | ||
| let mut errs = vec![]; | ||
| let policies = match policies.get_policy_set() { | ||
| Ok(pset) => pset, | ||
| Err(e) => { | ||
| errs.push(e); | ||
| PolicySet::new() | ||
| } | ||
| }; | ||
| let schema = match schema.get_schema() { | ||
| Ok(opt) => opt, | ||
| Err(e) => { | ||
| errs.push(e); | ||
| None | ||
| } | ||
| }; | ||
| let entities = match load_entities(entities_filename, schema.as_ref()) { | ||
| Ok(entities) => entities, | ||
| Err(e) => { | ||
| errs.push(e); | ||
| Entities::empty() | ||
| } | ||
| }; | ||
| match request.get_request(schema.as_ref()) { | ||
| Ok(request) if errs.is_empty() => { | ||
| let authorizer = Authorizer::new(); | ||
| let auth_start = Instant::now(); | ||
| let ans = authorizer.is_authorized(&request, &policies, &entities); | ||
| let auth_dur = auth_start.elapsed(); | ||
| if compute_duration { | ||
| println!( | ||
| "Authorization Time (micro seconds) : {}", | ||
| auth_dur.as_micros() | ||
| ); | ||
| } | ||
| Ok(ans) | ||
| } | ||
| Ok(_) => Err(errs), | ||
| Err(e) => { | ||
| errs.push(e.wrap_err("failed to parse request")); | ||
| Err(errs) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| /* | ||
| * Copyright Cedar Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| use std::{path::PathBuf, str::FromStr}; | ||
|
|
||
| use cedar_policy::Expression; | ||
| use clap::Args; | ||
| use miette::Report; | ||
|
|
||
| use crate::{load_entities, CedarExitCode, OptionalPoliciesArgs, OptionalSchemaArgs, PoliciesArgs}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct CheckParseArgs { | ||
| /// Policies args (incorporated by reference) | ||
| #[command(flatten)] | ||
| pub policies: OptionalPoliciesArgs, | ||
| /// Expression to parse | ||
| #[arg(long)] | ||
| pub expression: Option<String>, | ||
| /// Schema args (incorporated by reference) | ||
| #[command(flatten)] | ||
| pub schema: OptionalSchemaArgs, | ||
| /// File containing JSON representation of a Cedar entity hierarchy | ||
| #[arg(long = "entities", value_name = "FILE")] | ||
| pub entities_file: Option<PathBuf>, | ||
| } | ||
|
|
||
| pub fn check_parse(args: &CheckParseArgs) -> CedarExitCode { | ||
| // for backwards compatibility: if no policies/schema/entities/expression | ||
| // are provided, read policies from stdin and check that they parse | ||
| if args.policies.policies_file.is_none() | ||
| && args.schema.schema_file.is_none() | ||
| && args.entities_file.is_none() | ||
| && args.expression.is_none() | ||
| { | ||
| let pargs = PoliciesArgs { | ||
| policies_file: None, // read from stdin | ||
| policy_format: args.policies.policy_format, | ||
| template_linked_file: args.policies.template_linked_file.clone(), | ||
| }; | ||
| match pargs.get_policy_set() { | ||
| Ok(_) => return CedarExitCode::Success, | ||
| Err(e) => { | ||
| println!("{e:?}"); | ||
| return CedarExitCode::Failure; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[expect( | ||
| clippy::useless_let_if_seq, | ||
| reason = "exit_code is mutated by later expressions" | ||
| )] | ||
| let mut exit_code = CedarExitCode::Success; | ||
| if let Err(e) = args.policies.get_policy_set() { | ||
| println!("{e:?}"); | ||
| exit_code = CedarExitCode::Failure; | ||
| } | ||
| if let Some(e) = args | ||
| .expression | ||
| .as_ref() | ||
| .and_then(|expr| Expression::from_str(expr).err()) | ||
| { | ||
| println!("{:?}", Report::new(e)); | ||
| exit_code = CedarExitCode::Failure; | ||
| } | ||
| let schema = match args.schema.get_schema() { | ||
| Ok(schema) => schema, | ||
| Err(e) => { | ||
| println!("{e:?}"); | ||
| exit_code = CedarExitCode::Failure; | ||
| None | ||
| } | ||
| }; | ||
| if let Some(e) = args | ||
| .entities_file | ||
| .as_ref() | ||
| .and_then(|e| load_entities(e, schema.as_ref()).err()) | ||
| { | ||
| println!("{e:?}"); | ||
| exit_code = CedarExitCode::Failure; | ||
| } | ||
| exit_code | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.