Conditions :: Cerbos Authorization Management Platform // Documentation

Conditions

This documentation is for
a previous
version of Cerbos. Choose 0.53.0 from the version picker at the top right or navigate to https://docs.cerbos.dev for the latest version.

A powerful feature of Cerbos policies is the ability to define conditions that are evaluated against the data provided in the request. Conditions are written using the Common Expression Language (CEL).

Cerbos ships with an interactive REPL that can be used to experiment with writing CEL conditions. It can be started by running cerbos repl. See the REPL documentation for more information.

Every condition expression must evaluate to a boolean true/false value. A condition block in a policy can contain either a single condition expression, or multiple expressions combined using the all, any, or none operators. These logical operators may be nested.

Condition block

condition:
  match:
    all:
      of:
        - expr: request.resource.attr.status == "PENDING_APPROVAL"
        - expr: >
            "GB" in request.resource.attr.geographies

Top-level identifiers

Within a condition expression, you have access to several top-level identifiers:

request

Data provided in the check or plan request (principal, resource, and auxiliary data).

runtime

Additional data computed while evaluating the policy.

variables

Variables declared in the variables section of the policy.

constants

Variables declared in the constants section of the policy.

globals

Global variables declared in the policy engine configuration.

There are also single-letter aliases available to allow you to write terser expressions:

P

request.principal

R

request.resource

V

variables

C

constants

G

globals

The request object

request:
  principal: (1)
    id: alice (2)
    roles: (3)
      - employee
    attr: (4)
      geography: GB

resource: (5)
    kind: leave_request (6)
    id: XX125 (7)
    attr: (8)
      owner: alice

auxData: (9)
    jwt: (10)
      iss: acme.corp
1 The principal whose permissions are being checked.
2 ID of the principal.
3 Static roles that are assigned to the principal by your identity management system.
4 Free-form context data about the principal.
5 The resource on which the principal is performing actions.
6 Resource kind.
7 ID of the resource instance.
8 Free-form context data about the resource instance.
9 Auxiliary data sources.
10 JWT claims.

The runtime object

runtime:
  effectiveDerivedRoles: (1)
    - owner
    - gb_employee
1 Derived roles that were assigned to to the principal by Cerbos while evaluating the policy. This is only populated in expressions in resource policies, and only includes derived roles that are referenced in at least one policy rule.

Expressions and blocks

Single boolean expression

condition:
  match:
    expr: P.id.matches("^dev_.*")

all operator: all expressions must evaluate to true (logical AND)

condition:
  match:
    all:
      of:
        - expr: R.attr.status == "PENDING_APPROVAL"
        - expr: >
            "GB" in R.attr.geographies
        - expr: P.attr.geography == "GB"

any operator: only one of the expressions has to evaluate to true (logical OR)

condition:
  match:
    any:
      of:
        - expr: R.attr.status == "PENDING_APPROVAL"
        - expr: >
            "GB" in R.attr.geographies
        - expr: P.attr.geography == "GB"

none operator: none of the expressions should evaluate to true (logical negation)

condition:
  match:
    none:
      of:
        - expr: R.attr.status == "PENDING_APPROVAL"
        - expr: >
            "GB" in R.attr.geographies
        - expr: P.attr.geography == "GB"

Nesting operators

condition:
  match:
    all:
      of:
        - expr: R.attr.status == "DRAFT"
        - any:
            of:
              - expr: R.attr.dev == true
              - expr: R.attr.id.matches("^[98][0-9]+")
        - none:
            of:
              - expr: R.attr.qa == true
              - expr: R.attr.canary == true

The above nested block is equivalent to the following:

condition:
  match:
    expr: >
      (R.attr.status == "DRAFT" &&
        (R.attr.dev == true || R.attr.id.matches("^[98][0-9]+")) &&
        !(R.attr.qa == true || R.attr.canary == true))

Quotes in expressions

Single and double quotes have special meanings in YAML. To avoid parsing errors when your expression contains quotes, use the YAML block scalar syntax or wrap the expression in parentheses.

expr: >
  "GB" in R.attr.geographies
expr: ("GB" in R.attr.geographies)

Policy variables

To avoid duplication in condition expressions, you can define variables and constants in policies.

Auxiliary data

If you have auxiliary data sources configured, they can be accessed using request.auxData.

Accessing JWT claims

"cerbie" in request.auxData.jwt.aud && request.auxData.jwt.iss == "cerbos"

Operators

Operator Description
! Logical negation (NOT)
- Subtraction/numeric negation
!= Unequals
% Modulo
&& Logical AND
`
* Multiplication
+ Addition/concatenation
/ Division
<= Less than or equal to
< Less than
== Equals
>= Greater than or equal to
> Greater than
in Membership in lists or maps
? : Ternary condition (if-then-else)

Durations

Suffix Unit
ns Nanoseconds
us Microseconds
ms Milliseconds
s Seconds
m Minutes
h Hours

Test data

...
"resource": {
  "kind": "leave_request",
  "attr": {
    "cooldownPeriod": "3750s",
    "lastAccessed": "2021-04-20T10:00:20.021-05:00"
  }
}
... 
Function Description
duration Convert a string to a duration. The string must contain a valid duration suffixed by one of ns, us, ms, s, m or h. E.g. 3750s
getHours Get hours from a duration
getMilliseconds Get milliseconds from a duration
getMinutes Get minutes from a duration
getSeconds Get seconds from a duration
timeSince Time elapsed since the given timestamp to current time on the server. This is a Cerbos extension to CEL

Hierarchies

The hierarchy functions are Cerbos-specific extensions to CEL.

Test data

...
"principal": {
  "id": "john",
  "roles": ["employee"],
  "attr": {
    "scope": "foo.bar.baz.qux",
  }
},
"resource": {
  "kind": "leave_request",
  "attr": {
    "scope": "foo.bar",
  }
}
...
Function Description
hierarchy Convert a dotted string or a string list to a hierarchy
hierarchy Convert a delimited string representation to a hierarchy
ancestorOf Returns true if the first hierarchy shares a common prefix with the second hierarchy
commonAncestors Returns the common ancestor hierarchy
descendentOf Mirror function of ancestorOf
immediateChildOf Returns true if the first hierarchy is a first-level child of the second hierarchy
immediateParentOf Mirror function of immediateChildOf
overlaps Returns true if one of the hierarchies is a prefix of the other
siblingOf Returns true if both hierarchies share the same parent
size Returns the number of levels in the hierarchy
[] Access a level in the hierarchy

IP addresses

The IP address functions are Cerbos-specific extensions to CEL.

Test data

...
"principal": {
  "id": "elmer_fudd",
  "attr": {
    "ipv4Address": "192.168.0.10",
    "ipv6Address": "2001:0db8:0000:0000:0000:0000:1000:0000"
  }
}
...
Function Description
inIPAddrRange Check whether the IP address is in the range defined by the CIDR

Lists and maps

Test data

...
"principal": {
  "id": "elmer_fudd",
  "attr": {
    "id": "125",
    "teams": ["design", "communications", "product", "commercial"],
    "limits": {
        "design": 10,
        "product": 25
    },
    "clients": {
      "acme": {"active": true},
      "bb inc": {"active": true}
    }
  }
}
...
Operator/Function Description
+ Concatenates lists
[] Index into a list or a map
all Check whether all elements in a list match the predicate.
distinct Returns the distinct elements of a list
except Produces the set difference of two lists
exists Check whether at least one element matching the predicate exists in a list or map.
exists_one Check that only one element matching the predicate exists.
filter Filter a list using the predicate.
flatten Flattens a list.
hasIntersection Checks whether the lists have at least one common element
in Check whether the given element is contained in the list or map
intersect Produces the set intersection of two lists
isSubset Checks whether the list is a subset of another list
lists.range Returns a list of integers from 0 to n-1
map Transform each element in a list
reverse Returns the elements of a list in reverse order
size Number of elements in a list or map
slice Returns a new sub-list using the indexes provided
sort Sorts a list with comparable elements
sortBy Sorts a list by a key value
transformList Converts a map or a list into a list value.
transformMap Converts a map or a list into a map value.
transformMapEntry Converts a map or a list into a map value; however, this transform expects the entry expression be a map literal.

Math

Function Description
math.abs Returns the absolute value of the numeric type provided as input
math.bitAnd Performs a bitwise-AND operation over two int or uint values
math.bitNot Function which accepts a single int or uint and performs a bitwise-NOT ones-complement of the given binary value
math.bitOr Performs a bitwise-OR operation over two int or uint values
math.bitShiftLeft Perform a left shift of bits on the first parameter
math.bitShiftRight Perform a right shift of bits on the first parameter
math.bitXor Performs a bitwise-XOR operation over two int or uint values
math.ceil Compute the ceiling of a double value
math.floor Compute the floor of a double value
math.greatest Get the greatest valued number present in the arguments
math.isFinite Returns true if the value is a finite number
math.isInf Returns true if the input double value is -Inf or +Inf
math.isNaN Returns true if the input double value is NaN, false otherwise
math.least Get the least valued number present in the arguments
math.round Rounds the double value to the nearest whole number
math.sign Returns the sign of the numeric type, either -1, 0, 1
math.trunc Truncates the fractional portion of the double value

SPIFFE

The SPIFFE functions are Cerbos-specific extensions to CEL.

Test data

...
"principal": {
  "id": "spiffe://cerbos.dev/ns/privileged/sa/curl",
  "roles": ["api"],
}
...
Function Description
spiffeID.isMemberOf Check whether the ID belongs to given trust domain
spiffeID.path Get the path element of ID
spiffeID.trustDomain Get the trust domain of ID
spiffeMatchAny Match any SPIFFE ID
spiffeMatchExact Match a single SPIFFE ID
spiffeMatchOneOf Match any one of SPIFFE IDs
spiffeMatchTrustDomain Match any ID from the trust domain
spiffeTrustDomain.id Fully qualified trust domain ID
spiffeTrustDomain.name Name of trust domain

Strings

Test data

...
"resource": {
  "kind": "leave_request",
  "attr": {
    "id": "125",
    "department": "marketing"
  }
}
...
Function Description
base64.encode Encode as base64
base64.decode Decode base64
charAt Get the character at given index
contains Check whether a string contains the given substring
endsWith Check whether a string has the given suffix
format Format a string with the given arguments
indexOf Index of the first occurrence of the given character
lastIndexOf Index of the last occurrence of the given character
lowerAscii Convert ASCII characters to lowercase
matches Check whether a string matches a RE2 regular expression
replace Replace all occurrences of a substring
size Get the length of the string
split Split a string using a delimiter
startsWith Check whether a string has the given prefix
substring Selects a substring from the string
trim Remove whitespace from beginning and end
upperAscii Convert ASCII characters to uppercase

Timestamps

All timestamp getters (getHours, getMinutes, getDayOfWeek, and similar) take a time zone parameter. If omitted, the 'UTC' time zone is used by default.

Test data

...
"resource": {
  "kind": "leave_request",
  "attr": {
    "lastAccessed": "2021-04-20T10:00:20.021-05:00",
    "lastUpdateTime": "2021-05-01T13:34:12.024Z",
  }
}
...
Function Description
timestamp Convert an RFC3339 formatted string to a timestamp
getDate Get day of month from a timestamp
getDayOfMonth Get day of month from a timestamp. Returns a zero-based value
getDayOfWeek Get day of week from a timestamp. Returns a zero-based value where Sunday is 0
getDayOfYear Get day of year from a timestamp. Returns a zero-based value
getFullYear Get full year from a timestamp
getHours Get hours from a timestamp
getMilliseconds Get milliseconds from a timestamp
getMinutes Get minutes from a timestamp
getMonth Get month from a timestamp. Returns a zero-based value where January is 0
getSeconds Get seconds from a timestamp
now Current time on the server. This is a Cerbos extension to CEL
timeSince Time elapsed since the given timestamp to current time on the server. This is a Cerbos extension to CEL

Example: Assert that more than 36 hours has elapsed between last access time and last update time

timestamp(R.attr.lastUpdateTime) - timestamp(R.attr.lastAccessed) > duration("36h")

Example: Add a duration to a timestamp

timestamp(R.attr.lastUpdateTime) + duration("24h") == timestamp("2021-05-02T13:34:12.024Z")