Table of Contents

Open Policy Agent (OPA)

OPA (Open Policy Agent) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the entire stack. It decouples policy decisions from application code, providing a flexible and scalable way to manage and enforce policies in diverse environments, including microservices, Kubernetes, APIs, and more.

Key Features

Benefits

Code Examples

1. **Rego Policy:**

```rego package example

  1. Allow access if the user is an admin

allow {

   input.user.role == "admin"
}

  1. Allow access if the user is the owner of the resource

allow {

   input.user.id == input.resource.owner
} ```

This policy allows access to a resource if the user is either an admin or the owner of the resource.

2. **Kubernetes Admission Control Policy (Rego):**

```rego package kubernetes.admission

deny[msg] {

   input.request.kind.kind == "Pod"
   not input.request.object.spec.containers[_].image =~ "^my-registry/"
   msg := "Image must be from my-registry"
} ```

This policy denies the creation of pods unless their container images are sourced from the “my-registry” registry.

3. **Using OPA as a Library (Go):**

```go import (

   "context"
   "fmt"
   "github.com/open-policy-agent/opa/rego"
)

func main() {

   // Prepare the Rego query and input data
   query := rego.New(
       rego.Query("data.example.allow"),
       rego.Module("example.rego", `
           package example
           allow {
               input.user.role == "admin"
           }
       `),
   )
   inputData := map[string]interface{}{
       "user": map[string]interface{}{
           "role": "user",
       },
   }
   // Evaluate the policy
   ctx := context.Background()
   results, err := query.Eval(ctx, rego.EvalInput(inputData))
   if err != nil {
       // Handle error
   }
   // Check the result
   allow := results.Allowed()
   fmt.Println("Access allowed:", allow) 
} ```

This Go code snippet demonstrates how to use OPA as a library to evaluate a Rego policy and make an authorization decision based on the input data.

Additional Resources