The Complete Guide to CI/CD Pipeline Security

Introduction

CI/CD pipelines are the backbone of modern software delivery. They automate the journey from code commit to production deployment, enabling teams to ship faster, more reliably, and with greater confidence. But this power comes with a critical tradeoff: pipelines are increasingly the primary target for sophisticated attackers.

Think about what a CI/CD pipeline touches. It pulls source code, resolves dependencies, accesses secrets and credentials, builds artifacts, pushes to registries, and deploys to production infrastructure. A single compromised pipeline can give an attacker access to everything — source code, secrets, cloud accounts, customer data, and production systems.

This guide provides a complete overview of CI/CD pipeline security: what’s at stake, where the risks are, and how to build secure pipelines from source to production. Whether you’re a security engineer hardening existing pipelines or a DevOps team building new ones, this is your comprehensive reference for understanding and implementing CI/CD security.

We’ll cover the full landscape — from threat modeling and attack surfaces through secrets management, artifact integrity, policy enforcement, and platform-specific hardening. Along the way, we’ll link to detailed guides, hands-on labs, and practical resources that let you go deeper on every topic.

Why CI/CD Pipelines Are a Security Priority

CI/CD pipelines occupy a unique and dangerous position in modern infrastructure. They are automation systems with privileged access to nearly every critical resource in your organization. Understanding why they matter starts with understanding what they can reach.

Pipelines Are High-Value Targets

A typical CI/CD pipeline has access to:

  • Source code repositories — including private repositories, proprietary algorithms, and configuration
  • Secrets and credentials — API keys, cloud provider credentials, database passwords, signing keys
  • Cloud infrastructure — AWS, GCP, Azure accounts with deployment permissions
  • Production environments — direct deployment access to live systems serving customers
  • Artifact registries — container registries, package repositories, binary storage
  • Internal networks — runners often sit inside private networks with broad connectivity

A compromised pipeline doesn’t just give attackers a foothold — it gives them the keys to the kingdom. Pipeline compromise is one of the most efficient ways to achieve lateral movement across an entire organization.

Real-World Pipeline Attacks

This isn’t theoretical. Some of the most significant security incidents in recent years have been pipeline and supply chain attacks:

  • SolarWinds (2020) — Attackers compromised the build system for SolarWinds Orion, injecting malicious code into signed software updates that were distributed to ~18,000 organizations, including US government agencies. The attack went undetected for months because the malicious code was inserted during the build process, meaning the source code repository appeared clean.
  • Codecov (2021) — Attackers modified Codecov’s Bash Uploader script by exploiting a flaw in Docker image creation. For over two months, the compromised script exfiltrated environment variables — including CI/CD secrets, API tokens, and credentials — from thousands of CI environments that used Codecov.
  • CircleCI (2023) — An engineer’s laptop was compromised via malware, which gave attackers access to a CircleCI production session token. From there, attackers accessed customer environment variables, tokens, and keys stored within CircleCI’s platform. Every secret stored in CircleCI had to be considered compromised.
  • GitHub Actions (ongoing) — Multiple incidents involving compromised third-party actions, stolen GITHUB_TOKEN credentials, and supply chain attacks through action dependencies continue to demonstrate that pipeline security is a persistent and evolving threat.

The common thread in all these incidents: attackers target the pipeline itself, not the application. Traditional application security measures — WAFs, endpoint protection, runtime monitoring — don’t help when the attack vector is the build and deployment system.

The Asymmetry Problem

There’s a fundamental asymmetry in CI/CD security. Pipelines are designed to be permissive and fast. They need broad access to do their job. Security, on the other hand, requires restriction and verification. Bridging this gap — maintaining pipeline velocity while enforcing security boundaries — is the central challenge of CI/CD security.

The CI/CD Attack Surface

Before you can secure a pipeline, you need to understand where it can be attacked. The CI/CD attack surface is broad, spanning multiple systems, trust boundaries, and organizational domains.

Mapping the Attack Surface

The CI/CD attack surface includes:

  1. Source Code Repositories — Branch protection bypass, malicious pull requests, compromised developer accounts, unauthorized code changes to pipeline definitions
  2. Pipeline Definitions — Poisoned pipeline execution (PPE), where attackers modify CI configuration files (e.g., .github/workflows/, .gitlab-ci.yml, Jenkinsfile) through pull requests or branch pushes
  3. Build Environments — Shared runners, persistent build caches, compromised build tools, container escapes from build containers
  4. Dependencies — Dependency confusion, typosquatting, compromised upstream packages, malicious transitive dependencies
  5. Secrets and Credentials — Overly broad secret access, long-lived credentials, secrets leaked in logs, secrets accessible to forked repository builds
  6. Artifacts — Tampered build artifacts, unsigned images, compromised registries, artifact poisoning
  7. Deployment Targets — Unauthorized deployment, missing approval gates, insufficient environment separation

The OWASP Top 10 CI/CD Security Risks

The OWASP Top 10 CI/CD Security Risks project provides a structured framework for understanding these threats. It catalogs the most critical risks, including insufficient flow control mechanisms, inadequate identity and access management, dependency chain abuse, poisoned pipeline execution, and insufficient credential hygiene. Each risk maps to real-world attack patterns and provides concrete guidance for mitigation.

For a deep dive into why pipelines are the primary attack surface and how attackers exploit them, see our detailed analysis: Why CI/CD Pipelines Are the Primary Attack Surface.

Trust Boundaries and Execution Models

One of the most fundamental — and most frequently misunderstood — aspects of CI/CD security is trust boundaries. Every pipeline operates within a set of trust assumptions, and violations of those assumptions are where security breaks down.

Key Questions for Every Pipeline

For every pipeline execution, you should be able to answer:

  • Who triggered this pipeline? — Was it an internal developer, an external contributor, a scheduled job, or an automated dependency update?
  • What code is being executed? — Is it code from a trusted branch, a pull request from a fork, a third-party action, or a dynamically resolved dependency?
  • What identity does the pipeline assume? — What service accounts, cloud roles, or platform tokens are available during execution?
  • What resources can the pipeline access? — What secrets, infrastructure, registries, and environments are reachable?

Trust Models in CI/CD

Different pipeline triggers carry fundamentally different trust levels:

  • Push to protected branch — High trust. Code has passed review and branch protection rules.
  • Pull request from collaborator — Medium trust. Code author is known but changes haven’t been merged.
  • Pull request from fork — Low trust. Code comes from an external contributor and could contain anything.
  • Scheduled/cron jobs — Variable trust. Depends on what code and dependencies are resolved at execution time.
  • Manual dispatch — Depends on who dispatched and what parameters were provided.

The critical principle: pipeline permissions and secret access should be calibrated to the trust level of the trigger. A pull request from a fork should never have access to production deployment credentials.

Execution Models

Different CI/CD platforms handle execution isolation differently. Understanding the execution model — whether builds run in shared VMs, ephemeral containers, or persistent servers — directly impacts your security posture. Shared execution environments create risks of cross-build contamination, credential theft, and cache poisoning.

For a comprehensive exploration of CI/CD execution models and their security implications, see: CI/CD Execution Models, Trust Assumptions, and Security Guide.

Secrets Management

If there’s one area that deserves the most attention in CI/CD security, it’s secrets management. Credential compromise is consistently the #1 cause of CI/CD security incidents. Poor secrets hygiene — hardcoded credentials, overly broad access, long-lived tokens, secrets exposed to untrusted code — is behind nearly every major pipeline breach.

The Secrets Problem in CI/CD

Pipelines need secrets to function. They need credentials to pull code, resolve private dependencies, access cloud APIs, push artifacts, and deploy to production. The challenge is providing these credentials securely:

  • Minimizing exposure — Secrets should only be available to the specific steps that need them
  • Limiting lifetime — Credentials should be short-lived and automatically rotated
  • Restricting scope — Each credential should have the minimum permissions required
  • Preventing leakage — Secrets must not appear in logs, artifacts, error messages, or environment variables accessible to untrusted code

Secrets Management Approaches

There’s a maturity spectrum for secrets management in CI/CD:

Level 1: Native Platform Secrets

Every CI/CD platform provides a built-in secrets management mechanism — GitHub Actions secrets, GitLab CI variables, Jenkins credentials store. These provide basic encryption at rest and masking in logs. They’re a good starting point but have limitations: they’re platform-specific, difficult to audit, and typically offer coarse-grained access control.

Level 2: External Secret Managers

Integrating with dedicated secret management tools — HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, Google Secret Manager — provides centralized management, fine-grained access policies, audit logging, and automatic rotation. Vault, in particular, excels at generating dynamic, short-lived credentials scoped to specific pipeline runs.

Level 3: OIDC and Workload Identity Federation

The gold standard for CI/CD credentials is eliminating long-lived secrets entirely. Using OIDC (OpenID Connect) and workload identity federation, pipelines can authenticate to cloud providers using their platform identity — no stored secrets required. GitHub Actions, GitLab CI, and other platforms can exchange their OIDC tokens for short-lived cloud credentials scoped to specific repositories, branches, and environments.

This approach provides:

  • No secrets to steal — credentials are generated on-demand and expire in minutes
  • Fine-grained scoping — access can be restricted to specific repositories, branches, and deployment environments
  • Full auditability — every credential exchange is logged with pipeline context

Secrets Management Best Practices

  • Never hardcode secrets in pipeline definitions, source code, or Dockerfiles
  • Use environment-scoped secrets to separate staging and production credentials
  • Implement secret scanning in pre-commit hooks and CI to catch accidental exposure
  • Prefer OIDC/workload identity federation over stored credentials wherever possible
  • Use dynamic secrets (e.g., Vault dynamic database credentials) that are generated per-pipeline-run
  • Rotate all long-lived credentials on a regular schedule and immediately after any suspected compromise
  • Never expose secrets to pull request builds from forks

For detailed implementation guidance, see our in-depth guides:

Artifact Integrity and Supply Chain Security

Securing what goes into your pipeline (code, dependencies, secrets) is only half the battle. You also need to secure what comes out — the artifacts your pipeline produces and deploys. Artifact integrity ensures that what you deploy is exactly what you built, with no tampering along the way.

The Supply Chain Problem

Modern software doesn’t just consist of your code. A typical application includes hundreds or thousands of dependencies, base images, build tools, and third-party integrations. Each of these is a link in the supply chain, and each can be compromised. Supply chain attacks target these links — injecting malicious code into dependencies, tampering with build artifacts, or compromising registries.

Container Image Signing with Sigstore and Cosign

Container image signing provides cryptographic proof that an image was built by a trusted pipeline and hasn’t been tampered with. Sigstore and its Cosign tool have dramatically simplified image signing by providing keyless signing — using OIDC identities (like a CI/CD pipeline’s identity) to sign artifacts without managing long-lived signing keys.

In a secure pipeline, every container image should be:

  1. Signed at build time using the pipeline’s verified identity
  2. Verified at deployment time before being admitted to production
  3. Rejected if the signature doesn’t match a trusted identity or policy

Provenance and Attestations with SLSA and in-toto

SLSA (Supply-chain Levels for Software Artifacts) provides a framework for progressively improving supply chain integrity. At its core, SLSA defines provenance — a verifiable record of how, where, and by whom an artifact was built.

The in-toto framework complements SLSA by providing a way to define and verify the entire software supply chain — from source code through build to deployment. Each step in the chain produces attestations that can be verified against a predefined layout.

Key concepts:

  • Provenance — machine-readable metadata describing the build: what inputs were used, what build system ran, what outputs were produced
  • Attestations — signed statements about an artifact (e.g., “this image was built from this commit by this pipeline”)
  • Verification — automated checks at deployment time that reject artifacts without valid provenance

Software Bill of Materials (SBOM)

An SBOM provides a complete inventory of all components in a software artifact — every library, dependency, and tool version. SBOMs enable:

  • Vulnerability tracking — when a new CVE is published, you can immediately identify which artifacts are affected
  • License compliance — automated verification that all components meet license requirements
  • Incident response — rapid assessment of blast radius when a supply chain compromise is discovered

Reproducible Builds

Reproducible builds ensure that the same source code and build instructions always produce the same output artifact, bit-for-bit. This property makes it possible to independently verify that a released artifact matches its claimed source code, eliminating an entire class of build system attacks.

For detailed implementation guidance on artifact integrity, see:

Policy Enforcement

Security controls are only effective if they’re enforced consistently and automatically. Manual security reviews don’t scale. Checklists get forgotten. The solution is Policy as Code — encoding your security requirements as machine-readable policies that are automatically evaluated at every pipeline run.

Policy as Code with OPA and Rego

The Open Policy Agent (OPA) and its policy language Rego have become the de facto standard for policy enforcement in cloud-native environments. In a CI/CD context, OPA enables you to write policies that evaluate pipeline inputs, configurations, and outputs against your security requirements.

Common policy checks in CI/CD:

  • Container image policies — no latest tags, images must come from approved registries, no running as root
  • Kubernetes deployment policies — resource limits required, no privileged containers, network policies must exist
  • Infrastructure as Code policies — no public S3 buckets, encryption enabled, security groups properly scoped
  • Pipeline policies — required approval before production deployment, all tests must pass, vulnerability scan results within thresholds

Conftest for CI/CD Policy Evaluation

Conftest is a utility that makes it easy to run OPA/Rego policies against structured configuration data in CI/CD pipelines. It supports YAML, JSON, HCL, Dockerfile, and many other formats, making it versatile enough to validate Kubernetes manifests, Terraform plans, Dockerfiles, and pipeline configurations.

A typical policy enforcement pipeline stage:

  1. Pull policies from a central policy repository (version-controlled and reviewed)
  2. Run Conftest against the relevant configuration files
  3. Fail the pipeline if any mandatory policies are violated
  4. Generate a policy evaluation report as a pipeline artifact

Security Gates

Beyond configuration policies, effective CI/CD security requires automated security gates — checkpoints in the pipeline where security criteria must be met before proceeding. These include:

  • Static analysis gates — code must pass SAST scanning without critical findings
  • Dependency gates — no known critical or high CVEs in dependencies
  • Image scanning gates — container images must pass vulnerability scanning
  • Compliance gates — infrastructure configurations must meet compliance standards
  • Approval gates — production deployments require explicit human approval

For comprehensive guidance on implementing policy enforcement in your pipelines, see: Policy as Code in CI/CD: OPA, Rego, and Security Gates.

Pipeline Hardening Best Practices

Beyond the specific domains covered above, there are foundational hardening practices that apply across all CI/CD platforms and architectures. These practices reduce your attack surface, limit blast radius, and make your pipelines resilient to compromise.

Minimal Permissions (Least Privilege)

Every component in your pipeline should operate with the minimum permissions required to perform its function:

  • Platform tokens — GitHub’s GITHUB_TOKEN should be scoped to read-only by default, with write permissions granted only to specific steps that need them
  • Cloud credentials — IAM roles should be scoped to specific resources and actions, not broad policies like AdministratorAccess
  • Registry access — push access should be restricted to deployment pipelines, not every CI build
  • Repository access — pipeline service accounts should only have access to the repositories they need

Ephemeral Build Environments

Build environments should be ephemeral — created fresh for each pipeline run and destroyed afterward. Persistent build servers accumulate state, cached credentials, and potential compromises over time. Ephemeral runners ensure:

  • No cross-build contamination — each build starts clean
  • No persistent credentials — nothing survives beyond the build
  • Reduced attack surface — no long-running services to target
  • Consistent environments — no configuration drift

Action and Plugin Pinning

Third-party actions, plugins, and reusable components should be pinned to specific, immutable versions — preferably by commit SHA, not by mutable tag. Pinning by tag (e.g., v1) is vulnerable to tag hijacking, where an attacker pushes malicious code and moves the tag to point to it.

# Bad: Mutable tag, vulnerable to hijacking
- uses: actions/checkout@v4

# Good: Pinned to immutable commit SHA
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1

Branch Protection and Merge Controls

Branch protection rules are your first line of defense against unauthorized code changes:

  • Require pull request reviews before merging to protected branches
  • Require status checks (CI must pass) before merging
  • Require signed commits for verified authorship
  • Restrict who can push to protected branches
  • Prevent force pushes that could rewrite history
  • Require linear history to maintain auditability

Deployment Controls

Production deployments should have additional safeguards:

  • Environment protection rules — require manual approval for production deployments
  • Deployment freezes — ability to halt deployments during incidents or change freezes
  • Canary and progressive deployments — limit blast radius by rolling out changes gradually
  • Rollback capabilities — automated rollback when deployment health checks fail

Separation of Duties

No single person or system should control the entire pipeline from code commit to production deployment. Implement separation of duties by:

  • Requiring code review from someone other than the author
  • Separating CI (build/test) permissions from CD (deployment) permissions
  • Using separate credentials for different pipeline stages
  • Requiring multi-party approval for sensitive changes

For detailed guidance on hardening your pipelines, see:

Platform-Specific Guidance

While the principles of CI/CD security are universal, each platform has its own security model, features, and pitfalls. Here’s a brief overview of the major platforms with links to detailed guides.

GitHub Actions

GitHub Actions is the most widely adopted CI/CD platform for open-source and many commercial projects. Key security considerations include:

  • GITHUB_TOKEN permissions — set permissions at the workflow level with read-only defaults, granting write only where needed
  • Fork handlingpull_request_target is extremely dangerous if misused; prefer pull_request for untrusted code
  • Action pinning — pin all third-party actions by commit SHA
  • Environment protection — use environments with required reviewers and deployment branch policies
  • OIDC — use GitHub’s OIDC provider for keyless authentication to AWS, GCP, and Azure
  • Reusable workflows — centralize security patterns in reusable workflows maintained by the security team

GitLab CI

GitLab CI provides deep integration with GitLab’s broader DevSecOps platform. Key security considerations include:

  • Protected variables — mark sensitive variables as protected and masked; restrict to protected branches/tags
  • Protected runners — use protected runners for production deployments, shared runners for CI builds
  • Merge request pipelines — use rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" to control what runs on external contributions
  • OIDC/ID tokens — GitLab supports OIDC tokens via id_tokens keyword for keyless cloud authentication
  • Compliance frameworks — use GitLab’s compliance pipeline features to enforce required jobs

Tekton

Tekton is a Kubernetes-native CI/CD framework that provides unique security properties through its architecture:

  • Kubernetes-native isolation — each TaskRun executes in its own Pod, providing container-level isolation by default
  • Service account scoping — use dedicated Kubernetes service accounts for each pipeline with minimal RBAC permissions
  • Tekton Chains — automatic artifact signing and provenance generation, providing SLSA compliance natively
  • OCI bundles — distribute pipeline definitions as OCI artifacts for versioning and integrity verification
  • Admission control — integrate with Kubernetes admission controllers (e.g., Kyverno, Gatekeeper) for policy enforcement

Check the platform-specific cheat sheets and labs on our site for detailed, hands-on guidance for each platform.

Implementation Roadmap

Implementing CI/CD security doesn’t happen overnight. Here’s a phased approach that takes you from basic visibility to comprehensive enforcement.

Phase 1: Visibility (Weeks 1-4)

You can’t secure what you can’t see. Start with a complete inventory and assessment:

  • Audit all pipelines — inventory every CI/CD pipeline across your organization, including shadow CI systems teams may have set up independently
  • Map secret usage — identify every secret, credential, and token used in pipelines. Document their scope, lifetime, and rotation schedule
  • Scan for exposure — run secret scanning tools against repositories, pipeline definitions, and build logs to find leaked credentials
  • Assess permissions — review all service accounts, IAM roles, and platform tokens for excessive permissions
  • Document trust boundaries — map which pipelines can access which environments, secrets, and resources

Phase 2: Foundations (Weeks 5-12)

Implement fundamental security controls that reduce the most risk with the least complexity:

  • Implement least privilege — reduce all credentials to minimum required permissions. Set GITHUB_TOKEN to read-only by default. Scope cloud credentials to specific resources
  • Pin all dependencies — pin third-party actions by commit SHA, lock dependency versions, pin base images by digest
  • Secure secrets management — migrate to OIDC/workload identity federation where possible. Implement external secret managers for everything else. Rotate all credentials
  • Enable branch protection — require code review, status checks, and signed commits on all protected branches
  • Deploy ephemeral runners — replace persistent build servers with ephemeral, clean-room runners

Phase 3: Integrity (Weeks 13-20)

Build confidence that artifacts are authentic and untampered:

  • Implement artifact signing — sign all container images and build artifacts using Cosign with keyless signing
  • Generate provenance — produce SLSA provenance for all build artifacts, linking them to their source, build system, and parameters
  • Create SBOMs — generate SBOMs for all artifacts, enabling rapid vulnerability response
  • Enforce signature verification — configure admission controllers (Kyverno, Gatekeeper, Sigstore policy-controller) to reject unsigned or unverified images
  • Establish reproducible builds — work toward reproducible builds for critical artifacts

Phase 4: Enforcement (Weeks 21-30)

Automate security enforcement so it’s consistent, scalable, and not dependent on individual compliance:

  • Implement Policy as Code — define security policies in OPA/Rego and enforce them with Conftest in every pipeline
  • Deploy admission controllers — enforce runtime policies in Kubernetes that validate images, configurations, and deployments
  • Automate compliance checks — integrate compliance validation into pipelines with automated evidence collection
  • Implement security gates — add mandatory security checkpoints that block progression through the pipeline when criteria aren’t met
  • Continuous monitoring — set up alerting for policy violations, anomalous pipeline behavior, and unauthorized changes

Hands-On Labs

Theory is essential, but practice is where security skills are built. We provide hands-on labs that let you implement every concept covered in this guide in a real CI/CD environment:

Tools and Resources

The CI/CD security ecosystem includes a growing set of specialized tools. Here are the essential categories and key tools:

Secret Scanning and Management

  • GitLeaks / TruffleHog — scan repositories and commit history for exposed secrets
  • HashiCorp Vault — dynamic secrets, credential management, and encryption as a service
  • AWS Secrets Manager / GCP Secret Manager / Azure Key Vault — cloud-native secret management

Artifact Integrity

  • Sigstore (Cosign, Fulcio, Rekor) — keyless signing, certificate authority, and transparency log
  • in-toto — supply chain integrity framework
  • SLSA framework — supply chain security levels and provenance
  • Syft / Trivy — SBOM generation and vulnerability scanning

Policy Enforcement

  • OPA / Conftest — general-purpose policy engine for configuration validation
  • Kyverno — Kubernetes-native policy engine
  • Gatekeeper — OPA integration for Kubernetes admission control

Pipeline Security Scanning

  • Checkov — infrastructure as code scanning (Terraform, CloudFormation, Kubernetes)
  • StepSecurity Harden-Runner — runtime security for GitHub Actions
  • Snyk — developer-friendly security scanning for code, dependencies, and containers

For detailed tool comparisons and recommendations, visit our Resources page.

Conclusion

CI/CD pipeline security is not a single tool, a single practice, or a one-time effort. It’s a comprehensive discipline that spans the entire software delivery lifecycle — from the developer’s commit through build, test, packaging, and deployment to production.

The key takeaways from this guide:

  1. Pipelines are high-value targets — they have privileged access to everything. Treat them with the same security rigor as production systems.
  2. Understand your trust boundaries — know who triggers your pipelines, what code runs, and what resources are accessible at each stage.
  3. Secrets are your biggest risk — eliminate long-lived credentials wherever possible. Use OIDC, workload identity, and dynamic secrets.
  4. Verify artifact integrity — sign everything, generate provenance, create SBOMs, and enforce verification at deployment.
  5. Automate enforcement — encode security requirements as Policy as Code. Manual processes don’t scale and don’t survive the pressure of deadlines.
  6. Harden progressively — use the phased roadmap to systematically improve your security posture without disrupting delivery velocity.

The attack surface is broad, but the solutions are maturing rapidly. The Sigstore ecosystem, SLSA framework, OPA/Conftest, OIDC federation, and Kubernetes admission controllers provide a robust toolkit for building genuinely secure pipelines.

Start where you are. Audit your current state, implement the foundations, and progressively add integrity and enforcement controls. Every step you take closes a gap that attackers could exploit.

Explore the detailed guides, hands-on labs, and resources linked throughout this post to go deeper on every topic. Secure pipelines aren’t built in a day — but with the right knowledge and tools, they’re absolutely within reach.