Is there a way to do optional chaining with CEL/Ce...
# help
n
Is there a way to do optional chaining with CEL/Cerbos Policies? JS syntax:
<http://P.attr.org?.companies?.[role]|P.attr.org?.companies?.[role]> === "owner"
Our Principle object has optional fields we'd like to check, and it appears that CEL fails the whole eval if accessing an attribute that doesn't exist:
P.attr.a == "owner"
, if
a
doesn't exist. I can do has checks:
(has(P.attr.a) && P.attr.a == "owner")
that works, but it's becoming tedious when theres a few layers deep that all can be optional. For example we have the structure of
Principal > Org > Companies > Company >
and a "role" can exist at a company, if defined, otherwise on the org. Having to check if org has companies, then if org.companies has specific company id, then check the role, is a bit tedious but moreso risky we make a mistake in setting up policies as it's a bit non-intuitive, and the CEL runtime error fails silently in the Sandbox, resulting the eval as "false" making it tricky to identify the mistake.
d
Hi Nicholas, You can achieve a similar effect with the following pattern: put subexpressions that use different optional attributes into separate expressions of ’condition > match > any` section:
Copy code
condition:
      match:
        any:
          of:
          - expr: P.attr.org.companies.role == "owner"
          - expr: P.attr.org.role == "owner"
Here, the condition will be evaluated as true if the
role
attribute exists at the company or org level. This works because when Cerbos fails to evaluate a subexpression (due to a missing attribute), it automatically treats the subexpression as false.
n
Gotcha, thank you Dennis!