executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
open-policy-agent-opa"Open Policy Agent in Security & Compliance - cloud native architecture" patterns, pitfalls, and best practices
Independent GitHub snapshot · Automated classification · Original documentation governs
name: open-policy-agent-opa compatibility: opencode completeness: 95 content-types:
opa
├── opa (policy evaluation engine)
├── discovery API (dynamic configuration)
├── status API (health and metrics)
├── decision logs (audit trail)
└── bundle server (policy distribution)
package kubernetes.admission
import input.request
# Deny pod creation if runAsNonRoot is not set
deny[msg] {
input.request.kind.kind == "Pod"
not request.object.spec.containers[_].securityContext.runAsNonRoot
msg := "Pod containers must have runAsNonRoot: true"
}
# Allow only specific image registries
deny[msg] {
input.request.kind.kind == "Pod"
container := input.request.object.spec.containers[_]
not startswith(container.image, "gcr.io/my-org/")
msg := sprintf("Container image %v must be from trusted registry", [container.image])
}
POST /v1/data/kubernetes/admission
Content-Type: application/json
{
"input": {
"request": {
"kind": {"kind": "Pod"},
"object": {"spec": {"containers": [{"image": "nginx"}]}}
}
}
}
Response:
{
"result": [
{
"msg": "Pod containers must have runAsNonRoot: true"
}
]
}
API Server (Kubernetes)
↓ (mutating/webhook)
OPA Agent/Server
↓ (policy evaluation)
OPA Engine
↓ (policy documents + input)
Rego Policy
↓ (decision)
API Server
↓ (admit/deny)
Application
1. User creates pod via kubectl
2. Kubernetes API server receives request
3. Mutating admission webhook intercepts request
4. Webhook calls OPA for policy evaluation
5. OPA evaluates policy against request
6. OPA returns allow/deny decision
7. API server acts on decision
8. Pod created or rejected
1. Application receives request
2. Application calls OPA decision API
3. OPA loads relevant policy documents
4. OPA evaluates policy with request input
5. OPA returns decision
6. Application enforces decision
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: opa-validating-webhook
webhooks:
- name: validation.policy.openpolicyagent.org
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
clientConfig:
service:
name: opa
namespace: opa
path: /v1/data/kubernetes/admission
caBundle: "..."
admissionReviewVersions: ["v1", "v1beta1"]
sideEffects: None
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-labels
spec:
rules:
- name: check-app-label
match:
any:
- resources:
kinds:
- Pod
validate:
message: "The label 'app' is required"
pattern:
metadata:
labels:
app: "?*"
package certmanager.validations
deny[msg] {
input.request.kind.kind == "Certificate"
not input.request.object.spec.issuerRef.name == "internal-issuer"
msg := "Certificates must use internal issuer"
}
apiVersion: tekton.dev/v1beta1
kind: Pipeline
metadata:
name: deploy
spec:
params:
- name: opa-policy
type: string
tasks:
- name: validate-opa
taskRef:
name: opa-validate
params:
- name: policy
value: $(params.opa-policy)
- name: input
value: $(tasks.build-task.results.image)
package flagger.canary
# Deny canary deployment if image is not from trusted registry
deny[msg] {
input.canary.spec.template.spec.containers[_].image
not startswith(input.canary.spec.template.spec.containers[_].image, "gcr.io/secure/")
msg := "Canary deployments must use trusted registry images"
}
# opa.yaml
services:
- name: kubernetes
url: https://kubernetes.default.svc
credentials:
bearer_token:
path: /var/run/secrets/kubernetes.io/serviceaccount/token
plugins:
kubernetes:
bundle:
name: kubernetes/admission
path: /v1/data/kubernetes/admission
decision_logs:
enable: true
services:
- name: bundle-server
url: https://bundle.example.com
credentials:
bearer_token:
path: /var/run/secrets/bundle/token
# bundle.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: opa-bundle
namespace: opa
data:
policy.rego: |
package kubernetes.admission
# Policies here
labels.json: |
{
"app": "opa-bundle",
"version": "v1.0.0"
}
// Go implementation
func myCustomFunction(ctx context.Context, input []ast.Value) (ast.Value, error) {
// Custom logic here
return ast.Boolean(true), nil
}
// Register in OPA
opa.RegisterBuiltinFunction("mycustomfn", myCustomFunction, ast.TypeBoolean)
plugins:
cache:
default_ttl: "5m"
max_size: 10000
Problem: OPA evaluation slows down API requests.
Solution:
# Enable caching
plugins:
cache:
default_ttl: "5m"
# Optimize policies
- Use efficient built-in functions
- Avoid deep recursion
- Use sets instead of arrays where possible
- Enable caching for repeated evaluations
Problem: Policies don't load or update.
Solutions:
# Check policy status
curl http://localhost:8181/v1/policies
# Check decision logs
curl http://localhost:8181/v1/history
# Verify configuration
kubectl logs -n opa deploy/opa
Problem: Bundle updates cause inconsistencies.
Solutions:
Problem: Policies take too long to evaluate.
Solutions:
opa eval --bundleopa bench for performance testingProblem: OPA uses excessive memory.
Solutions:
# Limit memory usage
containers:
- name: opa
resources:
limits:
memory: "512Mi"
cpu: "500m"
Problem: Remote policy evaluation adds latency.
Solutions:
Problem: Policy decisions are unclear.
Solutions:
# Trace policy evaluation
curl -X POST http://localhost:8181/v1/debug/trace \
-H "Content-Type: application/json" \
-d '{
"input": {"request": {...}},
"packages": ["kubernetes.admission"]
}'
# Use OPA REPL for interactive testing
opa eval --bundle 'package test; p := true { input.x == 1 }' --input /dev/stdin <<< '{"x": 1}'
Problem: Breaking changes in policy cause issues.
Solutions:
Problem: Too many overlapping policies.
Solutions:
Problem: Malicious input bypasses policies.
Solutions:
Problem: Policies泄露 sensitive information.
Solutions:
Problem: Decision logs contain sensitive information.
Solutions:
# kubernetes/admission.rego
package kubernetes.admission
import input.request
# Default deny
default allow = false
# Allow if not denied
allow {
not deny
}
# Deny rules
deny[msg] {
# Security policies
# Compliance policies
# Cost policies
}
# Evaluate policy with input
curl -X POST http://localhost:8181/v1/data/kubernetes/admission \
-H "Content-Type: application/json" \
-d '{
"input": {
"request": {
"kind": {"kind": "Pod"},
"object": {"spec": {"containers": [{"image": "nginx", "securityContext": {"runAsNonRoot": true}}]}}
}
}
}'
# Upload policy
curl -X PUT http://localhost:8181/v1/policies/my-policy \
-H "Content-Type: text/plain" \
-d @policy.rego
# GitHub Actions example
- name: Run OPA Tests
run: opa test policy/*.rego -v
- name: Policy Linting
run: opa check policy/*.rego
- name: Build and Push Bundle
run: |
opa build -e kubernetes/admission policy -o bundle.tar.gz
# Upload bundle to storage