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.
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-evaltool to show, for each hostile token, why the role refuses it. - Use
trust-lintto catch the two classic mistakes: a wildcarded organisation and a missingsubcondition. - 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
subformat 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
testandprodget 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-sandboxfor 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
| File | Role in the lab |
|---|---|
policies/trust-ecr-push.json | Allows only the main branch to assume the ECR push role |
policies/trust-deploy-test.json and trust-deploy-prod.json | Allow only environment:test / environment:prod of one repository |
policies/trust-deploy-prod-immutable.json | The same, written for the immutable owner@id/repo@id subject format |
policies/trust-bad-wildcard.json, trust-bad-no-sub.json | Deliberately wrong policies to lint (labelled "DoNotCopyThis") |
policies/claims/*.json | Eight sample tokens: good and hostile |
tests/Harbourline.Delivery.Tests/TrustPolicyTests.cs | The same checks as xUnit tests, so loosening a policy fails CI |
infra/terraform/oidc.tf | Provider, 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.jsonsub: repo:harbourline-learn/accounts-api:environment:prod
- GitHubProdEnvironmentDeploys: Allow matched.
Decision: AllowedExit 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.jsonsub: 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: ImplicitDenyExit 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| Token | Why the prod role refuses it |
|---|---|
pull-request.json | sub is ...:pull_request, not the environment |
wrong-audience.json | aud is https://github.com/harbourline-learn, not sts.amazonaws.com (a token minted for another service) |
other-repo-prod.json | A sibling repository payments-service in the same organisation |
test-deploy.json | The test environment cannot reach the prod role |
main-push.json | A 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.jsonsub: repo:harbourline-learn/payments-service:environment:prod
- DoNotCopyThisWildcardsTheOrg: Allow matched.
Decision: Allowedrepo: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.jsonWarning 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.
| Rule | Severity | Meaning |
|---|---|---|
| HL001 | Error | No sub condition at all |
| HL002 | Warning | No aud equals sts.amazonaws.com condition |
| HL003 | Error | Wildcard in the owner or repository part of the subject |
| HL004 | Warning | StringLike wildcard allows every branch, tag, pull request and environment |
| HL005 | Warning | pull_request subject: unreviewed code could assume the role |
| HL006 | Info | StringLike 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.slnxExpected: 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.jsonImmutable 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.jsonsub: 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: ImplicitDenyWhy 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-sandboxIf 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.planRead 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 outputThe 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-sandboxCompare 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-identityCreate 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: writegrants nothing by itself. It lets the job request a token. Only a role whose trust policy matches the token grants access.- Pin the
subwithStringEquals. UseStringLikeonly for a deliberate, narrow pattern such asrepo:o/r:ref:refs/heads/release/*, and never wildcard the owner or repository. - Permissions are separate from trust. The deploy role allows
ecs:UpdateServiceon one service,iam:PassRoleonly for the two task roles and only toecs-tasks.amazonaws.com, and (prod only)s3:PutObjectunderreleases/*. It cannot create IAM users, read secrets or touch other services. - Sessions are short.
max_session_durationis 3600 seconds. A leaked session expires on its own. - Audit. Every
AssumeRoleWithWebIdentitycall is logged in CloudTrail with the role and session name. The workflow setsrole-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_requestsubject for a role that can change anything. - Forgetting the
audcondition, then accepting tokens minted for other purposes. - Granting
iam:PassRoleon*, 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
| Symptom | Likely cause | Fix |
|---|---|---|
Not authorized to perform sts:AssumeRoleWithWebIdentity | sub in the token differs from the policy: environment, branch, case, or immutable format | Print the token claims, compare to policies/, run trust-eval |
Could not load credentials from any providers | Job lacks permissions: id-token: write | Add it to the job |
EntityAlreadyExists creating the provider | The account already has one | Set create_oidc_provider = false |
Role assumes fine but AccessDenied on ECS | Trust works; the permissions policy is missing an action or resource | Read the CloudTrail error, fix the permissions policy, not the trust |
terraform destroy fails on the evidence bucket | Object Lock retention still active | Wait a day, or delete versions with --bypass-governance-retention (needs s3:BypassGovernanceRetention) |
trust-eval says Allowed for a token you expected to be refused | The policy has a StringLike wildcard | Run 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-1If 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-evalfor all eight claims againsttrust-deploy-test.jsonand write a table of results. Predict each result before running it. - 🟡 Challenge: write
trust-deploy-release.jsonthat allows only branches matchingrelease/*of the one repository, usingStringLike. Add one allowed and two denied claim files and a test inTrustPolicyTests.cs. Make suretrust-lintreports 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
Against the test role: test-deploy.json is Allowed; prod-deploy.json, fork-prod-environment.json, other-repo-prod.json, pull-request.json, main-push.json, wrong-audience.json and feature-branch.json are all ImplicitDeny. The test role trusts one sub (the test environment) and the audience; every other token fails the sub or aud condition. This is the pattern TrustPolicyTests encodes.
Use a policy with StringEquals on aud and StringLike on sub equal to repo:harbourline-learn/accounts-api:ref:refs/heads/release/*. Tokens for ref:refs/heads/release/2026.11 are allowed; ref:refs/heads/main and a fork's release/2026.11 are not. The linter reports HL004 only when the wildcard covers more than the context part, for example repo:harbourline-learn/accounts-api:*. Pair the wildcard with a branch protection or ruleset on release/*, otherwise anyone who can create such a branch can deploy.
- Capture the failing run's token
sub(a debug step printing the decoded claims, never the raw token) and compare it with the role's trust policy. - The organisation name changed, so the
subprefix changed. Update the trust policy with the new name in Terraform, plan, review and apply. If a change board is required, raise an emergency change; do not paste a wildcard. - Longer term, move to immutable ID-based subjects and add the CI lint and a scheduled assumption test so a mismatch is found before a hotfix.
Knowledge check
Answer: sub, because it contains the owner and repository. aud only says the token was meant for AWS, and the environment or ref alone can be recreated in a fork.
Answer: The policy has only an Allow statement whose condition does not match. With no matching Allow and no Deny, IAM's default is an implicit deny. An explicit deny comes from a Deny statement and cannot be overridden by any Allow.
Answer: For GitHub's issuer, AWS verifies the certificate chain with its own trusted CAs, so the lab's Terraform omits a thumbprint ⚠ VERIFY if you use a different identity provider, where a thumbprint may still be needed.
Answer: Anyone who can run a job in the test environment obtains prod permissions. Test and prod need separate roles (ideally separate accounts) keyed to separate environments, with approvals only on prod.
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?
audequalssts.amazonaws.comwithStringEquals, andsubequal to one repository and one environment (or protected branch) withStringEquals; 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
A pipeline deploys with a long-lived IAM user key stored as a CI secret. Security wants no stored cloud credentials. What is the best change? A. Rotate the key monthly. B. Encrypt the secret with KMS. C. Configure an IAM OIDC identity provider and a role whose trust policy restricts the token subject. D. Move the key to Parameter Store. Answer: C. It removes the long-lived key entirely. A and B still leave a key; D just moves the secret. The restriction on the token subject keeps other repositories out.
A web-identity role trusts the GitHub OIDC provider with a condition StringLike on sub of repo:acme/*. What is the problem? A. StringLike is not supported. B. Every repository in the organisation can assume the role. C. Only forks can assume it. D. The role cannot be assumed at all.
Answer: B. The wildcard matches all repositories under acme. Use StringEquals with the exact repository and environment or branch.
Completion checklist
- I can explain
subandaudin 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.
Environment separation: one AWS account per environment
Separate dev, test, staging and prod into their own AWS accounts under AWS Organizations, deploy into each with its own OIDC role from GitHub Actions, promote the same image digest from one environment to the next, and add guardrails so a pipeline can never deploy to the wrong account.
Secrets in CI/CD: keep them out of pipelines, logs and images
Classify every secret a delivery pipeline touches, remove the ones OIDC makes unnecessary, keep runtime secrets out of the pipeline entirely, and handle the rest with GitHub environment secrets, AWS Secrets Manager, CodeBuild and BuildKit secret mounts so they never appear in logs or image layers.