Skip to content

Instantly share code, notes, and snippets.

View anderseknert's full-sized avatar
👨‍💻
Hacking on all things OPA

Anders Eknert anderseknert

👨‍💻
Hacking on all things OPA
View GitHub Profile
@anderseknert
anderseknert / or_array.rego
Created September 20, 2023 12:54
Or array
arr := [x | some x in input.my_array]
@anderseknert
anderseknert / or_array.js
Created September 20, 2023 12:53
Imperative OR array
arr = my_array || []
@anderseknert
anderseknert / object_get.rego
Created September 20, 2023 12:52
object.get
allow if {
# return input.user.name, or "anyomous" if the lookup fails
user := object.get(input, ["user", "name"], "anonymous")
user != "anonymous"
# ... more conditions
}
@anderseknert
anderseknert / object_or.rego
Created September 20, 2023 12:51
Object-based OR
deny := message if {
code_reason_map := {
400: "Bad request",
404: "Not found",
500: "Internal server error",
}
message := code_reason_map[status_code]
}
allow {
# Simple way to "inline" an OR check — turn it into a "contains" problem
input.request.method in {“HEAD”, “GET”}
}
# Expressions may be evaluated in any order
allow if expression1
allow if expression2
allow if expression3
# Expressions evaluated from top to bottom
allow if {
expression1
} else {
expression2
@anderseknert
anderseknert / pattern_matching.rego
Created September 20, 2023 12:48
Pattern matching
# First name may be either "joe" or "jane" for function to evaluate
# No rule body needed as argument passed will be matched for equality
allowed_firstname("joe")
allowed_firstname("jane")
# This works with multiple arguments too, where only some are matched
# statically
alcohol_allowed("Sweden", age) if age > 18
alcohol_allowed("USA", age) if age > 21
alcohol_allowed(country, age) if {
@anderseknert
anderseknert / pattern_matching.rego
Created September 20, 2023 12:47
Pattern matching
# First name may be either "joe" or "jane" for function to evaluate
allowed_firstname(name) if name == "joe"
allowed_firstname(name) if name == "jane"
@anderseknert
anderseknert / multiple_outputs.rego
Created September 20, 2023 12:47
Multiple outputs
package play
import future.keywords.if
import future.keywords.in
# Both of the conditions could be true
validate_user(user) := "valid" if "admin" in user.roles
validate_user(user) := "invalid" if not user.email
valid := validate_user(input.user)
@anderseknert
anderseknert / helper_functions.rego
Created September 20, 2023 12:46
Helper functions
package policy
import future.keywords.if
default allow := false
allow if {
idx := indexof(input.user.email, "@")
fullname := substring(input.user.email, 0, idx)
firstname := lower(split(fullname, ".")[0])