intermediate By Mathias Paulenko

CI/CD Pipeline Security Template

A template for securing build and deployment pipelines against credential leaks, tampering, supply chain attacks, and unauthorized deployments.

Note: This guide follows English-language naming conventions and terminology standards common in international development teams. Examples use English identifiers and comments to maximize compatibility across codebases and tooling.

Overview

CI/CD pipelines are a high-value target for attackers because they have access to source code, build secrets, and production deployment paths. A compromised pipeline can introduce malware, exfiltrate data, or deploy unauthorized changes. This template defines controls to protect code integrity, runner security, secrets, and deployment approvals.

When to Use

  • For alternatives, see CI/CD Security: Harden Your Pipelines and Prevent Supply.

  • Setting up a new CI/CD platform.

  • Reviewing or improving an existing pipeline.

  • Preparing for a supply chain security audit.

  • After a build system compromise or unauthorized deployment.

  • Integrating DevSecOps controls into engineering workflows.

Prerequisites

  • A version control system with branch protection and audit logging.
  • A CI/CD platform such as GitHub Actions, GitLab CI, Azure DevOps, or Jenkins.
  • A secret management solution for pipeline credentials.
  • A process for code review and approval before merging.
  • Ownership from platform engineering, security, and release management.

Solution

Template

1. Source Control Security

ControlRequirementVerification
Branch protectionRequired reviews before merge to mainRepository settings
Signed commitsRequire verified commits for privileged accountsGit configuration
Access controlLeast-privilege access to repositoriesRBAC review
Audit loggingAll pushes, merges, and permission changes loggedPlatform logs
Dependency pinningLockfiles and pinned versions for reproducible buildsRepository files
Secret scanningAutomated detection of secrets in commitsPre-commit hooks + CI

2. Pipeline Configuration

ControlRequirementVerification
Immutable pipeline definitionsPipelines stored as code and reviewedRepository files
No secrets in codeSecrets loaded from vault, CI variables, or OIDCSecret scanning
Input validationPipeline parameters validated and sanitizedCode review
Self-hosted runner isolationProduction runners isolated from dev runnersRunner configuration
Ephemeral runnersFresh runner per build to reduce persistenceRunner settings
Pipeline provenanceSLSA provenance generated for artifactsAttestation tool

3. Secrets Management

Secret TypeStorageRotationScope
Cloud credentialsExternal vault or OIDC90 daysPer environment
Container registry tokensVault or short-lived CI tokens90 daysPer pipeline
Signing keysHardware-backed or KMS180 daysLimited service accounts
API keysVault or secret manager90 daysMinimum required permissions
Database passwordsVault dynamic secrets24 hoursPer pipeline run

4. Build Security

ControlRequirementVerification
Dependency scanningAll dependencies scanned for known CVEsScanner in CI
Static analysisSAST run on every pull requestCI job
Container image scanningBase image and layers scanned before pushRegistry scan
Reproducible buildsSame source produces same artifactBuild verification
Artifact signingAll artifacts signed with build identitySignature verification
SBOM generationBill of materials generated per buildCI output

5. Deployment Security

ControlRequirementVerification
Deployment gatesManual or automated approval before productionPipeline rules
Environment separationProduction credentials not available in devSecret scoping
Rollback planAutomated rollback trigger on failurePipeline definition
Immutable deploymentsArtifacts deployed by reference, not rebuiltDeployment logs
Drift detectionUnauthorized production changes detectedMonitoring tool
Audit trailWho deployed what, when, and whyDeployment logs

6. Incident Response

ScenarioResponseOwner
Secret leakedRotate secret, revoke tokens, audit usageSecurity team
Malicious commitRevert, investigate, revoke credentialsPlatform team
Compromised runnerTerminate runner, rebuild, review logsPlatform team
Unauthorized deploymentRollback, freeze pipeline, auditRelease manager
Tampered artifactBlock deployment, trace provenanceSecurity team

Explanation

Pipeline security is a subset of supply chain security. By protecting the source, the build process, and the deployment path, the organization reduces the risk of malicious code reaching production. The template maps each control to a verification method, making it suitable for audits and continuous improvement.

GitHub Actions Security Configuration

name: Secure CI Pipeline
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

permissions:
  contents: read
  packages: write
  id-token: write

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789:role/ci-role
          aws-region: us-east-1
          # No static keys - OIDC only

      - name: Build and sign
        uses: sigstore/cosign-installer@v3
      - run: |
          cosign sign-blob --yes artifact.tar.gz

      - name: Generate SBOM
        uses: anchore/sbom-action@v0
        with:
          format: spdx-json
          output-file: sbom.spdx.json

      - name: Scan dependencies
        uses: github/codeql-action/init@v3
      - run: npm audit --audit-level=high
      - uses: github/codeql-action/analyze@v3

SLSA Provenance Example

{
  "_type": "https://in-toto.io/Statement/v1",
  "subject": [
    {
      "name": "artifact.tar.gz",
      "digest": { "sha256": "abc123..." }
    }
  ],
  "predicateType": "https://slsa.dev/provenance/v1",
  "predicate": {
    "builder": { "id": "github-actions" },
    "buildType": "https://github.com/actions/runner",
    "invocation": {
      "configSource": {
        "uri": "git+https://github.com/org/repo",
        "digest": { "sha1": "commit-hash" }
      }
    },
    "materials": [
      { "uri": "git+https://github.com/org/repo", "digest": { "sha1": "commit-hash" } }
    ]
  }
}

Pipeline Security Audit Checklist

ControlVerifiedNotes
No long-lived secrets in CI
OIDC for cloud auth
Actions pinned to SHA
Minimal permissions per job
Branch protection on main
Signed artifacts verified
SBOM generated per build
Dependency scan in pipeline
Runners isolated per env
Audit log retention > 90 days

Variants

  • GitHub Actions security checklist: Focuses on actions pinning, workflow permissions, and reusable workflows.
  • GitLab CI security template: Includes CI/CD job token scopes, protected runners, and compliance pipelines.
  • Jenkins hardening template: Covers plugin management, agent isolation, and Groovy sandboxing.
  • Container-native pipeline: Emphasizes image signing, registry scanning, and Kubernetes admission.
  • High-compliance pipeline: Adds SLSA Level 3, dual approval, and signed SBOMs for regulated environments.

What works

  • Store pipeline definitions as code and review them like application code.
  • Use short-lived credentials and OIDC instead of long-lived secrets.
  • Scan dependencies before merging and before deploying.
  • Sign artifacts and verify signatures before deployment.
  • Separate build and production environments physically or logically.
  • Require human approval for production deployments.
  • Generate and retain SBOMs for every release.
  • Monitor pipeline activity for unusual behavior.

Common Mistakes

  • Storing secrets in environment variables or pipeline files.
  • Using third-party actions without pinning or reviewing them.
  • Allowing any branch to deploy to production.
  • Running production and dev workloads on the same runner.
  • Skipping security scans for hotfix deployments.
  • Not rotating pipeline credentials after a compromise.
  • Trusting artifacts without signature verification.

Troubleshooting

  • Authentication bypass in tests: ensure test users cannot reach production endpoints.
  • False positives in scanning tools: tune rules against the risk profile. Distinguish between reachable vulnerabilities and theoretical issues.
  • Secrets appear in logs: configure log filters to redact tokens, passwords, and keys. Audit log sinks for sensitive patterns.
  • CSP breaks legitimate functionality: use report-only mode first, then enforce. Iterate on allowed sources based on real violations.
  • Incident response stalls: run tabletop exercises.

Further Reading

  • Official documentation: check the current reference for the framework or tool used.
  • Related guides: explore the security and supply-chain guides for deeper coverage.
  • Complementary patterns: review design patterns applicable to your technology stack.
  • Public postmortems: study real incidents from teams that faced similar production issues.

Production Notes

  • Deploy gradually using canary or blue-green to catch regressions early.
  • Configure alerts for error rate, p99 latency, and failure rate before enabling in production.
  • Document the rollback in the runbook; test the procedure in staging at least once per quarter.
  • Review structured logs with correlation IDs to trace requests end-to-end during incidents.

Key Takeaways

  • Apply ci/cd pipeline security template when you need a practical solution for your use case.
  • Monitor performance after implementation; measure latency, errors, and resource usage before and after.
  • Check the Troubleshooting section for common failures; most have documented root causes with fixes.
  • Keep dependencies updated and run tests in CI to prevent production regressions.

Common Production Pitfalls

  • Leaving required fields blank or using vague one-word answers.
  • Filling the document once and never updating it after scope or decisions change.
  • Storing the document where the team does not look during incidents or reviews.
  • Not assigning an owner, due date, or review cadence.
  • Copying boilerplate without removing sections that do not apply.
  • Skipping version control, which makes rollback and accountability impossible.
  • Failing to link the document to related decisions or follow-up actions.
  • Avoiding quarterly reviews that would retire stale or unused sections.

Frequently Asked Questions

What is the biggest risk in CI/CD?
The most common high-impact risk is credential theft from a runner or pipeline file, which allows attackers to access production or tamper with builds.
How do we balance security with fast deployments?
Automate security checks, use fast scanners, and require approval only for production. Shift-left scanning gives fast feedback without blocking the pipeline.
What is SLSA provenance?
SLSA is a framework for supply chain security. Provenance records how an artifact was built, including source repository, build command, and dependencies, making it easier to detect tampering.
How do we secure secrets in CI/CD pipelines?
Use a dedicated secrets manager (HashiCorp Vault, AWS Secrets Manager, GitHub Actions secrets). Never hardcode secrets in pipeline files or environment variables. Use OIDC for cloud authentication...
What is the difference between SAST, DAST, and SCA?
SAST (Static Application Security Testing) analyzes source code for vulnerabilities without running it. DAST (Dynamic Application Security Testing) tests a running application from the outside. SCA...
Should we use self-hosted or cloud-managed runners?
Cloud-managed runners (GitHub-hosted, GitLab SaaS) are ephemeral and isolated by default, reducing attack surface. Self-hosted runners are necessary for private network access or specialized...
How do we implement dual approval for production deployments?
Configure your pipeline to require manual approval from two different team members before deploying to production. Use environment protection rules in GitHub Actions or GitLab protected environments....
What is an SBOM and why do we need it?
An SBOM (Software Bill of Materials) is a machine-readable inventory of all components in a software artifact, including transitive dependencies, versions, and licenses. It enables vulnerability...
What is cosign and how does it work?
Cosign is a tool from the Sigstore project for signing and verifying container images and blobs. It uses keyless signing with OIDC tokens from your CI provider, eliminating the need to manage signing...
How do we handle secrets for self-hosted runners?
Use ephemeral runners that are destroyed after each job. Inject secrets at runtime from a secrets manager (Vault, AWS Secrets Manager). Never store secrets on the runner disk. Scrub secret values...