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 an HTTP API authorization policy in Rego that controls access based on the HTTP method, request path, and the requesting user's role.
Create authz.rego with package httpapi.authz and import rego.v1.
The policy evaluates the following input structure:
{
"method": "GET",
"path": "/api/orders",
"subject": {
"user": "alice"
}
}External data is available at data.user_roles (maps usernames to a role name) and data.role_permissions (maps role names to a list of allowed HTTP methods). Example:
{
"user_roles": {
"alice": "admin",
"bob": "readonly"
},
"role_permissions": {
"admin": ["GET", "POST", "PUT", "DELETE"],
"readonly": ["GET"]
}
}Critical requirement: Do not use import input or import input as <alias> at the top of the file. Always reference input fields directly (e.g. input.method, input.subject.user).
The policy must:
deny (i.e., default allow := false)GET /api/healthuser_role that resolves the current user's role from data.user_rolespermitted_methods that yields the set of methods allowed for the current user's roleallow rule that permits access when input.method is in permitted_methodsCreate authz_test.rego with package httpapi.authz_test and import rego.v1.
Use the with keyword to inject both input and data in every test. Include tests for:
GET /api/health with no user — should be allowedDELETE request — should be allowedGET request — should be allowedPOST request — should be denieddata.user_roles making any request — should be deniedRun opa test . -v and confirm all tests pass.