GitHub Hour 6: Enterprise Security and Governance in Practice

From “a SECURITY.md file in the repo” to “organization-wide, auditable, measurable, secure by default”: Secret Protection, Code Security, Dependabot, identity, rulesets, audit logs, and AI governance
Secret Protection $19Code Security $30codeql-action v4.39dependency-review-action v5.0.0Verified against docs.github.com · 2026-11
Overall learning objectives
  • Explain how GitHub Advanced Security was split on 2025-04-01 into GitHub Secret Protection ($19/active committer/month) and GitHub Code Security ($30/active committer/month), and know which capabilities are free in public repositories, which require Team/Enterprise plus a license, and know how to use security configurations with security overview scaled rollout and measurement.
  • Understand secret scanning and push protection server-side mechanics: scan on push → match patterns → reject (GH013) and return an unblock link → bypass reason or delegated bypass approval → alerts and audit; know that the first action after a leak is always rotation (revoke/rotate), not rewriting history.
  • Master CodeQL the default and advanced setup of code scanning, read a CodeQL workflow (init → build/extract → database → query suite → SARIF → upload), upload third-party SARIF, handle alerts in PRs, and use Copilot Autofix, and use the ruleset's “Require code scanning results” to gate merges.
  • Configure Dependabot (alerts / security updates / version updates, including github-actions ecosystems, grouping, and cooldown),dependency-review-action PR gating and auto-triage rules.
  • Design an identity plan for organizations/enterprises: SAML SSO (PAT/SSH authorization),Enterprise Managed Users (Entra ID OIDC + SCIM), team sync,GHE.com data residency.
  • Use organization/enterprise rulesets, bypass lists, rule insights,audit log queries and streaming to build a compliance evidence trail; for Copilot Business/Enterprise configure policies, content exclusions, public code match filtering, and coding agent toggles; finally, complete a governance architecture review.

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (public practice repository myapp-sec)
0Before classPreparation: security lab repositoryfree organization myorg-lab, public repository myapp-sec, gh token scopes, optional GHAS trialPlan self-checkRepository and gh ready
100–06Security product overview and licensingSecret Protection / Code Security split and pricing, free portion for public repositories, security overview, security configurations, risk assessment“Plan × visibility → available features” calculatorUse the API to view and enable repository security features
206–14Secret scanning and push protectionpattern types, partner program, custom patterns, push protection blocking and bypass, delegated bypass, validity checks, rotate firstCore animation: git push → server-side scan → GH013 → bypass/approval → alertPractice blocking and handling with a one-time PAT
314–22Code scanning and CodeQLdefault vs advanced setup, CodeQL workflow, query suites, SARIF, PR alerts, Copilot Autofix, triage and dismissalCore animation: build database → query → SARIF → PR alertdefault setup + introduce a command injection and fix it
422–30Dependabot and dependency reviewdependency graph, alerts, security/version updates, dependabot.yml (grouping, cooldown, github-actions), dependency-review-action, auto-triageAlert matching + PR gate simulatorIntroduce a vulnerable requests and get blocked by the gate
530–38Organizations and enterprises: SSO, EMU, team syncSAML SSO and credential authorization, EMU (Entra OIDC/CAP), SCIM, team sync, GHE.com data residency“Token + session → 200/403” decision simulationRead SSO authorization status (concept + API)
638–46Rulesets, audit logs, and complianceorganization/enterprise rulesets, target repository patterns, bypass, rule insights, audit log queries and streaming, compliance reportsRuleset stacking evaluatorOrganization ruleset + audit log query
746–53Copilot and AI feature governanceBusiness/Enterprise policies, content exclusions, public code match filtering, audit, coding agent governance togglesEnterprise × organization policy resolverPolicy inventory checklist
853–60Governance architecture reviewreview checklist, maturity model, troubleshooting treeMaturity self-assessment + interactive troubleshooting treeProduce a one-page review conclusion
—After classCheat sheet · Capstone labone secret leak blocked + one vulnerability fix, closed loopFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / configurationLab
Determine the plan and license a feature requires✓✓✓✓✓✓✓✓security configurationsM1 calculator
Enable security features at scale✓·✓✓···✓gh api …/code-security/configurationsM1 lab
Block secrets from entering the repository and handle them correctly·✓···✓·✓secret-scanning/alerts, GH013leak drill
Static analysis and PR gating··✓··✓·✓codeql-action/init|analyze|upload-sarifCommand injection fix
Dependency vulnerabilities and supply chain gating···✓·✓·✓dependabot.yml, dependency-review-actionrequests vulnerability
Identity and access (SSO / EMU / SCIM)····✓·✓✓gh auth refresh, credential authorization403 diagnosis
Ruleset and exception governance·✓✓✓·✓·✓gh api orgs/ORG/rulesetsOrganization ruleset
Audit and compliance evidence·✓··✓✓✓✓audit log queries, streamingM6 lab
AI feature governance··✓···✓✓Copilot policies, content exclusionsM7 checklist

What this hour does not cover (and where to learn it)

TopicWhy it is not in this hourWhere to learn
branch protection, ruleset basics, CODEOWNERS, PR merge methodsThe Git course already covered platform basicsGit Lesson 3: Moving to a Hosted Platform
Actions security hardening (GITHUB_TOKEN least privilege, pinning by SHA,pull_request_target), artifact attestations, required workflowsCovered in the previous lessonLesson 5: Production-grade Actions
OIDC federated credentials to Azure/AWSCloud deployment topicsLesson 3 Azure · Lesson 4 AWS
Writing CodeQL custom query language (QL), variant analysis (MRVA)Belongs to security research, beyond 1 hourCodeQL documentation
GitHub Enterprise Server (self-hosted) operationsThis hour follows GitHub.com / GHE.comGHES administration documentation
Container image scanning, K8s runtime securityCovered in later coursesDocker course · K8s course

How to use this courseware

10 pages per module
Theory · diagrams · animation · commands · lab · production case · troubleshooting · quiz · audio · video. Read "Theory" and "Animation" first, then do the "Lab" in the public practice repository.
Learning progress
A quiz score ≥ 70% or clicking "Mark this module complete" counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Chinese audio
The "Audio" page reads the script aloud using the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version and plan notes Facts in this hour were verified on 2026-11-15 against docs.github.com and the GitHub Changelog. The names, entry points, and plan boundaries of GitHub security features change quickly (for example, the 2025-04 GHAS split, organization rulesets opened to Team in 2025-06, and the 2026 renaming to "AI detection" and the Copilot "AI controls" entry point),always refer to the settings pages actually shown in your account and the official documentation. Every step that requires a GitHub Team / Enterprise Cloud / GHAS license is marked with License required and a free alternative.

Module 0 · Preparation: security lab repository (complete before class)

Try secret scanning, push protection, CodeQL, Dependabot, and dependency review for free with a free organization + public repository
Before class ≈ 10 minGitHub Free is enoughEnterprise features require a trial
Prerequisites
  • CompletedLesson 5: a personal account and a sample organization myorg-lab (sample name, replace with your own organization), with the local install of gh CLI and Git 2.56.
  • The sample app reuses the one from the Docker course myapp (Flask + gunicorn + Redis, including Dockerfile and /healthz). This hour copies it to a public repository myorg-lab/myapp-sec: public repositories can use secret scanning, push protection, CodeQL default setup, Copilot Autofix, and dependency review for free.
  • Do not put real business code or real credentials in the public practice repository. The "secret" this hour uses to trigger push protection is a no-permission, 1-day-expiry token that is revoked immediately after the drill fine-grained PAT.

Plan and feature readiness overview

Feature in this hourPublic repository (any plan)Private/internal repositoryApproach in this hour
Secret scanning + push protectionFreeRequires Team/Enterprise + Secret ProtectionHands-on in public repository
custom patterns, delegated bypass, validity checks, AI detectionRequires Secret Protection (organization repositories)Requires Secret ProtectionTheory + GHAS trial (optional)
CodeQL code scanning, Copilot AutofixFreeRequires Code SecurityHands-on in public repository
Dependabot alerts / security updates / version updatesFreeFree (all plans)Hands-on
Dependency reviewFreeRequires Code SecurityHands-on
Organization rulesetsRequires Team or Enterprise (Team since 2025-06-16); Free can use repository-level rulesets (public repositories)Free organizations use repository-level rulesets instead
SAML SSO, EMU, audit log API/streaming, enterprise rulesetsRequires GitHub Enterprise CloudTheory + screenshot-style steps + optional GHEC trial

Step 1: Create the public practice repository and push myapp

ORG=myorg-lab          # replace with your organization (or personal account)
gh auth status
gh auth refresh -h github.com -s admin:org,security_events,read:audit_log   # scopes needed by later API calls
gh repo create $ORG/myapp-sec --public --description "Security lab (no real secrets)" --clone
cd myapp-sec
# copy the myapp source from the Docker course (app.py, requirements.txt, Dockerfile, tests/)
cp -r ../myapp/{app.py,requirements.txt,Dockerfile,tests} . 2>/dev/null || true
git add . && git commit -m "chore: import myapp for security lab" && git push -u origin main
✓ Logged in to github.com account alice (keyring)
✓ Created repository myorg-lab/myapp-sec on GitHub
  https://github.com/myorg-lab/myapp-sec
[main (root-commit) 3f2a9c1] chore: import myapp for security lab
 5 files changed, 142 insertions(+)
To https://github.com/myorg-lab/myapp-sec.git
 * [new branch]      main -> main

If you don't have myapp, the minimal version below is enough (Module 3 introduces and fixes a vulnerability on top of it):

from flask import Flask, jsonify
import os, redis

app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379)

@app.get("/healthz")
def healthz():
    return jsonify(status="ok")

@app.get("/")
def index():
    return jsonify(hits=r.incr("hits"))
flask==3.1.*
redis==5.*
gunicorn==23.*

Keep consistent with the Docker course. Note: the dependency graph for ==3.1.* range specifiers like this can only infer "possible versions"; Module 4 demonstrates exact pinned versions (==x.y.z) where Dependabot alerts are most accurate.

Step 2: Check the repository's current security settings

gh api repos/$ORG/myapp-sec --jq '.visibility, .security_and_analysis'
"public"
{
  "dependabot_security_updates": { "status": "disabled" },
  "secret_scanning": { "status": "enabled" },
  "secret_scanning_push_protection": { "status": "enabled" },
  "secret_scanning_non_provider_patterns": { "status": "disabled" },
  "secret_scanning_validity_checks": { "status": "disabled" }
}
Note Secret scanning on public repositories is usually enabled by default, and push protection is often enabled on new repositories—but an organization may change the defaults via a security configuration, so treat the API response as authoritative. Seeing advanced_security / secret_scanning / code_security and other different key names is normal: after the split, the API also keeps compatibility fields.

Step 3 (optional): Enterprise feature trial

Module 2's custom patterns and delegated bypass, Module 5's SAML/EMU, and Module 6's audit log streaming require GitHub Enterprise Cloud and/or a GHAS license. GitHub offers a GHEC trial, and the 2026-09-09 Changelog also expanded the self-serve trial scope for Code Security / Secret Protection. Remember to cancel before the trial ends to avoid charges; an EMU enterprise must be created separately (an existing personal account cannot be converted into a managed user).

Warm-up: answer from memory (30 seconds)

In Lesson 5, GITHUB_TOKEN what should the default permissions be set to? Why does the CodeQL job in this hour need security-events: write?

The default should be read-only (contents: read), elevated per job. CodeQL's analyze/upload-sarif writes SARIF to the code scanning API, so the job needs security-events: write; private repositories also need actions: read (to read workflow run information).

When rulesets and classic branch protection overlap, what is the final effect?

The strictest combination applies (all applicable rules take effect together). Module 6 of this hour extends this to organization/enterprise rulesets.

Environment self-check checklist

Module 1 · GitHub security product overview and licensing

00:00 – 06:00 · First clarify "what exists, which plan it requires, and how to enable it at scale", then discuss specific features
6 minSplit since 2025-04-01Prices per github.com★★★★☆
Learning objectives
  • Name the features included in GitHub Secret Protection and GitHub Code Security, the billing unit (active committers), and the purchase requirements (Team or Enterprise).
  • Distinguish "free for all repositories" (Dependabot, dependency graph), "free for public repositories" (secret scanning, push protection, CodeQL, Autofix, dependency review), and "must purchase" (the above features on private repositories, custom patterns, delegated bypass, security campaigns, etc.).
  • Know how to use security configurations to enable features across hundreds or thousands of repositories at once, and use security overview to view coverage and risk.
Prerequisites: organizations, repository visibility (public / private / internal). Importance:★★★★☆ (choosing the wrong plan = both budget and compliance risk)

What: GitHub's "security product family"

GitHub previously bundled paid security capabilities as GitHub Advanced Security (GHAS). The 2025-03-04 Changelog announced the split,starting 2025-04-01 sold as two separately purchasable products; together they are still called GHAS:

ProductProblem solvedIncludes (per docs.github.com, 2026-11)List price (Changelog 2025-03-04)
GitHub Secret ProtectionDetect and block credential leakssecret scanning, push protection, secrets detected by AI detection, custom patterns, delegated bypass for push protection, delegated dismissal for alerts, validity checks, security campaigns, security overview$19 / active committer / month
GitHub Code SecurityFind and fix code and dependency vulnerabilitiescode scanning (CodeQL and third-party SARIF), CodeQL CLI, Copilot Autofix, AI Scan (covers languages CodeQL does not support; per documentation), security campaigns, custom Dependabot auto-triage rules, dependency review, security overview$30 / active committer / month

Third-party price tracking in 2026 shows the GitHub pricing page presenting Code Quality, Code Security, and Secret Protection as add-on product cards; no official list price increase has been found. Before purchasing, check github.com/security/plans and your sales quote.

Billing unit: active committer

  • "In the past 90 days a commit was pushed to a repository with the product enabled" counts, and the person holds a Team or Enterprise seat in that organization/enterprise (member, managed user, outside collaborator, or pending invitee).
  • The same person counts as only 1 one license across the whole organization/enterprise, regardless of how many repositories they contribute to; GitHub App bots are not counted.
  • Billing model: metered—Team and Enterprise Cloud can self-serve, paying monthly for actual active committers, with no overage state; volume (bulk/subscription)—Enterprise only, pre-purchased fixed quantity; exceeding it requires buying more. Standalone GHES instances always use volume licensing.

Why: why define the boundaries first

The "price" of the same feature differs completely by visibility: CodeQL is free on public repositories and costs $30 per active committer per month on private ones. Many teams "turn on secret scanning" but only cover public repositories, so private repositories actually have no protection; other teams enable Code Security on every repository and end up with bills inflated by historical committers in many inactive repositories (the actual window is 90 days of activity, so inventory first).

How: free/paid boundaries at three levels

LevelFeatures
Free for all repositories and all plansdependency graph, Dependabot alerts, Dependabot security updates, Dependabot version updates, GitHub's built-in auto-triage rules, security advisories (GitHub Advisory Database), private vulnerability reporting (public repositories), user-level push protection (blocks you from pushing secrets to public repositories)
Free for public repositoriessecret scanning (including partner program notifications), repository-level push protection, code scanning / CodeQL (default and advanced setup), Copilot Autofix, dependency review, custom Dependabot auto-triage rules
Must purchase (private/internal repositories, or organization-level advanced capabilities)the above features used on private/internal repositories; custom patterns, delegated bypass / dismissal, validity checks, non-provider patterns (generic) and AI detection, security campaigns, full security overview

security overview and security configurations

  • Security overview (the Security tab for organizations/enterprises): aggregates alerts (risk view), feature enablement coverage, push protection blocking and bypass metrics, CodeQL fix rate, secret scanning metrics, etc. The full view requires Team/Enterprise and at least one GHAS product.
  • Security configurations (organization Settings → Advanced Security → Configurations): a set of "which features to enable" collections. GitHub provides GitHub recommended configurations, and you can also create custom configurations; you can apply a configuration to all or selected repositories, set it as the default for new repositories, and can enforce (enforce, so repository admins cannot change it in the repository). A repository's configuration status can be attached, enforced, detached (an admin changed settings on a non-enforced configuration), failed, etc.
  • Global settings: organization-level settings (for example, whether push protection applies to custom messages/links, whether Copilot Autofix is allowed, whether CodeQL uses the extended suite on PRs, etc.) work together with configurations.
  • Free risk assessment: Team/Enterprise organizations can run a secret risk assessment (counting historical leaks and estimating how many Secret Protection would block) and a code security risk assessment (scanning up to 20 of the most active repositories and estimating how much Autofix could fix).

When: how to choose

  • Mainly open source/public: no need to buy; just use a security configuration at the organization level to enable the free features uniformly.
  • Lots of private code, with credential leaks as the top risk (the most common real intrusion path): buy Secret Protection first; it is low-cost and quick to show results.
  • Regulated industry / need SAST evidence: add Code Security, and combine it with rulesets to gate merges with a "no high-severity alerts before merge" requirement.
  • GHES: features are largely the same but versions lag; licensing is volume; refer to the corresponding GHES version documentation.

Comparison with similar products

GitHub nativeAzure DevOpsThird-party (Snyk / SonarQube / GitGuardian, etc.)
SecretsSecret Protection: server-side push protection + partner automatic revocation notificationsGitHub Advanced Security for Azure DevOps (billed separately)mostly pre-commit / CI scanning, with weak server-side blocking
SASTCodeQL (semantic database + data flow)Same as above (based on CodeQL)Rule engines vary; can be SARIF uploaded to GitHub for unified display
DependenciesDependabot + dependency review (Advisory Database)dependency scanning (GHAzDO)richer vulnerability and license data; can be used together
Common misconceptions① "Enabling Dependabot means you bought GHAS"—Dependabot alerts/updates have always been free; only dependency review (private repositories) and custom auto-triage rules (private repositories) belong to Code Security. ② "Secret Protection only scans new commits"—once enabled, it scans the entire Git history (and issues, PRs, discussions, wikis, etc.; see the documented scope). ③ "Active committers = organization members"—only people who pushed commits to enabled repositories within 90 days are counted. ④ "Public repositories are free, so put anything in the organization"—public repositories mean the code is public; only the security features are free.

Architecture diagram: where GitHub security capabilities sit in the development lifecycle

Developer machineIDE · Copilot push Push protectionServer-side scan · GH013Secret Protection Pull RequestCodeQL · dependency reviewAutofix · ruleset gate Default branchMerge ReleaseAttestation (Lesson 5) Continuous: secret scanning full-history scan · CodeQL weekly scheduled scan · Dependabot alerts (triggered by new Advisory Database advisories) → alerts enter the Security tab → security overview aggregates → security campaigns batch-fix Identity and access (M5)SAML SSO · EMU · SCIM · team sync Policy and evidence (M6)rulesets · audit logs · streaming · compliance reports AI governance (M7)Copilot policies · content exclusions · agent toggles
Figure 1-1: shift-left (push/PR) and continuous scanning lines, plus three cross-cutting layers: identity, policy, and AI

Flowchart: scaling enablement with a security configuration

Inventory repositoriesvisibility · activity Risk assessment (free)secret / code risk Create configurationrecommended / custom Apply + set as defaultBatch by property enforcePrevent being turned off security overview → Coverage (enablement) / Risk (alerts) / push protection metricsfind detached / failed repositories → go back to the configuration and fix
Figure 1-2: configuration-driven (configuration-as-policy) rather than toggling switches repository by repository

Interactive calculator: plan × visibility × purchased products → which features are available

Select the organization plan, repository visibility, and purchased products; the table shows in real time whether each feature is available and estimates the monthly cost (based on the Changelog 2025-03-04 list prices, for illustration only).

Organization plan
Repository visibility
Purchased
Active committers in the past 90 days: 50

Core commands and API

Command / APIPurposeNotes
gh api repos/O/R --jq .security_and_analysisView repository security feature statusRead-only; repository admin access is required to see all fields
PATCH /repos/O/R (security_and_analysis)Per-repository toggles for secret scanning / push protection, etc.Private repositories require the corresponding license, otherwise returns 422
PUT /repos/O/R/vulnerability-alertsEnable Dependabot alertsautomated-security-fixes Enable security updates
GET /orgs/O/code-security/configurationsList the organization's security configurationsRequires admin:org or security manager
POST …/configurations/ID/attachApply a configuration to repositoriesscope: all / public / private_or_internal / selected etc.
PUT …/configurations/ID/defaultsSet as default configuration for new repositoriesdefault_for_new_repos: all / none / private_and_internal / public
ORG=myorg-lab; REPO=myapp-sec
# 1) enable secret scanning + push protection (free for public repositories)
gh api -X PATCH repos/$ORG/$REPO --input - <<'EOF'
{"security_and_analysis":{
  "secret_scanning":{"status":"enabled"},
  "secret_scanning_push_protection":{"status":"enabled"}}}
EOF
# 2) Dependabot alerts and security updates (free for all repositories)
gh api -X PUT repos/$ORG/$REPO/vulnerability-alerts
gh api -X PUT repos/$ORG/$REPO/automated-security-fixes
# 3) verify
gh api repos/$ORG/$REPO --jq '.security_and_analysis | to_entries[] | "\(.key)=\(.value.status)"'
dependabot_security_updates=enabled
secret_scanning=enabled
secret_scanning_push_protection=enabled
secret_scanning_non_provider_patterns=disabled
secret_scanning_validity_checks=disabled

Organization level: security configurations

gh api orgs/$ORG/code-security/configurations \
  --jq '.[] | {id, name, target_type, enforcement, secret_scanning, code_scanning_default_setup, dependabot_alerts}'
# apply to all public repositories in the organization (Free organizations can also use free features on public repositories)
gh api -X POST orgs/$ORG/code-security/configurations/CONFIG_ID/attach -f scope=public
gh api orgs/$ORG/code-security/configurations/CONFIG_ID/repositories --jq '.[] | "\(.repository.name)\t\(.status)"'
{"id":17,"name":"GitHub recommended","target_type":"global","enforcement":"unenforced","secret_scanning":"enabled","code_scanning_default_setup":"enabled","dependabot_alerts":"enabled"}
myapp-sec	attached
legacy-tool	attaching

How to verify: On the organization Security → Coverage page, the feature column for the repository shows Enabled. Common error: attaching a configuration that includes Code Security to a private repository without purchasing it changes the status to failed. Production use: first use custom properties (such as tier=prod) to filter repositories and apply in batches, observing the active committer count before expanding scope.

Lab 1: Inventory and enable security features on the practice repository (about 5 minutes)

View in the UI: open https://github.com/myorg-lab/myapp-sec/settings/security_analysis (Settings → Advanced Security, formerly called Code security and analysis). Record whether each feature is Enabled or Disabled, and note which items say a license is required.
Enable free features with the API: run steps 1)–3) on the "Commands" page and confirm secret_scanning_push_protection=enabled,dependabot_security_updates=enabled.
Enable visibility of the dependency graph and Dependabot alerts:
gh api repos/$ORG/$REPO/dependency-graph/sbom --jq '.sbom.packages | length'
gh api repos/$ORG/$REPO/dependabot/alerts --jq 'length'
7
0

The package count in the SBOM (SPDX) shows the dependency graph has been parsed requirements.txt; at this point there are 0 alerts. Module 4 will deliberately introduce a vulnerable dependency.

(requires Team/Enterprise) View the security overview and configurations: Organization → Security → Overview / Coverage; Settings → Advanced Security → Configurations, to see which features GitHub recommended includes. Free organization alternative: Use gh api orgs/$ORG/code-security/configurations to view (if it returns 404/403, the current plan or permissions do not support it; just record that).
Record a baseline: copy the table below into your review notes (used in Module 8): repository count, public/private ratio, enabled features, estimated 90-day active committers (gh api repos/$ORG/$REPO/stats/contributors rough estimate only).

Case 1: Security budget decision for a 200-person engineering team

Problem: The organization has 600 private repositories, and the CISO requires "enable GHAS on everything". Approach: First run the free secret risk assessment, which found 140 valid secrets in history; the 90-day active committer count is 180 people (another 70 people only committed to archived repositories). First buy Secret Protection for all private repositories (about 180 × $19); Code Security is enabled only for the 120 repositories with tier=prod (110 active committers). Configuration: Two custom security configurations, applied by custom property and enforced. Limitations: Prices are list prices; the contract governs. New members who push are automatically counted on the next month's bill.

Case 2: An open source foundation enables free features uniformly

Problem: 300 public repositories are managed by different maintainers; some have not even enabled Dependabot. Approach: The organization owner applied the GitHub recommended configuration to all public repositories and set it as the default for new repositories; the configuration is set to enforced to prevent it from being turned off. Result: Within a week, security overview coverage rose from 35% to 100%, and push protection blocked 12 PAT pushes. Limitations: After enforcement, repository maintainers cannot temporarily disable push protection; false positives must be handled through the bypass mechanism.

Case 3: Investigating a failed configuration status

Problem: After applying a configuration with CodeQL default setup to all repositories, dozens of repositories showed failed. Approach: Checked the causes one by one: private repositories had not purchased Code Security; some repositories had Actions disabled (default setup depends on Actions); some repositories already had an advanced-setup CodeQL workflow (default and advanced setup conflict). Fix: Split the configuration, enable Actions for the repositories that need it, and migrate or keep advanced setup.

Common errors and fixes

422 Unprocessable Entity: "Advanced Security must be enabled for this repository to change secret scanning settings." (or similar message)

Cause: Enabling secret scanning/push protection on a private/internal repository, but the organization has not purchased Secret Protection (or did not enable it for that repository).

gh api repos/O/R --jq '.visibility, .security_and_analysis'

Fix: Purchase and enable Secret Protection; or practice on a public repository. Prevention: Manage centrally with a security configuration to avoid manual per-repository operations.

gh: Not Found (HTTP 404) — GET /orgs/O/code-security/configurations

Cause: The token lacks admin:org (or read:org) scope, or you are not an owner/security manager.

gh auth status
gh auth refresh -h github.com -s admin:org

Fix: Refresh the token scopes; ask the owner to add you to the security manager role (organization role "Security manager").

security configuration status: failed / detached

Cause: failed: insufficient license, Actions disabled, conflict with existing settings; detached: a repository admin changed settings on a non-enforced configuration.

Fix: Check each repository's status reason on the Configurations page; set the configuration to enforced when uniformity is needed.

GHAS active committers on the bill are far more than expected

Cause: The product was enabled on many repositories, and everyone (including outside collaborators) who pushed to those repositories within 90 days is counted; large-scale migrations or bulk automated commits also increase the count (GitHub App bots are not counted).

Fix: Download the active committer report under enterprise Billing → Advanced Security, narrow the enablement scope by repository, and archive read-only historical repositories.

Command-line questions
1. One command that lists all security features of a repository as "name=status".
gh api repos/O/R --jq '.security_and_analysis | to_entries[] | "\(.key)=\(.value.status)"'
2. Set the security configuration with ID 17 as the default configuration for all new repositories.
gh api -X PUT orgs/O/code-security/configurations/17/defaults -f default_for_new_repos=all
Scenario analysis question
A company on the Team plan has 80 private repositories and 5 public repositories, and the budget only covers one product. Which would you recommend, and why?

Prioritize Secret Protection: credential leaks are the most common and most direct intrusion path, the $19 cost is lower, and push protection can stop the problem at the source. Public repositories already get CodeQL and dependency review for free, and private repositories can start with free Dependabot alerts/updates plus a third-party or open-source SAST (uploading SARIF to show results on private repositories requires Code Security, so in the meantime the CI can fail the build directly). Add Code Security for core repositories once the budget allows.

Verified instructional videos

▶
Introduction to GitHub Advanced Security | GH-500 | Episode 1 — Microsoft Learn
English · GH-500 certification series Episode 1, GHAS overview (recorded before some 2026 changes; product names follow this hour)
▶
Course Preview | GH-500 | GitHub Advanced Security — Microsoft Learn
English · series trailer, useful for planning a learning path
▶
GitHub Advanced Security Certification – Pass the Exam! — freeCodeCamp.org
English · full-length course covering M1–M4 of this hour

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: a big box "GHAS" splits in two; on the left a key icon "Secret Protection $19", on the right a magnifying glass "Code Security $30".
Narration: Starting April 2025, GitHub Advanced Security was split into two products that can be purchased separately.
Shot 2 · 20–45s
Visual: a three-tier pyramid: bottom tier "Free for all repositories: Dependabot", middle tier "Free for public repositories: secret scanning, CodeQL, Autofix", top tier "Paid: private repositories and advanced capabilities".
Narration: first distinguish the three tiers of boundaries, so you know where the money should go.
Shot 3 · 45–70s
Visual: avatars lit up within the 90-day window on a calendar are counted.
Narration: billing is per active committer, meaning people who pushed commits to enabled repositories within 90 days, each counted once.
Shot 4 · 70–90s
Visual: a configuration card is dragged onto hundreds of repository icons, which turn green one by one.
Narration: use a security configuration to enable and enforce everything at once, rather than toggling switches repository by repository.
or score ≥ 70% on the "Quiz"

Module 2 · Secret scanning and push protection

06:00 – 14:00 · The best leak response is to never push it; if it was pushed, the first step is rotation
8 minFree for public repositoriesCustom patterns/delegated bypass require Secret Protection★★★★★
Learning objectives
  • Explain the difference among the four detection pattern types (partner/provider patterns, non-provider generic patterns, custom patterns, AI detection) and the partner program.
  • Describe the server-side flow of push protection: receive pack → scan new content → match → with GH013 reject the ref update and return an unblock link → bypass reason or delegated bypass request → alerts, audit log, and email.
  • Handle a leak in the order "rotate first, then investigate, then clean up", and know when history must be rewritten.
Prerequisites: The basics of git push (Git course Lesson 1), PATs and SSH keys. Importance:★★★★★ (credential leaks are the most common starting point for cloud account intrusions)

What: what secret scanning scans and how it reports

Secret scanning Scans the repository the full Git history of all branches, as well as issue descriptions and comments, PR titles/descriptions/comments, Discussions, wikis, secret gists, etc., looking for hardcoded credentials. Runs automatically and free on public repositories; private/internal repositories require Secret Protection. Alerts appear in the repository's Security tab (the new UI calls it "Security and quality").

Detection typeExamplesWhat it producesNotes
Partner program (partner program)AWS, Azure, Slack, npm, etc. tokens in public repositoriesDirectly notifies the service provider, which may automatically revoke it; does not appear in repository alertsApplies automatically to public content; no configuration needed
Provider patterns (provider patterns)GitHub PAT (ghp_/github_pat_), Azure Storage key, Stripe keyRepository alerts (user alerts); high-confidence patterns participate in push protection by defaultThe list of supported types is long; refer to "Supported secret scanning patterns"
Non-provider patterns (generic / non-provider)Private keys (-----BEGIN … PRIVATE KEY-----), connection strings, HTTP Basic authentication headersRepository alerts (separate list; must be enabled by default)Higher false-positive rate
Custom patterns (custom patterns)Internal company tokens acme_[a-z0-9]{32}Alerts; can optionally be included in push protectionDefined at repository/organization/enterprise level, supports dry run; regex can be generated with AI
AI detection (AI detection, formerly Copilot secret scanning)Unstructured passwords password = "S3cr3t!"Alerts; AI detection in push protection is in public previewRenamed in 2026 to "AI detection for alerts / push protection"; third-party reports say the push protection part uses usage-based billing,official sources take precedence

Why: why push protection

Once a secret reaches the remote, even if deleted the next second, it already exists in commit objects, forks, CI caches, mirrors, and other people's clones; tokens in public repositories are exploited by automated crawlers within minutes. Push protection, at git push the server-side stage, rejects ref updates containing secrets, so secrets never enter the repository.

How: the two levels of push protection

User level (push protection for users)Repository level (push protection for repositories)
DefaultFor all GitHub.com accounts Enabled by default, can be disabled in personal Settings → Code securityDisabled by default; enabled by a repository admin, organization owner, security manager, or enterprise owner
ScopeBlocks you from pushing to any public repository supported secretsBlocks anyone from pushing to this repository secrets
After bypassno alert is generated (unless enabled at the repository level too)generates an alert + audit log + email notification
LicenseFreeFree for public repositories; private/internal requires Secret Protection

Covered entry points: command-line push, web commits and file uploads (all four pattern types are supported, including AI detection); REST API content writes (provider, generic, and custom patterns; excluding AI detection); GitHub MCP server (public repositories only).

After being blocked: three bypass reasons and delegated bypass

  • By default, anyone with write access can open the URL in the block message and choose a reason: It's used in tests (the alert is closed as "used in tests"),It's a false positive (closed as "false positive"),I'll fix it later (the alert stays open). Afterward, you must within 3 hours push again. Only the same user who performed the push can open that URL; others get a 404.
  • Delegated bypass (requires Secret Protection): the organization/repository designates "approvers" (roles or teams). Regular contributors can only submit a bypass request (with an explanation); approvers approve or deny in the Security → Push protection bypass requests list; after approval, the contributor pushes again. You can also configure an exemption (exemption), so that specific principals do not trigger push protection when pushing (use with caution).
  • Every bypass: generates a secret scanning alert, writes to the audit log (secret_scanning_push_protection.bypass ) and similar events), and emails the repository admins, organization owners, security managers, and watchers.

Validity checks (validity checks)

Requires Secret Protection. When enabled, GitHub periodically sends detected provider tokens to the partner's validation endpoint, and alerts show Active / Inactive / Unknown, helping prioritize by real risk (handle Active ones immediately). You can also view metadata for some tokens (such as owner and scope, "extended metadata"; see documentation).

Response order after a leak

  1. Rotate/revoke: immediately revoke the credential at the provider and generate a new one, then update Key Vault / Secrets Manager / Actions secrets.
  2. Investigate: review provider audit logs (for example Azure Activity Log, AWS CloudTrail, GitHub security log) to confirm whether it was used during the exposure window.
  3. Close the alert: select Revoked; record a ticket.
  4. (optional) Clean up history: only when compliance requires it, use git filter-repo to rewrite history and force-push, and also contact GitHub Support to clear cached views; rewriting history does not replace rotation, since forks and clones still hold copies.

When: how to roll it out

  • Enable push protection on all repositories (security configuration + enforce); bypass goes through delegated bypass, with approvers being the security team + security champions from each business line.
  • Format internal tokens (with a fixed prefix and checksum, such as acme_), so that low-false-positive custom patterns can be written.
  • Complements local pre-commit tools (such as gitleaks): local checks happen earlier but can be skipped; server-side push protection cannot be skipped by the client.
Common misconceptions① "I'll just delete that line and commit again"—the secret is still in the earlier commit, and push protection will keep blocking the whole push; you must modify the commit that introduced it. ② "Choosing false positive means it's fine"—a bypass leaves alert and audit records that the security team can see. ③ "A leak in a private repository doesn't matter"—insiders, third-party integrations, CI logs, and accidental public exposure all reveal it. ④ "Rewriting history makes it safe"—until rotation happens, the credential stays valid.

Sequence diagram: a push blocked by push protection

Developer gitGitHub receiverSecret scanning engineApprover / security team git push (pack + ref update) scan the newly added blobs/commits match Match: type, commit, path:line GH013 rejection + unblock URL (ref not updated) Open the URL: choose a reason / submit a bypass request delegated bypass: request notifies approvers Approved (or denied / expired) git push again within 3 hours → success Generates alert · audit log · email notification · security overview metrics
Figure 2-1: blocking happens before the ref update; objects may already be uploaded, but no branch points to them, so the commit is not visible in the repository

Decision diagram: response after discovering a leak

Alert / blockValidity: Active? ① Revoke + rotateat the provider ② Investigate usageCloudTrail / activity log ③ Close alertRevoked ④ Rewrite historyonly when compliance requires it The order must not be reversed: rewriting history before rotation leaves the credential valid in the meantime
Figure 2-2 Rotate first

Core animation: the full flow of push protection blocking a secret

Choose the secret type, repository settings, and handling method, then play step by step. The terminal on the right shows the real output you would see at each step (IDs and URLs are examples).

Push content
Repository settings
Developer's choice

Core commands and API

Command / APIPurposeNotes
GET /repos/O/R/secret-scanning/alertsList repository secret alertsstate=open,secret_type,validity=active; the organization-level equivalent is /orgs/O/secret-scanning/alerts
GET …/alerts/N/locationsView where a secret appearscommits, file lines, issue comments, etc.
PATCH …/alerts/NClose alertstate=resolved + resolution: false_positive / wont_fix / revoked / used_in_tests
git commit --amend / git rebase -iRemove the secret from commits that were never successfully pushedfor a secret in the latest commit, use amend; for an earlier commit, use interactive rebase (edit)
git filter-repo --replace-textRewrite pushed historyrequires third-party tools; after force-push, notify all collaborators to re-clone
gh secret setWrite the newly rotated credential into Actions secretsDo not put it in code or workflow files

Typical output when blocked (example; actual format may vary)

remote: error: GH013: Repository rule violations found for refs/heads/main.
remote:
remote: - GITHUB PUSH PROTECTION
remote:   —————————————————————————————————————————
remote:     Resolve the following violations before pushing again
remote:
remote:     - Push cannot contain secrets
remote:
remote:      (?) Learn how to resolve a blocked push
remote:      https://docs.github.com/code-security/secret-scanning/working-with-secret-scanning-and-push-protection/working-with-push-protection-from-the-command-line#resolving-a-blocked-push
remote:
remote:       —— GitHub Fine-grained Personal Access Token ————————
remote:        locations:
remote:          - commit: 8728dbe67
remote:            path: config/settings.py:4
remote:
remote:        (?) To push, remove secret from commit(s) or follow this URL to allow the secret.
remote:        https://github.com/myorg-lab/myapp-sec/security/secret-scanning/unblock-secret/2Xk…
remote:
To https://github.com/myorg-lab/myapp-sec.git
 ! [remote rejected] main -> main (push declined due to repository rule violations)
error: failed to push some refs to 'https://github.com/myorg-lab/myapp-sec.git'

Remove the secret and push again

# Case A: secret is in the latest commit
sed -i '/GITHUB_TOKEN_FOR_DEMO/d' config/settings.py
git commit --amend --all --no-edit
git push

# Case B: secret is in an earlier commit (8728dbe67)
git rebase -i 8728dbe67~1        # change that commit's pick to edit
# remove the secret → git add . → git commit --amend → git rebase --continue
git push

Query and close alerts

gh api "repos/$ORG/$REPO/secret-scanning/alerts?state=open" \
  --jq '.[] | [.number, .secret_type_display_name, .validity, .push_protection_bypassed] | @tsv'
gh api -X PATCH repos/$ORG/$REPO/secret-scanning/alerts/1 \
  -f state=resolved -f resolution=revoked -f resolution_comment="PAT revoked 2026-11-15, INC-1234"
1	GitHub Fine-grained Personal Access Token	inactive	true
{ "number": 1, "state": "resolved", "resolution": "revoked", ... }

Production use: Feed the organization-level alerts API into the SIEM/ticketing system, so validity=active alerts are automatically escalated to P1. Common error: Using git revert to remove the secret does not work: revert adds a new commit, and the original commit is still within the push range, so it is still blocked.

Lab 2: Practice blocking and handling a secret leak (about 8 minutes)

Safety prerequisites The token used for the drill must have: no repository/account permissions, a 1-day validity period, and be revoked immediately after the drill. Do not use any real cloud credentials, and do not use the example keys from AWS documentation (GitHub treats public example values as non-secret and will not trigger).
Generate a one-time token: GitHub → Settings → Developer settings → Fine-grained tokens → Generate new token: name pp-drill, Expiration 1 day, Repository access set to "Public repositories (read-only)", add no permissions. Copy the token (github_pat_…).
Try pushing:
cd myapp-sec
git switch -c drill/leak
mkdir -p config
printf 'GITHUB_TOKEN_FOR_DEMO = "%s"\n' "github_pat_[PASTE_YOUR_ONE_TIME_TOKEN]" > config/settings.py
git add config/settings.py && git commit -m "feat: add settings"
git push -u origin drill/leak

Expected: the push is rejected, with output GH013 and GITHUB PUSH PROTECTION (see the "Commands" page). The GitHub web UI does not show drill/leak the branch.

Experience the bypass flow (without actually bypassing): open the unblock URL in the output, observe the three reason options; if the organization has enabled delegated bypass, the page changes to "Submit bypass request". Do not click allow; just close the page.
Correct handling: rotate first: go back to the Fine-grained tokens page delete it immediately pp-drill (in a real scenario, this step is the revocation and rotation). Then amend the commit:
git rm --cached config/settings.py
printf 'import os\nGITHUB_TOKEN_FOR_DEMO = os.environ.get("DEMO_TOKEN", "")\n' > config/settings.py
echo "config/*.local" >> .gitignore
git add config/settings.py .gitignore
git commit --amend --no-edit
git push -u origin drill/leak
To https://github.com/myorg-lab/myapp-sec.git
 * [new branch]      drill/leak -> drill/leak
Verify and audit:
gh api "repos/$ORG/$REPO/secret-scanning/alerts" --jq 'length'
git log -p origin/drill/leak -- config/settings.py | grep -c github_pat_ || true
0
0

No bypass → no alert; the remote history contains no secret. If you chose bypass in the previous step, you will see an alert and a push protection bypass event in the organization audit log (see Module 6 for the GHEC audit log API).

(requires Secret Protection, optional) Add a custom pattern under organization Settings → Advanced Security → Global settings acme_[a-z0-9]{32}, run a dry run first, then check "Include in push protection"; configure the approval team for delegated bypass security-champions. Free alternative: Locally, use pre-commit + gitleaks custom rules to simulate the same regex.
Cleanup:
git switch main && git push origin --delete drill/leak && git branch -D drill/leak

Case 1: A cloud key in a public repository was exploited within 4 minutes

Problem: A team committed a cloud access key to a personal public repository without push protection; within minutes, scanners exploited it to create crypto-mining instances. Approach: Enable organization-level push protection and enforce it; fully migrate to OIDC federated credentials (Lessons 3/4), so CI no longer stores long-lived keys. Limitations: Push protection only covers supported high-confidence patterns; irregular passwords require AI detection or custom patterns.

Case 2: delegated bypass turns bypassing from "click casually" into "reviewed by someone"

Problem: The weekly security report showed 60 "false positive" bypasses per month; spot checks found half were real secrets. Approach: Enable delegated bypass, with approvers being the security team and security champions from each business line, SLA 4 hours; test fixtures are uniformly placed in tests/fixtures/ and use obviously fake values. Result: Bypasses dropped 80%, and real leaks were blocked. Limitations: Requires Secret Protection; approval delays may affect urgent releases, so an on-call mechanism is needed.

Case 3: Redesigning internal token format

Problem: Internal API keys are 32-character hexadecimal, and custom patterns have a very high false-positive rate. Approach: New tokens are changed to acme_live_ a prefix + Base62 + CRC32 checksum (modeled on GitHub's token format); custom patterns match only the new format and are included in push protection; old tokens are rotated out within 90 days.

Common errors and fixes

remote: error: GH013: Repository rule violations found … Push cannot contain secrets

Cause: A commit in this push contains a supported secret (not necessarily the latest commit).

git log --oneline origin/main..HEAD
git show 8728dbe67 -- config/settings.py

Fix: Locate it using the commit/path in the output, and use amend or rebase to modify the commit that introduced the secret; if the secret is real and valid, revoke it first. Only when it is truly a test value, use bypass and select used in tests.

Accessing the unblock URL returns 404

Cause: Only the user who performed that push can open it; or the validity period has passed.

Fix: Have the pusher open it; after timeout, push again to get a new URL.

Bypass was approved, but re-push is still rejected

Cause: More than 3 hours have passed; or this push contains a different secret; or the pusher is not the approved user.

Fix: Check whether the secret type and location in the output match what was approved; re-request if necessary.

Push protection did not block an obvious password

Cause: By default only high-confidence provider patterns are used; generic patterns, AI detection, and custom patterns must be enabled separately (and require a license), and some types do not support push protection.

Fix: Check the push protection column for that type in "Supported secret scanning patterns"; define custom patterns for internal tokens.

CI bot (GitHub App) push is blocked, pipeline fails

Cause: Automatically generated files contain token-style strings (for example, test snapshots).

Fix: Fix the generator so it avoids producing real-format values; if necessary, add the App to the delegated bypass exemption, and record the reason and review date.

Command-line questions
1. List all active (still unresolved) secret alerts in the organization.
gh api --paginate "orgs/$ORG/secret-scanning/alerts?state=open&validity=active" \
  --jq '.[] | [.repository.full_name, .number, .secret_type_display_name] | @tsv'
2. The secret is in the third-to-last commit; write the Git operation to remove it.
git rebase -i HEAD~3      # change the first line (the earliest commit) pick → edit
# edit the file to remove the secret
git add -A && git commit --amend --no-edit
git rebase --continue
git push
Scenario analysis question
Early-morning alert: an Azure storage account key has been committed in a private repository for 3 days, and the validity check shows Active. What are your response steps?

① Immediately rotate that storage account key in the Azure portal/CLI (az storage account keys renew), and update all consumers (preferably switch to managed identity or OIDC); ② review Azure Storage diagnostic logs and the activity log to determine whether there was any abnormal access in those 3 days; ③ in GitHub, close the alert as Revoked and link it to the incident ticket; ④ assess who can access the repository and whether forks and CI log copies exist; ⑤ post-incident review: enable push protection for the repository (private repositories require Secret Protection), and move this kind of key out of code. Whether to rewrite history depends on compliance requirements, but it is not the first step.

Verified instructional videos

▶
Introduction to secret leaks and getting started with GitHub Secret Protection — GitHub
English · official channel, Secret Protection introduction and push protection demo
▶
GitHub Secret Scanning: Configure Your Push Protection Patterns — Mickey Gousset
English · configuring push protection patterns (per the current UI)

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: in the terminal, git push is entered; the data packet flies toward the GitHub server and is blocked by a red gate showing GH013.
Narration: push protection checks the new content of this push on the server side and, on finding a secret, rejects the branch update.
Shot 2 · 20–45s
Visual: the error message is enlarged, highlighting the secret type, commit number, file line, and unblock link.
Narration: the output tells you which commit, which file and line, and an unblock link valid only for you.
Shot 3 · 45–70s
Visual: the developer submits a bypass request; the security team's phone receives a notification and taps "Approve", while the audit log gets a new line.
Narration: with delegated bypass enabled, bypassing requires approval, and each time it leaves an alert and audit record.
Shot 4 · 70–90s
Visual: large text "Rotate first"; the key is replaced with a new key.
Narration: if a secret has leaked, the first step is always revocation and rotation, and only then investigation and history cleanup.
or score ≥ 70% on the "Quiz"

Module 3 · Code scanning and CodeQL

14:00 – 22:00 · Turn code into a queryable database, and use data flow to find paths where "untrusted input flows into a dangerous function"
8 mingithub/codeql-action v4.39.3Free for public repositoriesPrivate repositories require Code Security★★★★★
Learning objectives
  • Distinguish CodeQL default setup (zero YAML, managed by GitHub) and advanced setup (a workflow in the repository, customizable queries, build, and triggers).
  • Read a CodeQL workflow: init (download the CodeQL bundle, prepare the extractor) → build/extract (build-mode: none / autobuild / manual) → generate database → analyze (run the query suite, generate SARIF, upload).
  • Upload third-party SARIF (category to distinguish multiple analyses), handle alerts in PRs, use Copilot Autofix, triage and dismiss by severity, and use rulesets for merge gating.
Prerequisites: Lesson 2 workflow syntax, Lesson 5 permissions. Importance:★★★★★

What: code scanning and CodeQL

Code scanning is GitHub's static analysis alert platform: any tool that can output SARIF 2.1.0 can upload results here; alerts appear in the Security tab and in PRs. CodeQL is GitHub's own analysis engine: it reads the source (for compiled languages during the build, for interpreted languages directly) extracts the code into a relational database, then runs data flow / taint tracking queries with the QL query language.

CodeQL-supported languages (per the official "Supported languages and frameworks"): C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, Swift, Rust, as well as GitHub Actions workflow (actions, used to find issues such as workflow injection).

Why: why not grep rules

“subprocess.run(cmd, shell=True)” itself is not necessarily dangerous; what is dangerous is cmd data coming from HTTP request parameters and never sanitized along the way. CodeQL, through source → propagation → sink data flow analysis, which raises an alert only when a reachable path exists and shows the full path in the alert; false positives are significantly lower than with pure pattern matching.

How: default setup vs advanced setup

default setupadvanced setup
Configuration methodSettings → Advanced Security → CodeQL analysis → Set up → Default; or security configuration; or APICommit .github/workflows/codeql.yml
Triggerpushes to the default/protected branches, PRs targeting them, weekly scheduled scans (scheduled scanning stops automatically after 6 months with no pushes or PRs, to save minutes)fully customized (push,pull_request,schedule,merge_group , etc.)
languagesAutomatically detects the CodeQL-supported languages in the repository; can be added or removed in the UI; new languages are included automatically once addedexplicitly listed in the matrix
buildFor C/C++, C#, Java, Rust, use build-mode: none (no build needed); for other compiled languages use autobuildoptional none / autobuild / manual (write your own build steps)
query suiteDefault or ExtendedAny: security-extended,security-and-quality, custom qlpack / query files
runnerGitHub-hosted, or with code-scanning label self-hosted/larger runnersany
Prerequisitesrepository has Actions enabled; public or with Code Security enabledsame as left; mutually exclusive with default setup

Query suites

  • default (code-scanning suite): high-precision, high-severity security queries with the fewest false positives.
  • security-extended: builds on default by adding security queries with slightly lower precision or severity, producing more alerts.
  • security-and-quality: adds maintainability/reliability queries too (code quality is now also available as a separate GitHub Code Quality product, per documentation).

Two severity levels for alerts

Security queries have security severity security severity (Critical / High / Medium / Low, based on CVSS-style scores); all queries have severity a standard severity (Error / Warning / Note). PR check failure and ruleset gate thresholds are configured based on these.

Alerts in PRs and Copilot Autofix

  • PRs show a "CodeQL" check and a "Code scanning results" summary; newly introduced alerts appear as inline comments appear in Files changed, reporting only new issues near lines changed in the PR.
  • Copilot Autofix: generates fix suggestions and explanations for supported alerts, shown inline in the PR and on the alert details page; can also generate fixes for existing alerts on the default branch. No Copilot subscription is required; enabled by default for repositories using CodeQL, and can be turned off at enterprise/organization/repository level. Supports some queries for C#, C/C++, Go, Java/Kotlin, Swift, JavaScript/TypeScript, Python, Ruby, Rust. Suggestions are non-deterministic and must be reviewed manually, especially when they add or upgrade dependencies. Use in private repositories requires Code Security.
  • Alert severity and dismissal: dismissal reasons are False positive,Used in tests,Won't fix, with an optional comment; a dismissed state persists for the same fingerprint. Organizations can enable "alert dismissal requires approval" (delegated alert dismissal, requires Code Security).
  • Merge gate: in the ruleset, the Require code scanning results rule—specifies required tools (such as CodeQL) and severity thresholds; merging is blocked when a required tool finds alerts at or above the threshold, when analysis is still in progress, or when it is not configured.

When: selection guidance

  • 90% of repositories: default setup, enabled uniformly via security configuration.
  • Needs a custom build (private dependencies, special compile flags), custom query packs, path-based scanning for a monorepo, or to run on merge_group self-hosted runners: advanced setup.
  • If you already have Semgrep/Trivy/Checkov or similar tools: keep using them, upload SARIF output, and unify triage and gating within code scanning.
Common misconceptions① "CodeQL finds all vulnerabilities"—it finds data-flow issues matching known patterns; business logic flaws and misconfigurations are not found. ② "No alerts in a PR means the code is secure"—a PR only shows newly introduced alerts; existing alerts are on the Security tab. ③ "Code generated by Autofix can be merged directly"—it must be manually reviewed and tested. ④ "Default setup and advanced setup can be enabled at the same time"—they are mutually exclusive; after enabling default setup, uploads from an advanced workflow will be rejected or conflict.

Architecture diagram: from source code to alerts in CodeQL

Source codecheckout initCodeQL bundleLanguages · queries · configuration extractnone / autobuild/ manual build CodeQL databaseAST · control flowData flow relations analyzeQuery suite→ SARIF Code scanning API (/code-scanning/sarifs)Deduplicate by tool + category + fingerprint / close fixed alerts AlertsSecurity tab · PR comments · checks Copilot Autofix suggestions Ruleset: Require code scanning results Third-party SARIFTrivy · Semgrep · Checkov
Figure 3-1: CodeQL and third-party tools both feed into the same code scanning API

Data flow illustration: source → sink

sourcerequest.args["host"] propagationcmd = f"ping -c1 {host}" sinksubprocess.run(cmd, shell=True) alertpy/command-line-injection If the path passes through sanitization (such as an argument list + validation that the value is a legal hostname), the path breaks and no alert is raised
Figure 3-2: the vulnerability introduced and fixed in this module's lab

Core animation: CodeQL from database build to PR alert

Choose the language and build mode, the query suite, and the code version in the PR, then step through each step of the CodeQL workflow. Logs are illustrative (imitating the Actions log format).

Language / build mode
Query suite
Code in PR

Core commands and API

Command / APIPurposeNotes
PATCH /repos/O/R/code-scanning/default-setupEnable/disable default setupstate=configured|not-configured,query_suite=default|extended
GET /repos/O/R/code-scanning/alertsList alertsstate,severity,tool_name,ref=refs/pull/N/merge
PATCH …/alerts/NDismiss/reopenstate=dismissed + dismissed_reason: false positive / won't fix / used in tests
GET /repos/O/R/code-scanning/analysesView each analysis (tool, category, result count)Investigate "why are there no alerts"
github/codeql-action/upload-sarif@v4Upload third-party SARIFcategory Distinguish multiple analyses of the same tool
codeql database create / analyzeRun the CodeQL CLI locally or in another CIUsing the CLI on private repositories also requires a Code Security license

Enable default setup and check status

gh api -X PATCH repos/$ORG/$REPO/code-scanning/default-setup \
  -f state=configured -f query_suite=default
gh api repos/$ORG/$REPO/code-scanning/default-setup
{"run_id":123456789,"run_url":"https://api.github.com/repos/myorg-lab/myapp-sec/actions/runs/123456789"}
{"state":"configured","languages":["actions","python"],"query_suite":"default","updated_at":"2026-11-15T09:12:44Z","schedule":"weekly"}

Advanced setup: CodeQL workflow

name: CodeQL
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: "27 3 * * 1"          # every Monday 03:27 UTC
permissions:
  contents: read
jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    runs-on: ubuntu-latest
    permissions:
      security-events: write      # upload SARIF
      contents: read
      actions: read               # required for private repositories
    strategy:
      fail-fast: false
      matrix:
        include:
          - language: python
            build-mode: none
          - language: actions
            build-mode: none
    steps:
      - uses: actions/checkout@v7.0.1
      - uses: github/codeql-action/init@v4      # in production, pin by SHA (v4.39.3, verified 2026-11)
        with:
          languages: ${{ matrix.language }}
          build-mode: ${{ matrix.build-mode }}
          queries: security-extended
      - uses: github/codeql-action/analyze@v4
        with:
          category: "/language:${{ matrix.language }}"

For compiled languages, use build-mode: manual ; when using it, add your own build steps between init and analyze (such as make,mvn -B package -DskipTests). Before switching to advanced setup, disable default setup in the UI first.

Upload third-party SARIF (using a Trivy filesystem scan as an example)

      - name: Trivy FS scan
        run: |
          docker run --rm -v "$PWD:/src" aquasec/trivy:latest fs --scanners vuln,misconfig \
            --format sarif --output /src/trivy.sarif /src
      - uses: github/codeql-action/upload-sarif@v4
        with:
          sarif_file: trivy.sarif
          category: trivy-fs

SARIF limits (docs, 2026-11): a single file ≤ 10 MB after gzip; ≤ 20 runs per file; ≤ 25,000 results per run, with only the top 5,000 displayed, sorted by severity. Results need a stable ruleId and partialFingerprints, otherwise duplicate alerts will be generated. In the example, the mirror tag uses latest is for demonstration only; in production, pin the version or digest.

Query and dismiss alerts

gh api "repos/$ORG/$REPO/code-scanning/alerts?state=open" \
  --jq '.[] | [.number, .rule.id, .rule.security_severity_level, .most_recent_instance.location.path] | @tsv'
gh api -X PATCH repos/$ORG/$REPO/code-scanning/alerts/3 \
  -f state=dismissed -f dismissed_reason="used in tests" -f dismissed_comment="fixture only"
1	py/command-line-injection	critical	app.py
3	py/flask-debug	high	tests/conftest.py

Lab 3: default setup + introduce and fix a command injection (about 10 minutes)

Enable CodeQL default setup: run the default-setup command on the "Commands" page (or in the UI: Settings → Advanced Security → CodeQL analysis → Set up → Default → Enable CodeQL). In Actions you will see a dynamic workflow run named "CodeQL" (the file is not in the repository). Wait for it to finish (Python takes about 2–4 minutes).
Introduce a vulnerability on a branch:
git switch -c feat/ping
cat >> app.py <<'EOF'

import subprocess
from flask import request

@app.get("/ping")
def ping():
    host = request.args.get("host", "127.0.0.1")
    out = subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True, text=True)
    return jsonify(output=out.stdout)
EOF
git commit -am "feat: add /ping diagnostics" && git push -u origin feat/ping
gh pr create --fill --base main
Observe the PR: a few minutes later the PR checks show "CodeQL" and "Code scanning results", and in Files changed subprocess.run a line has the comment "Uncontrolled command line" (py/command-line-injection), and clicking it shows the path from request.args.get to subprocess.run . If Copilot Autofix is available, "Generate fix" / a suggested fix will appear.
PR=$(gh pr view --json number -q .number)
gh api "repos/$ORG/$REPO/code-scanning/alerts?ref=refs/pull/$PR/merge&state=open" --jq '.[] | [.rule.id, .rule.security_severity_level] | @tsv'
py/command-line-injection	critical
Fix (you can refer to the Autofix suggestion, but review it yourself):
import ipaddress, subprocess
from flask import request, abort

@app.get("/ping")
def ping():
    host = request.args.get("host", "127.0.0.1")
    try:
        ip = str(ipaddress.ip_address(host))      # accept only valid IPs
    except ValueError:
        abort(400, "host must be an IP address")
    out = subprocess.run(["ping", "-c", "1", ip], capture_output=True, text=True, timeout=5)
    return jsonify(output=out.stdout)
git commit -am "fix: avoid shell injection in /ping" && git push

After re-analysis, the alert in the PR is marked Fixed and the check passes.

(Optional) add a merge gate: repository Settings → Rules → Rulesets → New branch ruleset → target main → check Require code scanning results, select CodeQL as the tool, and set the Security alerts threshold to "High or higher". Public repositories on the Free plan can also use repository-level rulesets.
Merge and clean up:
gh pr merge --squash --delete-branch

Case 1: CodeQL coverage for 600 repositories in one week

Problem: Each team handwrote CodeQL workflows with mixed versions (v2/v3 coexisting), and half the repositories had no scanning. Approach: Enabled default setup on all repositories via a security configuration; kept advanced setup only for the 12 C++/Java repositories that need custom builds, and unified them with a template (referencing the reusable workflow from Lesson 5). Result: 100% coverage, with significantly lower maintenance cost. Limitations: Repositories where default setup fails need their logs checked one by one (mostly private dependencies that cannot be fetched).

Case 2: unify multi-tool results with SARIF

Problem: The team uses Semgrep, Checkov, and Trivy at the same time, with results scattered across three consoles. Approach: All three output SARIF, uploaded with different category ; the ruleset requires CodeQL and Checkov to have no High-or-above alerts before merge. Limitations: SARIF has size and result-count limits; changes in third-party tool rule IDs cause duplicate alerts.

Case 3: Autofix introduced a nonexistent dependency

Problem: A developer accepted an Autofix suggestion directly, which added a package name with a similar spelling. Approach: The dependency review gate (Module 4) caught the new dependency; the team now requires a second person to review Autofix suggestions, and dependency changes must verify the package source. Lesson: The official documentation explicitly notes that Autofix may suggest nonexistent or insecure dependencies.

Common errors and fixes

Error: Resource not accessible by integration (when uploading SARIF)

Cause: The job lacks security-events: write; or the PR comes from a fork (read-only token).

Fix: In the job permissions add security-events: write; analysis for fork PRs is handled by GitHub's default setup; with advanced setup, uploads from fork PRs are restricted, which is expected.

CodeQL detected code written in Java/Kotlin but could not process any of it / autobuild failed

Cause: Autobuild failed, or the extractor did not see the compilation process.

gh run view RUN_ID --log | grep -iE "autobuild|extract|error" | head -40

Fix: First try build-mode: none (supported for Java, C#, C/C++, Rust); if that does not work, change to manual and write out the build commands; configure private package repository credentials.

Code scanning could not process the submitted SARIF file: … default setup is enabled

Cause: The repository has default setup enabled and also has an advanced CodeQL workflow uploading results.

Fix: Choose one: disable default setup and keep the workflow, or delete the workflow.

PR checks keep showing "Waiting for Code Scanning results"

Cause: The ruleset requires a tool, but that tool did not run on this PR (path filter, workflow not triggered, analysis failed).

Fix: Confirm the workflow triggers on pull_request and has no paths exclusion; check /code-scanning/analyses?ref=refs/pull/N/merge.

The same problem keeps recurring with new alert numbers

Cause: Third-party SARIF lacks a stable partialFingerprints, or the file path/ruleId changes every time; or the category changes.

Fix: Use upload-sarif (it attempts to compute fingerprints); fix the category; keep paths relative to the repository root.

Command-line questions
1. Switch the repository's CodeQL default setup to the extended query suite.
gh api -X PATCH repos/O/R/code-scanning/default-setup -f state=configured -f query_suite=extended
2. List the tool name, category, and result count of the last 5 analyses.
gh api "repos/O/R/code-scanning/analyses?per_page=5" --jq '.[] | [.tool.name, .category, .results_count, .created_at] | @tsv'
Scenario analysis question
A C++ repository uses a private build system and default setup analysis fails; the team wants to abandon CodeQL. What is your recommendation?

First try the default setup's build-mode: none (C/C++ already supports build-less extraction; coverage may be slightly lower); if the results are insufficient, switch to the advanced setup's manual mode, calling the private build script between init and analyze (it can run on a self-hosted runner to access internal dependencies, with label code-scanning or a custom label); for repositories with long compile times, run only on PRs and the weekly schedule. You can also introduce third-party tools to supplement via SARIF.

Verified instructional videos

▶
What is code scanning? — GitHub
English · official channel, introduction to code scanning concepts
▶
Code fixes in minutes, not months | Copilot Autofix — GitHub
English · official channel, Copilot Autofix demo

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: source code files flow into an "extractor" funnel and turn into a database table icon.
Narration: CodeQL first extracts the code into a database, which contains the syntax tree, control flow, and data flow.
Shot 2 · 20–45s
Visual: a red dot starts at request.args and flows along arrows to subprocess.run.
Narration: the query tracks untrusted input; as long as it can reach a dangerous function, it generates an alert and draws the full path.
Shot 3 · 45–70s
Visual: inline alert comments appear on the PR page, with an Autofix suggested diff popping up beside them.
Narration: alerts show up in the PR, Copilot Autofix offers a fix suggestion, but it must be reviewed manually.
Shot 4 · 70–90s
Visual: the merge button is locked by the ruleset and turns green after the fix.
Narration: use a ruleset to require code scanning results; high-severity unresolved alerts block the merge.
or score ≥ 70% on the "Quiz"

Module 4 · Dependabot and dependency review

22:00 – 30:00 · The dependency graph knows what you use, the Advisory Database knows what is problematic, Dependabot opens PRs, and dependency review blocks issues before merge
8 minDependabot is entirely freedependency-review-action v5.0.0Dependency review on private repositories requires Code Security★★★★★
Learning objectives
  • Distinguish dependency graph,Dependabot alerts,security updates,version updates and dependency review five concepts and their triggers.
  • Write .github/dependabot.yml: multiple ecosystems (pip, docker,github-actions),groups grouping,cooldown cooldown period,schedule,ignore.
  • Use actions/dependency-review-action@v5 as PR gates (severity, licenses), and use auto-triage rules to reduce alert noise.
Prerequisites: Package managers and lockfile concepts; pinning Actions by SHA from Lesson 5. Importance:★★★★★

What: five easily confused concepts

FeatureWhat it doesTriggerLicense
dependency graph (dependency graph)Parses manifests and lockfiles (plus build-time dependencies submitted via the Dependency submission API), lists direct/transitive dependencies, and can export an SPDX SBOMPushed to the default branchFree; enabled by default on public repositories
Dependabot alertsMatches the dependency graph with GitHub Advisory Database advisories, generating vulnerability alerts (including malicious package alerts)dependency change, or new advisory publishedFree
Dependabot security updatesAutomatically opens PRs for alerts, upgrading to the lowest fixed versionWhen an alert is generatedFree
Dependabot version updatesUpgrades dependencies to the latest version on a schedule (unrelated to vulnerabilities)dependabot.yml schedule inFree
dependency review (dependency review)Compares dependency differences between the base and head branches in a PR, showing vulnerabilities and licenses of newly added dependencies; used as a gate together with the actionPRFree for public repositories; private requires Code Security

Why: why a gate is needed, not just alerts

Alerts are "after the fact": the vulnerable dependency is already on the default branch. Dependency review moves the check forward to the PR,blocks newly added dependencies that are vulnerable or have non-compliant licenses; Dependabot handles cleaning up existing items. The two together form a closed loop.

How: key fields in dependabot.yml

  • version: 2; updates one per item in package-ecosystem (such as pip,npm,docker,github-actions,terraform), plus directory/directories. For GitHub Actions, the directory is written as / (Dependabot looks in .github/workflows).
  • schedule.interval: daily / weekly / monthly / quarterly / semiannually / yearly / cron.
  • groups: merge multiple updates into a single PR; can group by patterns/exclude-patterns,dependency-type (development/production),update-types (major/minor/patch) grouping; applies-to: security-updates to apply groups to security updates too. Also a cross-ecosystem multi-ecosystem-groups groups.
  • cooldown cooldown: wait a number of days after a new version is released before opening PRs (default-days,semver-major-days etc.), reducing the supply chain risk of "poisoned right after release". The docs note that version updates have a default 3-day cooldown, and security updates are not affected by cooldown.
  • open-pull-requests-limit (version updates default to 5),ignore,allow,labels,assignees,target-branch,registries (private registries).

Auto-triage rules

  • GitHub built-in (all repositories): "Dismiss low impact issues for development-scoped dependencies" (low-impact alerts for specific CWE categories in npm development dependencies; enabled by default on public repositories), "Dismiss package malware alerts" (disabled by default; used for false positives caused by internal packages with the same name).
  • Custom rules: automatically dismiss or snooze alerts (snooze until a patch is available) based on metadata such as severity, package name, CWE, and scope (see documentation for available conditions), or specify which alerts Dependabot automatically opens PRs for. Free for public repositories; private repositories require an organization repository + Code Security.

dependency-review-action (v5.0.0, 2026-05)

  • Breaking changes in v5: the runtime is upgraded from Node 20 to Node 24, requiring Actions Runner ≥ v2.327.1 (self-hosted runners must be upgraded).
  • Common inputs: fail-on-severity (low/moderate/high/critical),fail-on-scopes,allow-licenses (an allow list is recommended; the deny list was deprecated in v4.7.2),allow-ghsas,comment-summary-in-pr,show-openssf-scorecard,show_patched_versions (added in v4.9.0),config-file.

When: recommended combinations

  • All repositories: alerts + security updates (enabled uniformly via security configuration).
  • Active repositories: version updates, run weekly, group minor/patch, separate PRs for major, enable cooldown. Must include github-actions ecosystem: it updates Action versions in workflows (when pinned by SHA, it also updates the SHA and the version comment).
  • Protected branches: dependency review as a required check (ruleset required status check), threshold high, license allow list.

Comparison with similar tools

DependabotRenovateSnyk / Mend
HostedGitHub built-in, freeSelf-hosted or Mend-hosted AppCommercial SaaS
Configuration capabilitySufficient; grouping and cooldown are now coveredVery flexible (regex managers, merge policies)policies, reachability analysis
Vulnerability databaseGitHub Advisory Database (with community review)OSV, etc.Own vulnerability database
Common misconceptions① "Having version updates enabled means you don't need security updates"—version updates are bound by the schedule and PR limits, while security updates trigger immediately when an alert appears and are not affected by cooldown. ② "If Dependabot opened no PRs, there are no vulnerabilities"—this may be because there is no fixed version, the dependency graph cannot resolve it (for example, only setup.py dynamic dependencies), the PR limit is full, or it was paused due to long-term inactivity. ③ "Dependency review scans all dependencies"—it only looks at dependencies added or changed in this PR.

Architecture diagram: dependency security closed loop

Manifest / lockfilerequirements.txt · Dockerfile Dependency graphdirect + transitive · SBOM matchesGitHub Advisory Databaseadvisories (GHSA / CVE / malicious packages) alertauto-triage securityupdate PR version updatesdependabot.yml schedule · groups · cooldown PR: dependency review (dependency-review-action)Vulnerabilities in newly added dependencies ≥ threshold, or license not on the allow list → check fails ruleset required status check → merge → dependency graph updates → alerts close automatically
Figure 4-1: alerts clean up the existing backlog; gates prevent new additions

Interactive simulator: alert matching and PR gating

Choose the dependency version modified in the PR and the gate threshold, and observe the dependency graph → Advisory Database matching → gate decision → Dependabot behavior. The advisory data is illustrative (the actual content of the Advisory Database takes precedence).

Dependencies in PR
fail-on-severity
License allow list

Core configuration and commands

Command / APIPurposeNotes
GET /repos/O/R/dependabot/alertsList alertsstate,severity,ecosystem,scope; organization level /orgs/O/dependabot/alerts
PATCH …/dependabot/alerts/Ndismiss alertsdismissed_reason: fix_started / inaccurate / no_bandwidth / not_used / tolerable_risk
GET /repos/O/R/dependency-graph/compare/BASE...HEADDependency review API (called by the action under the hood)Returns added/removed dependencies and vulnerabilities
GET /repos/O/R/dependency-graph/sbomExport SPDX SBOMCompliance delivery
@dependabot rebase / recreate / ignore this major versionPR comment commandsInteract with Dependabot PRs
version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
      time: "06:00"
      timezone: "America/Toronto"
    open-pull-requests-limit: 5
    cooldown:
      default-days: 3
      semver-major-days: 14
    groups:
      python-minor-patch:
        update-types: ["minor", "patch"]
    labels: ["dependencies", "python"]

  - package-ecosystem: "github-actions"
    directory: "/"                     # scan .github/workflows
    schedule:
      interval: "weekly"
    groups:
      actions:
        patterns: ["*"]

  - package-ecosystem: "docker"
    directory: "/"
    schedule:
      interval: "weekly"
name: Dependency review
on:
  pull_request:
    branches: [main]
permissions:
  contents: read
  pull-requests: write          # write PR summary comment
jobs:
  dependency-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7.0.1
      - uses: actions/dependency-review-action@v5   # v5.0.0: node24, runner ≥ 2.327.1; in production pin by SHA
        with:
          fail-on-severity: moderate
          allow-licenses: Apache-2.0, MIT, BSD-2-Clause, BSD-3-Clause, ISC, PSF-2.0
          comment-summary-in-pr: on-failure
          show-openssf-scorecard: true
gh api "repos/$ORG/$REPO/dependabot/alerts?state=open" \
  --jq '.[] | [.number, .dependency.package.name, .security_advisory.ghsa_id, .security_vulnerability.severity, .security_vulnerability.first_patched_version.identifier] | @tsv'
4	requests	GHSA-x84v-xcm2-53pg	high	2.20.0
3	requests	GHSA-j8r2-6x86-q33q	moderate	2.31.0
2	requests	GHSA-9wx4-h78v-vm56	moderate	2.32.0
1	requests	GHSA-9hjg-9r4m-mvj7	moderate	2.32.4

GHSA IDs and fixed versions are examples; use what the API actually returns. Common error: The dependency review workflow uses pull_request_target triggers — not needed, and not safe; pull_request is sufficient.

Lab 4: introduce a vulnerable dependency → gate blocks it → Dependabot fixes it (about 10 minutes)

Commit dependabot.yml and the dependency review workflow (contents on the "Commands" page) to main:
git switch main && git pull
mkdir -p .github/workflows
# write .github/dependabot.yml and .github/workflows/dependency-review.yml
git add .github && git commit -m "ci: dependabot + dependency review" && git push

A few minutes later, under Insights → Dependency graph → Dependabot, you can see the latest check time for each ecosystem; github-actions the ecosystem may immediately propose an Action upgrade PR.

Introduce an old vulnerable version in a PR:
git switch -c chore/add-requests
echo "requests==2.19.1" >> requirements.txt
git commit -am "chore: add requests" && git push -u origin chore/add-requests
gh pr create --fill --base main
gh pr checks --watch
X  dependency-review   Dependency review   1m2s
✓  CodeQL              ...

The PR comment shows the dependency review summary, listing several advisories for requests 2.19.1 (including CVE-2018-18074). In Files changed requirements.txt next to it there is a "Display the rich diff" dependency view.

After the fix, it passes:
sed -i 's/^requests==2.19.1$/requests==2.32.5/' requirements.txt
git commit -am "chore: use patched requests" && git push
gh pr checks --watch && gh pr merge --squash --delete-branch

Use the latest patch version on PyPI at the time as the version number.

Try a Dependabot security update: to see the alert and automatic PR, commit the old version directly to main (only for the practice repository; in production, do not bypass the gate):
git switch main && git pull
sed -i 's/^requests==.*/requests==2.19.1/' requirements.txt
git commit -am "test: pin vulnerable requests for Dependabot drill" && git push
sleep 120; gh api "repos/$ORG/$REPO/dependabot/alerts?state=open" --jq 'length'
gh pr list --author "app/dependabot"
4
#12  Bump requests from 2.19.1 to 2.32.5   dependabot/pip/requests-2.32.5

If the repository already has a ruleset requiring PRs, direct pushes will be rejected — which shows the gate works; instead, merge temporarily via a PR. After merging the Dependabot PR, the alert automatically becomes Fixed.

auto-triage: Settings → Advanced Security → Dependabot → Dependabot rules, view the GitHub built-in rules; create a new custom rule (free for public repositories): severity:low scope:development → Dismiss.

Case 1: Dependabot PR flood

Problem: A monorepo received 40 Dependabot PRs every week, and developers started ignoring them. Approach: Use directories + groups to merge minor/patch into one PR per ecosystem, with major separate; enable a 7-day cooldown; pair with CI auto-merge for patch-level updates (requires all tests green + ruleset). Result: 3–5 PRs per week; merge rate rose from 20% to 90%.

Case 2: Using the github-actions ecosystem to handle an Action supply-chain incident

Problem: In the 2025-03 tj-actions/changed-files incident (CVE-2025-30066), repositories that referenced floating tags were affected. Approach: All workflows pinned by SHA (Lesson 5), and the Dependabot github-actions ecosystem is responsible for proposing weekly SHA upgrade PRs (with version comments), and uses cooldown to avoid pulling a tampered new version immediately. Limitations: Even after pinning by SHA, the diff of upgrade PRs still needs to be reviewed.

Case 3: License compliance gate

Problem: Legal requires that no AGPL dependencies be introduced into commercial products. Approach: Dependency review allow-licenses allow list + ruleset required check; for a small number of packages approved by legal, use allow-dependencies-licenses exceptions. Limitations: License information comes from package metadata, which may be inaccurate or missing (unknown), so a manual review process is needed.

Common errors and fixes

Dependency review is not supported on this repository. Please ensure that Dependency graph is enabled …

Cause: The private repository does not have the dependency graph enabled, or Code Security is not purchased.

Fix: Enable the dependency graph; purchase Code Security for private repositories; or switch to a public practice repository.

Dependabot did not create a security update PR

Cause: No fixed version is available; the fixed version conflicts with other dependency constraints (Dependabot shows the error in the alert); the PR limit is full; the repository was automatically paused due to long-term neglect of Dependabot PRs; security updates are not enabled.

gh api repos/O/R --jq .security_and_analysis.dependabot_security_updates
gh api "repos/O/R/dependabot/alerts/N" --jq '.security_vulnerability.first_patched_version'

Fix: Check the most recent run log under Insights → Dependency graph → Dependabot; interacting with Dependabot PRs (merge/close/change config) can lift the pause.

Dependabot couldn't authenticate with a private registry

Cause:registries Not configured, or credentials are stored in Actions secrets instead of Dependabot secrets.

Fix: Add them under Settings → Secrets and variables → Dependabot, and in registries reference them in ${{secrets.NAME}}.

dependency-review-action v5 reports an error on self-hosted runners: requires runner version 2.327.1 or later (or node24 is unavailable)

Cause: v5 runs on Node 24 and requires runner ≥ v2.327.1.

Fix: Upgrade self-hosted runners / ARC images; temporarily pin to v4.9.0 (Node 20 is approaching end of support, so long-term use is not recommended).

Dependabot PR workflows cannot access secrets; tests fail

Cause: Runs triggered by Dependabot pull_request/push can only access Dependabot secrets,GITHUB_TOKEN and the GITHUB_TOKEN defaults to read-only.

Fix: Add the secrets the tests need to Dependabot secrets as well; do not switch to pull_request_target to "solve" this problem (Lesson 5).

Command-line questions
1. List all open Dependabot alerts of critical severity in the organization.
gh api --paginate "orgs/$ORG/dependabot/alerts?state=open&severity=critical" \
  --jq '.[] | [.repository.full_name, .dependency.package.name, .security_advisory.ghsa_id] | @tsv'
2. Dismiss alert #7 in the repository with the reason "not used".
gh api -X PATCH repos/O/R/dependabot/alerts/7 -f state=dismissed -f dismissed_reason=not_used -f dismissed_comment="optional extra not installed"
Scenario analysis question
The security team requires that "any PR that introduces a dependency with a high-or-above vulnerability must not be merged; existing vulnerabilities must be fixed within 30 days." Please design a plan.

Incremental: the dependency review workflow (fail-on-severity: high) as a required status check in an organization ruleset (or deploy uniformly via required workflows / the ruleset "Require workflows"; see Lesson 5 and Module 6). Existing: enable alerts + security updates uniformly via security configuration; auto-triage rules automatically dismiss low-severity alerts in the dev scope to reduce noise; use security overview / the organization alerts API to generate a weekly report of open alerts created > 30 days ago; where necessary, use security campaigns (requires Code Security) to fix them centrally.

Verified instructional videos

▶
How to fix vulnerabilities automatically with Dependabot — GitHub
English · official channel, demo of alerts and security updates
▶
Security in 60 Seconds: Vulnerability Prioritization with Dependabot — GitHub
English · official short video, alert priority
▶
Use Dependabot Version Updates to Update Your GitHub Actions — Mickey Gousset
English · version updates for the github-actions ecosystem

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: requirements.txt expands into a dependency tree.
Narration: the dependency graph parses your manifest files, knowing which packages you use directly and indirectly.
Shot 2 · 20–45s
Visual: the Advisory Database adds a new advisory; a node in the tree turns red, an alert pops up, and then an upgrade PR appears.
Narration: as soon as a new advisory is published, Dependabot matches it, raises an alert, and automatically proposes a PR upgrading to the fixed version.
Shot 3 · 45–70s
Visual: the developer's PR tries to add an old version; the check turns red, and a comment lists the vulnerabilities.
Narration: dependency review compares dependency changes before merge, blocking newly added packages that are vulnerable or have non-compliant licenses.
Shot 4 · 70–90s
Visual: groups and cooldown in dependabot.yml are highlighted; the PR count goes from a pile down to three.
Narration: use groups and cooldown periods to keep update PRs few and focused.
or score ≥ 70% on the "Quiz"

Module 5 · Organizations and enterprises: SSO, EMU, team sync

30:00 – 38:00 · Identity is the root of governance: who can sign in, with which credentials, how quickly access is revoked when someone leaves, and where data is stored
8 minRequires GitHub Enterprise CloudEMU OIDC is Entra ID only★★★★☆
Learning objectives
  • Compare three enterprise identity models: personal account + organization-level SAML SSO, personal account + enterprise-level SAML SSO,Enterprise Managed Users (EMU).
  • Explain why, under SAML SSO, PATs (classic), SSH keys, and OAuth/GitHub Apps need to be "authorized for the organization", and be able to diagnose Resource protected by organization SAML enforcement 403.
  • Describe EMU's SCIM provisioning, OIDC + conditional access policies (CAP), team sync / IdP group mapping, and GHE.com data residency regions and limitations.
Prerequisites: Basic concepts of SAML 2.0, OIDC, and SCIM. Importance:★★★★☆

What: three identity models

Organization-level SAML SSOEnterprise-level SAML SSOEnterprise Managed Users (EMU)
Account ownershipThe user's own GitHub personal account, linked to an external identity via SAMLA managed account created and owned by the enterprise through the IdP managed account (the username is generated from the IdP identifier, normalized, with an enterprise short-code suffix, such as alice_acme)
AuthenticationAccessing the organization's resources requires a valid SAML sessionAccessing all organization resources within the enterprise requiresSign-in only through the IdP: SAML (Entra ID, Okta, PingFederate) or OIDC (Entra ID only)
Provisioning/deprovisioningManual invitation; optional SCIM (some IdPs)Same as leftSCIM required: the IdP creates, updates, and deactivates accounts; deactivation removes access
Team membersTeam sync (Entra ID, Okta)Same as leftIdP groups connected to GitHub teams (SCIM groups)
Public activityUnrestrictedUnrestrictedCannot create public content, cannot collaborate outside the enterprise; cannot change profile name and email
AppliesSmall pilotsMost enterprisesEnterprises with strict compliance and full control over the lifecycle; GHE.com data residency requires EMU

Why: why SSO is not enough

SAML SSO only controls browser sessions and whether credentials are authorized to access the organization; the personal account still belongs to the employee, and after they leave the account still exists (it only loses organization access). EMU lets the enterprise own the whole account lifecycle, and in OIDC mode GitHub validates access against Entra ID's conditional access policies (such as IP ranges and device compliance) at access time; both tokens and sessions are governed by CAP.

How: credential authorization under SAML SSO

  • Web session: when accessing protected organization resources, redirect to the IdP; the SAML session is valid for 24 hours by default (the IdP can specify otherwise).
  • PATs (classic) and SSH keys: you must click Configure SSO → Authorize for each token/key in Settings → Developer settings / SSH keys (requires an active SAML session at that time). Without authorization, the API returns 403 and Git operations are refused.
  • Fine-grained PAT: when the resource owner is an organization, it is controlled by the organization's PAT policy (can require approval, limit maximum lifetime); for SAML interaction details, follow the official documentation.
  • OAuth App / GitHub App (user authorization): authorization requires an active SSO session; after SSO is enabled, re-authorization is required. gh The CLI is an OAuth App,gh auth login and the web flow prompts for organization authorization.
  • Organization owners can view/revoke a member's linked identity and authorized credentials under People → Members → SAML identity (API: GET /orgs/O/credential-authorizations).

Team synchronization

Non-EMU GHEC organizations using SAML SSO with Entra ID or Okta can link GitHub teams to IdP groups: IdP group membership changes sync as team membership changes (non-organization members are not automatically invited). In EMU, groups are pushed via SCIM and connected in team settings via "Connect to IdP group".

Data residency: GitHub Enterprise Cloud with data residency (GHE.com)

  • The enterprise runs on a dedicated subdomain SUBDOMAIN.ghe.com (API: api.SUBDOMAIN.ghe.com), and code and data are stored in the selected region.
  • Available regions (docs, 2026-11): EU (including the Azure region in EFTA countries, currently Norway and Switzerland),Australia,US,Japan.
  • EMU is required; there are no public repositories (use internal instead); the IP ranges and SSH fingerprints differ from github.com; some features (including some Copilot features) are not yet available—check the feature list item by item before migrating.

When: how to choose

  • Employees need to participate in open source and contribute using personal accounts: enterprise-level SAML SSO + team sync.
  • Regulated industries, requiring full IdP control, prohibiting public activity: EMU (prefer OIDC + CAP for Entra ID users); open source contributions use separate personal accounts.
  • Data sovereignty requirements (for example, EU, Australia): GHE.com + EMU.
  • Note: existing enterprises moving from the personal account model to EMU need to create a new EMU enterprise and migrate repositories (GitHub Enterprise Importer); they cannot be converted in place.
Common misconceptions① "With SSO enabled, a departed employee's PAT is automatically invalid"—in SAML mode you must remove them in the IdP and revoke their SAML identity/credential authorization; combined with SCIM this can be automated; in EMU, disabling the IdP account suspends the managed account. ② "EMU supports OIDC with any IdP"—OIDC only supports Entra ID; Okta and Entra cannot be mixed for SSO and SCIM. ③ "GHE.com is just a different domain"—features, networking, and integrations all differ.

Flowchart: how an API request with SAML SSO is judged

RequestPAT / SSH / OAuth Resource belongs toan organization with SAML enabled? Yes credential already authorized for the organizationSSO authorization? Yes permissions / scopesrepository role 200 No 403 Resource protected by organization SAML enforcement(the response header X-GitHub-SSO provides the authorization URL) No Judged by ordinary permissions
Figure 5-1: SSO authorization is an extra check between "is the token valid" and "are the permissions sufficient"

Architecture diagram: EMU identity lifecycle

Microsoft Entra IDUsers · groups · app assignmentsConditional access policy (CAP)Leaves → disabled SCIM: create/update/deactivate users and groups OIDC sign-in + CAP check on every access EMU enterprisealice_acme (managed account)IdP group → team → repository permissionsNo public content Audit logexternal_identity.*org.add_member→ streaming (M6)
Figure 5-2: the IdP is the source of truth

Interactive simulator: will this request get 200 or 403?

Switch the identity mode and credential state, click "Send request", and view GitHub's step-by-step decision and response (message text is an example).

Identity mode
Credential
Status

Core commands and API

Command / APIPurposeNotes
gh auth login --web / gh auth refreshRe-authorize gh (including SSO)Click Authorize for the organization in the web flow
curl -I -H "Authorization: Bearer $TOKEN" https://api.github.com/orgs/OView X-GitHub-SSO response headersthe header gives the authorization URL or partial-results; organizations=…
GET /orgs/O/credential-authorizationsOwner views a member's authorized credentialsGHEC; can DELETE …/{credential_id} revoke
GET /scim/v2/enterprises/E/UsersEMU: view users provisioned via SCIMUsually called by the IdP; read-only use during troubleshooting
GET /orgs/O/teams/T/team-sync/group-mappingsView IdP group mapping for team syncTeam sync for non-EMU
ssh -T git@github.comTest SSH authenticationCloning organization repositories still fails when SSO is not authorized
TOKEN=ghp_xxx   # classic PAT not authorized for the organization (example)
curl -s -o /dev/null -D - -H "Authorization: Bearer $TOKEN" \
  https://api.github.com/repos/myorg/app | grep -iE "^HTTP|x-github-sso"
curl -s -H "Authorization: Bearer $TOKEN" https://api.github.com/repos/myorg/app | jq .message
HTTP/2 403
x-github-sso: required; url=https://github.com/orgs/myorg/sso?authorization_request=A5Y…
"Resource protected by organization SAML enforcement. You must grant your Personal Access token access to this organization."
# owner: list members' authorized credentials
gh api orgs/myorg/credential-authorizations \
  --jq '.[] | [.login, .credential_type, .credential_authorized_at, .credential_accessed_at] | @tsv'
alice	personal access token	2026-10-02T08:11:05Z	2026-11-15T07:40:12Z
bob	SSH key	2026-06-11T13:20:44Z	2026-08-01T09:02:31Z

Production use: Export this list regularly and revoke credentials unused for 90 days (credential_accessed_at). Note: These endpoints require a GHEC organization and owner permissions; calls from a Free organization return 404.

Lab 5: identity scheme drill (about 6 minutes)

Plan notes SAML SSO, EMU, team sync, and data residency all require GitHub Enterprise Cloud (EMU requires a separately applied EMU enterprise). Without GHEC, complete steps 1–2 and the "alternative" part of step 5; steps 3–4 serve as reading and design exercises.
Check your gh token:
gh auth status
curl -s -o /dev/null -D - -H "Authorization: Bearer $(gh auth token)" https://api.github.com/user | grep -iE "x-oauth-scopes|x-github-sso"
x-oauth-scopes: admin:org, gist, read:audit_log, repo, security_events, workflow

No x-github-sso header indicates this request does not involve an SSO organization resource.

Inventory long-term credentials (also possible on Free): under Settings → Developer settings, list all classic PATs and fine-grained PATs and delete unused ones; in organization Settings → Personal access tokens, enable "Require approval of fine-grained PATs" and "Restrict access via classic PATs" (organization policies, also available on Free/Team; follow the UI).
(GHEC) configure organization SAML SSO: organization Settings → Authentication security → Enable SAML authentication; fill in the IdP's Sign-on URL, Issuer, and public certificate; first run Test SAML configuration, then check Require SAML SSO. Save the recovery codes. Then click Configure SSO → Authorize for your PAT.
(design exercise) EMU scheme: for a company using Entra ID, write out: OIDC + CAP (company network/compliant devices only), SCIM app assignment groups gh-users, IdP groups gh-team-platform mapped to teams platform, short code acme, and how open source contributions are handled.
Alternative lab: simulating SSO 403 troubleshooting: on the "Animation" page, switch credentials and states in turn, record the response for each combination; write the handling steps against the "Troubleshooting" page.

Case 1: All CI bot requests return 403 on the day SSO was enabled

Problem: After the organization enabled Require SAML SSO, the classic PAT of the service account used by Jenkins failed in every case. Approach: Short term: the service account signs in to the IdP and authorizes the PAT; long term: switch to GitHub App (installation tokens are not affected by a personal SAML session, have finer permissions, and are auditable); inside Actions, use GITHUB_TOKEN. Lesson: Before enabling SSO, inventory all automation credentials and authorize them in advance.

Case 2: a bank chooses EMU + OIDC

Problem: Compliance requires "losing all code access within 15 minutes of departure" and "allowing access only from the corporate network". Approach: EMU + Entra ID OIDC, with CAP restricting compliant devices and named locations; SCIM automatically deactivates the managed account after the account is disabled in the HR system; audit logs are streamed to Sentinel (via Event Hubs). Limitations: Employees cannot use managed accounts to participate in open source; some third-party integrations need adaptation.

Case 3: data residency for an EU subsidiary

Problem: Customer contracts require source code to be stored in the EU. Approach: Create a new EMU enterprise in the GHE.com EU region and migrate with GitHub Enterprise Importer; allow GHE.com's dedicated IP ranges through the firewall; change all API calls in CI to api.SUBDOMAIN.ghe.com. Limitations: Before go-live, verify the availability of Actions, Copilot, Marketplace apps, etc. on GHE.com.

Common errors and fixes

HTTP 403: Resource protected by organization SAML enforcement. You must grant your Personal Access token access to this organization.

Cause: The PAT has not been SSO-authorized for that organization, or the authorization was revoked by an owner.

curl -sI -H "Authorization: Bearer $TOKEN" https://api.github.com/orgs/ORG | grep -i x-github-sso

Fix: Open the URL in the response header, or go to Settings → Developer settings → Tokens → Configure SSO → Authorize; for automation, switch to a GitHub App.

git clone fails: The 'ORG' organization has enabled or enforced SAML SSO. To access this repository, you must re-authorize … (the text depends on actual output)

Cause: The SSH key or the token in the Git credential manager is not authorized for that organization.

Fix: Settings → SSH and GPG keys → for the relevant key, Configure SSO → Authorize; for HTTPS, sign in again in GCM.

EMU user sees no repositories after signing in

Cause: SCIM created the account, but there is no organization/team membership (IdP group not connected to a team).

Fix: Add the user to the pushed group in the IdP, and connect that IdP group in the GitHub team settings; check the SCIM provisioning log.

In OIDC mode, a user accessing from home is denied: Your IP address is not permitted … (example)

Cause: Named-location restriction in the Entra ID conditional access policy; GitHub validates CAP for both web and token access.

Fix: Use a VPN per policy; plan exceptions for uncontrollable IP access such as GitHub Actions hosted runners (follow the official "CAP support" documentation).

After team sync, members were removed unexpectedly

Cause: Team membership follows the IdP group; manually added members will be removed at the next sync.

Fix: Make all membership changes in the IdP; for people who need temporary access, use a separate team or the outside collaborator process.

Command-line questions
1. Use curl to determine whether a token failure is related to SSO.
curl -s -D - -o /dev/null -H "Authorization: Bearer $TOKEN" https://api.github.com/orgs/ORG | grep -iE "^HTTP|x-github-sso"
2. As an owner, revoke an authorized credential (ID 12345).
gh api -X DELETE orgs/ORG/credential-authorizations/12345
Scenario analysis question
The company uses Okta and wants to use EMU and require that "only company devices can access GitHub." Is this feasible?

EMU supports Okta's SAML + SCIM, but GitHub's OIDC + CAP validation only supports Entra ID. With Okta, the device restriction can only be implemented at the Okta sign-in step (Okta device trust/policies); GitHub does not re-validate IdP policies on each token access. You can add GitHub's IP allow list (enterprise/organization level, a GHEC feature) to restrict network sources. Do not use Okta for SSO and Entra for SCIM; that combination is explicitly unsupported.

Verified instructional videos

▶
Authenticating to GitHub the classic way vs the EMU (Enterprise Managed Users) way — GitHub
English · official channel, comparison of personal account and EMU authentication methods
▶
GitHub Enterprise Cloud - Enterprise Managed Users ( Microsoft Entra ID - Single Sign-On Setup) — Jack G Kafaty
English · community author, demo of EMU SSO configuration with Entra ID (follow the current version's UI)

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: on the left, an employee's personal account with the company organization's badge; on the right, a managed account with an _acme suffix "owned" by an IdP icon.
Narration: SAML SSO links the employee's own account; EMU accounts are created and owned by the enterprise through the identity provider.
Shot 2 · 25–50s
Visual: a PAT request hits organization resources, and a 403 with an "Authorize" button pops up.
Narration: in an SSO organization, every token and SSH key must be separately authorized for the organization.
Shot 3 · 50–75s
Visual: an employee is disabled in the HR system; an arrow via SCIM reaches GitHub, and the account turns gray.
Narration: SCIM makes departures take effect automatically; with OIDC from Entra ID, conditional access policies can also be checked on every access.
Shot 4 · 75–90s
Visual: four regions light up on the map: EU, US, Australia, Japan.
Narration: when data residency is required, use GHE.com, choose a region, and you must use EMU.
or score ≥ 70% on the "Quiz"

Module 6 · Rulesets, audit log, and compliance

38:00 – 46:00 · Policies must be pushed centrally, exceptions must be visible, and every bypass and change must leave exportable evidence
8 minOrganization rulesets: Team since 2025-06-16Enterprise rulesets GA 2025-03-24Audit log API/streaming requires GHEC★★★★★
Learning objectives
  • Design organization/enterprise rulesets: target repositories (name patterns, custom properties), target branches/tags, rule combinations, bypass lists and bypass modes, and Evaluate-mode trial runs.
  • Use rule insights to view the rule evaluation results for each push/merge and locate "who was blocked and who bypassed."
  • Query audit logs (UI syntax and API), stream the enterprise audit log to Azure Event Hubs / Blob, Amazon S3, Splunk, Datadog, etc., and obtain compliance reports.
Prerequisites:Git Lesson 3repository ruleset basics,Lesson 5organization-level governance. Importance:★★★★★

What: three layers of rulesets

LevelAvailable plansTargetTypical use
Repository rulesetPublic repositories: all plans; private repositories: Pro/Team/EnterpriseBranches/tags/pushes in this repositoryDetailed rules self-managed by the team
Organization rulesetTeam (since 2025-06-16), Enterprise CloudBy repository name pattern (include/exclude, fnmatch),custom properties (such as tier=prod) or all repositoriesOrganization-wide unified main protection, tag protection, push restrictions
Enterprise rulesetEnterprise Cloud (GA 2025-03-24)By organization name / organization properties + repository propertiesEnterprise-wide mandatory baseline

When multiple rulesets (and classic branch protection) apply at the same time all stack, and the strictest wins (for example, two rulesets requiring 1 and 2 approvals respectively, the result is 2).

Common rules

  • Branches/tags: restrict creation/update/deletion, block force pushes, require linear history, require signed commits, require PRs (number of approvals, CODEOWNERS, most recent push must be approved by someone else, resolve conversations), require status checks, require successful deployments, require merge queue,Require code scanning results code scanning results (Module 3), restrict merge methods, restrict commit metadata (Enterprise).
  • Push rulesets (push rulesets, GA 2024-09): for private/internal repositories and their entire fork network restrict file paths, file extensions, file sizes, and path lengths—for example, block pushing *.pem,.env, and files larger than 50 MB.

Bypass lists and modes

  • Principals that can be added: repository roles (Admin, Maintain, Write, or custom roles), organization admins (owners), teams, GitHub Apps, deploy keys (repository rulesets), etc.
  • Modes: Always (direct pushes can also bypass) or For pull requests only (bypass is only selectable when merging a PR, leaving a PR record). The latter is recommended.
  • Every bypass is written to rule insights and the audit log (such as protected_branch.policy_override / ruleset bypass events; event names follow the audit log).

Enforcement status

Active (enforced),Disabled (disabled),Evaluate (evaluate only: records "would have blocked" without blocking—used for trial runs before go-live; Evaluate requires Enterprise).

Rule insights

The repository or organization Settings → Rules → Insights shows the "rule suite evaluation" for each push/merge: time, actor, ref, result (pass/fail/bypass), and which rule failed. API: GET /repos/O/R/rulesets/rule-suites and /orgs/O/rulesets/rule-suites.

Audit log

  • Organization audit log (owners on all plans can view it in the UI): Settings → Logs → Audit log; default retention is about 180 days, Git events (clone/fetch/push) about 7 days and must be enabled in the enterprise (follow the documentation). Query syntax: action:,actor:,repo:,created:,operation:,country:, which can be combined, such as action:repo.destroy created:>=2026-11-01.
  • Audit log REST API: /orgs/O/audit-log and /enterprises/E/audit-log require GitHub Enterprise Cloud, token scope read:audit_log.
  • Enterprise audit log streaming (GHEC, enterprise Settings → Audit log → Log streaming): targets include Amazon S3 (access key or OIDC),Azure Blob Storage,Azure Event Hubs,Datadog,Google Cloud Storage,Splunk (HEC), and Microsoft Purview (Copilot agent session events only). Exports audit events and Git events; optionally includes "API Request Events" (only security-related endpoints). Health check every 24 hours; configuration errors must be fixed within 6 days; data from pauses of 7 days or less is cached and exported after recovery; pauses of 3 weeks or more do not retain data. Streaming to multiple endpoints simultaneously is in public preview.
  • Other enterprise settings: show the event source IP in the audit log (Source IP disclosure, enterprise setting); record API request events.

Compliance reports

GHEC enterprise owners (and organization owners) can download GitHub's SOC 1 / SOC 2 Type 2 reports, ISO/IEC 27001 certificates, etc., under Settings → Compliance (available files follow the page), for vendor assessment. Your own compliance evidence comes from: ruleset configuration (exported JSON), rule insights, audit log streams, and the security alerts API.

When: rollout order

  1. Define repository custom properties (tier,data-class,owner-team), required when creating a repository.
  2. Organization ruleset "prod-main-baseline": target tier=prod, default branch requires PR + 2 approvals + CODEOWNERS + status checks + code scanning; first Evaluate (Enterprise) or go Active on a small scope.
  3. Push ruleset: block secret-type file extensions and oversized files.
  4. Bypass only for the "release-managers" team, mode For pull requests only.
  5. Stream the audit log to a SIEM and set alerts: ruleset modified, bypass, repository visibility changed to public, push protection bypass, SSO settings changed.
Common misconceptions① "Organization owners are not bound by rulesets"—only principals on the bypass list can bypass (owners can modify rulesets, but the modification itself is audited). ② "Being able to see the audit log in the UI is enough"—after 180 days the data disappears, and the UI is not suitable for correlated analysis; compliance scenarios must stream to long-term storage. ③ "Evaluate mode blocks"—it only records.

Architecture diagram: ruleset stacking evaluation

push / mergerefs/heads/main Enterprise rulesetBlock force pushes · signed commits Organization ruleset tier=prodPR + 2 approvals · code scanning Repository rulesetStatus check test Merge: strictest winsbypass list checkActive / Evaluate pass / bypass fail (GH013) → rule insights + audit log
Figure 6-1: there is no "override", only stacking; exceptions can only come from the bypass list

Architecture diagram: audit evidence chain

GHEC enterpriseAudit events + Git events(optional API request events) stream Azure Event Hubs Amazon S3 (OIDC) / Azure Blob / GCS Splunk HEC / Datadog SIEM / data lakeSentinel · SplunkLong-term retention (per compliance)Detection rules Alerts / reportsBypasses · visibility changes
Figure 6-2: audit log stream → long-term storage → detection and compliance reports

Interactive evaluator: which rulesets match this push?

Select the repository, target ref, actor, and operation method; the evaluator gives a result following "match target → stack rules → check bypass → enforcement", and generates rule insights records (the rulesets are example configurations).

Repository (properties)
Operation
Actor

Core commands and API

Command / APIPurposeNotes
gh api orgs/O/rulesetsList organization rulesetsPOST Create,PUT …/ID update; JSON can be managed in Git
gh api repos/O/R/rules/branches/mainView all rules actually in effect on a branchincludes rules from the organization/enterprise (after stacking)
gh api orgs/O/rulesets/rule-suitesrule insightsrule_suite_result=bypass|fail,actor_name,time_period
gh api orgs/O/properties/schemacustom property definitionsRulesets select repositories by property
gh api "orgs/O/audit-log?phrase=…"Query audit logGHEC; include=web|git|all; read:audit_log
gh api enterprises/E/audit-log/streamsView streaming configurationenterprise owner; endpoint details follow the REST documentation
{
  "name": "prod-main-baseline",
  "target": "branch",
  "enforcement": "active",
  "conditions": {
    "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] },
    "repository_property": {
      "include": [{ "name": "tier", "property_values": ["prod"] }],
      "exclude": []
    }
  },
  "bypass_actors": [
    { "actor_type": "Team", "actor_id": 1234567, "bypass_mode": "pull_request" }
  ],
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" },
    { "type": "pull_request", "parameters": {
        "required_approving_review_count": 2,
        "require_code_owner_review": true,
        "require_last_push_approval": true,
        "dismiss_stale_reviews_on_push": true,
        "required_review_thread_resolution": true } },
    { "type": "required_status_checks", "parameters": {
        "strict_required_status_checks_policy": false,
        "required_status_checks": [
          { "context": "dependency-review" }, { "context": "test" } ] } },
    { "type": "code_scanning", "parameters": { "code_scanning_tools": [
        { "tool": "CodeQL", "security_alerts_threshold": "high_or_higher", "alerts_threshold": "errors" } ] } }
  ]
}
gh api -X POST orgs/$ORG/rulesets --input org-ruleset-prod.json --jq '.id, .name, .enforcement'
gh api repos/$ORG/payments-api/rules/branches/main --jq '.[] | [.type, .ruleset_source_type, .ruleset_source] | @tsv'
gh api "orgs/$ORG/rulesets/rule-suites?rule_suite_result=bypass&time_period=week" \
  --jq '.[] | [.pushed_at, .actor_name, .repository_name, .ref, .result] | @tsv'
88231
prod-main-baseline
active
deletion	Organization	myorg-lab
non_fast_forward	Organization	myorg-lab
pull_request	Organization	myorg-lab
required_status_checks	Organization	myorg-lab
code_scanning	Organization	myorg-lab
2026-11-14T22:03:11Z	carol	payments-api	refs/heads/main	bypass

Rule parameter names follow the REST "Rules" documentation (code_scanning rule threshold values: none/critical/high_or_higher/medium_or_higher/all; alerts: none/errors/errors_and_warnings/all). Team IDs are obtained with gh api orgs/$ORG/teams/release-managers --jq .id .

Audit log query (GHEC)

gh api --paginate "orgs/$ORG/audit-log?phrase=action:repository_ruleset+created:>=2026-11-01&include=web" \
  --jq '.[] | [.["@timestamp"], .action, .actor, .repo // .org] | @tsv'
gh api "orgs/$ORG/audit-log?phrase=action:secret_scanning_push_protection" --jq '.[] | [.action, .actor, .repo] | @tsv'
gh api "orgs/$ORG/audit-log?phrase=action:repo.access" --jq '.[] | [.created_at, .actor, .repo, .visibility] | @tsv'
1763190191000	repository_ruleset.update	alice	myorg-lab
1763101902000	secret_scanning_push_protection.bypass	bob	myorg-lab/myapp-sec
1763011122000	repo.access	carol	myorg-lab/legacy-tool	public

Lab 6: organization ruleset + rule insights + audit log (about 8 minutes)

Define a custom property and tag the practice repository (Team/Enterprise; Free organizations skip to the step 3 alternative):
gh api -X PUT orgs/$ORG/properties/schema/tier -f value_type=single_select \
  -F 'allowed_values[]=prod' -F 'allowed_values[]=dev' -f required=false
gh api -X PATCH repos/$ORG/myapp-sec/properties/values --input - <<'EOF'
{"properties":[{"property_name":"tier","value":"prod"}]}
EOF
Create the organization ruleset: using the JSON on the "Commands" page (first change the bypass team ID to your release-managers team; if there is none, remove it bypass_actors; if the CodeQL gate is not enabled, you can first delete the code_scanning rule).
gh api -X POST orgs/$ORG/rulesets --input org-ruleset-prod.json --jq .id
Free organization alternative: repository-level ruleset (public repositories):
jq 'del(.conditions.repository_property) | .conditions = {ref_name: {include: ["~DEFAULT_BRANCH"], exclude: []}}' \
  org-ruleset-prod.json > repo-ruleset.json
gh api -X POST repos/$ORG/myapp-sec/rulesets --input repo-ruleset.json --jq .id
Verify blocking:
git switch main && git pull
echo "# direct" >> README.md && git commit -am "docs: direct push"
git push
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: - Changes must be made through a pull request.
remote: - 2 of 2 required status checks are expected.
 ! [remote rejected] main -> main (push declined due to repository rule violations)
git reset --hard origin/main
View rule insights: Settings → Rules → Insights, find the fail record just created; or gh api "repos/$ORG/myapp-sec/rulesets/rule-suites?rule_suite_result=fail".
View the audit log: organization Settings → Logs → Audit log, search for action:repository_ruleset and action:secret_scanning, to find the operation records from Modules 2–6. GHEC users then use the API to export the last 7 days of events as JSON.
(GHEC, optional) configure streaming: enterprise Settings → Audit log → Log streaming → Configure stream → Azure Event Hubs: enter the Event Hub instance name and connection string (SAS policy granting only Send permission); click Check endpoint, then save. Cost: Event Hubs Basic/Standard is billed by throughput unit; delete the resource group when the drill ends rg-gh-lab.
Keep the ruleset for the capstone lab; to revoke: gh api -X DELETE repos/$ORG/myapp-sec/rulesets/ID.

Case 1: migrating 400 branch protections to 3 organization rulesets

Problem: Each repository's branch protection was different, and during audits it was impossible to prove that "all production repositories require two-person approval."Approach: Introduce tier property, and deploy organization rulesets by property; use GET /repos/O/R/rules/branches/main to batch export the actually effective rules as audit evidence; gradually delete old branch protections. Limitations: Properties require a governance process to ensure correctness (new repository templates + required).

Case 2: discovering visibility changes via an audit log stream

Problem: A developer mistakenly changed an internal repository to public for 40 minutes. Approach: The audit log entered Microsoft Sentinel via Event Hubs; the detection rule matched repo.access and visibility=public, alerting within 5 minutes; then an organization policy restricted members from changing visibility; in EMU enterprises, managed users cannot create public repositories in the first place.

Case 3: bypass abuse governance

Problem: rule insights showed one team had 30 Always-mode bypasses per week. Approach: Change the bypass mode to For pull requests only and require the reason to be written in the PR; each month, use the rule-suites API to count bypasses and bring them into the governance meeting.

Common errors and fixes

GH013: Repository rule violations … Changes must be made through a pull request (automated release script blocked)

Cause: The release bot pushes directly to a protected branch.

Fix: Add the release GitHub App to the bypass list (mode as needed), or change to going through a PR + auto-merge; do not give a personal account Always bypass.

Ruleset "collateral damage": all repositories (including tool repositories before archiving) require 2 approvals, and small teams cannot merge

Cause: The target condition uses ~ALL or a repository name pattern that is too broad.

gh api orgs/O/rulesets/ID --jq .conditions

Fix: Switch to property-based targeting or an exclude list; before go-live, trial in Evaluate mode (Enterprise) or on a small scope, and check rule insights.

gh: Not Found (HTTP 404) — GET /orgs/O/audit-log

Cause: The audit log API is only open to GHEC organizations; or the token lacks read:audit_log.

Fix:gh auth refresh -s read:audit_log; Free/Team organizations view and export in the UI (the UI provides CSV/JSON export).

Streaming health check failed / audit log is missing a segment in the SIEM

Cause: Expired credentials (S3 keys, Event Hubs SAS), network/firewall, target quota; events not fixed within 6 days are lost; pauses longer than 7 days only backfill the most recent week.

Fix: On the enterprise Log streaming page, Check endpoint; switch S3 to OIDC to avoid rotating keys; set up an alert for "no events in 24 hours".

Looking for the entry point for required workflows but cannot find it

Cause: The legacy required workflows have been migrated to the "Require workflows to pass before merging" rule in rulesets (see Lesson 5).

Fix: Add that rule in the organization ruleset and select the workflow file from the source repository.

Command-line questions
1. View all rules actually in effect on the main branch of payments-api and their sources.
gh api repos/O/payments-api/rules/branches/main --jq '.[] | [.type, .ruleset_source_type, .ruleset_source] | @tsv'
2. List all ruleset bypass records in the organization this week.
gh api "orgs/O/rulesets/rule-suites?rule_suite_result=bypass&time_period=week" --jq '.[] | [.actor_name, .repository_name, .ref] | @tsv'
Scenario analysis question
An auditor requires proof that "over the past 12 months, the main branch of all production repositories was never force-pushed." How do you provide the evidence?

① Ruleset configuration history: the JSON of the organization ruleset (non_fast_forward blocked, target tier=prod) and its change audit events (repository_ruleset.*); ② Git push events and ruleset bypass events in the audit log stream—the UI only keeps about 180 days, so you must rely on long-term data streamed to a SIEM/data lake; ③ export the bypass/fail records from rule insights; ④ if there were bypasses, provide the corresponding PR and approval records. Without streaming, you can only prove a recent period, which is why the stream should be configured early.

Verified instructional videos

▶
Introducing repository rules — GitHub
English · official channel, introduction to rulesets concepts
▶
Govern your repositories with Push Rulesets — GitHub
English · official channel, push rulesets
▶
Quickly collect GitHub Enterprise Audit Logs - Splunk - GitHub Checkout — GitHub
English · official channel, audit log integration with Splunk
▶
Introduction to GitHub Actions - Part 6 - Repository Rulesets — Mickey Gousset
English · hands-on repository rulesets

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–25s
Visual: three semi-transparent ruleset cards (enterprise, organization, repository) stacked on the main branch; the darkest color appears where they overlap.
Narration: multiple rulesets take effect at the same time; the result is the strictest, and none overrides another.
Shot 2 · 25–50s
Visual: a release-managers team member's avatar passes the gate with a "PR-only bypass" pass; next to it a new bypass record appears in rule insights.
Narration: exceptions can only come from the bypass list, and every bypass is recorded.
Shot 3 · 50–75s
Visual: audit events flow like water into three buckets: Event Hubs, S3, and Splunk.
Narration: enterprise audit logs can be streamed to cloud storage and a SIEM for long-term retention and detection.
Shot 4 · 75–90s
Visual: an auditor's checklist with items ticked off one by one.
Narration: ruleset configuration, rule insights, and the audit log stream together form a complete compliance evidence chain.
or score ≥ 70% on the "Quiz"

Module 7 · Copilot and AI feature governance

46:00 – 53:00 · AI features are also principals with permissions: who can use them, which models and agents they can use, which code they can see, and what records they leave behind
7 minRequires Copilot Business / EnterpriseNames and entry points change quickly; follow the documentation★★★★☆
Learning objectives
  • Explain the policy hierarchy for Copilot Business / Enterprise: enterprise (AI controls) → organization → user, the meaning of "enabled / disabled / let organizations decide", and the conflict rules across multiple licenses.
  • Configure content exclusion and public code match filtering, and understand their boundaries (content exclusion is not a security boundary).
  • Set governance toggles for Copilot cloud agent (formerly coding agent), partner agents, MCP, and other new features, and supervise them using the audit log and usage metrics.
Prerequisites: Module 5 (identity), Module 6 (audit log). Importance:★★★★☆

What: Copilot organization-level plans and policies

Copilot Business and Copilot Enterprise are managed by the organization/enterprise by assigning seats to members and managing policies uniformly (list prices have long been $19 and $39 per user per month, with premium requests billed by usage; prices and quotas follow github.com/features/copilot/plans the official source). Personal plans (Free/Pro/Pro+) are not governed by organization policies—this is critical for governance.

Three major categories of policies (docs, 2026-11)

  • Features, agents, and models: control which Copilot features users can use (IDE completion, Chat, Copilot CLI, Copilot code review, cloud agent, partner agents, etc.) and which models. Two further policies decide new GA features/models not yet configured whether they are enabled or disabled by default.
  • Cloud access category: settings that apply to everyone, such as blocking Copilot cloud features in enterprise repositories.
  • Privacy category: such as suggestions matching public code (Suggestions matching public code: Allowed / Blocked). When Blocked, suggestions matching public code of roughly 150 characters are filtered; when Allowed, enable code referencing (code referencing), which shows the matching source and license (thresholds and behavior follow the documentation).

How enterprise and organization policies stack

  • Enterprise owners first configure: most policies can be set to explicitly enable/disable or let organizations decide (Let organizations decide); some newer policies also support "enable only for selected organizations" (selectable by organization custom properties). Once explicitly set at the enterprise, organizations cannot override it.
  • The new enterprise UI centralizes agent settings on the AI controls page (for example, configuring Copilot cloud agent under Installed Agents: Enabled everywhere / Let organizations decide, etc.); in older documentation it is Policies → Copilot. Follow your enterprise UI.
  • When a user gets seats from multiple organizations in the same enterprise: usually the most permissive policy applies (with exceptions); across multiple enterprises: almost always the strictest applies.
  • Users directly assigned by the enterprise are not overridden by "let organizations decide"; they are governed by the separate "Policies for enterprise-assigned users".

Content exclusion (content exclusion)

  • Supported for Business / Enterprise; repository admins can configure it for their repository, organization owners for users with seats in their organization, and enterprise owners can also configure it. The syntax is a list of path patterns, for example "/secrets/**","*.env", at the organization level it can be specified by referencing repositories.
  • Effect: excluded files are not offered for completion, are not used as context for completing other files, do not participate in Chat/agent answers, and are not reviewed by Copilot code review.
  • Coverage: completion supports VS Code, Visual Studio, JetBrains, Vim/Neovim, Xcode, Eclipse; Chat/agent supports VS Code, Visual Studio, JetBrains, Copilot CLI, cloud sessions on the GitHub website, and Copilot code review, etc. (follow the documentation table).
  • Boundary: the documentation explicitly states that content exclusion is not a file system security boundary, and cannot replace OS permissions; third-party MCP servers/clients are not guaranteed to comply; semantic information provided by the IDE (types, hover definitions) may still be used; symbolic links and remote file systems are not yet covered. Real secrets should not be in the repository at all (Module 2).

Governance of Copilot cloud agent (formerly coding agent)

  • Available on Copilot Pro, Pro+, Business, Enterprise; enterprises/organizations enable it via policies, and organizations can limit which repositories it can use under Settings → Copilot.
  • Built-in mitigations (docs "Risks and mitigations"): only users with write access to the repository can trigger it; the agent can only push to its own copilot/ branches and is constrained by branch protection and required checks; workflows triggered by PRs the agent opens require approval by someone with write access before running (admins can choose to run automatically); the person who initiated the request cannot approve that PR, the agent cannot approve or merge PRs; internet access is restricted by default (firewall, configurable allow list); commits are signed and attributed to Copilot, with the requester as co-author; output is passed through secret scanning.
  • Partner agents (for example Anthropic Claude, OpenAI Codex; follow the list on the organization policy page) are toggled separately under "Partner agents", with the same access scope as the repositories where cloud agent is enabled.
  • MCP: MCP servers in cloud agent and in the IDE are controlled by policy ("MCP servers in Copilot", etc.; names follow the UI).

Audit and metrics

  • The audit log records Copilot settings changes, seat assignments, policy changes, and agent-related events (event names follow the audit log); the enterprise audit log stream can send Copilot agent session events to Microsoft Purview (Module 6).
  • Copilot usage metrics (dashboard and REST API) are used to evaluate adoption; premium request usage is viewed on the billing page, where budgets can be set.
  • Data handling: retention of Business/Enterprise prompt and suggestion data, whether it is used for training, etc. follow GitHub Copilot Trust Center and the product terms.

When: recommended default baseline

SettingRecommendationRationale
New feature/model default stateDisabled; enable after evaluationAvoids automatically exposing unreviewed capabilities to everyone
Suggestions matching public codeBlocked (or Allowed + code referencing + legal process)Reduces license risk
Content exclusionExclude directories containing customer data samples, key templates, and export-controlled materialReduces sensitive context entering prompts
cloud agentEnable first for pilot organizations/repositories; keep manual approval of workflowsAn agent is a principal that can write code and trigger CI
Partner agents / MCPEnable one by one after evaluating vendors and data flowsThird-party data processing
AuditAudit log stream + monthly policy and seat reviewCompliance evidence
Common misconceptions① "The organization disabled Copilot, so employees cannot use it"—employees can use a personal Copilot plan to open company code (EMU managed accounts cannot purchase personal Copilot; for non-EMU, rely on policy and network controls). ② "Content exclusion can protect secrets"—it is not a security boundary. ③ "An agent's PR is the same as a human-opened PR"—it has extra restrictions (branches, workflow approval, the requester cannot approve); these are the levers of governance, so do not turn them off by setting auto-run.

Architecture diagram: Copilot policy resolution

Enterprise: AI controls / PoliciesEnabled · DisabledLet organizations decide Organization: Settings → CopilotOnly settable when the enterprise is set to "let organizations decide"cloud agent can restrict repositories the user's effective policymultiple organizations in the same enterprise: usually the most permissiveacross enterprises: almost always the strictest Content exclusionrepository / organization / enterpriseis not a security boundary cloud agent guardrailscopilot/ branch · workflow needs approvalrequester cannot approve · firewall SupervisionAudit log · Purview (agent sessions)Usage metrics · budget
Figure 7-1: policies decide "whether it can be used", content exclusion decides "what it can see", and guardrails and audit decide "what was done and can be controlled and traced"

Interactive resolver: enterprise policy × organization settings → whether a user can use a feature

Choose the feature, the enterprise policy, and the settings of two organizations (the user has seats in both), then view the effective result and explanation. Rules are based on the docs "About Copilot policies" (2026-11); exceptions exist; follow the documentation.

Feature
Enterprise policy
Organization A settings
Organization B settings

Core commands and API

Command / APIPurposeNotes
GET /orgs/O/copilot/billingOrganization Copilot settings overviewfields such as seat management method, public code suggestion policy
GET /orgs/O/copilot/billing/seatsList seats and last activity timeReclaim inactive seats
POST/DELETE /orgs/O/copilot/billing/selected_teamsAssign/unassign seats by teamTogether with IdP group → team (Module 5)
GET /orgs/O/copilot/metricsUsage metricsEndpoints and fields follow the REST documentation (the newer metrics API is evolving)
gh api "orgs/O/audit-log?phrase=action:copilot"Query Copilot-related audit eventsGHEC
gh api orgs/$ORG/copilot/billing --jq '{seat_management_setting, public_code_suggestions, ide_chat, platform_chat, cli, seat_breakdown}'
gh api --paginate orgs/$ORG/copilot/billing/seats \
  --jq '.seats[] | [.assignee.login, .last_activity_at, .last_activity_editor] | @tsv' | sort -k2
{"seat_management_setting":"assign_selected","public_code_suggestions":"block","ide_chat":"enabled","platform_chat":"enabled","cli":"enabled","seat_breakdown":{"total":42,"active_this_cycle":35,"inactive_this_cycle":7}}
dave	2026-08-02T10:11:00Z	vscode/1.10x
alice	2026-11-14T16:20:31Z	vscode/1.10x

Content exclusion example (organization level, Settings → Copilot → Content exclusion)

"*":                         # all repositories
  - "**/.env"
  - "**/secrets/**"
  - "**/*.pem"
https://github.com/myorg-lab/payments-api.git:
  - "/fixtures/customer-data/**"
git@github.com:myorg-lab/legal-docs.git:
  - "*"                       # entire repository

Syntax follows the docs "Excluding content from GitHub Copilot"; changes take effect with a delay, and the window can be reloaded in the IDE. Remember: this only reduces context exposure; it is not access control.

Lab 7: Copilot governance inventory (about 6 minutes)

Plan notes The organization needs Copilot Business or Enterprise. Without it, complete the design exercises in steps 1 and 5, and practice policy resolution on the "Animation" page.
List current policies: organization Settings → Copilot → Policies (enterprise: AI controls / Policies); copy each policy's status into the review table: completion, Chat, CLI, code review, cloud agent, partner agents, MCP, model list, public code suggestions, new feature default state.
Seat hygiene: run the seats command on the "Commands" page to find seats with no activity for 60 days, confirm, then reclaim them (DELETE /orgs/O/copilot/billing/selected_users).
Configure content exclusion: for myapp-sec add "/config/**", open in VS Code config/settings.py, and confirm the Copilot icon shows that file as excluded (no completions offered).
cloud agent guardrails (if enabled): assign an issue to Copilot and observe: the branch name starts with copilot/ ; the workflow on the PR shows that approval is required; as the requester you cannot approve that PR. Check the related events in the audit log.
Design exercise: write a one-page "AI feature admission process" for the company: request → security/legal review (data flows, vendors, logs) → pilot organization (by custom property) → metrics review → full rollout; plus a list of prohibited actions (such as handling customer data in excluded directories).

Case 1: phased rollout at a regulated enterprise

Problem: The compliance department worries that AI will read payment code. Approach: The enterprise set "new feature default state" to disabled; Copilot was enabled first for non-payment organizations; the payment organization enabled completion but disabled cloud agent, and content exclusion covers fixtures containing test card numbers; audit logs flow into a SIEM, and policy changes are reviewed monthly. Limitations: Content exclusion is not a security boundary; sensitive data must still be managed outside the codebase.

Case 2: an agent-produced PR triggered a workflow with deployment permissions

Problem: A repository admin set cloud agent's workflows to auto-run, and the agent's PR ran a workflow that deploys to a staging environment. Approach: Restored "approval required"; the deployment job uses environment protection rules (required reviewers), bound to the OIDC subject conditions from Lessons 3/4 environment:, so the PR branch cannot obtain cloud credentials.

Case 3: license risk

Problem: Legal requires avoiding introducing GPL code snippets. Approach: Set public code match suggestions to Blocked; for R&D teams that truly need Allowed, enable code referencing and require source declaration in the PR template; pair with the dependency review license allow list (Module 4).

Common errors and fixes

A user reports "Copilot is disabled by your organization" or a model/feature is not visible

Cause: Enterprise or organization policy disables it; or the feature is a new GA feature with a default state of disabled; or the user's seat comes from another organization.

Fix: Check in the order "enterprise → organization → seat source"; use the resolution logic on the "Animation" page to explain it to the user.

Content exclusion "does not take effect"; Chat still references the excluded file content

Cause: Delayed effect; the client does not support it (some IDEs/features); indirect reads via a third-party MCP or terminal commands; symbolic links.

Fix: Reload the IDE; check the support matrix in the documentation; move sensitive content out of the repository.

Workflow on cloud agent's PR keeps showing "Approval required"

Cause: This is the default guardrail: someone with write access must review the code and approve the run.

Fix: After reviewing the diff, click Approve and run workflows; turning this guardrail off is not recommended.

Cannot assign a Copilot seat to anyone other than EMU managed users / outside collaborators

Cause: Seats can only be assigned to organization members (outside collaborators under certain conditions, per the documentation); some Copilot features are unavailable on GHE.com.

Fix: Assign based on organization membership; check GHE.com feature differences.

Command-line questions
1. Find seats with no Copilot activity in the last 60 days.
CUTOFF=$(date -u -d '60 days ago' +%FT%TZ)
gh api --paginate orgs/$ORG/copilot/billing/seats --jq ".seats[] | select((.last_activity_at // \"1970\") < \"$CUTOFF\") | .assignee.login"
2. Query all Copilot-related events in the organization audit log.
gh api --paginate "orgs/$ORG/audit-log?phrase=action:copilot" --jq '.[] | [.action, .actor, .created_at] | @tsv'
Scenario analysis question
The CTO wants to immediately enable cloud agent and all partner agents for everyone; how do you, as the platform lead, respond?

Support it, but in phases: ① clarify data flows and vendor terms (data handling of partner agents); ② enable first for pilot organizations/repositories (enterprise policy set to "selected organizations" or let organizations decide, plus the organization restricting repositories); ③ keep the guardrails of manual workflow approval and no self-approval by the requester, and use environment protection for deployment jobs; ④ ensure rulesets require PR review and code scanning, so agent output is gated the same as human code; ⑤ audit log stream (including agent session events in Purview) and usage metrics, with a premium request budget; ⑥ after one month, review based on metrics and events before expanding.

Verified instructional videos

▶
GitHub Copilot Features - Content exclusions — Rob Bos
English · community author, content exclusion configuration and effect (recorded earlier; the support matrix follows this hour/documentation)
▶
Copilot Settings for GitHub Enterprise Administrators — TechRill Academy
English · community author, Copilot settings from the enterprise admin perspective (the UI has since evolved to AI controls; follow the current version)

No verified official GitHub video on cloud agent governance toggles was found; the following is a storyboard script.

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: a three-layer switch panel for enterprise, organization, and user; the organization switch lights up only after the enterprise switch is set to "let organizations decide".
Narration: Copilot policy is decided first by the enterprise; only when the enterprise lets organizations decide can an organization set its own.
Shot 2 · 20–45s
Visual: the secrets folder is covered with a gray mask; the Copilot bubble skips it, but next to it is written "not a security boundary".
Narration: content exclusion reduces sensitive files entering context, but it is not access control.
Shot 3 · 45–70s
Visual: a bot pushes to a copilot/ branch; the PR workflow shows "approval required", and the requester's approve button is grayed out.
Narration: the cloud agent has built-in guardrails: a dedicated branch, workflows that need human approval, and the requester cannot approve their own PR.
Shot 4 · 70–90s
Visual: audit events flow into a SIEM and Purview, with a usage dashboard beside them.
Narration: continuously supervise with audit logs and usage metrics; pilot new features before rolling them out.
or score ≥ 70% on the "Quiz"

Module 8 · Comprehensive governance architecture review

53:00 – 60:00 · Tie the first 7 modules into one review checklist, one maturity model, and one troubleshooting tree
7 minComprehensive★★★★★
Learning objectives
  • Review a GitHub organization/enterprise across 7 dimensions (identity, repositories and policy, secrets, code, dependencies, AI, audit and response).
  • Give the current state and a 90-day roadmap using the L1–L4 maturity model.
  • Quickly locate six common governance problems using the interactive troubleshooting tree: pushes blocked, CodeQL failures, Dependabot not opening PRs, SSO 403, ruleset collateral damage, missing audit logs.
Prerequisites: Modules 1–7. Importance:★★★★★

What: governance architecture review checklist

DimensionMust-check itemsEvidence sourceRequired plan
Identity and accessSSO/EMU scheme; SCIM; enforced 2FA; PAT policy (fine-grained, approval, maximum lifetime); outside collaborator process; IP allow listOrganization settings,credential-authorizations, audit log2FA/PAT policy: all; SSO/EMU/IP: GHEC
Repositories and policyComplete custom properties; organization/enterprise rulesets cover the default branch and tags; push rulesets; minimize bypass (PR only); members cannot change visibility or delete repositoriesrules/branches/main, rule insightsOrganization rulesets: Team+
SecretsPush protection fully covered and enforced; delegated bypass; custom patterns; validity checks; leak response runbook (rotate first); CI uses OIDCsecurity overview, alerts APIPrivate repositories: Secret Protection
CodeCodeQL default setup coverage; advanced setup templated; ruleset code scanning gate; alert SLA; Autofix review requirementCoverage view, analyses APIPrivate repositories: Code Security
Dependencies and supply chainDependabot alerts/security updates all enabled; version updates include github-actions; dependency review as a required check; Actions pinned by SHA; artifact attestations (Lesson 5)alerts API, rulesetsPrivate repository dependency review: Code Security
AI featuresNew features disabled by default; public code policy; content exclusion; cloud agent scope and guardrails; partner agent evaluation; seat reviewCopilot settings, audit logCopilot Business/Enterprise
Audit and responseAudit log streaming and health alerts; detection rules (bypass, visibility, ruleset changes, SSO changes); retention meets compliance; drill recordsSIEM, stream configurationStreaming: GHEC

Maturity model (the teaching model used in this hour)

LevelCharacteristicsTypical next step
L1 PassiveRepositories configured manually one by one; only public repositories are scanned; no unified rules; leaks are discovered after the factEnable free features + user-level/repository-level push protection; Dependabot fully enabled
L2 Baselinesecurity configuration covers all repositories; organization rulesets protect the default branch; SSOdependency review gate; CodeQL default setup; alert SLA
L3 Controlledenforced configurations; delegated bypass; code scanning merge gate; audit log stream + detection; EMU/SCIM; Copilot policy-drivencustom patterns, attribute-driven tiered policies, AI admission process
L4 Metrics-drivenKPIs of MTTR, bypass rate, coverage, fix rate; security campaigns; regular red-team/drills; policy as code (ruleset JSON reviewed in Git)Continuous optimization and automation

Why: why review rather than "turn everything on"

"Turn everything on" runs into three kinds of problems: cost (GHAS active committers), friction (overly strict rulesets make teams look for bypasses), and blind spots (looking only at tool toggles, not at exceptions and evidence). The review puts risk, cost, and developer experience on one table to weigh trade-offs, and assigns an owner and an expiry date to every exception.

How: structure of a 45-minute review meeting

  1. 10 minutes: current data (security overview coverage, alert backlog and MTTR, bypass statistics, seat data).
  2. 20 minutes: go through the checklist dimension by dimension, marking red/yellow/green, and record exceptions.
  3. 10 minutes: rate the maturity (L1–L4) and set a 90-day roadmap (each item has an owner).
  4. 5 minutes: confirm items needing purchase/licensing and their alternatives.

When: frequency

Quarterly review; ad-hoc review after major events (leaks, compliance audits, organization mergers, enabling new AI features).

Common misconceptions① "All tool toggles green = secure"—you also need to look at exceptions, bypasses, and alert handling time. ② "Higher maturity is always better"—for a small team, L2 may be the best value for money. ③ "Reviews are the security team's job"—platform, development, and legal must all participate, or the rules will drift from reality.

Reference architecture: governance overview of a GHEC enterprise

Entra IDOIDC + CAPSCIM users/groupsHR-driven departures EMU enterprise (optional GHE.com data residency) Enterprise rulesets · policiesCopilot AI controlssecurity configurations Organization A (prod)tier=prod rulesetsSP + CS enforced Organization B (internal tools)SP enforcedCS for core repositories only Organization C (open source, non-EMU)Free features for public repositoriesAnother enterprise/account Evidence and responseAudit log stream → Event Hubs→ Sentinel detectionPurview (agent sessions)Alerts API → ticketssecurity overview KPIQuarterly governance review Developer workflowPush protection → PR (CodeQL · dependency review · approval) → merge → release attestation
Figure 8-1: identity → policy → workflow → evidence, a four-layer closed loop

Interactive self-assessment: which maturity level is your organization at?

Check the items already achieved (saved in this browser); the score for each dimension and the overall level are calculated automatically, and the top 3 improvements are given.

Review data collection script

The script below collects the core metrics needed for the review for an organization (requires owner permissions; some endpoints require Team/GHEC; on failure it prints a notice without interrupting).

#!/usr/bin/env bash
# usage: ORG=myorg-lab bash gov-snapshot.sh
set -uo pipefail
ORG=${ORG:?set ORG}
try(){ gh api --paginate "$@" 2>/dev/null || echo "__unavailable__"; }

echo "== Repositories and visibility"
gh repo list "$ORG" --limit 1000 --json name,visibility,isArchived \
  --jq 'group_by(.visibility)[] | "\(.[0].visibility): \(length)"'

echo "== Security feature coverage (per repository)"
for r in $(gh repo list "$ORG" --limit 1000 --no-archived --json name -q '.[].name'); do
  gh api "repos/$ORG/$r" --jq "[\"$r\", .security_and_analysis.secret_scanning.status // \"-\",
     .security_and_analysis.secret_scanning_push_protection.status // \"-\"] | @tsv" 2>/dev/null
done | awk '{t++; if($2=="enabled")s++; if($3=="enabled")p++} END{printf "secret_scanning %d/%d  push_protection %d/%d\n",s,t,p,t}'

echo "== Alert backlog"
echo "secret(open):     $(try "orgs/$ORG/secret-scanning/alerts?state=open" --jq 'length' | paste -sd+ | bc 2>/dev/null)"
echo "code(open):       $(try "orgs/$ORG/code-scanning/alerts?state=open" --jq 'length' | paste -sd+ | bc 2>/dev/null)"
echo "dependabot(open): $(try "orgs/$ORG/dependabot/alerts?state=open" --jq 'length' | paste -sd+ | bc 2>/dev/null)"

echo "== Rulesets and bypasses"
try "orgs/$ORG/rulesets" --jq '.[] | "\(.name)\t\(.enforcement)\t\(.target)"'
try "orgs/$ORG/rulesets/rule-suites?rule_suite_result=bypass&time_period=month" --jq 'length'

echo "== Members without 2FA enabled"
try "orgs/$ORG/members?filter=2fa_disabled" --jq '.[].login'
== Repositories and visibility
private: 37
public: 6
== Security feature coverage (per repository)
secret_scanning 43/43  push_protection 41/43
== Alert backlog
secret(open):     3
code(open):       27
dependabot(open): 64
== Rulesets and bypasses
prod-main-baseline	active	branch
block-secret-files	active	push
4
== Members without 2FA enabled
dave

The script is slow when there are many repositories (it calls the API per repository; mind REST rate limits, see Lesson 7); for large organizations, use a security overview export or batch queries with GraphQL instead.

Lab 8: write a one-page review conclusion for myorg-lab (about 6 minutes)

Collect data: run ORG=myorg-lab bash gov-snapshot.sh, and save the output.
Self-assessment: on the "Animation" page, check the items already achieved and record the overall level.
Fill in the review table (copy into Markdown):
# GitHub governance review — myorg-lab — 2026-11-15
| Dimension | Status | Evidence | Exception (owner/expiry) | 90-day action |
|---|---|---|---|---|
| Identity | Yellow | 1 person without 2FA | — | Enforce 2FA; evaluate GHEC SSO |
| Rulesets | Green | prod-main-baseline active | release-managers PR-only bypass | Push rulesets |
| Secrets | Green | Push protection 41/43 | 2 repositories before archiving | Archive or enable |
| Code | Yellow | CodeQL only on public repositories | No license for private repositories | Evaluate Code Security / SARIF alternative |
| Dependencies | Green | Dependency review required check | — | Add cooldown |
| AI | — | Copilot not purchased | — | Draft AI admission process |
| Audit | Red | UI only, 180 days | — | Evaluate GHEC streaming |
**Overall level: L2** · Purchases needed: Code Security (private core repositories), GHEC (audit streaming / SSO)
Troubleshooting drill: on the interactive troubleshooting tree on the "Troubleshooting" page, walk through the two paths "push blocked" and "SSO 403", and confirm you can state the diagnostic command for each step.

Case 1: 30-day governance integration after an acquisition

Problem: An acquired company uses personal accounts with no SSO; 200 repositories must be merged in. Approach: Week 1: migrate into a separate organization and immediately apply the Secret Protection configuration (push protection + history scanning); found 9 valid secrets and rotated them; Week 2: connect enterprise SSO and team sync; Week 3: apply tier properties; enterprise rulesets take effect; Week 4: enable Code Security for tier=prod, and review to set the L2 → L3 roadmap.

Case 2: review finds "all rulesets green but bypasses rampant"

Problem: Coverage is 100%, but rule insights show 18% of merges were bypasses. Approach: Interviews revealed a flaky required check; fixed test stability and introduced a merge queue, bringing the bypass rate down to 2%. Lesson: The bypass rate is a key indicator of governance health.

Case 3: a "good enough" plan for a small team

Problem: A 10-person startup, all private repositories, limited budget. Approach: Team plan + Secret Protection; Dependabot fully enabled; did not buy CodeQL, instead running open-source SAST in CI and failing the build directly; an organization ruleset protects main. The review rated it L2, with a clear note that "at 50 people, introduce Code Security and GHEC."

Interactive troubleshooting tree: quickly locate governance problems

Choose step by step starting from the symptom; the final result gives the diagnosis, commands, and fix recommendations.

High-frequency problems at a glance

SymptomMost likely causeSee
GH013 Push cannot contain secretsA commit in history contains a secretModule 2
CodeQL analysis failsBuild failure / default and advanced setup conflict / permissionsModule 3
Dependabot does not create PRsNo fixed version / limit / paused / private registry authenticationModule 4
403 SAML enforcementCredential not authorized for the organizationModule 5
Ruleset collateral damageTarget too broad / missing bypass / check name mismatchModule 6
Audit log missingStreaming failure / beyond UI retention / planModule 6
Command-line questions
1. Count the number of repositories of each visibility in the organization.
gh repo list ORG --limit 1000 --json visibility --jq 'group_by(.visibility)[] | "\(.[0].visibility): \(length)"'
2. List the members of the organization who do not have 2FA enabled.
gh api --paginate "orgs/ORG/members?filter=2fa_disabled" --jq '.[].login'
Scenario analysis question
For a 300-person SaaS company with mixed public/private repositories that uses Entra ID, design a target GitHub governance architecture (one paragraph).

GHEC enterprise + EMU (Entra ID OIDC + CAP, SCIM group mapping to teams) hosts private code; open source uses a separate non-EMU organization; repository custom properties tier/data-class; enterprise rulesets (block force pushes, signed commits) + organization rulesets (tier=prod: PR with 2 approvals, CODEOWNERS, dependency review and CodeQL gates, push rulesets); security configurations: Secret Protection for all repositories (push protection enforced, delegated bypass), Code Security added for tier=prod; Dependabot fully enabled, version updates including github-actions; audit log streamed to Event Hubs → Sentinel, detecting bypasses/visibility/ruleset changes; Copilot Business enabled in phases, new features disabled by default, public code Blocked, content exclusion for sensitive directories, cloud agent piloted first; quarterly review, with KPIs for coverage, MTTR, and bypass rate.

Verified instructional videos

▶
GitHub Advanced Security Certification – Pass the Exam! — freeCodeCamp.org
English · long-form course, useful as a full review of this hour's GHAS portion
▶
Introduction to GitHub Advanced Security | GH-500 | Episode 1 — Microsoft Learn
English · GH-500 series, suited for certification preparation

No verified video specifically on "GitHub governance maturity review" was found; the following is a storyboard script.

Official documentation

Video storyboard script (about 90 seconds)

Shot 1 · 0–20s
Visual: seven pillars (identity, policy, secrets, code, dependencies, AI, audit), each with red/yellow/green lights.
Narration: the governance review starts from seven dimensions, and each dimension needs evidence.
Shot 2 · 20–45s
Visual: a staircase from L1 to L4, with a little figure stepping from L2 toward L3.
Use the maturity model to locate the current state, then build a 90-day roadmap.
Shot 3 · 45–70s
Visual: the dashboard shows 100% coverage, but the bypass-rate needle is in the red zone.
Narration: all toggles green does not mean secure; bypass rate and fix time matter just as much.
Shot 4 · 70–90s
Visual: the troubleshooting tree branches from "symptoms" into six diagnoses.
Narration: when a problem occurs, start from the symptom and follow the troubleshooting tree to the root cause.
or score ≥ 70% on the "Quiz"

Command cheat sheet

Enterprise security and governance · gh CLI and REST API · every code block can be copied with one click
After-class reference

Security feature toggles (M1)

gh api repos/O/R --jq '.security_and_analysis'
gh api -X PATCH repos/O/R --input - <<'EOF'
{"security_and_analysis":{"secret_scanning":{"status":"enabled"},
 "secret_scanning_push_protection":{"status":"enabled"}}}
EOF
gh api -X PUT repos/O/R/vulnerability-alerts
gh api -X PUT repos/O/R/automated-security-fixes
gh api orgs/O/code-security/configurations
gh api -X POST orgs/O/code-security/configurations/ID/attach -f scope=all
gh api -X PUT orgs/O/code-security/configurations/ID/defaults -f default_for_new_repos=all

Secret scanning (M2)

gh api "repos/O/R/secret-scanning/alerts?state=open"
gh api "orgs/O/secret-scanning/alerts?state=open&validity=active"
gh api repos/O/R/secret-scanning/alerts/N/locations
gh api -X PATCH repos/O/R/secret-scanning/alerts/N \
  -f state=resolved -f resolution=revoked
# Blocked: amend the commit that introduced the secret
git commit --amend --all --no-edit        # latest commit
git rebase -i SHA~1                       # earlier commit (pick→edit)

Code scanning (M3)

gh api -X PATCH repos/O/R/code-scanning/default-setup -f state=configured -f query_suite=default
gh api repos/O/R/code-scanning/default-setup
gh api "repos/O/R/code-scanning/alerts?state=open&severity=critical"
gh api "repos/O/R/code-scanning/alerts?ref=refs/pull/N/merge"
gh api "repos/O/R/code-scanning/analyses?per_page=5"
gh api -X PATCH repos/O/R/code-scanning/alerts/N \
  -f state=dismissed -f dismissed_reason="false positive"
# workflow: github/codeql-action/init|analyze|upload-sarif@v4 (v4.39.3)

Dependabot and dependency review (M4)

gh api "repos/O/R/dependabot/alerts?state=open"
gh api "orgs/O/dependabot/alerts?state=open&severity=critical"
gh api -X PATCH repos/O/R/dependabot/alerts/N -f state=dismissed -f dismissed_reason=tolerable_risk
gh api repos/O/R/dependency-graph/sbom > sbom.spdx.json
gh api repos/O/R/dependency-graph/compare/main...feature
gh pr list --author "app/dependabot"
# PR comment: @dependabot rebase | recreate | ignore this major version
# actions/dependency-review-action@v5 (node24, runner ≥ 2.327.1)

Identity and SSO (M5)

gh auth status; gh auth refresh -s admin:org,read:audit_log,security_events
curl -sI -H "Authorization: Bearer $TOKEN" https://api.github.com/orgs/O | grep -i x-github-sso
gh api orgs/O/credential-authorizations           # GHEC owner
gh api -X DELETE orgs/O/credential-authorizations/ID
gh api "orgs/O/members?filter=2fa_disabled"
gh api orgs/O/teams/T/team-sync/group-mappings     # team sync
ssh -T git@github.com

Rulesets and audit (M6)

gh api orgs/O/rulesets
gh api -X POST orgs/O/rulesets --input ruleset.json
gh api repos/O/R/rules/branches/main
gh api "orgs/O/rulesets/rule-suites?rule_suite_result=bypass&time_period=week"
gh api orgs/O/properties/schema
gh api -X PATCH repos/O/R/properties/values --input props.json
gh api "orgs/O/audit-log?phrase=action:repository_ruleset&include=all"   # GHEC
# UI syntax: action:repo.access actor:alice created:>=2026-11-01

Copilot governance (M7)

gh api orgs/O/copilot/billing
gh api --paginate orgs/O/copilot/billing/seats --jq '.seats[] | [.assignee.login, .last_activity_at] | @tsv'
gh api -X DELETE orgs/O/copilot/billing/selected_users -f 'selected_usernames[]=dave'
gh api "orgs/O/audit-log?phrase=action:copilot"     # GHEC
# content exclusion: Settings → Copilot → Content exclusion (not a security boundary)

dependabot.yml skeleton

version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule: { interval: "weekly" }
    cooldown: { default-days: 3 }
    groups:
      minor-patch: { update-types: ["minor", "patch"] }
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule: { interval: "weekly" }
    groups:
      actions: { patterns: ["*"] }

Quick plan reference

FeaturePublic repositoryPrivate/internal repository
Dependabot alerts / updates, dependency graphFreeFree
Secret scanning + push protectionFreeSecret Protection ($19/active committer/month)
custom patterns, delegated bypass, validity checksSecret Protection
CodeQL, Copilot Autofix, dependency reviewFreeCode Security ($30/active committer/month)
Organization rulesetsTeam / Enterprise
SAML SSO, EMU, audit log API and streaming, enterprise rulesets, data residencyEnterprise Cloud
Copilot policies, content exclusionCopilot Business / Enterprise

Capstone lab + final quiz

Build a complete "secure by default" defense line in a public practice repository, and drill one secret-leak block and one vulnerability-fix closed loop
After class ≈ 40 minPublic repositories are free throughoutOrganization rulesets require Team (Free uses repository rulesets instead)
Scenario myorg-lab is about to open-source myapp-sec. Security review requires: no secret can be pushed; every PR goes through CodeQL and dependency review; unresolved high-severity alerts must not be merged; Dependabot continuously cleans up existing dependencies (including Actions in workflows); the main branch can only be changed via PR, with force pushes prohibited; all exceptions must be traceable. Complete this in myorg-lab/myapp-sec (public) and submit a drill report.
① Baseline (Module 1): enable secret scanning, push protection, Dependabot alerts and security updates, and confirm:
ORG=myorg-lab; REPO=myapp-sec
gh api repos/$ORG/$REPO --jq '.visibility, (.security_and_analysis | to_entries[] | "\(.key)=\(.value.status)")'
"public"
dependabot_security_updates=enabled
secret_scanning=enabled
secret_scanning_push_protection=enabled
② CodeQL default setup (Module 3):
gh api -X PATCH repos/$ORG/$REPO/code-scanning/default-setup -f state=configured -f query_suite=extended
gh run list --workflow "CodeQL" --limit 1
③ Dependabot version updates + dependency review (Module 4): commit the Module 4 .github/dependabot.yml (including github-actions ecosystem and grouping) and .github/workflows/dependency-review.yml.
④ Rulesets (Module 6): in a Team/Enterprise organization, create an organization ruleset prod-main-baseline (target tier=prod); in a Free organization, create a repository ruleset. Rules: block deletions and force pushes, at least 1 PR approval (a personal drill may set 0 approvals but still require a PR), required status checks dependency-review, Require code scanning results (CodeQL, High or higher).
gh api repos/$ORG/$REPO/rules/branches/main --jq '.[].type'
deletion
non_fast_forward
pull_request
required_status_checks
code_scanning
⑤ Drill A: secret-leak blocking (Module 2): generate a fine-grained PAT with no permissions and a 1-day expiry, commit it to a branch and push → observe GH013 → revoke the token first → amend to remove it → push again successfully. Record: time of blocking, the secret type and location in the output, and the revocation time.
⑥ Drill B: vulnerability-fix closed loop (Modules 3 + 4): on the branch feat/ping add the Module 3 command-injection code, and in requirements.txt add requests==2.19.1, open a PR:
gh pr checks --watch
PR=$(gh pr view --json number -q .number)
gh api "repos/$ORG/$REPO/code-scanning/alerts?ref=refs/pull/$PR/merge&state=open" --jq '.[].rule.id'
X  dependency-review
X  CodeQL
py/command-line-injection

Attempting to merge should be blocked by the ruleset. Following Module 3, fix /ping, upgrade requests to the latest patch version, and push again: all checks pass, the alert shows Fixed in the PR, then squash-merge.

⑦ Evidence collection (Modules 6, 8):
gh api "repos/$ORG/$REPO/rulesets/rule-suites?time_period=day" --jq '.[] | [.pushed_at, .actor_name, .ref, .result] | @tsv'
gh api "repos/$ORG/$REPO/code-scanning/alerts?state=fixed" --jq '.[] | [.number, .rule.id, .fixed_at] | @tsv'
gh api "repos/$ORG/$REPO/secret-scanning/alerts" --jq 'length'

Compile the outputs and screenshots into the drill report (in the format of the Module 8 review table), noting which steps need Secret Protection / Code Security in private repositories, and that the organization ruleset requires Team.

⑧ Cleanup: delete the drill branch; confirm the pp-drill token has been deleted; if the drill repository is no longer needed: gh repo delete $ORG/$REPO --yes (requires delete_repo scope); delete the organization ruleset (gh api -X DELETE orgs/$ORG/rulesets/ID); GHEC trial and Azure Event Hubs (az group delete -n rg-gh-lab --yes --no-wait) — delete promptly when not in use.
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answer)

1. What does each of GitHub Secret Protection and Code Security include? How is it billed?

Secret Protection: secret scanning, push protection, AI detection, custom patterns, delegated bypass/dismissal, validity checks, etc.; Code Security: code scanning/CodeQL, Copilot Autofix, dependency review, custom auto-triage rules, security campaigns, etc. Both are billed per active committer in the past 90 days (list price $19 / $30 per person per month) and require Team or Enterprise. The core features on public repositories are free.

2. After push protection blocks a push, why is it still blocked when you delete that line and commit again?

Push protection scans all new commits in this push, and the secret still exists in earlier commit objects. You must modify the commit that introduced the secret with amend or interactive rebase, or go through the bypass process.

3. How do you choose between CodeQL default setup and advanced setup?

Default setup needs zero maintenance, auto-detects languages, and covers most languages with no-build mode, so it suits most repositories; use advanced setup when you need custom builds, query packs, trigger conditions, or running on merge_group. The two are mutually exclusive.

4. What problems do Dependabot alerts, security updates, version updates, and dependency review each solve?

Alerts: discover existing vulnerabilities; security updates: automatically open fix PRs; version updates: keep dependencies up to date on a schedule (including Actions); dependency review: block newly added vulnerable or license-noncompliant dependencies at the PR stage.

5. What is the essential difference between SAML SSO and EMU?

SSO links an employee's own personal account, and credentials must be authorized for the organization one by one; EMU accounts are created and owned by the enterprise through the IdP, with SCIM managing the lifecycle, no public activity, and CAP validated on every access under OIDC (Entra ID); GHE.com data residency requires EMU.

6. How do you prove that no one has bypassed the production repository branch rules in the past 12 months?

Ruleset configuration and change audit events, plus bypass/push events from the audit log stream sent to long-term storage, plus a rule insights export; the UI alone (about 180 days) is not enough, so streaming (GHEC) must be configured in advance.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for all technical facts in this hour (verified 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
GHAS split and pricingSince 2025-04-01, Secret Protection $19 and Code Security $30 per active committer per month; Team can self-serve on metered purchase; free secret risk assessmentChangelog 2025-03-04 · github.com/security/plans
Product feature boundariesFeatures included in each product; Team/Enterprise required to purchase; the part free for public repositories; code security risk assessment covers up to 20 repositoriesAbout GitHub Advanced Security
BillingActive committer = pushed within 90 days; metered (GHEC, GHES 3.13+ via GitHub Connect) and volume; bots not countedGHAS license billing
GHAS trialSelf-serve trial scope expanded on 2026-09-09Changelog 2026-09-09
Secret scanningFree public-repository scanning runs automatically; scans all branch history, issues, PRs, discussions, wikis, and secret gists; partner program directly notifies providers; generic/custom/AI detectionAbout secret scanning
Push protectionUser-level enabled by default (public repositories); repository-level must be enabled; three bypass reasons; delegated bypass and exemptions; covers CLI/Web/API/MCP (public); AI detection push protection is in public previewAbout push protection
Unblocking from the command lineRemove via amend / rebase; push again within 3 hours after bypass; the URL is accessible only to the pusherPush protection from the command line
CodeQL default setupRequires Actions; public or Code Security; C/C++, C#, Java, Rust use build-mode none; scheduled scanning is disabled after 6 months of inactivity; code-scanning label runnerConfiguring default setup
codeql-actionLatest tag v4.39.3 (git ls-remote, 2026-11-15); v4 is latest, v3 still supportedgithub/codeql-action
SARIF≤ 10 MB after gzip; ≤ 20 runs/file; ≤ 25,000 results/run, top 5,000 displayed; partialFingerprints; category rulesSARIF support
Copilot AutofixNo Copilot subscription required; can be turned off for CodeQL default setup; list of supported languages; limitations (non-deterministic, may suggest nonexistent dependencies)Responsible use of Autofix
RulesetsRequire code scanning results rule; push rulesets apply to private/internal repositories and fork networks; organization rulesets opened to Team (2025-06-16); enterprise rulesets GA (2025-03-24)Available rules · Changelog 2025-06-16 · Changelog 2025-03-24
Dependabotschedule values (including cron, quarterly, etc.); groups, multi-ecosystem-groups, cooldown (version updates default 3 days); PRs are paused after long-term neglectOptions reference · Changelog 2023-01-12
Auto-triageTwo GitHub built-in rules (dev dependencies low impact, malicious package alerts); custom rules free for public, private requires Code SecurityAbout auto-triage rules
dependency-review-actionv5.0.0 (05-08): Node 24, runner ≥ v2.327.1; v4.9.0 added show_patched_versions; deny list deprecated in v4.7.2Releases
EMUSupported IdPs: Entra ID, Okta, PingFederate; OIDC Entra ID only and validates CAP; SCIM; cannot create public content; mixing Okta+Entra is not supportedAbout EMU
SAML SSOPAT/SSH require authorization; SAML session defaults to 24 hours; OAuth/GitHub App authorization requires an active sessionAbout SSO
Data residencyGHE.com regions: EU (including Norway, Switzerland), Australia, US, Japan; EMU required; no public repositoriesData residency
Audit log streamingS3 (keys/OIDC), Azure Blob, Azure Event Hubs, Datadog, GCS, Splunk, Microsoft Purview (Copilot agent session events only); multi-endpoint is preview; 24-hour health check; pauses of 7 days cachedStreaming the audit log
Copilot policiesFeatures/agents/models, cloud access, default state policies; enterprise "let organizations decide"; multi-license conflict rulesAbout Copilot policies
Content exclusionBusiness/Enterprise; not a file system security boundary; support matrix; MCP not guaranteed to complyContent exclusion
Copilot cloud agentDocumentation now calls it "Copilot cloud agent"; write permission needed to trigger; copilot/ branch; workflow requires approval; requester cannot approve; firewall; commits signedRisks and mitigations

Video verification notes

The following videos were verified for title and channel via the YouTube oEmbed endpoint (2026-11-15): GitHub, "Introduction to secret leaks and getting started with GitHub Secret Protection" (vMhDkt5JNN0), "What is code scanning?" (Grel10blARo), "Code fixes in minutes, not months | Copilot Autofix" (mr6vQMDy-YU), "How to fix vulnerabilities automatically with Dependabot" (kyjQXPTuvqo), "Security in 60 Seconds: Vulnerability Prioritization with Dependabot" (2TmBPS4Ce-U), "Authenticating to GitHub the classic way vs the EMU (Enterprise Managed Users) way" (lwCm1ouN2ig), "Introducing repository rules" (sdE-jlIuK1A), "Govern your repositories with Push Rulesets" (u3MHqfeBzek), "Quickly collect GitHub Enterprise Audit Logs - Splunk - GitHub Checkout" (oASCxWDTAQo); Microsoft Learn, "Introduction to GitHub Advanced Security | GH-500 | Episode 1" (hb7AllAd7l0), "Course Preview | GH-500 | GitHub Advanced Security" (ikneq7kZIDw); freeCodeCamp.org, "GitHub Advanced Security Certification – Pass the Exam!" (i740xlsqxEM); Mickey Gousset, "GitHub Secret Scanning: Configure Your Push Protection Patterns" (RJCVRSqmrVU), "Use Dependabot Version Updates to Update Your GitHub Actions" (hY95AAKOVTw), "Introduction to GitHub Actions - Part 6 - Repository Rulesets" (ZTbM-h9RZOo); Jack G Kafaty, "GitHub Enterprise Cloud - Enterprise Managed Users ( Microsoft Entra ID - Single Sign-On Setup)" (GT76AOfE0B8); Rob Bos, "GitHub Copilot Features - Content exclusions" (J2qaVAaQzY8); TechRill Academy, "Copilot Settings for GitHub Enterprise Administrators" (2MrlPpDiWTg). oEmbed does not return durations or publish dates, so durations are not listed on the cards. No verified dedicated video was found for Copilot cloud agent governance or the governance maturity review; storyboard scripts are provided instead. All videos are in English, and their recording dates may predate the 2026 product renames and UI changes; this hour and the official documentation take precedence.

Audio narration notes

The "Audio" page uses the browser's Web Speech API (speechSynthesis, en-US) reads the script aloud in real time, and English terms are pronounced with en-US. The result depends on the voices installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; when offline audio is needed, pass the script to a TTS service such as Azure AI Speech.

Known limitations

  • The IDs, numbers, SHAs, timestamps, URLs, and GHSA IDs in the "expected output" blocks are example values; the exact format of GH013 output follows the actual output.
  • Prices are the list prices GitHub published (2025-03-04); no official price change was found for 2026. The usage-based billing for push protection with AI detection comes from third-party reports and was not verified in the official Changelog text, so this hour says "follow the official source".
  • Copilot product names and entry points changed a lot in 2026 (coding agent → cloud agent, the AI controls page, partner agents); policy names and UI paths follow what your account shows. The original text for Copilot Business/Enterprise list prices was not found on an official page during this verification, so it is marked "see the plans page".
  • The interaction between fine-grained PATs and SAML SSO, the audit log UI retention (about 180 days; Git events 7 days), and the EMU username short-code suffix format were not found verbatim during this verification, so they are stated conservatively based on the long-standing documentation.
  • SAML SSO, EMU, team sync, audit log API/streaming, enterprise rulesets, and Evaluate mode require GitHub Enterprise Cloud; this hour presents them through theory, example output, and design exercises.
  • The rulesets, policies, and advisory data in the animations are illustrative, used to explain the mechanisms.