The Security Policy Enforcement Problem
Without policy enforcement, container security depends on each developer remembering to add securityContext, restrict privileged access, and scan images. Some remember. Most don't. Security reviews try to catch violations, but that's slow and scales poorly. OPA solves this by making security policies executable and automated: you define once what containers must satisfy (run as non-root, no privileged escapes, signed images only), and OPA enforces it automatically on every deployment. No configuration drift, no reliance on human memory, no surprise violations at 3 AM.
Open Policy Agent (OPA) is a general-purpose policy engine that lets you define, test, and enforce policies as code. OPA decouples policy decisions from application logic, making policies centralized, reusable, testable, and auditable. It's widely used for container and Kubernetes security, but works for any system needing automated policy decisions.
The Problem: Manual Security Decisions
Without a policy engine, security decisions are enforced manually or hardcoded. Without explicit requirements, developers might forget to add securityContext, might use privileged mode, and enforcement becomes inconsistent. This creates inconsistency as each developer implements security differently, compliance gaps as some resources miss required controls, no audit trail to track policy violations, and requires manual reviews that are time-consuming.
How OPA Works
OPA evaluates policies against data. The policy engine takes input data (such as a Kubernetes Pod definition) and processes it through three main steps: loading the policy rules written in Rego, evaluating those rules against the input data, and making a final decision. The engine then outputs a decision—Allow, Deny, or a custom response.
OPA Components
Rego is a policy language similar to Prolog/SQL. The Engine evaluates Rego policies against data. Bundles distribute policies efficiently. Webhooks integrate with Kubernetes (Gatekeeper).
Rego: The Policy Language
Rego is a declarative policy language optimized for policy. An example policy enforces that containers must run as non-root. The policy package is kubernetes.admission and imports data.kubernetes.namespaces. The deny rule checks if a container runs as root (securityContext.runAsUser == 0) and generates a denial message.
Rego Basics
Simple Policy: Require securityContext
The policy denies if a container lacks securityContext by checking if container does not have securityContext and generating a message requiring it.
Policy with Details
The policy denies if readOnlyRootFilesystem is not true by checking the filesystem property and generating a message requiring it.
Multiple Conditions
The policy denies if container runs as root AND is not in a privileged namespace by checking UID and namespace membership, then generating a message.
Gatekeeper: OPA for Kubernetes
Gatekeeper is the Kubernetes integration for OPA. It acts as an admission controller. When a developer creates a Pod, the Kubernetes API Server intercepts the request and sends it to the Gatekeeper webhook. Gatekeeper loads the policy from a ConfigMap, evaluates the policy using the OPA engine, and returns an Allow or Deny decision. The result is either the pod being accepted if policy allows, or rejected if policy denies.
Installing Gatekeeper
You can install Gatekeeper on Kubernetes using kubectl to apply the official deployment. Gatekeeper creates a webhook for admission control, CRDs for ConstraintTemplate and Constraint, and a namespace for system components.
Container Security Policy Example
Step 1: Define ConstraintTemplate (Rego Policy)
A ConstraintTemplate includes metadata naming it k8srequiredcontainersecurity and spec with CRD names and rego policy. The rego policy denies containers running as root, denies if allowPrivilegeEscalation is not false, and denies if readOnlyRootFilesystem is not true.
Step 2: Create Constraint (Enforce Policy)
A Constraint applies the policy to Pod resources with parameters and match rules.
Step 3: Result
Attempting to create a non-compliant pod results in an admission webhook error stating the policy violation. Creating a compliant pod results in successful creation.
Common Container Security Policies
Policy 1: No Privileged Containers
The policy denies if any container has privileged=true, generating an error message.
Policy 2: No Host Network
The policy denies if the pod spec allows hostNetwork=true.
Policy 3: Resource Limits Required
The policy denies if containers are missing CPU or memory limits.
Policy 4: Image Registry Whitelist
The policy denies if images are not from approved registries.
Policy 5: Signed Images Only
The policy denies if container images lack required signatures.
OPA for Other Systems
OPA isn't just for Kubernetes. It works with API authorization (allowing access based on user role), build pipeline policy (requiring SBOM in artifacts), and data access control (RBAC for data access).
Testing OPA Policies
You can install OPA CLI and test policies using opa test security-policies/ -v, which outputs test pass/fail results.
Unit Testing Policies
Test cases can verify that non-root containers pass the policy and root containers fail the policy. Each test case sets up input data and verifies the policy response.
CleanStart and OPA
CleanStart Source Intelligence Core enforces supply chain policies using OPA/Gatekeeper, requires SBOM presence and quality, enforces SLSA level requirements, mandates image signing and signature verification, validates VEX statements for vulnerability context, and ensures compliance with security benchmarks.
Example policy requires SBOM and provenance attestations by denying if SBOM is absent and denying if provenance attestation is absent.
OPA Best Practices
To implement OPA effectively, start simple by beginning with basic policies and adding complexity gradually. Version policies by using git to track policy changes. Test thoroughly by unit testing all policies with positive and negative cases. Document rules by including comments explaining policy intent. Audit violations by logging all policy violations for compliance. Roll out gradually by starting in audit mode and moving to enforce mode. Review regularly by periodically auditing and updating policies. Organize policies by grouping related policies in packages.
Audit vs Enforce Modes
Audit mode logs violations without blocking. Enforce mode blocks violations.
Related Concepts
Container Security: OPA enforces container security policies. CIS Benchmarks: CIS controls can be implemented as OPA policies. SLSA: OPA can enforce SLSA level requirements. Admission Control: Gatekeeper implements admission control via OPA. Policy-as-Code: OPA is the leading policy-as-code platform.
CleanStart Admission Control Policies
For ready-to-use OPA/Gatekeeper and Kyverno policies tailored to CleanStart deployments (registry enforcement, image signing verification, pod security, SBOM attestation), see OPA Gatekeeper Policies for CleanStart and Kyverno Policies for CleanStart.
Further Reading
OPA Official Documentation - Complete OPA guide. Gatekeeper Documentation - Kubernetes integration. Rego Language Reference - Policy language guide. OPA Playground - Try OPA policies interactively.
