codeql

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CodeQL Code Scanning

CodeQL代码扫描

This skill provides procedural guidance for configuring and running CodeQL code scanning — both through GitHub Actions workflows and the standalone CodeQL CLI.
本技能提供了通过GitHub Actions工作流和独立CodeQL CLI配置与运行CodeQL代码扫描的流程指导。

When to Use This Skill

何时使用本技能

Use this skill when the request involves:
  • Creating or customizing a
    codeql.yml
    GitHub Actions workflow
  • Choosing between default setup and advanced setup for code scanning
  • Configuring CodeQL language matrix, build modes, or query suites
  • Running CodeQL CLI locally (
    codeql database create
    ,
    database analyze
    ,
    github upload-results
    )
  • Understanding or interpreting SARIF output from CodeQL
  • Troubleshooting CodeQL analysis failures (build modes, compiled languages, runner requirements)
  • Setting up CodeQL for monorepos with per-component scanning
  • Configuring dependency caching, custom query packs, or model packs
当请求涉及以下内容时,使用本技能:
  • 创建或自定义
    codeql.yml
    GitHub Actions工作流
  • 选择代码扫描的默认设置与高级设置
  • 配置CodeQL语言矩阵、构建模式或查询套件
  • 本地运行CodeQL CLI(
    codeql database create
    database analyze
    github upload-results
  • 理解或解读CodeQL的SARIF输出
  • 排查CodeQL分析失败问题(构建模式、编译型语言、运行器要求)
  • 为多仓库(monorepo)设置CodeQL以实现按组件扫描
  • 配置依赖缓存、自定义查询包或模型包

Supported Languages

支持的语言

CodeQL supports the following language identifiers:
LanguageIdentifierAlternatives
C/C++
c-cpp
c
,
cpp
C#
csharp
Go
go
Java/Kotlin
java-kotlin
java
,
kotlin
JavaScript/TypeScript
javascript-typescript
javascript
,
typescript
Python
python
Ruby
ruby
Rust
rust
Swift
swift
GitHub Actions
actions
Alternative identifiers are equivalent to the standard identifier (e.g.,
javascript
does not exclude TypeScript analysis).
CodeQL支持以下语言标识符:
语言标识符替代写法
C/C++
c-cpp
c
,
cpp
C#
csharp
Go
go
Java/Kotlin
java-kotlin
java
,
kotlin
JavaScript/TypeScript
javascript-typescript
javascript
,
typescript
Python
python
Ruby
ruby
Rust
rust
Swift
swift
GitHub Actions
actions
替代标识符与标准标识符等效(例如,
javascript
不会排除TypeScript分析)。

Core Workflow — GitHub Actions

核心工作流 — GitHub Actions

Step 1: Choose Setup Type

步骤1:选择设置类型

  • Default setup — Enable from repository Settings → Advanced Security → CodeQL analysis. Best for getting started quickly. Uses
    none
    build mode for most languages.
  • Advanced setup — Create a
    .github/workflows/codeql.yml
    file for full control over triggers, build modes, query suites, and matrix strategies.
To switch from default to advanced: disable default setup first, then commit the workflow file.
  • 默认设置 — 从仓库设置→高级安全→CodeQL分析启用。适合快速上手。大多数语言使用
    none
    构建模式。
  • 高级设置 — 创建
    .github/workflows/codeql.yml
    文件,以完全控制触发器、构建模式、查询套件和矩阵策略。
要从默认设置切换到高级设置:先禁用默认设置,然后提交工作流文件。

Step 2: Configure Workflow Triggers

步骤2:配置工作流触发器

Define when scanning runs:
yaml
on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '30 6 * * 1'  # Weekly Monday 6:30 UTC
  • push
    — scans on every push to specified branches; results appear in Security tab
  • pull_request
    — scans PR merge commits; results appear as PR check annotations
  • schedule
    — periodic scans of the default branch (cron must exist on default branch)
  • merge_group
    — add if repository uses merge queues
To skip scans for documentation-only PRs:
yaml
on:
  pull_request:
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'
paths-ignore
controls whether the workflow runs, not which files are analyzed.
定义扫描运行的时机:
yaml
on:
  push:
    branches: [main, protected]
  pull_request:
    branches: [main]
  schedule:
    - cron: '30 6 * * 1'  # Weekly Monday 6:30 UTC
  • push
    — 每次推送到指定分支时扫描;结果显示在安全选项卡中
  • pull_request
    — 扫描PR合并提交;结果以PR检查注释形式显示
  • schedule
    — 定期扫描默认分支(cron表达式必须存在于默认分支)
  • merge_group
    — 如果仓库使用合并队列,则添加此项
要跳过仅包含文档的PR扫描:
yaml
on:
  pull_request:
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'
paths-ignore
控制工作流是否运行,而非哪些文件会被分析。

Step 3: Configure Permissions

步骤3:配置权限

Set least-privilege permissions:
yaml
permissions:
  security-events: write   # Required to upload SARIF results
  contents: read            # Required to checkout code
  actions: read             # Required for private repos using codeql-action
设置最小权限:
yaml
permissions:
  security-events: write   # Required to upload SARIF results
  contents: read            # Required to checkout code
  actions: read             # Required for private repos using codeql-action

Step 4: Configure Language Matrix

步骤4:配置语言矩阵

Use a matrix strategy to analyze each language in parallel:
yaml
jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - language: javascript-typescript
            build-mode: none
          - language: python
            build-mode: none
For compiled languages, set the appropriate
build-mode
:
  • none
    — no build required (supported for C/C++, C#, Java, Rust)
  • autobuild
    — automatic build detection
  • manual
    — custom build commands (advanced setup only)
For detailed per-language autobuild behavior and runner requirements, search
references/compiled-languages.md
.
使用矩阵策略并行分析每种语言:
yaml
jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        include:
          - language: javascript-typescript
            build-mode: none
          - language: python
            build-mode: none
对于编译型语言,设置合适的
build-mode
  • none
    — 无需构建(支持C/C++、C#、Java、Rust)
  • autobuild
    — 自动检测构建流程
  • manual
    — 自定义构建命令(仅高级设置支持)
有关各语言自动构建行为和运行器要求的详细信息,请查阅
references/compiled-languages.md

Step 5: Configure CodeQL Init and Analysis

步骤5:配置CodeQL初始化与分析

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

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

  - name: Perform CodeQL Analysis
    uses: github/codeql-action/analyze@v4
    with:
      category: "/language:${{ matrix.language }}"
Query suite options:
  • security-extended
    — default security queries plus additional coverage
  • security-and-quality
    — security plus code quality queries
  • Custom query packs via
    packs:
    input (e.g.,
    codeql/javascript-queries:AlertSuppression.ql
    )
Dependency caching: Set
dependency-caching: true
on the
init
action to cache restored dependencies across runs.
Analysis category: Use
category
to distinguish SARIF results in monorepos (e.g., per-language, per-component).
yaml
steps:
  - name: Checkout repository
    uses: actions/checkout@v4

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

  - name: Perform CodeQL Analysis
    uses: github/codeql-action/analyze@v4
    with:
      category: "/language:${{ matrix.language }}"
查询套件选项:
  • security-extended
    — 默认安全查询加上额外覆盖范围
  • security-and-quality
    — 安全查询加上代码质量查询
  • 通过
    packs:
    输入使用自定义查询包(例如,
    codeql/javascript-queries:AlertSuppression.ql
依赖缓存:
init
操作中设置
dependency-caching: true
,以在多次运行之间缓存已恢复的依赖项。
分析分类: 使用
category
区分多仓库中的SARIF结果(例如,按语言、按组件)。

Step 6: Monorepo Configuration

步骤6:多仓库配置

For monorepos with multiple components, use the
category
parameter to separate SARIF results:
yaml
category: "/language:${{ matrix.language }}/component:frontend"
To restrict analysis to specific directories, use a CodeQL configuration file (
.github/codeql/codeql-config.yml
):
yaml
paths:
  - apps/
  - services/
paths-ignore:
  - node_modules/
  - '**/test/**'
Reference it in the workflow:
yaml
- uses: github/codeql-action/init@v4
  with:
    config-file: .github/codeql/codeql-config.yml
对于包含多个组件的多仓库,使用
category
参数分离SARIF结果:
yaml
category: "/language:${{ matrix.language }}/component:frontend"
要将分析限制在特定目录,使用CodeQL配置文件(
.github/codeql/codeql-config.yml
):
yaml
paths:
  - apps/
  - services/
paths-ignore:
  - node_modules/
  - '**/test/**'
在工作流中引用该文件:
yaml
- uses: github/codeql-action/init@v4
  with:
    config-file: .github/codeql/codeql-config.yml

Step 7: Manual Build Steps (Compiled Languages)

步骤7:手动构建步骤(编译型语言)

If
autobuild
fails or custom build commands are needed:
yaml
- language: c-cpp
  build-mode: manual
Then add explicit build steps between
init
and
analyze
:
yaml
- if: matrix.build-mode == 'manual'
  name: Build
  run: |
    make bootstrap
    make release
如果
autobuild
失败或需要自定义构建命令:
yaml
- language: c-cpp
  build-mode: manual
然后在
init
analyze
之间添加显式构建步骤:
yaml
- if: matrix.build-mode == 'manual'
  name: Build
  run: |
    make bootstrap
    make release

Core Workflow — CodeQL CLI

核心工作流 — CodeQL CLI

Step 1: Install the CodeQL CLI

步骤1:安装CodeQL CLI

Download the CodeQL bundle (includes CLI + precompiled queries):
bash
undefined
下载CodeQL捆绑包(包含CLI + 预编译查询):
bash
undefined

Extract and add to PATH

Extract and add to PATH

export PATH="$HOME/codeql:$PATH"
export PATH="$HOME/codeql:$PATH"

Verify installation

Verify installation

codeql resolve packs codeql resolve languages

> Always use the CodeQL bundle, not a standalone CLI download. The bundle ensures query compatibility and provides precompiled queries for better performance.
codeql resolve packs codeql resolve languages

> 始终使用CodeQL捆绑包,而非独立CLI下载。捆绑包确保查询兼容性,并提供预编译查询以提升性能。

Step 2: Create a CodeQL Database

步骤2:创建CodeQL数据库

bash
undefined
bash
undefined

Single language

Single language

codeql database create codeql-db
--language=javascript-typescript
--source-root=src
codeql database create codeql-db
--language=javascript-typescript
--source-root=src

Multiple languages (cluster mode)

Multiple languages (cluster mode)

codeql database create codeql-dbs
--db-cluster
--language=java,python
--command=./build.sh
--source-root=src

For compiled languages, provide the build command via `--command`.
codeql database create codeql-dbs
--db-cluster
--language=java,python
--command=./build.sh
--source-root=src

对于编译型语言,通过`--command`提供构建命令。

Step 3: Analyze the Database

步骤3:分析数据库

bash
codeql database analyze codeql-db \
  javascript-code-scanning.qls \
  --format=sarif-latest \
  --sarif-category=javascript \
  --output=results.sarif
Common query suites:
<language>-code-scanning.qls
,
<language>-security-extended.qls
,
<language>-security-and-quality.qls
.
bash
codeql database analyze codeql-db \
  javascript-code-scanning.qls \
  --format=sarif-latest \
  --sarif-category=javascript \
  --output=results.sarif
常见查询套件:
<language>-code-scanning.qls
<language>-security-extended.qls
<language>-security-and-quality.qls

Step 4: Upload Results to GitHub

步骤4:将结果上传到GitHub

bash
codeql github upload-results \
  --repository=owner/repo \
  --ref=refs/heads/main \
  --commit=<commit-sha> \
  --sarif=results.sarif
Requires
GITHUB_TOKEN
environment variable with
security-events: write
permission.
bash
codeql github upload-results \
  --repository=owner/repo \
  --ref=refs/heads/main \
  --commit=<commit-sha> \
  --sarif=results.sarif
需要具有
security-events: write
权限的
GITHUB_TOKEN
环境变量。

CLI Server Mode

CLI服务器模式

To avoid repeated JVM initialization when running multiple commands:
bash
codeql execute cli-server
For detailed CLI command reference, search
references/cli-commands.md
.
为避免运行多个命令时重复初始化JVM:
bash
codeql execute cli-server
有关CLI命令的详细参考,请查阅
references/cli-commands.md

Alert Management

告警管理

Severity Levels

严重级别

Alerts have two severity dimensions:
  • Standard severity:
    Error
    ,
    Warning
    ,
    Note
  • Security severity:
    Critical
    ,
    High
    ,
    Medium
    ,
    Low
    (derived from CVSS scores; takes display precedence)
告警包含两个严重程度维度:
  • 标准严重级别:
    Error
    Warning
    Note
  • 安全严重级别:
    Critical
    High
    Medium
    Low
    (由CVSS分数得出;显示优先级更高)

Copilot Autofix

Copilot自动修复

GitHub Copilot Autofix generates fix suggestions for CodeQL alerts in pull requests automatically — no Copilot subscription required. Review suggestions carefully before committing.
GitHub Copilot Autofix会自动为拉取请求中的CodeQL告警生成修复建议 — 无需Copilot订阅。提交前请仔细审核建议。

Alert Triage in PRs

PR中的告警分类

  • Alerts appear as check annotations on changed lines
  • Check fails by default for
    error
    /
    critical
    /
    high
    severity alerts
  • Configure merge protection rulesets to customize the threshold
  • Dismiss false positives with a documented reason for audit trail
For detailed alert management guidance, search
references/alert-management.md
.
  • 告警以检查注释形式显示在变更行上
  • 默认情况下,
    error
    /
    critical
    /
    high
    严重级别的告警会导致检查失败
  • 配置合并保护规则集来自定义阈值
  • 为误报添加文档化理由后关闭,以保留审计跟踪
有关告警管理的详细指南,请查阅
references/alert-management.md

Custom Queries and Packs

自定义查询与包

Using Custom Query Packs

使用自定义查询包

yaml
- uses: github/codeql-action/init@v4
  with:
    packs: |
      my-org/my-security-queries@1.0.0
      codeql/javascript-queries:AlertSuppression.ql
yaml
- uses: github/codeql-action/init@v4
  with:
    packs: |
      my-org/my-security-queries@1.0.0
      codeql/javascript-queries:AlertSuppression.ql

Creating Custom Query Packs

创建自定义查询包

Use the CodeQL CLI to create and publish packs:
bash
undefined
使用CodeQL CLI创建并发布包:
bash
undefined

Initialize a new pack

Initialize a new pack

codeql pack init my-org/my-queries
codeql pack init my-org/my-queries

Install dependencies

Install dependencies

codeql pack install
codeql pack install

Publish to GitHub Container Registry

Publish to GitHub Container Registry

codeql pack publish
undefined
codeql pack publish
undefined

CodeQL Configuration File

CodeQL配置文件

For advanced query and path configuration, create
.github/codeql/codeql-config.yml
:
yaml
paths:
  - apps/
  - services/
paths-ignore:
  - '**/test/**'
  - node_modules/
queries:
  - uses: security-extended
packs:
  javascript-typescript:
    - my-org/my-custom-queries
对于高级查询和路径配置,创建
.github/codeql/codeql-config.yml
yaml
paths:
  - apps/
  - services/
paths-ignore:
  - '**/test/**'
  - node_modules/
queries:
  - uses: security-extended
packs:
  javascript-typescript:
    - my-org/my-custom-queries

Code Scanning Logs

代码扫描日志

Summary Metrics

汇总指标

Workflow logs include key metrics:
  • Lines of code in codebase — baseline before extraction
  • Lines extracted — including external libraries and auto-generated files
  • Extraction errors/warnings — files that failed or produced warnings during extraction
工作流日志包含关键指标:
  • 代码库中的代码行数 — 提取前的基线
  • 已提取行数 — 包括外部库和自动生成的文件
  • 提取错误/警告 — 提取过程中失败或产生警告的文件

Debug Logging

调试日志

To enable detailed diagnostics:
  • GitHub Actions: re-run the workflow with "Enable debug logging" checked
  • CodeQL CLI: use
    --verbosity=progress++
    and
    --logdir=codeql-logs
要启用详细诊断:
  • GitHub Actions: 重新运行工作流时勾选“启用调试日志”
  • CodeQL CLI: 使用
    --verbosity=progress++
    --logdir=codeql-logs

Troubleshooting

故障排查

Common Issues

常见问题

ProblemSolution
Workflow not triggeringVerify
on:
triggers match event; check
paths
/
branches
filters; ensure workflow exists on target branch
Resource not accessible
error
Add
security-events: write
and
contents: read
permissions
Autobuild failureSwitch to
build-mode: manual
and add explicit build commands
No source code seenVerify
--source-root
, build command, and language identifier
C# compiler failureCheck for
/p:EmitCompilerGeneratedFiles=true
conflicts with
.sqlproj
or legacy projects
Fewer lines scanned than expectedSwitch from
none
to
autobuild
/
manual
; verify build compiles all source
Kotlin in no-build modeDisable and re-enable default setup to switch to
autobuild
Cache miss every runVerify
dependency-caching: true
on
init
action
Out of disk/memoryUse larger runners; reduce analysis scope via
paths
config; use
build-mode: none
SARIF upload failsEnsure token has
security-events: write
; check 10 MB file size limit
SARIF results exceed limitsSplit across multiple uploads with different
--sarif-category
; reduce query scope
Two CodeQL workflowsDisable default setup if using advanced setup, or remove old workflow file
Slow analysisEnable dependency caching; use
--threads=0
; reduce query suite scope
For comprehensive troubleshooting with detailed solutions, search
references/troubleshooting.md
.
问题解决方案
工作流未触发验证
on:
触发器是否匹配事件;检查
paths
/
branches
过滤器;确保工作流存在于目标分支
Resource not accessible
错误
添加
security-events: write
contents: read
权限
自动构建失败切换到
build-mode: manual
并添加显式构建命令
未检测到源代码验证
--source-root
、构建命令和语言标识符
C#编译器失败检查
/p:EmitCompilerGeneratedFiles=true
.sqlproj
或旧项目的冲突
扫描行数少于预期
none
切换到
autobuild
/
manual
;验证构建是否编译了所有源代码
Kotlin在无构建模式下异常禁用并重新启用默认设置以切换到
autobuild
每次运行都缓存未命中验证
init
操作中是否设置了
dependency-caching: true
磁盘/内存不足使用更大的运行器;通过
paths
配置缩小分析范围;使用
build-mode: none
SARIF上传失败确保令牌具有
security-events: write
权限;检查10MB文件大小限制
SARIF结果超出限制通过不同的
--sarif-category
拆分到多个上传;缩小查询范围
存在两个CodeQL工作流如果使用高级设置,请禁用默认设置,或删除旧的工作流文件
分析速度慢启用依赖缓存;使用
--threads=0
;缩小查询套件范围
有关包含详细解决方案的全面故障排查指南,请查阅
references/troubleshooting.md

Hardware Requirements (Self-Hosted Runners)

硬件要求(自托管运行器)

Codebase SizeRAMCPU
Small (<100K LOC)8 GB+2 cores
Medium (100K–1M LOC)16 GB+4–8 cores
Large (>1M LOC)64 GB+8 cores
All sizes: SSD with ≥14 GB free disk space.
代码库大小内存CPU
小型(<10万行)8GB+2核
中型(10万–100万行)16GB+4–8核
大型(>100万行)64GB+8核
所有规模:SSD,可用磁盘空间≥14GB。

Action Versioning

操作版本控制

Pin CodeQL actions to a specific major version:
yaml
uses: github/codeql-action/init@v4      # Recommended
uses: github/codeql-action/autobuild@v4
uses: github/codeql-action/analyze@v4
For maximum security, pin to a full commit SHA instead of a version tag.
将CodeQL操作固定到特定主版本:
yaml
uses: github/codeql-action/init@v4      # Recommended
uses: github/codeql-action/autobuild@v4
uses: github/codeql-action/analyze@v4
为了最高安全性,固定到完整提交SHA而非版本标签。

Reference Files

参考文件

For detailed documentation, load the following reference files as needed:
  • references/workflow-configuration.md
    — Full workflow trigger, runner, and configuration options
    • Search patterns:
      trigger
      ,
      schedule
      ,
      paths-ignore
      ,
      db-location
      ,
      model packs
      ,
      alert severity
      ,
      merge protection
      ,
      concurrency
      ,
      config file
  • references/cli-commands.md
    — Complete CodeQL CLI command reference
    • Search patterns:
      database create
      ,
      database analyze
      ,
      upload-results
      ,
      resolve packs
      ,
      cli-server
      ,
      installation
      ,
      CI integration
  • references/sarif-output.md
    — SARIF v2.1.0 object model, upload limits, and third-party support
    • Search patterns:
      sarifLog
      ,
      result
      ,
      location
      ,
      region
      ,
      codeFlow
      ,
      fingerprint
      ,
      suppression
      ,
      upload limits
      ,
      third-party
      ,
      precision
      ,
      security-severity
  • references/compiled-languages.md
    — Build modes and autobuild behavior per language
    • Search patterns:
      C/C++
      ,
      C#
      ,
      Java
      ,
      Go
      ,
      Rust
      ,
      Swift
      ,
      autobuild
      ,
      build-mode
      ,
      hardware
      ,
      dependency caching
  • references/troubleshooting.md
    — Comprehensive error diagnosis and resolution
    • Search patterns:
      no source code
      ,
      out of disk
      ,
      out of memory
      ,
      403
      ,
      C# compiler
      ,
      analysis too long
      ,
      fewer lines
      ,
      Kotlin
      ,
      extraction errors
      ,
      debug logging
      ,
      SARIF upload
      ,
      SARIF limits
  • references/alert-management.md
    — Alert severity, triage, Copilot Autofix, and dismissal
    • Search patterns:
      severity
      ,
      security severity
      ,
      CVSS
      ,
      Copilot Autofix
      ,
      dismiss
      ,
      triage
      ,
      PR alerts
      ,
      data flow
      ,
      merge protection
      ,
      REST API
如需详细文档,根据需要加载以下参考文件:
  • references/workflow-configuration.md
    —完整的工作流触发器、运行器和配置选项
    • 搜索关键词:
      trigger
      schedule
      paths-ignore
      db-location
      model packs
      alert severity
      merge protection
      concurrency
      config file
  • references/cli-commands.md
    —完整的CodeQL CLI命令参考
    • 搜索关键词:
      database create
      database analyze
      upload-results
      resolve packs
      cli-server
      installation
      CI integration
  • references/sarif-output.md
    —SARIF v2.1.0对象模型、上传限制和第三方支持
    • 搜索关键词:
      sarifLog
      result
      location
      region
      codeFlow
      fingerprint
      suppression
      upload limits
      third-party
      precision
      security-severity
  • references/compiled-languages.md
    —各语言的构建模式和自动构建行为
    • 搜索关键词:
      C/C++
      C#
      Java
      Go
      Rust
      Swift
      autobuild
      build-mode
      hardware
      dependency caching
  • references/troubleshooting.md
    —全面的错误诊断与解决方法
    • 搜索关键词:
      no source code
      out of disk
      out of memory
      403
      C# compiler
      analysis too long
      fewer lines
      Kotlin
      extraction errors
      debug logging
      SARIF upload
      SARIF limits
  • references/alert-management.md
    —告警严重级别、分类、Copilot自动修复和关闭
    • 搜索关键词:
      severity
      security severity
      CVSS
      Copilot Autofix
      dismiss
      triage
      PR alerts
      data flow
      merge protection
      REST API