Cloud security resource

Ci/cd pipeline security: protecting the cloud‑native application lifecycle

Secure CI/CD pipelines for cloud-native apps by locking down source control, isolating build agents, scanning and signing container images, enforcing Kubernetes admission policies, and wiring monitoring into every stage. Focus on least privilege, immutable artifacts, strong secrets management, and fast, automated detection and response for any pipeline compromise.

Security preflight checklist for CI/CD pipelines

  • Enforce SSO, MFA and least-privilege roles on your Git and CI/CD platforms (High).
  • Remove all long-lived credentials; adopt secrets managers and short-lived tokens (High).
  • Run builds on ephemeral, hardened runners with no direct internet exposure (High).
  • Integrate SAST, dependency and container image scanning as mandatory pipeline stages (High).
  • Sign images and enforce signature verification via Kubernetes admission controls (High).
  • Apply namespace-scoped RBAC and network policies for each environment (Medium).
  • Stream CI/CD logs to a central SIEM and alert on high-risk actions (Medium).

Threat modeling for cloud-native CI/CD workflows

Threat modeling clarifies where your cloud-native CI/CD is most exposed: source, build, registry, deployment and runtime. It is the fastest way to prioritize segurança em pipelines ci cd para aplicações cloud native without adding unnecessary complexity.

This approach is ideal when you:

  • Already run workloads on Kubernetes or other orchestrators and deploy frequently.
  • Use Git-based workflows with automated pipelines (GitHub Actions, GitLab CI, Jenkins, Azure DevOps, Bitbucket Pipelines, etc.).
  • Need to align security expectations across development, SRE and security teams.

Consider postponing a full threat model when:

  • Your team is still designing the basic CI/CD architecture and tools have not been chosen.
  • There is no clear owner for pipeline security or for approving mitigation actions.
  • You lack minimal inventory of repos, runners, registries and clusters; start by discovering assets first.

Minimal threat-model checklist (impact-first):

  • List high-value assets: production clusters, cloud accounts, critical registries, mainline branches.
  • Enumerate entry points: developer laptops, Git, CI runners, registry endpoints, Kubernetes APIs.
  • Map threats: code tampering, secrets exfiltration, dependency poisoning, image swap, deployment hijack.
  • Rank by blast radius and ease of exploit; treat High/Medium/Low as planning tags, not precise risk scores.

Once mapped, attach specific soluções de segurança para pipeline ci cd em ambiente cloud to each threat: least-privilege IAM, image signing, admission policies, network segmentation, and continuous monitoring.

Securing source control and secrets lifecycle

Source control and secrets are the primary targets for attackers. Harden them before investing in more advanced ferramentas de segurança para devops e ci cd em nuvem.

You will need at least:

  • Git platform with SSO and MFA (GitHub, GitLab, Bitbucket, etc.).
  • Cloud IAM (AWS IAM, Azure AD, GCP IAM, Keycloak, etc.) integrated for centralized identity.
  • A dedicated secrets manager (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault, GCP Secret Manager, or similar).
  • Code scanning and secret-detection tooling (gitleaks, trufflehog, GitHub Advanced Security, GitLab Secret Detection, etc.).
  • Protected branch rules, required reviews and status checks on main branches.

Baseline controls checklist (prioritized):

  • High: Enforce MFA and SSO on Git and CI/CD; block personal access tokens without expiry.
  • High: Enable protected branches, required pull/merge request reviews and signed commits for mainline.
  • High: Ban credentials in source; scan repos and block pushes with embedded secrets.
  • Medium: Rotate all CI/CD secrets regularly and prefer OIDC/JWT-based federation for pipelines.
  • Medium: Separate service accounts per pipeline with granular, least-privilege permissions.

Example GitHub repository protection (YAML for GitHub branch protection via Terraform-like pseudo-code):

# Example concept (adapt to your IaC provider)
resource "github_branch_protection" "main" {
  repository_id  = github_repository.app.id
  pattern        = "main"
  required_pull_request_reviews {
    required_approving_review_count = 1
  }
  require_signed_commits           = true
  enforce_admins                   = true
}

For GitHub Actions using OIDC to get cloud credentials (no static keys):

jobs:
  deploy:
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v4
      - name: Authenticate to cloud
        run: |
          # Example: exchange GitHub OIDC token for cloud credentials
          # aws sts assume-role-with-web-identity ...

Hardened build environments and dependency assurance

Build environments must be isolated, reproducible and free of unnecessary tools; dependencies must be verified and pinned. This section shows how to harden them step by step.

Preparation checklist before implementing the steps:

  • List all CI/CD runners (managed SaaS, self-hosted VMs, Kubernetes-based runners).
  • Define which environments need isolated runners (e.g., production deployments only).
  • Ensure you can rebuild runners from code (Terraform, Ansible, Packer, Kubernetes manifests).
  • Identify the package ecosystems you use (npm, pip, Maven, Go modules, etc.).
  • Choose at least one dependency scanner compatible with your stack (e.g., Snyk, Trivy, osv-scanner).
  1. Isolate CI/CD runners from production networks (High)
    Use network controls so runners cannot directly reach production databases or internal control planes. Permit access only to artifact registries and necessary APIs.

    • Place self-hosted runners in dedicated subnets or Kubernetes namespaces.
    • Use security groups or firewall rules to restrict egress and ingress.
    • Disable SSH access to runners, or tightly control it.
  2. Make runners ephemeral and immutable (High)
    Each job should run on a fresh environment that is destroyed when the job finishes. Build runner images from code, not by hand.

    • For Kubernetes-based runners, configure pods to be non-persistent and stateless.
    • Rebuild base images regularly with security updates.
    • Disallow manual logins to long-lived build servers.
    # Example: GitLab Runner using Kubernetes executor (values excerpt)
    runners:
      privileged: false
      podSecurityContext:
        runAsNonRoot: true
  3. Reduce runner attack surface (Medium)
    Install only the tools strictly required for builds. Remove compilers, shells and package managers where not needed.

    • Use minimal base images such as distroless or slim variants.
    • Avoid installing browsers or heavy debugging tools on shared runners.
    • Disable Docker-in-Docker if possible; prefer rootless builds or dedicated builder services.
  4. Pin dependencies and registries (High)
    Lock dependencies to exact versions and restrict where they can be downloaded from. This mitigates supply-chain attacks.

    • Use lockfiles (package-lock.json, yarn.lock, Pipfile.lock, go.sum, etc.) and commit them to source.
    • Configure package managers to use approved mirrors or private registries.
    • Block direct downloads from unknown registries in production pipelines.
    # Example: npm config for private registry
    npm config set registry https://registry.internal.example.com/
  5. Scan dependencies for known vulnerabilities (High)
    Add dependency scanning as a mandatory stage, failing builds for high-risk findings.

    • Integrate tools such as Trivy, osv-scanner or platform-native scanners.
    • Treat dependency updates as regular work, not only emergency tasks.
    • Track exceptions in code, with owners and expiry dates.
    # Example: Trivy dependency scan stage (GitHub Actions)
    - name: Scan dependencies
      uses: aquasecurity/trivy-action@master
      with:
        scan-type: "fs"
        security-checks: "vuln,secret,config"
  6. Lock build outputs and artifacts (Medium)
    Store build artifacts in write-once or append-only storage; prevent modification after publication.

    • Use separate artifact repositories per environment or trust level.
    • Require signatures or checksums before artifacts are promoted.
    • Disable manual uploads to production artifact repositories.

Container image security: scanning, signing and policy gates

Segurança em pipelines CI/CD: protegendo o ciclo de vida de aplicações cloud-native - иллюстрация

Container images are the main delivery unit for cloud-native workloads. Strong controls here are central to melhores práticas de segurança em pipelines ci cd kubernetes.

Use this checklist to validate your image security pipeline:

  • Images are built from minimal, trusted base images stored in an internal registry.
  • Builds run as non-root inside containers; Dockerfiles drop unnecessary capabilities.
  • Static analysis (SAST) runs against application code before image build.
  • Each image is scanned for OS and library vulnerabilities at build time using at least one scanner (e.g., Trivy, Grype).
  • Critical vulnerabilities cause the pipeline to fail unless a documented exception exists.
  • Images are signed (e.g., with cosign) and signatures are pushed to the same registry.
  • Production clusters enforce signature verification with an admission controller or policy engine (Kyverno, OPA Gatekeeper, admission plugins).
  • Only images from specific registries and projects are allowed to run in production namespaces.
  • Tagging is immutable for release tags (e.g., v1.2.3); tags are not overwritten with new content.
  • Runtime security agents or tools verify that running containers match approved, signed images.

Example: sign an image with cosign in a CI job:

cosign sign --key env://COSIGN_PRIVATE_KEY registry.example.com/app/backend:${GIT_COMMIT}

Example: verify signature in a Kubernetes admission policy (Kyverno-like pseudo-policy):

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: verify-image-signatures
spec:
  rules:
    - name: check-signature
      match:
        resources:
          kinds: ["Pod"]
      verifyImages:
        - image: "registry.example.com/app/*"
          key: "k8s://namespace/cosign-key"

Deployment-time protections: admission, RBAC and network policies

Deployment is where pipeline outputs become real risk. Admission controls, fine-grained RBAC and network isolation are central to como proteger o ciclo de vida de aplicações cloud native no ci cd.

Common misconfigurations to avoid:

  • Cluster-wide admin tokens stored as CI/CD variables, used for all deployments regardless of namespace.
  • Kubernetes ServiceAccounts bound to cluster-admin roles, even for simple app deployments.
  • No admission controller enforcing constraints such as mandatory namespaces, labels, or non-root execution.
  • CI/CD deploying directly to production with no separate approval or promotion from staging artifacts.
  • Lack of namespace separation between dev, staging and production workloads.
  • Missing or overly permissive NetworkPolicies, effectively turning the cluster into a flat network.
  • Ingress controllers with wildcard hosts and wide-open access from the public internet.
  • Helm charts or manifests that can override security policies (e.g., hostNetwork, privileged: true).
  • No limit on what kinds of resources pipelines can apply; a single pipeline account can change Ingress, NetworkPolicy, RBAC and more.
  • Drift between Git and the cluster; manual kubectl changes bypass policy and review.

Safer deployment-time patterns:

  • One ServiceAccount per pipeline per environment, with namespace-scoped, minimal RBAC.
  • Admission policies that block privileged containers, hostPath mounts and unapproved images.
  • Mandatory NetworkPolicies for every application namespace, even if initially permissive.
  • GitOps-style tools (Argo CD, Flux) pulling from Git, with CI only updating manifests and images.

Example: namespace-scoped RBAC for a deployer ServiceAccount:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: production
  name: ci-deployer
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "patch", "update"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  namespace: production
  name: ci-deployer-binding
subjects:
  - kind: ServiceAccount
    name: ci-deployer
    namespace: production
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: ci-deployer

Detecting, alerting and responding to pipeline compromises

Segurança em pipelines CI/CD: protegendo o ciclo de vida de aplicações cloud-native - иллюстрация

Detection and response must be built around your CI/CD and Kubernetes layers. Different approaches fit different maturity levels and tool stacks for segurança em pipelines ci cd para aplicações cloud native.

Consider these complementary options:

  • CI/CD-native audit and alerts (Low to Medium effort)
    Use built-in audit logs and security features in your CI/CD platform.

    • Enable audit logs for login attempts, token creation, secret changes and pipeline edits.
    • Create alerts for events such as new admin users, new runners, or pipeline configuration changes.
    • Stream logs to a central log system or SIEM (e.g., CloudWatch, Stackdriver, Elastic, Loki).
  • Cloud and Kubernetes security tools (Medium effort)
    Leverage existing cloud-native tooling as soluções de segurança para pipeline ci cd em ambiente cloud.

    • Use managed cloud security centers or CSPM tools to detect risky configurations in IAM and networks.
    • Deploy Kubernetes security tools that alert on suspicious pod activity, new privileged workloads or abnormal network flows.
    • Integrate container runtime security agents with image metadata from your CI/CD.
  • Dedicated DevSecOps monitoring stack (Higher effort)
    For larger teams, combine ferramentas de segurança para devops e ci cd em nuvem into a cohesive observability layer.

    • Correlate CI/CD events (pipeline changes, new secrets) with cluster events (new deployments, policy violations).
    • Automate responses such as locking service accounts, revoking tokens or pausing pipelines on high-confidence alerts.
    • Practice incident response drills specific to pipeline compromise scenarios.
  • Process and people safeguards (Low effort, high impact)
    Technical controls fail without clear procedures.

    • Define who can approve changes to CI/CD templates and security policies.
    • Create playbooks for leaked secrets, malicious commit detection and compromised runner response.
    • Train developers and SREs on secure pipeline usage and basic triage steps.

Operational gotchas and concise mitigations

How do I secure pipelines without slowing every deployment?

Segurança em pipelines CI/CD: protegendo o ciclo de vida de aplicações cloud-native - иллюстрация

Start with controls that are transparent to developers: MFA, least-privilege tokens, ephemeral runners and automated scanning. Then add policy gates only where you have clear remediation paths. Measure pipeline duration before and after each new control to avoid hidden performance regressions.

What is the minimum I should do before going to production with Kubernetes?

Enforce MFA on Git and CI/CD, use a secrets manager, run image and dependency scans, and deploy with namespace-scoped RBAC. Add at least basic admission policies to block privileged containers and enforce images from your registry. These steps already cover major classes of attacks.

How can I migrate from static cloud keys in CI to short-lived credentials?

Use OIDC or similar federation between your CI/CD platform and the cloud provider. Replace stored access keys with trust policies that issue short-lived tokens for specific pipelines and roles. Roll out per-project, keeping fallbacks until you validate permissions.

How do I handle legacy pipelines that use Docker-in-Docker and root users?

Introduce non-privileged builder images or remote builders and gradually migrate jobs. Run legacy jobs in tightly isolated runners with strict network controls until they are refactored. Track each legacy pattern with an owner and a target removal date.

What is the best way to audit who changed pipeline definitions?

Store pipeline configurations as code in Git, protected by reviews and branch rules. Ensure your CI/CD platform is integrated with central logging so pipeline edits, secret changes and token creations are logged and retained. Periodically review high-risk actions as part of security checks.

How can I validate that only signed images run in production?

Combine image signing in the CI pipeline with Kubernetes admission policies that verify signatures before permitting pods to start. Regularly test with intentionally unsigned images to ensure the policy triggers. Monitor admission logs for denied events and unusual bypass attempts.

What should I do first after discovering a leaked CI/CD secret?

Immediately revoke or rotate the secret in the source system, then in the CI/CD platform. Search logs for suspicious activity around the time of exposure. Add a detection rule to catch similar leaks and consider moving to a short-lived credential model to reduce future impact.