Перейти к основному содержимому
End-to-End DevSecOps Workflow & Policy as Code (OPA)
Урок 11 из 11

End-to-End DevSecOps Workflow & Policy as Code (OPA)

Design an end-to-end DevSecOps workflow that couples CI security checks with Open Policy Agent (OPA) Rego policies, unit tests, and Kubernetes admission control to enforce security standards consistently without manual bottlenecks.

Продвинутый 28 мин Облака и DevSecOps
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.

Цели обучения

  • Trace security controls across an end-to-end DevSecOps lifecycle from pre-merge CI to Kubernetes admission
  • Author Rego policies in OPA using `import rego.v1` to inspect Kubernetes workloads and reject privileged pods
  • Validate policy logic automatically with `opa test` unit tests and `conftest test` in GitHub Actions
  • Roll out admission policies safely using audit (`dryrun`) mode, scoped exemptions, and progressive enforcement

Рекомендуется заранее: Kubernetes Security: RBAC, Pod Security & NetworkPoliciesInfrastructure as Code (IaC) Security with TerraformSAST, DAST & SCA Integration Without Breaking Velocity

#Why this matters

Even when SAST, SCA, and container scanners run cleanly in CI, security gaps still slip into production through configuration drift: a developer enables privileged: true on a debugging pod, mounts a host directory, or deploys directly with kubectl apply and bypasses the pipeline altogether. Security checklists stored on internal wikis cannot stop those changes at deploy time.

Policy as Code (PaC) turns architecture and compliance guardrails into executable, version-controlled rules. Using Open Policy Agent (OPA) and its declarative language Rego, teams write one set of security invariants, test them with unit tests, evaluate them in GitHub Actions before merge, and enforce them at the Kubernetes API server so non-compliant workloads are blocked consistently.

#Architecture of an end-to-end DevSecOps workflow

A mature DevSecOps workflow enforces security checks at multiple control points rather than relying on a single gate:

Stage Primary checks Enforcement mechanism Why it is needed
Pull request (CI) SAST, SCA lockfiles, opa test, conftest test Required PR status check Fast feedback before code merges
Build and release Image build, SBOM, provenance attestation Signed artifacts via OIDC Prevents untrusted binaries from entering registry
Cluster admission Kubernetes Pod Security, ingress, RBAC rules OPA Gatekeeper validating webhook Stops out-of-band kubectl or GitOps drift
Runtime and audit Scheduled cluster policy sweeps Gatekeeper dryrun / warn logs Catches existing drift as policies evolve

Evaluating policies in CI gives developers sub-minute feedback inside their pull request, while enforcing the same rules in Kubernetes admission control guarantees that manual emergency commands or misconfigured controllers cannot bypass CI.

Policy evaluation across CI and cluster admissionPolicy evaluation across CI and cluster admissionDeveloperGitHubActionsConftestClusterGatekeeperOpen PR with Deployment YAMLRun conftest test against Rego policiesPass or fail with violation messageDeploy signed manifest after mergeAdmissionReview requestAllow or deny based on Rego constraintsCI gives fast feedback; admission makes enforcement non-bypassable

#Writing policies in OPA and Rego

OPA separates policy decision from policy enforcement. The caller (a CI runner or Kubernetes admission webhook) passes structured data as input to OPA, which evaluates .rego files and returns structured violations. Because Kubernetes manifests, Terraform plans, and GitHub Actions workflows all serialize cleanly to JSON, one policy engine covers the entire delivery chain.

Current OPA (with import rego.v1) uses explicit if and contains keywords to build sets of violation messages. Any rule inside deny contains msg if { ... } fires when all expressions inside the braces evaluate to true.

A classic Kubernetes bug occurs when policies only inspect input.spec.containers (which matches a standalone Pod) and miss input.spec.template.spec.containers (used by Deployment, StatefulSet, and DaemonSet), or forget initContainers. A helper rule normalises both shapes cleanly:

rego
package kubernetes.pod_security

import rego.v1

pod_containers contains container if {
	some container in input.spec.containers
}

pod_containers contains container if {
	some container in input.spec.initContainers
}

pod_containers contains container if {
	some container in input.spec.template.spec.containers
}

pod_containers contains container if {
	some container in input.spec.template.spec.initContainers
}

deny contains msg if {
	some container in pod_containers
	container.securityContext.privileged == true
	msg := sprintf("Privileged container not allowed: %s", [container.name])
}

Because Rego is declarative, every deny rule should be paired with automated unit tests in a _test.rego file. Unit tests prevent accidental policy regressions that could either allow insecure pods or break every deployment in the cluster:

rego
package kubernetes.pod_security

import rego.v1

test_deny_privileged_deployment if {
	count(deny) > 0 with input as {
		"kind": "Deployment",
		"spec": {"template": {"spec": {"containers": [
			{"name": "debug", "securityContext": {"privileged": true}},
		]}}},
	}
}

test_allow_unprivileged_pod if {
	count(deny) == 0 with input as {
		"kind": "Pod",
		"spec": {"containers": [
			{"name": "api", "securityContext": {"privileged": false, "allowPrivilegeEscalation": false}},
		]},
	}
}

You can verify the policy locally with opa test and test real YAML manifests using Conftest:

Testing Rego policies and Kubernetes manifests locally
$ opa test policy/ -v
policy/pod_security_test.rego:
data.kubernetes.pod_security.test_deny_privileged_deployment: PASS (412us)
data.kubernetes.pod_security.test_allow_unprivileged_pod: PASS (198us)
--------------------------------------------------------------------------------
PASS: 2/2
$ conftest test manifests/debug-pod.yaml -p policy/
FAIL - manifests/debug-pod.yaml - main - Privileged container not allowed: debug

#Enforcing policies in GitHub Actions and Kubernetes

Once policies have unit tests, wire them directly into CI with minimal permissions so a pull request cannot change workflows or secrets during evaluation. In GitHub Actions, run opa test to validate the policy suite itself, then run conftest test against application manifests alongside SAST and SCA checks:

yaml
name: devsecops-policy-gate
on:
  pull_request:
    branches: [main]
permissions:
  contents: read
jobs:
  policy-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Rego unit tests and manifest checks
        run: |
          opa test policy/ -v
          conftest test manifests/ -p policy/

Rolling out a strict policy across an existing cluster requires discipline. Turning OPA Gatekeeper directly to enforcementAction: deny on day one often breaks legitimate system DaemonSets or legacy services during a traffic spike. Follow a progressive rollout:

  1. Test in CI first: Block new pull requests with Conftest so new manifests comply immediately.
  2. Enable cluster audit (dryrun): Deploy the Gatekeeper Constraint with enforcementAction: dryrun. Gatekeeper logs every violation in cluster status without dropping pods, revealing legacy exceptions safely.
  3. Track exemptions as code: Grant narrow, namespace- or label-scoped exceptions with an expiration date and justification in Git, never cluster-wide disables.
  4. Switch to deny: Once dryrun violation counts hit zero for compliant namespaces, flip enforcementAction to deny.

#Common mistakes

  • Checking Pod paths only: Inspecting input.spec.containers without input.spec.template.spec.containers lets insecure Deployment, DaemonSet, and CronJob workloads pass silently.
  • Forgetting initContainers and ephemeralContainers: Attackers or misconfigured tooling can request privileged: true in an init container, gaining host access before the main container even starts.
  • Enforcing policy in CI without admission control: Pipeline checks alone do not stop someone with cluster credentials from running kubectl edit or kubectl apply directly against the API server.
  • Skipping _test.rego unit tests: Untested Rego rules frequently contain typos in nested JSON keys that evaluate to undefined, causing the deny rule to silently never fire.

#Summary

An end-to-end DevSecOps workflow pairs fast pull-request gates with non-bypassable runtime enforcement. Writing Policy as Code in OPA Rego lets teams validate Kubernetes manifests and IaC uniformly, prove rule correctness with opa test and conftest test in CI, and enforce the same invariants at cluster admission. Rolling out new constraints through dryrun audit mode and Git-tracked exemptions keeps production workloads stable while steadily raising the security baseline.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему