30 November 2026

Policy as Code Framework: How It Works and Where to Start

Reza Khosravi

Table of Contents

Policy as Code Framework: How It Works and Where to Start

A pull request lands on a Tuesday. It adds a storage bucket with public read access, one line copied from a tutorial, and it merges because nothing in the pipeline has an opinion about that line. Six months later an auditor asks who approved public access to a bucket holding customer records. The honest answer is that nobody decided. It just happened.

That gap between what a team intends and what reaches production is what a policy as code framework exists to close, and it doesn't close it with another wiki page.

Policy as Code, Explained Through a Building Inspector

A framer closes a wall on Thursday. Before the drywall goes up, an inspector checks the wiring against the electrical code, signs the card, and files it. A wrong outlet box stops the wall. The city does not trust the crew to remember the code.

A policy as code framework runs that sequence on a repository change. Rules live as versioned text in Git, not in a reviewer's memory. A machine evaluates the proposed change and returns a decision the pipeline acts on: block the merge, or let it through.

What this framework is not

A drift tool compares what exists with what should exist and reports the difference. Policy decides whether a proposed change is allowed to land.

Terraform, Ansible, and Puppet build and reconcile resources. Policy judges the plan before those tools run, or the objects before they are admitted.

A scanner reports what it found in an image or dependency. Policy can require a scan to have passed, which is a different job.

Working definition: a policy as code framework defines rules as code, evaluates them against inputs, and enforces the result at a chosen checkpoint.

The architecture that made this workable is the split between the rule and the thing being judged. The Cloud Native Computing Foundation's Open Policy Agent page traces one implementation of that split from a first commit on December 28, 2015, through entry into the CNCF on March 29, 2018 and Incubating status on April 2, 2019, to Graduated status on January 29, 2021. Teams write declarative rules in Rego. Pipelines and infrastructure query one decision service through APIs, so one policy language can back many enforcement points.

A conceptual illustration showing a developer creating a storage bucket with a security misconfiguration, causing audit problems.

That service is also where the framework fails in practice. Each check waits on a network call. If the service is down, fail closed and merges stall until someone bypasses the check. Fail open and the rule never really ran. Governance has to choose that outcome, and name who may edit a rule, before the first policy ships. A deny that cannot be traced to the design decision and the reviewer who approved it is only a red status. Later, nobody can say why the control exists.

Exit risk sits in the same choice. Rego moves across tools that speak OPA. It does not move to Cedar or Kyverno without a rewrite.

Secure development across many client environments is a separate problem from the policy engine. This framework guidance for MSSP teams covers secure software development practice for those teams.

Six Parts Every Policy-as-Code Framework Needs

Ask a team to describe its setup and you'll hear about the language and the pipeline check. Those are parts two and five of six. The missing ones are why the system falls apart the first time an auditor asks a question with a date attached.

A diagram illustrating the six essential components of a robust Policy-as-Code framework with numbered sequential steps.

ComponentWhat It DoesExample
Policy sourceStores rules as versioned text in GitRego or YAML files in a platform repository
Policy languageExpresses the rule declarativelyRego (OPA), Cedar policies, Kyverno YAML
Input dataSupplies the facts the rule checksResource configuration, PR diff, user role, ticket ID
Decision engineEvaluates the rule and returns allow, deny or indeterminateOPA server, Kyverno admission controller
Enforcement pointApplies the decision where the change happensPull request status check, CI job, Kubernetes admission
Audit trailRecords which policy version produced each decisionDecision log with commit SHA and reviewer identity

Walk it with the public bucket. The policy source is deny_public_buckets.rego in the platform repo. The input is the Terraform plan attached to the pull request. The engine reads the plan, sees acl = "public-read", and returns deny with rule ID storage-no-public-acl. The enforcement point fails the required status check and the merge button greys out. The audit trail writes the commit SHA, the policy version and, if a human later overrides, their name.

Remove any one of those six and the chain snaps somewhere you'll only notice under pressure. No versioned source and you can't roll a bad rule back. No input data and the rule guesses. No decision log and you can't answer the March question. No enforcement point and the whole thing is a suggestion.

The part that quietly goes missing

Audit trails get deferred because they feel like reporting rather than control. They're the only part that survives contact with a regulator, a customer security questionnaire or an incident review.

Practical rule: if you can't reconstruct why a specific change was allowed six months ago, including the rule text that was live at the time, you don't have a policy framework. You have a linter.

Start with one rule, one gate, one log

A minimum viable version is three things. One rule in Git that blocks a real problem you've already had. One pull request gate that runs it. One decision log that records the policy version and commit alongside the verdict.

Then, before you write a second rule, list the six components for your own stack and mark every one that's missing or has no named owner. Unowned components rot over time, and the rot looks exactly like compliance until the day someone checks.

Where Checks Run from Editor to Production

Placement decides how much a policy costs you. The same rule costs a developer three seconds in an editor and three days in an incident review, so you place each control at the earliest stage that has enough information to judge it.

StageTypical CheckWhat It Can CatchCan Block?
IDE or pre-commit hookLint policy on local filesHardcoded secrets, missing tagsWarns, or blocks commit if enforced locally
Pull requestEvaluate the diff against policiesUnapproved dependencies, public exposure, missing reviewYes, through a required status check
CI pipelineEvaluate build artifacts and infrastructure plansPlan changes that break policy, non-compliant container imagesYes, fails the job
Deployment or admissionAdmission control or deploy gateNon-compliant workloads reaching a clusterYes, rejects the object
Runtime or API gatewayContinuous evaluation of requestsUnauthorized calls and inappropriate data accessYes, for requests (not for code)

Why the pull request is the default first gate

The editor sees one file. The admission controller sees one object, already built, often already pushed. The pull request is the first point that sees the whole diff, knows who authored it, and can require a second human before anything moves.

A building inspector's visit schedule shows how timing changes cost. A framing inspection catches a missing beam while fixing it costs a day's work. The same flaw found at final inspection costs a teardown. Stages early in the table work like the framing visit: cheap to correct, limited in what they can see. Stages late in the table see everything, and everything costs more.

Start narrow: one repository, one gate, one rule that stops a mistake your team has actually made. Breadth comes later, and only after the gate earns trust.

Measure the gate, not just the rule

The Open Policy Agent performance documentation draws a distinction worth internalizing. Its opa bench command evaluates a Rego query repeatedly and reports metrics, and benchmarking policy evaluation alone is not the same as measuring the gate: the --e2e option adds server and integration overhead. A rule that evaluates in microseconds can still make a developer wait a minute once serialization, remote data lookups and source-control webhooks take their turn.

Time your gate end to end. Developers tolerate a check that finishes before they context-switch and route around one that doesn't, so latency is a governance property, not a performance nicety. While you're tuning the pipeline that hosts the gate, this guide to CI/CD pipeline security covers the surrounding hardening, from secret handling in build jobs to isolating runners.

Governance is part of the placement decision

Where a check runs also decides who controls it, and that choice outlives any single rule. A gate hosted in your own repositories moves when you move. A gate hosted inside a vendor's managed service moves when they let it. If you're buying a commercial engine or a managed decision service, understanding how the licensing process works before you commit keeps a renewal conversation from resetting your enforcement roadmap. Ask two questions up front: can you export every policy in plain text, and can you replay the decision log outside the vendor's console. If either answer is no, your exit plan is a rewrite, and the enforcement history your auditors expect may not survive the migration.

Writing Policies That Give Predictable Answers

Performance problems in policy usually start as modeling problems. An independent analysis of OPA and Rego performance reported that a workload of 1,000 users and 1,000 policies took 3.47 seconds to evaluate, while raising the input to 10,000 users and 10,000 policies pushed evaluation to slightly more than four minutes. That's one workload rather than a universal benchmark, but the shape of the curve is the lesson: input cardinality turns delivery time nonlinear, fast.

Why input shape decides whether the gate scales

Ten times the data did far more than ten times the damage. The rule likely scanned a list per user, and each added user multiplied the scan. Authorization and compliance policies hit this wall first because they often need to ask about relationships across many records.

Model the data so the engine doesn't loop. Fixes that work in practice:

  • Bound the input. Evaluate the resources in the change, not every resource in the account.
  • Precompute facts. Resolve team ownership, environment and service tier once, upstream, and pass them in as plain fields.
  • Use object-shaped data. Keyed lookups beat repeated scans over large arrays, every time.
  • Separate the expensive questions. Keep coarse admission checks fast and push relationship or graph analysis into its own staged evaluation.
  • Set an explicit timeout. Decide what a slow evaluation means before it happens, not during a release freeze.
  • Profile before you trust. Run the profiler on worst-case inputs, enable memory metrics, and fail the build when evaluation regresses.

Allow, deny and the third answer

Most enforcement contracts name two outcomes and leave the third to chance. Write all three down.

  • Allow. The rule passed. Log it anyway, with the policy version.
  • Deny. The rule was violated. Return the rule ID and a reason a developer can act on, not "validation failed".
  • Indeterminate. Data was missing, evaluation timed out, or the engine errored. Route to a named human reviewer instead of guessing.

Indeterminate is where frameworks fail. Treat it as pass and you've built a fail-open gate that blocks nothing. Treat it as fail and one flaky data source freezes every merge in the company. Give it its own path, and record the evaluated policy version with every decision so a later review can tell what the engine saw.

Write this down first: the three outcomes, and who owns each one, belong in the enforcement contract before the first rule is written.

How to Trace Controls from Design to Code Review

A control that can't be traced is a control nobody can defend. The trace runs in one direction: a design decision creates a control, the control becomes a policy, the policy runs on a pull request, and the reviewer sees all of it in one place.

A six-step infographic process showing how to trace security controls from design to code review.

  1. Record the design decision and its threat model. Give it a stable control ID in the design document that the ticket links to. Reason: the ID is what lets a failing check point backwards. Usual slip: the threat lives in a slide deck and the ID exists nowhere a developer will see it.
  2. Map the control to a policy with a named owner and a version. The owner is a person or a team, not "security". Reason: someone has to notice when the rule stops matching reality. Slip: policies inherit owners from whoever wrote them last, and that person left.
  3. Publish the policy where the governed code lives. Same repository or a platform repo with a documented dependency. Reason: review, rollback and blame all come free from Git. Slip: rules live in a vendor console, invisible to code review and impossible to export cleanly.
  4. Evaluate on every pull request and return the rule ID with the verdict. The answer arrives as allow, deny or approval required, with the control ID attached. Reason: a denial without a rule ID sends the developer on an archaeology expedition.
  5. Show the reviewer the reason, the decision it traces to, and the policy version. The same sentence covers a developer and an auditor. Reason: it turns a red check into an explanation. Slip: the check says "policy violation" and the reviewer approves anyway out of fatigue.
  6. Make exceptions explicit. A named approver, a logged reason and an expiry date. Reason: an exception is a decision, so it deserves the same evidence as a rule. Slip: exceptions granted in a Slack thread become permanent in practice.
  7. Re-run the check when the exception expires. Automatically, without a reminder email. Reason: temporary problems that are never re-tested become permanent risk. Slip: the expiry date exists in a spreadsheet that nobody queries.

The gap between a written requirement and a check that runs on every pull request is where audits are won, which is why verification requirements deserve the same version control as the code they govern.

The health check for your trace

Open one recent denial and follow it. It should name a rule ID, a policy version, a design decision ID, and the reviewer who owns the outcome. If any hop is missing, that's the hop to fix next week.

A trace is healthy when every failing check points to a design decision and every decision points back to at least one policy version. Nothing in that chain should require a meeting to reconstruct.

Governing AI-Generated Changes Without Two Rulebooks

A pull request arrives at 2 a.m. An agent wrote it after a developer typed three sentences into a prompt. The change touches a payments service, adds a dependency, and modifies a permission check. Your pipeline has ninety seconds to decide. Which rulebook applies?

If your answer depends on who typed the characters, you have a governance problem. Start with what this framework is not: it is not a parallel set of standards for machine-written code. It is one rule set that treats authorship as evidence, the same way it treats the diff, the ticket, and the deployment target.

The instinct to build that second rulebook is widespread, and the data shows it producing two-tier development. In the SonarSource developer survey report, 55% of respondents' organizations use AI-code guidelines, policies or quality gates that differ from those for developer-written code, up from 41% previously, while only 18% of enterprises and 12% of SMBs describe formal, distinct AI-code policies or automated checks. The same research reports 39% of enterprise respondents saying AI-code compliance reviews have become more rigorous, against 28% of SMB respondents.

Read those together and a picture forms: a majority of teams have different rules, a minority have enforceable checks, and rigor varies by company size. That is a mood, not governance.

Provenance is an input, not a rulebook

A second rulebook works like a separate security line at the airport that only some passengers are sent through. The frequent travelers figure out which terminal avoids it. Friction on a required check teaches developers to route around it, split the change into pieces too small to trigger review, or push generated code down a path with no gate at all.

Generic rules fail in the opposite direction. They miss hazards specific to agents: tool invocation, secrets exposure, unauthorized data access, and dependency changes nobody reviewed.

One rule set with provenance as an input avoids both traps. Evaluate intent, changed assets, permissions, provenance, and deployment context, then let the same policy decide. Authorship becomes a fact the rule can weigh, not a separate pipeline.

In practice, this means three things:

  1. Represent provenance as metadata on the change. Which tool or agent produced it, which model or configuration, and what it was asked to do. The agent-written payments change at 2 a.m. should carry that record the way a signed commit carries an author.
  2. Split controls by moment. Guidance belongs at generation time, inside the editor, where a secure prompt context steers output before it exists. Hard checks belong at pull request time, where they apply to every change regardless of who or what typed it. Guidance is fast and forgiving. Gates are neither.
  3. Keep the outcome format identical. A traceable allow, deny, or approval requirement, mapped to the same design decision and the same reviewer any human change would map to. An exception for AI-generated code expires on the same schedule as every other exception, in the same log, under the same named approver.

When that chain holds, the 2 a.m. pull request gets an answer that names the rule, the design decision behind it, and the person accountable for the outcome, whether the author was a developer, an agent, or a developer steering an agent. When it breaks, you get the failure mode teams report: generated code approved by tired reviewers because the check could not explain itself.

The test: if you removed the word "AI" from your process, would anything be less safe? If the answer is no, you've built a second rulebook for a problem the first one already covers.

The provenance question extends well beyond code generation. Wherever agents act with real consequences, someone has to answer what produced the action and what it was permitted to touch. The StalkChain guide to crypto agents works through that same question for trading agents, and the pull request version is no different in kind. The gate needs to know what produced the change and what it was permitted to touch.

Choose an Engine and Start with One Enforcement Point

Engine selection gets written up as a feature table. For a regulated team it's really a governance decision, and the question underneath is not which engine is best. It's what happens to your policies if a maintainer, a managed service or a cloud dependency changes direction.

EnginePolicy StylePrimary ScopeGovernance Note
Open Policy Agent (OPA)Rego, declarativeGeneral purpose: Kubernetes, CI/CD, APIsCNCF Graduated on January 29, 2021; vendor-neutral
KyvernoYAML policy resourcesKubernetes resourcesKubernetes-native; confirm current CNCF status before adoption
CedarDeclarative authorization policiesApplication access decisionsAWS-led; entered CNCF Sandbox in October 2025

A comparison table for policy as code frameworks showing Open Policy Agent, Kyverno, and Cedar engine options.

The exit-risk question nobody puts in the comparison table

An ecosystem analysis comparing Cedar and OPA makes the uncomfortable point directly. OPA remains CNCF-graduated and vendor-neutral, Cedar is AWS-led and entered the CNCF Sandbox in October 2025, and Styra's commercial OPA products wound down after the team moved to Apple. Open source removes a license risk. It doesn't remove concentration risk.

So score candidates on six things before you write a rule:

  • Jurisdictional control. Where does the decision execute, and whose region is that?
  • Exportability. Can you pull every policy out in a form that runs elsewhere?
  • Migration. What does a schema or major version change cost you, and who tests it?
  • Offline evaluation. Does the engine answer with no network, during an outage or an air-gapped review?
  • Audit evidence. Can you reconstruct a past decision outside the vendor's control plane?
  • Multi-cloud fit. Does the same policy work where your workloads run, today and next year?

Knowing how Rego handles rule evaluation and iteration helps you read those answers critically, and this explanation of what Rego is and how it evaluates is a reasonable starting point. We enforce policy as code on every pull request with the option to block unsafe merges, which makes the trace the default rather than an add-on.

A five-step first move

  1. Pick one enforcement point. The pull request, almost always.
  2. Write the three outcomes and who owns each.
  3. Export the policies to Git and confirm they evaluate outside the vendor's control plane.
  4. Benchmark the gate end to end, including the webhook and the data fetch.
  5. Turn on the decision log before you turn on blocking.

Then stop. Run that on one real repository for a month, with one rule, until the denials are boring and the log answers questions without a meeting. Widening scope is a decision you'll be able to defend because you'll have the evidence for it.


Policy as code only earns trust when a failing check can explain itself, and that means tying every rule back to the design decision and threat model it came from. DevArmor analyzes specs and tickets to generate structured security feedback and policy checks that run instantly in pull requests, then keeps the evidence linked to the decision, the reviewer and the version that produced it. If you'd rather start from a threat model than a copied rule, visit DevArmor and see what your first gate looks like.

Table of Contents

Subscribe