DEV Community

Michael Chenetz
Michael Chenetz

Posted on

What is Rego and how do you use it?

The Rego language, used primarily with the Open Policy Agent (OPA), is a high-level declarative language for writing policy as code. Here's a basic illustration of how to use Rego:

Example Scenario: User Access Control

Suppose we have a system where we need to control user access based on their roles.

Data Model

First, define a simple data model. In a real-world scenario, this could be JSON data representing user roles and permissions:

{
  "users": {
    "alice": {"role": "admin"},
    "bob": {"role": "developer"},
    "eve": {"role": "intern"}
  }
}
Enter fullscreen mode Exit fullscreen mode

Policy Definition

Next, write a Rego policy to specify who can access what. For instance, we might want only admins to access sensitive data:

package example

default allow = false

allow {
  input.user.role == "admin"
}
Enter fullscreen mode Exit fullscreen mode

In this policy:

  • The package keyword defines a namespace (example).
  • default allow = false sets the default decision to deny access.
  • The allow rule permits access if the user's role is "admin".

Query

You'd then query this policy with input data to make access decisions. The input might look like:

{
  "user": {"role": "admin"}
}
Enter fullscreen mode Exit fullscreen mode

You'd ask OPA a question like: "Given this input, should access be allowed?" If the input user role is "admin", the policy allows access, returning true.

Use in Code

In application code, you'd typically integrate OPA as a service or library. The application sends input data (e.g., user information) to OPA and gets back a decision based on your Rego policies.

This example is simplistic but illustrates the basic use of Rego. Real-world scenarios often involve more complex policies, multiple data sources, and integration with services like Kubernetes for dynamic policy enforcement.

Top comments (0)