codeql
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCodeQL 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.
此 Skill 提供有关配置和运行 CodeQL 代码扫描的流程指南,既涵盖通过 GitHub Actions 工作流执行扫描,也涵盖使用独立的 CodeQL CLI。
When to Use This Skill
何时使用此 Skill
Use this skill when the request involves:
- Creating or customizing a GitHub Actions workflow
codeql.yml - 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
当请求涉及以下内容时使用此 Skill:
- 创建或自定义 GitHub Actions 工作流
codeql.yml - 在代码扫描的默认设置和高级设置之间进行选择
- 配置 CodeQL 语言矩阵、构建模式或查询套件
- 在本地运行 CodeQL CLI(、
codeql database create、database analyze)github upload-results - 理解或解释 CodeQL 生成的 SARIF 输出
- 排查 CodeQL 分析失败问题(构建模式、编译型语言、runner 要求)
- 为 monorepo 设置 CodeQL,并按组件执行扫描
- 配置依赖项缓存、自定义查询包或 model pack
Supported Languages
支持的语言
CodeQL supports the following language identifiers:
| Language | Identifier | Alternatives |
|---|---|---|
| C/C++ | | |
| C# | | — |
| Go | | — |
| Java/Kotlin | | |
| JavaScript/TypeScript | | |
| Python | | — |
| Ruby | | — |
| Rust | | — |
| Swift | | — |
| GitHub Actions | | — |
Alternative identifiers are equivalent to the standard identifier (e.g.,does not exclude TypeScript analysis).javascript
CodeQL 支持以下语言标识符:
| 语言 | 标识符 | 别名 |
|---|---|---|
| C/C++ | | |
| C# | | — |
| Go | | — |
| Java/Kotlin | | |
| JavaScript/TypeScript | | |
| Python | | — |
| Ruby | | — |
| Rust | | — |
| Swift | | — |
| GitHub Actions | | — |
替代标识符与标准标识符等价(例如,不会排除 TypeScript 分析)。javascript
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 build mode for most languages.
none - Advanced setup — Create a file for full control over triggers, build modes, query suites, and matrix strategies.
.github/workflows/codeql.yml
To switch from default to advanced: disable default setup first, then commit the workflow file.
- 默认设置——从仓库 Settings → Advanced Security → CodeQL analysis 中启用。最适合快速上手。对大多数语言使用 构建模式。
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- — scans on every push to specified branches; results appear in Security tab
push - — scans PR merge commits; results appear as PR check annotations
pull_request - — periodic scans of the default branch (cron must exist on default branch)
schedule - — add if repository uses merge queues
merge_group
To skip scans for documentation-only PRs:
yaml
on:
pull_request:
paths-ignore:
- '**/*.md'
- '**/*.txt'controls whether the workflow runs, not which files are analyzed.paths-ignore
定义何时运行扫描:
yaml
on:
push:
branches: [main, protected]
pull_request:
branches: [main]
schedule:
- cron: '30 6 * * 1' # Weekly Monday 6:30 UTC- ——每次推送到指定分支时扫描;结果显示在 Security 标签页中
push - ——扫描 PR 合并提交;结果显示为 PR 检查注释
pull_request - ——定期扫描默认分支(cron 必须存在于默认分支中)
schedule - ——如果仓库使用 merge queue,则添加此项
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-actionStep 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: noneFor compiled languages, set the appropriate :
build-mode- — no build required (supported for C/C++, C#, Java, Rust)
none - — automatic build detection
autobuild - — custom build commands (advanced setup only)
manual
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- ——无需构建(支持 C/C++、C#、Java、Rust)
none - ——自动检测构建
autobuild - ——自定义构建命令(仅限高级设置)
manual
有关各语言 autobuild 行为和 runner 要求的详细信息,请搜索。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:
- — default security queries plus additional coverage
security-extended - — security plus code quality queries
security-and-quality - Custom query packs via input (e.g.,
packs:)codeql/javascript-queries:AlertSuppression.ql
Dependency caching: Set on the action to cache restored dependencies across runs.
dependency-caching: trueinitAnalysis category: Use to distinguish SARIF results in monorepos (e.g., per-language, per-component).
categoryyaml
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
依赖项缓存: 在 action 中设置 ,以在多次运行之间缓存恢复的依赖项。
initdependency-caching: true分析类别: 使用 区分 monorepo 中的 SARIF 结果(例如按语言或组件区分)。
categoryStep 6: Monorepo Configuration
第 6 步:配置 Monorepo
For monorepos with multiple components, use the parameter to separate SARIF results:
categoryyaml
category: "/language:${{ matrix.language }}/component:frontend"To restrict analysis to specific directories, use a CodeQL configuration file ():
.github/codeql/codeql-config.ymlyaml
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对于包含多个组件的 monorepo,请使用 参数分隔 SARIF 结果:
categoryyaml
category: "/language:${{ matrix.language }}/component:frontend"要将分析限制在特定目录中,请使用 CodeQL 配置文件():
.github/codeql/codeql-config.ymlyaml
paths:
- apps/
- services/
paths-ignore:
- node_modules/
- '**/test/**'在工作流中引用该文件:
yaml
- uses: github/codeql-action/init@v4
with:
config-file: .github/codeql/codeql-config.ymlStep 7: Manual Build Steps (Compiled Languages)
第 7 步:手动构建步骤(编译型语言)
If fails or custom build commands are needed:
autobuildyaml
- language: c-cpp
build-mode: manualThen add explicit build steps between and :
initanalyzeyaml
- if: matrix.build-mode == 'manual'
name: Build
run: |
make bootstrap
make release如果 失败或需要自定义构建命令:
autobuildyaml
- language: c-cpp
build-mode: manual然后在 和 之间添加明确的构建步骤:
initanalyzeyaml
- if: matrix.build-mode == 'manual'
name: Build
run: |
make bootstrap
make releaseCore 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 bundle(包含 CLI 和预编译查询):
bash
undefinedDownload from https://github.com/github/codeql-action/releases
Download from https://github.com/github/codeql-action/releases
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 bundle,而不是单独下载的 CLI。bundle 可确保查询兼容性,并提供预编译查询以提升性能。Step 2: Create a CodeQL Database
第 2 步:创建 CodeQL 数据库
bash
undefinedbash
undefinedSingle language
Single language
codeql database create codeql-db
--language=javascript-typescript
--source-root=src
--language=javascript-typescript
--source-root=src
codeql database create codeql-db
--language=javascript-typescript
--source-root=src
--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
--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
--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.sarifCommon query suites: , , .
<language>-code-scanning.qls<language>-security-extended.qls<language>-security-and-quality.qlsbash
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.qlsStep 4: Upload Results to GitHub
第 4 步:将结果上传到 GitHub
bash
codeql github upload-results \
--repository=owner/repo \
--ref=refs/heads/main \
--commit=<commit-sha> \
--sarif=results.sarifRequires environment variable with permission.
GITHUB_TOKENsecurity-events: writebash
codeql github upload-results \
--repository=owner/repo \
--ref=refs/heads/main \
--commit=<commit-sha> \
--sarif=results.sarif需要设置 环境变量,并授予 权限。
GITHUB_TOKENsecurity-events: writeCLI Server Mode
CLI Server 模式
To avoid repeated JVM initialization when running multiple commands:
bash
codeql execute cli-serverFor 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,WarningNote - Security severity: ,
Critical,High,Medium(derived from CVSS scores; takes display precedence)Low
警报具有两个严重性维度:
- 标准严重性: 、
Error、WarningNote - 安全严重性: 、
Critical、High、Medium(根据 CVSS 分数推导;显示时优先采用)Low
Copilot Autofix
Copilot Autofix
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 会自动为 PR 中的 CodeQL 警报生成修复建议,无需 Copilot 订阅。提交前应仔细审查这些建议。
Alert Triage in PRs
PR 中的警报分诊
- Alerts appear as check annotations on changed lines
- Check fails by default for /
error/criticalseverity alertshigh - 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 - 配置合并保护 ruleset,以自定义失败阈值
- 关闭误报时填写书面理由,以保留审计记录
有关详细的警报管理指南,请搜索。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.qlyaml
- uses: github/codeql-action/init@v4
with:
packs: |
my-org/my-security-queries@1.0.0
codeql/javascript-queries:AlertSuppression.qlCreating Custom Query Packs
创建自定义查询包
Use the CodeQL CLI to create and publish packs:
bash
undefined使用 CodeQL CLI 创建并发布查询包:
bash
undefinedInitialize 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
undefinedcodeql pack publish
undefinedCodeQL Configuration File
CodeQL 配置文件
For advanced query and path configuration, create :
.github/codeql/codeql-config.ymlyaml
paths:
- apps/
- services/
paths-ignore:
- '**/test/**'
- node_modules/
queries:
- uses: security-extended
packs:
javascript-typescript:
- my-org/my-custom-queries要配置高级查询和路径,请创建 :
.github/codeql/codeql-config.ymlyaml
paths:
- apps/
- services/
paths-ignore:
- '**/test/**'
- node_modules/
queries:
- uses: security-extended
packs:
javascript-typescript:
- my-org/my-custom-queriesCode 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 and
--verbosity=progress++--logdir=codeql-logs
要启用详细诊断信息:
- GitHub Actions: 勾选“Enable debug logging”后重新运行工作流
- CodeQL CLI: 使用 和
--verbosity=progress++--logdir=codeql-logs
Troubleshooting
故障排查
Common Issues
常见问题
| Problem | Solution |
|---|---|
| Workflow not triggering | Verify |
| Add |
| Autobuild failure | Switch to |
| No source code seen | Verify |
| C# compiler failure | Check for |
| Fewer lines scanned than expected | Switch from |
| Kotlin in no-build mode | Disable and re-enable default setup to switch to |
| Cache miss every run | Verify |
| Out of disk/memory | Use larger runners; reduce analysis scope via |
| SARIF upload fails | Ensure token has |
| SARIF results exceed limits | Split across multiple uploads with different |
| Two CodeQL workflows | Disable default setup if using advanced setup, or remove old workflow file |
| Slow analysis | Enable dependency caching; use |
For comprehensive troubleshooting with detailed solutions, search.references/troubleshooting.md
| 问题 | 解决方案 |
|---|---|
| 工作流未触发 | 验证 |
出现 | 添加 |
| Autobuild 失败 | 切换到 |
| 未检测到源代码 | 验证 |
| C# 编译器失败 | 检查 |
| 扫描行数少于预期 | 从 |
| no-build 模式下的 Kotlin 问题 | 禁用并重新启用默认设置,以切换到 |
| 每次运行都未命中缓存 | 验证 |
| 磁盘空间或内存不足 | 使用更大的 runner;通过 |
| SARIF 上传失败 | 确保 token 具有 |
| SARIF 结果超出限制 | 使用不同的 |
| 存在两个 CodeQL 工作流 | 使用高级设置时禁用默认设置,或删除旧工作流文件 |
| 分析速度缓慢 | 启用依赖项缓存;使用 |
如需全面的故障排查和详细解决方案,请搜索。references/troubleshooting.md
Hardware Requirements (Self-Hosted Runners)
硬件要求(自托管 Runner)
| Codebase Size | RAM | CPU |
|---|---|---|
| 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 |
|---|---|---|
| 小型(<100K LOC) | 8 GB+ | 2 核 |
| 中型(100K–1M LOC) | 16 GB+ | 4–8 核 |
| 大型(>1M LOC) | 64 GB+ | 8 核 |
所有规模均需配备至少有 14 GB 可用磁盘空间的 SSD。
Action Versioning
Action 版本控制
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@v4For maximum security, pin to a full commit SHA instead of a version tag.
将 CodeQL actions 固定到特定主版本:
yaml
uses: github/codeql-action/init@v4 # Recommended
uses: github/codeql-action/autobuild@v4
uses: github/codeql-action/analyze@v4为了获得最高安全性,应固定到完整的 commit SHA,而不是版本标签。
Reference Files
参考文件
For detailed documentation, load the following reference files as needed:
- — Full workflow trigger, runner, and configuration options
references/workflow-configuration.md- Search patterns: ,
trigger,schedule,paths-ignore,db-location,model packs,alert severity,merge protection,concurrencyconfig file
- Search patterns:
- — Complete CodeQL CLI command reference
references/cli-commands.md- Search patterns: ,
database create,database analyze,upload-results,resolve packs,cli-server,installationCI integration
- Search patterns:
- — SARIF v2.1.0 object model, upload limits, and third-party support
references/sarif-output.md- Search patterns: ,
sarifLog,result,location,region,codeFlow,fingerprint,suppression,upload limits,third-party,precisionsecurity-severity
- Search patterns:
- — Build modes and autobuild behavior per language
references/compiled-languages.md- Search patterns: ,
C/C++,C#,Java,Go,Rust,Swift,autobuild,build-mode,hardwaredependency caching
- Search patterns:
- — Comprehensive error diagnosis and resolution
references/troubleshooting.md- 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 uploadSARIF limits
- Search patterns:
- — Alert severity, triage, Copilot Autofix, and dismissal
references/alert-management.md- Search patterns: ,
severity,security severity,CVSS,Copilot Autofix,dismiss,triage,PR alerts,data flow,merge protectionREST API
- Search patterns:
如需详细文档,请按需加载以下参考文件:
- ——完整的工作流触发器、runner 和配置选项
references/workflow-configuration.md- 搜索模式:、
trigger、schedule、paths-ignore、db-location、model packs、alert severity、merge protection、concurrencyconfig file
- 搜索模式:
- ——完整的 CodeQL CLI 命令参考
references/cli-commands.md- 搜索模式:、
database create、database analyze、upload-results、resolve packs、cli-server、installationCI integration
- 搜索模式:
- ——SARIF v2.1.0 对象模型、上传限制和第三方支持
references/sarif-output.md- 搜索模式:、
sarifLog、result、location、region、codeFlow、fingerprint、suppression、upload limits、third-party、precisionsecurity-severity
- 搜索模式:
- ——各语言的构建模式和 autobuild 行为
references/compiled-languages.md- 搜索模式:、
C/C++、C#、Java、Go、Rust、Swift、autobuild、build-mode、hardwaredependency 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 uploadSARIF limits
- 搜索模式:
- ——警报严重性、分诊、Copilot Autofix 和关闭警报
references/alert-management.md- 搜索模式:、
severity、security severity、CVSS、Copilot Autofix、dismiss、triage、PR alerts、data flow、merge protectionREST API
- 搜索模式: