Ecstaticloud
Initializing0%
Ecstaticloud Logo
Back to all insights
Cybersecurity & Zero-TrustDecember 1, 2026• 8 min read

Zero-Trust AWS IAM: Securing CI/CD with OIDC Tokens

Eliminate credential leaks in GitHub Actions by migrating from static AWS IAM keys to ephemeral OIDC tokens, cutting security exposure to zero.

Quick Overview

To implement a zero-trust architecture using github actions oidc aws zero trust, you eliminate long-lived, static access keys (AWS_ACCESS_KEY_ID) in favor of short-lived, cryptographically signed OpenID Connect (OIDC) identity tokens. GitHub's OIDC provider issues a temporary JWT per job. AWS IAM validates this token via sts:AssumeRoleWithWebIdentity against pre-configured trust policies, granting scoped, temporary IAM credentials valid only for the execution duration.


Real-World Problem & Architectural Motivation

The Multi-Tenant CI/CD Attack Vector

In traditional cloud operations, enterprise deployment pipelines rely on long-lived AWS IAM User credentials (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) stored as static secrets inside CI/CD platforms like GitHub Actions, GitLab CI, or CircleCI.

This model introduces severe operational and security vectors:

[ Traditional Anti-Pattern ]
+-------------------------------------------------------------------+
|  GitHub Action Secrets Repository                                 |
|  - AWS_ACCESS_KEY_ID: AKIAIOSFODNN7EXAMPLE (Valid Indefinitely)   |
|  - AWS_SECRET_ACCESS_KEY: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY|
+-------------------------------------------------------------------+
                                 |
                                 v  (Compromised via dependency injection, rogue PR, or leak)
+-------------------------------------------------------------------+
|  Attacker / Malicious Third Party                                 |
|  -> Unrestricted Account Access until manually revoked            |
|  -> CloudTrail attribution points to static IAM User (No context) |
+-------------------------------------------------------------------+
  1. Credential Persistence and Blast Radius: Static credentials do not expire automatically. If a developer unintentionally logs environment variables, a third-party action in a workflow is compromised, or a developer workstation holding repository secrets is compromised, attackers gain persistent access to the target AWS account.
  2. Attribution and Audit Log Blindspots: When every pipeline execution uses the same static IAM User credentials, AWS CloudTrail logs record identical API calls under that single access key ID. You lose granular traceability into which specific repository, workflow run, git commit, or pull request executed an action.
  3. Secret Rotation Friction: Rotating static secrets across hundreds of microservices and repositories requires complex automation or manual engineering labor. The administrative burden causes organizations to skip secret rotation, violating basic SOC 2 Type II, ISO 27001, and NIST SP 800-53 compliance controls.
  4. Elevated Privileges: To avoid pipeline failures, operations teams frequently assign wide permissions (e.g., AdministratorAccess or full service-level wildcards s3:*, ecr:*) to static CI/CD IAM Users, failing the principle of least privilege.

The Zero-Trust Paradigm: Federated Ephemeral Identities

Zero-Trust CI/CD pipeline security enforces a fundamental rule: Never trust a runner location or platform implicit identity; always explicitly authenticate every pipeline execution using short-lived cryptographic proofs.

By leveraging an aws iam oidc identity provider, we eliminate static aws access keys entirely. The pipeline requests an OIDC identity token from GitHub's token service for every execution. AWS STS validates the signature of the token against GitHub's public keys, inspects embedded identity claims (such as repository name, workflow branch, and environment), and issues temporary AWS credentials with a maximum lifespan as low as 15 minutes.


Architecture Blueprint & Flow

The authentication flow utilizes standard OAuth 2.0 / OIDC protocols combined with AWS Security Token Service (STS).

Request Lifecycle Diagram

+------------------+         +-------------------------+         +------------------+         +-------------------+
|  GitHub Actions  |         |  GitHub OIDC Provider   |         |     AWS STS      |         |   AWS Resources   |
|  Runner (Job)    |         | (token.actions.github)  |         | (Security Token) |         | (S3, ECR, EKS)    |
+------------------+         +-------------------------+         +------------------+         +-------------------+
         |                                |                               |                             |
         | 1. Request OIDC Token          |                               |                             |
         |------------------------------->|                               |                             |
         |                                |                               |                             |
         | 2. Return Signed JWT           |                               |                             |
         |<-------------------------------|                               |                             |
         |    (Contains repository,       |                               |                             |
         |     git ref, environment)      |                               |                             |
         |                                |                               |                             |
         | 3. Call sts:AssumeRoleWithWebIdentity(JWT, RoleArn)            |                             |
         |--------------------------------------------------------------->|                             |
         |                                                                |                             |
         |                                | 4. Fetch Public JWKS Keys     |                             |
         |                                |<------------------------------|                             |
         |                                | 5. Return Public Keys (RS256) |                             |
         |                                |------------------------------>|                             |
         |                                                                |                             |
         |                                                                | 6. Validate JWT Signature,  |
         |                                                                |    Audience & StringEquals  |
         |                                                                |    Condition on 'sub' claim |
         |                                                                |                             |
         | 7. Return Temporary AccessKeyId, SecretAccessKey, SessionToken |                             |
         |<---------------------------------------------------------------|                             |
         |                                                                                              |
         | 8. Authenticated AWS API Requests (e.g., ecr:GetAuthorizationToken)                          |
         |--------------------------------------------------------------------------------------------->|

Deep-Dive Component Interactions

  1. Token Provisioning Request: The GitHub Actions runner initiates a local request to the GitHub token issuer using an environment-provided IPC endpoint. The runner MUST declare permissions: id-token: write.
  2. Cryptographic Signing: GitHub’s Token Service generates an RS256-signed JSON Web Token (JWT). The payload includes standard claims (iss, aud, exp, nbf) alongside custom claims:
    • sub (Subject): repo:ecstaticloud/core-infrastructure:ref:refs/heads/main
    • aud (Audience): Set by default to sts.amazonaws.com or a specified client ID.
    • repository: ecstaticloud/core-infrastructure
    • actor: octocat
    • environment: production
  3. Federated Authentication Call: The runner executes the AWS authentication step, invoking sts:AssumeRoleWithWebIdentity with the raw JWT and the targeted IAM Role ARN.
  4. Signature & Claim Validation:
    • JWKS Fetching: AWS STS uses the Issuer URL (https://token.actions.githubusercontent.com) to query the OIDC Discovery document (/.well-known/openid-configuration) and fetch GitHub's JSON Web Key Set (/.well-known/jwks.json).
    • Cryptographic Verification: AWS STS verifies that the JWT signature matches GitHub's public key.
    • Trust Policy Evaluation: AWS IAM matches the parameters inside the JWT against the IAM Role’s Trust Policy Condition Keys. Specifically, it ensures the aud claim matches sts.amazonaws.com and the sub claim satisfies strict string equality or pattern matches defined in the policy.
  5. Session Generation: Upon successful validation, AWS STS returns short-lived temporary access credentials:
    • AccessKeyId (Prefix ASIA...)
    • SecretAccessKey
    • SessionToken
    • Expiration (e.g., 900 seconds)
  6. Scoped AWS Access: The pipeline runner executes AWS SDK commands or Terraform scripts using these transient credentials. CloudTrail records the exact IAM Role, along with the OIDC subject parameters (sub), identifying the exact commit, pipeline run, and actor.

Production-Ready Implementation & Code

This production implementation provides complete infrastructure configuration using Terraform HCL alongside a hardened GitHub Actions workflow.

1. Terraform Provisioning (AWS IAM OIDC Setup)

This Terraform module establishes the OpenID Connect identity provider in AWS, builds a least-privilege IAM role, and attaches strict Trust Policies asserting both repository isolation and production environment bounds.

# main.tf

terraform {
  required_version = ">= 1.5.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

variable "aws_region" {
  type        = string
  default     = "us-east-1"
  description = "Target AWS Region for deployment."
}

variable "github_organization" {
  type        = string
  default     = "ecstaticloud"
  description = "GitHub Organization name permitted to assume the IAM Role."
}

variable "github_repository" {
  type        = string
  default     = "production-service"
  description = "Target GitHub Repository name."
}

# ------------------------------------------------------------------------------
# GitHub OIDC Identity Provider
# Note: AWS now automatically manages GitHub OIDC root CA thumbprints. 
# We supply standard OpenSSL thumbprints for fallback explicit declaration.
# ------------------------------------------------------------------------------
resource "aws_iam_openid_connect_provider" "github_actions" {
  url             = "https://token.actions.githubusercontent.com"
  client_id_list  = ["sts.amazonaws.com"]
  thumbprint_list = [
    "6938fd4d98bab03faadb97b34396831e3780aea1",
    "1c58a2a856c645c7d1096b77b63994e60b085072"
  ]

  tags = {
    Environment = "production"
    ManagedBy   = "terraform"
    Architect   = "Ecstaticloud"
  }
}

# ------------------------------------------------------------------------------
# IAM Trust Policy Document
# Enforces matching repository, git reference (main branch), and environment.
# ------------------------------------------------------------------------------
data "aws_iam_policy_document" "github_actions_assume_role" {
  statement {
    sid     = "ExplicitGitHubOIDCFederation"
    effect  = "Allow"
    actions = ["sts:AssumeRoleWithWebIdentity"]

    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github_actions.arn]
    }

    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = ["sts.amazonaws.com"]
    }

    # Strict Zero-Trust Match: Restrict execution to the main branch of a specific repository
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:${var.github_organization}/${var.github_repository}:ref:refs/heads/main"]
    }

    # Optional Security Enforcement: Require deployment environment claim
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:environment"
      values   = ["production"]
    }
  }
}

# ------------------------------------------------------------------------------
# IAM Role Definition
# Sets absolute minimum required session duration (15 mins to 1 hour).
# ------------------------------------------------------------------------------
resource "aws_iam_role" "github_actions_deployer" {
  name                 = "ecstaticloud-gha-production-deployer"
  description          = "Scoped deployment role assumed strictly by GitHub Actions main branch"
  assume_role_policy   = data.aws_iam_policy_document.github_actions_assume_role.json
  max_session_duration = 3600 # 1 hour maximum lifetime

  tags = {
    Environment = "production"
    ManagedBy   = "terraform"
  }
}

# ------------------------------------------------------------------------------
# Least-Privilege Scoped Policy
# Grants explicit deployment actions for ECR container image management.
# ------------------------------------------------------------------------------
data "aws_iam_policy_document" "deployment_permissions" {
  statement {
    sid    = "ECRAuthTokenFetch"
    effect = "Allow"
    actions = [
      "ecr:GetAuthorizationToken"
    ]
    resources = ["*"]
  }

  statement {
    sid    = "ScopedECRImageOperations"
    effect = "Allow"
    actions = [
      "ecr:BatchCheckLayerAvailability",
      "ecr:GetDownloadUrlForLayer",
      "ecr:BatchGetImage",
      "ecr:PutImage",
      "ecr:InitiateLayerUpload",
      "ecr:UploadLayerPart",
      "ecr:CompleteLayerUpload"
    ]
    resources = [
      "arn:aws:ecr:${var.aws_region}:*:repository/${var.github_repository}"
    ]
  }
}

resource "aws_iam_policy" "deployment_policy" {
  name        = "ecstaticloud-gha-ecr-deploy-policy"
  description = "Scoped explicit permissions for ECR deployments"
  policy      = data.aws_iam_policy_document.deployment_permissions.json
}

resource "aws_iam_role_policy_attachment" "attach_deployment" {
  role       = aws_iam_role.github_actions_deployer.name
  policy_arn = aws_iam_policy.deployment_policy.arn
}

output "role_arn" {
  value       = aws_iam_role.github_actions_deployer.arn
  description = "ARN of the provisioned IAM Role for GitHub Actions."
}

2. Production GitHub Actions Workflow

This workflow uses official AWS actions to fetch temporary credentials and push container images to Amazon ECR without embedding persistent keys.

# .github/workflows/production-deploy.yml

name: "Production Microservice Deployment"

on:
  push:
    branches:
      - main

# Explicit global permissions required for OIDC authentication
permissions:
  id-token: write # Mandatory to request the JWT token from GitHub OIDC provider
  contents: read  # Minimum permission required to checkout repository code

concurrency:
  group: production-deploy-${{ github.ref }}
  cancel-in-progress: false

jobs:
  build-and-push:
    name: "Build & Push ECR Container Image"
    runs-on: ubuntu-latest
    environment: production # Triggers environment condition matching in AWS Trust Policy

    steps:
      - name: "Checkout Code Repository"
        uses: actions/checkout@v4
        with:
          persist-credentials: false

      - name: "Configure AWS Credentials via OIDC"
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: "arn:aws:iam::123456789012:role/ecstaticloud-gha-production-deployer"
          aws-region: "us-east-1"
          role-duration-seconds: 900 # Request temporary credentials for exactly 15 minutes
          audience: "sts.amazonaws.com"
          output-credentials: true

      - name: "Verify Authenticated Caller Identity"
        run: |
          echo "Verifying STS Identity Attestation..."
          aws sts get-caller-identity

      - name: "Log in to Amazon ECR"
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

      - name: "Build, Tag, and Push OCI Container Image"
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          ECR_REPOSITORY: "production-service"
          IMAGE_TAG: ${{ github.sha }}
        run: |
          echo "Building container image tagged as ${IMAGE_TAG}..."
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
          docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:latest
          
          echo "Pushing layers to Amazon ECR..."
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest

      - name: "Audit Trail Logging"
        if: always()
        run: |
          echo "Pipeline execution completed for run: ${{ github.run_id }}"
          echo "Commit: ${{ github.sha }} executed by Actor: ${{ github.actor }}"

Benchmarks & Comparison Matrix

Evaluating static access key deployments against an optimized OIDC identity provider setup highlights key security and operational metrics:

| Metric / Dimension | Traditional Architecture (Static IAM Keys) | Ecstaticloud Optimized Architecture (OIDC Zero-Trust) | Impact / Performance Gain | | :--- | :--- | :--- | :--- | | Credential Lifetime | Indefinite (Months / Years until manual rotation) | 15 to 60 Minutes (Configurable maximum TTL) | >99.99% Reduction in valid credential exposure window | | Credential Leak Impact | High risk of account takeover and resource misuse | Negligible Risk (Tokens expire before exploitation can occur) | Zero static credential surface area | | Key Rotation Overhead | ~40 Engineering Hours / Year per 50 Microservices | 0 Hours / Year (Automated cryptographic attestation) | 100% Elimination of secret rotation toil | | CloudTrail Traceability | Generic IAM User (Ambiguous run identification) | Detailed Claims Map (sub, repo, commit, actor) | Direct attribution for forensic audits | | Authentication Overhead Latency | 0 ms (Static values injected at run start) | ~140 ms (One-time STS token exchange per job) | Minor runtime addition (+140ms) for total security isolation | | Compliance Readiness (SOC2 / ISO27001) | High Audit Finding Risk (Unrotated high-privilege keys) | Native Zero-Trust Compliance Alignment | Fully meets strict compliance access requirements | | Cross-Account Access Maintenance | Complex IAM User mapping + manual secret duplication | Federated Role Assumption across AWS accounts | Reduced complexity for enterprise multi-account strategies |


Production Pitfalls & Gotchas

While setting up OIDC federated authentication in CI/CD pipelines eliminates long-lived secret risks, edge cases in enterprise production deployments can cause service interruptions or introduce subtle vulnerabilities.

1. Overly Permissive Wildcards in sub Claim Assertions

A dangerous misconfiguration occurs when engineers use overly broad wildcard operators in the IAM Trust Policy condition block:

// DANGEROUS MISCONFIGURATION - DO NOT USE IN PRODUCTION
"Condition": {
  "StringLike": {
    "token.actions.githubusercontent.com:sub": "repo:ecstaticloud/*:*"
  }
}

Failure Mode

The wildcard repo:ecstaticloud/*:* matches any repository in the organization, running on any branch (including unreviewed pull requests from feature branches or untrusted developers). An attacker who can commit to a sandbox repository within the same organization can create a workflow that assumes this target role and extracts sensitive infrastructure state.

Fix

Enforce explicit, narrow subject claim matching:

condition {
  test     = "StringEquals"
  variable = "token.actions.githubusercontent.com:sub"
  values   = ["repo:ecstaticloud/production-service:ref:refs/heads/main"]
}

If multiple branches require deployment capabilities (e.g., release tags or staging branches), construct explicit string lists or constrain wildcards strictly to target patterns like repo:ecstaticloud/production-service:ref:refs/heads/release/*.


2. Missing id-token: write Explicit Permissions

Developers often attempt to migrate workflows by calling aws-actions/configure-aws-credentials without adjusting the workflow's job-level permissions block.

Failure Mode

GitHub defaults job permissions to contents: read (or restrictive defaults set at the organization level). When the runner executes configure-aws-credentials, the local workflow agent cannot fetch the JWT from GitHub's internal token service. The step fails with an opaque error message:

Error: Could not retrieve OIDC token: Request failed with status code 403: "Resource not accessible by integration"

Fix

Explicitly define top-level or job-level permissions inside your workflow specification:

permissions:
  id-token: write # Grants permission to fetch GitHub OIDC JWT token
  contents: read  # Grants permission to checkout code

3. Outdated CA Thumbprint Policies & AWS Automatic Thumbprint Management

Historically, AWS required manual configuration of top-level Certificate Authority (CA) root thumbprints when registering an OpenID Connect Provider (aws_iam_openid_connect_provider). When GitHub changed its intermediate signing certificates (e.g., during routine library or provider rotations), pipelines worldwide failed sts:AssumeRoleWithWebIdentity requests due to thumbprint mismatches.

Failure Mode

AWS STS rejects token attestation attempts during GitHub TLS certificate rotations, outputting:

An error occurred (InvalidIdentityToken) when calling the AssumeRoleWithWebIdentity operation: OpenIDConnect provider's HTTPS certificate CA is not trusted.

Fix

AWS IAM now automatically manages the CA certificate thumbprints for top OIDC providers, including GitHub Actions (token.actions.githubusercontent.com). However, to maintain backward compatibility with infrastructure-as-code libraries:

  1. Always set thumbprint_list in Terraform, but ensure your automation stack regularly updates the hashicorp/aws provider to version 5.x+.
  2. Rely on AWS STS's internal, managed verification logic for GitHub endpoints rather than maintaining manual certificate thumbprints in legacy script setups.

4. Temporal Drift and STS Session Duration Mismatches

AWS IAM Roles enforce a strict max_session_duration parameter (defaulting to 3,600 seconds / 1 hour). If a CI/CD job requests a session lifetime exceeding the target IAM Role configuration, AWS STS rejects the request.

Failure Mode

Setting role-duration-seconds: 7200 (2 hours) in GitHub Actions when the target IAM Role has a max_session_duration of 3600 results in immediate job failure:

An error occurred (ValidationError) when calling the AssumeRoleWithWebIdentity operation: The requested DurationSeconds exceeds the MaxSessionDuration set for this role.

Fix

Align the configuration parameters according to the zero-trust principle of least-duration access:

  1. Set max_session_duration in your Terraform aws_iam_role resource to match the expected upper limit of the pipeline (e.g., 3600).
  2. Set role-duration-seconds in configure-aws-credentials to the shortest possible time window needed for pipeline completion (e.g., 900 seconds / 15 minutes for typical container pushes).

Frequently Asked Questions

How do I migrate existing CI/CD pipelines from static AWS access keys to OIDC without downtime?

Migration should follow a dual-authentication strategy:

  1. Provision the aws_iam_openid_connect_provider and the target IAM Role alongside your existing static IAM User credentials using Terraform.
  2. Update non-critical development and staging workflows to use aws-actions/configure-aws-credentials with OIDC, validating parameter setups in test environments.
  3. Verify CloudTrail logs for proper OIDC role assumption and event attestation (AssumeRoleWithWebIdentity calls).
  4. Update production workflows to use OIDC authentication.
  5. Once validated, remove the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY entries from GitHub Secrets and delete the static IAM Users in AWS IAM.

Can GitHub Actions OIDC assume IAM roles across multiple AWS accounts?

Yes. You can manage multi-account deployment models using two primary patterns:

  • Direct Multi-Account Providers: Provision an aws_iam_openid_connect_provider and corresponding IAM Role in every target AWS account (e.g., Staging, Production, Audit). The workflow authenticates directly to the target account's IAM Role via OIDC.
  • Hub-and-Spoke Assumption: Register the OIDC provider in a central "Identity" or "Deployment" AWS account. The GitHub Actions runner assumes the central role via AssumeRoleWithWebIdentity, then immediately uses those temporary credentials to call standard sts:AssumeRole into downstream target workload accounts.

What happens if GitHub's OIDC certificate thumbprint changes?

AWS IAM automatically updates and trusts the root signing certificates for major identity providers, including GitHub Actions. Even if GitHub rotates its TLS certificates, AWS manages validation in the background.

If using custom infrastructure automation that hardcodes thumbprints, update your configurations to use current thumbprint values. AWS IAM handles verification behind the scenes, ensuring uninterrupted OIDC operations across rotations.


How does OIDC protect against security risks from pull request forks?

When a pull request is submitted from a public fork, GitHub Actions runs the workflow in a restricted context:

  1. Token Access Restrictions: GitHub does not issue id-token: write permissions to workflows triggered by pull_request events from forks by default.
  2. Subject Claim Isolation: The sub claim generated for a fork reflects the fork repository name (e.g., repo:external-user/production-service:pull_request), not your internal repository path (repo:ecstaticloud/production-service:...).
  3. IAM Condition Blocking: AWS IAM checks the sub value against the configured Trust Policy. Because the subject claim doesn't match your repository pattern, AWS STS rejects the AssumeRoleWithWebIdentity attempt, preventing unauthorized code execution from accessing cloud resources.

Need Help Scaling Cloud Infrastructure?

Partner with Ecstaticloud's boutique engineering architects to implement zero-trust architectures, optimize inference workloads, or eliminate cloud waste.

Talk to an Architect
Deep Dives

Related Technical Insights

View all →