Skip to main content

Chapter 6: Security, Audit & Compliance

Part II: Licensing, Policies & Governance Prerequisites: Chapter 5: Copilot Policies & Content Controls, Chapter 8: Access Control & Permissions Model GH-100 Exam Mapping: Domain 5 (Enable secure software development and ensure compliance -- 36%) Verified: 2026-02-01 against official documentation


1. Introduction​

This is the most critical chapter in the book. Domain 5 -- "Enable secure software development and ensure compliance" -- accounts for 36% of the GH-100 exam weight, more than double any other domain. If you master the material in this chapter, you have secured more than a third of the exam before opening another page. If you skip it, passing becomes nearly impossible regardless of your performance elsewhere.

GitHub Enterprise Cloud (GHEC) provides a comprehensive security platform that spans every phase of the software development lifecycle (SDLC): from the moment a developer writes code, through the pull request review process, into the Continuous Integration/Continuous Deployment (CI/CD) pipeline, and across every administrative action taken in your enterprise. This chapter covers six interconnected security pillars that together form GitHub's enterprise security posture:

  1. Code scanning with CodeQL -- static analysis that finds vulnerabilities in source code before they reach production
  2. Secret scanning and push protection -- detection and prevention of credential leaks in repositories
  3. Dependabot alerts and security updates -- automated monitoring and patching of vulnerable dependencies
  4. Repository rulesets and branch protection -- governance rules that enforce code review, status checks, and deployment gates
  5. Audit log streaming and SIEM integration -- comprehensive activity logging with enterprise-grade export to Security Information and Event Management (SIEM) systems
  6. Security overview dashboard -- enterprise-wide visibility into the security posture of every organization and repository

These six pillars do not operate in isolation. A secret detected by secret scanning triggers an audit log entry. A CodeQL finding blocks a pull request merge through a required status check defined in a ruleset. A Dependabot security update creates a pull request that must pass the same branch protection rules as human-authored code. Understanding how these systems interlock is essential for both the exam and for operating GitHub securely at enterprise scale.

Learning Objectives​

After completing this chapter, you will be able to:

  • Configure default setup and advanced setup for CodeQL code scanning across an enterprise
  • Interpret CodeQL alert severities, dismiss alerts with documented reasons, and manage alert lifecycle
  • Enable secret scanning with push protection at the enterprise, organization, and repository levels
  • Explain the secret scanning partner program, custom patterns, and validity checks
  • Configure Dependabot alerts, security updates, and version updates for dependency management
  • Design repository rulesets that enforce branch protection, required status checks, and code review at scale
  • Set up audit log streaming to supported SIEM endpoints (Splunk, Azure Event Hubs, Amazon S3, Google Cloud Storage, Datadog)
  • Query the audit log using the web UI, REST API, and GraphQL API for compliance investigations
  • Navigate the enterprise security overview dashboard and interpret risk metrics
  • Map GitHub Advanced Security (GHAS) features to compliance frameworks (SOC 2, ISO 27001, PCI DSS, HIPAA)

Exam Domain Coverage​

DomainWeightTopics in This Chapter
D5: Secure development & compliance36%Code scanning (CodeQL), secret scanning (push protection), Dependabot (alerts, security updates, version updates), audit logs (streaming, SIEM integration), repository rulesets (branch protection, required status checks, required reviews), deployment environments, security overview dashboard, GitHub Advanced Security (GHAS) licensing and enablement

Chapter Overview​

This chapter is structured to build your understanding progressively. We begin with GitHub Advanced Security (GHAS) as the licensing and feature umbrella that gates access to code scanning, secret scanning, and the security overview. We then examine each security pillar in depth, starting with proactive defenses (code scanning, secret scanning, Dependabot) and moving to governance controls (rulesets, audit logs, security overview). Each section includes enterprise-scale configuration guidance for organizations with 50 or more developers, real-world scenarios, and exam-focused callouts.

Cross-reference: This chapter assumes you understand the enterprise account hierarchy (enterprise, organizations, teams, repositories) covered in Chapter 1: Enterprise Subscription & Environment Setup. It also assumes familiarity with the Copilot policy model from Chapter 5: Copilot Policies & Content Controls. For fine-grained permission details referenced in this chapter, see Chapter 8: Access Control & Permissions Model.


2. Theory & Deep Dive​

2.1 GitHub Advanced Security (GHAS) -- The Licensing Foundation​

GitHub Advanced Security (GHAS) is the umbrella license that unlocks the enterprise security features covered in this chapter. Understanding what GHAS includes -- and what it does not include -- is foundational.

What GHAS includes:

  • Code scanning with CodeQL (and third-party SARIF upload support)
  • Secret scanning with push protection
  • Secret scanning custom patterns
  • Security overview dashboard at the enterprise and organization levels
  • Dependency review (the enhanced pull request diff view showing dependency changes)

What GHAS does NOT include (these are available without GHAS):

  • Dependabot alerts (available on all GitHub plans for public repositories; available on GHEC for private repositories without GHAS)
  • Dependabot security updates and version updates (available without GHAS)
  • Basic branch protection rules (available without GHAS)
  • Audit log access (available for enterprise accounts without GHAS, though some security-specific events require GHAS)
  • Secret scanning for public repositories (free for all public repositories)

GHAS licensing model: GHAS is licensed per unique active committer. A committer is anyone who has pushed at least one commit to a GHAS-enabled private or internal repository in the last 90 days. Enterprise owners enable GHAS at the organization level, and billing is calculated across the entire enterprise. Each unique committer is counted once, even if they commit to repositories across multiple organizations.

Enterprise Scenario: Acme Corp has 200 developers across four organizations. They enable GHAS on two organizations containing their customer-facing applications (120 unique committers). Their internal tooling organizations remain without GHAS. Acme is billed for 120 GHAS seats. When a developer from the internal tooling org contributes a commit to a GHAS-enabled repository, the seat count increases to 121.

Enabling GHAS at scale:

GHAS can be enabled at three levels:

  1. Enterprise level: Enterprise owners can set a policy allowing or disallowing organizations from enabling GHAS
  2. Organization level: Organization owners enable GHAS for all repositories or specific repositories
  3. Repository level: Repository administrators enable specific features (code scanning, secret scanning) on individual repositories
# Check GHAS status for all repositories in an organization using the GitHub CLI
gh api orgs/acme-corp/repos --paginate --jq '.[] | {name: .name, security_and_analysis: .security_and_analysis}'
# PowerShell: Enable GHAS for an organization via the REST API
$headers = @{
"Authorization" = "Bearer $env:GITHUB_TOKEN"
"Accept" = "application/vnd.github+json"
"X-GitHub-Api-Version" = "2022-11-28"
}

Invoke-RestMethod -Uri "https://api.github.com/orgs/acme-corp" `
-Method Patch `
-Headers $headers `
-Body '{"advanced_security_enabled_for_new_repositories": true}'

Exam Tip: The exam tests your understanding of what requires GHAS versus what is available without it. Remember: Dependabot alerts and updates do NOT require GHAS. Code scanning with CodeQL and secret scanning with push protection on private repositories DO require GHAS.


2.2 Code Scanning with CodeQL​

Code scanning is GitHub's static analysis feature that identifies security vulnerabilities and coding errors in your source code. CodeQL is GitHub's first-party semantic code analysis engine that powers the default code scanning experience. Third-party tools can also upload results in Static Analysis Results Interchange Format (SARIF) to display alongside CodeQL findings.

How CodeQL Works​

CodeQL treats code as data. The analysis process has three phases:

  1. Database creation: CodeQL extracts a relational database from your source code. For compiled languages (C, C++, C#, Java, Go, Swift), this requires building the code. For interpreted languages (JavaScript, TypeScript, Python, Ruby), CodeQL creates the database directly from the source without a build step.

  2. Query execution: CodeQL runs a suite of queries against the database. Each query models a specific vulnerability pattern (SQL injection, cross-site scripting, buffer overflow, etc.). GitHub maintains and regularly updates the default query suites.

  3. Result generation: Query results are converted to SARIF format and uploaded to GitHub, where they appear as code scanning alerts on the repository's Security tab and inline on pull request diffs.

CodeQL Language Support​

CodeQL supports the following languages, each identified by a language identifier used in workflow configuration:

LanguageIdentifierBuild Required
C/C++cppYes (or none build mode)
C#csharpYes (or none build mode)
GogoNo
Java/KotlinjavaYes (or none build mode)
JavaScript/TypeScriptjavascriptNo
PythonpythonNo
RubyrubyNo
SwiftswiftYes

Note: Use javascript for both JavaScript and TypeScript analysis. Use java for both Java and Kotlin. Use cpp for both C and C++.

Default Setup vs. Advanced Setup​

GitHub offers two ways to configure CodeQL code scanning:

Default setup is the recommended starting point for most repositories. It requires no workflow file creation. GitHub automatically detects the languages in your repository, selects appropriate query suites, and runs analysis on push events to the default branch and on pull requests targeting the default branch. Default setup is enabled through the repository's Settings > Code security and analysis page or programmatically via the API.

# Enable default code scanning setup for a repository
gh api repos/acme-corp/payments-api/code-scanning/default-setup \
-X PATCH \
-f state=configured \
-f query_suite=default

Advanced setup provides full control over the CodeQL workflow. It creates a GitHub Actions workflow file (.github/workflows/codeql.yml) in the repository, allowing you to customize:

  • Which languages to analyze
  • Which query suites to run (default, security-extended, security-and-quality)
  • Build commands for compiled languages
  • Trigger events (push, pull_request, schedule)
  • Custom CodeQL query packs
# .github/workflows/codeql.yml -- Advanced setup example
name: "CodeQL Analysis"

on:
push:
branches: [ "main", "release/*" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '25 14 * * 3' # Weekly on Wednesday

jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
security-events: write
packages: read
actions: read
contents: read

strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
- language: python
build-mode: none
- language: java-kotlin
build-mode: autobuild

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
queries: security-extended

- if: matrix.build-mode == 'manual'
name: Manual build step
run: |
echo "Provide build commands here"

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"

Query Suites​

CodeQL provides three built-in query suites with increasing breadth:

SuiteDescriptionUse Case
defaultHigh-precision security queries with low false-positive rateProduction repositories needing clean signal
security-extendedDefault suite plus additional security queries with moderate false-positive rateSecurity-sensitive applications
security-and-qualityAll security queries plus code quality queriesRepositories where code quality and security are equally important

Enterprise Scenario: A healthcare company enables default setup with the default query suite across all 300 repositories as a baseline. For their 15 patient-facing applications, the security team configures advanced setup with security-extended and adds a custom CodeQL pack that detects HIPAA-specific data handling violations.

CodeQL Alert Management​

When CodeQL identifies a vulnerability, it creates an alert on the repository's Security tab. Each alert includes:

  • Severity: Critical, High, Medium, or Low (based on CVSS scoring)
  • CWE mapping: Common Weakness Enumeration identifier (e.g., CWE-89 for SQL Injection)
  • Affected file and line: Exact location in the source code
  • Data flow path: For data-flow queries, the path from source (user input) to sink (vulnerable function call)
  • Remediation guidance: Suggested fix and documentation links

Alerts can be in the following states:

  • Open: Active vulnerability requiring attention
  • Dismissed: Manually closed with a reason (false positive, used in tests, won't fix)
  • Fixed: Automatically closed when the code change that triggered the alert is no longer present

Exam Tip: When dismissing a CodeQL alert, you must provide a reason. The exam may test whether dismissed alerts count toward the security overview metrics (they do not -- only open alerts count).

Enabling Code Scanning at Enterprise Scale​

For enterprises with hundreds of repositories, enabling code scanning one repository at a time is impractical. GitHub provides several mechanisms for enterprise-wide enablement:

  1. Organization-level default setup: Organization owners can enable default setup for all existing and new repositories simultaneously from the organization's Code security settings page.

  2. Security configurations: GitHub provides predefined security configurations (e.g., "GitHub recommended") that bundle multiple security features together. Enterprise owners can apply these configurations across organizations.

  3. API-driven enablement: Use the REST API to programmatically enable code scanning across repositories.

# Enable default code scanning for all repositories in an organization
# This script iterates through all repos and enables default setup
gh api orgs/acme-corp/repos --paginate --jq '.[].name' | while read repo; do
gh api "repos/acme-corp/$repo/code-scanning/default-setup" \
-X PATCH \
-f state=configured \
-f query_suite=default \
2>/dev/null && echo "Enabled: $repo" || echo "Skipped: $repo"
done
# PowerShell: Enable default code scanning for all repos in an org
$orgName = "acme-corp"
$repos = gh api "orgs/$orgName/repos" --paginate --jq '.[].name' | ForEach-Object { $_ }

foreach ($repo in $repos) {
try {
gh api "repos/$orgName/$repo/code-scanning/default-setup" `
-X PATCH `
-f state=configured `
-f query_suite=default
Write-Host "Enabled: $repo" -ForegroundColor Green
} catch {
Write-Host "Skipped: $repo" -ForegroundColor Yellow
}
}

Third-Party SARIF Uploads​

CodeQL is not the only tool that can produce code scanning results. Any tool that outputs SARIF (Static Analysis Results Interchange Format) version 2.1.0 can upload results to GitHub. This is critical for enterprises that use commercial static analysis tools (e.g., Checkmarx, Fortify, Snyk Code) alongside CodeQL.

# Upload third-party SARIF results to GitHub code scanning
- name: Upload SARIF results
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
category: "third-party-scanner"

The category parameter allows you to distinguish between CodeQL results and third-party results in the Security tab. Each category maintains its own alert set.


2.3 Secret Scanning and Push Protection​

Secret scanning detects credentials, tokens, API keys, and other secrets that have been accidentally committed to a repository. This feature operates in two modes: detection (scanning existing repository content and commit history) and prevention (push protection that blocks secrets before they enter the repository).

How Secret Scanning Works​

GitHub partners with over 200 service providers (as of early 2026) to define token patterns. When secret scanning is enabled, GitHub continuously scans:

  • All branches and tags in the repository
  • Issue descriptions and comments
  • Pull request titles, descriptions, and comments
  • Discussion titles, descriptions, and comments
  • Wiki pages

When a matching pattern is detected, GitHub can take two actions:

  1. Alert the repository administrator: An alert appears on the repository's Security tab
  2. Notify the partner: For partner patterns, GitHub notifies the service provider (e.g., AWS, Azure, Slack), which may automatically revoke the token

Secret Scanning Alert Types​

Secret scanning generates three categories of alerts:

Alert TypeTriggerAvailable On
Partner alertsPatterns from GitHub's 200+ partner providersAll public repositories (free); private/internal repositories with GHAS
User alertsAll partner patterns plus additional high-entropy and keyword-based patternsPrivate/internal repositories with GHAS
Push protection alertsHigh-confidence patterns blocked during git pushRepositories with push protection enabled (requires GHAS for private repos)

Push Protection​

Push protection is the prevention counterpart to secret scanning's detection capability. When enabled, GitHub scans every git push for high-confidence secret patterns and blocks the push if a secret is detected. The developer sees an error message identifying the secret and its location.

Push protection only blocks high-confidence patterns -- those with an extremely low false-positive rate. This design choice ensures that push protection does not impede developer velocity with false alarms.

Developer bypass options: When a push is blocked, the developer has three choices:

  1. Remove the secret: The recommended action. Remove the credential from the code and history
  2. Mark as false positive: If the detected string is not actually a secret (e.g., a test fixture)
  3. Mark as used in tests: If the secret is intentionally used in a test environment
  4. Mark as will fix later: Acknowledges the risk but allows the push (creates an alert for tracking)

Important: Even when a developer bypasses push protection, an alert is still created. The bypass is logged in the audit log, and the security team is notified. This ensures that bypasses are tracked and reviewed.

Enabling Secret Scanning at Scale​

# Enable secret scanning and push protection for an organization
gh api orgs/acme-corp \
-X PATCH \
-f "security_and_analysis[secret_scanning][status]=enabled" \
-f "security_and_analysis[secret_scanning_push_protection][status]=enabled"
# Enable secret scanning for all new repositories in an organization
gh api orgs/acme-corp \
-X PATCH \
-F secret_scanning_enabled_for_new_repositories=true \
-F secret_scanning_push_protection_enabled_for_new_repositories=true

Custom Secret Patterns​

For enterprises that use proprietary token formats or internal credential systems, GitHub supports custom secret patterns defined using regular expressions. Custom patterns are defined at the organization or enterprise level and can optionally include push protection.

# Example: Define a custom secret pattern for an internal API key format
# Internal API keys follow the pattern: ACME-KEY-[32 hex characters]
# This is configured via the GitHub UI or API at the organization level
gh api orgs/acme-corp/secret-scanning/custom-patterns \
-X POST \
-f name="Acme Internal API Key" \
-f pattern="ACME-KEY-[0-9a-f]{32}" \
-f scope=organization

Custom patterns support three components:

  1. Secret pattern (required): The regular expression matching the secret itself
  2. Before secret (optional): A pattern that must appear before the secret (e.g., api_key\s*=\s*)
  3. After secret (optional): A pattern that must appear after the secret (e.g., [^0-9a-f])

Secret Scanning Validity Checks​

For supported partner patterns, GitHub can verify whether a detected secret is still active by making a controlled API call to the partner service. Validity checks add a status to each alert:

StatusMeaning
ActiveThe secret is valid and can be used to authenticate
InactiveThe secret has been revoked or expired
Possibly activeThe partner does not support automatic validation, or validation was inconclusive
UnknownValidation has not yet been performed

Enterprise Scenario: A 75-developer company enables secret scanning with push protection across all organizations. Within the first week, push protection blocks 12 pushes containing AWS access keys, GitHub personal access tokens (PATs), and Slack webhook URLs. The security team configures a custom pattern for their internal service mesh tokens (SVC-MESH-[A-Z0-9]{48}) and enables push protection for this custom pattern. They also enable validity checks for all supported patterns, allowing them to prioritize active secrets for immediate rotation.


2.4 Dependabot -- Alerts, Security Updates, and Version Updates​

Dependabot is GitHub's automated dependency management system. It monitors your repository's dependency files (package.json, requirements.txt, Gemfile, pom.xml, go.mod, etc.) and alerts you when a dependency has a known vulnerability. Dependabot consists of three distinct but related features:

Dependabot Alerts​

Dependabot alerts notify repository administrators when a dependency in their repository has a known vulnerability listed in the GitHub Advisory Database. The advisory database aggregates vulnerability data from the National Vulnerability Database (NVD), security advisories published by package maintainers, and GitHub's own security research.

Each Dependabot alert includes:

  • Advisory details: CVE (Common Vulnerabilities and Exposures) identifier, description, severity (critical, high, medium, low)
  • Affected dependency: Package name, current vulnerable version, patched version (if available)
  • Dependency scope: Whether the dependency is a direct dependency or a transitive (indirect) dependency
  • CVSS score: Common Vulnerability Scoring System score quantifying the severity
  • Reachability analysis (where supported): Whether the vulnerable code path is actually reachable from your application code

Important: Dependabot alerts are available on GHEC for both public and private repositories without GHAS. This is a common exam question.

Dependabot Security Updates​

Dependabot security updates go beyond alerts by automatically creating pull requests that update vulnerable dependencies to the minimum patched version. These PRs include:

  • The version bump in the dependency manifest file (and lock file if applicable)
  • Release notes and changelog excerpts from the dependency
  • Compatibility score based on CI pass rates from other repositories that made the same update

Security updates are conservative -- they update to the minimum non-vulnerable version to reduce the risk of breaking changes.

# .github/dependabot.yml -- Configure Dependabot security and version updates
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
timezone: "America/New_York"
open-pull-requests-limit: 10
reviewers:
- "acme-corp/security-team"
labels:
- "dependencies"
- "security"
commit-message:
prefix: "deps"
include: "scope"

- package-ecosystem: "pip"
directory: "/backend"
schedule:
interval: "daily"
groups:
development-dependencies:
dependency-type: "development"
production-dependencies:
dependency-type: "production"
update-types:
- "minor"
- "patch"

Dependabot Version Updates​

While security updates address known vulnerabilities, version updates keep dependencies current by creating PRs for any new version (not just security patches). Version updates are configured in the .github/dependabot.yml file and can be grouped, scheduled, and scoped to specific directories.

Key differences between security updates and version updates:

AspectSecurity UpdatesVersion Updates
TriggerKnown vulnerability in GitHub Advisory DatabaseAny new version release
ConfigurationEnabled via repository settings (no YAML required)Requires .github/dependabot.yml
PR scopeMinimum patch to resolve vulnerabilityLatest version within configured constraints
GroupingOne PR per vulnerable dependencyConfigurable groups
GHAS requiredNoNo

Dependency Review​

Dependency review is a GHAS feature that enhances the pull request experience. When a PR modifies dependency files, the dependency review action shows a rich diff that highlights:

  • New dependencies being added (with their known vulnerability status)
  • Dependencies being removed
  • Version changes and their security implications
# Add dependency review to your CI pipeline
name: Dependency Review
on: pull_request

permissions:
contents: read

jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Dependency Review
uses: actions/dependency-review-action@v4
with:
fail-on-severity: high
deny-licenses: GPL-3.0, AGPL-3.0

The deny-licenses parameter is especially valuable for enterprises that need to block copyleft licenses from entering their codebase.

Enterprise Scenario: A 100-developer SaaS company configures Dependabot across all 80 repositories. They enable security updates globally and configure version updates for their 20 production services. They group development dependency updates into weekly batches and production dependency updates into individual PRs for careful review. The dependency review action is added to all repositories with a fail-on-severity: high policy, ensuring no PR introducing a high-severity vulnerability can be merged.


2.5 Repository Rulesets and Branch Protection​

Repository rulesets are GitHub's modern, scalable replacement for branch protection rules. While branch protection rules are configured per-branch, per-repository, rulesets can be defined at the organization or enterprise level and applied across multiple repositories simultaneously.

Branch Protection Rules (Legacy)​

Branch protection rules have been available on GitHub for years and remain widely used. They protect specific branches (typically main or release/*) by enforcing:

  • Required pull request reviews: A minimum number of approving reviews before merge
  • Required status checks: Specific CI checks must pass before merge
  • Require branches to be up to date: The branch must be rebased on or merged with the target branch
  • Require signed commits: All commits must be GPG or SSH signed
  • Require linear history: No merge commits; squash or rebase only
  • Restrict who can push: Limit direct pushes to specific users, teams, or apps
  • Include administrators: Whether repository admins are also subject to the rules
  • Allow force pushes: Whether force pushes are permitted (generally disabled)
  • Allow deletions: Whether the branch can be deleted
# View branch protection rules for the main branch
gh api repos/acme-corp/payments-api/branches/main/protection

# Update branch protection to require 2 reviews and CodeQL status check
gh api repos/acme-corp/payments-api/branches/main/protection \
-X PUT \
-f "required_pull_request_reviews[required_approving_review_count]=2" \
-f "required_pull_request_reviews[dismiss_stale_reviews]=true" \
-f "required_status_checks[strict]=true" \
-f "required_status_checks[contexts][]=CodeQL" \
-f "enforce_admins=true" \
-f "restrictions=null"

Repository Rulesets (Modern)​

Rulesets address the scalability limitations of branch protection rules. Key advantages:

FeatureBranch ProtectionRulesets
ScopeSingle branch per ruleMultiple branches via patterns; can target tags
Management levelRepository onlyRepository, organization, or enterprise
LayeringSingle rule per branchMultiple rulesets can stack on the same branch
Bypass permissionsAdmins bypass by defaultExplicit bypass list (actors, teams, apps)
Audit trailLimitedFull audit log integration
Import/ExportManual recreationJSON-based import/export

Rulesets use a layered evaluation model: when multiple rulesets apply to the same branch, the most restrictive combination wins. A push must satisfy ALL applicable rulesets to succeed.

Ruleset rule types:

RuleDescription
restrict_creationsPrevent creating matching branches or tags
restrict_updatesPrevent updates to matching branches or tags
restrict_deletionsPrevent deleting matching branches or tags
require_linear_historyRequire linear commit history (no merge commits)
require_merge_queueRequire pull requests to go through the merge queue
require_deploymentsRequire successful deployment to specified environments before merge
require_signed_commitsRequire GPG or SSH signed commits
require_pull_requestRequire a pull request before merge
required_status_checksRequire specified status checks to pass
require_code_scanningRequire code scanning results with no alerts above a specified severity
non_fast_forwardPrevent force pushes

Creating an Organization-Level Ruleset​

# Create an organization-level ruleset that applies to all repositories
gh api orgs/acme-corp/rulesets \
-X POST \
--input - << 'EOF'
{
"name": "Production Branch Protection",
"target": "branch",
"enforcement": "active",
"conditions": {
"ref_name": {
"include": ["refs/heads/main", "refs/heads/release/*"],
"exclude": []
},
"repository_name": {
"include": ["*"],
"exclude": ["sandbox-*", "demo-*"]
}
},
"rules": [
{
"type": "pull_request",
"parameters": {
"required_approving_review_count": 2,
"dismiss_stale_reviews_on_push": true,
"require_code_owner_review": true,
"require_last_push_approval": true,
"required_review_thread_resolution": true
}
},
{
"type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": true,
"required_status_checks": [
{
"context": "CodeQL",
"integration_id": null
},
{
"context": "unit-tests",
"integration_id": null
}
]
}
},
{
"type": "required_deployments",
"parameters": {
"required_deployment_environments": ["staging"]
}
},
{
"type": "non_fast_forward"
}
],
"bypass_actors": [
{
"actor_id": 1,
"actor_type": "RepositoryRole",
"bypass_mode": "always"
}
]
}
EOF

Required Status Checks​

Required status checks are one of the most important governance mechanisms. They ensure that automated checks (CI tests, code scanning, linting, security scans) pass before code can be merged. When configured as "strict," the branch must also be up-to-date with the target branch, ensuring that the checks run against the final merged code.

Exam Tip: A required status check only blocks merge if the check reports a status. If a required check never runs (e.g., because the workflow file was deleted), the merge is blocked indefinitely. This is by design -- a missing check is treated as a failure, not as a pass.

Required Code Scanning Results​

The require_code_scanning rule type in rulesets integrates directly with code scanning. You can specify:

  • Which code scanning tools must produce results (e.g., CodeQL)
  • The maximum alert severity allowed (e.g., block merge if any high or critical alerts exist)

This is the mechanism that connects CodeQL analysis to the merge process: a PR that introduces a new high-severity vulnerability will be blocked from merging.

Deployment Environments and Protection Rules​

GitHub deployment environments add another layer of governance. Environments can be configured with:

  • Required reviewers: One or more people or teams who must approve the deployment
  • Wait timer: A mandatory delay (up to 30 days) before the deployment can proceed
  • Branch restrictions: Only specific branches can deploy to the environment
  • Environment secrets: Secrets scoped to a specific environment (e.g., production database credentials)
  • Environment variables: Non-sensitive configuration values scoped to the environment
# GitHub Actions workflow using deployment environments
name: Deploy to Production
on:
push:
branches: [main]

jobs:
deploy-staging:
runs-on: ubuntu-latest
environment:
name: staging
url: https://staging.acme.com
steps:
- uses: actions/checkout@v4
- name: Deploy to staging
run: ./deploy.sh staging

deploy-production:
runs-on: ubuntu-latest
needs: deploy-staging
environment:
name: production
url: https://app.acme.com
steps:
- uses: actions/checkout@v4
- name: Deploy to production
run: ./deploy.sh production

Enterprise Scenario: A financial services company with 200 developers creates an enterprise-level ruleset named "Regulatory Compliance" that applies to all repositories matching *-prod-*. The ruleset requires: 2 approving reviews (including at least one from CODEOWNERS), CodeQL with no high-severity alerts, a passing CI suite, signed commits, and successful deployment to the staging environment. The production environment has a 4-hour wait timer and requires approval from the release management team. Only the CI/CD service account has bypass permissions, and all bypasses are logged.


2.6 Audit Log Streaming and SIEM Integration​

The GitHub audit log captures every significant action performed across your enterprise, organizations, and repositories. For enterprises subject to compliance requirements (SOC 2, ISO 27001, PCI DSS, HIPAA, FedRAMP), the audit log provides the evidentiary foundation for demonstrating security controls.

What the Audit Log Captures​

The audit log records events across several categories:

CategoryExample Events
repoRepository creation, deletion, visibility change, transfer
orgMember additions/removals, team changes, billing updates
enterprisePolicy changes, SAML SSO events, IP allow list modifications
secret_scanningAlert created, alert resolved, push protection bypass
secret_scanning_push_protectionPush blocked, push allowed after bypass
code_scanning_alertAlert created, alert dismissed, alert fixed
dependabot_alertsAlert created, alert dismissed, alert fixed, auto-dismiss
copilotSeat assigned, seat removed, policy changed
gitClone, push, fetch events (when enabled)
businessEnterprise account changes, admin role assignments
integration_installationGitHub App installed, permissions changed, uninstalled
repository_rulesetRuleset created, updated, deleted, bypass used

Each audit log event contains:

  • Timestamp: When the event occurred (UTC)
  • Actor: The user, app, or system that performed the action
  • Action: The specific action taken (e.g., repo.create, org.add_member)
  • Target: The entity affected (repository, user, team, etc.)
  • Additional context: IP address, user agent, geographic location, and action-specific metadata

Querying the Audit Log​

Web UI: Enterprise owners can access the audit log at https://github.com/enterprises/ENTERPRISE/settings/audit-log. The web UI supports text-based search with filters:

action:repo.create actor:jsmith created:>2026-01-01
action:secret_scanning_alert.create org:acme-corp
action:code_scanning_alert.dismiss actor_type:User

REST API: The enterprise audit log REST API returns JSON events and supports pagination:

# Query audit log events for secret scanning alerts in the last 7 days
gh api /enterprises/acme-enterprise/audit-log \
--paginate \
-f "phrase=action:secret_scanning_alert created:>2026-01-25" \
-f "per_page=100"

GraphQL API: The GraphQL API provides more flexible querying:

# GraphQL query for audit log entries
gh api graphql -f query='
{
enterprise(slug: "acme-enterprise") {
ownerInfo {
auditLog(first: 50, query: "action:repo.create") {
edges {
node {
... on AuditEntry {
action
actorLogin
createdAt
}
}
}
}
}
}
}'

Audit Log Streaming​

For enterprises that need long-term retention, real-time analysis, and correlation with other security data, GitHub supports streaming the audit log to external destinations. Streaming sends events in near-real-time (typically within minutes) as JSON payloads.

Supported streaming destinations:

DestinationProtocolUse Case
Amazon S3S3 APILong-term storage, AWS-based SIEM (e.g., Amazon Security Lake)
Azure Blob StorageBlob APIMicrosoft Sentinel integration, Azure-native compliance
Azure Event HubsEvent Hubs APIReal-time streaming to Microsoft Sentinel or custom consumers
Google Cloud StorageGCS APIGoogle Chronicle integration, GCP-native compliance
DatadogDatadog APIReal-time monitoring, dashboards, and alerting
SplunkHTTP Event Collector (HEC)Enterprise SIEM analysis and compliance reporting

Important: Audit log streaming is available at the enterprise level only. Organization-level streaming is not available. Enterprise owners configure streaming from Enterprise Settings > Audit log > Log streaming.

Configuring Audit Log Streaming to Splunk​

# Configure audit log streaming to Splunk via the REST API
gh api /enterprises/acme-enterprise/audit-log/streams \
-X POST \
--input - << 'EOF'
{
"enabled": true,
"stream_type": "SplunkHttpEventCollector",
"vendor_specific": {
"domain": "splunk-hec.acme.com",
"port": 8088,
"token": "REDACTED",
"ssl_verify": true
}
}
EOF

Configuring Audit Log Streaming to Azure Event Hubs​

# Configure streaming to Azure Event Hubs
gh api /enterprises/acme-enterprise/audit-log/streams \
-X POST \
--input - << 'EOF'
{
"enabled": true,
"stream_type": "AzureEventHubs",
"vendor_specific": {
"namespace": "acme-github-audit",
"shared_access_key_name": "github-audit-sender",
"shared_access_key": "REDACTED",
"event_hub_name": "github-audit-events"
}
}
EOF

SIEM Integration Patterns​

Once audit log data reaches your SIEM, you can build detection and alerting rules. Common enterprise detection patterns include:

DetectionAudit Log EventsAlert Priority
Secret leak (push protection bypass)secret_scanning_push_protection.bypassCritical
Repository made publicrepo.access with visibility=publicHigh
Enterprise admin addedbusiness.add_adminHigh
SAML SSO disabledbusiness.disable_samlCritical
Ruleset deleted or weakenedrepository_ruleset.destroy, repository_ruleset.updateHigh
Bulk repository deletionMultiple repo.destroy events from same actor in short windowCritical
Code scanning alert dismissed without fixcode_scanning_alert.dismissMedium
Copilot enabled for new organizationcopilot.cfb_seat_management_changedLow (informational)

Enterprise Scenario: A publicly traded company with 500 developers streams their GitHub audit log to Splunk. Their Security Operations Center (SOC) builds a dashboard that tracks: (1) daily count of push protection bypasses, (2) code scanning alerts opened vs. closed over 30 days, (3) Dependabot alerts by severity across all repositories, and (4) any changes to enterprise-level policies. An alert fires within 5 minutes if any repository's visibility changes from private to public, triggering the on-call security engineer's pager.

Audit Log Retention​

Access MethodRetention Period
Web UI180 days
REST API180 days
Git export (monthly archives)Indefinite (available for download)
StreamingDepends on your SIEM/storage destination

Exam Tip: GitHub retains audit log data for 180 days via the web UI and API. For longer retention, you must configure audit log streaming to an external destination. The git-based monthly archives provide indefinite retention but are not real-time.


2.7 Security Overview Dashboard​

The security overview dashboard provides enterprise and organization owners with a centralized view of their security posture. It aggregates data from code scanning, secret scanning, and Dependabot across all repositories.

Enterprise Security Overview​

At the enterprise level, the security overview shows:

  • Risk view: Repositories ranked by the number and severity of open security alerts
  • Coverage view: Which repositories have security features enabled and which do not
  • Alert trends: Open vs. closed alerts over time across all organizations

The coverage view is particularly valuable for enterprise administrators rolling out GHAS. It answers the question: "Which repositories still need security features enabled?"

Organization Security Overview​

At the organization level, the security overview provides more granular data:

  • Code scanning alerts: Broken down by tool (CodeQL, third-party), severity, and repository
  • Secret scanning alerts: Broken down by secret type, validity status, and repository
  • Dependabot alerts: Broken down by severity, ecosystem (npm, pip, Maven, etc.), and repository

Filtering and Export​

The security overview supports extensive filtering:

# Filter code scanning alerts by severity and tool
is:open severity:critical tool:CodeQL

# Filter secret scanning alerts by secret type
is:open secret-type:github_personal_access_token

# Filter Dependabot alerts by ecosystem
is:open ecosystem:npm severity:high

Results can be exported as CSV for offline analysis and compliance reporting.

Security Overview Metrics for Compliance​

The security overview provides metrics that map directly to compliance framework controls:

Compliance FrameworkRelevant Security Overview Metric
SOC 2 (CC6.1 -- Logical Access)Secret scanning coverage percentage
SOC 2 (CC7.1 -- System Monitoring)Audit log streaming status
SOC 2 (CC8.1 -- Change Management)Ruleset coverage and required review compliance
ISO 27001 (A.12.6 -- Technical Vulnerability Management)Dependabot alert count and mean time to remediation
PCI DSS (6.2 -- Security Patches)Dependabot security update adoption rate
PCI DSS (6.3 -- Secure Development)Code scanning coverage and open alert count
HIPAA (164.312(a)(1) -- Access Control)Secret scanning push protection enablement

Enterprise Scenario: During their annual SOC 2 Type II audit, Acme Corp's auditors request evidence of vulnerability management processes. The security team exports the security overview showing: 100% code scanning coverage across all production repositories, a mean time to remediation (MTTR) of 4.2 days for high-severity code scanning alerts, zero active secret scanning alerts with "active" validity status, and Dependabot security update PRs merged within 48 hours for critical-severity advisories. The audit log streaming configuration to Splunk demonstrates continuous monitoring (SOC 2 CC7.1).


2.8 Putting It All Together: The Enterprise Security Lifecycle​

The six security pillars covered in this chapter form a continuous security lifecycle:

  1. Prevent: Push protection blocks secrets before they enter the repository
  2. Detect: Code scanning and Dependabot identify vulnerabilities in code and dependencies
  3. Enforce: Rulesets require that security checks pass before code is merged
  4. Monitor: The audit log captures every action across the enterprise
  5. Report: The security overview dashboard provides visibility and compliance evidence
  6. Remediate: Dependabot security updates and developer-driven fixes close the loop

This lifecycle operates continuously and automatically. When a developer pushes code:

  • Push protection checks for secrets (prevent)
  • CodeQL scans the code for vulnerabilities (detect)
  • The required status check blocks merge if vulnerabilities are found (enforce)
  • The push, scan results, and merge decision are logged in the audit log (monitor)
  • The security overview updates to reflect the new alert (report)
  • If a vulnerability is found, the developer fixes it and the cycle repeats (remediate)

3. Diagrams​

Enterprise Security Architecture​

flowchart TB
subgraph Developer["Developer Workflow"]
A[Developer writes code] --> B[git push]
B --> C{Push Protection<br/>Secret Scan}
C -->|Secret detected| D[Push blocked<br/>Developer removes secret]
C -->|Clean| E[Push accepted]
D --> B
end

subgraph CI["CI/CD Pipeline"]
E --> F[Pull Request created]
F --> G[CodeQL Analysis]
F --> H[Dependabot<br/>Dependency Review]
F --> I[Unit Tests &<br/>Integration Tests]
G --> J{Required Status<br/>Checks}
H --> J
I --> J
J -->|All pass| K{Required Reviews<br/>2 approvals +<br/>CODEOWNERS}
J -->|Any fail| L[Merge blocked]
K -->|Approved| M[Merge to main]
K -->|Not approved| L
end

subgraph Deploy["Deployment"]
M --> N[Deploy to staging<br/>environment]
N --> O{Staging<br/>health checks}
O -->|Pass| P[Manual approval<br/>required]
P --> Q[Deploy to production<br/>environment]
O -->|Fail| R[Rollback]
end

subgraph Monitor["Monitoring & Compliance"]
B -.->|Event| S[Audit Log]
G -.->|Alert| S
H -.->|Alert| S
M -.->|Event| S
Q -.->|Event| S
S --> T[SIEM<br/>Splunk / Sentinel]
S --> U[Security Overview<br/>Dashboard]
T --> V[SOC Alerting<br/>& Dashboards]
U --> W[Compliance<br/>Reports]
end

style Developer fill:#e1f5fe,stroke:#0288d1
style CI fill:#f3e5f5,stroke:#7b1fa2
style Deploy fill:#e8f5e9,stroke:#388e3c
style Monitor fill:#fff3e0,stroke:#f57c00

GHAS Feature Licensing Map​

graph LR
subgraph Free["Free (All GHEC Repos)"]
DA[Dependabot Alerts]
DSU[Dependabot Security Updates]
DVU[Dependabot Version Updates]
BP[Branch Protection Rules]
AL[Audit Log Access]
SSP[Secret Scanning<br/>Public Repos Only]
end

subgraph GHAS["Requires GHAS License"]
CS[Code Scanning<br/>CodeQL]
SSPriv[Secret Scanning<br/>Private/Internal Repos]
PP[Push Protection<br/>Private/Internal Repos]
CP[Custom Secret Patterns]
DR[Dependency Review<br/>Enhanced PR Diff]
SO[Security Overview<br/>Dashboard]
end

style Free fill:#e8f5e9,stroke:#388e3c
style GHAS fill:#fce4ec,stroke:#c62828

Audit Log Streaming Architecture​

flowchart LR
subgraph GitHub["GitHub Enterprise Cloud"]
EL[Enterprise Audit Log]
OL[Organization Audit Log]
RL[Repository Events]
RL --> OL --> EL
end

EL --> Stream[Audit Log<br/>Streaming Service]

Stream --> S3[Amazon S3]
Stream --> AEH[Azure Event Hubs]
Stream --> ABS[Azure Blob Storage]
Stream --> GCS[Google Cloud Storage]
Stream --> DD[Datadog]
Stream --> SPL[Splunk HEC]

S3 --> SIEM1[AWS Security Lake /<br/>Amazon OpenSearch]
AEH --> SIEM2[Microsoft Sentinel]
GCS --> SIEM3[Google Chronicle]
SPL --> SIEM4[Splunk Enterprise<br/>Security]
DD --> SIEM5[Datadog Security<br/>Monitoring]

style GitHub fill:#e1f5fe,stroke:#0288d1
style Stream fill:#fff3e0,stroke:#f57c00

4. Summary​

Key Takeaways​

  • GitHub Advanced Security (GHAS) is the license that enables code scanning with CodeQL, secret scanning on private/internal repositories, push protection, custom secret patterns, and the security overview dashboard. Dependabot alerts and updates do NOT require GHAS.

  • CodeQL code scanning uses semantic code analysis to detect vulnerabilities. It supports C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, and Swift. Default setup requires zero configuration; advanced setup provides full workflow customization. Query suites range from default (high precision) to security-and-quality (broadest coverage).

  • Secret scanning detects over 200 partner token patterns. Push protection blocks high-confidence secrets during git push. Developers can bypass push protection with documented reasons, but all bypasses are logged and create alerts. Custom patterns extend detection to proprietary credentials. Validity checks confirm whether detected secrets are still active.

  • Dependabot provides three layers: alerts (notifications about vulnerable dependencies), security updates (automated PRs for minimum patched versions), and version updates (automated PRs for latest versions). Dependency review enhances PR diffs with vulnerability and license information.

  • Repository rulesets are the modern replacement for branch protection rules. They can be defined at the enterprise, organization, or repository level and applied across multiple repositories simultaneously. Multiple rulesets stack (most restrictive combination wins). Key rules include required pull request reviews, required status checks (including CodeQL), required deployments, and signed commits.

  • Audit log streaming sends enterprise audit events in near-real-time to external SIEM destinations (Splunk, Azure Event Hubs, Amazon S3, Google Cloud Storage, Datadog, Azure Blob Storage). The web UI and API retain events for 180 days; streaming enables indefinite retention. Audit log data is essential for SOC 2, ISO 27001, PCI DSS, and HIPAA compliance evidence.

  • Security overview dashboard provides enterprise-wide visibility into risk (open alerts by severity), coverage (which repositories have security features enabled), and trends (alert remediation velocity). It supports filtering, export, and maps directly to compliance framework controls.

  • The enterprise security lifecycle is: prevent (push protection) > detect (code scanning, Dependabot) > enforce (rulesets, required status checks) > monitor (audit log) > report (security overview) > remediate (fixes, security updates).


5. Hands-On Assignment​

Prerequisites Check: Before starting this lab, ensure you have completed:

  • A working GitHub Enterprise Cloud environment (Chapter 1: Enterprise Subscription & Environment Setup)
  • Copilot policies configured (Chapter 5: Copilot Policies & Content Controls)
  • At least one organization with GHAS enabled
  • A test repository with JavaScript or Python code
  • GitHub CLI (gh) installed and authenticated

Objective​

Configure a complete enterprise security posture for a multi-organization GitHub Enterprise Cloud environment. You will enable GHAS features, configure rulesets, set up audit log streaming, and validate the security overview dashboard.

Prerequisites​

  • A GitHub Enterprise Cloud account with enterprise owner permissions
  • At least one organization with GHAS enabled
  • A test repository with at least one supported CodeQL language (JavaScript, Python, or Java recommended)
  • Access to a Splunk instance (or Splunk free trial) for audit log streaming, OR access to Azure Event Hubs
  • The GitHub CLI (gh) installed and authenticated

Assignment Tasks​

Task 1: Enable Code Scanning with CodeQL

  1. Choose a test repository with JavaScript or Python code
  2. Enable default code scanning setup via the GitHub UI
  3. Trigger a code scan by pushing a commit
  4. Review the code scanning results on the Security tab
  5. If any alerts exist, examine the data flow path and CWE mapping
  6. Upgrade to advanced setup with the security-extended query suite
  7. Add a scheduled scan (weekly) in addition to push and PR triggers

Task 2: Configure Secret Scanning with Push Protection

  1. Enable secret scanning and push protection for the organization
  2. Create a test file containing a fake secret matching a known pattern
  3. Attempt to push the file and observe the push protection block
  4. Practice the bypass workflow (mark as "used in tests")
  5. Verify the alert was created on the Security tab
  6. Create a custom secret pattern for a fictional internal token format: ACME-[A-Z]{4}-[0-9a-f]{32}
  7. Verify the custom pattern detects test instances

Task 3: Configure Dependabot

  1. Enable Dependabot alerts for the organization
  2. Enable Dependabot security updates for the test repository
  3. Create a .github/dependabot.yml file configuring version updates
  4. Review any Dependabot PRs that are generated
  5. Configure the dependency review action in a CI workflow

Task 4: Create an Organization-Level Ruleset

  1. Create a ruleset named "Security Baseline" at the organization level
  2. Apply it to all branches matching main and release/*
  3. Require: 1 approving review, CodeQL status check, dismissal of stale reviews
  4. Set enforcement to "active"
  5. Test the ruleset by attempting to push directly to main (should be blocked)
  6. Test the ruleset by creating a PR without the required review (should block merge)

Task 5: Configure Audit Log Streaming

  1. Navigate to Enterprise Settings > Audit log > Log streaming
  2. Configure a streaming destination (Splunk HEC or Azure Event Hubs)
  3. Verify events are flowing to the destination
  4. Query the audit log via the REST API for secret scanning events from the past 24 hours
  5. Build a basic SIEM dashboard showing: push protection bypasses, code scanning alert trends, and repository visibility changes

Task 6: Review the Security Overview

  1. Navigate to the enterprise security overview
  2. Identify the top 3 repositories by open alert count (risk view)
  3. Identify any repositories without code scanning enabled (coverage view)
  4. Export the alert data as CSV for compliance documentation

Acceptance Criteria​

  • CodeQL default setup is running and produces alerts (or confirms zero alerts)
  • CodeQL advanced setup workflow exists with security-extended and weekly schedule
  • Secret scanning push protection blocks a test secret push
  • A custom secret pattern is created and detects test instances
  • Dependabot alerts are enabled and version updates are configured
  • Dependency review action is added to the CI pipeline
  • An organization-level ruleset enforces reviews and status checks on main
  • Audit log streaming is configured and events are flowing to the SIEM
  • A REST API query returns audit log events
  • The security overview dashboard shows risk and coverage data

6. Step-by-Step Walkthrough​

Task 1: Enable Code Scanning with CodeQL​

Step 1.1: Enable default setup via the UI

  1. Navigate to your test repository on GitHub.com
  2. Click Settings > Code security and analysis (left sidebar, under "Security")
  3. Find the Code scanning section
  4. Click Set up next to "CodeQL analysis"
  5. Select Default setup
  6. Review the detected languages and query suite (default)
  7. Click Enable CodeQL

GitHub will create the initial CodeQL database and run the first analysis. This typically takes 5-15 minutes depending on repository size.

Step 1.2: Trigger a scan with a commit

# Clone the repository
gh repo clone acme-corp/security-test-repo
cd security-test-repo

# Create a file with a potential vulnerability (SQL injection example)
cat > vulnerable.py << 'PYEOF'
import sqlite3

def get_user(username):
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
# Vulnerable to SQL injection - CodeQL should detect this
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)
return cursor.fetchone()
PYEOF

# Commit and push
git add vulnerable.py
git commit -m "Add user lookup function"
git push origin main

Step 1.3: Review results

  1. After the scan completes (check the Actions tab for workflow status)
  2. Navigate to Security > Code scanning alerts
  3. You should see an alert for "SQL query built from user-controlled sources" (CWE-89)
  4. Click the alert to examine the data flow path showing how username flows into the SQL query

Step 1.4: Upgrade to advanced setup

  1. Navigate to Settings > Code security and analysis
  2. In the Code scanning section, click Switch to advanced setup
  3. GitHub will generate a .github/workflows/codeql.yml file
  4. Edit the file to add the security-extended query suite and a weekly schedule:
# Modify the generated workflow
name: "CodeQL"

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '0 6 * * 1' # Every Monday at 6:00 UTC

jobs:
analyze:
name: Analyze (${{ matrix.language }})
runs-on: ubuntu-latest
permissions:
security-events: write
packages: read
actions: read
contents: read

strategy:
fail-fast: false
matrix:
include:
- language: python
build-mode: none

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
queries: security-extended

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{ matrix.language }}"
  1. Commit the workflow file to the repository

Task 2: Configure Secret Scanning with Push Protection​

Step 2.1: Enable at the organization level

  1. Navigate to your organization on GitHub.com
  2. Click Settings > Code security and analysis (under "Security")
  3. Under Secret scanning, click Enable all
  4. Under Push protection, click Enable all
  5. Confirm the changes

Or use the CLI:

# Enable secret scanning and push protection for the organization
gh api orgs/acme-corp \
-X PATCH \
-f "secret_scanning_enabled_for_new_repositories=true" \
-f "secret_scanning_push_protection_enabled_for_new_repositories=true"

Step 2.2: Test push protection

# In your test repository, create a file with a test secret
# WARNING: Use a revoked or test-only token. Never commit real credentials.
cd security-test-repo

cat > config.py << 'PYEOF'
# This is a test file -- DO NOT use real credentials
# The following is a fake GitHub PAT format that push protection should detect
GITHUB_TOKEN = "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef01"
PYEOF

git add config.py
git commit -m "Add configuration"
git push origin main

You should see output similar to:

remote: error: GH013: Repository rule violations found for refs/heads/main.
remote:
remote: -- Push protection: secret scanning detected a GitHub Personal Access Token
remote: in config.py:3
remote:
remote: To push, you need to either remove the secret or bypass push protection.

Step 2.3: Practice the bypass workflow

  1. On the error message, follow the URL provided to bypass push protection
  2. Select It's used in tests as the reason
  3. Click Allow secret
  4. Push again -- the push will succeed
  5. Navigate to Security > Secret scanning alerts -- verify the alert was created with the bypass reason

Step 2.4: Create a custom pattern

  1. Navigate to your organization Settings > Code security and analysis
  2. Under Secret scanning > Custom patterns, click New pattern
  3. Configure:
    • Pattern name: Acme Internal Token
    • Secret format: ACME-[A-Z]{4}-[0-9a-f]{32}
    • Before secret (optional): (token|key|secret)\s*[=:]\s*["']?
    • Enable Push protection for this pattern
  4. Click Save and then Publish
  5. Test by attempting to push a file containing ACME-TEST-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4

Task 3: Configure Dependabot​

Step 3.1: Enable Dependabot alerts

  1. Navigate to your organization Settings > Code security and analysis
  2. Under Dependabot, enable:
    • Dependabot alerts: Click Enable all
    • Dependabot security updates: Click Enable all

Step 3.2: Create the Dependabot configuration file

cd security-test-repo

# Create the Dependabot configuration
mkdir -p .github
cat > .github/dependabot.yml << 'EOF'
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
day: "tuesday"
time: "10:00"
timezone: "America/New_York"
open-pull-requests-limit: 5
reviewers:
- "acme-corp/security-team"
labels:
- "dependencies"
- "automated"
commit-message:
prefix: "deps"
EOF

git add .github/dependabot.yml
git commit -m "Configure Dependabot version updates"
git push origin main

Step 3.3: Add the dependency review action

cat > .github/workflows/dependency-review.yml << 'EOF'
name: Dependency Review
on: [pull_request]

permissions:
contents: read
pull-requests: write

jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Dependency Review
uses: actions/dependency-review-action@v4
with:
fail-on-severity: high
comment-summary-in-pr: always
deny-licenses: GPL-3.0, AGPL-3.0
EOF

git add .github/workflows/dependency-review.yml
git commit -m "Add dependency review action"
git push origin main

Task 4: Create an Organization-Level Ruleset​

Step 4.1: Create the ruleset via the UI

  1. Navigate to your organization on GitHub.com
  2. Click Settings > Rules > Rulesets (under "Code, planning, and automation")
  3. Click New ruleset > New branch ruleset
  4. Configure:
    • Ruleset name: Security Baseline
    • Enforcement status: Active
    • Target branches: Add pattern main; Add pattern release/*
    • Branch rules:
      • Check Restrict deletions
      • Check Require a pull request before merging:
        • Required approvals: 1
        • Dismiss stale pull request approvals when new commits are pushed: Yes
        • Require review from Code Owners: Yes
        • Require approval of the most recent reviewable push: Yes
      • Check Require status checks to pass:
        • Add required check: CodeQL
        • Require branches to be up to date before merging: Yes
      • Check Block force pushes
  5. Click Create

Step 4.2: Test the ruleset

# Attempt to push directly to main (should be blocked)
cd security-test-repo
echo "# Test direct push" >> README.md
git add README.md
git commit -m "Test direct push"
git push origin main

Expected result: The push is rejected because the ruleset requires a pull request.

# Create a branch and PR instead
git checkout -b test/ruleset-validation
git push origin test/ruleset-validation
gh pr create --title "Test ruleset enforcement" --body "Validating that rulesets block merge without required reviews and status checks"

The PR should show:

  • A pending review requirement (1 approval needed)
  • A pending status check for CodeQL

Task 5: Configure Audit Log Streaming​

Step 5.1: Configure via the UI

  1. Navigate to Enterprise Settings > Audit log (left sidebar)
  2. Click Log streaming
  3. Click Configure stream
  4. Select your destination (e.g., Splunk)
  5. Enter connection details:
    • Domain: Your Splunk HEC endpoint (e.g., splunk-hec.acme.com)
    • Port: 8088
    • HEC Token: Your Splunk HEC token
    • Enable SSL verification: Yes
  6. Click Check endpoint to validate connectivity
  7. Click Save

Step 5.2: Query audit log via REST API

# Query for secret scanning events in the last 24 hours
gh api /enterprises/acme-enterprise/audit-log \
--paginate \
-f "phrase=action:secret_scanning created:>=$(date -u -d '24 hours ago' '+%Y-%m-%d')" \
-f "per_page=100" \
--jq '.[] | {action: .action, actor: .actor, created_at: .created_at, repo: .repo}'
# PowerShell: Query for secret scanning events
$yesterday = (Get-Date).AddDays(-1).ToString("yyyy-MM-dd")
gh api "/enterprises/acme-enterprise/audit-log" `
--paginate `
-f "phrase=action:secret_scanning created:>=$yesterday" `
-f "per_page=100" `
--jq '.[] | {action: .action, actor: .actor, created_at: .created_at, repo: .repo}'

Step 5.3: Verify events in SIEM

  1. Open your Splunk or SIEM console
  2. Search for GitHub audit events (e.g., index=github_audit sourcetype=github:enterprise:audit)
  3. Verify events from your earlier activities appear (push protection bypass, code scanning results, etc.)

Task 6: Review the Security Overview​

Step 6.1: Navigate to the enterprise security overview

  1. Go to https://github.com/enterprises/YOUR-ENTERPRISE/security
  2. Click on Risk to see repositories ranked by open alert count
  3. Click on Coverage to see which repositories have each security feature enabled

Step 6.2: Identify gaps

  1. In the Coverage view, filter for repositories where code scanning is not enabled
  2. Note the repository names -- these are candidates for CodeQL enablement
  3. In the Risk view, sort by "Critical" alerts to identify the highest-risk repositories

Step 6.3: Export for compliance

  1. Use the Export button to download alert data as CSV
  2. Review the CSV to ensure it contains: repository name, alert type, severity, status (open/closed/dismissed), and date

7. Q&A -- Chapter Review​

Question 1

Your enterprise has GitHub Advanced Security (GHAS) enabled. A developer pushes a commit containing an AWS access key to a private repository with push protection enabled. What happens?

A) The push succeeds and a secret scanning alert is created for the repository administrator to review B) The push is blocked and the developer must remove the secret, bypass with a documented reason, or mark it as a false positive C) The push succeeds but the AWS access key is automatically redacted from the commit D) The push is blocked permanently and only an enterprise owner can unblock it

Answer: B

Push protection blocks the push and presents the developer with options: remove the secret, mark as false positive, mark as used in tests, or mark as will fix later. If the developer bypasses, the push succeeds but an alert is created and the bypass is logged in the audit log. Push protection does not redact content or require enterprise owner intervention.


Question 2

Which of the following features requires a GitHub Advanced Security (GHAS) license on private repositories?

A) Dependabot alerts B) Dependabot security updates C) Code scanning with CodeQL D) Branch protection rules

Answer: C

Code scanning with CodeQL on private and internal repositories requires GHAS. Dependabot alerts, Dependabot security updates, and branch protection rules are available on GitHub Enterprise Cloud without GHAS. This is a critical distinction for the exam.


Question 3

An enterprise administrator wants to enforce a policy across all 150 repositories requiring two pull request reviews and a passing CodeQL scan before any merge to main. What is the most scalable approach?

A) Configure branch protection rules on each repository individually B) Create an organization-level repository ruleset targeting the main branch with required reviews and required status checks C) Create a GitHub Actions workflow that blocks merges without reviews D) Use a pre-receive hook on GitHub Enterprise Server

Answer: B

Organization-level (or enterprise-level) rulesets are the scalable solution for applying branch protection policies across multiple repositories. Branch protection rules (option A) require per-repository configuration. GitHub Actions workflows (option C) cannot enforce merge policies. Pre-receive hooks (option D) are only available on GitHub Enterprise Server, not GHEC.


Question 4

Your security team discovers that audit log events in the GitHub web UI only go back 180 days. They need 7 years of retention for PCI DSS compliance. What should they configure?

A) Upgrade to GitHub Enterprise Server, which retains audit logs indefinitely B) Configure audit log streaming to an external SIEM or storage destination C) Use the GraphQL API to export logs monthly, which provides indefinite retention D) Request extended retention from GitHub Support

Answer: B

Audit log streaming sends events in near-real-time to external destinations (Splunk, Azure Event Hubs, Amazon S3, Google Cloud Storage, Datadog), where retention is controlled by the enterprise's storage policies. The web UI and APIs retain logs for 180 days. GitHub does not offer extended retention beyond 180 days through the web UI or API. While git-based monthly archives exist, streaming provides real-time capture which is the recommended approach.


Question 5

A CodeQL analysis finds a critical SQL injection vulnerability (CWE-89) in a pull request. The repository has a ruleset with require_code_scanning set to block merges when critical-severity alerts are present. What must the developer do to merge the PR?

A) Ask a repository administrator to bypass the ruleset B) Fix the SQL injection vulnerability so the CodeQL alert is resolved, then re-run the analysis C) Dismiss the CodeQL alert as "won't fix" and merge D) Disable CodeQL for the repository temporarily

Answer: B

When a ruleset requires code scanning results with no critical alerts, the developer must fix the vulnerability. Dismissing the alert (option C) may not satisfy the ruleset depending on configuration. Disabling CodeQL (option D) would cause the required status check to fail. While a bypass actor could theoretically bypass (option A), the correct approach -- and the exam-expected answer -- is to fix the vulnerability.


Question 6

Which audit log streaming destinations are supported by GitHub Enterprise Cloud?

A) Splunk, Amazon S3, Azure Event Hubs, Google Cloud Storage, Datadog, Azure Blob Storage B) Splunk, Elastic, Amazon S3, Azure Blob Storage C) Only Splunk and Microsoft Sentinel D) Any destination that supports webhooks

Answer: A

GitHub Enterprise Cloud supports streaming to six destinations: Splunk (via HTTP Event Collector), Amazon S3, Azure Event Hubs, Azure Blob Storage, Google Cloud Storage, and Datadog. Elastic is not a natively supported streaming destination (though you can feed data from S3 or Event Hubs into Elastic). Webhooks are a separate feature and not used for audit log streaming.


Question 7

A developer bypasses push protection to push a commit containing an API key, selecting "will fix later" as the reason. Which of the following is TRUE?

A) No alert is created because the developer acknowledged the risk B) An alert is created, the bypass is logged in the audit log, and the secret remains in the repository history C) The secret is automatically revoked by the partner provider D) The push protection bypass is only visible to enterprise owners

Answer: B

When push protection is bypassed, GitHub still creates a secret scanning alert, and the bypass event is recorded in the audit log. The secret remains in the repository history (GitHub does not modify commit history). Partner notification and potential revocation happen based on the alert, not the bypass -- but revocation is not guaranteed and depends on the partner. The bypass is visible to repository administrators and anyone with access to the security tab, not just enterprise owners.


Question 8

What is the difference between Dependabot security updates and Dependabot version updates?

A) Security updates require GHAS; version updates do not B) Security updates are triggered by known vulnerabilities and update to the minimum patched version; version updates are triggered by any new release and update to the latest version C) Security updates only work for npm packages; version updates support all ecosystems D) Security updates are manual; version updates are automatic

Answer: B

Security updates are triggered when the GitHub Advisory Database identifies a vulnerability in a dependency, and they update to the minimum version that fixes the vulnerability. Version updates are triggered by any new release and can update to the latest version. Neither requires GHAS. Both support all ecosystems that Dependabot supports. Both are automatic when enabled.


Question 9

In the security overview dashboard, what does the "Coverage" view show?

A) The percentage of code covered by unit tests across all repositories B) Which repositories have security features (code scanning, secret scanning, Dependabot) enabled and which do not C) The number of developers with GHAS seats versus total developers D) The compliance framework mapping for each repository

Answer: B

The Coverage view in the security overview shows which repositories have each security feature enabled. This is essential for enterprises rolling out GHAS because it identifies gaps in security coverage. It does not show test coverage, seat utilization, or compliance mappings.


Question 10

An enterprise has three organizations. Organization A enables GHAS with CodeQL. Organization B does not have GHAS. A developer with access to both organizations pushes code to a private repository in Organization B. Which security features apply to that push?

A) CodeQL analysis runs because the developer has GHAS access through Organization A B) No CodeQL analysis runs because GHAS is not enabled on Organization B; however, Dependabot alerts still apply if enabled C) CodeQL analysis runs but results are only visible in Organization A's security overview D) The push is blocked because the developer's GHAS seat does not cover Organization B

Answer: B

GHAS features are enabled per-organization (or per-repository), not per-user. A developer's GHAS access in Organization A does not extend to repositories in Organization B. CodeQL will not run on Organization B's repositories unless GHAS is enabled there. However, Dependabot alerts (which do not require GHAS) will still apply if enabled for Organization B. The push is not blocked -- GHAS is not a gating mechanism for pushes.


End of Chapter 6