Skip to main content
Back to Blog
Automation TutorialsCI and Test Infrastructure ยท Part 7

Secure CI with OIDC: Exact Trust Conditions and Job-Scoped Tokens

A trust policy of repo:acme/shop:* lets any branch or pull request in the repository assume the role. Sign GitHub-shaped tokens against a local JWKS to see which subjects each condition admits, why an environment subject still needs a branch rule, and how to keep id-token: write and fork code apart.

Shashank Rawlani

Engineering Leader | Builder | Problem Solver | AI Engineer

Published Nov 19, 202621 min read
View AI-ready Markdown
Four horizontal lanes enter from the left, each carrying a three-segment token card. A dashed rectangular boundary in the middle holds a tall gate with one narrow slot. The green middle lane passes through the slot to a ringed node and flows into a panel of stacked layer bars on the right. Two grey lanes stop short at the boundary, an orange bottom lane ends at a crossed-out circle before the gate, and a dashed orange arc loops from the top lane over the gate toward the stacked panel.
Quick answer: Grant id-token: write only to the job that deploys, and start every workflow from permissions: {}. Trust that job by an exact subject such as repo:acme/shop:environment:release, never repo:acme/shop:*, and give the release environment a deployment-branch rule and reviewers, because the subject names the environment, not the branch. Keep pull_request_target away from fork code. Prove each condition by verifying tokens you sign against a local JWKS before you touch a real role.

Consider a registry-push role that trusts repo:acme/shop:*, and a release workflow that grants id-token: write at the top level, so that every job in it can request an OIDC token, including the test job that runs npm ci on any branch matching feature/**. One compromised dependency's install script is enough: it calls the token endpoint, exchanges the token for registry credentials and pushes an image tagged latest. No secret leaks, and the cloud does exactly what the trust policy says: any workflow in that repository, on any ref, may become the pusher.

OIDC removes the stored key that can be copied out of a log. It moves the question of who may assume the role into a trust condition that is usually written once and never tested. This part writes those conditions so they fail closed and checks them with tokens you mint yourself. Part 4 covered cache poisoning and the cache-mode key, so the cache is only referenced here.

Versions checked on 2026-11-09: actions/checkout v7.0.1 (released 2026-07-20) and aws-actions/configure-aws-credentials v6.3.0 (released 2026-09-15) are the latest releases. GitHub Actions is the platform throughout; the trust-condition syntax is shown for AWS IAM, Google Cloud Workload Identity Federation and Microsoft Entra. The labs ran on Node.js 26.12.1 and Python 3 with PyYAML 6.0.3, entirely on 127.0.0.1, and never contact GitHub or a cloud provider. The examples pin actions by major tag for readability; GitHub's secure-use reference recommends a full commit SHA or a workflow dependency lockfile.

What the cloud role is actually comparing

When a job has id-token: write, the runner exposes ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN, and any step can use them to request a JWT signed by https://token.actions.githubusercontent.com. The cloud fetches the issuer's JWKS, checks the RS256 signature, then compares claims against the role's conditions. The claims are where your policy lives.

The default sub is built from the job's context, and the shape changes with the trigger:

  • A job that references an environment gets repo:ORG/REPO:environment:NAME. The branch is not in the subject at all.
  • Without an environment, a pull_request run gets repo:ORG/REPO:pull_request, with no branch or PR number.
  • Otherwise the subject carries the ref: repo:ORG/REPO:ref:refs/heads/main or ...:ref:refs/tags/v1.4.0.
  • Any colon inside a value is encoded, so an environment named Production:V1 appears as Production%3AV1.

One change in 2026 breaks exact-match policies without warning. Repositories created after July 15, 2026, and repositories renamed or transferred after that date, receive an immutable subject that embeds numeric IDs: repo:octo-org@123456/octo-repo@456789:ref:refs/heads/main. Older repositories keep the name-only format unless an admin opts in, and GitHub Enterprise Server is not included. The reason is namespace recycling: a deleted organization's name can be registered by someone else. Google's federation guide makes the same point and recommends the numeric repository_id and repository_owner_id over names.

The default aud is the owner's URL, but login actions set their own. configure-aws-credentials requests sts.amazonaws.com; azure/login defaults to api://AzureADTokenExchange. What each cloud can test also differs. AWS STS turns only standard claims such as aud and sub into condition keys, and GitHub's AWS guide states that custom claims are unavailable there. Google evaluates a CEL expression over any claim you map. Entra matches the subject exactly and does not support patterns for branches or tags.

Sign GitHub-shaped tokens against a local JWKS

You can test a trust condition without a cloud account by playing both sides. The script below serves a discovery document and a JWKS on 127.0.0.1, mints tokens with the claims GitHub would issue in nine situations, and verifies each the way an STS does: signature, iss, aud, exp and nbf first, then the role's conditions. The like() helper reproduces IAM's StringLike, where * matches any run of characters, colons and slashes included.

// Local OIDC trust lab. No network access beyond 127.0.0.1.
// 1. Starts a fake issuer that serves a discovery document and a JWKS.
// 2. Mints RS256 tokens shaped like GitHub Actions OIDC tokens.
// 3. Verifies each token the way a cloud STS does: fetch JWKS, check the
//    signature, iss, aud, exp/nbf, then evaluate trust-policy conditions.
import { createServer } from "node:http";
import { generateKeyPairSync, createSign, createVerify, createPublicKey } from "node:crypto";

const b64url = (buf) => Buffer.from(buf).toString("base64url");

const issuerKey = generateKeyPairSync("rsa", { modulusLength: 2048 });
const attackerKey = generateKeyPairSync("rsa", { modulusLength: 2048 });
const KID = "lab-key-1";

const jwk = { ...issuerKey.publicKey.export({ format: "jwk" }), kid: KID, alg: "RS256", use: "sig" };

const server = createServer((req, res) => {
  res.setHeader("content-type", "application/json");
  if (req.url === "/.well-known/openid-configuration") {
    res.end(JSON.stringify({ issuer: ISSUER, jwks_uri: `${ISSUER}/.well-known/jwks`, id_token_signing_alg_values_supported: ["RS256"] }));
  } else if (req.url === "/.well-known/jwks") {
    res.end(JSON.stringify({ keys: [jwk] }));
  } else {
    res.statusCode = 404;
    res.end("{}");
  }
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const ISSUER = `http://127.0.0.1:${server.address().port}`;

function mint(claims, { key = issuerKey.privateKey, kid = KID, ttl = 300, iatOffset = 0 } = {}) {
  const now = Math.floor(Date.now() / 1000) + iatOffset;
  const header = { typ: "JWT", alg: "RS256", kid };
  const payload = { iss: ISSUER, aud: "sts.amazonaws.com", iat: now, nbf: now, exp: now + ttl, jti: crypto.randomUUID(), ...claims };
  const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
  const sig = createSign("RSA-SHA256").update(input).sign(key);
  return `${input}.${b64url(sig)}`;
}

// What a relying party does with nothing but the issuer URL it was configured with.
async function verify(token, expectedIssuer, expectedAud) {
  const [h, p, s] = token.split(".");
  const header = JSON.parse(Buffer.from(h, "base64url"));
  const claims = JSON.parse(Buffer.from(p, "base64url"));
  const disco = await (await fetch(`${expectedIssuer}/.well-known/openid-configuration`)).json();
  const { keys } = await (await fetch(disco.jwks_uri)).json();
  const key = keys.find((k) => k.kid === header.kid);
  if (!key) return { ok: false, why: `no JWKS key for kid ${header.kid}`, claims };
  if (header.alg !== "RS256") return { ok: false, why: `alg ${header.alg} not allowed`, claims };
  const good = createVerify("RSA-SHA256").update(`${h}.${p}`).verify(createPublicKey({ key, format: "jwk" }), Buffer.from(s, "base64url"));
  if (!good) return { ok: false, why: "signature does not match JWKS key", claims };
  const now = Math.floor(Date.now() / 1000);
  if (claims.iss !== expectedIssuer) return { ok: false, why: `iss ${claims.iss}`, claims };
  if (claims.aud !== expectedAud) return { ok: false, why: `aud ${claims.aud}`, claims };
  if (claims.exp <= now) return { ok: false, why: `expired ${now - claims.exp}s ago`, claims };
  if (claims.nbf > now) return { ok: false, why: "not yet valid", claims };
  return { ok: true, claims };
}

// IAM StringLike: * matches any run of characters (including ':' and '/'), ? matches one.
const like = (pattern, value) =>
  new RegExp("^" + pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$").test(value);

const policies = {
  "wide   StringLike repo:acme/shop:*": (c) => like("repo:acme/shop:*", c.sub),
  "typo   StringLike repo:acme/shop*": (c) => like("repo:acme/shop*", c.sub),
  "narrow StringEquals ...:environment:release": (c) => c.sub === "repo:acme/shop:environment:release",
  // Google-style attribute condition: numeric IDs plus the ref, not the sub string.
  "ids    owner_id+repo_id+environment+ref": (c) =>
    c.repository_owner_id === "1001" && c.repository_id === "2002" && c.environment === "release" && c.ref === "refs/heads/main",
};

const base = { repository: "acme/shop", repository_owner: "acme", repository_id: "2002", repository_owner_id: "1001", runner_environment: "github-hosted" };
const cases = [
  ["release job, main, env release", mint({ ...base, sub: "repo:acme/shop:environment:release", environment: "release", ref: "refs/heads/main", event_name: "push" })],
  ["feature push, no env", mint({ ...base, sub: "repo:acme/shop:ref:refs/heads/feature/login", ref: "refs/heads/feature/login", event_name: "push" })],
  ["same-repo pull_request", mint({ ...base, sub: "repo:acme/shop:pull_request", ref: "refs/pull/41/merge", event_name: "pull_request" })],
  ["feature branch, env release", mint({ ...base, sub: "repo:acme/shop:environment:release", environment: "release", ref: "refs/heads/feature/login", event_name: "push" })],
  ["other repo acme/shop-sandbox", mint({ ...base, repository: "acme/shop-sandbox", repository_id: "3003", sub: "repo:acme/shop-sandbox:ref:refs/heads/main", ref: "refs/heads/main", event_name: "push" })],
  ["immutable sub, env release", mint({ ...base, sub: "repo:acme@1001/shop@2002:environment:release", environment: "release", ref: "refs/heads/main", event_name: "push" })],
  ["Azure-style audience", mint({ ...base, aud: "api://AzureADTokenExchange", sub: "repo:acme/shop:environment:release", environment: "release", ref: "refs/heads/main" })],
  ["signed by another key", mint({ ...base, sub: "repo:acme/shop:environment:release", environment: "release", ref: "refs/heads/main" }, { key: attackerKey.privateKey })],
  ["replayed after expiry", mint({ ...base, sub: "repo:acme/shop:environment:release", environment: "release", ref: "refs/heads/main" }, { iatOffset: -600 })],
];

console.log(`issuer ${ISSUER}  jwks keys: 1 (kid ${KID})\n`);
const names = Object.keys(policies);
console.log(["token".padEnd(32), "verify", ...names.map((n) => n.split(" ")[0].padEnd(6))].join(" | "));
for (const [label, token] of cases) {
  const r = await verify(token, ISSUER, "sts.amazonaws.com");
  const cols = names.map((n) => (r.ok ? (policies[n](r.claims) ? "ALLOW" : "deny") : "-").padEnd(6));
  console.log([label.padEnd(32), (r.ok ? "ok" : "FAIL").padEnd(6), ...cols].join(" | ") + (r.ok ? `   sub=${r.claims.sub}` : `   ${r.why}`));
}
server.close();

Running node lab.mjs printed:

issuer http://127.0.0.1:55848  jwks keys: 1 (kid lab-key-1)

token                            | verify | wide   | typo   | narrow | ids   
release job, main, env release   | ok     | ALLOW  | ALLOW  | ALLOW  | ALLOW    sub=repo:acme/shop:environment:release
feature push, no env             | ok     | ALLOW  | ALLOW  | deny   | deny     sub=repo:acme/shop:ref:refs/heads/feature/login
same-repo pull_request           | ok     | ALLOW  | ALLOW  | deny   | deny     sub=repo:acme/shop:pull_request
feature branch, env release      | ok     | ALLOW  | ALLOW  | ALLOW  | deny     sub=repo:acme/shop:environment:release
other repo acme/shop-sandbox     | ok     | deny   | ALLOW  | deny   | deny     sub=repo:acme/shop-sandbox:ref:refs/heads/main
immutable sub, env release       | ok     | deny   | deny   | deny   | ALLOW    sub=repo:acme@1001/shop@2002:environment:release
Azure-style audience             | FAIL   | -      | -      | -      | -        aud api://AzureADTokenExchange
signed by another key            | FAIL   | -      | -      | -      | -        signature does not match JWKS key
replayed after expiry            | FAIL   | -      | -      | -      | -        expired 300s ago

Four findings from one table

The wide column is the policy from the opening. It allows the feature-branch push and the same-repository pull request, which is everything a contributor with write access can trigger, and it is the AWS documentation's own example for "any branch within the repository". IAM refuses a GitHub trust policy whose sub condition is missing or is only a wildcard, but repo:acme/shop:* passes that check.

The typo column drops one colon. repo:acme/shop* now matches acme/shop-sandbox, a different repository. A missing separator is easy to miss in review and obvious in this table.

The narrow column is an exact environment subject, and it still allows row four: a feature branch whose job references environment: release. The token says ref: refs/heads/feature/login, but AWS cannot see that claim, and the subject does not contain it. Whether that row is reachable is decided entirely by the environment's settings in GitHub, which is the subject of the next section.

The ids column shows what a provider that reads arbitrary claims can do: require the numeric owner and repository IDs, the environment and the ref together. It denies the feature branch and is unaffected by the switch to immutable subjects, which every subject-string policy denied. On a real role that row is an outage after a repository transfer, not a breach.

The last three rows fail before any condition runs. A token signed by another key with the same kid is rejected on signature, an Azure-audience token is rejected on aud, and an expired token is rejected on exp. Keep them as negative controls: if one ever reads ok, the verifier is broken and every ALLOW above it means nothing.

Make the environment hold the branch rule

An environment subject is only as strong as the environment's deployment protection rules, so configure release before you reference it in a trust policy:

  • Deployment branches and tags: choose "Selected branches and tags" and add main. The pattern is matched against GITHUB_REF. The "Protected branches only" option has a trap: if no branch in the repository has a protection rule, every branch can deploy.
  • Required reviewers: up to six users or teams, one approval needed, with an option to stop the person who triggered the run from approving it.
  • Administrator bypass: allowed by default. Disallow it for an environment whose token can publish.

The rules gate the token as well as the deployment record. GitHub documents that every deployment protection rule must pass before a job that references the environment is sent to a runner, so an unapproved job has no steps executing and nothing that could call the token endpoint. Environment secrets follow the same rule: they are unavailable until a reviewer approves.

Check your plan first. On GitHub Free, Pro and Team, required reviewers apply only to public repositories, and a private repository on Free has no deployment branch rules, so an environment subject there gives no branch guarantee. In that case, trust the release branch's ref subject, repo:acme/shop:ref:refs/heads/main, and control who can push to that branch.

Give each job only the token it needs

The permissions key has one rule that surprises people: once you list any permission, every permission you did not list becomes none. A job that declares only id-token: write therefore also has contents: none, and its token can no longer read a private repository's code. The fix is to list contents: read explicitly, not to fall back to write-all. id-token: write itself grants nothing on any resource; it only lets the job request the JWT.

The opening's workflow, before and after:

name: release
on:
  push:
    branches: [main, "feature/**"]
permissions:
  contents: write
  id-token: write
  packages: write
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: npm ci && npm test
  publish:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/shop-registry-push
          aws-region: eu-west-1
      - run: ./scripts/push-image.sh
name: release
on:
  push:
    branches: [main]
permissions: {}
jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7
      - run: npm ci && npm test
  publish:
    needs: test
    runs-on: ubuntu-latest
    environment: release
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/shop-registry-push
          aws-region: eu-west-1
      - run: ./scripts/push-image.sh

Feature branches no longer trigger the workflow. The top level grants nothing, so a job added later starts from zero. Only publish can mint a token, and only after the release environment's rules pass, so npm ci in the test job has no path to the registry role.

Anyone with write access can edit the permissions key, as GitHub's settings documentation notes. The block limits what a compromised dependency or action can do inside a job. Against a committer, the controls are the environment rules and a trust condition that names that environment.

A short static check catches the regressions before review does. This one reads workflow files and nothing else:

"""Flag GITHUB_TOKEN and OIDC exposure in workflow files. Reads files only."""
import re
import sys

import yaml

PRIVILEGED = {"pull_request_target", "workflow_run"}
HEAD_REF = re.compile(r"github\.event\.pull_request\.head\.(sha|ref|repo)|refs/pull/")


def triggers(wf):
    # PyYAML follows YAML 1.1, so a bare `on:` key is parsed as the boolean True.
    on = wf.get("on", wf.get(True))
    if isinstance(on, str):
        return {on}
    return set(on or [])


def lint(path):
    wf = yaml.safe_load(open(path))
    events = triggers(wf)
    top = wf.get("permissions")
    findings = []
    if top is None:
        findings.append("no top-level permissions: jobs without their own block get the repository default")
    elif isinstance(top, dict) and top.get("id-token") == "write":
        findings.append("id-token: write at workflow level: every job can mint an OIDC token")
    for name, job in wf.get("jobs", {}).items():
        perms = job.get("permissions", top)
        mints = isinstance(perms, dict) and perms.get("id-token") == "write"
        steps = job.get("steps", [])
        checks_out = [s for s in steps if str(s.get("uses", "")).startswith("actions/checkout@")]
        if mints and not job.get("environment"):
            findings.append(f"{name}: mints OIDC without an environment, so sub cannot name one")
        if mints and events & PRIVILEGED:
            findings.append(f"{name}: mints OIDC on {sorted(events & PRIVILEGED)}")
        if isinstance(job.get("permissions"), dict) and checks_out and "contents" not in job["permissions"]:
            findings.append(f"{name}: job permissions omit contents, so contents is none")
        for s in checks_out:
            ref = str((s.get("with") or {}).get("ref", "")) + str((s.get("with") or {}).get("repository", ""))
            if events & PRIVILEGED and HEAD_REF.search(ref):
                findings.append(f"{name}: checks out pull request head under {sorted(events & PRIVILEGED)} ({s['uses']})")
    return findings


status = 0
for path in sys.argv[1:]:
    found = lint(path)
    print(f"{path}: {len(found)} finding(s)")
    for f in found:
        print(f"  - {f}")
    status |= bool(found)
sys.exit(status)

PyYAML follows YAML 1.1, where a bare on key parses as the boolean True; the triggers() helper reads both. Against the two release files and a third workflow described in the next section, python3 -I lint_workflows.py workflows/release-before.yml workflows/release-after.yml workflows/preview-pr.yml printed this and exited 1:

workflows/release-before.yml: 3 finding(s)
  - id-token: write at workflow level: every job can mint an OIDC token
  - test: mints OIDC without an environment, so sub cannot name one
  - publish: mints OIDC without an environment, so sub cannot name one
workflows/release-after.yml: 0 finding(s)
workflows/preview-pr.yml: 5 finding(s)
  - no top-level permissions: jobs without their own block get the repository default
  - preview: mints OIDC without an environment, so sub cannot name one
  - preview: mints OIDC on ['pull_request_target']
  - preview: job permissions omit contents, so contents is none
  - preview: checks out pull request head under ['pull_request_target'] (actions/checkout@v6)

The test job is flagged in the first file even though it never calls a login action. That is the point: the ability to mint comes from the permission, not from the step that happens to use it.

Forks, pull_request_target and the privileged checkout

A pull_request run from a fork executes the fork's workflow file from the merge commit, so GitHub downgrades its write permissions to read and withholds the repository's other secrets. Since id-token accepts only write or none, do not build anything that assumes a fork's run can mint a token.

pull_request_target inverts this. The workflow comes from the default branch, GITHUB_REF is the default branch, and the job gets the base repository's read/write token and its secrets, even when the pull request comes from a public fork. That is safe until a step executes code from the pull request head, the pattern GitHub calls a "pwn request":

name: preview
on: pull_request_target
jobs:
  preview:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - run: npm ci && npm run build

The checkout runs nothing. npm ci does, through any install script in the fork's package.json, inside a job that can mint a token.

Two platform changes help, each with an edge. actions/checkout v7.0.0 blocks checking out fork pull request code under pull_request_target and workflow_run unless you set allow-unsafe-pr-checkout: true, a name chosen to stand out in review. The workflow above pins v6, which has no such check, and fetching with git fetch or gh pr checkout bypasses it on any version. GitHub has also added a default policy that blocks pull_request_target in public repositories; it runs in evaluate mode until enforcement begins on December 2, 2026, and does not apply to private or internal repositories.

The safe shape splits the work: build and test the fork's code under pull_request with no secrets, and if something privileged must follow, such as posting a comment, run it under workflow_run, treating anything the first run uploaded as data that is never executed. Keep id-token: write out of both. On the cache side, pull_request_target runs get read-only access to the default branch's cache scope; part 4 explains why opting out with a write-capable cache-mode reopens the poisoning path.

Scope what the role can do once trusted

The trust policy decides who becomes the role; the permission policy decides what it can break. For a release job that pushes one image, the ECR user guide lists exactly what pushing needs: six layer and image actions on the repository's ARN, and ecr:GetAuthorizationToken, which the guide grants on *.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:acme/shop:environment:release"
        }
      }
    }
  ]
}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:InitiateLayerUpload",
        "ecr:UploadLayerPart",
        "ecr:CompleteLayerUpload",
        "ecr:PutImage",
        "ecr:BatchGetImage"
      ],
      "Resource": "arn:aws:ecr:eu-west-1:111122223333:repository/shop"
    },
    { "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" }
  ]
}

Leave out delete, lifecycle and repository-policy actions. A role that can push but not delete limits a stolen session to adding images to one repository. configure-aws-credentials requests a one-hour session unless you set role-duration-seconds; size it to the push, not to the longest job you have.

On Google Cloud, put the ref and the numeric IDs into the provider's attribute condition, which is the ids column from the lab written in CEL:

assertion.repository_owner_id == '1001' && assertion.repository_id == '2002' && assertion.environment == 'release' && assertion.ref == 'refs/heads/main'

Google requires an attribute mapping for every field the condition uses, for example attribute.repository_id=assertion.repository_id. On Entra, create one federated credential per exact subject. Microsoft's guide warns that a mismatched subject makes the exchange fail without an error, so test the subject string from your lab before you paste it.

When the exchange fails, read the claims first

From the log, every OIDC failure looks the same: the login step could not assume the role. Print the decoded payload from a debugging run, never the token itself; GitHub's github/actions-oidc-debugger action does this. Then compare one claim per cause:

  • The subject contains @ and digits. The repository is new, renamed or transferred, and now has an immutable subject. Update the policy to the ID format; the old string will never match again.
  • The subject ends in :pull_request or an unexpected ref. The job has no environment, or a different one from the policy's. Fix the workflow, not the policy.
  • The subject is right but aud differs. The login action's default audience is not the one the provider allows. Make them agree, and confirm the provider's issuer is exactly https://token.actions.githubusercontent.com.
  • event_name is dynamic. The token came from a Dependabot update job. Restrict event_name where the provider supports it; on AWS, give Dependabot a separate role.

Tighten one role this week

Pick the cloud role your release job uses and do the following, in order:

  1. Add the role's exact sub and aud conditions to the lab's policies object, with a row for every context that can request a token: branches, pull requests, tags, reusable workflows. Any ALLOW other than the release job is the finding.
  2. Run the linter across .github/workflows/ and remove each workflow-level id-token: write.
  3. Open the environment the policy names and confirm the deployment-branch rule lists your release branch and that administrator bypass is off. On a private repository, confirm your plan supports the rule at all.
  4. Search for pull_request_target and workflow_run, and for any actions/checkout pinned below v7 in those files.

Save the lab and linter output from before and after the change. Together they show the role can now be assumed from only the context you intended.

Questions about OIDC trust in CI

Is a short-lived token still worth it if the trust policy is wide?

It removes the static key that can be copied from a log, but a wide trust policy hands fresh credentials to anyone who can run a workflow in the repository. An hour-long session is little comfort when the next push mints another.

How do I restrict a role to one reusable deployment workflow?

Use GitHub's subject customization API to include job_workflow_ref in the sub claim, then match that full string in the trust policy. This works on AWS because it changes the subject, not because AWS reads the extra claim. Create the matching condition in the cloud before switching the template, or the next job's token will be refused. An organization-level template also does nothing for a repository until that repository opts in with use_default: false.

Does any of this change on self-hosted runners?

The token is the same, but a self-hosted runner is not guaranteed to be clean between jobs, so a later job may read what the release job left behind. The runner_environment claim distinguishes github-hosted from self-hosted; on providers that read arbitrary claims, require github-hosted for publish roles, or use just-in-time runners that take one job and are removed.

Primary sources behind this guide

CI and Test Infrastructure

Get part 8: Measure CI Pipeline Reliability from First Attempts

It is live now: read part 8. The form below subscribes you to The Automation Brief, the site newsletter.

No spam, no sending cadence promised. Unsubscribe any time.