<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: implementing-security-guardrails
description: >-
  Deploy automated security guardrails using OPA, Kyverno, and CI policy engines
  to enforce security standards without blocking developer velocity. Implement
  soft and hard guardrails across the SDLC.
domain: cybersecurity
subdomain: devsecops
tags:
  - guardrails
  - opa
  - kyverno
  - policy-engine
  - compliance
  - governance
  - developer-experience
  - shift-left
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: []
---

# Implementing Security Guardrails

## Overview

Security guardrails are automated policy enforcement mechanisms that prevent insecure
configurations from reaching production while maintaining developer velocity. This
skill covers implementing soft guardrails (warn/advise) and hard guardrails (block)
using OPA/Rego, Kyverno, and CI policy engines across infrastructure, containers,
and application code.

Mode: `[MODE: ARCHITECT]` — Governance through automated policy enforcement.

## Prerequisites

| Requirement | Details |
|---|---|
| OPA (`brew install opa`) or Kyverno in Kubernetes | Required |
| CI/CD platform with policy evaluation step | Required |
| Rego policy language familiarity | Required |
| Kubernetes cluster for admission policies | Required |

## Key Concepts

### OPA Policy for Terraform

```rego
# policy/terraform/security_groups.rego
package terraform.security_groups

import rego.v1

deny contains msg if {
    resource := input.resource_changes[_]
    resource.type == "aws_security_group_rule"
    resource.change.after.cidr_blocks[_] == "0.0.0.0/0"
    resource.change.after.type == "ingress"
    msg := sprintf(
        "Security group '%s' allows ingress from 0.0.0.0/0 — restrict CIDR range",
        [resource.address],
    )
}

deny contains msg if {
    resource := input.resource_changes[_]
    resource.type == "aws_s3_bucket"
    not resource.change.after.server_side_encryption_configuration
    msg := sprintf(
        "S3 bucket '%s' missing encryption — enable server-side encryption",
        [resource.address],
    )
}

warn contains msg if {
    resource := input.resource_changes[_]
    resource.type == "aws_instance"
    not resource.change.after.monitoring
    msg := sprintf(
        "EC2 instance '%s' has no detailed monitoring — consider enabling",
        [resource.address],
    )
}
```

### Kyverno Cluster Policies

```yaml
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-resource-limits
spec:
  validationFailureAction: Enforce
  rules:
    - name: require-limits
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "CPU and memory limits are required"
        pattern:
          spec:
            containers:
              - resources:
                  limits:
                    memory: "?*"
                    cpu: "?*"

---
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-privileged
spec:
  validationFailureAction: Enforce
  rules:
    - name: no-privileged
      match:
        any:
          - resources:
              kinds: ["Pod"]
      validate:
        message: "Privileged containers are not allowed"
        pattern:
          spec:
            containers:
              - securityContext:
                  privileged: "!true"
```

### CI Guardrail Pipeline

```yaml
name: Security Guardrails
on:
  pull_request:

jobs:
  guardrails:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install OPA
        run: |
          curl -sL -o opa https://openpolicyagent.org/downloads/v0.68.0/opa_linux_amd64_static
          chmod +x opa && sudo mv opa /usr/local/bin/
      - name: Terraform plan
        run: |
          cd terraform/
          terraform init
          terraform plan -out=tfplan
          terraform show -json tfplan > plan.json
      - name: Evaluate hard guardrails
        run: |
          DENIALS=$(opa eval --data policy/ --input terraform/plan.json \
            --format raw 'data.terraform.security_groups.deny')
          if [ "$DENIALS" != "[]" ]; then
            echo "::error::Security guardrail violations: $DENIALS"
            exit 1
          fi
      - name: Evaluate soft guardrails
        run: |
          WARNINGS=$(opa eval --data policy/ --input terraform/plan.json \
            --format raw 'data.terraform.security_groups.warn')
          if [ "$WARNINGS" != "[]" ]; then
            echo "::warning::Security recommendations: $WARNINGS"
          fi
```

### Guardrail Categories

```yaml
# guardrails.yaml — Policy classification
hard_guardrails:   # Block deployment
  - no_public_s3_buckets
  - no_unencrypted_databases
  - no_privileged_containers
  - no_hardcoded_secrets
  - no_open_security_groups

soft_guardrails:   # Warn and advise
  - enable_detailed_monitoring
  - use_multi_az_deployments
  - tag_all_resources
  - enable_access_logging
  - use_latest_runtime_versions
```

## Workflow

### Step 1: Evaluate Policies

```bash
node scripts/agent.js --action evaluate --input terraform/plan.json --policy-dir ./policy/ --output /tmp/guardrail-results.json
```

### Step 2: List Policy Violations

```bash
node scripts/agent.js --action violations --input terraform/plan.json --output /tmp/violations.json
```

### Step 3: Generate Policy Report

```bash
node scripts/agent.js --action report --policy-dir ./policy/ --output /tmp/policy-report.json
```

## Verification

- [ ] Hard guardrails block non-compliant deployments
- [ ] Soft guardrails produce warnings without blocking
- [ ] Policies version-controlled alongside infrastructure
- [ ] Guardrail exceptions require documented approval
- [ ] Policy coverage metrics tracked
- [ ] Developer feedback loop established (clear error messages)

## References

- [Open Policy Agent](https://www.openpolicyagent.org/docs/)
- [Kyverno Documentation](https://kyverno.io/docs/)
- [Rego Language](https://www.openpolicyagent.org/docs/latest/policy-language/)
- [Conftest](https://www.conftest.dev/)
