### Tenant Resource Slice Examples Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Examples of resource slices for a tenant, showing both populated and empty attribute structures. ```json [ { "uid": { "type": "EmailApp::Tenant", "id": "acme" }, "attrs": { "planTier": "enterprise", "maxUsers": 100 }, "parents": [] } ] ``` ```json [ { "uid": { "type": "EmailApp::Tenant", "id": "tenantIdFromUdlParams" }, "attrs": {}, "parents": [] } ] ``` -------------------------------- ### Like Operator Pattern Matching Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Comprehensive examples of string matching using the like operator and wildcards. ```cedar "eggs" like "ham*" //false "eggs" like "*ham" //false "eggs" like "*ham*" //false "ham and eggs" like "ham*" //true "ham and eggs" like "*ham" //false "ham and eggs" like "*ham*" //true "ham and eggs" like "*h*a*m*" //true "eggs and ham" like "ham*" //false "eggs and ham" like "*ham" //true "eggs, ham, and spinach" like "ham*" //false "eggs, ham, and spinach" like "*ham" //false "eggs, ham, and spinach" like "*ham*" //true "Gotham" like "ham*" //false "Gotham" like "*ham" //true "ham" like "ham" //true "ham" like "ham*" //true "ham" like "*ham" //true "ham" like "*h*a*m*" //true "ham and ham" like "ham*" //true "ham and ham" like "*ham" //true "ham" like "*ham and eggs*" //false "\\afterslash" like "\\*" //true "string\\with\\backslashes" like "string\\with\\backslashes" //true "string\\with\\backslashes" like "string*with*backslashes" //true "string*with*stars" like "string\*with\*stars" //true ``` -------------------------------- ### List Email Campaigns HTTP Request Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Example of a GET request to list email campaigns for a specific tenant. ```http GET /tenants/acme/campaigns ``` -------------------------------- ### Like Operator Context Example Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Example context for evaluating string matching with the like operator. ```json "context": { "location": "s3://bucketA/redTeam/some/thing" } ``` -------------------------------- ### HTTP Requests for Open Endpoints Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Example HTTP requests for login and signup actions. ```HTTP POST /login { "email": "alice@acme.com", "password": "..." } POST /signup { "email": "bob@newcorp.com", "displayName": "Bob" } ``` -------------------------------- ### Multiplication operator examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of multiplication operations using literals and context/resource attributes. ```cedar 10 * 20 //200 resource.value * 10 //30 2 * context.budget > 100 //false context.budget * resource.value //depends on entity data 9223372036854775807 * 2 //error - overflow //Validates 5 * (-3) //-15 5 * 0 //0 "5" * 0 //error - both operands must have type `long` //Doesn't validate ``` -------------------------------- ### Decimal Parsing Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of valid and invalid decimal string parsing in Cedar policies. ```Cedar decimal("1.0") decimal("-1.0") decimal("123.456") decimal("0.1234") decimal("-0.0123") decimal("55.1") decimal("00.000") decimal(context.time) //Evaluates //Doesn't validate (parameter not a string literal) decimal(context.date) //error - invalid format (not valid as parameter not a string literal) decimal("1234") //error - missing decimal decimal("1.0.") //error - stray period at end decimal("1.") //error - missing fractional part decimal(".1") //error - missing whole number part decimal("1.a") //error - invalid fractional part decimal("-.") //error - invalid format decimal("1000000000000000.0") //error - overflow decimal("922337203685477.5808") //error - overflow decimal("0.12345") //error - too many fractional digits ``` -------------------------------- ### Addition operator examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of addition operations, including valid cases and those resulting in validation or overflow errors. ```cedar 11 + 0 //11 -1 + 1 //0 9223372036854775807 + 1 //error - overflow //Validates 7 + "3" //error - second operand not a long //Doesn't validate "lamp" + "la" //error - operands not `long` //Doesn't validate ``` -------------------------------- ### Create template-linked policies Source: https://docs.cedarpolicy.com/bestpractices/bp-relationship-representation.html Example policies instantiated from templates to grant specific access. ```Cedar //Managed relationship permissions permit ( principal in User::"df82e4ad-949e-44cb-8acf-2d1acda71798", action in Action::"DocumentContributorActions", resource in Document::"c943927f-d803-4f40-9a53-7740272cb969" ); permit ( principal in UserGroup::"df82e4ad-949e-44cb-8acf-2d1acda71798", action in Action::"DocumentReviewerActions", resource == Document::"661817a9-d478-4096-943d-4ef1e082d19a" ); permit ( principal in User::"df82e4ad-949e-44cb-8acf-2d1acda71798", action in Action::"DocumentContributorActions", resource in Folder::"b8ee140c-fa09-46c3-992e-099438930894" ); ``` -------------------------------- ### Datetime Parsing Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of valid and invalid datetime string parsing in Cedar policies. ```Cedar datetime("2024-10-15") datetime("2024-10-15T11:35:00Z") datetime("2024-10-15T11:35:00.000Z") datetime("2024-10-15T11:35:00+0100") datetime("2024-10-15T11:35:00.000+0100") datetime(context.time) //Evaluates but does not validate (parameter not a string literal) datetime(context.date) //error - invalid format (five digits for years) datetime("2022-10-10 ") //error - trailing space datetime("2024-10-15Z") //error - Zulu code in date only format datetime("2024-10-15T11:38:02ZZ") //error - double Zulu code datetime("2024-01-01T01:02") //error - no seconds field nor timezone code datetime("2024-01-01T00:00:00") //error - no timezone specified datetime("2016-12-31T23:59:60.000Z") //error - leap second in seconds field ``` -------------------------------- ### Subtraction and negation operator examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of unary negation and binary subtraction, including overflow and type mismatch error cases. ```cedar -3 //-3 44 - 31 //13 5 - (-3) //8 -9223372036854775807 - 2 + 3 //error - overflow //Validates 7 - "3" //error - second operand not a `long` //Doesn't validate ``` -------------------------------- ### Resource scope examples Source: https://docs.cedarpolicy.com/policies/syntax-policy.html Demonstrates various ways to constrain the resource element in a policy. ```cedar //matches any resource resource //matches only the one specified resource of type Photo resource == Photo::"VacationPhoto94.jpg" //matches any resource that is in the hierarchy of the specified entity of type Album resource in Album::"alice_vacation" //matches any resource of type Photo resource is Photo //matches any resource of type Photo in the hierarchy of the specified Album resource is Photo in Album::"alice_vacation" ``` -------------------------------- ### OR Operator Validation Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples illustrating how the validator handles short-circuiting and type checking for the OR operator. ```cedar 3 || true //error (first operand not a boolean) true || 3 //Evaluates to true (due to short-circuiting) //Validates false || 3 //error (second operand not a boolean) (3 == 3) || 3 //Evaluates to true (due to short-circuiting) //Doesn't validate ``` -------------------------------- ### Conditional expression evaluation examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Various examples showing evaluation results and validation status for different if expression structures. ```cedar if 1 == 1 then "ok" else "wrong" //Evaluates to "ok" //Validates if 1 == 2 then User::"foo" else "ok" //Evaluates to "ok" //Doesn't validate if 1 then "wrong" else "wrong" //error if false then (1 && "hello") else "ok" //Evaluates to "ok" (due to short circuiting) //Validates if true then (1 && "hello") else "error" //error ``` -------------------------------- ### Define a basic namespace schema Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of a namespace declaration containing entity types and actions. ```json { "ExampleCo::Database": { "entityTypes": { "Table": { ... } }, "actions": { "createTable": { ... } } } } ``` -------------------------------- ### NOT Operator Usage Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples showing basic negation and error handling with the NOT operator. ```cedar ! true //false ! false //true ! 8 //error if !true then "hello" else "goodbye" //"goodbye" ``` -------------------------------- ### Construct datetime extension values Source: https://docs.cedarpolicy.com/policies/syntax-datatypes.html Examples of using the datetime() constructor with various string formats. ```Cedar datetime("2024-10-15") // a date only datetime("2024-10-15T11:35:00Z") // a UTC datetime datetime("2024-10-15T11:35:00.000Z") // a UTC datetime with millisecond precision datetime("2024-10-15T11:35:00+0100") // a datetime with timezone offset datetime("2024-10-15T11:35:00.000+0100") // a datetime with timezone offset and millisecond precision ``` -------------------------------- ### Define Cedar Record syntax Source: https://docs.cedarpolicy.com/policies/syntax-datatypes.html Examples of defining record structures with key-value pairs. ```Cedar {"key": "some value", id: "another value"} ``` ```Cedar {} {"foo": 2, bar: [3, 4, -47], ham: "eggs", "hello": true } ``` -------------------------------- ### Define action constraints with appliesTo Source: https://docs.cedarpolicy.com/schema/json-schema.html Example showing an action group with empty constraints and specific actions that define principal and resource types. ```json "actions": { "read": { "appliesTo": { "principalTypes": [], "resourceTypes": [] } }, "viewPhoto": { "memberOf": [ { "id": "read" } ], "appliesTo": { "principalTypes": [ "User" ], "resourceTypes": [ "Photo" ] } }, "listAlbums": { "memberOf": [ { "id": "read" } ], "appliesTo": { "principalTypes": [ "User" ], "resourceTypes": [ "Account" ] } } } ``` -------------------------------- ### Example Policy for Validation Source: https://docs.cedarpolicy.com/policies/validation.html A policy that passes validation against the example schema, allowing principals with specific attributes to perform actions. ```Cedar permit (principal, action, resource) when { principal.name == "superuser" || principal.jobLevel > 8 }; ``` -------------------------------- ### Cedar Policy Set Example Source: https://docs.cedarpolicy.com/policies/json-format.html A sample policy set containing a static permit policy and a forbid policy template. ```cedar permit ( principal == User::"12UA45", action == Action::"view", resource in Folder::"abc" ); forbid ( principal == User::"12UA45", action == Action::"view", resource in ?resource ); ``` -------------------------------- ### Action scope examples Source: https://docs.cedarpolicy.com/policies/syntax-policy.html Demonstrates various ways to constrain the action element in a policy. ```cedar //matches any action action //matches only the one specified action action == Action::"view" //matches any of the listed actions action in [Action::"listAlbums", Action::"listPhotos", Action::"view"] //matches any action in the "admin" action group action in Action::"admin" ``` -------------------------------- ### Define and reference common types Source: https://docs.cedarpolicy.com/schema/schema.html Example showing how to define a common type and reference it in action declarations to avoid redundancy. ```cedar type commonContext = { ip: ipaddr, is_authenticated: Bool, timestamp: Long }; action view appliesTo { context: commonContext }; action upload appliesTo { context: commonContext }; ``` -------------------------------- ### Entity type testing examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Various examples demonstrating valid and invalid usage of the 'is' operator, including type checks and membership tests. ```cedar User::"alice" is User //true principal is User //true if `principal` has the `User` entity type principal is User in Group::"friends" //true if `principal` has the `User` entity type and is in `Group::"friends"" ExampleCo::User::"alice" is ExampleCo::User //true Group::"friends" is User //false ExampleCo::User::"alice" is User //false - `ExampleCo::User` and `User` are different entity types "alice" is String //error - `is` applies only to entity types, not strings ``` -------------------------------- ### IP Address Comparison Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Illustrates equality comparisons between IP addresses and ranges, noting that some comparisons may fail validation due to type mismatch. ```cedar ip("127.0.0.1") == ip("127.0.0.1") //true ip("192.168.0.1") == ip("8.8.8.8") //false ip("192.168.0.1/24") == ip("8.8.8.8/8") //false ip("192.168.0.1/24") == ip("192.168.0.8/24") //false - different host address ip("127.0.0.1") == ip("::1") //false – different IP versions ip("127.0.0.1") == ip("192.168.0.1/24") //false - address compared to range ip("127.0.0.1") == "127.0.0.1" //false – different types //Doesn't validate ip("::1") == 1 //false – different types //Doesn't validate ``` -------------------------------- ### Specific Policy Example Source: https://docs.cedarpolicy.com/bestpractices/bp-map-actions.html A concise and well-scoped policy enabled by using resource-specific actions. ```cedar permit( principal == ProjectApp::User::"alice", action == ProjectApp::Action::"ViewProject", resource is ProjectApp::Project ); ``` -------------------------------- ### Equality operator (==) examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Demonstrates equality comparisons between various types. Note that some comparisons may fail validation if types do not match. ```cedar 1 == 1 //true "something" == "something" //true "Something" == "something" //false [1, -33, 707] == [1, -33] //false [1, 2, 40] == [1, 2, 40] //true [1, 2, 40] == [1, 40, 2] //true [1, -2, 40] == [1, 40] //false [1, 1, 1, 2, 40] == [40, 1, 2] //true [1, 1, 2, 1, 40, 2, 1, 2, 40, 1] == [1, 40, 1, 2] //true true == true //true context.device_properties == {"os": "Windows", "version": 11} //true if context.device_properties represents a Windows 11 computer User::"alice" == User::"alice" //true User::"alice" == User::"bob" //false -- two different entities of same type User::"alice" == Admin::"alice" //false -- entities of two different types //Validates 5 == "5" //false -- operands have two different types //Doesn't validate "alice" == User::"alice" //false -- operands have two different types //Doesn't validate ``` -------------------------------- ### Create Email Campaign HTTP Request Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Example of a POST request to create a new email campaign within a specific tenant. ```http POST /tenants/acme/campaigns { "name": "Spring Sale" } ``` -------------------------------- ### Define partial context Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Example of a context missing a sub-record. ```JSON "context": { "role": ["admin", "user"] } ``` -------------------------------- ### Duration Parsing Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Demonstrates valid and invalid string inputs for the duration() function, including overflow and formatting errors. ```cedar duration("2h30m") duration("-1d12h") duration("1h30m45s") duration(context.time) //Evaluates but does not validate (parameter not a string literal) duration(context.dur) //error - invalid format (minus sign on unit) duration("1d2h3m4s5ms ") //error - trailing space duration("1d2h3m4s5ms6") //error - trailing amount duration("d") //error - unit with no amount duration("1s1d") //error - invalid order duration("1s1s") //error - repeated units duration("1d9223372036854775807ms") //error - overflow ``` -------------------------------- ### IP Address Parsing Examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Shows how to parse IPv4 and IPv6 strings into ipaddr types, including validation errors for invalid formats and types. ```cedar ip("127.0.0.1") ip("::1") ip("127.0.0.1/24") ip("ffee::/64") ip("ff00::2") ip("::2") ip(context.addr) //Evaluates //Doesn't validate (parameter not a string literal) ip(context.time) //error - invalid format (not valid as parameter not a string literal) ip("380.0.0.1") //error – invalid IPv4 address ip("ab.ab.ab.ab") //error – invalid IPv4 address ip("127.0.0.1/8/24") //error – invalid CIDR notation ip("fee::/64::1") //error – invalid IPv6 address ip("fzz::1") //error – invalid character in address ip([127,0,0,1]) //error – invalid operand type "127.0.0.1".ip() //error – invalid call style ``` -------------------------------- ### OR Operator Short-Circuiting Example Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Demonstrates using the OR operator to safely check for an attribute's existence before accessing it. ```cedar !(principal has age) || principal.age < 21 ``` -------------------------------- ### Specify Cedar Entities Source: https://docs.cedarpolicy.com/policies/syntax-datatypes.html Examples of defining principals, actions, and resources using namespace and identifier syntax. ```Cedar // A resource of type File File::"myfile.txt" // An action to allow reading a resource of type File Action::"ReadFile" // A principal of type User with a full UUID as // the entity identifier and its friendly name in comments User::"a1b2c3d4-e5f6-a1b2-c3d4-EXAMPLE11111" // A principal of type User in a Namespace PhotoFlash PhotoFlash::User::"alice" // A principal of type File in a nested namespace Nested::Namespace::App::File::"myFile.txt" ``` -------------------------------- ### Define action identifiers Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of defining specific action names as keys within the actions object. ```json "actions": { "ViewPhoto": { ... }, "ListPhotos": { ... }, ... } ``` -------------------------------- ### Reference Fully Qualified Entity Type Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of a fully qualified entity type name. ```json "My::Name::Space::UserGroup" ``` -------------------------------- ### Define redundant action contexts Source: https://docs.cedarpolicy.com/schema/schema.html Example showing repetitive context definitions for different actions in the Cedar schema format. ```cedar action view appliesTo { principal: User, resource: File, context: { ip: ipaddr, is_authenticated: Bool, timestamp: Long } }; action upload appliesTo { principal: User, resource: Server, context: { ip: ipaddr, is_authenticated: Bool, timestamp: Long } }; ``` -------------------------------- ### Reference Context in Policies Source: https://docs.cedarpolicy.com/auth/entities-syntax.html Examples of accessing context attributes within a policy using dot notation. ```cedar when { context.sourceIp.isInRange(ip("222.222.222.0/24")) } ``` ```cedar when { context.authnMfa } ``` -------------------------------- ### Type Resolution Example Source: https://docs.cedarpolicy.com/schema/human-readable-schema.html Demonstrates how the parser resolves conflicting names based on the defined priority order. ```cedar namespace Demo { entity Host { // the type of attribute `ip` is common type `ipaddr` // instead of extension type `__cedar::ipaddr` // because the former has a higher priority ip: ipaddr, // the type of attribute `bandwidth` is extension type `decimal` // because there is not any common type or entity type // that shares the same name bandwidth: decimal, }; // An artificial entity type name that conflicts with // primitive type `String` entity String { groups: Set<__cedar::String>, }; // A common type name that conflicts with extension // type `ipaddr` type ipaddr = { // The type of attribute `repr` is the entity type // `String` declared above instead of primitive type // `__cedar::String` because the former has a higher // priority repr: String, // The type of attribute `isV4` is the primitive type // `Bool` because there is not any common type or // entity type that shares the same name isV4: Bool, }; } ``` -------------------------------- ### Use Immutable Entity Identifiers Source: https://docs.cedarpolicy.com/other/security.html Examples comparing mutable identifiers like usernames against recommended immutable identifiers like UUIDs. ```text permit (principal == User::"alice",action in ...,resource in ...); ``` ```text permit ( principal == User::"2dad2883-cba1-4a1e-b212-a6c0a5290dad", // "Alice" action in ..., resource in ... ); ``` -------------------------------- ### HTTP Request for Dashboard Data Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Example HTTP request for retrieving dashboard data. ```HTTP GET /dashboard-data ``` -------------------------------- ### Constructing Set Literals in Cedar Source: https://docs.cedarpolicy.com/policies/syntax-datatypes.html Examples of set construction using bracket syntax. Note that while these evaluate, only sets with uniform types and non-empty contents pass the policy validator. ```cedar // a set of three elements, two of type long, and one of type string [2, 4, "hello"] // a set of a single type long [-1] // an empty set [ ] // a set with a Bool expression, a nested set, and a Bool value [3<5, ["nested", "set"], true] ``` -------------------------------- ### Datetime less than (<) operator examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Compares datetime values. Both operands must be valid datetimes. ```cedar datetime("1970-01-01") < datetime("1970-01-02") //true datetime(resource.creationDate) < datetime("2024-10-15T11:38:33Z") //false datetime("1970-01-01T01:00:00Z") < 3600000 //error - operator not allowed on non-datetime ``` -------------------------------- ### Reflexivity and Non-existent Entities Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples showing how the 'in' operator handles non-existent entities based on reflexivity. ```Cedar Stranger::"jimmy" in Stranger::"jimmy" //true by reflexivity. Stranger::"jimmy" in Group::"jane_friends" //false - Stranger::"jimmy" does not refer to an existing entity Stranger::"jimmy" in [ Group::"jane_family", Stranger::"jimmy" ] //true - Stranger::"jimmy" in Stranger::"jimmy" is true ``` -------------------------------- ### Define Entities with Attributes and Parents Source: https://docs.cedarpolicy.com/auth/entities-syntax.html Example of an entities file using uid, attrs, and parents with implicit and explicit escapes for extension types and entity references. ```json [ { "uid": { "type": "User", "id": "alice" }, "attrs": { "department": "HardwareEngineering", "jobLevel": 5, "homeIp": { "__extn": { "fn": "ip", "arg": "222.222.222.7" } }, "confidenceScore": { "__extn": { "fn": "decimal", "arg": "33.57" } } }, "parents": [ { "type": "UserGroup", "id": "aliceFriends" }, { "type": "UserGroup", "id": "bobFriends" } ] }, { "uid": { "type": "User", "id": "ahmad"}, "attrs" : { "department": "HardwareEngineering", "jobLevel": 4, "manager": { "__entity": { "type": "User", "id": "alice" } } }, "parents": [] } ] ``` -------------------------------- ### Evaluate and validate AND operator expressions Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples showing how the && operator behaves during evaluation and validation, including short-circuiting scenarios. ```cedar 3 && false //error -- first operand is not a boolean false && 3 //Evaluates to false (due to short circuiting) //Validates (3 == 4) && 3 //Evaluates to false (due to short circuiting) //Doesn't validate (User::"alice" == Action::"viewPhoto") && 3 //Evaluates to false //Validates true && 3 //error -- second operand is not a boolean (false && 3) == 3 //Evaluates to false //Doesn't validate (== applied to different types) ``` -------------------------------- ### Raw URL context data Source: https://docs.cedarpolicy.com/bestpractices/bp-normalize-data-input.html Example of unformatted URL data that requires normalization before being used in policies. ```json { "url": "https://example.com/path/to/page?name=alice&color=red" } ``` -------------------------------- ### Handle missing attributes Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of 'has' returning false or causing errors when attributes are missing or types are incorrect. ```Cedar context has tag //false ``` ```Cedar context.role has admin //type error ``` ```Cedar context.addr has country && context.addr.country == "US " //false ``` -------------------------------- ### Represent a standard Cedar policy Source: https://docs.cedarpolicy.com/policies/json-format.html Example of a standard Cedar policy written in the native language syntax. ```cedar permit ( principal == User::"12UA45", action == Action::"view", resource in Folder::"abc" ) when { context.tls_version == "1.3" }; ``` -------------------------------- ### Migrating from Coarse-Grained to Fine-Grained Actions Source: https://docs.cedarpolicy.com/bestpractices/bp-fine-grained-permissions.html Example of updating a policy to replace a broad action with a set of specific, fine-grained actions. ```cedar permit ( principal == User::"6688f676-1aa9-456a-acf4-228340b54e9d", // action == Action::"read", -- coarse-grained permission -- commented out action in [ // -- finer grained permissions Action::"listFolderContents", Action::"viewFile" ], resource in Account::"c863f89b-461f-4fc2-b638-e5fa5f79a48b" ); ``` -------------------------------- ### Unnormalized URL string Source: https://docs.cedarpolicy.com/bestpractices/bp-normalize-data-input.html Example of a URL string containing inconsistent capitalization and path separators. ```json { "url": "https://EXAMPLE.COM////path/to/page?name=alice&color=red" } ``` -------------------------------- ### Define and reference a ReusedContext record Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of defining a record type in commonTypes and applying it to multiple actions. ```json ... "commonTypes": { "ReusedContext": { "type": "Record", "attributes": { "ip": { "type": "Extension", "name": "ipaddr" }, "is_authenticated": { "type": "Boolean" }, "timestamp": { "type": "Long" } } } }, "actions": { "view": { "appliesTo": { "principalTypes": [ "User" ], "resourceTypes": [ "Photo" ], "context": { "type": "ReusedContext" } } }, "upload": { "appliesTo": { "principalTypes": [ "User" ], "resourceTypes": [ "Server" ], "context": { "type": "ReusedContext" } } } } ``` -------------------------------- ### Example of a mutable identifier in a policy Source: https://docs.cedarpolicy.com/bestpractices/bp-mutable-identifiers.html This demonstrates a policy using a potentially mutable group name, which is discouraged. ```cedar permit ( principal in Group::"TeamExample", action in ..., resource in ... ); ``` -------------------------------- ### Define Request Context Source: https://docs.cedarpolicy.com/auth/entities-syntax.html Examples of defining request context objects using key-value pairs, supporting both implicit and explicit type escapes. ```json { "authnMfa": true } ``` ```json { "sourceIp": "10.0.1.101", "authnMfa": true } ``` -------------------------------- ### Apply conditional constraints to ReBAC policies Source: https://docs.cedarpolicy.com/overview/patterns.html These examples demonstrate adding attribute-based conditions to ReBAC policies to handle edge cases like terminated users or private resources. ```Cedar // Contributors policy, disallowed for terminated users permit ( principal is User, action in Action::"contributorActions", resource is List) when { resource has contributingUsers && principal in resource.contributingUsers } unless { principal has isTerminated && principal.isTerminated }; // Viewer policy, constrained for private resources permit ( principal is User, action in Action::"viewerActions", resource is List) when { resource has viewingUsers && principal in resource.viewingUsers } unless { resource has isPrivate and resource.isPrivate }; ``` -------------------------------- ### Define User and Group Entity Types Source: https://docs.cedarpolicy.com/schema/human-readable-schema.html Example showing the declaration of a User entity with attributes and a Group entity restricted to specific EIDs. ```cedar entity User in [Group] { personalGroup: Group, delegate?: User, blocked: Set, } tags String; @doc("Only three values of EIDs are valid for entities of type `Group`.") entity Group enum ["G1", "G2", "G3"]; ``` -------------------------------- ### Combine membership and discretionary policies Source: https://docs.cedarpolicy.com/overview/patterns.html Demonstrates how to implement admin roles, public access, and system daemon permissions within the same policy store. ```Cedar // admin role policy - membership based permit ( principal in Role::"Admin", action in Action::"adminActions", resource is List); // public access policy - constrained membership permit ( principal in UserGroup::"rootUserGroup", action in [Action::"viewList"] resource is List ) when { resource has isPublic && resource.isPublic } ; // housekeeping policy - discretionary permit ( principal == daemon::"housekeeping", action in Action::"housekeepingActions", resource is List); ``` -------------------------------- ### Example of an immutable identifier in a policy Source: https://docs.cedarpolicy.com/bestpractices/bp-mutable-identifiers.html This demonstrates the recommended approach using a UUID to ensure the identifier remains unique and non-recyclable. ```cedar permit ( principal in Group::"fcaf664d4f89fec0cda8", // "TeamExample" action in ..., resource in ... ); ``` -------------------------------- ### Invalid Shadowing Example Source: https://docs.cedarpolicy.com/schema/human-readable-schema.html Example of an invalid schema where a namespace definition shadows a global type definition. ```cedar type id = { group: String, name: String, }; namespace Demo { entity User { name: id, }; // ERROR - this definition of `id` would shadow the one above type id = String; } ``` -------------------------------- ### Java type checking example Source: https://docs.cedarpolicy.com/policies/syntax-operators.html An example of a Java expression that fails to type check despite being logically unreachable. ```java if (false) { return 1 == "hello"; } else { return true; } ``` -------------------------------- ### Create a policy template for dynamic sharing Source: https://docs.cedarpolicy.com/overview/patterns.html Use templates to define the policy structure, allowing the application to populate principal and resource IDs at runtime. ```Cedar // Template for ticket sharing permit ( principal == ?principal, action in Action::"Shared_TicketAccess", resource == ?resource) when { resource.status == "OPEN" } ; ``` -------------------------------- ### Define action group membership Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of an action that is a member of a specific action group. ```json "actions": { "viewAlbum": { … "memberOf": [ { "id": "viewImages", "type": "PhotoFlash::Images::Action" }, ], … } } ``` -------------------------------- ### Allow access to groups of entities Source: https://docs.cedarpolicy.com/policies/policy-examples.html Demonstrates various ways to grant access using groups, sets of actions, and role hierarchies. ```Cedar permit( principal in Group::"alice_friends", action == Action::"view", resource == Photo::"VacationPhoto94.jpg" ); ``` ```Cedar permit( principal == User::"alice", action == Action::"view", resource in Album::"alice_vacation" ); ``` ```Cedar permit( principal == User::"alice", action in [Action::"view", Action::"edit", Action::"delete"], resource in Album::"alice_vacation" ); ``` ```Cedar permit( principal == User::"alice", action in Photoflash::Role::"admin", resource in Album::"alice_vacation" ); ``` ```Cedar permit( principal == User::"alice", action in [Photoflash::Role::"viewer", Action::"edit"], resource in Album::"alice_vacation" ); ``` -------------------------------- ### Principal scope examples Source: https://docs.cedarpolicy.com/policies/syntax-policy.html Demonstrates various ways to constrain the principal element in a policy. ```cedar //matches any principal entity of any type principal //matches only the one specified entity of type User principal == User::"alice" //matches any principal in the hierarchy of the specified Group principal in Group::"alice_friends" //matches any principal of type User principal is User //matches any principal of type User in the hierarchy of the specified Group principal is User in Group::"alice_friends" ``` -------------------------------- ### Validate entity type format Source: https://docs.cedarpolicy.com/auth/entities-syntax.html Example of an invalid entity type containing whitespace. ```json "type": "User " ``` -------------------------------- ### Invalid 'in' Operator Usage Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Examples of invalid usage that result in evaluation and validation errors. ```Cedar "some" in ["some", "thing"] //error - these are strings, not entities. Use `contains` for set membership. "os" in {"os":"Windows "} //error - use `has` operator to check if a key exists ``` -------------------------------- ### Define Entity Type Name Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of declaring an entity type name within a namespace. ```json "My::Name::Space": { "entityTypes": { "UserGroup": { ... } // New entity type name } } ``` -------------------------------- ### Define RecInits syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Represents record initialization syntax using identifiers or strings as keys. ```ebnf RecInits ::= (IDENT | STR) ':' Expr {',' (IDENT | STR) ':' Expr} ``` -------------------------------- ### Resource creation authorization pattern Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Authorizes against the container resource since the target resource does not yet exist. ```Cedar principal = App::User::"alice" action = App::Action::"UploadPhoto" resource = App::Folder::"alice-vacation-2024" ``` -------------------------------- ### Define VAR syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Lists the built-in variable names. ```ebnf VAR ::= 'principal' | 'action' | 'resource' | 'context' ``` -------------------------------- ### Define entity attributes Source: https://docs.cedarpolicy.com/auth/entities-syntax.html Example of specifying primitive attributes within an entity's attrs object. ```json "attrs": { "department": "HardwareEngineering", "jobLevel": 5 } ``` -------------------------------- ### Context-based Set Membership Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Illustrates using context records to perform set membership checks. ```JSON { "groups ": [Group::"jane_family", Group::"jane_friends "] } ``` ```Cedar User::"alice" in context.groups User::"alice" in [Group::"jane_family", Group::"jane_friends"] ``` -------------------------------- ### Instantiate template-linked policies for role assignment Source: https://docs.cedarpolicy.com/bestpractices/bp-implementing-roles-templates.html Creates specific policy instances linking a user to a resource group using the defined template. ```cedar createPolicy ( template = "Approver-Role-assignment", principal = User::"Alice", resource = TimesheetGrp::"UK" ) ``` ```cedar createPolicy ( template = "Approver-Role-assignment", principal = User::"Alice", resource = TimesheetGrp::"France" ) ``` -------------------------------- ### Define Path Syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Defines namespace or path resolution syntax. ```ebnf Path ::= IDENT {'::' IDENT} ``` -------------------------------- ### List Email Messages HTTP Request Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html GET request to list messages belonging to a specific campaign. ```http GET /campaigns/campaign-001/messages ``` -------------------------------- ### Avoid Dynamic Policy Construction via String Concatenation Source: https://docs.cedarpolicy.com/other/security.html Demonstrates the insecure practice of building policies using string concatenation, which can lead to Cedar code injection. ```text let src = "permit (" + input + ", action == Action::\"view\", resource) when { principal.level > 3 }"; let policy = parse(src); addToPolicySet(policy); ``` ```text permit (principal == User::"alice", action == Action::"view", resource) when { principal.level > 3 }; ``` ```text "principal,action,resource); //" ``` ```text permit (principal,action,resource); //, action == ,Action::"view", resource) when { principal.level > 3 }; ``` -------------------------------- ### Overly Broad Policy Example Source: https://docs.cedarpolicy.com/bestpractices/bp-map-actions.html A policy that grants access to all resource types due to the use of a generic action. ```cedar // Grants View access to ALL resource types — documents, projects, dashboards, etc. permit( principal == ProjectApp::User::"alice", action == ProjectApp::Action::"View", resource ); ``` -------------------------------- ### Define Policy for New Country Expansion Source: https://docs.cedarpolicy.com/bestpractices/bp-implementing-roles-groups.html Example of adding a new policy to support a new region, such as Japan. ```Cedar // Role policy to approve Japanese timesheets permit ( principal in Role::"Approver-Japan", action in Action::"ApproverActions", resource in TimesheetGrp::"Japanese-timesheets" ); ``` -------------------------------- ### Represent a decimal function call in JSON Source: https://docs.cedarpolicy.com/policies/json-format.html Demonstrates the JSON representation for a simple extension function call. ```text decimal("10.0") ``` ```json { "decimal": [ { "Value": "10.0" } ] } ``` -------------------------------- ### Define ExtFun syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Represents an external function call, optionally qualified by a path. ```ebnf ExtFun ::= [Path '::'] IDENT ``` -------------------------------- ### Use common types in entity definitions Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of defining a primitive type alias and using it within entity attributes. ```json ... "commonTypes": { "name": { "type": "String", } }, "entityTypes": { "User": { "shape": { "type": "Record", "attributes": { "firstName": { "type": "name" }, "lastName": { "type": "name" } } } } } ``` -------------------------------- ### Define policy annotation syntax Source: https://docs.cedarpolicy.com/policies/syntax-policy.html Shows the standard format for attaching key-value metadata to a policy. ```cedar @annotationname("annotation value") ``` -------------------------------- ### Generic Action Schema Definition Source: https://docs.cedarpolicy.com/bestpractices/bp-map-actions.html An example of a schema using generic actions that apply to multiple resource types, which is discouraged. ```cedar namespace ProjectApp { entity User = {}; entity Project = {}; entity Task = {}; entity TaskComment = {}; entity Sprint = {}; entity Epic = {}; action Create appliesTo { principal: [User], resource: [Project, Task, TaskComment, Sprint, Epic] }; action View appliesTo { principal: [User], resource: [Project, Task, TaskComment, Sprint, Epic] }; action Update appliesTo { principal: [User], resource: [Project, Task, TaskComment, Sprint, Epic] }; action Delete appliesTo { principal: [User], resource: [Project, Task, TaskComment, Sprint, Epic] }; } ``` -------------------------------- ### Integer less than (<) operator examples Source: https://docs.cedarpolicy.com/policies/syntax-operators.html Compares long integer values. Operands must be of type long to avoid evaluation errors. ```cedar 3 < 303 //true principal.age < 22 //true (assuming principal.age is 21) 3 < "3" //error - operator not allowed on non-long false < true //error - operator not allowed on non-long "" < "zzz" //error - operator not allowed on non-long [1, 2] < [47, 0] //error - operator not allowed on non-long ``` -------------------------------- ### Reference entities across namespaces Source: https://docs.cedarpolicy.com/schema/json-schema.html Demonstrates how an entity type in one namespace can reference an entity type defined in another namespace. ```json { "ExampleCo::Clients": { "entityTypes": { "Manufacturer": { ... } }, "actions": { ... }, "annotations" : { "doc": "the namespace representing clients" } }, "ExampleCo::Furniture": { "entityTypes": { "Table": { "shape": { "type": "Record", "attributes": { "manufacturer": { "type": "Entity", "name": "ExampleCo::Clients::Manufacturer" } } } } }, "actions": { ... } } } ``` -------------------------------- ### Define EntList Syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Defines a list of entities. ```ebnf EntList ::= Entity {',' Entity} ``` -------------------------------- ### Reference common types within other common types Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of nesting common type references, ensuring no circular dependencies are formed. ```json ... "commonTypes": { "Person": { "type": "Record", "attributes": { "age": {"type": "Long"}, "name": {"type": "Name"} } }, "Name": { "type": "String"} }, "entityTypes": { "Employee": { "shape": { "type": "Person" } }, "Customer": { "shape": { "type": "Person" } } } ``` -------------------------------- ### Share record types across entities Source: https://docs.cedarpolicy.com/schema/json-schema.html Example of using a single record type definition for the shape of multiple entity types. ```json ... "commonTypes": { "Person": { "type": "Record", "attributes": { "age": {"type": "Long"}, "name": {"type": "String"} } } }, "entityTypes": { "Employee": { "shape": { "type": "Person" } }, "Customer": { "shape": { "type": "Person" } } } ``` -------------------------------- ### Policy with Validation Errors Source: https://docs.cedarpolicy.com/policies/validation.html Example policy containing type mismatches and attribute access errors that the validator will flag based on the schema. ```cedar permit ( principal, action == ExampleCo::Personnel::Action::"remoteAccess", resource ) when { principal.numberOfLatpops < 5 && // (1) principal.name > 3 && // (2) principal.jobLevel == "somethingelse" // (3) }; ``` -------------------------------- ### Define an Action with Applicability Constraints Source: https://docs.cedarpolicy.com/schema/human-readable-schema.html Defines an action named 'ViewDocument' with membership in specific action groups and constraints on principals, resources, and context. ```cedar action ViewDocument in [ReadActions, ExampleNS::Action::"Write"] appliesTo { principal: [User,Public], resource: Document, context: { network: ipaddr, browser: String } }; ``` -------------------------------- ### Define STR syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Defines string literals using fully-escaped Unicode. ```ebnf STR ::= Fully-escaped Unicode surrounded by '"'s ``` -------------------------------- ### Model Open Endpoints in Cedar Source: https://docs.cedarpolicy.com/bestpractices/bp-authorization-patterns.html Use this pattern for actions not scoped to a specific resource, such as login or signup, by targeting the application entity. ```Cedar principal = App::User::"alice" action = App::Action::"Login" resource = App::Application::"myApp" ``` -------------------------------- ### Define Access Syntax Source: https://docs.cedarpolicy.com/policies/syntax-grammar.html Defines property or index access syntax. ```ebnf Access ::= '.' IDENT ['(' [ExprList] ')'] | '[' STR ']' ```