About code scanning configuration
You can run code scanning on GitHub, using GitHub Actions, or from your continuous integration (CI) system. For more information, see 写入工作流 or Using code scanning with your existing CI system.
With advanced setup for code scanning, you can customize a code scanning workflow for granular control over your configuration. For more information, see Configuring advanced setup for code scanning.
CodeQL analysis is just one type of code scanning you can do in GitHub. GitHub Marketplace contains other code scanning workflows you can use. You can find a selection of these on the "Get started with code scanning" page, which you can access from the Security tab. The specific examples given in this article relate to the CodeQL 分析工作流程 file.
Editing a code scanning workflow
GitHub saves workflow files in the .github/workflows directory of your repository. You can find a workflow you have added by searching for its file name. For example, by default, the workflow file for CodeQL code scanning is called codeql-analysis.yml.
- In your repository, browse to the workflow file you want to edit.
- In the upper right corner of the file view, to open the workflow editor, click .
- After you have edited the file, click Start commit and complete the "Commit changes" form. You can choose to commit directly to the current branch, or create a new branch and start a pull request.
For more information about editing workflow files, see 写入工作流.
Configuring frequency
You can configure the CodeQL 分析工作流程 to scan code on a schedule or when specific events occur in a repository.
Scanning code when someone pushes a change, and whenever a pull request is created, prevents developers from introducing new vulnerabilities and errors into the code. Scanning code on a schedule informs you about the latest vulnerabilities and errors that GitHub, security researchers, and the community discover, even when developers aren't actively maintaining the repository.
Scanning on push
By default, the CodeQL 分析工作流程 uses the on:push event to trigger a code scan on every push to the default branch of the repository and any protected branches. For code scanning to be triggered on a specified branch, the workflow must exist in that branch. For more information, see GitHub Actions 的工作流语法.
If you scan on push, then the results appear in the Security tab for your repository. For more information, see 评估存储库的代码扫描警报.
Additionally, when an on:push scan returns results that can be mapped to an open pull request, these alerts will automatically appear on the pull request in the same places as other pull request alerts. The alerts are identified by comparing the existing analysis of the head of the branch to the analysis for the target branch. For more information on code scanning alerts in pull requests, see 鉴定拉取请求中的代码扫描警报.
Scanning pull requests
The default CodeQL 分析工作流程 uses the pull_request event to trigger a code scan on pull requests targeted against the default branch. If a pull request is from a private fork, the pull_request event will only be triggered if you've selected the "Run workflows from fork pull requests" option in the repository settings. For more information, see 管理存储库的 GitHub Actions 设置.
For more information about the pull_request event, see 触发工作流的事件.
If you scan pull requests, then the results appear as alerts in a pull request check. For more information, see 鉴定拉取请求中的代码扫描警报.
Using the pull_request trigger, configured to scan the pull request's merge commit rather than the head commit, will produce more efficient and accurate results than scanning the head of the branch on each push. However, if you use a CI/CD system that cannot be configured to trigger on pull requests, you can still use the on:push trigger and code scanning will map the results to open pull requests on the branch and add the alerts as annotations on the pull request. For more information, see Scanning on push.
注意
If your repository is configured with a merge queue, you need to include the merge_group event as an additional trigger for code scanning. This will ensure that pull requests are also scanned when they are added to a merge queue. For more information, see 管理合并队列.
Avoiding unnecessary scans of pull requests
You might want to avoid a code scan being triggered on specific pull requests targeted against the default branch, irrespective of which files have been changed. You can configure this by specifying on:pull_request:paths-ignore or on:pull_request:paths in the code scanning workflow. For example, if the only changes in a pull request are to files with the file extensions .md or .txt you can use the following paths-ignore array.
on:
push:
branches: [main, protected]
pull_request:
branches: [main]
paths-ignore:
- '**/*.md'
- '**/*.txt'
on:
push:
branches: [main, protected]
pull_request:
branches: [main]
paths-ignore:
- '**/*.md'
- '**/*.txt'
注意
on:pull_request:paths-ignore and on:pull_request:paths set conditions that determine whether the actions in the workflow will run on a pull request. They don't determine what files will be analyzed when the actions are run. When a pull request contains any files that are not matched by on:pull_request:paths-ignore or on:pull_request:paths, the workflow runs the actions and scans all of the files changed in the pull request, including those matched by on:pull_request:paths-ignore or on:pull_request:paths, unless the files have been excluded. For information on how to exclude files from analysis, see Specifying directories to scan.
For more information about using on:pull_request:paths-ignore and on:pull_request:paths to determine when a workflow will run for a pull request, see GitHub Actions 的工作流语法.
Scanning on a schedule
If you use the default CodeQL 分析工作流程, the workflow will scan the code in your repository once a week, in addition to the scans triggered by events. To adjust this schedule, edit the cron value for the on.schedule event in the workflow. For more information, see GitHub Actions 的工作流语法.
注意
仅当工作流文件存在于默认分支上时,此事件才会触发工作流运行。
Example
The following example shows a CodeQL 分析工作流程 for a particular repository that has a default branch called main and one protected branch called protected.
on:
push:
branches: [main, protected]
pull_request:
branches: [main]
schedule:
- cron: '20 14 * * 1'
on:
push:
branches: [main, protected]
pull_request:
branches: [main]
schedule:
- cron: '20 14 * * 1'
This workflow scans:
- Every push to the default branch and the protected branch
- Every pull request to the default branch
- The default branch every Monday at 14:20 UTC
Specifying an operating system
注意
-
Code scanning of Swift code uses macOS runners by default. GitHub-hosted macOS runners are more expensive than Linux and Windows runners, so you should consider only scanning the build step. For more information about configuring code scanning for Swift, see CodeQL code scanning for compiled languages. For more information about pricing for GitHub-hosted runners, see GitHub Actions 计费.
-
属于 Actions Runner Controller (ARC) 的运行器不支持 Swift 代码的 Code scanning,因为 ARC 运行器仅使用 Linux,且 Swift 需要 macOS 运行器。 但是,你可以混合使用 ARC 运行器和自托管 macOS 运行器。 有关详细信息,请参阅“Actions Runner Controller”。
If your code requires a specific operating system to compile, you can configure the operating system in your CodeQL 分析工作流程. Edit the value of jobs.analyze.runs-on to specify the operating system for the machine that runs your code scanning actions.
jobs:
analyze:
name: Analyze
runs-on: [ubuntu-latest]
jobs:
analyze:
name: Analyze
runs-on: [ubuntu-latest]
If you choose to use a self-hosted runner for code scanning, you can specify an operating system by using an appropriate label as the second element in a two-element array, after self-hosted.
jobs:
analyze:
name: Analyze
runs-on: [self-hosted, ubuntu-latest]
jobs:
analyze:
name: Analyze
runs-on: [self-hosted, ubuntu-latest]
CodeQL code scanning supports the latest versions of Ubuntu, Windows, and macOS. Typical values for this setting are therefore: ubuntu-latest, windows-latest, and macos-latest. For more information, see 选择作业的运行器 and 将标签与自托管运行程序结合使用.
If you use a self-hosted runner, you must ensure that Git is in the PATH variable. For more information, see 自托管运行程序 and 添加自托管的运行器.
For recommended specifications (RAM, CPU cores, and disk) for running CodeQL analysis on self-hosted machines, see 推荐用于运行 CodeQL 的硬件资源.
Specifying the location for CodeQL databases
In general, you do not need to worry about where the CodeQL 分析工作流程 places CodeQL databases since later steps will automatically find databases created by previous steps. However, if you are writing a custom workflow step that requires the CodeQL database to be in a specific disk location, for example to upload the database as a workflow artifact, you can specify that location using the db-location parameter under the init action.
- uses: github/codeql-action/init@v4
with:
db-location: '${{ github.runner_temp }}/my_location'
- uses: github/codeql-action/init@v4
with:
db-location: '${{ github.runner_temp }}/my_location'
The CodeQL 分析工作流程 will expect the path provided in db-location to be writable, and either not exist, or be an empty directory. When using this parameter in a job running on a self-hosted runner or using a Docker container, it's the responsibility of the user to ensure that the chosen directory is cleared between runs, or that the databases are removed once they are no longer needed. This is not necessary for jobs running on GitHub-hosted runners, which obtain a fresh instance and a clean filesystem each time they run. For more information, see GitHub 托管的运行程序.
If this parameter is not used, the CodeQL 分析工作流程 will create databases in a temporary location of its own choice. Currently the default value is ${{ github.runner_temp }}/codeql_databases.
Changing the languages that are analyzed
CodeQL code scanning supports code written in the following languages:
- C/C++
- C#
- Go
- Java/Kotlin
- JavaScript/TypeScript
- Python
- Ruby
- Rust
- 切换 * GitHub Actions工作流
注意
- 使用
java-kotlin分析用 Java 或/和 Kotlin 编写的代码。 - 使用
javascript-typescript分析用 JavaScript 和/或 TypeScript 编写的代码。
有关详细信息,请参阅 CodeQL 网站上的文档:“支持的语言和框架”。
CodeQL uses the following language identifiers:
| 语言 | Identifier | 可选替代标识符(如果有) |
|---|---|---|
| C/C++ | c-cpp |
`c` 或 `cpp` |
| C# | csharp |
| |
GitHub Actions 工作流程 | actions
|
| Go | go |
| Java/Kotlin | java-kotlin |
java 或 kotlin |
| JavaScript/TypeScript | javascript-typescript |
javascript 或 typescript |
| Python | python |
| Ruby | ruby |
| |
Rust | rust
|
| Swift | swift |
注意
If you specify one of the alternative identifiers, this is equivalent to using the standard language identifier. For example, specifying javascript instead of javascript-typescript will not exclude analysis of TypeScript code. Instead, you can use a custom configuration file to exclude files from analysis using the paths-ignore setting. For more information, see Using a custom configuration file and Specifying directories to scan.
These language identifiers can be used as arguments to the languages input of the init action. We recommend that only one language is provided as an argument:
- uses: github/codeql-action/init@v4
with:
languages: javascript-typescript
- uses: github/codeql-action/init@v4
with:
languages: javascript-typescript
The default CodeQL 分析工作流程 file created after configuring advanced setup for code scanning with CodeQL defines a matrix containing a property named language which lists the languages in your repository that will be analyzed. This matrix has been automatically pre-populated with supported languages detected in your repository. Using the language matrix allows CodeQL to run each language analysis in parallel and to customize analysis for each language. In an individual analysis, the name of the language from the matrix is provided to the init action as the argument for the languages input. We recommend that all workflows adopt this configuration. For more information about matrices, see 在工作流中运行作业的变体.
- uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
- uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
If your workflow uses the language matrix, then CodeQL will only analyze the languages in the matrix. To change the languages you want to analyze, edit the matrix configuration. You can remove a language to prevent it from being analyzed. There are several reasons you might want to prevent a language being analyzed. For example, the project might have dependencies in a different language to the main body of your code, and you might prefer not to see alerts for those dependencies. You can also add a language that was not present in the repository when code scanning was configured. For example, if the repository initially only contained JavaScript when code scanning was configured, and you later added Python code, you will need to add python to the matrix.
jobs:
analyze:
name: Analyze
...
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
- language: python
build-mode: none
jobs:
analyze:
name: Analyze
...
strategy:
fail-fast: false
matrix:
include:
- language: javascript-typescript
build-mode: none
- language: python
build-mode: none
For compiled languages, the matrix can also be used to configure which build mode should be used for analysis by changing the value of the build-mode property. For more information about build modes, see CodeQL code scanning for compiled languages.
If your workflow does not provide an argument to the languages input of the init action, then CodeQL is configured to run analyses sequentially. In this case, CodeQL automatically detects, and attempts to analyze, any supported languages in the repository. Depending on the size of the repository and the number of languages, this may take a long time. If analysis for one language fails in this mode, then the analysis for all languages fails. Therefore, we do not recommend this configuration.
注意
When analyzing languages sequentially, the default build-mode for every language will be used. Alternatively, if you provide an explicit autobuild step, then every language that supports the autobuild mode will use it while other languages use their default mode. If a more complex build-mode configuration than this is required, then you will need to configure a matrix.
Defining the alert severities that cause a check failure for a pull request
You can use rulesets to prevent pull requests from being merged when one of the following conditions is met:
- 所需工具发现了一个 code scanning 警报,其严重性是在规则集中定义的。
- 所需 code scanning 工具的分析仍在进行中。
- 未为存储库配置所需的 code scanning 工具。
For more information, see Set code scanning merge protection. For more general information about rulesets, see 关于规则集.
Configuring a category for the analysis
Use category to distinguish between multiple analyses for the same tool and commit, but performed on different languages or different parts of the code. The category you specify in your workflow will be included in the SARIF results file.
This parameter is particularly useful if you work with monorepos and have multiple SARIF files for different components of the monorepo.
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
with:
# Optional. Specify a category to distinguish between multiple analyses
# for the same tool and ref. If you don't use `category` in your workflow,
# GitHub will generate a default category name for you
category: "my_category"
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
with:
# Optional. Specify a category to distinguish between multiple analyses
# for the same tool and ref. If you don't use `category` in your workflow,
# GitHub will generate a default category name for you
category: "my_category"
If you don't specify a category parameter in your workflow, GitHub will generate a category name for you, based on the name of the workflow file triggering the action, the action name, and any matrix variables. For example:
- The
.github/workflows/codeql-analysis.ymlworkflow and theanalyzeaction will produce the category.github/workflows/codeql.yml:analyze. - The
.github/workflows/codeql-analysis.ymlworkflow, theanalyzeaction, and the{language: javascript-typescript, os: linux}matrix variables will produce the category.github/workflows/codeql-analysis.yml:analyze/language:javascript-typescript/os:linux.
The category value will appear as the <run>.automationDetails.id property in SARIF v2.1.0. For more information, see 对代码扫描的 SARIF 支持.
Your specified category will not overwrite the details of the runAutomationDetails object in the SARIF file, if included.
Extending CodeQL coverage with CodeQL model packs
If your codebase depends on a library or framework that is not recognized by the standard queries in CodeQL, you can extend the CodeQL coverage in your code scanning workflow by specifying published CodeQL model packs. For more information about creating your own model packs, see Creating and working with CodeQL packs.
注意
CodeQL 模型包目前包含在 公共预览版 中,可能会更改。 C/C++、C#、Java/Kotlin、Python、Ruby 和 Rust 分析支持模型包。
Visual Studio Code 的 CodeQL 扩展中的 CodeQL 支持对 C#、Java/Kotlin、Python 和 Ruby 的依赖项建模。
Using CodeQL model packs
To add one or more published CodeQL model packs, specify them inside the with: packs: entry within the uses: github/codeql-action/init@v4 section of the workflow. Within packs you specify one or more packages to use and, optionally, which version to download. Where you don't specify a version, the latest version is downloaded. If you want to use packages that are not publicly available, you need to set the GITHUB_TOKEN environment variable to a secret that has access to the packages. For more information, see 在工作流中使用 GITHUB_TOKEN 进行身份验证 and 在 GitHub Actions 中使用机密.
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
queries: security-extended
packs: my-company/my-java-queries@~7.8.9,my-repo/my-java-model-pack
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
queries: security-extended
packs: my-company/my-java-queries@~7.8.9,my-repo/my-java-model-pack
In this example, the default queries will be run for Java, as well as the queries from a version greater than or equal to 7.8.9 and less than 7.9.0 of the query pack my-company/my-java-queries. The dependencies modeled in the latest version of the model pack my-repo/my-java-model-pack will be available to both the default queries and those in my-company/my-java-queries.
Running additional queries
使用 CodeQL 扫描代码时,CodeQL 分析引擎将从代码生成数据库并对其运行查询。 CodeQL 分析使用默认的查询集,但除了默认查询外,您还可以指定更多的查询来运行。
提示
还可以指定要从分析中排除或是包含在分析中的查询。 这需要使用自定义配置文件。 有关详细信息,请参阅下面的“使用自定义配置文件”和“从分析中排除特定查询”。
如果它们是发布到 GitHub Container registry 的 CodeQL 包或存储在存储库中的 CodeQL 包的一部分,则可以运行额外的查询。 有关详细信息,请参阅“关于使用 CodeQL 进行代码扫描”。
可用于指定要运行的其他查询的选项有:
packs,可安装一个或多个 CodeQL 查询包并为这些包运行默认查询套件或查询。queries,可指定单个 .ql 文件、包含多个 .ql 文件的目录、.qls 查询套件定义文件或任意组合 。 有关查询套件定义的详细信息,请参阅“创建 CodeQL 查询套件”。
可以在同一工作流中同时使用 packs 和 queries。
不建议直接从 github/codeql 存储库引用查询套件,例如 github/codeql/cpp/ql/src@main。 此类查询必须重新编译,并且可能与 GitHub Actions 上当前活动的 CodeQL 版本不兼容,这可能会导致分析过程中出错。
Using query packs
To add one or more CodeQL query packs, add a with: packs: entry within the uses: github/codeql-action/init@v4 section of the workflow. Within packs you specify one or more packages to use and, optionally, which version to download. Where you don't specify a version, the latest version is downloaded. If you want to use packages that are not publicly available, you need to set the GITHUB_TOKEN environment variable to a secret that has access to the packages. For more information, see 在工作流中使用 GITHUB_TOKEN 进行身份验证 and 在 GitHub Actions 中使用机密.
注意
For workflows that generate CodeQL databases for multiple languages, you must instead specify the CodeQL query packs in a configuration file. For more information, see Specifying CodeQL query packs below.
In the example below, scope is the organization or personal account that published the package. When the workflow runs, the four CodeQL query packs are downloaded from GitHub and the default queries or query suite for each pack run:
- The latest version of
pack1is downloaded and all default queries are run. - Version 1.2.3 of
pack2is downloaded and all default queries are run. - The latest version of
pack3that is compatible with version 3.2.1 is downloaded and all queries are run. - Version 4.5.6 of
pack4is downloaded and only the queries found inpath/to/queriesare run.
- uses: github/codeql-action/init@v4
with:
# Comma-separated list of packs to download
packs: scope/pack1,scope/pack2@1.2.3,scope/pack3@~3.2.1,scope/pack4@4.5.6:path/to/queries
- uses: github/codeql-action/init@v4
with:
# Comma-separated list of packs to download
packs: scope/pack1,scope/pack2@1.2.3,scope/pack3@~3.2.1,scope/pack4@4.5.6:path/to/queries
注意
If you specify a particular version of a query pack to use, beware that the version you specify may eventually become too old to be used efficiently by the default CodeQL engine used by the CodeQL action. To ensure optimal performance, if you need to specify exact query pack versions, you should consider reviewing periodically whether the pinned version of the query pack needs to be moved forward.
For more information about pack compatibility, see Publishing and using CodeQL packs.
Downloading CodeQL packs from GitHub Enterprise Server
If your workflow uses packs that are published on a GitHub Enterprise Server installation, you need to tell your workflow where to find them. You can do this by using the registries input of the github/codeql-action/init@v4 action. This input accepts a list of url, packages, and token properties as shown below.
- uses: github/codeql-action/init@v4
with:
registries: |
# URL to the container registry, usually in this format
- url: https://containers.GHEHOSTNAME1/v2/
# List of package glob patterns to be found at this registry
packages:
- my-company/*
- my-company2/*
# Token, which should be stored as a secret
token: ${{ secrets.GHEHOSTNAME1_TOKEN }}
# URL to the default container registry
- url: https://ghcr.io/v2/
# Packages can also be a string
packages: "*/*"
token: ${{ secrets.GHCR_TOKEN }}
- uses: github/codeql-action/init@v4
with:
registries: |
# URL to the container registry, usually in this format
- url: https://containers.GHEHOSTNAME1/v2/
# List of package glob patterns to be found at this registry
packages:
- my-company/*
- my-company2/*
# Token, which should be stored as a secret
token: ${{ secrets.GHEHOSTNAME1_TOKEN }}
# URL to the default container registry
- url: https://ghcr.io/v2/
# Packages can also be a string
packages: "*/*"
token: ${{ secrets.GHCR_TOKEN }}
The package patterns in the registries list are examined in order, so you should generally place the most specific package patterns first. The values for token must be a personal access token (classic) generated by the GitHub instance you are downloading from with the read:packages permission.
Notice the | after the registries property name. This is important since GitHub Actions inputs can only accept strings. Using the | converts the subsequent text to a string, which is parsed later by the github/codeql-action/init@v4 action.
Using queries in QL packs
To add one or more queries, add a with: queries: entry within the uses: github/codeql-action/init@v4 section of the workflow. If the queries are in a private repository, use the external-repository-token parameter to specify a token that has access to checkout the private repository.
You can also specify query suites in the value of queries. Query suites are collections of queries, usually grouped by purpose or language.
- uses: github/codeql-action/init@v4
with:
# Comma-separated list of queries / packs / suites to run.
# This may include paths or a built in suite, for example:
# security-extended or security-and-quality.
queries: security-extended
# Optional. Provide a token to access queries stored in private repositories.
external-repository-token: ${{ secrets.ACCESS_TOKEN }}
- uses: github/codeql-action/init@v4
with:
# Comma-separated list of queries / packs / suites to run.
# This may include paths or a built in suite, for example:
# security-extended or security-and-quality.
queries: security-extended
# Optional. Provide a token to access queries stored in private repositories.
external-repository-token: ${{ secrets.ACCESS_TOKEN }}
以下查询套件内置于 CodeQL code scanning,可供使用。
| 查询套件 | 描述 |
|---|---|
security-extended | 来自默认套件的查询,以及较低严重性和精度查询 |
security-and-quality | 来自 security-extended 的查询,以及可维护性和可靠性查询。 |
有关详细信息,请参阅“CodeQL 查询套件”。
其中每个查询套件都包含该语言的内置 CodeQL 查询包中随附的不同查询子集。 查询套件是使用每个查询的元数据自动生成的。 有关详细信息,请参阅“CodeQL 查询的元数据”。
指定查询套件时,CodeQL 分析引擎将运行默认查询集和其他查询套件中定义的任何其他查询。
Working with custom configuration files
If you also use a configuration file for custom settings, any additional packs or queries specified in your workflow are used instead of those specified in the configuration file. If you want to run the combined set of additional packs or queries, prefix the value of packs or queries in the workflow with the + symbol. For more information, see Using a custom configuration file.
In the following example, the + symbol ensures that the specified additional packs and queries are used together with any specified in the referenced configuration file.
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
packs: +scope/pack1,scope/pack2@1.2.3,scope/pack3@4.5.6:path/to/queries
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
queries: +security-and-quality,octo-org/python-qlpack/show_ifs.ql@main
packs: +scope/pack1,scope/pack2@1.2.3,scope/pack3@4.5.6:path/to/queries
Using a custom configuration file
A custom configuration file is an alternative way to specify additional packs and queries to run. You can also use the file to disable the default queries, exclude or include specific queries, and to specify which directories to scan during analysis.
In the workflow file, use the config-file parameter of the init action to specify the path to the configuration file you want to use. This example loads the configuration file ./.github/codeql/codeql-config.yml.
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
- uses: github/codeql-action/init@v4
with:
config-file: ./.github/codeql/codeql-config.yml
配置文件可以位于正在分析的存储库中,也可以位于外部存储库中。 使用外部存储库可以在一个位置为多个存储库指定配置选项。 引用位于外部存储库中的配置文件时,可以使用 OWNER/REPOSITORY/FILENAME@BRANCH 语法。 例如, octo-org/shared/codeql-config.yml@main 。
If the configuration file is located in an external private repository, use the external-repository-token parameter of the init action to specify a token that has access to the private repository.
- uses: github/codeql-action/init@v4
with:
external-repository-token: ${{ secrets.ACCESS_TOKEN }}
- uses: github/codeql-action/init@v4
with:
external-repository-token: ${{ secrets.ACCESS_TOKEN }}
The settings in the configuration file are written in YAML format.
Specifying CodeQL query packs
You specify CodeQL query packs in an array. Note that the format is different from the format used by the workflow file.
packs: # Use the latest version of 'pack1' published by 'scope' - scope/pack1 # Use version 1.2.3 of 'pack2' - scope/pack2@1.2.3 # Use the latest version of 'pack3' compatible with 3.2.1 - scope/pack3@~3.2.1 # Use pack4 and restrict it to queries found in the 'path/to/queries' directory - scope/pack4:path/to/queries # Use pack5 and restrict it to the query 'path/to/single/query.ql' - scope/pack5:path/to/single/query.ql # Use pack6 and restrict it to the query suite 'path/to/suite.qls' - scope/pack6:path/to/suite.qls
packs:
# Use the latest version of 'pack1' published by 'scope'
- scope/pack1
# Use version 1.2.3 of 'pack2'
- scope/pack2@1.2.3
# Use the latest version of 'pack3' compatible with 3.2.1
- scope/pack3@~3.2.1
# Use pack4 and restrict it to queries found in the 'path/to/queries' directory
- scope/pack4:path/to/queries
# Use pack5 and restrict it to the query 'path/to/single/query.ql'
- scope/pack5:path/to/single/query.ql
# Use pack6 and restrict it to the query suite 'path/to/suite.qls'
- scope/pack6:path/to/suite.qls
The full format for specifying a query pack is scope/name[@version][:path]. Both version and path are optional. version is semver version range. If it is missing, the latest version is used. For more information about semver ranges, see the semver docs on npm.
If you have a workflow that generates more than one CodeQL database, you can specify any CodeQL query packs to run in a custom configuration file using a nested map of packs.
packs:
# Use these packs for JavaScript and TypeScript analysis
javascript:
- scope/js-pack1
- scope/js-pack2
# Use these packs for Java and Kotlin analysis
java:
- scope/java-pack1
- scope/java-pack2@v1.0.0
packs:
# Use these packs for JavaScript and TypeScript analysis
javascript:
- scope/js-pack1
- scope/js-pack2
# Use these packs for Java and Kotlin analysis
java:
- scope/java-pack1
- scope/java-pack2@v1.0.0
Extending CodeQL coverage with threat models
注意
风险模型功能目前为 公共预览版,可能随时更改。 在 公共预览版 期间,风险模型仅支持 Java/Kotlin 和 C# 分析。
The default threat model includes remote sources of untrusted data. You can extend the CodeQL threat model to include local sources of untrusted data (for example: command-line arguments, environment variables, file systems, and databases) by specifying threat-models: local in a custom configuration file. If you extend the threat model, the default threat model will also be used.
Specifying additional queries
You specify additional queries in a queries array. Each element of the array contains a uses parameter with a value that identifies a single query file, a directory containing query files, or a query suite definition file.
queries: - uses: ./my-basic-queries/example-query.ql - uses: ./my-advanced-queries - uses: ./query-suites/my-security-queries.qls
queries:
- uses: ./my-basic-queries/example-query.ql
- uses: ./my-advanced-queries
- uses: ./query-suites/my-security-queries.qls
Optionally, you can give each array element a name, as shown in the example configuration files below. For more information about additional queries, see Running additional queries above.
Disabling the default queries
If you only want to run custom queries, you can disable the default security queries by using disable-default-queries: true.
Excluding specific queries from analysis
You can add exclude and include filters to your custom configuration file, to specify the queries you want to exclude or include in the analysis.
This is useful if you want to exclude, for example:
- Specific queries from the default suites (
security,security-extendedandsecurity-and-quality). - Specific queries whose results do not interest you.
- All the queries that generate warnings and recommendations.
You can use exclude filters similar to those in the configuration file below to exclude queries that you want to remove from the default analysis. In the example of configuration file below, both the js/redundant-assignment and the js/useless-assignment-to-local queries are excluded from analysis.
query-filters:
- exclude:
id: js/redundant-assignment
- exclude:
id: js/useless-assignment-to-local
query-filters:
- exclude:
id: js/redundant-assignment
- exclude:
id: js/useless-assignment-to-local
To find the id of a query, you can click the alert in the list of alerts in the Security tab. This opens the alert details page. The Rule ID field contains the query id. For more information about the alert details page, see 关于代码扫描警报.
提示
- The order of the filters is important. The first filter instruction that appears after the instructions about the queries and query packs determines whether the queries are included or excluded by default.
- Subsequent instructions are executed in order and the instructions that appear later in the file take precedence over the earlier instructions.
You can find another example illustrating the use of these filters in the Example configuration files section.
For more information about using exclude and include filters in your custom configuration file, see Creating CodeQL query suites. For information on the query metadata you can filter on, see Metadata for CodeQL queries.
Specifying directories to scan
When codebases are analyzed without building the code, you can restrict code scanning to files in specific directories by adding a paths array to the configuration file. You can also exclude the files in specific directories from analysis by adding a paths-ignore array. You can use this option when you run the CodeQL actions on an interpreted language (Python, Ruby, and JavaScript/TypeScript) or when you analyze a compiled language without building the code (currently supported for C/C++、C#, Java 和 Rust).
paths: - src paths-ignore: - src/node_modules - '**/*.test.js'
paths:
- src
paths-ignore:
- src/node_modules
- '**/*.test.js'
注意
- The
pathsandpaths-ignorekeywords, used in the context of the code scanning configuration file, should not be confused with the same keywords when used foron.<push|pull_request>.pathsin a workflow. When they are used to modifyon.<push|pull_request>in a workflow, they determine whether the actions will be run when someone modifies code in the specified directories. For more information, see GitHub Actions 的工作流语法. - The filter pattern characters
?,+,[,], and!are not supported and will be matched literally. **characters can only be at the start or end of a line, or surrounded by slashes, and you can't mix**and other characters. For example,foo/**,**/foo, andfoo/**/barare all allowed syntax, but**fooisn't. However you can use single stars along with other characters, as shown in the example. You'll need to quote anything that contains a*character.
For analysis where code is built, if you want to limit code scanning to specific directories in your project, you must specify appropriate build steps in the workflow. The commands you need to use to exclude a directory from the build will depend on your build system. For more information, see CodeQL code scanning for compiled languages.
You can quickly analyze small portions of a monorepo when you modify code in specific directories. You'll need to both exclude directories in your build steps and use the paths-ignore and paths keywords for on.<push|pull_request> in your workflow.
Example configuration files
当扫描代码时,此配置文件将 security-and-quality 查询套件添加到 CodeQL 运行的查询列表中。 有关可供使用的查询套件的详细信息,请参阅“运行其他查询”。
name: "My CodeQL config"
queries:
- uses: security-and-quality
以下配置文件禁用默认查询,并指定一组要运行的自定义查询。 它还配置 CodeQL 以扫描 src 目录(相对于根目录)中的文件,除了 src/node_modules 目录和名称以 .test.js 结尾的文件 。 因此,src/node_modules 中的文件和名称以 .test.js 结尾的文件被排除在分析之外 。
name: "My CodeQL config"
disable-default-queries: true
queries:
- name: Use an in-repository CodeQL pack (run queries in the my-queries directory)
uses: ./my-queries
- name: Use an external JavaScript CodeQL pack (run queries from an external repo)
uses: octo-org/javascript-codeql-pack@main
- name: Use an external query (run a single query from an external CodeQL pack)
uses: octo-org/python-codeql-pack/show_ifs.ql@main
- name: Use a query suite file (run queries from a query suite in this repo)
uses: ./codeql-packs/complex-python-codeql-pack/rootAndBar.qls
paths:
- src
paths-ignore:
- src/node_modules
- '**/*.test.js'
以下配置文件仅运行生成严重性错误警报的查询。 该配置首先选择所有默认查询、./my-queries 中的所有查询以及 codeql/java-queries 中的默认套件,然后排除生成警告或建议的所有查询。
queries:
- name: Use an in-repository CodeQL query pack (run queries in the my-queries directory)
uses: ./my-queries
packs:
- codeql/java-queries
query-filters:
- exclude:
problem.severity:
- warning
- recommendation
Specifying configuration details using the config input
If you'd prefer to specify additional configuration details in the workflow file, you can use the config input of the init command of the CodeQL action. The value of this input must be a YAML string that follows the configuration file format documented at Using a custom configuration file above.
Example configuration
This step in a GitHub Actions workflow file uses a config input to disable the default queries, add the security-extended query suite, and exclude queries that are tagged with cwe-020.
- uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
config: |
disable-default-queries: true
threat-models: local
queries:
- uses: security-extended
query-filters:
- exclude:
tags: /cwe-020/
You can use the same approach to specify any valid configuration options in the workflow file.
提示
You can share one configuration across multiple repositories using GitHub Actions variables. One benefit of this approach is that you can update the configuration in a single place without editing the workflow file.
In the following example, vars.CODEQL_CONF is a GitHub Actions variable. Its value can be the contents of any valid configuration file. For more information, see 在变量中存储信息.
- uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
config: ${{ vars.CODEQL_CONF }}
Configuring code scanning for compiled languages
For compiled languages, you can decide how the CodeQL action creates a CodeQL database for analysis. For information about the build options available, see CodeQL code scanning for compiled languages.
Uploading code scanning data to GitHub
GitHub can display code analysis data generated externally by a third-party tool. You can upload code analysis data with the upload-sarif action. For more information, see Uploading a SARIF file to GitHub.