DevSecOps

DevSecOps Pipeline Security: Integrating Security into CI/CD

Nicu Constantin
••14 min read
#devsecops#ci-cd#pipeline-security#sast#dast#container-security

Petru Constantin has run Kubernetes, Terraform and GitLab CI/CD in production since 2022, first as a Senior DevOps engineer and now as an IT project manager and AI specialist who stays hands-on with the infrastructure. Code examples are written against the Kubernetes 1.37, GitHub Actions (actions/checkout v7, codeql-action v4, trivy-action v0.36.0), the current GitLab CI/CD security templates and OPA 1.x (Rego v1) documentation.

DevSecOps Pipeline Security: Integrating Security into CI/CD

DevSecOps represents a fundamental shift in how organizations approach security - moving from a final gate before deployment to an integrated practice throughout the software development lifecycle. The CI/CD pipeline is where this integration takes concrete form.

This guide provides practical approaches to building secure pipelines.

The Secure Pipeline Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                         Secure CI/CD Pipeline                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐  │
│  │  Code    │ → │  Build   │ → │  Test    │ → │  Deploy  │ → │ Monitor  │  │
│  │  Commit  │   │          │   │          │   │          │   │          │  │
│  └────┬─────┘   └────┬─────┘   └────┬─────┘   └────┬─────┘   └────┬─────┘  │
│       │              │              │              │              │         │
│       ▼              ▼              ▼              ▼              ▼         │
│  ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌──────────┐  │
│  │ Pre-     │   │ SAST     │   │ DAST     │   │ Config   │   │ Runtime  │  │
│  │ commit   │   │ SCA      │   │ Security │   │ Audit    │   │ Security │  │
│  │ Hooks    │   │ Secrets  │   │ Tests    │   │ CSPM     │   │ RASP     │  │
│  └──────────┘   └──────────┘   └──────────┘   └──────────┘   └──────────┘  │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

Stage 1: Pre-Commit Security

Git Hooks Configuration

# .pre-commit-config.yaml
repos:
  # Secrets detection (create the baseline once: detect-secrets scan > .secrets.baseline)
  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.5.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']
 
  # Python security linting (pre-commit passes the staged .py files)
  - repo: https://github.com/PyCQA/bandit
    rev: 1.9.4
    hooks:
      - id: bandit
        args: ['-ll']
 
  # Dockerfile linting
  - repo: https://github.com/hadolint/hadolint
    rev: v2.15.1
    hooks:
      - id: hadolint-docker
        args: ['--ignore', 'DL3008']
 
  # Terraform security (needs trivy and checkov installed locally)
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.109.5
    hooks:
      - id: terraform_trivy
      - id: terraform_checkov
 
  # YAML linting (for K8s manifests)
  - repo: https://github.com/adrienverge/yamllint
    rev: v1.38.0
    hooks:
      - id: yamllint
        args: ['-c', '.yamllint.yml']

Custom Security Hooks

#!/usr/bin/env bash
# .git/hooks/pre-commit
set -euo pipefail
 
echo "Running security checks..."
 
# Scan only the lines added in this commit (staged content, not the working tree)
ADDED_LINES="$(git diff --cached --unified=0 --no-color --diff-filter=ACM | grep -E '^\+[^+]' || true)"
 
SECRET_PATTERNS=(
    '(password|passwd|secret|api[_-]?key)[[:space:]]*[:=][[:space:]]*["'\''][^"'\'']{8,}'
    'AKIA[0-9A-Z]{16}'
    '-----BEGIN ([A-Z]+ )?PRIVATE KEY-----'
)
 
for pattern in "${SECRET_PATTERNS[@]}"; do
    # Here-string instead of a pipe: grep -q with pipefail can report a false "no match"
    if grep -qiE -e "$pattern" <<< "$ADDED_LINES"; then
        echo "ERROR: staged change matches secret pattern: $pattern" >&2
        echo "Remove the secret before committing; if it was ever pushed, rotate it" >&2
        exit 1
    fi
done
 
# Block sensitive file types
SENSITIVE_REGEX='\.(pem|key|p12|pfx)$|(^|/)\.env(\.[^/]*)?$'
if git diff --cached --name-only --diff-filter=ACM | grep -E "$SENSITIVE_REGEX"; then
    echo "ERROR: sensitive file type staged; use a secrets manager instead" >&2
    exit 1
fi
 
echo "Pre-commit security checks passed"

Stage 2: Build Security

GitHub Actions Secure Pipeline

# .github/workflows/secure-pipeline.yml
name: Secure CI/CD Pipeline
 
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]
 
# Least privilege by default; jobs ask for more only where they need it.
permissions:
  contents: read
 
# Version tags are shown for readability. Pin every action to a full commit SHA
# in production (GitHub secure-use guide); trivy-action is pinned that way below.
jobs:
  sast:
    runs-on: ubuntu-latest
    # returntocorp/semgrep-action is deprecated; run the Semgrep CLI image instead
    container:
      image: semgrep/semgrep
    permissions:
      contents: read
      security-events: write   # upload SARIF to code scanning
    steps:
      - uses: actions/checkout@v7.0.1
        with:
          persist-credentials: false
 
      - name: Run SAST (Semgrep)
        run: semgrep scan --config auto --sarif --output semgrep.sarif
 
      - name: Upload SAST results
        if: always()
        uses: github/codeql-action/upload-sarif@v4.39.3
        with:
          sarif_file: semgrep.sarif
          category: semgrep
 
  security-scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - name: Checkout code
        uses: actions/checkout@v7.0.1
        with:
          fetch-depth: 0          # full history for secret scanning
          persist-credentials: false
 
      # SCA - dependencies and lockfiles
      - name: Run SCA (Trivy)
        # trivy-action tags were force-pushed in March 2026 (GHSA-69fq-xp46-6x23): pin by SHA
        uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          scan-type: 'fs'
          scan-ref: '.'
          format: 'sarif'
          output: 'trivy-sca.sarif'
          severity: 'CRITICAL,HIGH'
 
      - name: Upload SCA results
        uses: github/codeql-action/upload-sarif@v4.39.3
        with:
          sarif_file: trivy-sca.sarif
          category: trivy-fs
 
      # Secret scanning over the git history
      - name: Scan for secrets
        uses: trufflesecurity/trufflehog@v3.99.9
        with:
          extra_args: --results=verified,unknown
 
      # IaC scanning before anything is deployed
      - name: Scan infrastructure config
        uses: bridgecrewio/checkov-action@v12
        with:
          directory: ./terraform
          framework: terraform
          output_format: sarif
          output_file_path: checkov.sarif
 
      - name: Upload infrastructure scan
        if: always()
        uses: github/codeql-action/upload-sarif@v4.39.3
        with:
          sarif_file: checkov.sarif
          category: checkov
 
  build-and-scan:
    needs: [sast, security-scan]
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v7.0.1
        with:
          persist-credentials: false
 
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v4.4.1
 
      - name: Build container image
        uses: docker/build-push-action@v7.4.0
        with:
          context: .
          push: false
          load: true
          tags: app:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
 
      # Container image scanning
      - name: Scan container image
        uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
        with:
          image-ref: 'app:${{ github.sha }}'
          format: 'sarif'
          output: 'trivy-container.sarif'
          severity: 'CRITICAL,HIGH'
          exit-code: '1'
 
      - name: Upload container scan results
        if: always()
        uses: github/codeql-action/upload-sarif@v4.39.3
        with:
          sarif_file: trivy-container.sarif
          category: trivy-image
 
      # SBOM generation (the action uploads it as a workflow artifact by default)
      - name: Generate SBOM
        uses: anchore/sbom-action@v0.24.3
        with:
          image: app:${{ github.sha }}
          format: spdx-json
          output-file: sbom.spdx.json
 
      # DAST against the image built in this job (images are not shared between jobs)
      - name: Start the application
        run: |
          set -euo pipefail
          docker run -d --name app -p 8080:8080 "app:${GITHUB_SHA}"
          curl --fail --silent --show-error --retry 10 --retry-connrefused --retry-delay 3 \
            http://localhost:8080/ > /dev/null
 
      - name: Run DAST (OWASP ZAP baseline)
        uses: zaproxy/action-baseline@v0.15.0
        with:
          target: 'http://localhost:8080'
          rules_file_name: '.zap/rules.tsv'
          cmd_options: '-a'
          allow_issue_writing: false   # no issues: write permission needed
          artifact_name: zap-baseline
 
  deploy-staging:
    needs: build-and-scan
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: staging
    permissions:
      contents: read
      id-token: write   # OIDC token for AWS, no static access keys
    steps:
      - name: Configure AWS credentials (OIDC)
        uses: aws-actions/configure-aws-credentials@v6.3.0
        with:
          role-to-assume: ${{ vars.AWS_STAGING_ROLE_ARN }}
          aws-region: eu-central-1
 
      - name: Deploy to staging
        run: |
          aws sts get-caller-identity
          # your deployment command goes here (helm upgrade, terraform apply, ...)

GitLab CI Secure Pipeline

# .gitlab-ci.yml
stages:
  - build
  - test        # GitLab security templates run in the test stage
  - dast
 
variables:
  SAST_EXCLUDED_PATHS: "spec, test, tests, tmp, vendor"
  CS_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA"   # image scanned by container_scanning
 
# Security scanning templates.
# License-Scanning.gitlab-ci.yml was removed in GitLab 17.0; license data comes from dependency scanning.
include:
  - template: Jobs/SAST.gitlab-ci.yml
  - template: Jobs/Secret-Detection.gitlab-ci.yml
  - template: Jobs/Dependency-Scanning.v2.gitlab-ci.yml
  - template: Jobs/Container-Scanning.gitlab-ci.yml
 
# Build and push with Buildah (no Docker-in-Docker daemon)
build:
  stage: build
  image: quay.io/buildah/stable
  variables:
    STORAGE_DRIVER: vfs
    BUILDAH_FORMAT: docker
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | buildah login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
  script:
    - buildah build
      --label "org.opencontainers.image.revision=$CI_COMMIT_SHA"
      -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA" .
    - buildah push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA"
 
# Custom dependency audit
security-audit:
  stage: test
  image: node:24-alpine
  script:
    - npm ci --ignore-scripts
    - npm audit --audit-level=high
  allow_failure: false
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
 
# Infrastructure scanning
infra-security:
  stage: test
  image:
    name: bridgecrew/checkov:latest
    entrypoint: [""]
  script:
    - checkov -d ./terraform --framework terraform --output cli --output junitxml --output-file-path ./checkov-results
  artifacts:
    when: always
    reports:
      junit: checkov-results/results_junitxml.xml
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - "terraform/**/*"
 
# DAST baseline against staging (STAGING_URL is a CI/CD variable)
dast-baseline:
  stage: dast
  image: ghcr.io/zaproxy/zaproxy:stable
  script:
    - mkdir -p /zap/wrk
    - zap-baseline.py -t "$STAGING_URL" -r zap-report.html || ZAP_EXIT=$?
    - cp /zap/wrk/zap-report.html .
    - exit "${ZAP_EXIT:-0}"
  artifacts:
    when: always
    paths:
      - zap-report.html
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

Stage 3: Security Testing Integration

SAST Configuration (Semgrep)

# .semgrep.yml
rules:
  - id: hardcoded-secret
    pattern-regex: (?i)(password|secret|api_key|token)\s*=\s*['"][^'"]{8,}['"]
    message: Hardcoded secret detected
    languages: [python, javascript, typescript, java]
    severity: ERROR
 
  - id: sql-injection
    # pattern-either = logical OR; a list under "patterns" would require all of them at once
    pattern-either:
      - pattern: $CURSOR.execute("..." + $INPUT, ...)
      - pattern: $CURSOR.execute("..." % $INPUT, ...)
      - pattern: $CURSOR.execute(f"...", ...)
    message: Potential SQL injection, use parameterized queries
    languages: [python]
    severity: ERROR
 
  - id: unsafe-deserialization
    pattern-either:
      - pattern: pickle.loads($X)
      - pattern: pickle.load($X)
    message: Unsafe deserialization with pickle
    languages: [python]
    severity: ERROR
 
  - id: command-injection
    pattern-either:
      - pattern: subprocess.$FUNC($CMD, ..., shell=True, ...)
      - pattern: os.system($CMD)
    message: Potential command injection
    languages: [python]
    severity: ERROR

SCA Configuration (Dependabot + Renovate)

# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "daily"
    open-pull-requests-limit: 10
    labels:
      - "dependencies"
      - "security"
    groups:
      security-patches:
        applies-to: security-updates
        patterns:
          - "*"
 
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "daily"
    groups:
      security-patches:
        applies-to: security-updates
        patterns:
          - "*"
 
  - package-ecosystem: "docker"
    directory: "/"
    schedule:
      interval: "weekly"
 
  - package-ecosystem: "terraform"
    directory: "/terraform"
    schedule:
      interval: "weekly"
{
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
  "extends": [
    "config:recommended",
    ":semanticCommits"
  ],
  "vulnerabilityAlerts": {
    "enabled": true,
    "labels": ["security"]
  },
  "osvVulnerabilityAlerts": true,
  "packageRules": [
    {
      "matchUpdateTypes": ["patch", "minor"],
      "matchCurrentVersion": "!/^0/",
      "automerge": true,
      "automergeType": "pr",
      "automergeStrategy": "squash"
    },
    {
      "matchDepTypes": ["devDependencies"],
      "automerge": true
    },
    {
      "matchUpdateTypes": ["major"],
      "labels": ["major-update"]
    }
  ]
}

Stage 4: Container Security

Secure Dockerfile

# Dockerfile with security best practices
 
# Pin a version, not latest (Node.js 24 is an LTS line; pin the full tag or the digest)
FROM node:24-alpine AS builder
 
WORKDIR /app
 
# Copy only package files first for better caching
COPY package*.json ./
 
# Full install: the build step needs devDependencies
RUN npm ci
 
COPY . .
 
# Build, drop devDependencies, then audit what ships
RUN npm run build && \
    npm prune --omit=dev && \
    npm audit --omit=dev --audit-level=high
 
# Production stage
FROM node:24-alpine AS production
 
# Security updates
RUN apk upgrade --no-cache && \
    apk add --no-cache dumb-init
 
# Create non-root user (UID 1001 matches runAsUser in the Kubernetes manifest)
RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup
 
WORKDIR /app
 
# Copy built application
COPY --from=builder --chown=appuser:appgroup /app/dist ./dist
COPY --from=builder --chown=appuser:appgroup /app/node_modules ./node_modules
COPY --from=builder --chown=appuser:appgroup /app/package.json ./
 
ENV NODE_ENV=production
ENV NPM_CONFIG_LOGLEVEL=warn
 
# Numeric UID so Kubernetes can verify runAsNonRoot
USER 1001:1001
 
# healthcheck.js must be part of the build output in dist/
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD ["node", "dist/healthcheck.js"]
 
# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/server.js"]
 
# Labels
LABEL org.opencontainers.image.source="https://github.com/org/repo"
LABEL org.opencontainers.image.description="Application description"
LABEL org.opencontainers.image.licenses="MIT"

Kubernetes Security Policies

# k8s/security-policies.yaml
 
# Pod Security Admission: enforce the "restricted" Pod Security Standard on the namespace
apiVersion: v1
kind: Namespace
metadata:
  name: production
  labels:
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.37
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/audit: restricted
 
---
# A Deployment that passes the restricted profile
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  namespace: production
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 1001
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          image: registry.example.com/myapp:1.0.0
          ports:
            - containerPort: 8080
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true   # hardening, not required by the restricted profile
            capabilities:
              drop: ["ALL"]
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 256Mi
          volumeMounts:
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: tmp
          emptyDir: {}
 
---
# Network Policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: myapp
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: api-gateway
      ports:
        - protocol: TCP
          port: 8080
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: database
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - namespaceSelector: {}
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
 
---
# Resource Quotas
apiVersion: v1
kind: ResourceQuota
metadata:
  name: security-quota
  namespace: production
spec:
  hard:
    pods: "20"
    requests.cpu: "10"
    requests.memory: 20Gi
    limits.cpu: "20"
    limits.memory: 40Gi

Stage 5: Compliance as Code

Policy as Code (OPA/Rego)

# policies/kubernetes.rego (Rego v1 syntax: "contains" and "if" in rule heads)
 
package kubernetes.admission
 
# Deny containers that may run as root (neither container nor pod sets runAsNonRoot)
deny contains msg if {
    input.request.kind.kind == "Pod"
    some container in input.request.object.spec.containers
    not container.securityContext.runAsNonRoot
    not input.request.object.spec.securityContext.runAsNonRoot
    msg := sprintf("Container %v must run as non-root", [container.name])
}
 
# Require resource limits
deny contains msg if {
    input.request.kind.kind == "Pod"
    some container in input.request.object.spec.containers
    not container.resources.limits
    msg := sprintf("Container %v must have resource limits", [container.name])
}
 
# Deny privileged containers
deny contains msg if {
    input.request.kind.kind == "Pod"
    some container in input.request.object.spec.containers
    container.securityContext.privileged
    msg := sprintf("Container %v must not be privileged", [container.name])
}
 
# Require approved registries
deny contains msg if {
    input.request.kind.kind == "Pod"
    some container in input.request.object.spec.containers
    not startswith(container.image, "gcr.io/my-project/")
    not startswith(container.image, "docker.io/library/")
    msg := sprintf("Container %v uses unapproved registry", [container.name])
}
 
# Require security scanning label
deny contains msg if {
    input.request.kind.kind == "Deployment"
    not input.request.object.metadata.labels["security-scanned"]
    msg := "Deployment must have security-scanned label"
}

Monitoring and Alerting

# prometheus-alerts.yml
# The metric names below are examples: Prometheus has no such metrics by default.
# Your scanners or CI jobs must export them (for example through a Pushgateway).
groups:
  - name: security-alerts
    rules:
      - alert: SecurityScanFailed
        expr: security_scan_status{result="failed"} > 0
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: Security scan failed
          description: "Security scan failed for {{ $labels.project }}"
 
      - alert: HighVulnerabilityDetected
        expr: security_vulnerabilities{severity="critical"} > 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: Critical vulnerability detected
          description: "Critical vulnerability in {{ $labels.image }}"
 
      - alert: UnauthorizedDeployment
        expr: deployment_without_approval > 0
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: Deployment without security approval
 
      - alert: SecretExposed
        expr: secret_scan_detections > 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: Secret exposed in code

Conclusion

Every stage above adds a check, but a check only protects you when it runs on every change and its failure blocks the merge or the deploy. Keep the fast checks (secrets, linters) in pre-commit and repeat them in CI, because a local hook can be skipped with git commit --no-verify.

Key takeaways:

  1. Shift left - Catch issues as early as possible
  2. Automate everything - Manual security checks don't scale
  3. Fail fast - Block insecure code from progressing
  4. Measure and improve - Track security metrics over time
  5. Balance security and velocity - Security shouldn't be a bottleneck

From production

JARVIS, the multi-agent system on Claude Code that runs DeviDevs, applies the same idea to its own repository. Secret scanning runs on content at commit, and the reason is written in the code: a secret that reaches git history cannot be taken back, the key has to be rotated. Between 7 September and 15 November 2026 that check produced 45 real blocks. A shell rule blocks curl | bash, process substitution and $(curl ...) passed to an interpreter, fail-closed: 299 real blocks in the same period. One lesson carries over to any pipeline: tests that exist but don't run protect nothing. Until September 2026 nobody ran the hook tests, neither CI nor pre-commit; then they got a runner.

Official references

Related on this site: Container Security in Kubernetes: DevSecOps Guide, API Security Testing Automation: OWASP API Top 10 Coverage, Application Security in SDLC: Shifting Security Left. More articles in the DevSecOps category, and the engineering work behind them is on the services page.

Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.