Open Policy Agent and Rego

Open Policy Agent, or OPA, evaluates policy against structured input and data. Rego is its declarative policy language. Begin by defining a decision contract: what trusted context the caller supplies, what result OPA returns, and what the enforcing application does with that result.

An allow result is not an action. The application, gateway or admission integration must enforce it at the intended boundary and handle errors deliberately. A correct policy evaluated on attacker-controlled identity fields can still authorize the wrong caller.

TL;DR

Quick Example

Save this teaching policy as authz.rego. It uses Rego v1 syntax and permits only a fictional read by a reader whose nonempty tenant matches the resource tenant. The application must supply authenticated subject context and a trusted resource lookup; a caller must not choose either authority field unchecked.

Save the following as authz_test.rego in the same isolated directory, then run opa test . -v from that directory with a compatible OPA executable. The example was written for OPA 1.x.

All five tests passed locally. A deliberately permissive replacement failed the denied cases, confirming the suite can catch that regression. These are local decisions only; no API enforcement, external policy/data service, Kubernetes admission or Gatekeeper installation was exercised.

Core Concepts

Decision and enforcement

OPA decouples decision-making from enforcement. It evaluates supplied structured input against policies and data and can return structured outputs beyond simple booleans. The caller’s interpretation is therefore part of the contract. OPA overview

Rules and undefined values

Rego expresses conditions over documents. A rule whose body is not satisfied can be undefined; references to absent values do not become trusted defaults automatically. The example gives allow an explicit false default and requires the positive conditions. Policy language

Tests express the boundary

OPA’s test framework discovers Rego test rules and supports replacing input for a case. Include the cases the policy must reject, not just the happy path. A passing suite is evidence for those cases, not a proof of completeness. Policy testing

Trace a request through the decision contract

Inventory the trust origin of each field. A request body can propose an operation; an authenticated session establishes a subject; an authoritative resource lookup supplies ownership or tenant context. Avoid combining these into a single unvalidated object simply because JSON makes it convenient.

Use object-level tests in the enforcing application. Confirm the denied request cannot reach the protected operation through another route, background job or cached response. The Rego tenant comparison is a teaching rule, not a complete multi-tenant authorization design.

Define behavior when OPA is unavailable, evaluation fails or required data is stale. The choice has availability and security consequences and must match the operation’s requirements. Do not silently convert an error into an allow result. Test the selected behavior under an isolated failure scenario.

Distribute policy as an operational change

Treat a policy revision like consequential application code. Review the change, run positive and negative tests, identify compatible input/data versions and stage its rollout. Keep the deployed policy identity visible in diagnostics so decisions can be explained after a revision changes.

Separate policy logic from the lifecycle of supporting data. A correct rule can make an obsolete decision when its group membership, inventory or resource attributes are stale. Define data ownership, update timing and what evidence shows that a consumer loaded the intended revision.

Restrict who can publish policies and who can change the authority data. Verify provenance and integrity through the selected distribution mechanism. Avoid giving an untrusted caller the ability to select a more permissive policy bundle or data revision.

For a rollback, identify both policy and data compatibility. Reverting code while retaining incompatible input or data can produce a new failure. Test a representative old/new transition and an emergency recovery path before broad enforcement.

Measure evaluation and integration costs on representative input sizes and request patterns. Local microsecond figures from a tiny test are not a throughput or latency promise for an application. Include input construction, data access, network calls and enforcement overhead in the measurement scope.

Understand what Gatekeeper adds

Gatekeeper integrates policy into Kubernetes through admission webhooks and CRD-based policy resources. Validation uses ConstraintTemplate and Constraint resources; audit reports violations in existing resources. Validation and mutation are separately configured concerns. Gatekeeper introduction

The standalone input.subject example is not a drop-in Gatekeeper template. AdmissionReview input, template structure, supported Rego dialect/version and constraint parameters must match the actual Gatekeeper integration. Translate the policy only after defining that input contract.

Pilot constraints with appropriate observation and enforcement settings. Test intended allowed and denied Kubernetes requests, excluded scopes, updates, existing-resource audit and webhook failure behavior. An audit violation report does not by itself prove an admission request was blocked or that the existing object was remediated.

Plan recovery access before enabling a broad constraint. A policy that prevents its own authorized repair can turn a rule error into a platform incident. Keep exceptions narrow, accountable and observable, then verify the intended rule after recovery. No such cluster operation was performed for the local policy fixture.

Best Practices

Keep denied cases prominent

Test other tenants, missing context, wrong actions and malformed values. Include a regression that the suite must detect.

Enforce where the action occurs

Tie the decision to the actual protected operation and authoritative resource. Recheck alternative paths and stale cached authority.

Retain revision context

Record deployed policy/data identities and the necessary diagnostic context without storing sensitive input indiscriminately.

Common Mistakes

Bad: Trusting role and tenant directly from a request body.

Correct: Build decision input from authenticated subject context and authoritative resource data.

Bad: Treating a successful local policy test as deployed enforcement.

Correct: Test the caller’s protected operation, errors, alternate routes and actual integration.

Bad: Copying standalone Rego into Gatekeeper unchanged.

Correct: Use the correct admission input, template/constraint schema and supported language version.

FAQ

Does OPA authenticate users?

The decision engine evaluates supplied input. Authentication and trustworthy context construction belong to the surrounding integration.

Does a false default handle every failure?

It makes this decision defined when positive conditions do not match. The caller must still handle evaluation errors, unavailable services and stale required data.

Is Gatekeeper audit the same as admission denial?

No. Audit examines existing resources and reports violations. Admission enforcement and its failure behavior need separate tests.

Related Topics

References