SecurityIntermediate

How to Secure Your CI/CD Pipelines from Code to Deployment

10 min read

TL;DR

Implementing security measures and best practices throughout your CI/CD pipeline to ensure secure software delivery.

How to Secure Your CI/CD Pipelines from Code to Deployment

Executive Summary

Your CI/CD pipeline holds the keys to production: it can read your source, build your artifacts, and deploy to every environment. An attacker who compromises the pipeline does not need to breach your application at all. This guide secures the pipeline stage by stage — source, build, artifact, deployment — covering code and secret scanning, pinned and verified dependencies, hardened builds, signed artifacts, least-privilege pipeline identities, and deployment guardrails, plus the monitoring that detects misuse. By the end you will be able to decide which stage of your pipeline is most exposed and what to fix first.

Why This Matters

Pipeline compromises are supply-chain compromises: the malicious code arrives through the channel everyone trusts, signed by your own process. The recurring causes are mundane — a leaked token in a build log, a third-party action swapped for a malicious version, a dependency pulled from an attacker-controlled source, a deploy credential that never expires. Because pipelines run unattended and with broad permissions, a single weakness converts directly into production access. The cost of securing the pipeline late is that you must also answer an unanswerable question: which past builds can you still trust?

Core Concepts

Threat Model: What Attackers Actually Target

Five risks dominate: code injection (a contributor or a compromised account lands malicious code), dependency vulnerabilities and substitution, secrets exposure in logs/artifacts/repos, infrastructure compromise of the runners themselves, and unauthorised access to pipeline configuration. Every control below maps to one of these.

Source Stage: Scan Code and Secrets on Every Change

The cheapest place to stop a problem is the pull request. Run static analysis, dependency checks, and secret scanning as required status checks — a commit containing a credential should be unmergeable, and the credential treated as compromised the moment it was pushed:

# Example GitHub Actions workflow with security checks
name: Security Checks

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Run SAST
        uses: github/codeql-action/analyze@v2
        
      - name: Check Dependencies
        uses: snyk/actions/node@master
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
          
      - name: Secrets Scanning
        uses: gitleaks/gitleaks-action@v2

Pin third-party actions to full commit SHAs, not tags — a tag can be moved to point at malicious code, a SHA cannot.

Build Stage: Reproducible, Minimal, Isolated

Builds should run in ephemeral, isolated environments, produce the same artifact from the same inputs, and run as non-root with only the files they need:

# Secure Dockerfile example
FROM node:18-alpine AS builder

# Use non-root user
USER node

# Set secure defaults
ENV NODE_ENV=production
ENV NPM_CONFIG_LOGLEVEL=error

# Copy only necessary files
COPY --chown=node:node package*.json ./
RUN npm ci --only=production

COPY --chown=node:node . .

# Use multi-stage build
FROM node:18-alpine
COPY --from=builder /app/dist ./dist

# Security headers
LABEL security.alpha.kubernetes.io/seccomp=runtime/default
LABEL security.alpha.kubernetes.io/capabilities=drop=all

USER node
CMD ["node", "dist/main.js"]

Use lockfiles and install in frozen mode (npm ci) so the build cannot silently resolve a different dependency graph than the one that was reviewed. Keep build logs free of secrets — mask values, and never echo environment variables for debugging.

Artifact Stage: Provenance and Integrity

An artifact you cannot verify is an artifact you cannot trust. Store artifacts in a controlled repository over TLS, and record provenance — which commit, which pipeline run, which dependencies — alongside the artifact itself:

# Example Maven settings for secure artifact handling
<settings>
  <mirrors>
    <mirror>
      <id>secure-central</id>
      <url>https://repo.maven.apache.org/maven2</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
  
  <servers>
    <server>
      <id>nexus-releases</id>
      <configuration>
        <httpConfiguration>
          <tlsVersions>
            <tlsVersion>TLSv1.2</tlsVersion>
          </tlsVersions>
        </httpConfiguration>
      </configuration>
    </server>
  </servers>
</settings>

Sign images and binaries (cosign is the common choice for containers) and verify signatures at deployment time. Promotion between environments should move the identical signed artifact — rebuilding for production means production runs something that was never tested.

Deployment Stage: Guardrails at the Gate

The deploy target enforces its own posture regardless of what the pipeline sends — non-root, no privilege escalation, read-only filesystem, bounded resources:

# Kubernetes deployment with security context
apiVersion: apps/v1
kind: Deployment
metadata:
  name: secure-app
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
      containers:
      - name: app
        image: secure-app:latest
        securityContext:
          allowPrivilegeEscalation: false
          readOnlyRootFilesystem: true
          capabilities:
            drop:
            - ALL
        resources:
          limits:
            memory: "256Mi"
            cpu: "500m"

Production deployments deserve an approval gate or a policy check (admission control verifying signatures and provenance) so that a compromised pipeline alone cannot push arbitrary code to production.

Pipeline Identity and Secrets

The pipeline's own credentials are the highest-value target in the system. Rules: one identity per pipeline and environment, least privilege (the test pipeline cannot deploy; the deploy identity cannot modify the pipeline), short-lived credentials via OIDC federation instead of stored cloud keys, and secrets fetched at runtime from a manager — never baked into images or written to disk:

// Example of secure secrets handling
import { SecretsManager } from '@aws-sdk/client-secrets-manager';

class SecureSecretsManager {
  private readonly client: SecretsManager;
  
  constructor() {
    this.client = new SecretsManager({
      region: process.env.AWS_REGION,
      maxRetries: 3
    });
  }
  
  async getSecret(secretName: string): Promise<string> {
    try {
      const response = await this.client.getSecretValue({
        SecretId: secretName,
        VersionStage: 'AWSCURRENT'
      });
      
      return response.SecretString || '';
    } catch (error) {
      console.error('Failed to retrieve secret:', error);
      throw error;
    }
  }
}

Dependencies: Continuous, Not Ceremonial

Scanning once at adoption decays within weeks. Wire audit tooling into the pipeline and into a scheduled job, and automate update pull requests so patching is routine rather than a project:

{
  "name": "secure-app",
  "version": "1.0.0",
  "scripts": {
    "security-audit": "npm audit && snyk test",
    "update-deps": "npm-check-updates -u && npm install"
  },
  "dependencies": {
    "express": "^4.18.2"
  },
  "devDependencies": {
    "snyk": "^1.1130.0",
    "npm-check-updates": "^16.14.6"
  }
}

Infrastructure and Monitoring

Pipeline infrastructure is production infrastructure: patch runners, encrypt artifact storage, log everything, and review the logs. Declare the build environment as code with logging and encryption on, the way you would any other workload:

# Terraform example with security configurations
resource "aws_codebuild_project" "secure_build" {
  name = "secure-build-project"
  
  environment {
    compute_type = "BUILD_GENERAL1_SMALL"
    image        = "aws/codebuild/standard:5.0"
    type         = "LINUX_CONTAINER"
    
    environment_variable {
      name  = "ENABLE_SECURITY_SCANNING"
      value = "true"
    }
  }
  
  logs_config {
    cloudwatch_logs {
      status = "ENABLED"
    }
  }
  
  artifacts {
    type = "S3"
    encryption_disabled = false
  }
  
  cache {
    type = "LOCAL"
    modes = ["LOCAL_DOCKER_LAYER_CACHE"]
  }
}

Then monitor pipeline behaviour itself — who changed the pipeline definition, which runs used which credentials, what deployed where — and codify the compliance gates so they are uniform across projects:

# Example compliance check configuration
compliance:
  checks:
    - name: secrets-scan
      type: gitleaks
      severity: HIGH
      
    - name: dependency-check
      type: owasp-dependency-check
      severity: MEDIUM
      
    - name: container-scan
      type: trivy
      severity: HIGH
      
    - name: code-quality
      type: sonarqube
      severity: MEDIUM

Structured event logging makes that monitoring possible:

# Example monitoring implementation
import logging
from dataclasses import dataclass
from datetime import datetime

@dataclass
class PipelineEvent:
    timestamp: datetime
    stage: str
    status: str
    details: dict

class PipelineMonitor:
    def __init__(self):
        self.logger = logging.getLogger("pipeline_monitor")
        
    def monitor_stage(self, event: PipelineEvent):
        # Log stage execution
        self.logger.info(f"Pipeline stage: {event}")
        
        # Check for security violations
        if self._detect_violation(event):
            self._trigger_alert(event)
            
    def _detect_violation(self, event: PipelineEvent) -> bool:
        # Implement security violation detection logic
        return False
        
    def _trigger_alert(self, event: PipelineEvent):
        # Implement alert mechanism
        pass

Security Tests as Pipeline Gates

Finally, express the non-negotiables as tests that fail the build: no critical vulnerabilities in the shipped artifact, secure headers and cookie flags present in the running application:

// Example security test implementation
import { SecurityScanner } from './security-scanner';

describe('Security Tests', () => {
  const scanner = new SecurityScanner();
  
  test('should not have critical vulnerabilities', async () => {
    const results = await scanner.scan({
      target: 'application',
      severity: 'CRITICAL'
    });
    
    expect(results.criticalVulnerabilities).toBe(0);
  });
  
  test('should have secure configurations', async () => {
    const config = await scanner.checkConfiguration();
    expect(config.secureHeaders).toBe(true);
    expect(config.secureCookies).toBe(true);
  });
});

Decision Framework

SituationRecommendation
Starting from an unsecured pipelineSecret scanning + least-privilege pipeline identity first; they close the highest-yield holes
Long-lived cloud keys stored in CIReplace with OIDC federation and short-lived credentials
Third-party actions/plugins by tagPin to full commit SHAs; mirror critical ones internally
Same artifact rebuilt per environmentBuild once, sign, promote the identical artifact
Regulated environmentProvenance records (SLSA-style) + admission verification at deploy
Self-hosted runnersTreat as production servers: patch, isolate per trust level, never share between public and private repos

Implementation Checklist

  • [ ] SAST, dependency scanning, and secret scanning are required checks on every pull request
  • [ ] Any secret ever committed is rotated, not just deleted from the file
  • [ ] Third-party actions and plugins pinned to commit SHAs
  • [ ] Builds run ephemeral and isolated, from lockfiles in frozen mode, as non-root
  • [ ] Artifacts signed at build; signatures and provenance verified at deploy
  • [ ] One least-privilege identity per pipeline per environment; OIDC short-lived credentials, no stored cloud keys
  • [ ] Production deploys gated by approval or admission policy
  • [ ] Pipeline definition changes are code-reviewed like production code
  • [ ] Pipeline audit logs retained and alerting on definition changes and unusual deploys
  • Trade-offs

    Every gate adds minutes and occasional false positives to the delivery path, and a pipeline that cries wolf will be bypassed — tune severities so failures mean something. Signing and provenance add tooling that must itself be maintained. Ephemeral runners cost more than a beloved long-lived build server. The balance to strike: automate the checks that catch the common failures, keep them fast, and reserve human gates for production promotion, where the cost of a bad deploy dwarfs the cost of a pause.

    When Not to Use

  • A personal or throwaway project with no production target: full provenance and admission control is disproportionate. Keep secret scanning and dependency updates; skip the rest.
  • Manual approval gates for every environment: approvals on dev/test deploys teach people to click approve reflexively. Gate production; automate the rest.
  • Self-hosted runners for untrusted code: never run public/fork pull-request code on runners that hold production credentials. Use hosted ephemeral runners for untrusted builds.
  • Conclusion

    A secure pipeline is one where the trusted path is also the verified path: scanned code, pinned dependencies, signed artifacts, short-lived least-privilege identities, and a production gate that checks all of it. Secure the stages in order of exposure — identity and secrets first — and the pipeline stops being your largest attack surface and starts being your strongest control.

    References

    Here are essential resources for securing CI/CD pipelines:

  • OWASP CI/CD Security - Pipeline security guide
  • GitHub Security Best Practices - GitHub Actions security
  • GitLab Security - GitLab pipeline security
  • Jenkins Security - Jenkins security guide
  • Azure DevOps Security - Pipeline security
  • AWS CodePipeline Security - AWS security
  • Container Security - Container scanning
  • Supply Chain Security - SLSA framework
  • Dependency Management - Supply chain security
  • Infrastructure as Code Security - IaC scanning
  • Secret Management - HashiCorp Vault
  • DevSecOps Practices - Security integration
  • These resources provide comprehensive information about securing CI/CD pipelines effectively.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.