Rego is the declarative policy language used by Open Policy Agent (OPA) for writing and enforcing policies across cloud-native stacks, featuring data-driven rules, comprehensions, and 200+ built-in functions for infrastructure, security, and compliance automation.
Overall
score
97%
Create a role-based access control (RBAC) policy in Rego that controls access to documents based on user roles.
Create rbac.rego with package policy.rbac and import rego.v1.
The policy evaluates the following input structure:
{
"user": "alice",
"action": "write",
"resource": "document:123"
}External role data is available at data.user_roles (maps usernames to a list of role names) and data.role_permissions (maps role names to a list of permitted actions). Example:
{
"user_roles": {
"alice": ["editor"],
"bob": ["viewer"],
"carol": ["admin"]
},
"role_permissions": {
"admin": ["read", "write", "delete"],
"editor": ["read", "write"],
"viewer": ["read"]
}
}The policy must:
deny (i.e., default allow := false)user_has_role[role] that yields each role assigned to input.user via data.user_rolesuser_has_permission[action] that yields each action permitted to any of the user's roles via data.role_permissionsallow rule that permits access when input.action is in user_has_permissionCreate rbac_test.rego with package policy.rbac_test and import rego.v1.
Use the with keyword to inject both input and data in every test. Include tests for:
delete action (should be allowed)write action (should be allowed)read action (should be allowed)write action (should be denied)Run opa test . -v and confirm all tests pass.