{"title":"Secure CI with OIDC: Exact Trust Conditions and Job-Scoped Tokens","excerpt":"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.","canonicalUrl":"https://automationtester.in/blog/automation-tutorials/secure-ci-oidc-least-privilege","category":{"name":"Automation Tutorials","slug":"automation-tutorials"},"tags":["github-actions","oidc","ci-cd","least-privilege","pipeline-security","cloud-iam"],"author":{"name":"Shashank Rawlani","url":"https://shashank.rawlani.com","linkedin":"https://www.linkedin.com/in/shashankrawlani/"},"datePublished":"2026-11-19T13:30:00.000Z","dateModified":"2026-11-19T13:30:00.000Z","coverImage":{"url":"https://ik.imagekit.io/automationtester/automationtester-in/blog/covers/v3/secure-ci-oidc-least-privilege.webp","alt":"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."},"contentHtml":"<div class=\"callout callout-info\"><strong>Quick answer:</strong> Grant <code>id-token: write</code> only to the job that deploys, and start every workflow from <code>permissions: {}</code>. Trust that job by an exact subject such as <code>repo:acme/shop:environment:release</code>, never <code>repo:acme/shop:*</code>, and give the <code>release</code> environment a deployment-branch rule and reviewers, because the subject names the environment, not the branch. Keep <code>pull_request_target</code> away from fork code. Prove each condition by verifying tokens you sign against a local JWKS before you touch a real role.</div>\n\n<p>Consider a registry-push role that trusts <code>repo:acme/shop:*</code>, and a release workflow that grants <code>id-token: write</code> at the top level, so that every job in it can request an OIDC token, including the test job that runs <code>npm ci</code> on any branch matching <code>feature/**</code>. One compromised dependency's install script is enough: it calls the token endpoint, exchanges the token for registry credentials and pushes an image tagged <code>latest</code>. 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.</p>\n\n<p>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. <a href=\"/blog/automation-tutorials/ci-cache-dependencies-without-hiding-drift\">Part 4</a> covered cache poisoning and the <code>cache-mode</code> key, so the cache is only referenced here.</p>\n\n<div class=\"callout callout-warning\"><strong>Versions checked on 2026-11-09:</strong> <code>actions/checkout</code> v7.0.1 (released 2026-07-20) and <code>aws-actions/configure-aws-credentials</code> 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.</div>\n\n<h2 id=\"cioidc-what-the-role-compares\">What the cloud role is actually comparing</h2>\n\n<p>When a job has <code>id-token: write</code>, the runner exposes <code>ACTIONS_ID_TOKEN_REQUEST_URL</code> and <code>ACTIONS_ID_TOKEN_REQUEST_TOKEN</code>, and any step can use them to request a JWT signed by <code>https://token.actions.githubusercontent.com</code>. 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.</p>\n\n<p>The default <code>sub</code> is built from the job's context, and the shape changes with the trigger:</p>\n\n<ul>\n<li>A job that references an environment gets <code>repo:ORG/REPO:environment:NAME</code>. The branch is not in the subject at all.</li>\n<li>Without an environment, a <code>pull_request</code> run gets <code>repo:ORG/REPO:pull_request</code>, with no branch or PR number.</li>\n<li>Otherwise the subject carries the ref: <code>repo:ORG/REPO:ref:refs/heads/main</code> or <code>...:ref:refs/tags/v1.4.0</code>.</li>\n<li>Any colon inside a value is encoded, so an environment named <code>Production:V1</code> appears as <code>Production%3AV1</code>.</li>\n</ul>\n\n<p>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: <code>repo:octo-org@123456/octo-repo@456789:ref:refs/heads/main</code>. 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 <code>repository_id</code> and <code>repository_owner_id</code> over names.</p>\n\n<p>The default <code>aud</code> is the owner's URL, but login actions set their own. <code>configure-aws-credentials</code> requests <code>sts.amazonaws.com</code>; <code>azure/login</code> defaults to <code>api://AzureADTokenExchange</code>. What each cloud can test also differs. AWS STS turns only standard claims such as <code>aud</code> and <code>sub</code> 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.</p>\n\n<h2 id=\"cioidc-local-issuer-lab\">Sign GitHub-shaped tokens against a local JWKS</h2>\n\n<p>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, <code>iss</code>, <code>aud</code>, <code>exp</code> and <code>nbf</code> first, then the role's conditions. The <code>like()</code> helper reproduces IAM's <code>StringLike</code>, where <code>*</code> matches any run of characters, colons and slashes included.</p>\n\n<pre><code class=\"language-javascript\">// Local OIDC trust lab. No network access beyond 127.0.0.1.\n// 1. Starts a fake issuer that serves a discovery document and a JWKS.\n// 2. Mints RS256 tokens shaped like GitHub Actions OIDC tokens.\n// 3. Verifies each token the way a cloud STS does: fetch JWKS, check the\n//    signature, iss, aud, exp/nbf, then evaluate trust-policy conditions.\nimport { createServer } from \"node:http\";\nimport { generateKeyPairSync, createSign, createVerify, createPublicKey } from \"node:crypto\";\n\nconst b64url = (buf) =&gt; Buffer.from(buf).toString(\"base64url\");\n\nconst issuerKey = generateKeyPairSync(\"rsa\", { modulusLength: 2048 });\nconst attackerKey = generateKeyPairSync(\"rsa\", { modulusLength: 2048 });\nconst KID = \"lab-key-1\";\n\nconst jwk = { ...issuerKey.publicKey.export({ format: \"jwk\" }), kid: KID, alg: \"RS256\", use: \"sig\" };\n\nconst server = createServer((req, res) =&gt; {\n  res.setHeader(\"content-type\", \"application/json\");\n  if (req.url === \"/.well-known/openid-configuration\") {\n    res.end(JSON.stringify({ issuer: ISSUER, jwks_uri: `${ISSUER}/.well-known/jwks`, id_token_signing_alg_values_supported: [\"RS256\"] }));\n  } else if (req.url === \"/.well-known/jwks\") {\n    res.end(JSON.stringify({ keys: [jwk] }));\n  } else {\n    res.statusCode = 404;\n    res.end(\"{}\");\n  }\n});\nawait new Promise((r) =&gt; server.listen(0, \"127.0.0.1\", r));\nconst ISSUER = `http://127.0.0.1:${server.address().port}`;\n\nfunction mint(claims, { key = issuerKey.privateKey, kid = KID, ttl = 300, iatOffset = 0 } = {}) {\n  const now = Math.floor(Date.now() / 1000) + iatOffset;\n  const header = { typ: \"JWT\", alg: \"RS256\", kid };\n  const payload = { iss: ISSUER, aud: \"sts.amazonaws.com\", iat: now, nbf: now, exp: now + ttl, jti: crypto.randomUUID(), ...claims };\n  const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;\n  const sig = createSign(\"RSA-SHA256\").update(input).sign(key);\n  return `${input}.${b64url(sig)}`;\n}\n\n// What a relying party does with nothing but the issuer URL it was configured with.\nasync function verify(token, expectedIssuer, expectedAud) {\n  const [h, p, s] = token.split(\".\");\n  const header = JSON.parse(Buffer.from(h, \"base64url\"));\n  const claims = JSON.parse(Buffer.from(p, \"base64url\"));\n  const disco = await (await fetch(`${expectedIssuer}/.well-known/openid-configuration`)).json();\n  const { keys } = await (await fetch(disco.jwks_uri)).json();\n  const key = keys.find((k) =&gt; k.kid === header.kid);\n  if (!key) return { ok: false, why: `no JWKS key for kid ${header.kid}`, claims };\n  if (header.alg !== \"RS256\") return { ok: false, why: `alg ${header.alg} not allowed`, claims };\n  const good = createVerify(\"RSA-SHA256\").update(`${h}.${p}`).verify(createPublicKey({ key, format: \"jwk\" }), Buffer.from(s, \"base64url\"));\n  if (!good) return { ok: false, why: \"signature does not match JWKS key\", claims };\n  const now = Math.floor(Date.now() / 1000);\n  if (claims.iss !== expectedIssuer) return { ok: false, why: `iss ${claims.iss}`, claims };\n  if (claims.aud !== expectedAud) return { ok: false, why: `aud ${claims.aud}`, claims };\n  if (claims.exp &lt;= now) return { ok: false, why: `expired ${now - claims.exp}s ago`, claims };\n  if (claims.nbf &gt; now) return { ok: false, why: \"not yet valid\", claims };\n  return { ok: true, claims };\n}\n\n// IAM StringLike: * matches any run of characters (including ':' and '/'), ? matches one.\nconst like = (pattern, value) =&gt;\n  new RegExp(\"^\" + pattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&amp;\").replace(/\\*/g, \".*\").replace(/\\?/g, \".\") + \"$\").test(value);\n\nconst policies = {\n  \"wide   StringLike repo:acme/shop:*\": (c) =&gt; like(\"repo:acme/shop:*\", c.sub),\n  \"typo   StringLike repo:acme/shop*\": (c) =&gt; like(\"repo:acme/shop*\", c.sub),\n  \"narrow StringEquals ...:environment:release\": (c) =&gt; c.sub === \"repo:acme/shop:environment:release\",\n  // Google-style attribute condition: numeric IDs plus the ref, not the sub string.\n  \"ids    owner_id+repo_id+environment+ref\": (c) =&gt;\n    c.repository_owner_id === \"1001\" &amp;&amp; c.repository_id === \"2002\" &amp;&amp; c.environment === \"release\" &amp;&amp; c.ref === \"refs/heads/main\",\n};\n\nconst base = { repository: \"acme/shop\", repository_owner: \"acme\", repository_id: \"2002\", repository_owner_id: \"1001\", runner_environment: \"github-hosted\" };\nconst cases = [\n  [\"release job, main, env release\", mint({ ...base, sub: \"repo:acme/shop:environment:release\", environment: \"release\", ref: \"refs/heads/main\", event_name: \"push\" })],\n  [\"feature push, no env\", mint({ ...base, sub: \"repo:acme/shop:ref:refs/heads/feature/login\", ref: \"refs/heads/feature/login\", event_name: \"push\" })],\n  [\"same-repo pull_request\", mint({ ...base, sub: \"repo:acme/shop:pull_request\", ref: \"refs/pull/41/merge\", event_name: \"pull_request\" })],\n  [\"feature branch, env release\", mint({ ...base, sub: \"repo:acme/shop:environment:release\", environment: \"release\", ref: \"refs/heads/feature/login\", event_name: \"push\" })],\n  [\"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\" })],\n  [\"immutable sub, env release\", mint({ ...base, sub: \"repo:acme@1001/shop@2002:environment:release\", environment: \"release\", ref: \"refs/heads/main\", event_name: \"push\" })],\n  [\"Azure-style audience\", mint({ ...base, aud: \"api://AzureADTokenExchange\", sub: \"repo:acme/shop:environment:release\", environment: \"release\", ref: \"refs/heads/main\" })],\n  [\"signed by another key\", mint({ ...base, sub: \"repo:acme/shop:environment:release\", environment: \"release\", ref: \"refs/heads/main\" }, { key: attackerKey.privateKey })],\n  [\"replayed after expiry\", mint({ ...base, sub: \"repo:acme/shop:environment:release\", environment: \"release\", ref: \"refs/heads/main\" }, { iatOffset: -600 })],\n];\n\nconsole.log(`issuer ${ISSUER}  jwks keys: 1 (kid ${KID})\\n`);\nconst names = Object.keys(policies);\nconsole.log([\"token\".padEnd(32), \"verify\", ...names.map((n) =&gt; n.split(\" \")[0].padEnd(6))].join(\" | \"));\nfor (const [label, token] of cases) {\n  const r = await verify(token, ISSUER, \"sts.amazonaws.com\");\n  const cols = names.map((n) =&gt; (r.ok ? (policies[n](r.claims) ? \"ALLOW\" : \"deny\") : \"-\").padEnd(6));\n  console.log([label.padEnd(32), (r.ok ? \"ok\" : \"FAIL\").padEnd(6), ...cols].join(\" | \") + (r.ok ? `   sub=${r.claims.sub}` : `   ${r.why}`));\n}\nserver.close();</code></pre>\n\n<p>Running <code>node lab.mjs</code> printed:</p>\n\n<pre><code class=\"language-text\">issuer http://127.0.0.1:55848  jwks keys: 1 (kid lab-key-1)\n\ntoken                            | verify | wide   | typo   | narrow | ids   \nrelease job, main, env release   | ok     | ALLOW  | ALLOW  | ALLOW  | ALLOW    sub=repo:acme/shop:environment:release\nfeature push, no env             | ok     | ALLOW  | ALLOW  | deny   | deny     sub=repo:acme/shop:ref:refs/heads/feature/login\nsame-repo pull_request           | ok     | ALLOW  | ALLOW  | deny   | deny     sub=repo:acme/shop:pull_request\nfeature branch, env release      | ok     | ALLOW  | ALLOW  | ALLOW  | deny     sub=repo:acme/shop:environment:release\nother repo acme/shop-sandbox     | ok     | deny   | ALLOW  | deny   | deny     sub=repo:acme/shop-sandbox:ref:refs/heads/main\nimmutable sub, env release       | ok     | deny   | deny   | deny   | ALLOW    sub=repo:acme@1001/shop@2002:environment:release\nAzure-style audience             | FAIL   | -      | -      | -      | -        aud api://AzureADTokenExchange\nsigned by another key            | FAIL   | -      | -      | -      | -        signature does not match JWKS key\nreplayed after expiry            | FAIL   | -      | -      | -      | -        expired 300s ago</code></pre>\n\n<h3 id=\"cioidc-reading-the-matrix\">Four findings from one table</h3>\n\n<p>The <code>wide</code> 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 <code>sub</code> condition is missing or is only a wildcard, but <code>repo:acme/shop:*</code> passes that check.</p>\n\n<p>The <code>typo</code> column drops one colon. <code>repo:acme/shop*</code> now matches <code>acme/shop-sandbox</code>, a different repository. A missing separator is easy to miss in review and obvious in this table.</p>\n\n<p>The <code>narrow</code> column is an exact environment subject, and it still allows row four: a feature branch whose job references <code>environment: release</code>. The token says <code>ref: refs/heads/feature/login</code>, 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.</p>\n\n<p>The <code>ids</code> 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.</p>\n\n<p>The last three rows fail before any condition runs. A token signed by another key with the same <code>kid</code> is rejected on signature, an Azure-audience token is rejected on <code>aud</code>, and an expired token is rejected on <code>exp</code>. Keep them as negative controls: if one ever reads <code>ok</code>, the verifier is broken and every <code>ALLOW</code> above it means nothing.</p>\n\n<h2 id=\"cioidc-environment-branch-rule\">Make the environment hold the branch rule</h2>\n\n<p>An environment subject is only as strong as the environment's deployment protection rules, so configure <code>release</code> before you reference it in a trust policy:</p>\n\n<ul>\n<li><strong>Deployment branches and tags:</strong> choose \"Selected branches and tags\" and add <code>main</code>. The pattern is matched against <code>GITHUB_REF</code>. The \"Protected branches only\" option has a trap: if no branch in the repository has a protection rule, every branch can deploy.</li>\n<li><strong>Required reviewers:</strong> up to six users or teams, one approval needed, with an option to stop the person who triggered the run from approving it.</li>\n<li><strong>Administrator bypass:</strong> allowed by default. Disallow it for an environment whose token can publish.</li>\n</ul>\n\n<p>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.</p>\n\n<p>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, <code>repo:acme/shop:ref:refs/heads/main</code>, and control who can push to that branch.</p>\n\n<h2 id=\"cioidc-job-scoped-permissions\">Give each job only the token it needs</h2>\n\n<p>The <code>permissions</code> key has one rule that surprises people: once you list any permission, every permission you did not list becomes <code>none</code>. A job that declares only <code>id-token: write</code> therefore also has <code>contents: none</code>, and its token can no longer read a private repository's code. The fix is to list <code>contents: read</code> explicitly, not to fall back to <code>write-all</code>. <code>id-token: write</code> itself grants nothing on any resource; it only lets the job request the JWT.</p>\n\n<p>The opening's workflow, before and after:</p>\n\n<pre><code class=\"language-yaml\">name: release\non:\n  push:\n    branches: [main, \"feature/**\"]\npermissions:\n  contents: write\n  id-token: write\n  packages: write\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v7\n      - run: npm ci &amp;&amp; npm test\n  publish:\n    needs: test\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v7\n      - uses: aws-actions/configure-aws-credentials@v6\n        with:\n          role-to-assume: arn:aws:iam::111122223333:role/shop-registry-push\n          aws-region: eu-west-1\n      - run: ./scripts/push-image.sh</code></pre>\n\n<pre><code class=\"language-yaml\">name: release\non:\n  push:\n    branches: [main]\npermissions: {}\njobs:\n  test:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n    steps:\n      - uses: actions/checkout@v7\n      - run: npm ci &amp;&amp; npm test\n  publish:\n    needs: test\n    runs-on: ubuntu-latest\n    environment: release\n    permissions:\n      contents: read\n      id-token: write\n    steps:\n      - uses: actions/checkout@v7\n      - uses: aws-actions/configure-aws-credentials@v6\n        with:\n          role-to-assume: arn:aws:iam::111122223333:role/shop-registry-push\n          aws-region: eu-west-1\n      - run: ./scripts/push-image.sh</code></pre>\n\n<p>Feature branches no longer trigger the workflow. The top level grants nothing, so a job added later starts from zero. Only <code>publish</code> can mint a token, and only after the <code>release</code> environment's rules pass, so <code>npm ci</code> in the test job has no path to the registry role.</p>\n\n<p>Anyone with write access can edit the <code>permissions</code> 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.</p>\n\n<p>A short static check catches the regressions before review does. This one reads workflow files and nothing else:</p>\n\n<pre><code class=\"language-python\">\"\"\"Flag GITHUB_TOKEN and OIDC exposure in workflow files. Reads files only.\"\"\"\nimport re\nimport sys\n\nimport yaml\n\nPRIVILEGED = {\"pull_request_target\", \"workflow_run\"}\nHEAD_REF = re.compile(r\"github\\.event\\.pull_request\\.head\\.(sha|ref|repo)|refs/pull/\")\n\n\ndef triggers(wf):\n    # PyYAML follows YAML 1.1, so a bare `on:` key is parsed as the boolean True.\n    on = wf.get(\"on\", wf.get(True))\n    if isinstance(on, str):\n        return {on}\n    return set(on or [])\n\n\ndef lint(path):\n    wf = yaml.safe_load(open(path))\n    events = triggers(wf)\n    top = wf.get(\"permissions\")\n    findings = []\n    if top is None:\n        findings.append(\"no top-level permissions: jobs without their own block get the repository default\")\n    elif isinstance(top, dict) and top.get(\"id-token\") == \"write\":\n        findings.append(\"id-token: write at workflow level: every job can mint an OIDC token\")\n    for name, job in wf.get(\"jobs\", {}).items():\n        perms = job.get(\"permissions\", top)\n        mints = isinstance(perms, dict) and perms.get(\"id-token\") == \"write\"\n        steps = job.get(\"steps\", [])\n        checks_out = [s for s in steps if str(s.get(\"uses\", \"\")).startswith(\"actions/checkout@\")]\n        if mints and not job.get(\"environment\"):\n            findings.append(f\"{name}: mints OIDC without an environment, so sub cannot name one\")\n        if mints and events &amp; PRIVILEGED:\n            findings.append(f\"{name}: mints OIDC on {sorted(events &amp; PRIVILEGED)}\")\n        if isinstance(job.get(\"permissions\"), dict) and checks_out and \"contents\" not in job[\"permissions\"]:\n            findings.append(f\"{name}: job permissions omit contents, so contents is none\")\n        for s in checks_out:\n            ref = str((s.get(\"with\") or {}).get(\"ref\", \"\")) + str((s.get(\"with\") or {}).get(\"repository\", \"\"))\n            if events &amp; PRIVILEGED and HEAD_REF.search(ref):\n                findings.append(f\"{name}: checks out pull request head under {sorted(events &amp; PRIVILEGED)} ({s['uses']})\")\n    return findings\n\n\nstatus = 0\nfor path in sys.argv[1:]:\n    found = lint(path)\n    print(f\"{path}: {len(found)} finding(s)\")\n    for f in found:\n        print(f\"  - {f}\")\n    status |= bool(found)\nsys.exit(status)</code></pre>\n\n<p>PyYAML follows YAML 1.1, where a bare <code>on</code> key parses as the boolean <code>True</code>; the <code>triggers()</code> helper reads both. Against the two release files and a third workflow described in the next section, <code>python3 -I lint_workflows.py workflows/release-before.yml workflows/release-after.yml workflows/preview-pr.yml</code> printed this and exited 1:</p>\n\n<pre><code class=\"language-text\">workflows/release-before.yml: 3 finding(s)\n  - id-token: write at workflow level: every job can mint an OIDC token\n  - test: mints OIDC without an environment, so sub cannot name one\n  - publish: mints OIDC without an environment, so sub cannot name one\nworkflows/release-after.yml: 0 finding(s)\nworkflows/preview-pr.yml: 5 finding(s)\n  - no top-level permissions: jobs without their own block get the repository default\n  - preview: mints OIDC without an environment, so sub cannot name one\n  - preview: mints OIDC on ['pull_request_target']\n  - preview: job permissions omit contents, so contents is none\n  - preview: checks out pull request head under ['pull_request_target'] (actions/checkout@v6)</code></pre>\n\n<p>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.</p>\n\n<h2 id=\"cioidc-forks-and-prt\">Forks, pull_request_target and the privileged checkout</h2>\n\n<p>A <code>pull_request</code> 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 <code>id-token</code> accepts only <code>write</code> or <code>none</code>, do not build anything that assumes a fork's run can mint a token.</p>\n\n<p><code>pull_request_target</code> inverts this. The workflow comes from the default branch, <code>GITHUB_REF</code> 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\":</p>\n\n<pre><code class=\"language-yaml\">name: preview\non: pull_request_target\njobs:\n  preview:\n    runs-on: ubuntu-latest\n    permissions:\n      id-token: write\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          ref: ${{ github.event.pull_request.head.sha }}\n      - run: npm ci &amp;&amp; npm run build</code></pre>\n\n<p>The checkout runs nothing. <code>npm ci</code> does, through any install script in the fork's <code>package.json</code>, inside a job that can mint a token.</p>\n\n<p>Two platform changes help, each with an edge. <code>actions/checkout</code> v7.0.0 blocks checking out fork pull request code under <code>pull_request_target</code> and <code>workflow_run</code> unless you set <code>allow-unsafe-pr-checkout: true</code>, a name chosen to stand out in review. The workflow above pins v6, which has no such check, and fetching with <code>git fetch</code> or <code>gh pr checkout</code> bypasses it on any version. GitHub has also added a default policy that blocks <code>pull_request_target</code> in public repositories; it runs in evaluate mode until enforcement begins on December 2, 2026, and does not apply to private or internal repositories.</p>\n\n<p>The safe shape splits the work: build and test the fork's code under <code>pull_request</code> with no secrets, and if something privileged must follow, such as posting a comment, run it under <code>workflow_run</code>, treating anything the first run uploaded as data that is never executed. Keep <code>id-token: write</code> out of both. On the cache side, <code>pull_request_target</code> runs get read-only access to the default branch's cache scope; <a href=\"/blog/automation-tutorials/ci-cache-dependencies-without-hiding-drift\">part 4</a> explains why opting out with a write-capable <code>cache-mode</code> reopens the poisoning path.</p>\n\n<h2 id=\"cioidc-scope-the-role\">Scope what the role can do once trusted</h2>\n\n<p>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 <code>ecr:GetAuthorizationToken</code>, which the guide grants on <code>*</code>.</p>\n\n<pre><code class=\"language-json\">{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": { \"Federated\": \"arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com\" },\n      \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n      \"Condition\": {\n        \"StringEquals\": {\n          \"token.actions.githubusercontent.com:aud\": \"sts.amazonaws.com\",\n          \"token.actions.githubusercontent.com:sub\": \"repo:acme/shop:environment:release\"\n        }\n      }\n    }\n  ]\n}</code></pre>\n\n<pre><code class=\"language-json\">{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"ecr:BatchCheckLayerAvailability\",\n        \"ecr:InitiateLayerUpload\",\n        \"ecr:UploadLayerPart\",\n        \"ecr:CompleteLayerUpload\",\n        \"ecr:PutImage\",\n        \"ecr:BatchGetImage\"\n      ],\n      \"Resource\": \"arn:aws:ecr:eu-west-1:111122223333:repository/shop\"\n    },\n    { \"Effect\": \"Allow\", \"Action\": \"ecr:GetAuthorizationToken\", \"Resource\": \"*\" }\n  ]\n}</code></pre>\n\n<p>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. <code>configure-aws-credentials</code> requests a one-hour session unless you set <code>role-duration-seconds</code>; size it to the push, not to the longest job you have.</p>\n\n<p>On Google Cloud, put the ref and the numeric IDs into the provider's attribute condition, which is the <code>ids</code> column from the lab written in CEL:</p>\n\n<pre><code class=\"language-text\">assertion.repository_owner_id == '1001' &amp;&amp; assertion.repository_id == '2002' &amp;&amp; assertion.environment == 'release' &amp;&amp; assertion.ref == 'refs/heads/main'</code></pre>\n\n<p>Google requires an attribute mapping for every field the condition uses, for example <code>attribute.repository_id=assertion.repository_id</code>. 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.</p>\n\n<h2 id=\"cioidc-failure-signatures\">When the exchange fails, read the claims first</h2>\n\n<p>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 <code>github/actions-oidc-debugger</code> action does this. Then compare one claim per cause:</p>\n\n<ul>\n<li><strong>The subject contains <code>@</code> and digits.</strong> 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.</li>\n<li><strong>The subject ends in <code>:pull_request</code> or an unexpected ref.</strong> The job has no environment, or a different one from the policy's. Fix the workflow, not the policy.</li>\n<li><strong>The subject is right but <code>aud</code> differs.</strong> The login action's default audience is not the one the provider allows. Make them agree, and confirm the provider's issuer is exactly <code>https://token.actions.githubusercontent.com</code>.</li>\n<li><strong><code>event_name</code> is <code>dynamic</code>.</strong> The token came from a Dependabot update job. Restrict <code>event_name</code> where the provider supports it; on AWS, give Dependabot a separate role.</li>\n</ul>\n\n<h2 id=\"cioidc-apply-today\">Tighten one role this week</h2>\n\n<p>Pick the cloud role your release job uses and do the following, in order:</p>\n\n<ol>\n<li>Add the role's exact <code>sub</code> and <code>aud</code> conditions to the lab's <code>policies</code> object, with a row for every context that can request a token: branches, pull requests, tags, reusable workflows. Any <code>ALLOW</code> other than the release job is the finding.</li>\n<li>Run the linter across <code>.github/workflows/</code> and remove each workflow-level <code>id-token: write</code>.</li>\n<li>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.</li>\n<li>Search for <code>pull_request_target</code> and <code>workflow_run</code>, and for any <code>actions/checkout</code> pinned below v7 in those files.</li>\n</ol>\n\n<p>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.</p>\n\n<h2 id=\"cioidc-questions\">Questions about OIDC trust in CI</h2>\n\n<h3 id=\"cioidc-faq-why-not-secret\">Is a short-lived token still worth it if the trust policy is wide?</h3>\n\n<p>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.</p>\n\n<h3 id=\"cioidc-faq-reusable-workflow\">How do I restrict a role to one reusable deployment workflow?</h3>\n\n<p>Use GitHub's subject customization API to include <code>job_workflow_ref</code> in the <code>sub</code> 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 <code>use_default: false</code>.</p>\n\n<h3 id=\"cioidc-faq-self-hosted\">Does any of this change on self-hosted runners?</h3>\n\n<p>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 <code>runner_environment</code> claim distinguishes <code>github-hosted</code> from <code>self-hosted</code>; on providers that read arbitrary claims, require <code>github-hosted</code> for publish roles, or use just-in-time runners that take one job and are removed.</p>\n\n<h2 id=\"cioidc-references\">Primary sources behind this guide</h2>\n\n<ul>\n<li><a href=\"https://docs.github.com/en/actions/concepts/security/openid-connect\">OpenID Connect (GitHub Actions concepts)</a> (GitHub): How a job exchanges its OIDC token for a cloud token, the example token header and claims, and that the default sub format changed for repositories created after July 15, 2026.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/security/oidc\">OpenID Connect reference for GitHub Actions</a> (GitHub): Subject formats per trigger (environment, pull_request, ref, tag), %3A encoding, immutable subjects with owner and repository IDs, default and custom aud, sub customization with include_claim_keys and use_default, event_name dynamic for Dependabot, id-token: write granting nothing else, and the ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN variables.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#permissions\">Workflow syntax for GitHub Actions: permissions</a> (GitHub): Unlisted permissions become none once any is listed, id-token accepts only write or none, pull_request_target receives a read/write token from public forks, and fork pull request runs have write permissions downgraded to read.</li>\n<li><a href=\"https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository#setting-the-permissions-of-the-github_token-for-your-repository\">Managing GitHub Actions settings for a repository</a> (GitHub): Anyone with write access can change GITHUB_TOKEN permissions through the permissions key, and the default token permissions for new repositories.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments\">Deployments and environments reference</a> (GitHub): Deployment branch and tag rules matched against GITHUB_REF, the protected-branches-only trap when no branch is protected, required reviewers and self-review prevention, administrator bypass on by default, and plan availability for private repositories.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idenvironment\">jobs.&lt;job_id&gt;.environment in the workflow syntax</a> (GitHub): All deployment protection rules must pass before a job that references the environment is sent to a runner.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target\">Securely using pull_request_target</a> (GitHub): Why pull_request_target is privileged, the pwn request shapes, the default policy for public repositories in evaluate mode with enforcement on December 2, 2026, read-only cache access for these runs, and the allow-unsafe-pr-checkout opt-out and what it does not cover.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request_target\">Events that trigger workflows: pull_request_target</a> (GitHub): GITHUB_SHA and GITHUB_REF for pull_request_target point at the default branch.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/security/secure-use\">Secure use reference for GitHub Actions</a> (GitHub): Commit-SHA pinning and workflow dependency lockfiles, workflow_run artifacts as untrusted, self-hosted runners not guaranteed to run one job, and just-in-time runners.</li>\n<li><a href=\"https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws\">Configuring OpenID Connect in Amazon Web Services</a> (GitHub): The sts.amazonaws.com audience for the official action, environment subjects in AWS trust policies, and that custom OIDC claims are unavailable in AWS.</li>\n<li><a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html#idp_oidc_Create_GitHub\">IAM User Guide: configuring a role for GitHub OIDC identity provider</a> (Amazon Web Services): IAM rejects GitHub trust policies whose sub condition is missing or only a wildcard, and the any-branch StringLike example.</li>\n<li><a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif\">IAM condition keys available for AWS OIDC federation</a> (Amazon Web Services): Which token claims become STS condition keys for providers that use the default mapping, including GitHub.</li>\n<li><a href=\"https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-push-iam.html\">IAM permissions for pushing an image to an Amazon ECR private repository</a> (Amazon Web Services): The six repository-scoped actions needed to push an image and ecr:GetAuthorizationToken granted on *.</li>\n<li><a href=\"https://cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines\">Workload Identity Federation with deployment pipelines</a> (Google Cloud): Attribute conditions as CEL expressions, the requirement to map every field a condition uses, the spoofing warning for shared issuers, and the recommendation to use numeric repository and owner IDs over names.</li>\n<li><a href=\"https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation-create-trust\">Configure an app to trust an external identity provider (Microsoft Entra)</a> (Microsoft): Federated credential subjects must match exactly, pattern matching is unsupported for branches and tags, and a mismatch fails without an error.</li>\n<li><a href=\"https://github.com/actions/checkout/blob/v7.0.1/CHANGELOG.md\">actions/checkout changelog at v7.0.1</a> (GitHub): v7.0.0 blocks checking out fork pull request code under pull_request_target and workflow_run; v7.0.1 is the current release.</li>\n<li><a href=\"https://github.com/actions/checkout/blob/v7.0.1/action.yml\">actions/checkout action.yml at v7.0.1</a> (GitHub): The allow-unsafe-pr-checkout input, its default of false, and the triggers it applies to.</li>\n<li><a href=\"https://github.com/aws-actions/configure-aws-credentials/blob/v6.3.0/action.yml\">configure-aws-credentials action.yml at v6.3.0</a> (Amazon Web Services): The default audience sts.amazonaws.com and the one-hour default role session duration.</li>\n<li><a href=\"https://yaml.org/type/bool.html\">Boolean Language-Independent Type for YAML Version 1.1</a> (YAML.org): In YAML 1.1, which PyYAML follows, on and off are boolean values, so a bare on key in a workflow parses as True.</li>\n</ul>\n"}