### Install Cedar CLI from Source Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/README.md Installs the Cedar CLI using Cargo, Rust's package manager. Ensure Rust is installed via rustup. ```bash cargo install cedar-policy-cli ``` -------------------------------- ### Rust Quick Start with Cedar Authorizer Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy/README.md Embed a Cedar policy in Rust and use the Cedar Authorizer to check permissions for different users and actions. This example demonstrates authorization for Alice (allowed) and Bob (denied). ```rust use cedar_policy::* fn main() { const POLICY_SRC: &str = r#" permit(principal == User::"alice", action == Action::"view", resource == File::"93"); "#; let policy: PolicySet = POLICY_SRC.parse().unwrap(); let action = r#"Action::"view""#.parse().unwrap(); let alice = r#"User::"alice""#.parse().unwrap(); let file = r#"File::"93""#.parse().unwrap(); let request = Request::new(alice, action, file, Context::empty(), None).unwrap(); let entities = Entities::empty(); let authorizer = Authorizer::new(); let answer = authorizer.is_authorized(&request, &policy, &entities); // Should output `Allow` println!("{:?}", answer.decision()); let action = r#"Action::"view""#.parse().unwrap(); let bob = r#"User::"bob""#.parse().unwrap(); let file = r#"File::"93""#.parse().unwrap(); let request = Request::new(bob, action, file, Context::empty(), None).unwrap(); let answer = authorizer.is_authorized(&request, &policy, &entities); // Should output `Deny` println!("{:?}", answer.decision()); } ``` -------------------------------- ### Get Cedar CLI Help Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/README.md Displays the available commands and options for the Cedar CLI. This is useful for understanding the CLI's capabilities. ```bash cargo run -- --help ``` -------------------------------- ### Simple Cedar Policy Example Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy/README.md A basic Cedar policy that permits a specific user to perform a specific action on a specific resource. ```cedar permit(principal == User::"alice", action == Action::"view", resource == File::"93"); ``` -------------------------------- ### Authorize View Photo (Permit) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to authorize a user to view a specific photo. This example relies on the principal being part of a group that has been granted view access. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_1.cedar \ --entities entities.json ``` -------------------------------- ### Verify Cedar Policy Set Does Not Always Allow Requests Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-symcc/README.md This example demonstrates how to use SymCC to verify that a given Cedar policy set does not always allow any well-formed request. It includes parsing schema and policies, initializing the symbolic compiler, and iterating through request environments to check the 'always allows' property. It also shows how to use the `check_always_allows_with_counterexample` function to obtain a synthesized request and entity store that is denied by the policy set. ```rust use tokio; use std::str::FromStr; use cedar_policy::{Schema, PolicySet, Authorizer, Decision}; use cedar_policy_symcc::{solver::LocalSolver, CedarSymCompiler, SymEnv, WellTypedPolicies}; #[tokio::main] async fn main() { // Parse Cedar schema let schema = Schema::from_cedarschema_str(r#" entity User; entity Document { owner: User }; action view appliesTo { principal: [User], resource: [Document] }; "#).unwrap().0; // Parse Cedar policy set let policy_set = PolicySet::from_str(r#" permit(principal, action == Action::"view", resource) when { resource.owner == principal }; "#).unwrap(); // Initialize the symbolic compiler let cvc5 = LocalSolver::cvc5().unwrap(); let mut compiler = CedarSymCompiler::new(cvc5).unwrap(); // Iterate through all request environments and check the property for req_env in schema.request_envs() { // Encode the request environment symbolically let sym_env = SymEnv::new(&schema, &req_env).unwrap(); // Validate/type check the policy set let typed_policies = WellTypedPolicies::from_policies(&policy_set, &req_env, &schema).unwrap(); // Verify that `policy_set` does not always allow any request let always_denies = compiler.check_always_allows(&typed_policies, &sym_env).await.unwrap(); assert!(!always_denies); // Similar to above, but returns a counterexample (a synthesized request // and entity store) which is denied by the policy set. let cex = compiler.check_always_allows_with_counterexample(&typed_policies, &sym_env).await.unwrap().unwrap(); let resp = Authorizer::new().is_authorized(&cex.request, &policy_set, &cex.entities); assert!(resp.decision() == Decision::Deny); } } ``` -------------------------------- ### Initialize Cedar WASM with a Buffer (Web Subpackage) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This method uses the `web` subpackage to initialize Cedar WASM with a pre-loaded WASM binary buffer. This is useful for custom loading strategies or specific Jest setups where the WASM file needs to be fetched or read manually. ```javascript const wasmBuffer = ... // `fetch` it or use `fs` to read it from `node_modules` in jest setupTests import * as cedarJsBindings from '@cedar-policy/cedar-wasm/web'; cedarJsBindings.initSync(wasmBuffer); ``` -------------------------------- ### Vite 5 Configuration for WASM Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This configuration adds the necessary Vite plugins (`vite-plugin-wasm` and `vite-plugin-top-level-await`) to enable WebAssembly support in a Vite 5 project. Ensure these are installed as dev dependencies. ```javascript import wasm from 'vite-plugin-wasm'; import topLevelAwait from 'vite-plugin-top-level-await'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ wasm(), topLevelAwait() ] }); ``` -------------------------------- ### Cedar 'is' Operator Usage Examples Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/hierarchy/is.md Demonstrates the basic syntax for using the 'is' operator to check entity types, including checks within specific entities or sets of entities. ```cedar is ``` ```cedar is in ``` ```cedar is in set() ``` -------------------------------- ### Level Validation Error Example Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/level-validation/README.md This output shows a typical level validation error when a Level One policy is incorrectly validated at Level Zero, highlighting the specific violation. ```text × policy set validation failed ╰─▶ for policy `policy0`, the maximum allowed level 0 is violated. Actual level is 1 ╭─[2:3] 1 │ permit(principal, action, resource) when { 2 │ principal.jobLevel > 5 · ────────────────── 3 │ }; ╰──── help: Consider increasing the level ``` -------------------------------- ### Build Cedar CLI from Source Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/README.md Builds the Cedar CLI project using Cargo. Use 'cargo build --release' for an optimized build. ```bash cargo build ``` -------------------------------- ### Authorize Initial Request Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Use this command to perform an authorization request before linking any policies. It checks if 'alice' can view 'VacationPhoto94.jpg'. Expect DENY. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies.cedar \ --entities entities.json ``` -------------------------------- ### Display Cedar Format CLI Help Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-formatter/README.md Invoke the 'cedar format -h' command to view all available options and usage instructions for the formatter subcommand. ```shell cedar format -h ``` -------------------------------- ### Authorize Request with Context and IP Address Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_b/README.md This command demonstrates authorization using request context, including IP addresses. It's useful for testing access control based on network location. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"vacation.jpg"' \ --context context.json \ --policies policies_6.cedar \ --entities entities.json ``` -------------------------------- ### Authorize Different Actions for Users Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md This command tests authorization for different users with varying permissions on resources within an album. It highlights how policies can differentiate access based on user roles or explicit grants. ```shell cargo run authorize \ --principal 'User::"bob"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_2.cedar \ --entities entities.json ``` -------------------------------- ### Build and Test SymCC Crate Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-symcc/README.md Commands to build and test the cedar-policy-symcc crate. Ensure the CVC5 executable path is set in the environment variable. ```sh cargo build -p cedar-policy-symcc ``` ```sh CVC5= cargo test -p cedar-policy-symcc ``` -------------------------------- ### Authorize Action on Photo (Action List) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to authorize specific actions (view, edit, delete) on a photo. This policy set demonstrates how to define permissions for an explicit list of actions. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_2.cedar \ --entities entities.json ``` -------------------------------- ### Authorize After Linking for Alice Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Re-runs the authorization request after linking the policy for 'alice'. This time, with the linked policy, 'alice' should be granted ALLOW access. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies.cedar \ --entities entities.json \ --template-linked ./linked ``` -------------------------------- ### Link Policy Template for Bob Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Links the 'AccessVacation' template to create a new policy 'BobAccess'. It fills the '?principal' slot with 'User::"bob"', granting 'bob' access to the photo. ```shell cargo run link \ --policies policies.cedar \ --template-linked ./linked \ --template-id "AccessVacation" \ --new-id "BobAccess" \ --arguments '{ "?principal" : "User::\"bob\"" }' ``` -------------------------------- ### Run Cedar Integration Tests Source: https://github.com/cedar-policy/cedar/blob/main/cedar-testing/README.md Clone the integration tests repository and run cargo test with the 'integration-testing' feature. Use '--include-ignored' to run corpus tests. ```bash # starting in the top-level directory (..) rm -rf cedar-integration-tests git clone --depth 1 https://github.com/cedar-policy/cedar-integration-tests cd cedar-integration-tests tar xzf corpus-tests.tar.gz cd .. cargo test --features "integration-testing" -- --include-ignored ``` -------------------------------- ### Link Policy Template for Alice Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Links the 'AccessVacation' template to create a new policy 'AliceAccess'. It fills the '?principal' slot with 'User::"alice"' and saves the linked policy to './linked'. ```shell cargo run link \ --policies policies.cedar \ --template-linked ./linked \ --template-id "AccessVacation" \ --new-id "AliceAccess" \ --arguments '{ "?principal" : "User::\"alice\"" }' ``` -------------------------------- ### Load Cedar WASM in Node.js (ESM Async Import) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This snippet demonstrates loading the Node.js version of Cedar WASM using an asynchronous ES module import. This is useful in environments that support dynamic imports. ```javascript import('@cedar-policy/cedar-wasm/nodejs') .then(cedar => console.log(cedar.getCedarVersion())); ``` -------------------------------- ### Authorize View Photo (Implicit Deny) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to test implicit denial. This request should be denied because the principal is not part of the group with view access and no other policy permits the action. ```shell cargo run authorize \ --principal 'User::"bob"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_1.cedar \ --entities entities.json ``` -------------------------------- ### Authorize with JSON Policy Format Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/json-authorize/README.md Use this command to perform an authorization request when your policies are in JSON format. Ensure you specify `--policy-format json` and provide the path to your JSON policy file. ```bash cedar authorize --policy-format json \ --policies policy.cedar.json \ --entities entity.json \ --principal 'User::"bob"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' ``` -------------------------------- ### Load Cedar WASM in Webpack 5 (Dynamic Import) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This snippet shows how to load the Cedar WASM package using a dynamic import within your application's entry point when using Webpack 5. This is the recommended approach for bundling. ```javascript import('@cedar-policy/cedar-wasm').then(mod => { // cache it globally here or invoke functions like mod.getCedarVersion(); }); ``` -------------------------------- ### Authorize Request with Separate Arguments Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample1/README.md Use this command to authorize a request by providing principal, action, and resource as separate arguments. This is useful for simpler or ad-hoc authorization checks. ```bash cargo run authorize \ --policies policy.cedar \ --entities entity.json \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' ``` -------------------------------- ### Format Cedar Policies with Cedar CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-formatter/README.md Use the 'cedar format' subcommand to format policies. Options include default indentation (2 spaces) and line width (80 characters). ```shell cedar format -p my-policies.cedar ``` ```shell # I want more indentation. cedar format -i 4 -p my-policies.cedar ``` ```shell # I like shorter lines. cedar format -l 40 -p my-policies.cedar ``` -------------------------------- ### Authorize Request with Cedar CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample4/README.md Use this command to authorize a user's action against a policy and entities. Ensure policy.cedar, entity.json, and request.json are in the current directory. ```bash cargo run authorize \ --policies policy.cedar \ --entities entity.json \ --request-json request.json ``` -------------------------------- ### Authorize Public ListPhotos Action on Album Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to test public access for the 'listPhotos' action on an album. This policy allows any principal to perform this action on the specified album. ```shell cargo run authorize \ --principal 'User::"tim"' \ --action 'Action::"listPhotos"' \ --resource 'Album::"jane_vacation"' \ --policies policies_3.cedar \ --entities entities.json ``` -------------------------------- ### Authorize Alice After Template Update Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Authorizes 'alice' after the template has been updated with an ABAC rule. Alice should now be DENIED because her entity does not have the 'department' attribute set to 'research'. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_edited.cedar \ --entities entities.json \ --template-linked ./linked ``` -------------------------------- ### Load Cedar WASM in Node.js (CommonJS Alternative) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This is an alternative way to import the Node.js specific subpackage using CommonJS `require`. It's suitable for environments that primarily use CommonJS modules. ```javascript const cedar = require('@cedar-policy/cedar-wasm/nodejs') ``` -------------------------------- ### Check JSON Policy Parsing with Cedar CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/json-check-parse/README.md Use this command to verify that a policy file written in JSON format is syntactically correct and parsable by the Cedar CLI. Ensure the policy file path is correctly specified. ```bash cedar check-parse --policy-format json \ --policies policy.cedar.json ``` -------------------------------- ### Authorize Request for Viewing Photos Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_b/README.md Use this command to test authorization for viewing photos based on department and job level. Ensure the principal meets the specified criteria. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"prototype_v0.jpg"' \ --policies policies_4.cedar \ --entities entities.json ``` -------------------------------- ### Evaluate Cedar Expression with Principal, Action, and Resource Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample2/README.md Evaluate a Cedar expression by specifying the principal, action, resource, and entities. This allows for detailed policy evaluation. ```bash cargo run evaluate \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --entities entity.json \ "resource.owner" ``` -------------------------------- ### Authorize a Request with Cedar CLI (Allowed) Source: https://github.com/cedar-policy/cedar/blob/main/README.md Use the Cedar CLI to authorize a request. This command checks if 'alice' can view 'VacationPhoto94.jpg', which is in 'jane_vacation' album. Ensure 'policy.cedar' and 'entities.json' are in the current directory. ```sh cargo run --bin cedar authorize \ --policies policy.cedar \ --entities entities.json \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' ``` -------------------------------- ### Authorize View Photo (Forbid Override) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to test a scenario where a user is explicitly forbidden from an action, overriding a general permit policy. This demonstrates the precedence of forbid policies. ```shell cargo run authorize \ --principal 'User::"tim"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_1.cedar \ --entities entities.json ``` -------------------------------- ### Authorize a Request with Cedar CLI (Denied) Source: https://github.com/cedar-policy/cedar/blob/main/README.md This command tests a request for 'alice' to view 'SecretPhoto94.jpg', which is in 'jane_secrets' album. The policy does not grant access to this album, resulting in a DENY. ```sh cargo run --bin cedar authorize \ --policies policy.cedar \ --entities entities.json \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"SecretPhoto94.jpg"' ``` -------------------------------- ### Basic If-Else Syntax Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/logical/if.md Use the 'if' operator to return one of two expressions based on a boolean condition. The condition must evaluate to a boolean. ```cedar if then else ``` -------------------------------- ### Webpack 5 Configuration for WASM Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md This is a minimal webpack.config.js file for integrating Cedar WASM. It includes necessary configurations for TypeScript, WASM support, and a development server. ```json { "name": "webpack-ts-tester", "version": "1.0.0", "description": "", "private": true, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "dev": "webpack serve" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@cedar-policy/cedar-wasm": "3.2.0" }, "devDependencies": { "ts-loader": "^9.5.1", "typescript": "^5.4.5", "webpack": "^5.91.0", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.0.4", "html-webpack-plugin": "^5.6.0" } } ``` ```json { "compilerOptions": { "outDir": "./dist/", "noImplicitAny": true, "module": "es2020", "target": "es5", "jsx": "react", "allowJs": true, "moduleResolution": "node" } } ``` ```javascript const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', // change this to suit you entry: './src/index.ts', module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/, }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, experiments: { asyncWebAssembly: true, // enables wasm support in webpack }, plugins: [new HtmlWebpackPlugin()], devServer: { static: { directory: path.join(__dirname, 'dist'), }, compress: true, port: 8000, } }; ``` -------------------------------- ### duration() constructor Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/datetime/duration.md Constructs a duration value from a string representing a time period. ```APIDOC ## duration() *(duration constructor)* ### Description Function that constructs a duration value from a string representing a time period. ### Usage ```cedar duration() ``` ``` -------------------------------- ### Add cedar-policy Crate Dependency Source: https://github.com/cedar-policy/cedar/blob/main/README.md Use this command to add the cedar-policy crate as a dependency to your Rust project. ```sh cargo add cedar-policy ``` -------------------------------- ### Authorize Public View Access to Photo Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to test public access for the 'view' action on photos within a specific album. This policy allows any principal to view these resources. ```shell cargo run authorize \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_3.cedar \ --entities entities.json ``` -------------------------------- ### Define a Cedar Policy Source: https://github.com/cedar-policy/cedar/blob/main/README.md This policy grants 'alice' permission to view resources within the 'jane_vacation' album. Ensure the policy file is named 'policy.cedar'. ```cedar permit ( principal == User::"alice", action == Action::"view", resource in Album::"jane_vacation" ); ``` -------------------------------- ### Authorize Request with Type-Specific Policy Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample9/README.md This command demonstrates authorizing a request using a Cedar policy that includes the 'is' operator. It checks if 'User::"Bob"' can view 'Photo::"VacationPhoto94.jpg"' based on the defined policy and entity data. ```console sample9$ cargo run authorize --policies policy.cedar --entities entity.json --request-json request.json ALLOW ``` -------------------------------- ### Load Cedar WASM in Node.js (CommonJS) Source: https://github.com/cedar-policy/cedar/blob/main/cedar-wasm/README.md Use this method to import the CommonJS version of the Cedar WASM package in a Node.js environment without a bundler. It allows direct access to Cedar functions. ```javascript const cedar = require('@cedar-policy/cedar-wasm/nodejs'); console.log(cedar.getCedarVersion()); ``` -------------------------------- ### Validate Cedar Policy with Schema CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample4/README.md Validate the syntax and structure of your Cedar policies against a schema file. This command checks for compliance with the defined schema. ```bash cargo run validate \ --policies policy.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Authorize Bob After Template Update Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md Authorizes 'bob' after the template has been updated with an ABAC rule. Bob should still have access because his entity has the 'department' attribute set to 'research'. ```shell cargo run authorize \ --principal 'User::"bob"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --policies policies_edited.cedar \ --entities entities.json \ --template-linked ./linked ``` -------------------------------- ### Evaluate Cedar Expression with CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample8/README.md Evaluate a specific Cedar expression using provided entities and a request. This is useful for testing individual policy logic or expressions. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "principal.score.lessThan(decimal(\"1.2345\"))" ``` -------------------------------- ### Evaluate Cedar Expression with CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample7/README.md Evaluate a Cedar expression using provided entity data. This is useful for testing specific policy logic or context-dependent conditions. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "context.role.contains(\"admin\")" ``` -------------------------------- ### Evaluate Cedar Expression with Entities Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample2/README.md Evaluate a Cedar expression using provided entities. This is useful for testing specific parts of your policy logic. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "resource.owner" ``` -------------------------------- ### Evaluate Cedar Expression with Separate Arguments Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample1/README.md Evaluate a Cedar expression using principal, action, and resource arguments, along with entity data. The expression is provided as the last argument. ```bash cargo run evaluate \ --principal 'User::"alice"' \ --action 'Action::"view"' \ --resource 'Photo::"VacationPhoto94.jpg"' \ --entities entity.json \ "principal in UserGroup::\"jane_friends\"" ``` -------------------------------- ### Evaluate Cedar Expression Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to evaluate a Cedar expression against a set of entities and authorization context. This is useful for testing specific conditions or logic within policies. ```shell cargo run evaluate \ --principal 'User::"alice"' \ --action 'Action::"listPhotos"' \ --resource 'Album::"jane_vacation"' \ --entities entities.json \ "resource in Account::\"jane\"" ``` -------------------------------- ### Evaluate Cedar Expression with CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample6/README.md Evaluate a specific Cedar expression using provided entities. This is useful for testing policy logic or understanding expression outcomes. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "principal.account.age >= 17" ``` -------------------------------- ### durationSince() Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/datetime/duration_since.md Calculates the duration between two datetime values. ```APIDOC ## durationSince() ### Description Calculates the duration between two datetime values. ### Method Function call ### Signature `.durationSince()` ### Parameters #### Arguments - **datetime** (datetime) - The datetime value to compare against. ### Returns - (duration) - The duration between the two datetime values. ``` -------------------------------- ### Constructing Durations with duration() Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/datetime/duration.md Use the duration() function to create a duration value from a string. The string should represent a valid time period. ```cedar duration() ``` -------------------------------- ### Validate Level Zero Policy Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/level-validation/README.md Use this command to validate a policy that adheres to Level Zero restrictions, which disallows attribute access on entities. ```bash cargo run validate \ --level 0 \ --policies policy-level-0.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Define Entities for Policy Evaluation Source: https://github.com/cedar-policy/cedar/blob/main/README.md This JSON structure defines the entities involved in the policy, including users, albums, and photos, along with their attributes and relationships. Save this as 'entities.json'. ```json [ { "uid": { "type": "User", "id": "alice"} , "attrs": {"age": 18}, "parents": [] }, { "uid": { "type": "Photo", "id": "VacationPhoto94.jpg"}, "attrs": {}, "parents": [{ "type": "Album", "id": "jane_vacation" }] }, { "uid": { "type": "Photo", "id": "SecretPhoto94.jpg"}, "attrs": {}, "parents": [{ "type": "Album", "id": "jane_secrets" }] } ] ``` -------------------------------- ### Cedar 'like' Operator Usage Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/comparison/like.md Use the 'like' operator to check if a string matches a pattern containing wildcards. The asterisk (*) matches zero or more characters. To match a literal asterisk, escape it with a backslash (\*). ```cedar like ``` -------------------------------- ### Usage of Less Than or Equal To Operator Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/comparison/less_than_or_equals.md This snippet demonstrates the basic syntax for using the less than or equal to operator with two long integer operands. Ensure both operands are of type 'long' to avoid validation errors. ```cedar <= ``` -------------------------------- ### Validate Cedar Policy with Typo Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md This command demonstrates policy validation failure due to an unrecognized entity type. It highlights the importance of correct naming and schema adherence. ```shell cargo run validate \ --policies policies_1_bad.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Cedar Policy Template Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_c/README.md A Cedar policy template with a slot '?principal'. This template grants 'view' permission on 'VacationPhoto94.jpg' to any principal specified in the slot. ```cedar @id("AccessVacation") permit( principal in ?principal, action == Action::"view", resource == Photo::"VacationPhoto94.jpg" ); ``` -------------------------------- ### isLoopback() Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/ip/is_loopback.md Checks if an IP address is a loopback address for its IP version type. Evaluates to an error if the receiver is not an IP address type. ```APIDOC ## isLoopback() ### Description Evaluates to true if the receiver is a valid loopback address for its IP version type. Evaluates (and validates) to an error if the receiver does not have an IP address type. This function takes no operands. ### Usage ```cedar .isLoopback() ``` ### Parameters This function takes no parameters. ### Returns - boolean: true if the IP address is a loopback address, false otherwise. ### Errors - Error: If the receiver is not an IP address type. ``` -------------------------------- ### Evaluate Cedar Expression Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample5/README.md Evaluate a Cedar expression using provided entities and a JSON request. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "principal.addr.isLoopback()" ``` -------------------------------- ### Decimal lessThan() Comparison Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/decimal/less_than.md Use this function to check if one decimal value is numerically less than another. Ensure both operands are decimals to avoid evaluation errors. ```cedar .lessThan() ``` -------------------------------- ### Validate Cedar Policy Schema Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_b/README.md Use this command to validate a Cedar policy against a schema file. This ensures the policy conforms to the defined structure and constraints. ```shell cargo run validate \ --policies policies_5.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Evaluate Cedar Expression with JSON Input Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample1/README.md Evaluate a Cedar expression using data from JSON files for requests and entities. The expression is provided as the last argument. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "principal in UserGroup::\"jane_friends\"" ``` -------------------------------- ### Logical AND Operator Usage Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/logical/and.md Use the `&&` operator to combine two boolean expressions. It short-circuits if the first operand is false. ```cedar && ``` -------------------------------- ### Validate Level Two Policy Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/level-validation/README.md Use this command to validate a policy that adheres to Level Two restrictions, allowing access to attributes of entities referenced by other entities. ```bash cargo run validate \ --level 2 \ --policies policy-level-2.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Authorize Request for Private Photo Viewing Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_b/README.md This command tests authorization for viewing private photos, checking if the requester is the owner. It's used when resources have a 'private' attribute set to true. ```shell cargo run authorize \ --principal 'User::"stacey"' \ --action 'Action::"view"' \ --resource 'Photo::"alice_w2.jpg"' \ --policies policies_5.cedar \ --entities entities.json ``` -------------------------------- ### lessThanOrEqual() Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/decimal/less_than_or_equal.md Compares two decimal operands and evaluates to true if the left operand is numerically less than or equal to the right operand. Both operands must be decimals, otherwise evaluation results in an error. ```APIDOC ## lessThanOrEqual(decimal other) ### Description Compares two decimal operands and evaluates to true if the left operand is numerically less than or equal to the right operand. If either operand is not a decimal then evaluation (and validation) results in an error. ### Method Signature `.lessThanOrEqual()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cedar let x = 10.5 let y = 10.5 x.lessThanOrEqual(y) ``` ### Response #### Success Response (Boolean) - **true**: if the left operand is less than or equal to the right operand. - **false**: if the left operand is greater than the right operand. #### Response Example ```json true ``` #### Error Response - **Error**: If either operand is not a decimal. ``` -------------------------------- ### Evaluate Cedar Expression CLI Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample4/README.md Evaluate a specific Cedar expression using provided entities and a JSON request. This is useful for testing policy logic or understanding expression outcomes. ```bash cargo run evaluate \ --request-json request.json \ --entities entity.json \ "resource.owner == User::\"bob\"" ``` -------------------------------- ### Pin Cedar Policy Version in Cargo.toml Source: https://github.com/cedar-policy/cedar/blob/main/README.md To prevent automatic updates to Cedar, pin to a specific version in your Cargo.toml file using the '=' operator. This ensures predictable behavior by locking to an exact version. ```toml [dependencies] cedar-policy = "=2.4.2" ``` -------------------------------- ### Check if a Set is Empty in Cedar Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/hierarchy/is_empty.md Use the isEmpty() function to check if a set is empty. The receiver must be a set, or an error will occur. ```cedar .isEmpty() ``` -------------------------------- ### Validate Cedar Policy Schema Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/sandbox_a/README.md Use this command to validate a Cedar policy file against a schema file. This ensures the policy adheres to the defined entity types, actions, and relationships. ```shell cargo run validate \ --policies policies_1.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Validate Level One Policy Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/level-validation/README.md Use this command to validate a policy that adheres to Level One restrictions, allowing direct attribute access on entities referenced in the request. ```bash cargo run validate \ --level 1 \ --policies policy-level-1.cedar \ --schema schema.cedarschema ``` -------------------------------- ### Using the Less Than Operator Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/comparison/less_than.md Compares two long integer operands. Evaluation results in an error if either operand is not a long. ```cedar < ``` -------------------------------- ### isEmpty() - Set Emptiness Test Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/hierarchy/is_empty.md The `isEmpty()` function evaluates to `true` if the set is empty. The receiver must be of type set, otherwise evaluation produces an error. ```APIDOC ## isEmpty() ### Description Tests if a set is empty. Returns `true` if the set contains no elements, and `false` otherwise. ### Syntax ```cedar .isEmpty() ``` ### Parameters This method does not take any explicit parameters. It operates on the set object it is called upon. ### Receiver Type The receiver of this method must be of type `set`. Calling `isEmpty()` on a non-set type will result in an evaluation error. ### Return Value - `boolean`: `true` if the set is empty, `false` otherwise. ### Example ```cedar let mySet = new Set(); mySet.isEmpty() // Returns true let anotherSet = new Set([1, 2, 3]); anotherSet.isEmpty() // Returns false ``` ``` -------------------------------- ### Evaluate Conditional Cedar Expression Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample2/README.md Evaluate a Cedar expression that includes conditional logic. This demonstrates how to test 'if-then-else' structures. ```bash cargo run evaluate \ --request-json request.json \ "if 10 > 5 then \"good\" else \"bad\"" ``` -------------------------------- ### Parse String to Decimal in Cedar Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/decimal/decimal.md Use this function to convert a string to a decimal type. Ensure the string adheres to decimal formatting rules, including a decimal separator and valid digit counts. The value must also be within the supported decimal range. ```cedar decimal() ``` -------------------------------- ### Calculate Duration Between Datetimes Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/datetime/duration_since.md Use the durationSince function to find the time elapsed between two datetime values. Ensure both arguments are valid datetime types. ```cedar .durationSince() ``` -------------------------------- ### Hierarchy Membership Check with 'in' Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/hierarchy/in.md Use the 'in' operator to determine if the entity on the left is a descendant of the entity on the right. An error occurs if operands are not entities or sets of entities. ```cedar in ``` -------------------------------- ### Binary Subtraction and Unary Negation Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/arithmetic/subtract.md Use the '-' operator for binary subtraction between two long integers or for unary negation of a single long integer. Ensure operands are long integers to avoid validation errors. Overflow or underflow during subtraction will result in evaluation failure. ```cedar - // binary subtraction - // unary negation ``` -------------------------------- ### Decimal greaterThan() Comparison Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/decimal/greater_than.md Use this function to check if one decimal value is numerically greater than another. Ensure both operands are decimals to avoid errors. ```cedar .greaterThan() ``` -------------------------------- ### Using the ip() function in Cedar Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/ip/ip.md Use the ip() function to parse a string and convert it to an ipaddr type. An error occurs if the string is not a valid IP address or range. ```cedar ip() ``` -------------------------------- ### Check if IP Address is within a Range using isInRange() Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/ip/is_in_range.md Use this function to verify if an IP address falls completely inside a defined IP address range. Ensure both the IP address and the range are valid IP address types. ```cedar .isInRange() ``` -------------------------------- ### Decimal greaterThanOrEqual() Usage Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/extension/decimal/greater_than_or_equal.md Use this function to compare two decimal values. Ensure both operands are decimals to avoid errors. ```cedar .greaterThanOrEqual() ``` -------------------------------- ### Cedar Policy with Principal == Resource Owner Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample9/README.md This policy attempts to allow any principal to view a resource if they are the resource's owner. It may fail validation if not all resources have an 'owner' attribute. ```cedar permit ( principal, action == Action::"view", resource ) when { principal == resource.owner }; ``` -------------------------------- ### Cedar Equality Operator Usage Source: https://github.com/cedar-policy/cedar/blob/main/cedar-language-server/src/documentation/markdown/comparison/equals.md Use the equality operator to compare two values for exact sameness in both type and value. This operator is binary and can be applied to operands of any type. ```cedar == ``` -------------------------------- ### Cedar Policy Validation Success Source: https://github.com/cedar-policy/cedar/blob/main/cedar-policy-cli/sample-data/tiny_sandboxes/sample9/README.md This console output indicates that the Cedar policy has been validated successfully after incorporating the 'is' operator to ensure type safety. ```console sample9$ cedar validate --policies policy.cedar --schema schema.cedarschema Validation Passed ```