GitHub Hour 6: Enterprise Security and Governance in Practice
- 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-actionsecosystems, 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
| # | Time | Module | Core content | Animation / interaction | Lab (public practice repository myapp-sec) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: security lab repository | free organization myorg-lab, public repository myapp-sec, gh token scopes, optional GHAS trial | Plan self-check | Repository and gh ready |
| 1 | 00–06 | Security product overview and licensing | Secret Protection / Code Security split and pricing, free portion for public repositories, security overview, security configurations, risk assessment | “Plan × visibility → available features” calculator | Use the API to view and enable repository security features |
| 2 | 06–14 | Secret scanning and push protection | pattern types, partner program, custom patterns, push protection blocking and bypass, delegated bypass, validity checks, rotate first | Core animation: git push → server-side scan → GH013 → bypass/approval → alert | Practice blocking and handling with a one-time PAT |
| 3 | 14–22 | Code scanning and CodeQL | default vs advanced setup, CodeQL workflow, query suites, SARIF, PR alerts, Copilot Autofix, triage and dismissal | Core animation: build database → query → SARIF → PR alert | default setup + introduce a command injection and fix it |
| 4 | 22–30 | Dependabot and dependency review | dependency graph, alerts, security/version updates, dependabot.yml (grouping, cooldown, github-actions), dependency-review-action, auto-triage | Alert matching + PR gate simulator | Introduce a vulnerable requests and get blocked by the gate |
| 5 | 30–38 | Organizations and enterprises: SSO, EMU, team sync | SAML SSO and credential authorization, EMU (Entra OIDC/CAP), SCIM, team sync, GHE.com data residency | “Token + session → 200/403” decision simulation | Read SSO authorization status (concept + API) |
| 6 | 38–46 | Rulesets, audit logs, and compliance | organization/enterprise rulesets, target repository patterns, bypass, rule insights, audit log queries and streaming, compliance reports | Ruleset stacking evaluator | Organization ruleset + audit log query |
| 7 | 46–53 | Copilot and AI feature governance | Business/Enterprise policies, content exclusions, public code match filtering, audit, coding agent governance toggles | Enterprise × organization policy resolver | Policy inventory checklist |
| 8 | 53–60 | Governance architecture review | review checklist, maturity model, troubleshooting tree | Maturity self-assessment + interactive troubleshooting tree | Produce a one-page review conclusion |
| — | After class | Cheat sheet · Capstone lab | one secret leak blocked + one vulnerability fix, closed loop | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / configuration | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Determine the plan and license a feature requires | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | security configurations | M1 calculator |
| Enable security features at scale | ✓ | · | ✓ | ✓ | · | · | · | ✓ | gh api …/code-security/configurations | M1 lab |
| Block secrets from entering the repository and handle them correctly | · | ✓ | · | · | · | ✓ | · | ✓ | secret-scanning/alerts, GH013 | leak drill |
| Static analysis and PR gating | · | · | ✓ | · | · | ✓ | · | ✓ | codeql-action/init|analyze|upload-sarif | Command injection fix |
| Dependency vulnerabilities and supply chain gating | · | · | · | ✓ | · | ✓ | · | ✓ | dependabot.yml, dependency-review-action | requests vulnerability |
| Identity and access (SSO / EMU / SCIM) | · | · | · | · | ✓ | · | ✓ | ✓ | gh auth refresh, credential authorization | 403 diagnosis |
| Ruleset and exception governance | · | ✓ | ✓ | ✓ | · | ✓ | · | ✓ | gh api orgs/ORG/rulesets | Organization ruleset |
| Audit and compliance evidence | · | ✓ | · | · | ✓ | ✓ | ✓ | ✓ | audit log queries, streaming | M6 lab |
| AI feature governance | · | · | ✓ | · | · | · | ✓ | ✓ | Copilot policies, content exclusions | M7 checklist |
What this hour does not cover (and where to learn it)
| Topic | Why it is not in this hour | Where to learn |
|---|---|---|
| branch protection, ruleset basics, CODEOWNERS, PR merge methods | The Git course already covered platform basics | Git Lesson 3: Moving to a Hosted Platform |
Actions security hardening (GITHUB_TOKEN least privilege, pinning by SHA,pull_request_target), artifact attestations, required workflows | Covered in the previous lesson | Lesson 5: Production-grade Actions |
| OIDC federated credentials to Azure/AWS | Cloud deployment topics | Lesson 3 Azure · Lesson 4 AWS |
| Writing CodeQL custom query language (QL), variant analysis (MRVA) | Belongs to security research, beyond 1 hour | CodeQL documentation |
| GitHub Enterprise Server (self-hosted) operations | This hour follows GitHub.com / GHE.com | GHES administration documentation |
| Container image scanning, K8s runtime security | Covered in later courses | Docker course · K8s course |
How to use this courseware
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.
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).
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.
Module 0 · Preparation: security lab repository (complete before class)
- CompletedLesson 5: a personal account and a sample organization
myorg-lab(sample name, replace with your own organization), with the local install ofghCLI 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 repositorymyorg-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 hour | Public repository (any plan) | Private/internal repository | Approach in this hour |
|---|---|---|---|
| Secret scanning + push protection | Free | Requires Team/Enterprise + Secret Protection | Hands-on in public repository |
| custom patterns, delegated bypass, validity checks, AI detection | Requires Secret Protection (organization repositories) | Requires Secret Protection | Theory + GHAS trial (optional) |
| CodeQL code scanning, Copilot Autofix | Free | Requires Code Security | Hands-on in public repository |
| Dependabot alerts / security updates / version updates | Free | Free (all plans) | Hands-on |
| Dependency review | Free | Requires Code Security | Hands-on |
| Organization rulesets | Requires 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 rulesets | Requires GitHub Enterprise Cloud | Theory + 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" }
}
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.
Module 1 · GitHub security product overview and licensing
- 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.
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:
| Product | Problem solved | Includes (per docs.github.com, 2026-11) | List price (Changelog 2025-03-04) |
|---|---|---|---|
| GitHub Secret Protection | Detect and block credential leaks | secret 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 Security | Find and fix code and dependency vulnerabilities | code 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
| Level | Features |
|---|---|
| Free for all repositories and all plans | dependency 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 repositories | secret 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 native | Azure DevOps | Third-party (Snyk / SonarQube / GitGuardian, etc.) | |
|---|---|---|---|
| Secrets | Secret Protection: server-side push protection + partner automatic revocation notifications | GitHub Advanced Security for Azure DevOps (billed separately) | mostly pre-commit / CI scanning, with weak server-side blocking |
| SAST | CodeQL (semantic database + data flow) | Same as above (based on CodeQL) | Rule engines vary; can be SARIF uploaded to GitHub for unified display |
| Dependencies | Dependabot + dependency review (Advisory Database) | dependency scanning (GHAzDO) | richer vulnerability and license data; can be used together |
Architecture diagram: where GitHub security capabilities sit in the development lifecycle
Flowchart: scaling enablement with a security configuration
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).
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
gh api repos/O/R --jq .security_and_analysis | View repository security feature status | Read-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-alerts | Enable Dependabot alerts | automated-security-fixes Enable security updates |
GET /orgs/O/code-security/configurations | List the organization's security configurations | Requires admin:org or security manager |
POST …/configurations/ID/attach | Apply a configuration to repositories | scope: all / public / private_or_internal / selected etc. |
PUT …/configurations/ID/defaults | Set as default configuration for new repositories | default_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)
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.secret_scanning_push_protection=enabled,dependabot_security_updates=enabled.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.
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).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.
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
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
Official documentation
- About GitHub Advanced Security
- GitHub Advanced Security license billing
- Changelog: Introducing Secret Protection and Code Security
- About enabling security features at scale
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 2 · Secret scanning and push protection
- 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
GH013reject 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.
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 type | Examples | What it produces | Notes |
|---|---|---|---|
| Partner program (partner program) | AWS, Azure, Slack, npm, etc. tokens in public repositories | Directly notifies the service provider, which may automatically revoke it; does not appear in repository alerts | Applies automatically to public content; no configuration needed |
| Provider patterns (provider patterns) | GitHub PAT (ghp_/github_pat_), Azure Storage key, Stripe key | Repository alerts (user alerts); high-confidence patterns participate in push protection by default | The 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 headers | Repository 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 protection | Defined 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 preview | Renamed 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) | |
|---|---|---|
| Default | For all GitHub.com accounts Enabled by default, can be disabled in personal Settings → Code security | Disabled by default; enabled by a repository admin, organization owner, security manager, or enterprise owner |
| Scope | Blocks you from pushing to any public repository supported secrets | Blocks anyone from pushing to this repository secrets |
| After bypass | no alert is generated (unless enabled at the repository level too) | generates an alert + audit log + email notification |
| License | Free | Free 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
- Rotate/revoke: immediately revoke the credential at the provider and generate a new one, then update Key Vault / Secrets Manager / Actions secrets.
- 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.
- Close the alert: select Revoked; record a ticket.
- (optional) Clean up history: only when compliance requires it, use
git filter-repoto 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.
Sequence diagram: a push blocked by push protection
Decision diagram: response after discovering a leak
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).
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
GET /repos/O/R/secret-scanning/alerts | List repository secret alerts | state=open,secret_type,validity=active; the organization-level equivalent is /orgs/O/secret-scanning/alerts |
GET …/alerts/N/locations | View where a secret appears | commits, file lines, issue comments, etc. |
PATCH …/alerts/N | Close alert | state=resolved + resolution: false_positive / wont_fix / revoked / used_in_tests |
git commit --amend / git rebase -i | Remove the secret from commits that were never successfully pushed | for a secret in the latest commit, use amend; for an earlier commit, use interactive rebase (edit) |
git filter-repo --replace-text | Rewrite pushed history | requires third-party tools; after force-push, notify all collaborators to re-clone |
gh secret set | Write the newly rotated credential into Actions secrets | Do 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)
pp-drill, Expiration 1 day, Repository access set to "Public repositories (read-only)", add no permissions. Copy the token (github_pat_…).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.
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
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).
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.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.
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
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
Official documentation
- About secret scanning
- About push protection
- Working with push protection from the command line
- Supported secret scanning patterns
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 3 · Code scanning and CodeQL
- 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 (
categoryto distinguish multiple analyses), handle alerts in PRs, use Copilot Autofix, triage and dismiss by severity, and use rulesets for merge gating.
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 setup | advanced setup | |
|---|---|---|
| Configuration method | Settings → Advanced Security → CodeQL analysis → Set up → Default; or security configuration; or API | Commit .github/workflows/codeql.yml |
| Trigger | pushes 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.) |
| languages | Automatically detects the CodeQL-supported languages in the repository; can be added or removed in the UI; new languages are included automatically once added | explicitly listed in the matrix |
| build | For C/C++, C#, Java, Rust, use build-mode: none (no build needed); for other compiled languages use autobuild | optional none / autobuild / manual (write your own build steps) |
| query suite | Default or Extended | Any: security-extended,security-and-quality, custom qlpack / query files |
| runner | GitHub-hosted, or with code-scanning label self-hosted/larger runners | any |
| Prerequisites | repository has Actions enabled; public or with Code Security enabled | same as left; mutually exclusive with default setup |
Query suites
- default (
code-scanningsuite): 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_groupself-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.
Architecture diagram: from source code to alerts in CodeQL
Data flow illustration: source → sink
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).
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
PATCH /repos/O/R/code-scanning/default-setup | Enable/disable default setup | state=configured|not-configured,query_suite=default|extended |
GET /repos/O/R/code-scanning/alerts | List alerts | state,severity,tool_name,ref=refs/pull/N/merge |
PATCH …/alerts/N | Dismiss/reopen | state=dismissed + dismissed_reason: false positive / won't fix / used in tests |
GET /repos/O/R/code-scanning/analyses | View each analysis (tool, category, result count) | Investigate "why are there no alerts" |
github/codeql-action/upload-sarif@v4 | Upload third-party SARIF | category Distinguish multiple analyses of the same tool |
codeql database create / analyze | Run the CodeQL CLI locally or in another CI | Using 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)
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).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 mainsubprocess.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
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.
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.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.
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'
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
Official documentation
- Configuring default setup for code scanning
- SARIF support for code scanning
- Responsible use of Copilot Autofix for code scanning
- github/codeql-action
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 4 · Dependabot and dependency review
- 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),groupsgrouping,cooldowncooldown period,schedule,ignore. - Use
actions/dependency-review-action@v5as PR gates (severity, licenses), and use auto-triage rules to reduce alert noise.
What: five easily confused concepts
| Feature | What it does | Trigger | License |
|---|---|---|---|
| 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 SBOM | Pushed to the default branch | Free; enabled by default on public repositories |
| Dependabot alerts | Matches the dependency graph with GitHub Advisory Database advisories, generating vulnerability alerts (including malicious package alerts) | dependency change, or new advisory published | Free |
| Dependabot security updates | Automatically opens PRs for alerts, upgrading to the lowest fixed version | When an alert is generated | Free |
| Dependabot version updates | Upgrades dependencies to the latest version on a schedule (unrelated to vulnerabilities) | dependabot.yml schedule in | Free |
| 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 action | PR | Free 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;updatesone per item inpackage-ecosystem(such aspip,npm,docker,github-actions,terraform), plusdirectory/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 bypatterns/exclude-patterns,dependency-type(development/production),update-types(major/minor/patch) grouping;applies-to: security-updatesto apply groups to security updates too. Also a cross-ecosystemmulti-ecosystem-groupsgroups.cooldowncooldown: wait a number of days after a new version is released before opening PRs (default-days,semver-major-daysetc.), 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-actionsecosystem: 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
| Dependabot | Renovate | Snyk / Mend | |
|---|---|---|---|
| Hosted | GitHub built-in, free | Self-hosted or Mend-hosted App | Commercial SaaS |
| Configuration capability | Sufficient; grouping and cooldown are now covered | Very flexible (regex managers, merge policies) | policies, reachability analysis |
| Vulnerability database | GitHub Advisory Database (with community review) | OSV, etc. | Own vulnerability database |
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
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).
Core configuration and commands
| Command / API | Purpose | Notes |
|---|---|---|
GET /repos/O/R/dependabot/alerts | List alerts | state,severity,ecosystem,scope; organization level /orgs/O/dependabot/alerts |
PATCH …/dependabot/alerts/N | dismiss alerts | dismissed_reason: fix_started / inaccurate / no_bandwidth / not_used / tolerable_risk |
GET /repos/O/R/dependency-graph/compare/BASE...HEAD | Dependency review API (called by the action under the hood) | Returns added/removed dependencies and vulnerabilities |
GET /repos/O/R/dependency-graph/sbom | Export SPDX SBOM | Compliance delivery |
@dependabot rebase / recreate / ignore this major version | PR comment commands | Interact 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)
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.
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.
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.
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.
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).
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"
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
Official documentation
Video storyboard script (about 90 seconds)
Visual: requirements.txt expands into a dependency tree.
Narration: the dependency graph parses your manifest files, knowing which packages you use directly and indirectly.
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.
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.
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.
Module 5 · Organizations and enterprises: SSO, EMU, team sync
- 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 enforcement403. - Describe EMU's SCIM provisioning, OIDC + conditional access policies (CAP), team sync / IdP group mapping, and GHE.com data residency regions and limitations.
What: three identity models
| Organization-level SAML SSO | Enterprise-level SAML SSO | Enterprise Managed Users (EMU) | |
|---|---|---|---|
| Account ownership | The user's own GitHub personal account, linked to an external identity via SAML | A 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) | |
| Authentication | Accessing the organization's resources requires a valid SAML session | Accessing all organization resources within the enterprise requires | Sign-in only through the IdP: SAML (Entra ID, Okta, PingFederate) or OIDC (Entra ID only) |
| Provisioning/deprovisioning | Manual invitation; optional SCIM (some IdPs) | Same as left | SCIM required: the IdP creates, updates, and deactivates accounts; deactivation removes access |
| Team members | Team sync (Entra ID, Okta) | Same as left | IdP groups connected to GitHub teams (SCIM groups) |
| Public activity | Unrestricted | Unrestricted | Cannot create public content, cannot collaborate outside the enterprise; cannot change profile name and email |
| Applies | Small pilots | Most enterprises | Enterprises 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.
ghThe CLI is an OAuth App,gh auth loginand 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.
Flowchart: how an API request with SAML SSO is judged
Architecture diagram: EMU identity lifecycle
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).
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
gh auth login --web / gh auth refresh | Re-authorize gh (including SSO) | Click Authorize for the organization in the web flow |
curl -I -H "Authorization: Bearer $TOKEN" https://api.github.com/orgs/O | View X-GitHub-SSO response headers | the header gives the authorization URL or partial-results; organizations=… |
GET /orgs/O/credential-authorizations | Owner views a member's authorized credentials | GHEC; can DELETE …/{credential_id} revoke |
GET /scim/v2/enterprises/E/Users | EMU: view users provisioned via SCIM | Usually called by the IdP; read-only use during troubleshooting |
GET /orgs/O/teams/T/team-sync/group-mappings | View IdP group mapping for team sync | Team sync for non-EMU |
ssh -T git@github.com | Test SSH authentication | Cloning 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)
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.
gh-users, IdP groups gh-team-platform mapped to teams platform, short code acme, and how open source contributions are handled.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.
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
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
Official documentation
- About Enterprise Managed Users
- About authentication with single sign-on
- About GitHub Enterprise Cloud with data residency
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 6 · Rulesets, audit log, and compliance
- 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.
What: three layers of rulesets
| Level | Available plans | Target | Typical use |
|---|---|---|---|
| Repository ruleset | Public repositories: all plans; private repositories: Pro/Team/Enterprise | Branches/tags/pushes in this repository | Detailed rules self-managed by the team |
| Organization ruleset | Team (since 2025-06-16), Enterprise Cloud | By repository name pattern (include/exclude, fnmatch),custom properties (such as tier=prod) or all repositories | Organization-wide unified main protection, tag protection, push restrictions |
| Enterprise ruleset | Enterprise Cloud (GA 2025-03-24) | By organization name / organization properties + repository properties | Enterprise-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 asaction:repo.destroy created:>=2026-11-01. - Audit log REST API:
/orgs/O/audit-logand/enterprises/E/audit-logrequire GitHub Enterprise Cloud, token scoperead: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
- Define repository custom properties (
tier,data-class,owner-team), required when creating a repository. - 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. - Push ruleset: block secret-type file extensions and oversized files.
- Bypass only for the "release-managers" team, mode For pull requests only.
- Stream the audit log to a SIEM and set alerts: ruleset modified, bypass, repository visibility changed to public, push protection bypass, SSO settings changed.
Architecture diagram: ruleset stacking evaluation
Architecture diagram: audit evidence chain
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).
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
gh api orgs/O/rulesets | List organization rulesets | POST Create,PUT …/ID update; JSON can be managed in Git |
gh api repos/O/R/rules/branches/main | View all rules actually in effect on a branch | includes rules from the organization/enterprise (after stacking) |
gh api orgs/O/rulesets/rule-suites | rule insights | rule_suite_result=bypass|fail,actor_name,time_period |
gh api orgs/O/properties/schema | custom property definitions | Rulesets select repositories by property |
gh api "orgs/O/audit-log?phrase=…" | Query audit log | GHEC; include=web|git|all; read:audit_log |
gh api enterprises/E/audit-log/streams | View streaming configuration | enterprise 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)
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"}]}
EOFrelease-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
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 .idgit 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
gh api "repos/$ORG/myapp-sec/rulesets/rule-suites?rule_suite_result=fail".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.rg-gh-lab.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.
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'
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
Official documentation
- Available rules for rulesets
- Changelog: Organization rulesets for GitHub Team
- Streaming the audit log for your enterprise
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 7 · Copilot and AI feature governance
- 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.
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
| Setting | Recommendation | Rationale |
|---|---|---|
| New feature/model default state | Disabled; enable after evaluation | Avoids automatically exposing unreviewed capabilities to everyone |
| Suggestions matching public code | Blocked (or Allowed + code referencing + legal process) | Reduces license risk |
| Content exclusion | Exclude directories containing customer data samples, key templates, and export-controlled material | Reduces sensitive context entering prompts |
| cloud agent | Enable first for pilot organizations/repositories; keep manual approval of workflows | An agent is a principal that can write code and trigger CI |
| Partner agents / MCP | Enable one by one after evaluating vendors and data flows | Third-party data processing |
| Audit | Audit log stream + monthly policy and seat review | Compliance evidence |
Architecture diagram: Copilot policy resolution
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.
Core commands and API
| Command / API | Purpose | Notes |
|---|---|---|
GET /orgs/O/copilot/billing | Organization Copilot settings overview | fields such as seat management method, public code suggestion policy |
GET /orgs/O/copilot/billing/seats | List seats and last activity time | Reclaim inactive seats |
POST/DELETE /orgs/O/copilot/billing/selected_teams | Assign/unassign seats by team | Together with IdP group → team (Module 5) |
GET /orgs/O/copilot/metrics | Usage metrics | Endpoints 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 events | GHEC |
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)
DELETE /orgs/O/copilot/billing/selected_users).myapp-sec add "/config/**", open in VS Code config/settings.py, and confirm the Copilot icon shows that file as excluded (no completions offered).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.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.
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'
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
No verified official GitHub video on cloud agent governance toggles was found; the following is a storyboard script.
Official documentation
- About Copilot policies
- Content exclusion
- Copilot cloud agent: Risks and mitigations
- Managing policies for Copilot in your organization
Video storyboard script (about 90 seconds)
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.
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.
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.
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.
Module 8 · Comprehensive governance architecture review
- 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.
What: governance architecture review checklist
| Dimension | Must-check items | Evidence source | Required plan |
|---|---|---|---|
| Identity and access | SSO/EMU scheme; SCIM; enforced 2FA; PAT policy (fine-grained, approval, maximum lifetime); outside collaborator process; IP allow list | Organization settings,credential-authorizations, audit log | 2FA/PAT policy: all; SSO/EMU/IP: GHEC |
| Repositories and policy | Complete custom properties; organization/enterprise rulesets cover the default branch and tags; push rulesets; minimize bypass (PR only); members cannot change visibility or delete repositories | rules/branches/main, rule insights | Organization rulesets: Team+ |
| Secrets | Push protection fully covered and enforced; delegated bypass; custom patterns; validity checks; leak response runbook (rotate first); CI uses OIDC | security overview, alerts API | Private repositories: Secret Protection |
| Code | CodeQL default setup coverage; advanced setup templated; ruleset code scanning gate; alert SLA; Autofix review requirement | Coverage view, analyses API | Private repositories: Code Security |
| Dependencies and supply chain | Dependabot 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, rulesets | Private repository dependency review: Code Security |
| AI features | New features disabled by default; public code policy; content exclusion; cloud agent scope and guardrails; partner agent evaluation; seat review | Copilot settings, audit log | Copilot Business/Enterprise |
| Audit and response | Audit log streaming and health alerts; detection rules (bypass, visibility, ruleset changes, SSO changes); retention meets compliance; drill records | SIEM, stream configuration | Streaming: GHEC |
Maturity model (the teaching model used in this hour)
| Level | Characteristics | Typical next step |
|---|---|---|
| L1 Passive | Repositories configured manually one by one; only public repositories are scanned; no unified rules; leaks are discovered after the fact | Enable free features + user-level/repository-level push protection; Dependabot fully enabled |
| L2 Baseline | security configuration covers all repositories; organization rulesets protect the default branch; SSO | dependency review gate; CodeQL default setup; alert SLA |
| L3 Controlled | enforced configurations; delegated bypass; code scanning merge gate; audit log stream + detection; EMU/SCIM; Copilot policy-driven | custom patterns, attribute-driven tiered policies, AI admission process |
| L4 Metrics-driven | KPIs 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
- 10 minutes: current data (security overview coverage, alert backlog and MTTR, bypass statistics, seat data).
- 20 minutes: go through the checklist dimension by dimension, marking red/yellow/green, and record exceptions.
- 10 minutes: rate the maturity (L1–L4) and set a 90-day roadmap (each item has an owner).
- 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).
Reference architecture: governance overview of a GHEC enterprise
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)
ORG=myorg-lab bash gov-snapshot.sh, and save the output.# 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)
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
| Symptom | Most likely cause | See |
|---|---|---|
| GH013 Push cannot contain secrets | A commit in history contains a secret | Module 2 |
| CodeQL analysis fails | Build failure / default and advanced setup conflict / permissions | Module 3 |
| Dependabot does not create PRs | No fixed version / limit / paused / private registry authentication | Module 4 |
| 403 SAML enforcement | Credential not authorized for the organization | Module 5 |
| Ruleset collateral damage | Target too broad / missing bypass / check name mismatch | Module 6 |
| Audit log missing | Streaming failure / beyond UI retention / plan | Module 6 |
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'
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
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)
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.
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.
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.
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.
Command cheat sheet
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=allSecret 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
| Feature | Public repository | Private/internal repository |
|---|---|---|
| Dependabot alerts / updates, dependency graph | Free | Free |
| Secret scanning + push protection | Free | Secret Protection ($19/active committer/month) |
| custom patterns, delegated bypass, validity checks | Secret Protection | |
| CodeQL, Copilot Autofix, dependency review | Free | Code Security ($30/active committer/month) |
| Organization rulesets | Team / Enterprise | |
| SAML SSO, EMU, audit log API and streaming, enterprise rulesets, data residency | Enterprise Cloud | |
| Copilot policies, content exclusion | Copilot Business / Enterprise | |
Capstone lab + final quiz
myorg-lab/myapp-sec (public) and submit a drill report.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
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
.github/dependabot.yml (including github-actions ecosystem and grouping) and .github/workflows/dependency-review.yml.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
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.
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.
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.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
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| GHAS split and pricing | Since 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 assessment | Changelog 2025-03-04 · github.com/security/plans |
| Product feature boundaries | Features included in each product; Team/Enterprise required to purchase; the part free for public repositories; code security risk assessment covers up to 20 repositories | About GitHub Advanced Security |
| Billing | Active committer = pushed within 90 days; metered (GHEC, GHES 3.13+ via GitHub Connect) and volume; bots not counted | GHAS license billing |
| GHAS trial | Self-serve trial scope expanded on 2026-09-09 | Changelog 2026-09-09 |
| Secret scanning | Free public-repository scanning runs automatically; scans all branch history, issues, PRs, discussions, wikis, and secret gists; partner program directly notifies providers; generic/custom/AI detection | About secret scanning |
| Push protection | User-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 preview | About push protection |
| Unblocking from the command line | Remove via amend / rebase; push again within 3 hours after bypass; the URL is accessible only to the pusher | Push protection from the command line |
| CodeQL default setup | Requires 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 runner | Configuring default setup |
| codeql-action | Latest tag v4.39.3 (git ls-remote, 2026-11-15); v4 is latest, v3 still supported | github/codeql-action |
| SARIF | ≤ 10 MB after gzip; ≤ 20 runs/file; ≤ 25,000 results/run, top 5,000 displayed; partialFingerprints; category rules | SARIF support |
| Copilot Autofix | No 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 |
| Rulesets | Require 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 |
| Dependabot | schedule values (including cron, quarterly, etc.); groups, multi-ecosystem-groups, cooldown (version updates default 3 days); PRs are paused after long-term neglect | Options reference · Changelog 2023-01-12 |
| Auto-triage | Two GitHub built-in rules (dev dependencies low impact, malicious package alerts); custom rules free for public, private requires Code Security | About auto-triage rules |
| dependency-review-action | v5.0.0 (05-08): Node 24, runner ≥ v2.327.1; v4.9.0 added show_patched_versions; deny list deprecated in v4.7.2 | Releases |
| EMU | Supported IdPs: Entra ID, Okta, PingFederate; OIDC Entra ID only and validates CAP; SCIM; cannot create public content; mixing Okta+Entra is not supported | About EMU |
| SAML SSO | PAT/SSH require authorization; SAML session defaults to 24 hours; OAuth/GitHub App authorization requires an active session | About SSO |
| Data residency | GHE.com regions: EU (including Norway, Switzerland), Australia, US, Japan; EMU required; no public repositories | Data residency |
| Audit log streaming | S3 (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 cached | Streaming the audit log |
| Copilot policies | Features/agents/models, cloud access, default state policies; enterprise "let organizations decide"; multi-license conflict rules | About Copilot policies |
| Content exclusion | Business/Enterprise; not a file system security boundary; support matrix; MCP not guaranteed to comply | Content exclusion |
| Copilot cloud agent | Documentation now calls it "Copilot cloud agent"; write permission needed to trigger; copilot/ branch; workflow requires approval; requester cannot approve; firewall; commits signed | Risks 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.