◀ Playbook index
NO.19.5

Code Scanning

Updated: 2026-10-27

In a nutshell

Code Scanning finds vulnerabilities through static analysis (SAST), without running your code.

CodeQL turns code into a queryable database. Eligible findings can get Copilot Autofix suggestions or be assigned to Copilot for a fix.

Code scanning is not CodeQL 📖 Docs

Code scanning is the GitHub feature; CodeQL is one analysis engine. AI findings complement it on pull requests, and third-party tools can supply SARIF results.

▸ CLICK FOR DETAILS

Code scanning (the feature)

Code scanning — GitHub's surface

The feature that collects results from static analysis (CodeQL, third-party tools) and AI detections, and surfaces them: Security tab alerts, inline PR comments, merge protection, Security overview, APIs. Whatever the engine, results land here.

CodeQL (the engine)

CodeQL — the analysis engine

GitHub's default semantic analysis engine (acquired from Semmle, 2019). CodeQL CLI also runs locally or in other CI systems.

Supported languages: C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, Rust and Swift, plus GitHub Actions workflows.

As of 2026-10-23. 📘 Supported languages documentation ↗

AI Scan (PR only)

AI Scan

Complements CodeQL for uncovered languages and frameworks, such as PHP, Bash, HCL and Dockerfiles. Pull requests only: no full-repo scan or backlog alerts. Advisory, not a merge gate. Requires code scanning and AI Scan enabled, not CodeQL default setup. Uses Code Security AI Credits; organization enablement and repository opt-out are available through the UI or REST API.

As of 2026-10-22: no Copilot license required. Private/internal organization repos need Code Security or GHAS. 📘 Docs ↗ / 📘 API changelog ↗

SARIF (the contract)

SARIF — the format that joins them

The OASIS standard format for static-analysis results. Push Semgrep, Snyk or Checkmarx through upload-sarif and their findings sit next to CodeQL's, same screen.

📘 SARIF support ↗

SELECT A TOPIC ▸

How CodeQL works 📖 Docs

Extract code into a database, then compile and evaluate queries against it.

CodeQL architecture: source code and build monitoring feed the extractor and database. The schema, query and libraries feed the QL compiler. The evaluator combines the compiled query with the database to produce results. Build artifacts are separate.

The schema describes the data; the database stores it. Extraction reads source directly or monitors a build, depending on the language and build mode ↗.

Reading a CodeQL query

QL is a declarative logic-programming language. You describe the shape of a bug and the evaluator finds every instance. The structure mirrors SQL’s FROM / WHERE / SELECT.

import java                                       // ① pull in the standard library

from IfStmt ifstmt, Block block                   // ② declare the elements to inspect
where
  block = ifstmt.getThen() and                    // ③ constrain them
  block.getNumStmt() = 0                          //    → a then-branch with no statements
select ifstmt, "This if-statement is redundant."  // ④ what to report, and how

The whole language is that shape: where is the definition of “what the bug looks like”, and the evaluator does the searching.

🔬 Security queries layer DataFlow / TaintTracking on top, defining sources, sinks and sanitizers and searching for paths between them. The packs are open source at github/codeql ↗. In practice they are enough — you write custom queries mainly to teach CodeQL the sources and sinks of your in-house framework.

📘 Details: About CodeQL queries ↗ / About data flow analysis ↗

What CodeQL finds

▸ CLICK FOR DETAILS

Injection

Injection

SQL injection, command injection, path traversal, XSS, SSRF. User input reaching an interpreter (SQL, a shell, a file path, HTML, an HTTP client) without escaping. This is CodeQL's home turf and where data-flow analysis pays for itself.

Auth, authz & crypto

Auth, authorization and crypto

Broken access control, weak cryptographic algorithms (MD5 / SHA-1), insecure randomness, hard-coded credentials, disabled certificate validation.

Memory safety (C/C++)

Memory safety (C/C++)

Buffer overflow, use after free, null dereference, integer overflow. Only reachable because types and pointer flow live in the database — regex-based tools cannot go here.

Data flow tracking

Data flow tracking (taint tracking)

The alert carries the path itself, source to sink. Anything crossing a sanitizer drops out, which is what keeps false positives down. models-as-data lets you register your own framework's sources and sinks without writing a query.

📘 sanitizers in models-as-data ↗

CI/CD (Actions)

CI/CD (GitHub Actions)

Workflows are analysed too: pull_request_target combined with an untrusted checkout, script injection, excessive permissions, unpinned third-party actions — the supply-chain side of the repo.

SELECT A CATEGORY ▸

🌐 Supported languages — C/C++, C#, Go, Java/Kotlin, JavaScript/TypeScript, Python, Ruby, Rust, Swift, GitHub Actions. A repo with no CodeQL-supported language runs no scans and burns no Actions minutes.

Main capabilities

DEMOCodeQL Advanced setupFOR PRESENTER ONLY
  1. OPEN REPOSITORY SETTINGS

    Open ghas-test-1 → Advanced Security ↗ and show Code scanning → CodeQL analysis.

    For an unconfigured repository, the entry point is Set up → Advanced. This demo repository already has a workflow, so open the existing file without switching setup types.

  2. WALK THROUGH ADVANCED SETUP

    Open codeql.yml ↗. Show push / PR / schedule under on, the language matrix, and the runner under runs-on.

    C/C++ uses build-mode: manual with make -C src/c / make -C src/cpp; the other languages use none. Point out queries: security-and-quality and the C/C++ CERT / MISRA packs.

    These packs come from github/codeql-coding-standards ↗: an example of extra query packs you can add (AUTOSAR C++14, CERT C/C++, MISRA C/C++).

    Advanced setup controls the build and execution conditions through a versioned Actions workflow.

  3. FROM CONFIGURATION TO RESULTS

    Open an existing run under Actions → CodeQL ↗. Show the per-language Analyze jobs and their initialization, build, and analysis logs.

    Finish at Security → Code scanning ↗ to see the alerts.

    No workflow edits or commits are needed for this walkthrough. Leave the existing scans enabled.

Start with Default setup, customize it with repository properties, and reach for Advanced only when you need your own build.

▸ CLICK + FOR DETAILS

Default setupOne click, org-wideDocs

What it doesNo workflow file. Detects CodeQL languages, and adds new ones automatically as they appear

When it runsPushes to the default or a protected branch, PRs targeting them, and a weekly schedule

RolloutApply a security configuration to every repo in the org at once

Custom queriesDefault setup + repo propertyChangelog

What it doesAdd your own queries (e.g. coding standards, in-house rules) without switching to Advanced

Howgithub-codeql-config-file merges a central config file (queries, paths, threat models). github-codeql-extra-queries only adds queries

ScopeSet an org-wide default; org owners decide whether repos may override it. GA

Advanced setupYour own workflowDocs

What it doesYou own .github/workflows/codeql.yml: your own build for compiled languages, matrix builds, triggers and schedule

Outside ActionsRun the CodeQL CLI in another CI, or upload third-party results as SARIF

Merge protectionBefore PR mergeDocs

On the PRNew alerts show up as annotations in Files changed, posted by github-advanced-security[bot]

Merge gateRuleset Require code scanning results blocks the merge on alerts of a chosen severity, or while the required tool has not finished

ScopeRepo or Org (Enterprise plans). Without a ruleset, code scanning never blocks a merge

AI ScanPRs onlyDocs

What it doesAI flags risks in what CodeQL does not cover: PHP, Shell, Terraform, Dockerfile

ScopePRs only: no full-repo scan, no backlog alerts, not a merge gate. Enable code scanning and AI Scan; CodeQL default setup is not required

Copilot AutofixOn the alert or PRDocs

What it doesSuggests a patch from the alert, the surrounding code and CodeQL's data-flow path

WhereInline on PRs; Generate fix on backlog alerts. You review and apply it

Agentic Autofix1–25 backlog alertsDocs

What it doesAssign to Copilot: the cloud agent explores the repo, fixes, validates, then opens a draft PR

Scope1–25 default-branch backlog alerts, including campaigns. GA since 2026-10-15

Security campaignsRemediation at scaleDocs

What it doesA time-boxed set of alerts (up to 1000) with a campaign manager and a due date

FlowShows up in each repo's Security tab; developers fix with Autofix or Copilot

Why shift left: fix it in the PR

A vulnerability is cheapest to fix in the pull request that introduces it. Once merged, it becomes security debt, and debt rarely gets paid down.

🟢 In the PR🔴 After merge
🧠 ContextFresh in the author’s headRediscovered weeks later
🔁 Fix costOne commit, same reviewTicket, PR, review, deploy
🚀 ExposureNever reaches productionCan ship and stay live until fixed
  • 📉 Merged means forgotten: historically, only 10% of security debt in merged code gets addressed (GitHub data ↗)
  • ⏱️ In the PR, it is fast: with Copilot Autofix, PR-time alerts were fixed in a median 28 min vs 1.5 h manually (GitHub, 2024 ↗)

Copilot Autofix: suggested fixes 📖 Docs

Copilot Autofix can generate a suggested patch for an eligible alert. You review, test and apply it; a successful fix is not guaranteed.

  • 🤖 Input: alert details, surrounding code and CodeQL’s data-flow path inform the suggestion.
  • 💬 On pull requests: supported alerts can receive inline suggestions automatically.
  • 🛠️ On default-branch backlog alerts with Agentic Autofix off: Generate fix → Create PR with fix, if Copilot Autofix is enabled and supports the alert.
  • 🆓 Cost: no Copilot license or AI credits for classic Autofix. Included with Code Security; free on public repositories.
  • 🔌 Enablement: allowed by default with CodeQL unless an administrator disables it.

Agentic Autofix (GA) 📖 Docs

DEMOAgentic Autofix: settings to alertsFOR PRESENTER ONLY
  1. 1. ALLOW AT ENTERPRISE LEVEL, IF APPLICABLE

    An enterprise owner or security manager opens Policies → Advanced Security → Agentic Autofix and selects All organizations: Allowed. Skip this for a standalone organization. Setup docs ↗

    Allowed grants permission to configure the feature; it does not enable any organization. Confirm the billing method and Code Security AI Credits budget before rollout.

  2. 2. SHOW THE TWO ORGANIZATION SETTINGS

    Open theomonfort-org Advanced Security settings ↗ as an organization owner or security manager. In Global settings → Code scanning, locate Copilot Autofix and Agentic Autofix.

    Copilot Autofix controls classic suggestions. To enable agent remediation, set Agentic Autofix → On. Preview users must enable it again after GA.

    Turning this on enables Agentic Autofix for eligible repositories by default, not just the demo repo. Show the control without toggling it unless an organization-wide rollout is intended.

  3. 3. CHECK THE REPOSITORY OVERRIDE

    In the chosen demo repository, open Settings → Advanced Security → Code Security → Agentic Autofix. A repository administrator can set it to Off to opt out, or On if higher-level settings permit. Keep Copilot Autofix on if you want classic suggestions too.

    With Agentic Autofix enabled, users with write access can assign default-branch backlog alerts. No Copilot license is required. Enabling the setting alone does not start a repair session.

  4. THE SECURITY BOT ON A PR

    Open octodemo/octocat_supply-automatic-octo-funicular#57 ↗. In Files changed, show the comments from github-advanced-security[bot].

    These findings are separate from Copilot code review. Keep this deliberately vulnerable demo PR unmerged.

  5. TELL CODEQL AND AI FINDINGS APART

    The CodeQL XSS comment ↗ is on api/src/routes/cart.ts. Show the rule title and follow Show more details to the Security alert.

    For CartShareController.php, show the risk explanation and fix advice in the AI SQL injection comment ↗ and command injection comment ↗.

    The author is the same bot, but AI findings are PR-only and do not become backlog alerts in Security.

  6. FROM FINDING TO AGENTIC AUTOFIX

    The linked PR is in octodemo, so theomonfort-org settings do not apply to it. Open the CodeQL XSS alert ↗ only as a reference. For remediation, choose an existing default-branch backlog alert in the configured demo repository; a PR-only alert cannot be assigned.

    Show Assign to Copilot when Agentic Autofix is enabled. With it off, Generate fix is available only if classic Copilot Autofix is enabled and supports the alert.

    A bot finding is not a remediation session. Invoking Assign to Copilot starts the agent's repair work and produces a separate draft PR. You can show the entry point without starting a session.

GA since 2026-10-15. When Agentic Autofix is enabled, Assign to Copilot replaces Generate fix on default-branch backlog alerts.

▸ CLICK + FOR DETAILS

Assign1–25 alerts

Scope1–25 default-branch backlog alerts, including campaigns. One assignment → one session → one PR. No PR-only or other-branch-only alerts

Agent sessionDraft PR

FlowExplore → fix → rerun CodeQL and iterate → draft PR with validation details. Review the session log; request changes in the session or PR comments

Copilot MemoryLearns fix patternsChangelog

ReadsExisting repository memories for context, when Copilot Memory is enabled

WritesEach fix pattern as a new memory. Copilot code review and cloud agent learn your secure patterns from it too

RequirementsNo Copilot license

AccessGA for Code Security / GHAS customers on Enterprise Cloud, including data residency. Current docs also cover eligible personal public repos; managed-user personal repos are excluded

NeedsAgentic Autofix enabled, a configured billing method and repository write access. No Copilot license or pre-generated suggestion required. Settings on the next slide

CostAI credits + Actions

AgenticCode Security AI Credits + Actions minutes, including public repos. Usage appears under Advanced Security in billing's AI usage

BudgetEligible included credits are used first, then metered usage. Configure a Code Security AI Credits SKU budget

ValidationBest-effort

LimitsCannot confirm fixes for custom queries, security-extended or third-party alerts. Unvalidated fixes or suspected false positives are noted in the PR. Review and test before merging

Autofix vs Agentic Autofix 📖 Docs

Two independent settings, not a cloud-agent switch (2026-10-19).

▸ OPEN EACH LEVEL TO SEE THE EXACT SETTINGS

CompareSuggestion vs agent

ClassicOne suggested patch for a supported alert; you review and apply it. No AI credits

AgenticInvestigates, fixes and validates 1–25 default-branch backlog alerts; opens a draft PR. Code Security AI Credits + Actions. Neither type needs a Copilot license

EnterpriseAllow ≠ enable

WherePolicies → Advanced Security → Agentic Autofix → All organizations: Allowed. Enterprise owner or security manager

EffectAllows organizations to configure it; enables no repositories by itself. Copilot Autofix has a separate policy. Skip this level for standalone organizations

OrganizationEnable eligible reposDocs

WhereSettings → Advanced Security → Global settings → Code scanning → Agentic Autofix → On. Organization owner or security manager

EffectEnables eligible repositories by default. Coordinate opt-outs first. An enterprise block cannot be overridden here

RepositoryOpt out / re-enable

WhereSettings → Advanced Security → Code Security → Agentic Autofix → On / Off. Repository administrator

EffectCan opt out or re-enable only when parent settings permit. Eligible personal public repos configure this directly; managed-user personal repos are excluded

Which button?Separate controlsDocs

Agentic onAssign to Copilot on default-branch backlog alerts. Assignment starts the metered session, not enablement

Agentic offGenerate fix → Create PR with fix only if Copilot Autofix is on and supports the alert. Both off: no AI fix entry point

ClassicCopilot Autofix is on by default with CodeQL and has its own cascading controls at the same settings levels. Its PR suggestions remain separate from agent remediation

⚠️ Preview users must enable Agentic Autofix again after GA.

Security Campaigns — drive remediation at scale

Detection is the easy half; what happens after the alert is the real work. At scale, don’t grind the raw alert list — run a time-boxed campaign.

▸ CLICK A STEP FOR DETAILS

SCOPE

🎯 SCOPE — not the whole org

Org → Security and quality → Campaigns → New campaign, then pick From template or From code scanning filters.

Filter by severity, CWE, query, language, repo, team, age. Targeting a repo custom property (props.BusinessPriority:Urgent) is the usual move. Hard cap: 1000 alerts.

TRIAGE

⚡ TRIAGE — make it finishable

Start with critical and high, and with findings that carry a real reachable data-flow path. Dumping the whole security-extended backlog in guarantees nobody starts.

Watch the count drop as you filter. Cutting it down to one sprint's worth is the only trick that makes campaigns work.

OWN

👥 OWN — a name and a date

Every campaign gets a due date and a campaign manager. The picker only offers org owners and security managers.

Alerts route to CODEOWNERS or a named team. Publishing notifies everyone who can see the alerts, and the campaign appears in each repo's Security tab.

FIX

🤖 FIX — hand the batch to Copilot

With Agentic Autofix enabled, select 1–25 default-branch backlog alerts and assign them to Copilot. This consumes Code Security AI Credits + Actions minutes.

For the rest, batch apply the Autofix suggestions on the PR. The dashboard burns down open / fixed / overdue as you go.

SELECT A STEP ▸

📘 Details: About security campaigns (GitHub Docs) ↗

DEMOCode Scanning checklistFOR PRESENTER ONLY
  1. 1. ENABLEMENT AND COVERAGE

    ghas-test-1 → Advanced Security ↗ / CodeQL runs ↗: inspect the existing Advanced setup and language jobs. Do not switch this configured repository to Default setup.

  2. 2. EXTRA QUERY PACKS

    ghas-test-1 → codeql.yml ↗ / MISRA / CERT / AUTOSAR packs ↗: show how the workflow configures additional queries and packs.

  3. 3. MERGE PROTECTION

    ghas-test-1 → New branch ruleset ↗: Require code scanning results → CodeQL. Example: Security alerts: High or higher, Alerts: Errors, target main. Keep it disabled for a walkthrough.

  4. 4. AI SCAN

    octodemo ↗ → Policies → Advanced Security → AI Scan, then theomonfort-org → Global settings ↗ → AI Scan.

    Confirm enterprise permission and the Code Security AI Credits budget. Organization enablement affects all eligible repositories; show the controls without toggling them.

  5. 5. ASSISTED REMEDIATION

    theomonfort-org → Autofix settings ↗: show the separate Copilot Autofix and Agentic Autofix controls. Check enterprise permission before enabling Agentic Autofix.

    ghas-test-1 → Repository override ↗ / Code scanning alerts ↗

  6. 6. SECURITY CAMPAIGNS

    theomonfort-org → Campaigns ↗: Create campaign → From code scanning filters. Scope to ghas-test-1, choose a manager and due date, then save as a draft.

Validate detection, protect new code, then reduce the backlog.

▸ CHECK COMPLETED STEPS. OPEN A STEP FOR SETTINGS

1Enable CodeQL and verify coverageACTIVATEDocs

StartCodeQL settings ↗: start with Default setup. Check the first scan, languages and Actions usage before rolling out with security configurations.

2Add extra query packs if neededOPTIONALDocs

CustomizeCodeQL configuration ↗: add MISRA / CERT / AUTOSAR packs ↗ for C/C++, or internal queries. Adapt the configuration to your build.

3Block high-risk findings before mergeRULESETSDocs

ExampleRulesets ↗: Require code scanning results (CodeQL). Security alerts: High or higher; Alerts: Errors. Target main and restrict bypass.

4Enable AI Scan for pull requestsAI SCANDocs

Opt inOrg settings ↗: enterprise permission + Code Security AI Credits budget first; then enable org-wide for eligible repos. PR-only advice, no merge gate or backlog.

5Set up assisted remediationAUTOFIXDocs

PrepareOrg settings ↗: classic Autofix is on with CodeQL unless disabled. Optionally enable Agentic Autofix for draft PRs; budget AI credits + Actions.

6Create security campaignsCAMPAIGNSDocs

RemediateCampaigns ↗: select code scanning alerts, prioritize risk, set a manager and due date. Start with a small backlog.

URL templates: replace ORG, OWNER, REPO.

Advanced setup and SARIF

When Default is not enough (monorepo, unusual build, another SAST tool), write the workflow yourself.

# .github/workflows/codeql.yml
name: CodeQL
on:
  push: { branches: [main] }
  pull_request: { branches: [main] }
  schedule: [{ cron: '30 5 * * 1' }]
jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions: { security-events: write, contents: read }
    strategy:
      matrix: { language: [javascript, python] }
    steps:
      - uses: actions/checkout@v4
      - uses: github/codeql-action/init@v3
        with: { languages: '${{ matrix.language }}', queries: security-extended }
      - uses: github/codeql-action/analyze@v3

      # third-party SAST (Semgrep, Snyk, ESLint security) lands in the same UI:
      - uses: github/codeql-action/upload-sarif@v3
        with: { sarif_file: results.sarif }

💡 Point runs-on at a self-hosted runner and the Actions minutes are not billed — the first lever when scan cost bites at scale.

Pricing: three meters 📖 Docs

▸ + UNFOLDS THE DETAIL

CostHow it is measuredGood to know
💺 License $30 / active committer / month
GitHub Code Security
What's included

CodeQL (default and advanced), Copilot Autofix, SARIF upload, Security overview, Security campaigns, custom queries. Autofix costs nothing extra.

Who counts

Active committers have a commit pushed to an enabled repo in the last 90 days. One license per person across enabled repos and orgs in the enterprise; GitHub App bots are excluded. Code Security is sold standalone.

⚙️ Actions minutes CodeQL runs on Actions. Private scans consume minutes; overages are billed.
When it runs

Default setup runs on pushes to the default or protected branches, PRs against them and a weekly schedule. Minutes depend on run duration, repository count, languages and frequency.

Cap the spend

Self-hosted runners are not billed, or set an Actions budget. Minutes are not included in the Code Security license. Trap: larger runners are charged even on public repos.

Measure it

Filter Actions usage metrics by workflow name to isolate what CodeQL alone costs, so the conversation runs on real numbers instead of estimates.
github.com/orgs/<org>/actions/metrics/usage?filters=codeql.yml

🤖 AI credits Metered: AI Scan (detection) and Agentic Autofix (fixing). Classic Autofix suggestions remain free.
AI Scan

As of 2026-10-26: automatic PR detection consumes Code Security AI Credits, even without a fix request. On an organization-owned repo, the organization's billing account pays (standalone org or enterprise), not the PR author's personal credits. No Copilot license required. Billing docs ↗

Copilot Autofix

Classic suggestions, including Generate fix → Create PR with fix, consume no AI credits. No Copilot license required; included with Code Security and free on public repos. Docs ↗

Agentic Autofix

As of 2026-10-26: Security → Assign to Copilot or campaign assignment consumes Code Security AI Credits + Actions minutes. On an organization-owned repo, the org or enterprise billing account pays, not your personal credits, even when you assign the alert yourself. No Copilot license required. Set a Code Security AI Credits SKU budget. Billing docs ↗

Copilot Chat / agent

Asking Copilot Chat or starting a regular cloud-agent task to fix a vulnerability is Copilot usage, not Agentic Autofix. It consumes AI credits under your Copilot plan: your allowance on an individual plan, or the shared org / enterprise pool on Business / Enterprise. Individual ↗ / Organization ↗

Eligibility by repository type 📖 Docs

FeaturePublic repoPrivate repo
without Code Security
Private repo
with Code Security
Core code scanning✅ Free❌✅ Included
Security campaigns❌❌✅ Included
Actions minutesFree*Not applicableSeparate usage*

📦 Core: CodeQL, custom queries, SARIF uploads, eligible Autofix suggestions, PR annotations and Security overview.

💰 Actions*: standard hosted runners are free for public repos. Private repos consume included minutes, then bill overages. Larger runners are always billed.

⚠️ Public → private: Code Security is required to keep code scanning enabled.

Code Security Risk Assessment (free inventory scan)

One click, CodeQL scans the 20 most active repos in your org and shows where the vulnerabilities are. No GHAS / Code Security license needed, completely free (GA April 2026).

  • 🔎 Scope — up to 20 repos with the most recent commits, re-selectable each run
  • 📊 Output — report by severity, language, rule type, plus how many Copilot Autofix can fix
  • 🕒 Frequency — re-runnable once every 90 days; org owners / security managers only
  • 🚀 How to run — Org → Security → Assessments → Run code security risk assessment
  • 🆓 Cost — no license, no Actions minutes — ideal for evaluating Code Security before buying

📊 Pair this with Secret Risk Assessment (see Secret Scanning ↗) and you get a full posture read in a single day, then decide on Code Security with real numbers.

📘 Details: Code security risk assessment ↗ / How exposed is your code? ↗

Slides 日本語