Rules

A rule describes a set of conditions that result in either true or false.

Rules in Sentinel are a first-class concept. They are used for making complex logic more understandable by breaking it down into a set of rules, for testing policies by asserting certain rules are passed, and more.

Writing Rules

Let's look at the Sentinel policy we wrote in the previous section:

hour = 4
main = rule { hour >= 0 and hour < 12 }

The logic in this policy is straightforward and easy to understand. However, it is common for policy logic to become much more complicated. Rules are the key abstraction for making complex logic understandable. We can turn the policy above into a set of rules:

hour = 4

past_midnight = rule { hour >= 0 }
before_noon   = rule { hour < 12 }

main = rule {
    past_midnight and
    before_noon
}

This policy is easier to read. Our original policy was already quite simple, but it is easy to imagine a more complex policy becoming much more readable by extracting logical expressions into a set of rules.

Rules don't just exist to make a policy more readable. They're also a testing and debugging point. For testing, you can assert that certain rules are certain values given a specific input to verify that your policy works as you expect. Testing and debugging are covered in later sections.

Conditional Rules

In many cases, a rule is only valid when something else is also true.

Consider the human language statement "before you eat, you must wash your hands." The rule "you must wash your hands" is only valid "before you eat". In any other scenario, the rule is meaningless. This is also true in a technical context. Imagine the rule "if the driver is Docker, you must not expose any ports." For this example, assume rules is_docker and has_no_exposed_ports exist. You can write this rule like this:

main = rule when is_docker { has_no_exposed_ports }

When is_docker is true, the rule is evaluated as normal. However, when is_docker is false, the rule always returns true, because the logic of the rule is meaningless.

Let's learn how to create more complex rules with logical expressions.