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.
本技能提供了通过GitHub Actions工作流和独立CodeQL CLI配置与运行CodeQL代码扫描的流程指导。
When to Use This 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
当请求涉及以下内容时,使用本技能:
- 创建或自定义GitHub Actions工作流
codeql.yml - 选择代码扫描的默认设置与高级设置
- 配置CodeQL语言矩阵、构建模式或查询套件
- 本地运行CodeQL CLI(、
codeql database create、database analyze)github upload-results - 理解或解读CodeQL的SARIF输出
- 排查CodeQL分析失败问题(构建模式、编译型语言、运行器要求)
- 为多仓库(monorepo)设置CodeQL以实现按组件扫描
- 配置依赖缓存、自定义查询包或模型包
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.
- 默认设置 — 从仓库设置→高级安全→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- — 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- — 每次推送到指定分支时扫描;结果显示在安全选项卡中
push - — 扫描PR合并提交;结果以PR检查注释形式显示
pull_request - — 定期扫描默认分支(cron表达式必须存在于默认分支)
schedule - — 如果仓库使用合并队列,则添加此项
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
有关各语言自动构建行为和运行器要求的详细信息,请查阅。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
依赖缓存: 在操作中设置,以在多次运行之间缓存已恢复的依赖项。
initdependency-caching: true分析分类: 使用区分多仓库中的SARIF结果(例如,按语言、按组件)。
categoryStep 6: Monorepo Configuration
步骤6:多仓库配置
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对于包含多个组件的多仓库,使用参数分离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捆绑包(包含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捆绑包,而非独立CLI下载。捆绑包确保查询兼容性,并提供预编译查询以提升性能。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需要具有权限的环境变量。
security-events: writeGITHUB_TOKENCLI Server Mode
CLI服务器模式
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自动修复
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/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 - 配置合并保护规则集来自定义阈值
- 为误报添加文档化理由后关闭,以保留审计跟踪
有关告警管理的详细指南,请查阅。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: 重新运行工作流时勾选“启用调试日志”
- 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
| 问题 | 解决方案 |
|---|---|
| 工作流未触发 | 验证 |
| 添加 |
| 自动构建失败 | 切换到 |
| 未检测到源代码 | 验证 |
| C#编译器失败 | 检查 |
| 扫描行数少于预期 | 从 |
| Kotlin在无构建模式下异常 | 禁用并重新启用默认设置以切换到 |
| 每次运行都缓存未命中 | 验证 |
| 磁盘/内存不足 | 使用更大的运行器;通过 |
| SARIF上传失败 | 确保令牌具有 |
| SARIF结果超出限制 | 通过不同的 |
| 存在两个CodeQL工作流 | 如果使用高级设置,请禁用默认设置,或删除旧的工作流文件 |
| 分析速度慢 | 启用依赖缓存;使用 |
有关包含详细解决方案的全面故障排查指南,请查阅。references/troubleshooting.md
Hardware Requirements (Self-Hosted Runners)
硬件要求(自托管运行器)
| 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 |
|---|---|---|
| 小型(<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@v4For 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:
- — 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:
如需详细文档,根据需要加载以下参考文件:
- —完整的工作流触发器、运行器和配置选项
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
- 搜索关键词:
- —各语言的构建模式和自动构建行为
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自动修复和关闭
references/alert-management.md- 搜索关键词:、
severity、security severity、CVSS、Copilot Autofix、dismiss、triage、PR alerts、data flow、merge protectionREST API
- 搜索关键词: