Skip to Content
Cloud Engineering Academy
9. DevOps & CI/CD

Lab 9.2: an OIDC deploy role that a fork cannot assume

Evaluate real GitHub OIDC tokens against IAM trust policies offline, prove that a fork, a pull request, another repository and the wrong audience are all refused, lint dangerous policies, then create the provider and three least-privilege roles with Terraform.

intermediate⏱ 1 h 30 min🟢 FreeDOP-C02SCS-C03

Assumes: .NET 10 LTS · Terraform 1.10 or later with AWS provider 6.x · AWS CLI v2 · GitHub Actions (aws-actions/configure-aws-credentials v6.3.0) · Region us-east-1 · labs/m09-delivery-pipeline. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lab you can:

  • Explain what a GitHub OIDC token contains and which claim (sub) the trust policy should pin.
  • Use the lab's trust-eval tool to show, for each hostile token, why the role refuses it.
  • Use trust-lint to catch the two classic mistakes: a wildcarded organisation and a missing sub condition.
  • Create the IAM OIDC provider and three roles (ECR push, deploy to test, deploy to prod) with Terraform, then confirm what AWS created.
  • Describe how the sub format differs for repositories that send immutable owner and repository IDs.

Prerequisites

  • GitHub Actions with OIDC, which explains the token exchange in depth.
  • Environment separation, for why test and prod get different roles.
  • Docker (to run the tools) or the .NET 10 SDK. Terraform 1.10 or later, AWS CLI v2 and aws sso login --profile learn-sandbox for Part B only.

Cost label

Parts A and C are free (everything runs offline). Part B is free of charge too as IAM roles and the OIDC provider have no price, but it touches your sandbox account, and the lab also creates an ECR repository and an S3 evidence bucket (a few cents at most while empty ⚠ VERIFY, destroyed at the end). Label: 🟢 free for the proof, 🟡 credits for the optional deploy.

Scenario

Harbourline's pipeline must deploy to AWS without a stored access key. GitHub issues each workflow run a short-lived signed token that says who is running, and an IAM role can trust that token. The risk is in the details: if the trust policy is loose, any repository in the organisation, or a pull request from a fork, can become your production deployer. You will test the details before you ever touch AWS.

Architecture

In this lab the middle step is done by trust-eval, a small C# evaluator in src/Harbourline.Delivery/Oidc/. It applies the same rule IAM applies to these policies: every condition on a matching Allow statement must hold, otherwise the result is an implicit deny, and an explicit Deny always wins.

The evaluator is a teaching model

trust-eval implements StringEquals and StringLike (with * and ?) on the claims in the sample token. Real IAM supports more operators and evaluates more context. Use it to learn and to guard regressions in CI, and treat the IAM Policy Simulator and a real assumption test as the final word.

The files

FileRole in the lab
policies/trust-ecr-push.jsonAllows only the main branch to assume the ECR push role
policies/trust-deploy-test.json and trust-deploy-prod.jsonAllow only environment:test / environment:prod of one repository
policies/trust-deploy-prod-immutable.jsonThe same, written for the immutable owner@id/repo@id subject format
policies/trust-bad-wildcard.json, trust-bad-no-sub.jsonDeliberately wrong policies to lint (labelled "DoNotCopyThis")
policies/claims/*.jsonEight sample tokens: good and hostile
tests/Harbourline.Delivery.Tests/TrustPolicyTests.csThe same checks as xUnit tests, so loosening a policy fails CI
infra/terraform/oidc.tfProvider, roles and permissions for real

Part A: prove it offline

All commands run from the lab root. If you have no SDK on the host, wrap each one as shown at the end of this part.

Read a real claim set

cat policies/claims/prod-deploy.json
{
  "sub": "repo:harbourline-learn/accounts-api:environment:prod",
  "aud": "sts.amazonaws.com",
  "repository": "harbourline-learn/accounts-api",
  "ref": "refs/heads/main",
  "event_name": "push",
  "environment": "prod"
}

The sub (subject) says which repository and which context ran the job. A job that references a GitHub environment gets environment:<name>; a plain push job gets ref:refs/heads/<branch>; a pull-request job without an environment gets pull_request. The aud (audience) says who the token was minted for: AWS expects sts.amazonaws.com.

The legitimate deploy is allowed

dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/prod-deploy.json
sub: repo:harbourline-learn/accounts-api:environment:prod
  - GitHubProdEnvironmentDeploys: Allow matched.
Decision: Allowed

Exit code 0. The prod role trusts exactly that string with StringEquals, plus aud equal to sts.amazonaws.com.

The fork is refused

An attacker forks the repository into mallory-example and creates a prod environment there, so their token also says environment:prod.

dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/fork-prod-environment.json
sub: repo:mallory-example/accounts-api:environment:prod
  - GitHubProdEnvironmentDeploys: conditions not met — StringEquals token.actions.githubusercontent.com:sub expected [repo:harbourline-learn/accounts-api:environment:prod] but token has 'repo:mallory-example/accounts-api:environment:prod'
Decision: ImplicitDeny

Exit code 1. The owner and repository are part of the subject, so a fork has a different one. Note that the attacker controls their own environment names, which is why you must pin the repository as well as the environment.

Pull requests, wrong audience and other repositories

for c in pull-request wrong-audience other-repo-prod test-deploy main-push; do
  echo "== $c"
  dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/$c.json | tail -2
done
TokenWhy the prod role refuses it
pull-request.jsonsub is ...:pull_request, not the environment
wrong-audience.jsonaud is https://github.com/harbourline-learn, not sts.amazonaws.com (a token minted for another service)
other-repo-prod.jsonA sibling repository payments-service in the same organisation
test-deploy.jsonThe test environment cannot reach the prod role
main-push.jsonA push to main without the environment, so no approval happened

Every one ends in ImplicitDeny. The TrustPolicyTests class runs these same twelve combinations as a data-driven test.

See the bug a loose policy causes

dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-bad-wildcard.json policies/claims/other-repo-prod.json
sub: repo:harbourline-learn/payments-service:environment:prod
  - DoNotCopyThisWildcardsTheOrg: Allow matched.
Decision: Allowed

repo:harbourline-learn/* lets any repository in the organisation assume the role. Teams write it for convenience: "all our repos deploy the same way". Within an organisation, a junior contractor's experimental repository could then deploy to the production account.

Lint the two bad policies and the three good ones

dotnet run --project src/Harbourline.Delivery -- trust-lint policies/trust-bad-wildcard.json
dotnet run --project src/Harbourline.Delivery -- trust-lint policies/trust-bad-no-sub.json
dotnet run --project src/Harbourline.Delivery -- trust-lint policies/trust-deploy-prod.json
Warning HL002 DoNotCopyThisWildcardsTheOrg: add StringEquals 'token.actions.githubusercontent.com:aud' = 'sts.amazonaws.com' so tokens minted for other audiences are rejected.
Error   HL003 DoNotCopyThisWildcardsTheOrg: subject 'repo:harbourline-learn/*' wildcards the owner or repository. Other repositories (including forks you do not control) could match.
2 finding(s).

Error   HL001 DoNotCopyThisAnyRepositoryOnGitHub: no condition on 'token.actions.githubusercontent.com:sub'. Any repository on GitHub could assume this role.
1 finding(s).

No findings.

The first two exit with code 1 (errors); the last exits 0. That is how ci.yml uses it in its iam-policy-lint job: every trust policy the roles use is linted on each pull request.

RuleSeverityMeaning
HL001ErrorNo sub condition at all
HL002WarningNo aud equals sts.amazonaws.com condition
HL003ErrorWildcard in the owner or repository part of the subject
HL004WarningStringLike wildcard allows every branch, tag, pull request and environment
HL005Warningpull_request subject: unreviewed code could assume the role
HL006InfoStringLike used without a wildcard; use StringEquals

Run it all as tests

docker run --rm -v "${PWD}:/src" -w /src mcr.microsoft.com/dotnet/sdk:10.0 dotnet test --solution DeliveryPipeline.slnx

Expected: 74 passed, 1 skipped. If someone edits trust-deploy-prod.json to be looser, the "fork cannot assume" test fails and the pull request is blocked.

To run the CLI commands with Docker only, prefix them like this:

docker run --rm -v "${PWD}:/src" -w /src mcr.microsoft.com/dotnet/sdk:10.0 \
  dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod.json policies/claims/prod-deploy.json

Immutable subjects: the "it worked yesterday" outage

GitHub documents an immutable subject format that includes numeric owner and repository IDs, for example repo:harbourline-learn@81234567/accounts-api@912345678:environment:prod. Repositories created after 2026-07-15 use it, and so do repositories that opt in; renames and transfers after that date switch format too. A trust policy written for one format silently denies the other.

dotnet run --project src/Harbourline.Delivery -- trust-eval policies/trust-deploy-prod-immutable.json policies/claims/prod-deploy.json
sub: repo:harbourline-learn/accounts-api:environment:prod
  - GitHubProdEnvironmentDeploysImmutableIds: conditions not met — StringEquals token.actions.githubusercontent.com:sub expected [repo:harbourline-learn@81234567/accounts-api@912345678:environment:prod] but token has 'repo:harbourline-learn/accounts-api:environment:prod'
Decision: ImplicitDeny

Why it matters beyond the outage: names can be recycled. If an organisation is renamed and an attacker registers the old name, a name-based subject could match the attacker's repository, while an ID-based subject cannot. ⚠ VERIFY the exact rollout rules for your account and GitHub Enterprise in GitHub's OIDC reference before changing production trust policies. The Terraform variable github_subject_prefix lets you supply the immutable prefix.

Part B: create the real provider and roles (optional)

⚠ Learning shortcut — not for production

The lab creates all three roles in one sandbox account, and the test and prod roles have the same permissions. A bank puts each environment in a separate AWS account with its own provider and role, and an SCP that only the pipeline can change workloads. The state bucket is also yours. See Environment separation.

Configure

cd infra/terraform
cp backend.hcl.example backend.hcl            # set your state bucket (hl-tfstate-<account-id>-us-east-1)
cp terraform.tfvars.example terraform.tfvars  # owner, github_owner, github_repo
aws sso login --profile learn-sandbox

If the account already has the GitHub OIDC provider, set create_oidc_provider = false: an account can hold only one provider per URL.

Plan and read it before applying

terraform init -backend-config=backend.hcl
terraform plan -out tf.plan

Read the plan. You should see one aws_iam_openid_connect_provider, three aws_iam_role resources (hl-m09-gh-ecr-push, hl-m09-gh-deploy-test, hl-m09-gh-deploy-prod), their inline policies, an ECR repository with an immutable-tag setting and a lifecycle policy, and an S3 evidence bucket with Object Lock. The provider has no thumbprint: IAM validates GitHub's TLS certificate with its own library of trusted CAs.

Apply and read the outputs

terraform apply tf.plan
terraform output

The outputs ecr_push_role_arn, deploy_role_arns and evidence_bucket are the values the project page puts into GitHub variables. Role ARNs are identifiers, not secrets.

Inspect what AWS actually trusts

aws iam get-role --role-name hl-m09-gh-deploy-prod --profile learn-sandbox \
  --query 'Role.AssumeRolePolicyDocument' --output json
aws iam list-role-policies --role-name hl-m09-gh-deploy-prod --profile learn-sandbox

Compare the returned document with policies/trust-deploy-prod.json: the sub must be repo:<owner>/<repo>:environment:prod for your values. Paste it into trust-lint. This round trip, declared policy, deployed policy, tested policy, is a habit worth keeping.

Try it from GitHub (optional)

In your own repository add a workflow that requests a token and assumes the test role:

name: oidc-smoke
on: workflow_dispatch
permissions:
  contents: read
  id-token: write
jobs:
  whoami:
    runs-on: ubuntu-latest
    environment: test
    steps:
      - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: us-east-1
      - run: aws sts get-caller-identity

Create a GitHub environment named test with a variable AWS_DEPLOY_ROLE_ARN set to the test role ARN. The output shows an assumed-role ARN with a session name, and no access key was stored anywhere. If you rename the environment to staging, the same workflow fails with Not authorized to perform sts:AssumeRoleWithWebIdentity, which proves the trust policy is doing its job.

Security considerations

  • id-token: write grants nothing by itself. It lets the job request a token. Only a role whose trust policy matches the token grants access.
  • Pin the sub with StringEquals. Use StringLike only for a deliberate, narrow pattern such as repo:o/r:ref:refs/heads/release/*, and never wildcard the owner or repository.
  • Permissions are separate from trust. The deploy role allows ecs:UpdateService on one service, iam:PassRole only for the two task roles and only to ecs-tasks.amazonaws.com, and (prod only) s3:PutObject under releases/*. It cannot create IAM users, read secrets or touch other services.
  • Sessions are short. max_session_duration is 3600 seconds. A leaked session expires on its own.
  • Audit. Every AssumeRoleWithWebIdentity call is logged in CloudTrail with the role and session name. The workflow sets role-session-name: gh-<run id>-<job>, so you can match an AWS event to a GitHub run ⚠ VERIFY which CloudTrail field carries the web-identity subject in your Region.

Common mistakes

  • Trusting repo:org/* "because it's all our repos".
  • Using the pull_request subject for a role that can change anything.
  • Forgetting the aud condition, then accepting tokens minted for other purposes.
  • Granting iam:PassRole on *, which lets a pipeline attach any role to a task and escalate.
  • Creating a second OIDC provider for the same URL and getting EntityAlreadyExists.

Troubleshooting

SymptomLikely causeFix
Not authorized to perform sts:AssumeRoleWithWebIdentitysub in the token differs from the policy: environment, branch, case, or immutable formatPrint the token claims, compare to policies/, run trust-eval
Could not load credentials from any providersJob lacks permissions: id-token: writeAdd it to the job
EntityAlreadyExists creating the providerThe account already has oneSet create_oidc_provider = false
Role assumes fine but AccessDenied on ECSTrust works; the permissions policy is missing an action or resourceRead the CloudTrail error, fix the permissions policy, not the trust
terraform destroy fails on the evidence bucketObject Lock retention still activeWait a day, or delete versions with --bypass-governance-retention (needs s3:BypassGovernanceRetention)
trust-eval says Allowed for a token you expected to be refusedThe policy has a StringLike wildcardRun trust-lint; tighten to StringEquals

Cost and cleanup

Part A costs nothing. Part B creates IAM resources (free), an ECR repository (free while empty) and an S3 bucket with a few bytes ⚠ VERIFY; keep them for the project page or remove them now.

cd infra/terraform
terraform destroy

# Confirm nothing remains
aws iam list-roles --query "Roles[?starts_with(RoleName, 'hl-m09-')].RoleName" --profile learn-sandbox
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m09-delivery-pipeline \
  --profile learn-sandbox --region us-east-1

If you set create_oidc_provider = false, Terraform leaves the shared provider alone. If the project page's ECS resources are not deployed, the ECS part of the role policy refers to resources that do not exist yet, which is harmless.

Exercises

  • 🟢 Guided: run trust-eval for all eight claims against trust-deploy-test.json and write a table of results. Predict each result before running it.
  • 🟡 Challenge: write trust-deploy-release.json that allows only branches matching release/* of the one repository, using StringLike. Add one allowed and two denied claim files and a test in TrustPolicyTests.cs. Make sure trust-lint reports HL004 only if you make the pattern broader than you meant.
  • 🔴 Live problem: after a GitHub organisation rename, every deploy fails with "Not authorized to perform sts:AssumeRoleWithWebIdentity" at 16:40 on a Friday, and a hotfix is waiting. Lay out your diagnosis steps, the safest fix, and what you would change so a rename cannot cause this again. Do not "temporarily" use a wildcard.

Assignment

In your portfolio repository add policies/ with your own trust policy, three hostile claim files, and a test class that proves each is refused. Include a short README paragraph explaining the immutable subject format.

Solutions

Knowledge check

Interview questions

  • How does GitHub Actions authenticate to AWS without keys? The job requests an OIDC token from GitHub, presents it to STS with AssumeRoleWithWebIdentity, and STS returns short-lived credentials if the token's signature, audience and subject satisfy the role's trust policy.
  • What would you put in the trust policy of a production deploy role? aud equals sts.amazonaws.com with StringEquals, and sub equal to one repository and one environment (or protected branch) with StringEquals; no wildcards in owner or repo.
  • How do you stop trust policies being loosened by accident? Lint them and test known-bad tokens in CI, require code-owner review on the policy files, and detect drift between Terraform and the deployed role.

Certification practice

Completion checklist

  • I can explain sub and aud in two sentences
  • I proved the fork, pull-request, other-repo and wrong-audience tokens are refused
  • I linted a wildcard policy and fixed it
  • I can describe the immutable subject format and the outage it can cause
  • I destroyed the Terraform resources or recorded why I kept them for the project

Key takeaways

  • The subject is the access control. Pin repository and environment with StringEquals.
  • Test trust policies like code: sample tokens, hostile cases, CI lint.
  • Trust (who may assume) and permissions (what they can do) are two separate policies; keep both narrow.
  • Short-lived sessions and CloudTrail make a leaked token a small, traceable problem.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page