10.5 Example of an OPA Policy Document

The following is an example of an OPA Policy Document written in Rego.

package {{PACKAGE}} 

import future.keywords.if 

default allow := false 

allow if user_is_owner 

allow if {
    user_is_employee
    action_is_read
} 

allow if {
    user_is_employee
    user_is_senior
    action_is_update
} 

allow if {
    user_is_customer
    action_is_read
    not pet_is_adopted
} 

user_is_owner if data.{{ENGINENAMESPACE}}.user_attributes[input.user].title == "owner" 

user_is_employee if data.{{ENGINENAMESPACE}}.user_attributes[input.user].title == "employee" 

user_is_customer if data.{{ENGINENAMESPACE}}.user_attributes[input.user].title == "customer" 

user_is_senior if data.{{ENGINENAMESPACE}}.user_attributes[input.user].tenure > 8 

action_is_read if input.action == "read" 

action_is_update if input.action == "update" 

pet_is_adopted if data.{{ENGINENAMESPACE}}.pet_attributes[input.resource].adopted == true

The following is the associated Data Document:

{
    "user_attributes": {
        "alice": {
            "tenure": 20,
            "title": "owner"
        },
        "bob": {
            "tenure": 15,
            "title": "employee"
        },
        "eve": {
            "tenure": 5,
            "title": "employee"
        },
        "dave": {
            "tenure": 5,
            "title": "customer"
        }
    },
    "pet_attributes": {
        "dog123": {
            "adopted": true,
            "age": 2,
            "breed": "terrier",
            "name": "toto"
        },
        "dog456": {
            "adopted": false,
            "age": 3,
            "breed": "german-shepherd",
            "name": "rintintin"
        },
        "dog789": {
            "adopted": false,
            "age": 2,
            "breed": "collie",
            "name": "lassie"
        },
        "cat123": {
            "adopted": false,
            "age": 1,
            "breed": "fictitious",
            "name": "cheshire"
        }
    }
}