Security as Code: What It Is and How It Works in 2026
Table of Contents

Your pull request is ready, the tests pass, and someone asks whether the change meets the security requirements. Those requirements are in a design document nobody has opened since planning. The reviewer can approve the code, but they can't easily prove that it still follows the approved design.
Security as code closes that gap by turning requirements into checks that run inside delivery workflows. The important part isn't automating more scans. It's deciding what each check should do, who can override it, and what evidence remains after the software ships.
What Security as Code Means in Plain Terms
Say your security standard says containers must run without root privileges. A developer copies an old deployment template, misses that requirement, and ships a container configured to run as root. The rule existed, but nobody connected it to the deployment.
Security as code means writing security requirements as machine-readable rules, storing them in version control beside the software, and evaluating them automatically when code, configuration, or infrastructure changes.
Think of a building inspector checking walls while the framing is exposed. Checking at that stage makes problems easier to find and fix than waiting for the final walkthrough. Software controls work the same way when engineers place them where relevant decisions happen.

The rule, the checkpoint, and the decision
Keep these parts separate:
- Policy: The requirement a tool evaluates, such as containers must not run as root.
- Evaluation point: The place where it runs, such as a pull request, build, or cluster deployment.
- Decision: Allow, warn, or block, with the outcome recorded.
A scanner supplies observations. A policy determines what to do with them. Finding a suspicious string and deciding whether it should stop a merge aren't the same operation.
This approach has an established production history. A 2020 survey of approximately 150 OPA users found 56% used it in production for Kubernetes admission control and 47% for API authorization in microservices, according to InfoQ's report on OPA's CNCF graduation.
A requirement in a document tells people what should happen. An enforced policy checks whether it actually happened.
Unlike document-only reviews or occasional scans, executable controls can follow relevant changes. The practical test is simple: can you write down the control, test it, version it, and review it like code? If so, it's a candidate for security as code.
Where Security as Code Fits the Delivery Lifecycle
Security as code runs throughout the software delivery lifecycle, not only before release. Each checkpoint needs a control, an enforcement location, and evidence that the next checkpoint can use.
Security as code controls across the delivery lifecycle
| Stage | Security as code control | Enforcement point | Evidence kept |
|---|---|---|---|
| Plan | Threat model and requirements stored as versioned files | Ticket or design review | Approved design decision |
| Code | Secret detection and secure coding rules | IDE hook or pre-commit check | Lint and scan results |
| Review | Policy checks on every pull request | Pull request merge gate | Policy decision log |
| Build | Build provenance and SBOM generation | CI pipeline | Signed attestation |
| Deploy | Admission rules for images and configuration | Kubernetes admission controller | Admission audit record |
| Run | Runtime authorization and configuration drift checks | API gateway or service mesh | Access and alert logs |
From design intent to reviewed code
Planning establishes what the software is allowed to do. For a payment service, that might include which components can read account data and which connections cross a trust boundary. Store those decisions in a versioned threat model with named owners and links to the relevant services.
Planning is the least mechanical stage. A tool can check that a requirement exists, but a security engineer still needs to judge whether it addresses the actual threat. A completed template isn't proof of a sound design.
During coding, local checks provide immediate feedback. A pre-commit secret detector can catch a credential before it reaches shared source control, while secure coding checks can flag unsafe patterns.
At review, centrally enforced checks evaluate the proposed change against repository requirements. Don't rely exclusively on local hooks, which developers can skip. For example, a merge gate could require security approval when a change modifies authentication code identified in the threat model.
From an approved change to running software
At build time, the pipeline should connect its output to the reviewed source revision. A successful approval for one commit must not authorize a different commit that appeared afterward.
At deployment, the gate evaluates the artifact being released, not merely whether a pipeline once showed green. At runtime, authorization policies govern requests, while drift checks identify configuration changes outside the approved path.
The engineering task is connecting these handoffs. Review uses design requirements; the build records the reviewed revision; deployment verifies the build evidence. Treat those connections as part of CI/CD pipeline security, rather than unrelated scanner integrations.
Practical rule: Start where a bad change is cheapest to stop, usually the pull request, then extend enforcement as reliable evidence becomes available.
Key Implementation Patterns and What Each One Enforces
| Pattern | Typical trigger | Default action | Good first use |
|---|---|---|---|
| Policy on pull request | Pull request opened or updated | Block on critical rules, warn otherwise | Secret detection and banned licences |
| Pipeline attestation gate | Build completes | Block release without required attestation | Isolated builds and signed provenance |
| Admission control | Deployment to a cluster | Reject non-compliant manifests | Privileged containers and unsigned images |
| API authorization policy | Each service request | Deny when the policy evaluates false | Role checks across microservices |
| AI coding agent guardrail | AI tool proposes or applies a change | Limit tool calls and require review above a threshold | Repositories holding sensitive data |
These are recommended starting defaults, not settings every tool applies automatically. Each pattern addresses a different decision, so choose the checkpoint that has enough information to make that decision accurately.
Checks before merge and release
Pull request policies are a useful entry point. Use a secret detector such as Gitleaks to produce findings, then evaluate those findings with OPA and Rego or a comparable policy engine. OPA evaluates structured input; it doesn't discover credentials by itself.
A first rule might reject a newly introduced credential finding while reporting uncertain matches for review. For licence checks, supply normalized dependency metadata and compare licence identifiers against an approved list. Missing metadata needs its own explicit outcome.
A pipeline attestation gate checks release evidence. Use verification tooling such as Sigstore cosign to verify signatures and inspect claims, then require evidence from the approved build identity. A valid signature alone isn't enough if any identity can sign an acceptable artifact.

Checks at deployment and during execution
For admission control, OPA Gatekeeper or Kyverno can evaluate Kubernetes resources before admission. Start with a rule rejecting privileged containers. Image signature enforcement also requires a configured verification mechanism and trusted identities; a manifest check alone can't establish image authenticity.
For API authorization, place policy evaluation in the request path through a gateway, proxy, or service integration. A useful first rule permits access only when the caller's verified role and tenant match the requested resource. Define a denial response for false decisions and a separate failure policy for unavailable authorization services.
AI agent guardrails operate around actions, not just generated files. Use sandbox permissions and tool allowlists to restrict shell access, repository writes, and external connections. Require human approval before an agent modifies authentication code or delivery configuration.
Give the agent repository-specific security requirements before it starts. Treat comments, retrieved documents, and tool responses as untrusted input, not instructions that can expand its permissions.
The underlying separation matters: applications and delivery tools supply context, while a policy engine evaluates explicit rules. CNCF's OPA project overview describes that separation of policy decisions from application logic. Keep rules independently testable, and assign blocking or warning behavior according to confidence and impact rather than the tool's name.
Deciding What Blocks, What Warns and When Exceptions Expire
The block-or-warn choice is an operational decision, not merely a severity label. A high-impact finding with weak evidence needs different handling from a confirmed credential leak.
Use the following as a starting policy. The rollout duration shown is an example configuration, not an industry requirement.
Enforcement tier and exception rules
| Severity | Default action | Exception rule | Evidence kept |
|---|---|---|---|
| Critical | Block merge or release | Named owner and fixed expiry date | Decision log entry |
| High | Warn and open a ticket | Named owner and fixed expiry date | Warning record linked to ticket |
| Medium or low | Report only | No exception needed | Scan report |
| New rule in rollout | Warn only for two weeks | No exception needed | Warning log reviewed before blocking |
Make overrides narrow and temporary
Rank decisions using exploitability, business criticality, regulatory impact, confidence, and remediation cost. Severity is an input, not the entire calculation. An architectural violation exposing sensitive records may justify blocking even when a scanner assigns it an unremarkable label.
Every exception should identify the affected rule and resource, owner, reason, approver, compensating control, and expiry date. Store it as reviewable configuration, not a chat message. On expiry, remove the override automatically so the rule resumes its normal action, including blocking where applicable.
Record the rule version, input reference or digest, outcome, and approval details. Preserve enough context to reconstruct the decision without retaining raw secrets or unnecessary personal information. A replay also requires the relevant policy inputs, not just a green check mark.
Earn the right to block
Use a deliberate rollout:
- Observe first. Run the new rule in warning mode.
- Review noise. Count false positives during regular reviews and classify why they occurred.
- Repair the rule. Improve parsing, narrow its scope, or add missing context.
- Promote deliberately. Enable blocking only after meeting a false-positive threshold agreed before rollout.
Distinguish false positives and false negatives. A quiet rule isn't necessarily accurate if it misses dangerous changes.
A study of software supply-chain security practice describes alert overload, inconsistent metadata, and dependency churn as operational challenges. Maximum blocking can encourage workarounds rather than better decisions.
For an initial dependency gate, focus on direct dependencies with confirmed serious vulnerabilities, then extend coverage to transitive paths as metadata improves. Batch routine updates without delaying urgent fixes. Apply equivalent thresholds to agents: log permitted routine actions, but pause sensitive changes for human approval.
An exception is a temporary risk decision, not a permanent way to silence a rule.
Proving What Shipped with Provenance and SBOMs
A scan of source code can't establish which build produced the deployed package. To connect the security decision to what shipped, the release process needs verifiable evidence about the artifact.
NIST's guidance on software supply-chain security in CI/CD describes an approach in which build systems generate attestations and policy verifies their presence, authorized origin, and required metadata. Implement that loop as follows:
- Generate evidence. The build creates an attestation bound to the artifact's digest and signs it using the configured build identity.
- Check presence. The release policy requires the expected attestation type.
- Verify identity. The verifier checks the signature and whether the signer is authorized.
- Evaluate claims. The policy compares source revision, builder identity, and other required metadata against approved values.
- Keep the result. Store the verification decision and references to its supporting evidence.
Provenance explains how the artifact was produced
Provenance is verifiable information describing where, when, and how an artifact was produced. The SLSA provenance specification connects outputs to source revisions and build processes, and models the supply chain as a graph of sources, builds, dependencies, and packages.
That graph matters because your application inherits more than its own build history. A dependency may have been produced through a separate build system with different trust assumptions.

Useful enforcement rules include:
- Require provenance: Reject an artifact when the required provenance is absent or doesn't identify that artifact.
- Trust approved builders: Accept evidence only from builders and signing identities your organization authorizes.
- Evaluate dependency trust: Stop deployment when a dependency fails the trust requirements defined for that service.
An SBOM explains what's inside
A software bill of materials, or SBOM, inventories software components. It answers a different question from provenance: what's included, rather than how the artifact was produced.
Generate the SBOM from the build output where possible and bind it to the artifact digest. A list created from a source manifest can miss components added during packaging. Neither an SBOM nor a signature proves that software has no vulnerabilities.
For audits, preserve the relationship among the released digest, source revision, SBOM, provenance, and policy decision. An auditor should be able to identify which evidence supported a particular release without relying on a developer's memory. That traceability is a practical foundation for software supply-chain security.
The visibility gap is substantial: 67% of developers said that at least one-quarter of the code they work on comes from open-source libraries, while only 21% of organizations used an SBOM to document software components, according to GitLab's 2024 Global DevSecOps Report.
Start by making evidence available and artifact-specific. A release gate can't make a trustworthy decision from missing, stale, or unrelated metadata.
Real-World Examples and Misconceptions to Avoid
Consider a developer adding a database connection string containing a password to a configuration file. The pull request check identifies the credential and blocks merging. Its message names the file and rule without copying the password into the decision log.
The developer moves the credential into a secrets manager and changes the application to retrieve it through an approved mechanism. Because the credential entered source control, the response also includes revoking or rotating it. Deleting the string from the latest revision doesn't remove it from history.
Useful failures explain the fix
In another scenario, a deployment requests root execution and privileged access. A Kubernetes admission rule rejects it before the workload starts.
A useful rejection identifies the exact fields that violated policy and explains the permitted alternative. The developer configures a non-root user, removes privileged mode, and tests whether the application still runs. If extra access is necessary, the team reviews a narrowly scoped exception rather than weakening the rule for every workload.
These cases expose a practical limit: automation can stop a known violation, but it can't guarantee that the replacement design is secure. A secrets-manager integration can still grant excessive access, and an unprivileged container can still expose an insecure API.
Misconceptions that weaken the system
Security as code replaces the security team. Someone still has to define acceptable risk, understand trust boundaries, and approve unusual cases. Engineers also need to decide what happens when a check times out or receives incomplete input. Automation executes security judgment; it doesn't remove ownership.
A rule written once stays correct. A framework upgrade may change configuration fields, or a new service may invalidate an old assumption. Give policies owners, representative fixtures, and tests covering allowed, denied, and malformed inputs. Maintain policies as production software, not permanent truths.
AI-generated code is safe once it works. Functional tests demonstrate selected behavior, not every security property. TechTarget's coverage of AI coding and delivery risks discusses the gap between working generated code and secure delivery, including the additional risks of agent-executed actions.
An agent that can edit files and run commands needs constraints before generation, not only a scan afterward. Require approved context, restricted permissions, and review for sensitive actions. Apply security requirements to both the generated change and the process that produced it.
A passing check means the change satisfied that check's conditions. It doesn't mean someone has proved the whole system secure.
Choose Your First Policy to Automate
Pick a control whose failure would matter to your team, then introduce it through a small, reversible rollout.
- Name the rule and its owner. Choose a specific requirement, such as no newly introduced credentials in tracked files. Assign someone who can resolve disputes about the result.
- Write a test that can fail. Include an allowed example, a prohibited example, and malformed input. Decide how the checker should handle missing information.
- Store it beside the software. Keep policy, tests, and configuration in version control, with changes subject to review.
- Start with warnings. For example, schedule a two-week observation period on pull requests without making the new check a required merge condition.
- Review findings and exceptions. Correct false positives, document legitimate exceptions, and assign each exception an owner and expiry date.
- Block critical violations only. Promote reliable checks after the team confirms that developers receive clear, actionable failure messages.
Choose a safe place to learn
Use the lowest-risk enforcement point that still provides useful input. A non-blocking pull request check lets developers inspect findings before you make it mandatory. Don't begin with a production admission rule that nobody has tested against existing workloads.
DevArmor enforces Policy-as-Code on every pull request, with the option to block unsafe merges, and keeps traceable review outcomes. Our security reviews happen inside the tools developers already use, connecting checks to the flow of development.
Choose the rule whose failure would hurt most. Start it in warning mode at a low-risk checkpoint, review the results, and promote it to blocking only when the evidence supports that decision.
DevArmor helps teams connect security standards to threat models and enforce those requirements during development, with optional blocking of unsafe merges. Visit DevArmor to explore how continuous threat modeling, in-workflow reviews, and Policy-as-Code can support your first enforceable control.
Table of Contents
Subscribe

