Skip to main content

Go vs Rego for Policy as Code

info

Beta Content If you've found a problem with this documentation or would like to suggest improvements, please join us in the Styra Community Slack!

Go is a statically typed, compiled programming language. It is commonly used in cloud native environments for building services and APIs.

Go is generally well suited to such use cases. However, when it comes to expressing policy code, it can be verbose when expressing large policies that must unpack unstructured or untrusted data safely.

This guide presents a series of examples illustrating how a policy can be expressed in Go, and the corresponding Rego code for comparison.

Check If a User Is an Admin

Admin status is often encoded in a JWT (JSON Web Token). This example shows how to extract information from a JWT and make an authorization decision based on it. The example uses an insecure secret to verify the JWT for brevity.

Go

package main

import (
"fmt"

"github.com/golang-jwt/jwt"
)

func allow(tokenString string) (bool, error) {
token, err := jwt.Parse(
tokenString,
func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}

return []byte("pa$$w0rd"), nil
},
)
if err != nil {
return false, fmt.Errorf("failed to parse token: %v", err)
}

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
roles, ok := claims["roles"].([]any)
if !ok {
return false, nil
}
if slices.Contains(roles, "admin") {
return true, nil
}
}

return false, nil
}

Rego

package example

import rego.v1

claims := io.jwt.decode(input.token)[1] if {
io.jwt.verify_hs256(input.token, "pa$$w0rd")
}

default allow := false

allow if "admin" in claims.roles

Note: Verifying JWTs with a hard-coded secret is insecure and is used here for example only, please refer to the OPA documentation on Token Verification for more information on how to securely verify JWTs.

Grant Access Based on Inherited Permissions

Staff roles are used to define permissions that a given user has within an organization. In this example, we show how permissions can be inherited from other roles based on the organization's staff hierarchy. Rego's graph.reachable built-in function not only keeps the policy concise but is also safe from infinite recursion caused by cyclic dependencies in the staff hierarchy.

Go

package main

import (
"fmt"
"slices"
)

var manages = map[string][]string{
"manager": {"supervisor", "security"},
"supervisor": {"assistant"},
"security": {},
"assistant": {},
}

var datasetPermissions = map[string][]string{
"manager": {"salaries"},
"supervisor": {"rotas"},
"security": {"cctv"},
"assistant": {"product_prices"},
}

func reachableRolesForRole(role string) []string {
roles := []string{role}

for _, r := range manages[role] {
roles = append(roles, r)
roles = append(
roles,
reachableRolesForRole(r)...,
)
}

return roles
}

func allow(role, dataset string) (bool, error) {
inheritableRoles := reachableRolesForRole(role)

for _, r := range inheritableRoles {
if datasets, ok := datasetPermissions[r]; ok {
if slices.Contains(datasets, dataset) {
return true, nil
}
}
}

return false, nil
}

Rego

package example

import rego.v1

manages := {
"manager": {"supervisor", "security"},
"supervisor": {"assistant"},
"security": set(),
"assistant": set(),
}

dataset_permissions := {
"manager": {"salaries"},
"supervisor": {"rotas"},
"security": {"cctv"},
"assistant": {"product_prices"},
}

default allow := false

allow if {
some inherited_role in graph.reachable(
manages, {input.role}
)
input.dataset in dataset_permissions[inherited_role]
}

Validate User-Generated Content

Policy is often used to guide users when they make mistakes. Validation of user-generated resources can be complicated and often needs to be implemented in many applications. This example compares code for validating a user-submitted blog post and shows how Rego rules can be defined incrementally.

Go

package main

import (
"fmt"
"strings"
)

func validations(input map[string]interface{}) []string {
var messages []string

// ensure that title and content are set
fields := []string{"title", "content"}
for _, field := range fields {
if val, ok := input[field]; !ok || val == "" {
messages = append(messages, fmt.Sprintf("Value missing for field '%s'", field))
}
}

// ensure that title starts with a capital letter
if title, ok := input["title"].(string); ok {
if title != "" && title[0] < 'A' || title[0] > 'Z' {
messages = append(messages, "Title must start with a capital")
}
}

// ensure user identifier is set
user, ok := input["user"].(map[string]interface{})
if !ok {
messages = append(messages, "User email or id must be set")
} else {
_, hasEmail := user["email"]
_, hasId := user["id"]
if !hasEmail && !hasId {
messages = append(messages, "User email or id must be set")
}
if email, ok := user["email"].(string); ok {
// ensure example.com emails are not allowed
if strings.HasSuffix(email, "example.com") {
messages = append(messages, "example.com emails not allowed")
}
}
}

return messages
}

Rego

package example

import rego.v1

# ensure title and content are set
validations contains message if {
some field in {"title", "content"}
object.get(input, field, "") == ""
message := sprintf("Value missing for field '%s'", [field])
}

# ensure title starts with a capital letter
validations contains "Title must start with a capital" if {
not regex.match(`^[A-Z]`, input.title)
}

# ensure user identifier is set
validations contains "User email or id must be set" if {
not input.user.email
not input.user.id
}

# ensure example.com emails are not allowed
validations contains "example.com emails not allowed" if {
endswith(input.user.email, "@example.com")
}

If you've found a problem with this documentation or would like to suggest improvements, please join us in the Styra Community Slack!