Compare commits

..
Author SHA1 Message Date
Eli Reisman 455d760c6a regen dist 2024-07-04 00:06:17 +00:00
Eli Reisman 46a56b892b short-term fix: hard truncate core.summary if it is over 1024k size limit 2024-07-04 00:05:52 +00:00
41 changed files with 4982 additions and 108436 deletions
@@ -1,7 +0,0 @@
## Purpose
_Describe the purpose of this pull request_
## Related Issues
_What issues does this PR close or relate to?_
-11
View File
@@ -12,14 +12,3 @@ updates:
ignore: ignore:
- dependency-name: '@types/node' - dependency-name: '@types/node'
update-types: ['version-update:semver-major'] update-types: ['version-update:semver-major']
groups:
minor-updates:
update-types:
- 'minor'
- 'patch'
exclude-patterns:
- '*spdx*'
# Pull out any updates to spdx definitions and parsing as a priority PR
spdx-licenses:
patterns:
- '*spdx*'
+54
View File
@@ -0,0 +1,54 @@
# `dist/index.js` is a special file in Actions.
# When you reference an action with `uses:` in a workflow,
# `index.js` is the code that will run.
# For our project, we generate this file through a build process from other source files.
# We need to make sure the checked-in `index.js` actually matches what we expect it to be.
name: Check dist/
on:
push:
branches:
- main
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
workflow_dispatch:
jobs:
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set Node.js 20.x
uses: actions/setup-node@v4
with:
node-version: 20.x
cache: npm
- name: Install dependencies
run: npm ci
- name: Rebuild the dist/ directory
run: |
npm run build
npm run package
- name: Compare the expected and actual dist/ directories
run: |
if [ "$(git diff --ignore-space-at-eol dist/ | wc -l)" -gt "0" ]; then
echo "Detected uncommitted changes after build. See status below:"
git diff
exit 1
fi
id: diff
# If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v4
if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with:
name: dist
path: dist/
+2 -5
View File
@@ -10,15 +10,12 @@ on:
paths-ignore: paths-ignore:
- '**.md' - '**.md'
permissions:
contents: read
jobs: jobs:
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v6 - uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 20
cache: npm cache: npm
@@ -31,7 +28,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v6 - uses: actions/setup-node@v4
with: with:
node-version: 20 node-version: 20
cache: npm cache: npm
+3 -3
View File
@@ -20,7 +20,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: [ 'javascript-typescript', 'actions', 'ruby' ] language: [ 'javascript-typescript' ]
steps: steps:
- name: Checkout repository - name: Checkout repository
@@ -28,7 +28,7 @@ jobs:
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v4 uses: github/codeql-action/init@v3
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
@@ -43,6 +43,6 @@ jobs:
- dist/sourcemap-register.js - dist/sourcemap-register.js
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4 uses: github/codeql-action/analyze@v3
with: with:
category: "/language:${{matrix.language}}" category: "/language:${{matrix.language}}"
+1 -2
View File
@@ -1,5 +1,4 @@
name: 'Dependency Review' name: 'Dependency Review'
on: [pull_request] on: [pull_request]
permissions: permissions:
@@ -12,4 +11,4 @@ jobs:
- name: 'Checkout Repository' - name: 'Checkout Repository'
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Dependency Review - name: Dependency Review
uses: ./ uses: actions/dependency-review-action@main
+2 -5
View File
@@ -12,15 +12,12 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v10.1.0 - uses: actions/stale@v9.0.0
name: Clean up stale PRs and Issues name: Clean up stale PRs and Issues
with: with:
stale-pr-message: "👋 This pull request has been marked as stale because it has been open with no activity for 180 days. You can: comment on the PR or remove the stale label to hold stalebot off for a while, add the `Keep` label to hold stale off permanently, or do nothing. If you do nothing, this pull request will be closed eventually by the stalebot. Please see CONTRIBUTING.md for more policy details." stale-pr-message: "👋 This pull request has been marked as stale because it has been open with no activity. You can: comment on the issue or remove the stale label to hold stale off for a while, add the `Keep` label to hold stale off permanently, or do nothing. If you do nothing, this pull request will be closed eventually by the stale bot. Please see CONTRIBUTING.md for more policy details."
stale-pr-label: "Stale" stale-pr-label: "Stale"
close-pr-message: "👋 This pull request has been closed by stalebot because it has been open with no activity for over 180 days. Please see CONTRIBUTING.md for more policy details."
stale-issue-label: "Stale" stale-issue-label: "Stale"
stale-issue-message: "👋 This issue has been marked as stale because it has been open with no activity for 180 days. You can: comment on the issue or remove the stale label to hold stalebot off for a while, add the `Keep` label to hold stale off permanently, or do nothing. If you do nothing, this issue will be closed eventually by the stalebot. Please see CONTRIBUTING.md for more policy details."
close-issue-message: "👋 This issue has been closed by stalebot because it has been open with no activity for over 180 days. Please see CONTRIBUTING.md for more policy details."
exempt-pr-labels: "Keep" # a "Keep" label will keep the PR from being closed as stale exempt-pr-labels: "Keep" # a "Keep" label will keep the PR from being closed as stale
exempt-issue-labels: "Keep" # a "Keep" label will keep the issue from being closed as stale exempt-issue-labels: "Keep" # a "Keep" label will keep the issue from being closed as stale
days-before-pr-stale: 180 # when the PR is considered stale days-before-pr-stale: 180 # when the PR is considered stale
+33 -30
View File
@@ -16,7 +16,7 @@ If you've encountered a problem, please let us know by [submitting an issue](htt
## Enhancements and feature requests ## Enhancements and feature requests
If you've got an idea for a new feature or a significant change to the code or its dependencies, please submit as [an issue](https://github.com/actions/dependency-review-action/issues/new) so that the community can see it, and we can discuss it there. We may not be able to respond to every single issue, but will make a best effort! If you've got an idea for a new feature, please submit as [an issue](https://github.com/actions/dependency-review-action/issues/new) so that the community can see it, and we can discuss it there. We may not be able to respond to every single issue, but will make a best effort!
If you'd like to make a contribution yourself, we ask that before significant effort is put into code changes, that we have agreement that the change aligns with our strategy for the action. Since this is a verified Action owned by GitHub we want to make sure that contributions are high quality, and that they maintain consistency with the rest of the action's behavior. If you'd like to make a contribution yourself, we ask that before significant effort is put into code changes, that we have agreement that the change aligns with our strategy for the action. Since this is a verified Action owned by GitHub we want to make sure that contributions are high quality, and that they maintain consistency with the rest of the action's behavior.
@@ -25,7 +25,7 @@ If you'd like to make a contribution yourself, we ask that before significant ef
## Stalebot ## Stalebot
We have begun using a [Stalebot action](https://github.com/actions/stale) to help keep the Issues and Pull requests backlogs tidy. You can see [the configuration](.github/workflows/stalebot.yml). If you'd like to keep an issue open after getting a stalebot warning, simply comment on it and it'll reset the clock. We have begun using a [Stalebot action](https://github.com/actions/stale) to help keep the Issues and Pull requests backlogs tidy. You can see the configuration [here](.github/workflows/stalebot.yml). If you'd like to keep an issue open after getting a stalebot warning, simply comment on it and it'll reset the clock.
## Development lifecycle ## Development lifecycle
@@ -35,11 +35,11 @@ Ready to contribute to `dependency-review-action`? Here is some information to h
This action makes an authenticated query to the [Dependency Review API](https://docs.github.com/en/rest/dependency-graph/dependency-review) endpoint (`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`) to find out the set of added and removed dependencies for each manifest. This action makes an authenticated query to the [Dependency Review API](https://docs.github.com/en/rest/dependency-graph/dependency-review) endpoint (`GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}`) to find out the set of added and removed dependencies for each manifest.
The action then evaluates the differences between the pushes based on the rules defined in the action configuration, and summarizes the differences and any violations of the rules you have defined as a comment in the pull request that triggered it and the action outputs. The action then evaluates the differences between the pushes based on the the rules defined in the action configuration, and summarizes the differences and any violations of the rules you have defined as a comment in the pull request that triggered it and the action outputs.
### Local Development ### Local Development
Before you begin, you need to have [Node.js](https://nodejs.org/en/) installed, minimum version 20. Before you begin, you need to have [Node.js](https://nodejs.org/en/) installed, minimum version 18.
#### Bootstrapping the project #### Bootstrapping the project
@@ -50,9 +50,10 @@ Before you begin, you need to have [Node.js](https://nodejs.org/en/) installed,
#### Manually testing for vulnerabilities #### Manually testing for vulnerabilities
We have a script to scan a given PR for vulnerabilities, which will help you test your local changes. Make sure to [grab a Personal Access Token (PAT)](https://github.com/settings/tokens) before proceeding (you'll need `repo` permissions for private repos): We have a script to scan a given PR for vulnerabilities, this will
help you test your local changes. Make sure to [grab a Personal Access Token (PAT)](https://github.com/settings/tokens) before proceeding (you'll need `repo` permissions for private repos):
<img width="480" alt="Screen to create a PAT with a note of `dr-token`, 30 day duration (expiring Jun 11, 2022), with `repo` scopes selected" src="https://user-images.githubusercontent.com/2161/168026161-16788a0a-b6c8-428e-bb6a-83ea2a403070.png"> <img width="480" alt="Screenshot 2022-05-12 at 10 22 21" src="https://user-images.githubusercontent.com/2161/168026161-16788a0a-b6c8-428e-bb6a-83ea2a403070.png">
The syntax of the script is: The syntax of the script is:
@@ -80,15 +81,14 @@ $ GITHUB_TOKEN=<token> ./scripts/scan_pr --config-file my_custom_config.yml <pr_
npm run test npm run test
``` ```
_Note_: We don't have a very comprehensive test suite, so any contributions to the existing tests are welcome! _Note_: We don't a very comprehensive test suite, so any contributions to the existing tests are welcome!
### Submitting a pull request ### Submitting a pull request
1. Create a new branch: `git checkout -b my-branch-name` 1. Create a new branch: `git checkout -b my-branch-name`
2. Make your change, add tests, and make sure the tests still pass 2. Make your change, add tests, and make sure the tests still pass
3. Push to your fork and [submit a pull request][pr] 3. Make sure to build and package before pushing: `npm run build && npm run package`
4. Push to your fork and [submit a pull request][pr]
(note: we don't recommend including changes to the `dist` directory in your pull request, because changes there have an increased likelihood of conflicts.)
Here are a few things you can do that will increase the likelihood of your pull request being accepted: Here are a few things you can do that will increase the likelihood of your pull request being accepted:
@@ -105,38 +105,41 @@ Here are a few things you can do that will increase the likelihood of your pull
_Note: these instructions are for maintainers_ _Note: these instructions are for maintainers_
- Create a local branch based on the `main` of the upstream repo. 1. Update the version number in [package.json](https://github.com/actions/dependency-review-action/blob/main/package.json) and run `npm i` to update the lockfile.
- Update the version number in [package.json](https://github.com/actions/dependency-review-action/blob/main/package.json) and run `npm i` to update the lockfile. 1. Go to [Draft a new
- Update the dist files by running `npm run build` and `npm run package` release](https://github.com/actions/dependency-review-action/releases/new)
- Go to [Draft a new release](https://github.com/actions/dependency-review-action/releases/new) in the Releases page. in the Releases page.
- Make sure that the `Publish this Action to the GitHub Marketplace` checkbox is enabled 1. Make sure that the `Publish this Action to the GitHub Marketplace`
checkbox is enabled
<img width="481" alt="Screen showing Release Action with Publish this Action to the GitHub Marketplace checked" src="https://user-images.githubusercontent.com/2161/173822484-4b60d8b4-c674-4bff-b5ff-b0c4a3650ab7.png"> <img width="481" alt="Screenshot 2022-06-15 at 12 08 19" src="https://user-images.githubusercontent.com/2161/173822484-4b60d8b4-c674-4bff-b5ff-b0c4a3650ab7.png">
- Click "Choose a tag" and then "Create new tag", where the tag name 3. Click "Choose a tag" and then "Create new tag", where the tag name
will be your version prefixed by a `v` (e.g. `v1.2.3`). will be your version prefixed by a `v` (e.g. `v1.2.3`).
- Use a version number for the release title (e.g. "1.2.3"). 4. Use a version number for the release title (e.g. "1.2.3").
<img width="700" alt="Create an action release in categories Security + Dependency management from branch main creating tag v2.0.0 on publish" src="https://user-images.githubusercontent.com/2161/173822548-33ab3432-d679-4dc1-adf8-b50fdaf47de3.png"> <img width="700" alt="Screenshot 2022-06-15 at 12 08 36" src="https://user-images.githubusercontent.com/2161/173822548-33ab3432-d679-4dc1-adf8-b50fdaf47de3.png">
- Add your release notes. If this is a major version make sure to include details about any breaking changes in the new version. 5. Add your release notes. If this is a major version make sure to
- Click "Publish Release". include a small description of the biggest changes in the new version.
6. Click "Publish Release".
You now have a tag and release using the semver version you used above. The last remaining thing to do is to update the major version branch to match the current release. This allows users to adopt a major version number (e.g. `v4`) in their workflows while automatically getting all the minor/patch updates. You now have a tag and release using the semver version you used
above. The last remaining thing to do is to move the dynamic version
identifier to match the current SHA. This allows users to adopt a
major version number (e.g. `v1`) in their workflows while
automatically getting all the
minor/patch updates.
As of v4.8.3, we use a **branch** (not a force-pushed tag) for the major version pointer. This is important because force-pushing tags breaks GitHub's auto-generated release changelog links (see [#1035](https://github.com/actions/dependency-review-action/issues/1035)) and violates git's (unenforced) expectation that tags are immutable. To do this just checkout `main`, force-create a new annotated tag, and push it:
To update the major version branch:
``` ```
git checkout main git tag -fa v4 -m "Updating v4 to 4.0.1"
git pull origin main git push origin v4 --force
git branch -f v4 HEAD
git push origin v4
``` ```
</details> </details>
## Resources ## Resources
- [Creating JavaScript GitHub actions](https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action) - [Creating JavaScript GitHub actions](https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action)
+11 -35
View File
@@ -1,18 +1,8 @@
# dependency-review-action # dependency-review-action
- [dependency-review-action](#dependency-review-action)
- [Overview](#overview) - [Overview](#overview)
- [Viewing the results](#viewing-the-results)
- [Installation](#installation) - [Installation](#installation)
- [Installation (standard)](#installation-standard)
- [Installation (GitHub Enterprise Server)](#installation-github-enterprise-server)
- [Configuration](#configuration) - [Configuration](#configuration)
- [Configuration options](#configuration-options)
- [Configuration methods](#configuration-methods)
- [Option 1: Using inline configuration](#option-1-using-inline-configuration)
- [Option 2: Using an external configuration file](#option-2-using-an-external-configuration-file)
- [`OTHER` in license strings](#other-in-license-strings)
- [Further information](#further-information)
- [Using dependency review action to block a pull request from being merged](#using-dependency-review-action-to-block-a-pull-request-from-being-merged) - [Using dependency review action to block a pull request from being merged](#using-dependency-review-action-to-block-a-pull-request-from-being-merged)
- [Outputs](#outputs) - [Outputs](#outputs)
- [Getting help](#getting-help) - [Getting help](#getting-help)
@@ -25,7 +15,6 @@ The dependency review action scans your pull requests for dependency changes, an
The action is supported by an [API endpoint](https://docs.github.com/en/rest/dependency-graph/dependency-review?apiVersion=2022-11-28) that diffs the dependencies between any two revisions on your default branch. The action is supported by an [API endpoint](https://docs.github.com/en/rest/dependency-graph/dependency-review?apiVersion=2022-11-28) that diffs the dependencies between any two revisions on your default branch.
The action is available for: The action is available for:
- Public repositories - Public repositories
- Private repositories with a [GitHub Advanced Security](https://docs.github.com/en/enterprise-cloud@latest/get-started/learning-about-github/about-github-advanced-security) license. - Private repositories with a [GitHub Advanced Security](https://docs.github.com/en/enterprise-cloud@latest/get-started/learning-about-github/about-github-advanced-security) license.
@@ -97,8 +86,7 @@ You can install the action on repositories on GitHub Enterprise Server.
- name: 'Dependency Review' - name: 'Dependency Review'
uses: actions/dependency-review-action@v4 uses: actions/dependency-review-action@v4
``` ```
5. In the workflow file, replace the `runs-on` value with the label of any of your runners. (The default value is `self-hosted`.)
4. In the workflow file, replace the `runs-on` value with the label of any of your runners. (The default value is `self-hosted`.)
## Configuration ## Configuration
@@ -112,17 +100,17 @@ There are various configuration options you can use to specify settings for the
All configuration options are optional. All configuration options are optional.
| Option | Usage | Possible values | Default value | | Option | Usage | Possible values | Default value |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------- | | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------- |
| `fail-on-severity` | Defines the threshold for the level of severity. The action will fail on any pull requests that introduce vulnerabilities of the specified severity level or higher. | `low`, `moderate`, `high`, `critical` | `low` | | `fail-on-severity` | Defines the threshold for the level of severity. The action will fail on any pull requests that introduce vulnerabilities of the specified severity level or higher. | `low`, `moderate`, `high`, `critical` | `low` |
| `allow-licenses`\* | Contains a list of allowed licenses. The action will fail on pull requests that introduce dependencies with licenses that do not match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none | | `allow-licenses`\* | Contains a list of allowed licenses. The action will fail on pull requests that introduce dependencies with licenses that do not match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `deny-licenses`\* | ⚠️ This option is deprecated for possible removal in the next major release. See [Deprecate the deny-licenses option #938](https://github.com/actions/dependency-review-action/issues/938) for more information. <br> Contains a list of prohibited licenses. The action will fail on pull requests that introduce dependencies with licenses that match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none | | `deny-licenses`\* | Contains a list of prohibited licenses. The action will fail on pull requests that introduce dependencies with licenses that match the list. | Any [SPDX-compliant identifier(s)](https://spdx.org/licenses/) | none |
| `fail-on-scopes` | Contains a list of strings of the build environments you want to support. The action will fail on pull requests that introduce vulnerabilities in the scopes that match the list. | `runtime`, `development`, `unknown` | `runtime` | | `fail-on-scopes` | Contains a list of strings of the build environments you want to support. The action will fail on pull requests that introduce vulnerabilities in the scopes that match the list. | `runtime`, `development`, `unknown` | `runtime` |
| `allow-ghsas` | Contains a list of GitHub Advisory Database IDs that can be skipped during detection. | Any GHSAs from the [GitHub Advisory Database](https://github.com/advisories) | none | | `allow-ghsas` | Contains a list of GitHub Advisory Database IDs that can be skipped during detection. | Any GHSAs from the [GitHub Advisory Database](https://github.com/advisories) | none |
| `license-check` | Enable or disable the license check performed by the action. | `true`, `false` | `true` | | `license-check` | Enable or disable the license check performed by the action. | `true`, `false` | `true` |
| `vulnerability-check` | Enable or disable the vulnerability check performed by the action. | `true`, `false` | `true` | | `vulnerability-check` | Enable or disable the vulnerability check performed by the action. | `true`, `false` | `true` |
| `allow-dependencies-licenses`\* | Contains a list of packages that will be excluded from license checks. | Any package(s) in [purl](https://github.com/package-url/purl-spec) format | none | | `allow-dependencies-licenses`\* | Contains a list of packages that will be excluded from license checks. | Any package(s) in [purl](https://github.com/package-url/purl-spec) format | none |
| `base-ref`/`head-ref` | Provide custom git references for the git base/head when performing the comparison check. This is only used for event types other than `pull_request` and `pull_request_target`. | Any valid git ref(s) in your project | none | | `base-ref`/`head-ref` | Provide custom git references for the git base/head when performing the comparison check. This is only used for event types other than `pull_request` and `pull_request_target`. | Any valid git ref(s) in your project | none |
| `comment-summary-in-pr` | Enable or disable reporting the review summary as a comment in the pull request. If enabled, you must give the workflow or job the `pull-requests: write` permission. With each execution, a new comment will overwrite the existing one. | `always`, `on-failure`, `never` | `never` | | `comment-summary-in-pr` | Enable or disable reporting the review summary as a comment in the pull request. If enabled, you must give the workflow or job the `pull-requests: write` permission. | `always`, `on-failure`, `never` | `never` |
| `deny-packages` | Any number of packages to block in a PR. This option will match on the exact version provided. If no version is provided, the option will treat the specified package as a wildcard and deny all versions. | Package(s) in [purl](https://github.com/package-url/purl-spec) format | empty | | `deny-packages` | Any number of packages to block in a PR. This option will match on the exact version provided. If no version is provided, the option will treat the specified package as a wildcard and deny all versions. | Package(s) in [purl](https://github.com/package-url/purl-spec) format | empty |
| `deny-groups` | Any number of groups (namespaces) to block in a PR. | Namespace(s) in [purl](https://github.com/package-url/purl-spec) format (no package name, no version number) | empty | | `deny-groups` | Any number of groups (namespaces) to block in a PR. | Namespace(s) in [purl](https://github.com/package-url/purl-spec) format (no package name, no version number) | empty |
| `retry-on-snapshot-warnings`\* | Enable or disable retrying the action every 10 seconds while waiting for dependency submission actions to complete. | `true`, `false` | `false` | | `retry-on-snapshot-warnings`\* | Enable or disable retrying the action every 10 seconds while waiting for dependency submission actions to complete. | `true`, `false` | `false` |
@@ -132,7 +120,6 @@ All configuration options are optional.
| `warn-on-openssf-scorecard-level` | When `show-openssf-scorecard-levels` is set to `true`, this option lets you configure the threshold for when a score is considered too low and gets a :warning: warning in the CI. | Any positive integer | 3 | | `warn-on-openssf-scorecard-level` | When `show-openssf-scorecard-levels` is set to `true`, this option lets you configure the threshold for when a score is considered too low and gets a :warning: warning in the CI. | Any positive integer | 3 |
> [!NOTE] > [!NOTE]
>
> - \* Not supported for use with GitHub Enterprise Server. (Checking for licenses is not supported on GitHub Enterprise Server because the API does not return license information.) > - \* Not supported for use with GitHub Enterprise Server. (Checking for licenses is not supported on GitHub Enterprise Server because the API does not return license information.)
> - \+ When `warn-only` is set to `true`, all vulnerabilities, independently of the severity, will be reported as warnings and the action will not fail. > - \+ When `warn-only` is set to `true`, all vulnerabilities, independently of the severity, will be reported as warnings and the action will not fail.
> - The `allow-licenses` and `deny-licenses` options are mutually exclusive; an error will be raised if you provide both. > - The `allow-licenses` and `deny-licenses` options are mutually exclusive; an error will be raised if you provide both.
@@ -141,7 +128,6 @@ All configuration options are optional.
### Configuration methods ### Configuration methods
To specify settings for the dependency review action, you can choose from two options: To specify settings for the dependency review action, you can choose from two options:
- [Option 1: Inline the configuration options]() in your workflow file. - [Option 1: Inline the configuration options]() in your workflow file.
- [Option 2: Reference an external configuration file]() in your workflow file. - [Option 2: Reference an external configuration file]() in your workflow file.
@@ -150,7 +136,6 @@ To specify settings for the dependency review action, you can choose from two op
You can pass configuration options to the dependency review action using your workflow file. You can pass configuration options to the dependency review action using your workflow file.
1. In the same YAML workflow file you created during installation, use the `with:` key to specify your chosen settings: 1. In the same YAML workflow file you created during installation, use the `with:` key to specify your chosen settings:
```yaml ```yaml
name: 'Dependency Review' name: 'Dependency Review'
on: [pull_request] on: [pull_request]
@@ -169,7 +154,6 @@ You can pass configuration options to the dependency review action using your wo
# Use comma-separated names to pass list arguments: # Use comma-separated names to pass list arguments:
deny-licenses: LGPL-2.0, BSD-2-Clause deny-licenses: LGPL-2.0, BSD-2-Clause
allow-dependencies-licenses: "pkg:npm/@myorg/mypackage, pkg:npm/packagename, pkg:githubactions/owner/[email protected]"
``` ```
#### Option 2: Using an external configuration file #### Option 2: Using an external configuration file
@@ -194,11 +178,9 @@ You can use an external configuration file to specify settings for this action.
with: with:
config-file: './.github/dependency-review-config.yml' config-file: './.github/dependency-review-config.yml'
``` ```
| Option | Usage | Possible values | | Option | Usage | Possible values |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | |--------------------- | ----------- | ----------------------------- |
| `config-file` | A path to a file in the current repository or an external repository. Use this syntax for external files: `OWNER/REPOSITORY/FILENAME@BRANCH` | **Local file**: `./.github/dependency-review-config.yml` <br> **External repo**: `github/octorepo/dependency-review-config.yml@main` | | `config-file` | A path to a file in the current repository or an external repository. Use this syntax for external files: `OWNER/REPOSITORY/FILENAME@BRANCH` | **Local file**: `./.github/dependency-review-config.yml` <br> **External repo**: `github/octorepo/dependency-review-config.yml@main` |
2. Optionally, if the file resides in a private external repository, and for all GitHub Enterprise Server repositories, use `external-repo-token` to specify a token for fetching the file. 2. Optionally, if the file resides in a private external repository, and for all GitHub Enterprise Server repositories, use `external-repo-token` to specify a token for fetching the file.
```yaml ```yaml
@@ -210,26 +192,20 @@ You can use an external configuration file to specify settings for this action.
``` ```
| Option | Usage | Possible values | | Option | Usage | Possible values |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | |--------------------- | ----------- | ----------------------------- |
| `external-repo-token` | Specifies a token for fetching the configuration file. It is required if the file resides in a private external repository and for all GitHub Enterprise Server repositories. Create a token in [developer settings](https://github.com/settings/tokens). | Any token with `read` permissions to the repository hosting the config file. | | `external-repo-token` | Specifies a token for fetching the configuration file. It is required if the file resides in a private external repository and for all GitHub Enterprise Server repositories. Create a token in [developer settings](https://github.com/settings/tokens). | Any token with `read` permissions to the repository hosting the config file. |
3. Create the configuration file in the path you specified for `config-file`. 3. Create the configuration file in the path you specified for `config-file`.
4. In the configuration file, specify your chosen settings. 4. In the configuration file, specify your chosen settings.
```yaml ```yaml
fail-on-severity: 'critical' fail_on_severity: 'critical'
allow-licenses: allow_licenses:
- 'GPL-3.0' - 'GPL-3.0'
- 'BSD-3-Clause' - 'BSD-3-Clause'
- 'MIT' - 'MIT'
``` ```
> [!NOTE]
#### `OTHER` in license strings > For external configuration files, the option names use underscores instead of dashes.
> Example: `fail_on_severity`
License data comes from [ClearlyDefined](https://clearlydefined.io) and you may sometimes see licenses displayed with the string `OTHER` in them. ClearlyDefined [defines OTHER](https://docs.clearlydefined.io/docs/curation/curation-guidelines) as:
> This indicates that a human confirmed that there is license information in the file but that the license is not an SPDX-identified license.
`OTHER` is not a valid [SPDX license identifier](https://spdx.org/licenses/), so we convert `OTHER` in a license string into `LicenseRef-clearlydefined-OTHER`, which _is_ valid in SPDX. If you want to add that to the deny or allow list, be sure to add `LicenseRef-clearlydefined-OTHER` to this list, because that is what we'll actually be comparing.
#### Further information #### Further information
+16 -79
View File
@@ -1,8 +1,13 @@
import {expect, test, beforeEach} from '@jest/globals' import {expect, test, beforeEach} from '@jest/globals'
import {readConfig} from '../src/config' import {readConfig} from '../src/config'
import {getRefs} from '../src/git-refs' import {getRefs} from '../src/git-refs'
import * as Utils from '../src/utils'
import {setInput, clearInputs} from './test-helpers' import {setInput, clearInputs} from './test-helpers'
beforeAll(() => {
jest.spyOn(Utils, 'isSPDXValid').mockReturnValue(true)
})
beforeEach(() => { beforeEach(() => {
clearInputs() clearInputs()
}) })
@@ -14,11 +19,11 @@ test('it defaults to low severity', async () => {
test('it reads custom configs', async () => { test('it reads custom configs', async () => {
setInput('fail-on-severity', 'critical') setInput('fail-on-severity', 'critical')
setInput('allow-licenses', 'ISC, GPL-2.0') setInput('allow-licenses', ' BSD, GPL 2')
const config = await readConfig() const config = await readConfig()
expect(config.fail_on_severity).toEqual('critical') expect(config.fail_on_severity).toEqual('critical')
expect(config.allow_licenses).toEqual(['ISC', 'GPL-2.0']) expect(config.allow_licenses).toEqual(['BSD', 'GPL 2'])
}) })
test('it defaults to false for warn-only', async () => { test('it defaults to false for warn-only', async () => {
@@ -35,7 +40,7 @@ test('it defaults to empty allow/deny lists ', async () => {
test('it raises an error if both an allow and denylist are specified', async () => { test('it raises an error if both an allow and denylist are specified', async () => {
setInput('allow-licenses', 'MIT') setInput('allow-licenses', 'MIT')
setInput('deny-licenses', 'BSD-3-Clause') setInput('deny-licenses', 'BSD')
await expect(readConfig()).rejects.toThrow( await expect(readConfig()).rejects.toThrow(
'You cannot specify both allow-licenses and deny-licenses' 'You cannot specify both allow-licenses and deny-licenses'
@@ -123,78 +128,6 @@ test('it raises an error when no refs are provided and the event is not a pull r
).toThrow() ).toThrow()
}) })
const pullRequestLikeEvents = ['pull_request', 'pull_request_target']
test.each(pullRequestLikeEvents)(
'it uses the given refs even when the event is %s',
async eventName => {
setInput('base-ref', 'a-custom-base-ref')
setInput('head-ref', 'a-custom-head-ref')
const refs = getRefs(await readConfig(), {
payload: {
pull_request: {
number: 42,
base: {sha: 'pr-base-ref'},
head: {sha: 'pr-head-ref'}
}
},
eventName
})
expect(refs.base).toEqual('a-custom-base-ref')
expect(refs.head).toEqual('a-custom-head-ref')
}
)
test.each(pullRequestLikeEvents)(
'it uses the event refs when the event is %s and no refs are provided in config',
async eventName => {
const refs = getRefs(await readConfig(), {
payload: {
pull_request: {
number: 42,
base: {sha: 'pr-base-ref'},
head: {sha: 'pr-head-ref'}
}
},
eventName
})
expect(refs.base).toEqual('pr-base-ref')
expect(refs.head).toEqual('pr-head-ref')
}
)
test('it uses the given refs even when the event is merge_group', async () => {
setInput('base-ref', 'a-custom-base-ref')
setInput('head-ref', 'a-custom-head-ref')
const refs = getRefs(await readConfig(), {
payload: {
merge_group: {
base_sha: 'pr-base-ref',
head_sha: 'pr-head-ref'
}
},
eventName: 'merge_group'
})
expect(refs.base).toEqual('a-custom-base-ref')
expect(refs.head).toEqual('a-custom-head-ref')
})
test('it uses the event refs when the event is merge_group and no refs are provided in config', async () => {
const refs = getRefs(await readConfig(), {
payload: {
merge_group: {
base_sha: 'pr-base-ref',
head_sha: 'pr-head-ref'
}
},
eventName: 'merge_group'
})
expect(refs.base).toEqual('pr-base-ref')
expect(refs.head).toEqual('pr-head-ref')
})
test('it defaults to runtime scope', async () => { test('it defaults to runtime scope', async () => {
const config = await readConfig() const config = await readConfig()
expect(config.fail_on_scopes).toEqual(['runtime']) expect(config.fail_on_scopes).toEqual(['runtime'])
@@ -271,17 +204,21 @@ test('it is not possible to disable both checks', async () => {
}) })
describe('licenses that are not valid SPDX licenses', () => { describe('licenses that are not valid SPDX licenses', () => {
beforeAll(() => {
jest.spyOn(Utils, 'isSPDXValid').mockReturnValue(false)
})
test('it raises an error for invalid licenses in allow-licenses', async () => { test('it raises an error for invalid licenses in allow-licenses', async () => {
setInput('allow-licenses', ' BSD-YOLO, GPL-2.0') setInput('allow-licenses', ' BSD, GPL 2')
await expect(readConfig()).rejects.toThrow( await expect(readConfig()).rejects.toThrow(
'Invalid license(s) in allow-licenses: BSD-YOLO' 'Invalid license(s) in allow-licenses: BSD,GPL 2'
) )
}) })
test('it raises an error for invalid licenses in deny-licenses', async () => { test('it raises an error for invalid licenses in deny-licenses', async () => {
setInput('deny-licenses', ' GPL-2.0, BSD-YOLO, Apache-2.0, ToIll') setInput('deny-licenses', ' BSD, GPL 2')
await expect(readConfig()).rejects.toThrow( await expect(readConfig()).rejects.toThrow(
'Invalid license(s) in deny-licenses: BSD-YOLO, ToIll' 'Invalid license(s) in deny-licenses: BSD,GPL 2'
) )
}) })
}) })
+5 -59
View File
@@ -33,6 +33,11 @@ jest.mock('octokit', () => {
beforeEach(async () => { beforeEach(async () => {
jest.resetModules() jest.resetModules()
jest.doMock('spdx-satisfies', () => {
// mock spdx-satisfies return value
// true for BSD, false for all others
return jest.fn((license: string, _: string): boolean => license === 'BSD')
})
npmChange = createTestChange({ecosystem: 'npm'}) npmChange = createTestChange({ecosystem: 'npm'})
rubyChange = createTestChange({ecosystem: 'rubygems'}) rubyChange = createTestChange({ecosystem: 'rubygems'})
@@ -134,62 +139,3 @@ test('allows packages not defined in the deny packages and groups list', async (
expect(deniedChanges.length).toEqual(0) expect(deniedChanges.length).toEqual(0)
}) })
test('deny packages does not prevent removal of denied packages', async () => {
const changes: Changes = [
createTestChange({
change_type: 'added',
name: 'deny-by-name-and-version',
version: '1.0.0',
ecosystem: 'npm'
}),
createTestChange({
change_type: 'removed',
name: 'pass-by-name-and-version',
version: '1.0.0',
ecosystem: 'npm'
}),
createTestChange({
change_type: 'added',
name: 'deny-by-name',
version: '1.0.0',
ecosystem: 'npm'
}),
createTestChange({
change_type: 'removed',
name: 'pass-by-name',
version: '1.0.0',
ecosystem: 'npm'
}),
createTestChange({
change_type: 'added',
package_url: 'pkg:npm/org.test.deny.by.namespace/[email protected]',
ecosystem: 'npm'
}),
createTestChange({
change_type: 'removed',
package_url: 'pkg:npm/org.test.pass.by.namespace/[email protected]',
ecosystem: 'npm'
})
]
const deniedPackages = createTestPURLs([
'pkg:npm/org.test.deny.by/[email protected]',
'pkg:npm/org.test.pass.by/[email protected]',
'pkg:npm/org.test.deny.by/deny-by-name',
'pkg:npm/org.test.pass.by/pass-by-name'
])
const deniedGroups = createTestPURLs([
'pkg:npm/org.test.deny.by.namespace/',
'pkg:npm/org.test.pass.by.namespace/'
])
const deniedChanges = await getDeniedChanges(
changes,
deniedPackages,
deniedGroups
)
expect(deniedChanges.length).toEqual(3)
expect(deniedChanges[0]).toBe(changes[0])
expect(deniedChanges[1]).toBe(changes[2])
expect(deniedChanges[2]).toBe(changes[4])
})
+6 -2
View File
@@ -1,6 +1,6 @@
import {expect, test, beforeEach} from '@jest/globals' import {expect, test, beforeEach} from '@jest/globals'
import {readConfig} from '../src/config' import {readConfig} from '../src/config'
import * as spdx from '../src/spdx' import * as Utils from '../src/utils'
import {setInput, clearInputs} from './test-helpers' import {setInput, clearInputs} from './test-helpers'
const externalConfig = `fail_on_severity: 'high' const externalConfig = `fail_on_severity: 'high'
@@ -25,6 +25,10 @@ jest.mock('octokit', () => {
} }
}) })
beforeAll(() => {
jest.spyOn(Utils, 'isSPDXValid').mockReturnValue(true)
})
beforeEach(() => { beforeEach(() => {
clearInputs() clearInputs()
}) })
@@ -34,7 +38,7 @@ test('it reads an external config file', async () => {
const config = await readConfig() const config = await readConfig()
expect(config.fail_on_severity).toEqual('critical') expect(config.fail_on_severity).toEqual('critical')
expect(config.allow_licenses).toEqual(['BSD-3-Clause', 'GPL-2.0']) expect(config.allow_licenses).toEqual(['BSD', 'GPL 2'])
}) })
test('raises an error when the config file was not found', async () => { test('raises an error when the config file was not found', async () => {
+2 -2
View File
@@ -1,4 +1,4 @@
fail_on_severity: critical fail_on_severity: critical
allow_licenses: allow_licenses:
- 'BSD-3-Clause' - 'BSD'
- 'GPL-2.0' - 'GPL 2'
+30 -128
View File
@@ -1,6 +1,7 @@
import {expect, jest, test} from '@jest/globals' import {expect, jest, test} from '@jest/globals'
import {Change, Changes} from '../src/schemas' import {Change, Changes} from '../src/schemas'
import {getInvalidLicenseChanges} from '../src/licenses'
let getInvalidLicenseChanges: Function
const npmChange: Change = { const npmChange: Change = {
manifest: 'package.json', manifest: 'package.json',
@@ -29,7 +30,7 @@ const rubyChange: Change = {
name: 'actionsomething', name: 'actionsomething',
version: '3.2.0', version: '3.2.0',
package_url: 'pkg:gem/[email protected]', package_url: 'pkg:gem/[email protected]',
license: 'BSD-3-Clause', license: 'BSD',
source_repository_url: 'github.com/some-repo', source_repository_url: 'github.com/some-repo',
scope: 'runtime', scope: 'runtime',
vulnerabilities: [ vulnerabilities: [
@@ -74,46 +75,6 @@ const pipChange: Change = {
] ]
} }
const complexLicenseChange: Change = {
change_type: 'added',
manifest: 'requirements.txt',
ecosystem: 'pip',
name: 'package-1',
version: '1.1.1',
package_url: 'pkg:pypi/[email protected]',
license: 'MIT AND Apache-2.0',
source_repository_url: 'github.com/some-repo',
scope: 'runtime',
vulnerabilities: [
{
severity: 'moderate',
advisory_ghsa_id: 'second-random_string',
advisory_summary: 'not so dangerous',
advisory_url: 'github.com/future-funk'
},
{
severity: 'low',
advisory_ghsa_id: 'third-random_string',
advisory_summary: 'dont page me',
advisory_url: 'github.com/future-funk'
}
]
}
const unlicensedChange: Change = {
change_type: 'added',
manifest: '.github/workflows/ci.yml',
ecosystem: 'actions',
name: 'foo-org/actions-repo/.github/workflows/some-action.yml',
version: '1.1.1',
package_url:
'pkg:githubactions/foo-org/actions-repo/.github/workflows/[email protected]',
license: null,
source_repository_url: 'github.com/some-repo',
scope: 'development',
vulnerabilities: []
}
jest.mock('@actions/core') jest.mock('@actions/core')
const mockOctokit = { const mockOctokit = {
@@ -139,67 +100,40 @@ jest.mock('octokit', () => {
beforeEach(async () => { beforeEach(async () => {
jest.resetModules() jest.resetModules()
jest.doMock('spdx-satisfies', () => {
// mock spdx-satisfies return value
// true for BSD, false for all others
return jest.fn((license: string, _: string): boolean => license === 'BSD')
})
// eslint-disable-next-line @typescript-eslint/no-require-imports
;({getInvalidLicenseChanges} = require('../src/licenses'))
}) })
test('it adds license outside the allow list to forbidden changes', async () => { test('it adds license outside the allow list to forbidden changes', async () => {
const changes: Changes = [ const changes: Changes = [npmChange, rubyChange]
npmChange, // MIT license
rubyChange // BSD license
]
const {forbidden} = await getInvalidLicenseChanges(changes, { const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['BSD-3-Clause'] allow: ['BSD']
}) })
expect(forbidden[0]).toBe(npmChange) expect(forbidden[0]).toBe(npmChange)
expect(forbidden.length).toEqual(1) expect(forbidden.length).toEqual(1)
}) })
test('it adds license inside the deny list to forbidden changes', async () => { test('it adds license inside the deny list to forbidden changes', async () => {
const changes: Changes = [ const changes: Changes = [npmChange, rubyChange]
npmChange, // MIT license
rubyChange // BSD license
]
const {forbidden} = await getInvalidLicenseChanges(changes, { const {forbidden} = await getInvalidLicenseChanges(changes, {
deny: ['BSD-3-Clause'] deny: ['BSD']
}) })
expect(forbidden[0]).toBe(rubyChange) expect(forbidden[0]).toBe(rubyChange)
expect(forbidden.length).toEqual(1) expect(forbidden.length).toEqual(1)
}) })
test('it handles allowed complex licenses', async () => {
const changes: Changes = [
complexLicenseChange // MIT AND Apache-2.0 license
]
const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['MIT', 'Apache-2.0']
})
expect(forbidden.length).toEqual(0)
})
test('it handles complex licenses not all on the allow list', async () => {
const changes: Changes = [
complexLicenseChange // MIT AND Apache-2.0 license
]
const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['MIT']
})
expect(forbidden.length).toEqual(1)
})
test('it does not add license outside the allow list to forbidden changes if it is in removed changes', async () => { test('it does not add license outside the allow list to forbidden changes if it is in removed changes', async () => {
const changes: Changes = [ const changes: Changes = [
{...npmChange, change_type: 'removed'}, {...npmChange, change_type: 'removed'},
{...rubyChange, change_type: 'removed'} {...rubyChange, change_type: 'removed'}
] ]
const {forbidden} = await getInvalidLicenseChanges(changes, { const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['BSD-3-Clause'] allow: ['BSD']
}) })
expect(forbidden).toStrictEqual([]) expect(forbidden).toStrictEqual([])
}) })
@@ -210,7 +144,7 @@ test('it does not add license inside the deny list to forbidden changes if it is
{...rubyChange, change_type: 'removed'} {...rubyChange, change_type: 'removed'}
] ]
const {forbidden} = await getInvalidLicenseChanges(changes, { const {forbidden} = await getInvalidLicenseChanges(changes, {
deny: ['BSD-3-Clause'] deny: ['BSD']
}) })
expect(forbidden).toStrictEqual([]) expect(forbidden).toStrictEqual([])
}) })
@@ -222,18 +156,23 @@ test('it adds license outside the allow list to forbidden changes if it is in bo
{...rubyChange, change_type: 'removed'} {...rubyChange, change_type: 'removed'}
] ]
const {forbidden} = await getInvalidLicenseChanges(changes, { const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['BSD-3-Clause'] allow: ['BSD']
}) })
expect(forbidden).toStrictEqual([npmChange]) expect(forbidden).toStrictEqual([npmChange])
}) })
test('it adds all licenses to unresolved if it is unable to determine the validity', async () => { test('it adds all licenses to unresolved if it is unable to determine the validity', async () => {
const changes: Changes = [ jest.resetModules() // reset module set in before
{...npmChange, license: 'Foo'}, jest.doMock('spdx-satisfies', () => {
{...rubyChange, license: 'Bar'} return jest.fn((_first: string, _second: string) => {
] throw new Error('Some Error')
})
})
// eslint-disable-next-line @typescript-eslint/no-require-imports
;({getInvalidLicenseChanges} = require('../src/licenses'))
const changes: Changes = [npmChange, rubyChange]
const invalidLicenses = await getInvalidLicenseChanges(changes, { const invalidLicenses = await getInvalidLicenseChanges(changes, {
allow: ['Apache-2.0'] allow: ['BSD']
}) })
expect(invalidLicenses.forbidden.length).toEqual(0) expect(invalidLicenses.forbidden.length).toEqual(0)
expect(invalidLicenses.unlicensed.length).toEqual(0) expect(invalidLicenses.unlicensed.length).toEqual(0)
@@ -243,7 +182,7 @@ test('it adds all licenses to unresolved if it is unable to determine the validi
test('it does not filter out changes that are on the exclusions list', async () => { test('it does not filter out changes that are on the exclusions list', async () => {
const changes: Changes = [pipChange, npmChange, rubyChange] const changes: Changes = [pipChange, npmChange, rubyChange]
const licensesConfig = { const licensesConfig = {
allow: ['BSD-3-Clause'], allow: ['BSD'],
licenseExclusions: ['pkg:pypi/[email protected]', 'pkg:npm/[email protected]'] licenseExclusions: ['pkg:pypi/[email protected]', 'pkg:npm/[email protected]']
} }
const invalidLicenses = await getInvalidLicenseChanges( const invalidLicenses = await getInvalidLicenseChanges(
@@ -259,7 +198,7 @@ test('it does not fail when the packages dont have a valid PURL', async () => {
const changes: Changes = [emptyPurlChange, npmChange, rubyChange] const changes: Changes = [emptyPurlChange, npmChange, rubyChange]
const licensesConfig = { const licensesConfig = {
allow: ['BSD-3-Clause'], allow: ['BSD'],
licenseExclusions: ['pkg:pypi/[email protected]', 'pkg:npm/[email protected]'] licenseExclusions: ['pkg:pypi/[email protected]', 'pkg:npm/[email protected]']
} }
@@ -273,36 +212,21 @@ test('it does not fail when the packages dont have a valid PURL', async () => {
test('it does filters out changes if they are not on the exclusions list', async () => { test('it does filters out changes if they are not on the exclusions list', async () => {
const changes: Changes = [pipChange, npmChange, rubyChange] const changes: Changes = [pipChange, npmChange, rubyChange]
const licensesConfig = { const licensesConfig = {
allow: ['BSD-3-Clause'], allow: ['BSD'],
licenseExclusions: [ licenseExclusions: [
'pkg:pypi/[email protected]', 'pkg:pypi/[email protected]',
'pkg:npm/[email protected]' 'pkg:npm/[email protected]'
] ]
} }
const invalidLicenses = await getInvalidLicenseChanges( const invalidLicenses = await getInvalidLicenseChanges(
changes, changes,
licensesConfig licensesConfig
) )
expect(invalidLicenses.forbidden.length).toEqual(2) expect(invalidLicenses.forbidden.length).toEqual(2)
expect(invalidLicenses.forbidden[0]).toBe(pipChange) expect(invalidLicenses.forbidden[0]).toBe(pipChange)
expect(invalidLicenses.forbidden[1]).toBe(npmChange) expect(invalidLicenses.forbidden[1]).toBe(npmChange)
}) })
test('it does not fail if there is a license expression in the allow list', async () => {
const changes: Changes = [
{...npmChange, license: 'MIT AND Apache-2.0'},
{...rubyChange, license: 'BSD-3-Clause'}
]
const {forbidden} = await getInvalidLicenseChanges(changes, {
allow: ['BSD-3-Clause', 'MIT AND Apache-2.0', 'MIT', 'Apache-2.0']
})
expect(forbidden.length).toEqual(0)
})
describe('GH License API fallback', () => { describe('GH License API fallback', () => {
test('it calls licenses endpoint if atleast one of the changes has null license and valid source_repository_url', async () => { test('it calls licenses endpoint if atleast one of the changes has null license and valid source_repository_url', async () => {
const nullLicenseChange = { const nullLicenseChange = {
@@ -340,26 +264,4 @@ describe('GH License API fallback', () => {
expect(mockOctokit.rest.licenses.getForRepo).not.toHaveBeenCalled() expect(mockOctokit.rest.licenses.getForRepo).not.toHaveBeenCalled()
expect(unlicensed.length).toEqual(0) expect(unlicensed.length).toEqual(0)
}) })
test('it does not call licenses API if the package is excluded', async () => {
const {unlicensed} = await getInvalidLicenseChanges([unlicensedChange], {
licenseExclusions: [
'pkg:githubactions/foo-org/actions-repo/.github/workflows/some-action.yml'
]
})
expect(mockOctokit.rest.licenses.getForRepo).not.toHaveBeenCalled()
expect(unlicensed.length).toEqual(0)
})
test('it checks namespaces when doing exclusions', async () => {
const {unlicensed} = await getInvalidLicenseChanges([unlicensedChange], {
licenseExclusions: [
'pkg:githubactions/bar-org/actions-repo/.github/workflows/some-action.yml'
]
})
expect(mockOctokit.rest.licenses.getForRepo).not.toHaveBeenCalled()
expect(unlicensed.length).toEqual(1)
})
}) })
-164
View File
@@ -1,164 +0,0 @@
import {
afterEach,
beforeEach,
describe,
expect,
jest,
test
} from '@jest/globals'
import * as fs from 'fs'
import * as core from '@actions/core'
import {DefaultArtifactClient} from '@actions/artifact'
import type {SpyInstance} from 'jest-mock'
import {handleLargeSummary} from '../src/main'
jest.mock('ansi-styles', () => ({
__esModule: true,
default: {
color: {
red: {open: '', close: ''},
yellow: {open: '', close: ''},
grey: {open: '', close: ''},
green: {open: '', close: ''}
},
bold: {open: '', close: ''}
}
}))
jest.mock('../src/dependency-graph', () => ({}))
jest.mock('@actions/core', () => {
const summary = {
addRaw: jest.fn().mockReturnThis(),
addHeading: jest.fn().mockReturnThis(),
addTable: jest.fn().mockReturnThis(),
addSeparator: jest.fn().mockReturnThis(),
addImage: jest.fn().mockReturnThis(),
addList: jest.fn().mockReturnThis(),
addBreak: jest.fn().mockReturnThis(),
addLink: jest.fn().mockReturnThis(),
addDetails: jest.fn().mockReturnThis(),
addSection: jest.fn().mockReturnThis(),
addCodeBlock: jest.fn().mockReturnThis(),
addFields: jest.fn().mockReturnThis(),
addEol: jest.fn().mockReturnThis(),
write: jest.fn(async () => undefined),
emptyBuffer: jest.fn(),
stringify: jest.fn(() => '')
}
return {
__esModule: true,
getInput: jest.fn((name: string) =>
name === 'repo-token' ? 'gh_test_token' : ''
),
setOutput: jest.fn(),
setFailed: jest.fn(),
warning: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
startGroup: jest.fn(),
endGroup: jest.fn(),
group: jest.fn(async (_name: string, fn: () => Promise<unknown>) => fn()),
summary
}
})
jest.mock('@actions/artifact', () => ({
DefaultArtifactClient: jest.fn()
}))
const ORIGINAL_ENV = {...process.env}
type ArtifactClientInstance = {
uploadArtifact: jest.Mock
}
const DefaultArtifactClientMock = DefaultArtifactClient as unknown as jest.Mock
const createArtifactClient = (): ArtifactClientInstance => ({
uploadArtifact: jest.fn(async () => undefined)
})
describe('handleLargeSummary', () => {
let writeFileSpy: SpyInstance<typeof fs.promises.writeFile>
beforeEach(() => {
process.env = {...ORIGINAL_ENV}
writeFileSpy = jest
.spyOn(fs.promises, 'writeFile')
.mockImplementation(async () => undefined)
DefaultArtifactClientMock.mockClear()
DefaultArtifactClientMock.mockImplementation(() => createArtifactClient())
})
afterEach(() => {
writeFileSpy.mockRestore()
jest.clearAllMocks()
process.env = {...ORIGINAL_ENV}
})
test('returns original summary when under size threshold', async () => {
const summaryContent = 'short summary'
const result = await handleLargeSummary(summaryContent)
expect(result).toBe(summaryContent)
expect(writeFileSpy).not.toHaveBeenCalled()
expect(DefaultArtifactClientMock).not.toHaveBeenCalled()
})
test('uploads artifact and returns minimal summary when summary is too large', async () => {
process.env.GITHUB_SERVER_URL = 'https://github.com'
process.env.GITHUB_REPOSITORY = 'owner/repo'
process.env.GITHUB_RUN_ID = '12345'
const largeSummary = 'a'.repeat(1024 * 1024 + 1)
const result = await handleLargeSummary(largeSummary)
expect(writeFileSpy).toHaveBeenCalledTimes(1)
expect(writeFileSpy).toHaveBeenCalledWith('summary.md', largeSummary)
expect(DefaultArtifactClientMock).toHaveBeenCalledTimes(1)
const artifactInstance = DefaultArtifactClientMock.mock.results[0]
?.value as ArtifactClientInstance
expect(artifactInstance.uploadArtifact).toHaveBeenCalledWith(
'dependency-review-summary',
['summary.md'],
'.',
{retentionDays: 1}
)
expect(result).toContain('# Dependency Review Summary')
expect(result).toContain('dependency-review-summary')
expect(result).toContain('actions/runs/12345')
})
test('returns truncated summary and replaces buffer when artifact upload fails', async () => {
const warningMock = core.warning as jest.Mock
const emptyBufferMock = core.summary.emptyBuffer as jest.Mock
const addRawMock = core.summary.addRaw as jest.Mock
warningMock.mockClear()
emptyBufferMock.mockClear()
addRawMock.mockClear()
const largeSummary = 'b'.repeat(1024 * 1024 + 1)
DefaultArtifactClientMock.mockImplementation(() => ({
uploadArtifact: jest.fn(async () => {
throw new Error('upload failed')
})
}))
const result = await handleLargeSummary(largeSummary)
// Should NOT return the original oversized content
expect(result).not.toBe(largeSummary)
// Should return a truncated summary
expect(result).toContain('Dependency Review Summary')
expect(result).toContain('too large to display')
// Should replace the core.summary buffer to prevent write() from failing
expect(emptyBufferMock).toHaveBeenCalled()
expect(addRawMock).toHaveBeenCalledWith(result)
expect(warningMock).toHaveBeenCalledWith(
expect.stringContaining('Failed to upload large summary as artifact')
)
})
})
-326
View File
@@ -1,326 +0,0 @@
import {expect, test, describe} from '@jest/globals'
import * as spdx from '../src/spdx'
describe('satisfiesAny', () => {
const units = [
{
candidate: 'MIT',
licenses: ['MIT'],
expected: true
},
{
candidate: 'MIT OR Apache-2.0',
licenses: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: '(MIT AND ISC) OR Apache-2.0',
licenses: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: 'MIT AND Apache-2.0',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT AND BSD-3-Clause',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
// missing params, case sensitivity, syntax problems,
// or unknown licenses will return 'false'
{
candidate: 'MIT OR',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: '',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT OR (Apache-2.0 AND ISC)',
licenses: [],
expected: false
},
{
candidate: 'MIT AND (ISC',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT OR ISC',
licenses: ['MiT'],
expected: false
},
{
candidate: 'MIT AND OTHER',
licenses: ['MIT'],
expected: false
},
{
candidate: 'MIT OR OTHER',
licenses: ['MIT', 'LicenseRef-clearlydefined-OTHER'],
expected: true
}
]
for (const unit of units) {
const got: boolean = spdx.satisfiesAny(unit.candidate, unit.licenses)
test(`should return ${unit.expected} for ("${unit.candidate}", "${unit.licenses}")`, () => {
expect(got).toBe(unit.expected)
})
}
})
describe('satisfiesAll', () => {
const units = [
{
candidate: 'MIT',
licenses: ['MIT'],
expected: true
},
{
candidate: 'Apache-2.0',
licenses: ['MIT', 'ISC', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT AND Apache-2.0',
licenses: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: '(MIT OR ISC) AND Apache-2.0',
licenses: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: 'MIT OR BSD-3-Clause',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'BSD-3-Clause OR ISC',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: '(MIT AND ISC) OR Apache-2.0',
licenses: ['MIT', 'ISC'],
expected: true
},
// missing params, case sensitivity, syntax problems,
// or unknown licenses will return 'false'
{
candidate: 'MIT OR',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: '',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT OR (Apache-2.0 AND ISC)',
licenses: [],
expected: false
},
{
candidate: 'MIT AND (ISC',
licenses: ['MIT', 'Apache-2.0'],
expected: false
},
{
candidate: 'MIT OR ISC',
licenses: ['MiT'],
expected: false
},
{
candidate: 'MIT AND OTHER',
licenses: ['MIT'],
expected: false
},
{
candidate: 'MIT AND OTHER',
licenses: ['MIT', 'LicenseRef-clearlydefined-OTHER'],
expected: true
}
]
for (const unit of units) {
const got: boolean = spdx.satisfiesAll(unit.candidate, unit.licenses)
test(`should return ${unit.expected} for ("${unit.candidate}", "${unit.licenses}")`, () => {
expect(got).toBe(unit.expected)
})
}
})
describe('satisfies', () => {
const units = [
{
candidate: 'MIT',
allowList: ['MIT'],
expected: true
},
{
candidate: 'Apache-2.0',
allowList: ['MIT'],
expected: false
},
{
candidate: 'MIT OR Apache-2.0',
allowList: ['MIT'],
expected: true
},
{
candidate: 'MIT OR Apache-2.0',
allowList: ['Apache-2.0'],
expected: true
},
{
candidate: 'MIT OR Apache-2.0',
allowList: ['BSD-3-Clause'],
expected: false
},
{
candidate: 'MIT OR Apache-2.0',
allowList: ['Apache-2.0', 'BSD-3-Clause'],
expected: true
},
{
candidate: 'MIT AND Apache-2.0',
allowList: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: 'MIT OR Apache-2.0',
allowList: ['MIT', 'Apache-2.0'],
expected: true
},
{
candidate: 'ISC OR (MIT AND Apache-2.0)',
allowList: ['MIT', 'Apache-2.0'],
expected: true
},
// missing params, case sensitivity, syntax problems,
// or unknown licenses will return 'false'
{
candidate: 'MIT',
allowList: ['MiT'],
expected: false
},
{
candidate: 'MIT AND (ISC OR',
allowList: ['MIT'],
expected: false
},
{
candidate: 'MIT OR ISC OR Apache-2.0',
allowList: [],
expected: false
},
{
candidate: '',
allowList: ['BSD-3-Clause', 'ISC', 'MIT'],
expected: false
},
{
candidate: 'MIT OR OTHER',
allowList: ['MIT', 'LicenseRef-clearlydefined-OTHER'],
expected: true
},
{
candidate: '(Apache-2.0 AND OTHER) OR (MIT AND OTHER)',
allowList: ['Apache-2.0', 'LicenseRef-clearlydefined-OTHER'],
expected: true
}
]
for (const unit of units) {
const got: boolean = spdx.satisfies(unit.candidate, unit.allowList)
test(`should return ${unit.expected} for ("${unit.candidate}", "${unit.allowList}")`, () => {
expect(got).toBe(unit.expected)
})
}
})
describe('isValid', () => {
const units = [
{
candidate: 'MIT',
expected: true
},
{
candidate: 'MIT AND BSD-3-Clause',
expected: true
},
{
candidate: '(MIT AND ISC) OR BSD-3-Clause',
expected: true
},
{
candidate: 'NOASSERTION',
expected: false
},
{
candidate: 'Foobar',
expected: false
},
{
candidate: '',
expected: false
},
{
candidate: 'MIT AND OTHER',
expected: true
}
]
for (const unit of units) {
const got: boolean = spdx.isValid(unit.candidate)
test(`should return ${unit.expected} for ("${unit.candidate}")`, () => {
expect(got).toBe(unit.expected)
})
}
})
describe('cleanInvalidSPDX', () => {
const units = [
{
candidate: 'MIT',
expected: 'MIT'
},
{
candidate: 'OTHER',
expected: 'LicenseRef-clearlydefined-OTHER'
},
{
candidate: 'LicenseRef-clearlydefined-OTHER',
expected: 'LicenseRef-clearlydefined-OTHER'
},
{
candidate: 'OTHER AND MIT',
expected: 'LicenseRef-clearlydefined-OTHER AND MIT'
},
{
candidate: 'MIT AND OTHER',
expected: 'MIT AND LicenseRef-clearlydefined-OTHER'
},
{
candidate: 'MIT AND SomethingElse-OTHER',
expected: 'MIT AND SomethingElse-OTHER'
}
]
for (const unit of units) {
const got: string = spdx.cleanInvalidSPDX(unit.candidate)
test(`should return ${unit.expected} for ("${unit.candidate}")`, () => {
expect(got).toBe(unit.expected)
})
}
})
+39 -51
View File
@@ -1,5 +1,5 @@
import {expect, jest, test} from '@jest/globals' import {expect, jest, test} from '@jest/globals'
import {Changes, ConfigurationOptions, Scorecard} from '../src/schemas' import {Change, Changes, ConfigurationOptions, Scorecard} from '../src/schemas'
import * as summary from '../src/summary' import * as summary from '../src/summary'
import * as core from '@actions/core' import * as core from '@actions/core'
import {createTestChange} from './fixtures/create-test-change' import {createTestChange} from './fixtures/create-test-change'
@@ -109,38 +109,46 @@ test('prints headline as h1', () => {
expect(text).toContain('<h1>Dependency Review</h1>') expect(text).toContain('<h1>Dependency Review</h1>')
}) })
test('does not add deprecation warning for deny-licenses option if not set', () => { test('returns minimal summary in case the core.summary is too large for a PR comment', () => {
summary.addSummaryToSummary( let changes: Changes = [
emptyChanges, createTestChange({name: 'lodash', version: '1.2.3'}),
createTestChange({name: 'colors', version: '2.3.4'}),
createTestChange({name: '@foo/bar', version: '*'})
]
let minSummary: string = summary.addSummaryToSummary(
changes,
emptyInvalidLicenseChanges, emptyInvalidLicenseChanges,
emptyChanges, emptyChanges,
scorecard, scorecard,
defaultConfig defaultConfig
) )
// side effect DR report into core.summary as happens in main.ts
summary.addScannedDependencies(changes)
const text = core.summary.stringify() const text = core.summary.stringify()
expect(text).not.toContain('deny-licenses') expect(text).toContain('<h1>Dependency Review</h1>')
}) expect(minSummary).toContain('# Dependency Review')
test('adds deprecation warning for deny-licenses option if set', () => { expect(text).toContain('❌ 3 vulnerable package(s)')
const config = {...defaultConfig, deny_licenses: ['MIT']} expect(text).not.toContain('* ❌ 3 vulnerable package(s)')
expect(text).toContain('lodash')
expect(text).toContain('colors')
expect(text).toContain('@foo/bar')
summary.addSummaryToSummary( expect(minSummary).toContain('* ❌ 3 vulnerable package(s)')
emptyChanges, expect(minSummary).not.toContain('lodash')
emptyInvalidLicenseChanges, expect(minSummary).not.toContain('colors')
emptyChanges, expect(minSummary).not.toContain('@foo/bar')
scorecard,
config
)
const text = core.summary.stringify()
expect(text).toContain('deny-licenses') expect(text.length).toBeGreaterThan(minSummary.length)
}) })
test('returns minimal summary formatted for posting as a PR comment', () => { test('returns minimal summary formatted for posting as a PR comment', () => {
const OLD_ENV = process.env const OLD_ENV = process.env
const changes: Changes = [ let changes: Changes = [
createTestChange({name: 'lodash', version: '1.2.3'}), createTestChange({name: 'lodash', version: '1.2.3'}),
createTestChange({name: 'colors', version: '2.3.4'}), createTestChange({name: 'colors', version: '2.3.4'}),
createTestChange({name: '@foo/bar', version: '*'}) createTestChange({name: '@foo/bar', version: '*'})
@@ -150,7 +158,7 @@ test('returns minimal summary formatted for posting as a PR comment', () => {
process.env.GITHUB_REPOSITORY = 'owner/repo' process.env.GITHUB_REPOSITORY = 'owner/repo'
process.env.GITHUB_RUN_ID = 'abc-123-xyz' process.env.GITHUB_RUN_ID = 'abc-123-xyz'
const minSummary: string = summary.addSummaryToSummary( let minSummary: string = summary.addSummaryToSummary(
changes, changes,
emptyInvalidLicenseChanges, emptyInvalidLicenseChanges,
emptyChanges, emptyChanges,
@@ -224,10 +232,14 @@ test('groups dependencies with empty manifest paths together', () => {
emptyScorecard, emptyScorecard,
defaultConfig defaultConfig
) )
summary.addScannedFiles(changesWithEmptyManifests) summary.addScannedDependencies(changesWithEmptyManifests)
const text = core.summary.stringify() const text = core.summary.stringify()
expect(text).toContain('Unnamed Manifest')
expect(text).toContain('python/dist-info/METADATA') expect(text).toContain('<summary>Unnamed Manifest</summary>')
expect(text).toContain('castore')
expect(text).toContain('connection')
expect(text).toContain('<summary>python/dist-info/METADATA</summary>')
expect(text).toContain('pygments')
}) })
test('does not include status section if nothing was found', () => { test('does not include status section if nothing was found', () => {
@@ -315,7 +327,7 @@ test('uses checkmarks for vulnerabilities if only license issues were found', ()
expect(text).toContain('✅ 0 package(s) with unknown licenses') expect(text).toContain('✅ 0 package(s) with unknown licenses')
}) })
test('addChangeVulnerabilitiesToSummary() - only includes section if any vulnerabilities found', () => { test('addChangeVulnerabilitiesToSummary() - only includes section if any vulnerabilites found', () => {
summary.addChangeVulnerabilitiesToSummary(emptyChanges, 'low') summary.addChangeVulnerabilitiesToSummary(emptyChanges, 'low')
const text = core.summary.stringify() const text = core.summary.stringify()
expect(text).toEqual('') expect(text).toEqual('')
@@ -385,7 +397,7 @@ test('addChangeVulnerabilitiesToSummary() - prints severity statement if above l
) )
}) })
test('addChangeVulnerabilitiesToSummary() - does not print severity statement if it is set to "low"', () => { test('addChangeVulnerabilitiesToSummary() - does not print severity statment if it is set to "low"', () => {
const changes = [createTestChange()] const changes = [createTestChange()]
summary.addChangeVulnerabilitiesToSummary(changes, 'low') summary.addChangeVulnerabilitiesToSummary(changes, 'low')
@@ -464,9 +476,7 @@ test('addLicensesToSummary() - includes list of configured allowed licenses', ()
summary.addLicensesToSummary(licenseIssues, config) summary.addLicensesToSummary(licenseIssues, config)
const text = core.summary.stringify() const text = core.summary.stringify()
expect(text).toContain( expect(text).toContain('<strong>Allowed Licenses</strong>: MIT, Apache-2.0')
'<details><summary><strong>Allowed Licenses</strong>:</summary> MIT, Apache-2.0</details>'
)
}) })
test('addLicensesToSummary() - includes configured denied license', () => { test('addLicensesToSummary() - includes configured denied license', () => {
@@ -478,33 +488,11 @@ test('addLicensesToSummary() - includes configured denied license', () => {
const config: ConfigurationOptions = { const config: ConfigurationOptions = {
...defaultConfig, ...defaultConfig,
deny_licenses: ['MIT', 'Apache-2.0'] deny_licenses: ['MIT']
} }
summary.addLicensesToSummary(licenseIssues, config) summary.addLicensesToSummary(licenseIssues, config)
const text = core.summary.stringify() const text = core.summary.stringify()
expect(text).toContain( expect(text).toContain('<strong>Denied Licenses</strong>: MIT')
'<details><summary><strong>Denied Licenses</strong>:</summary> MIT, Apache-2.0</details>'
)
})
test('addLicensesToSummary() - includes allowed dependency licences', () => {
const licenseIssues = {
forbidden: [createTestChange()],
unresolved: [],
unlicensed: []
}
const config: ConfigurationOptions = {
...defaultConfig,
allow_dependencies_licenses: ['MIT', 'Apache-2.0']
}
summary.addLicensesToSummary(licenseIssues, config)
const text = core.summary.stringify()
expect(text).toContain(
'<details><summary><strong>Excluded from license check</strong>:</summary> MIT, Apache-2.0</details>'
)
}) })
+1 -1
View File
@@ -53,7 +53,7 @@ inputs:
description: A boolean to determine if vulnerability checks should be performed description: A boolean to determine if vulnerability checks should be performed
required: false required: false
comment-summary-in-pr: comment-summary-in-pr:
description: "Determines if the summary is posted as a comment in the PR itself. Setting this to `always` or `on-failure` requires you to give the workflow `pull-requests: write` permissions" description: Determines if the summary is posted as a comment in the PR itself. Setting this to `always` or `on-failure` requires you to give the workflow the write permissions for pull-requests
required: false required: false
deny-packages: deny-packages:
description: A comma-separated list of package URLs to deny (e.g. "pkg:npm/express, pkg:pypi/pycrypto"). If version specified, only deny matching packages and version; else, deny all regardless of version. description: A comma-separated list of package URLs to deny (e.g. "pkg:npm/express, pkg:pypi/pycrypto"). If version specified, only deny matching packages and version; else, deny all regardless of version.
Generated Vendored
+3611 -101948
View File
File diff suppressed because one or more lines are too long
Generated Vendored
+1 -1
View File
File diff suppressed because one or more lines are too long
Generated Vendored
+26 -2870
View File
File diff suppressed because it is too large Load Diff
Generated Vendored
+1 -1
View File
File diff suppressed because one or more lines are too long
+7 -7
View File
@@ -1,10 +1,10 @@
# Examples of how to use the Dependency Review Action # Examples on how to use the Dependency Review Action
## Basic Usage ## Basic Usage
A very basic example of how to use the action. This will run the action with the default configuration. A very basic example of how to use the action. This will run the action with the default configuration.
See the [full list of configuration options](../README.md#configuration-options). The full list of configuration options can be found [here](../README.md#configuration-options).
```yaml ```yaml
name: 'Dependency Review' name: 'Dependency Review'
@@ -89,7 +89,7 @@ The following example will use a configuration file from an external public GitH
Let's say that the configuration file is located in `github/octorepo/dependency-review-config.yml@main` Let's say that the configuration file is located in `github/octorepo/dependency-review-config.yml@main`
The Dependency Review Action workflow file will then look like this: The Dependancy Review Action workflow file will then look like this:
```yaml ```yaml
name: 'Dependency Review' name: 'Dependency Review'
@@ -112,11 +112,11 @@ jobs:
## Using a configuration file from an external repository with a personal access token ## Using a configuration file from an external repository with a personal access token
The following example will use a configuration file from an external private GitHub repository to configure the action. The following example will use a configuration file from an external private GtiHub repository to configure the action.
Let's say that the configuration file is located in `github/octorepo-private/dependency-review-config.yml@main` Let's say that the configuration file is located in `github/octorepo-private/dependency-review-config.yml@main`
The Dependency Review Action workflow file will then look like this: The Dependancy Review Action workflow file will then look like this:
```yaml ```yaml
name: 'Dependency Review' name: 'Dependency Review'
@@ -233,7 +233,7 @@ jobs:
fail-on-severity: critical fail-on-severity: critical
deny-licenses: LGPL-2.0, BSD-2-Clause deny-licenses: LGPL-2.0, BSD-2-Clause
comment-summary-in-pr: always comment-summary-in-pr: always
allow-dependencies-licenses: 'pkg:npm/lodash, pkg:pypi/requests' allow-dependencies-licenses: 'pkg:npm/loadash, pkg:pypi/requests'
``` ```
If we were to use configuration file, the configuration would look like this: If we were to use configuration file, the configuration would look like this:
@@ -244,7 +244,7 @@ allow-licenses:
- 'LGPL-2.0' - 'LGPL-2.0'
- 'BSD-2-Clause' - 'BSD-2-Clause'
allow-dependencies-licenses: allow-dependencies-licenses:
- 'pkg:npm/lodash' - 'pkg:npm/loadash'
- 'pkg:pypi/requests' - 'pkg:pypi/requests'
``` ```
+727 -1998
View File
File diff suppressed because it is too large Load Diff
+21 -27
View File
@@ -1,6 +1,6 @@
{ {
"name": "dependency-review-action", "name": "dependency-review-action",
"version": "4.8.3", "version": "4.3.3",
"private": true, "private": true,
"description": "A GitHub Action for Dependency Review", "description": "A GitHub Action for Dependency Review",
"main": "lib/main.js", "main": "lib/main.js",
@@ -25,42 +25,36 @@
"author": "GitHub", "author": "GitHub",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/artifact": "^5.0.1", "@actions/core": "^1.10.1",
"@actions/core": "^1.11.1", "@actions/github": "^6.0.0",
"@actions/github": "^6.0.1", "@octokit/plugin-retry": "^6.0.1",
"@octokit/plugin-retry": "^6.1.0", "@octokit/request-error": "^5.0.1",
"@octokit/request-error": "^5.1.1", "@types/jest": "^29.5.12",
"@octokit/types": "12.5.0",
"@onebeyond/spdx-license-satisfies": "^1.0.1",
"ansi-styles": "^6.2.1", "ansi-styles": "^6.2.1",
"got": "^14.4.7", "got": "^14.2.0",
"jest": "^29.7.0", "jest": "^29.7.0",
"octokit": "^3.1.2", "octokit": "^3.1.2",
"spdx-expression-parse": "^4.0.0", "spdx-expression-parse": "^3.0.1",
"spdx-satisfies": "^6.0.0", "spdx-satisfies": "^5.0.1",
"ts-jest": "^29.4.1", "ts-jest": "^29.1.2",
"yaml": "^2.8.1", "yaml": "^2.3.4",
"zod": "^3.24.1" "zod": "^3.22.3"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.14",
"@types/node": "^20", "@types/node": "^20",
"@types/spdx-expression-parse": "^3.0.4", "@types/spdx-expression-parse": "^3.0.4",
"@types/spdx-satisfies": "^0.1.1",
"@typescript-eslint/eslint-plugin": "^6.21.0", "@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0", "@typescript-eslint/parser": "^6.21.0",
"@vercel/ncc": "^0.38.3", "@vercel/ncc": "^0.38.0",
"esbuild-register": "^3.6.0", "esbuild-register": "^3.5.0",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-plugin-github": "^4.10.2", "eslint-plugin-github": "^4.10.2",
"eslint-plugin-jest": "^28.8.3", "eslint-plugin-jest": "^27.9.0",
"eslint-plugin-prettier": "^5.5.4", "eslint-plugin-prettier": "^5.1.3",
"js-yaml": "^4.1.1", "js-yaml": "^4.1.0",
"nodemon": "^3.1.10", "nodemon": "^3.1.0",
"prettier": "3.6.2", "prettier": "3.2.5",
"typescript": "^5.9.2" "typescript": "^5.4.5"
},
"overrides": {
"cross-spawn": ">=7.0.5",
"@octokit/[email protected]": "5.1.1"
} }
} }
+1 -1
View File
@@ -143,7 +143,7 @@ async function createSummary(
...licenseIssues.unlicensed ...licenseIssues.unlicensed
] ]
summary.addScannedFiles(allChanges) summary.addScannedDependencies(allChanges)
const text = core.summary.stringify() const text = core.summary.stringify()
await fs.promises.writeFile(path.resolve(tmpDir, fileName), text, { await fs.promises.writeFile(path.resolve(tmpDir, fileName), text, {
+84 -5
View File
@@ -1,8 +1,87 @@
#!/usr/bin/env ruby #!/usr/bin/env ruby
require 'json'
require 'tempfile'
require 'open3'
require 'bundler/inline'
require 'optparse'
# Load the scan_pr library gemfile do
require_relative 'scan_pr_lib' source 'https://rubygems.org'
gem 'octokit'
end
# Create and run the scanner config_file = nil
scanner = ScanPr.new github_token = ENV["GITHUB_TOKEN"]
scanner.run(ARGV)
if !github_token || github_token.empty?
puts "Please set the GITHUB_TOKEN environment variable"
exit -1
end
op = OptionParser.new do |opts|
usage = <<EOF
Run Dependency Review on a repository.
\e[1mUsage:\e[22m
scripts/scan_pr [options] <pr_url>
\e[1mExample:\e[22m
scripts/scan_pr https://github.com/actions/dependency-review-action/pull/294
EOF
opts.banner = usage
opts.on('-c', '--config-file <FILE>', 'Use an external configuration file') do |cf|
config_file = cf
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end
op.parse!
# make sure we have a NWO somewhere in the parameters
arg = /(?<repo_nwo>[\w\-]+\/[\w\-]+)\/pull\/(?<pr_number>\d+)/.match(ARGV.join(" "))
if arg.nil?
puts op
exit -1
end
repo_nwo = arg[:repo_nwo]
pr_number = arg[:pr_number]
octo = Octokit::Client.new(access_token: github_token)
pr = octo.pull_request(repo_nwo, pr_number)
event_file = Tempfile.new
event_file.write("{ \"pull_request\": #{pr.to_h.to_json}}")
event_file.close
action_inputs = {
"repo-token": github_token,
"config-file": config_file
}
dev_cmd_env = {
"GITHUB_REPOSITORY" => repo_nwo,
"GITHUB_EVENT_NAME" => "pull_request",
"GITHUB_EVENT_PATH" => event_file.path,
"GITHUB_STEP_SUMMARY" => "/dev/null"
}
# bash does not like variable names with dashes like the ones Actions
# uses (e.g. INPUT_REPO-TOKEN). Passing them through `env` instead of
# manually setting them does the job.
action_inputs_env_str = action_inputs.map { |name, value| "\"INPUT_#{name.upcase}=#{value}\"" }.join(" ")
dev_cmd = "./node_modules/.bin/nodemon --exec \"env #{action_inputs_env_str} node -r esbuild-register\" src/main.ts"
Open3.popen2e(dev_cmd_env, dev_cmd) do |stdin, out|
while line = out.gets
puts line.gsub(github_token, "<REDACTED>")
end
end
-128
View File
@@ -1,128 +0,0 @@
require 'json'
require 'tempfile'
require 'open3'
require 'bundler/inline'
require 'optparse'
gemfile do
source 'https://rubygems.org'
gem 'octokit'
end
class ScanPr
def initialize
@config_file = nil
@github_token = ENV["GITHUB_TOKEN"]
validate_token
end
def run(args)
parse_options(args)
repo_nwo, pr_number = extract_repo_and_pr(args)
pr = fetch_pull_request(repo_nwo, pr_number)
event_file = create_event_file(pr)
execute_dependency_review(repo_nwo, event_file)
ensure
event_file&.unlink
end
private
def validate_token
if !@github_token || @github_token.empty?
puts "Please set the GITHUB_TOKEN environment variable"
exit -1
end
end
def parse_options(args)
op = OptionParser.new do |opts|
usage = <<EOF
Run Dependency Review on a repository.
\e[1mUsage:\e[22m
scripts/scan_pr [options] <pr_url>
\e[1mExample:\e[22m
scripts/scan_pr https://github.com/actions/dependency-review-action/pull/294
EOF
opts.banner = usage
opts.on('-c', '--config-file <FILE>', 'Use an external configuration file') do |cf|
@config_file = cf
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end
op.parse!(args)
@option_parser = op
end
def extract_repo_and_pr(args)
# make sure we have a NWO somewhere in the parameters
arg = /(?<repo_nwo>[\w\-]+\/[\w\-]+)\/pull\/(?<pr_number>\d+)/.match(args.join(" "))
if arg.nil?
puts @option_parser
exit -1
end
[arg[:repo_nwo], arg[:pr_number]]
end
def fetch_pull_request(repo_nwo, pr_number)
octo = Octokit::Client.new(access_token: @github_token)
octo.pull_request(repo_nwo, pr_number)
end
def create_event_file(pr)
event_file = Tempfile.new
event_file.write("{ \"pull_request\": #{pr.to_h.to_json}}")
event_file.close
event_file
end
def execute_dependency_review(repo_nwo, event_file)
action_inputs = {
"repo-token": @github_token,
"config-file": @config_file
}
dev_cmd_env = {
"GITHUB_REPOSITORY" => repo_nwo,
"GITHUB_EVENT_NAME" => "pull_request",
"GITHUB_EVENT_PATH" => event_file.path,
"GITHUB_STEP_SUMMARY" => "/dev/null"
}
# Merge action inputs into environment, formatting keys as INPUT_...
action_inputs_env = action_inputs.each_with_object({}) do |(name, value), h|
h["INPUT_#{name.to_s.upcase}"] = value unless value.nil?
end
env = dev_cmd_env.merge(action_inputs_env)
dev_cmd = [
"./node_modules/.bin/nodemon",
"--exec",
"node",
"-r",
"esbuild-register",
"src/main.ts"
]
Open3.popen2e(env, *dev_cmd) do |stdin, out|
while line = out.gets
puts line.gsub(@github_token, "<REDACTED>")
end
end
end
end
+3 -3
View File
@@ -17,13 +17,13 @@ const COMMENT_MARKER = '<!-- dependency-review-pr-comment-marker -->'
export async function commentPr( export async function commentPr(
commentContent: string, commentContent: string,
config: ConfigurationOptions, config: ConfigurationOptions
issueFound: boolean
): Promise<void> { ): Promise<void> {
if ( if (
!( !(
config.comment_summary_in_pr === 'always' || config.comment_summary_in_pr === 'always' ||
(config.comment_summary_in_pr === 'on-failure' && issueFound) (config.comment_summary_in_pr === 'on-failure' &&
process.exitCode === core.ExitCode.Failure)
) )
) { ) {
return return
+3 -6
View File
@@ -4,8 +4,7 @@ import YAML from 'yaml'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as z from 'zod' import * as z from 'zod'
import {ConfigurationOptions, ConfigurationOptionsSchema} from './schemas' import {ConfigurationOptions, ConfigurationOptionsSchema} from './schemas'
import {octokitClient} from './utils' import {isSPDXValid, octokitClient} from './utils'
import {isValid} from './spdx'
type ConfigurationOptionsPartial = Partial<ConfigurationOptions> type ConfigurationOptionsPartial = Partial<ConfigurationOptions>
@@ -114,12 +113,10 @@ function validateLicenses(
return return
} }
const invalid_licenses = licenses.filter(license => !isValid(license)) const invalid_licenses = licenses.filter(license => !isSPDXValid(license))
if (invalid_licenses.length > 0) { if (invalid_licenses.length > 0) {
throw new Error( throw new Error(`Invalid license(s) in ${key}: ${invalid_licenses}`)
`Invalid license(s) in ${key}: ${invalid_licenses.join(', ')}`
)
} }
} }
+9 -4
View File
@@ -9,17 +9,15 @@ export async function getDeniedChanges(
): Promise<Change[]> { ): Promise<Change[]> {
const changesDenied: Change[] = [] const changesDenied: Change[] = []
let hasDeniedPackage = false
for (const change of changes) { for (const change of changes) {
if (change.change_type === 'removed') {
continue
}
for (const denied of deniedPackages) { for (const denied of deniedPackages) {
if ( if (
(!denied.version || change.version === denied.version) && (!denied.version || change.version === denied.version) &&
change.name === denied.name change.name === denied.name
) { ) {
changesDenied.push(change) changesDenied.push(change)
hasDeniedPackage = true
} }
} }
@@ -32,10 +30,17 @@ export async function getDeniedChanges(
} }
if (namespace && namespace === denied.namespace) { if (namespace && namespace === denied.namespace) {
changesDenied.push(change) changesDenied.push(change)
hasDeniedPackage = true
} }
} }
} }
if (hasDeniedPackage) {
core.setFailed('Dependency review detected denied packages.')
} else {
core.info('Dependency review did not detect any denied packages')
}
return changesDenied return changesDenied
} }
+5 -18
View File
@@ -1,22 +1,14 @@
import { import {PullRequestSchema, ConfigurationOptions} from './schemas'
PullRequestSchema,
ConfigurationOptions,
MergeGroupSchema
} from './schemas'
export function getRefs( export function getRefs(
config: ConfigurationOptions, config: ConfigurationOptions,
context: { context: {payload: {pull_request?: unknown}; eventName: string}
payload: {pull_request?: unknown; merge_group?: unknown}
eventName: string
}
): {base: string; head: string} { ): {base: string; head: string} {
let base_ref = config.base_ref let base_ref = config.base_ref
let head_ref = config.head_ref let head_ref = config.head_ref
// If possible, source default base & head refs from the GitHub event. // If possible, source default base & head refs from the GitHub event.
// The base/head ref from the config take priority, if provided. // The base/head ref from the config take priority, if provided.
if (!base_ref && !head_ref) {
if ( if (
context.eventName === 'pull_request' || context.eventName === 'pull_request' ||
context.eventName === 'pull_request_target' context.eventName === 'pull_request_target'
@@ -24,30 +16,25 @@ export function getRefs(
const pull_request = PullRequestSchema.parse(context.payload.pull_request) const pull_request = PullRequestSchema.parse(context.payload.pull_request)
base_ref = base_ref || pull_request.base.sha base_ref = base_ref || pull_request.base.sha
head_ref = head_ref || pull_request.head.sha head_ref = head_ref || pull_request.head.sha
} else if (context.eventName === 'merge_group') {
const merge_group = MergeGroupSchema.parse(context.payload.merge_group)
base_ref = base_ref || merge_group.base_sha
head_ref = head_ref || merge_group.head_sha
}
} }
if (!base_ref && !head_ref) { if (!base_ref && !head_ref) {
throw new Error( throw new Error(
'Both a base ref and head ref must be provided, either via the `base_ref`/`head_ref` ' + 'Both a base ref and head ref must be provided, either via the `base_ref`/`head_ref` ' +
'config options, `base-ref`/`head-ref` workflow action options, or by running a ' + 'config options, `base-ref`/`head-ref` workflow action options, or by running a ' +
'`pull_request`/`pull_request_target`/`merge_group` workflow.' '`pull_request`/`pull_request_target` workflow.'
) )
} else if (!base_ref) { } else if (!base_ref) {
throw new Error( throw new Error(
'A base ref must be provided, either via the `base_ref` config option, ' + 'A base ref must be provided, either via the `base_ref` config option, ' +
'`base-ref` workflow action option, or by running a ' + '`base-ref` workflow action option, or by running a ' +
'`pull_request`/`pull_request_target`/`merge_group` workflow.' '`pull_request`/`pull_request_target` workflow.'
) )
} else if (!head_ref) { } else if (!head_ref) {
throw new Error( throw new Error(
'A head ref must be provided, either via the `head_ref` config option, ' + 'A head ref must be provided, either via the `head_ref` config option, ' +
'`head-ref` workflow action option, or by running a ' + '`head-ref` workflow action option, or by running a ' +
'or by running a `pull_request`/`pull_request_target`/`merge_group` workflow.' 'or by running a `pull_request`/`pull_request_target` workflow.'
) )
} }
+42 -62
View File
@@ -1,7 +1,7 @@
import spdxSatisfies from 'spdx-satisfies'
import {Change, Changes} from './schemas' import {Change, Changes} from './schemas'
import {octokitClient} from './utils' import {isSPDXValid, octokitClient} from './utils'
import {parsePURL, PackageURL} from './purl' import {parsePURL} from './purl'
import * as spdx from './spdx'
/** /**
* Loops through a list of changes, filtering and returning the * Loops through a list of changes, filtering and returning the
@@ -29,24 +29,41 @@ export async function getInvalidLicenseChanges(
licenseExclusions?: string[] licenseExclusions?: string[]
} }
): Promise<InvalidLicenseChanges> { ): Promise<InvalidLicenseChanges> {
const deny = licenses.deny const {allow, deny} = licenses
let allow = licenses.allow
// Filter out elements of the allow list that include AND
// or OR because the list should be simple license IDs and
// not expressions.
allow = allow?.filter(license => {
return !license.includes(' AND ') && !license.includes(' OR ')
})
const licenseExclusions = licenses.licenseExclusions?.map( const licenseExclusions = licenses.licenseExclusions?.map(
(pkgUrl: string) => { (pkgUrl: string) => {
return parsePURL(pkgUrl) return parsePURL(pkgUrl)
} }
) )
const groupedChanges = await groupChanges(changes, licenseExclusions) const groupedChanges = await groupChanges(changes)
// Takes the changes from the groupedChanges object and filters out the ones that are part of the exclusions list
// It does by creating a new PackageURL object from the change and comparing it to the exclusions list
groupedChanges.licensed = groupedChanges.licensed.filter(change => {
if (change.package_url.length === 0) {
return true
}
const changeAsPackageURL = parsePURL(encodeURI(change.package_url))
// We want to find if the licenseExclussion list contains the PackageURL of the Change
// If it does, we want to filter it out and therefore return false
// If it doesn't, we want to keep it and therefore return true
if (
licenseExclusions !== null &&
licenseExclusions !== undefined &&
licenseExclusions.findIndex(
exclusion =>
exclusion.type === changeAsPackageURL.type &&
exclusion.name === changeAsPackageURL.name
) !== -1
) {
return false
} else {
return true
}
})
const licensedChanges: Changes = groupedChanges.licensed const licensedChanges: Changes = groupedChanges.licensed
const invalidLicenseChanges: InvalidLicenseChanges = { const invalidLicenseChanges: InvalidLicenseChanges = {
@@ -70,19 +87,15 @@ export async function getInvalidLicenseChanges(
} else if (validityCache.get(license) === undefined) { } else if (validityCache.get(license) === undefined) {
try { try {
if (allow !== undefined) { if (allow !== undefined) {
if (spdx.isValid(license)) { const found = allow.find(spdxExpression =>
const found = spdx.satisfies(license, allow) spdxSatisfies(license, spdxExpression)
validityCache.set(license, found) )
} else { validityCache.set(license, found !== undefined)
invalidLicenseChanges.unresolved.push(change)
}
} else if (deny !== undefined) { } else if (deny !== undefined) {
if (spdx.isValid(license)) { const found = deny.find(spdxExpression =>
const found = spdx.satisfiesAny(license, deny) spdxSatisfies(license, spdxExpression)
validityCache.set(license, !found) )
} else { validityCache.set(license, found === undefined)
invalidLicenseChanges.unresolved.push(change)
}
} }
} catch (err) { } catch (err) {
invalidLicenseChanges.unresolved.push(change) invalidLicenseChanges.unresolved.push(change)
@@ -148,55 +161,22 @@ const setGHLicenses = async (changes: Change[]): Promise<Change[]> => {
return Promise.all(updatedChanges) return Promise.all(updatedChanges)
} }
// Currently Dependency Graph licenses are truncated to 255 characters // Currently Dependency Graph licenses are truncated to 255 characters
// This possibly makes them invalid spdx ids // This possibly makes them invalid spdx ids
const truncatedDGLicense = (license: string): boolean => const truncatedDGLicense = (license: string): boolean =>
license.length === 255 && !spdx.isValid(license) license.length === 255 && !isSPDXValid(license)
async function groupChanges( async function groupChanges(
changes: Changes, changes: Changes
licenseExclusions: PackageURL[] | null = null
): Promise<Record<string, Changes>> { ): Promise<Record<string, Changes>> {
const result: Record<string, Changes> = { const result: Record<string, Changes> = {
licensed: [], licensed: [],
unlicensed: [] unlicensed: []
} }
let candidateChanges = changes
// If a package is excluded from license checking, we don't bother trying to
// fetch the license for it and we leave it off of the `licensed` and
// `unlicensed` lists.
if (licenseExclusions !== null && licenseExclusions !== undefined) {
candidateChanges = candidateChanges.filter(change => {
if (change.package_url.length === 0) {
return true
}
const changeAsPackageURL = parsePURL(change.package_url)
// We want to find if the licenseExclusion list contains the PackageURL of the Change
// If it does, we want to filter it out and therefore return false
// If it doesn't, we want to keep it and therefore return true
if (
licenseExclusions.findIndex(
exclusion =>
exclusion.type === changeAsPackageURL.type &&
exclusion.namespace === changeAsPackageURL.namespace &&
exclusion.name === changeAsPackageURL.name
) !== -1
) {
return false
} else {
return true
}
})
}
const ghChanges = [] const ghChanges = []
for (const change of candidateChanges) { for (const change of changes) {
if (change.change_type === 'removed') { if (change.change_type === 'removed') {
continue continue
} }
+28 -127
View File
@@ -24,10 +24,6 @@ import {getRefs} from './git-refs'
import {groupDependenciesByManifest} from './utils' import {groupDependenciesByManifest} from './utils'
import {commentPr, MAX_COMMENT_LENGTH} from './comment-pr' import {commentPr, MAX_COMMENT_LENGTH} from './comment-pr'
import {getDeniedChanges} from './deny' import {getDeniedChanges} from './deny'
import {DefaultArtifactClient} from '@actions/artifact'
import * as fs from 'fs'
import type {PayloadRepository} from '@actions/github/lib/interfaces.d'
async function delay(ms: number): Promise<void> { async function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms)) return new Promise(resolve => setTimeout(resolve, ms))
@@ -65,62 +61,6 @@ async function getComparison(
return comparison return comparison
} }
export async function handleLargeSummary(
summaryContent: string
): Promise<string> {
const MAX_SUMMARY_SIZE = 1024 * 1024 // 1024k in bytes
if (Buffer.byteLength(summaryContent, 'utf8') <= MAX_SUMMARY_SIZE) {
return summaryContent
}
const summarySize = Math.round(
Buffer.byteLength(summaryContent, 'utf8') / 1024
)
const truncatedSummary = `# Dependency Review Summary
The full dependency review summary was too large to display here (${summarySize}KB, limit is 1024KB).`
const artifactClient = new DefaultArtifactClient()
const artifactName = 'dependency-review-summary'
const files = ['summary.md']
try {
// Write the summary to a file
await fs.promises.writeFile('summary.md', summaryContent)
// Upload the artifact
await artifactClient.uploadArtifact(artifactName, files, '.', {
retentionDays: 1
})
// Return a shorter summary with a link to the artifact
const shortSummary = `${truncatedSummary}
Please download the artifact named "${artifactName}" to view the complete report.
[View full job summary](${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID})`
// Set core.summary to the shorter summary value to avoid exceeding MAX_SUMMARY_SIZE
core.summary.emptyBuffer()
core.summary.addRaw(shortSummary)
return shortSummary
} catch (error) {
core.warning(
`Failed to upload large summary as artifact: ${error instanceof Error ? error.message : 'Unknown error'}`
)
// Even though artifact upload failed, we must still replace the buffer
// with a truncated summary to prevent core.summary.write() from failing
// with the oversized content (see issue #867)
core.summary.emptyBuffer()
core.summary.addRaw(truncatedSummary)
return truncatedSummary
}
}
interface RepoWithPrivate extends PayloadRepository {
private: boolean
}
async function run(): Promise<void> { async function run(): Promise<void> {
try { try {
const config = await readConfig() const config = await readConfig()
@@ -201,16 +141,10 @@ async function run(): Promise<void> {
summary.addSnapshotWarnings(config, snapshot_warnings) summary.addSnapshotWarnings(config, snapshot_warnings)
} }
let issueFound = false
if (config.vulnerability_check) { if (config.vulnerability_check) {
core.setOutput('vulnerable-changes', JSON.stringify(vulnerableChanges)) core.setOutput('vulnerable-changes', JSON.stringify(vulnerableChanges))
summary.addChangeVulnerabilitiesToSummary(vulnerableChanges, minSeverity) summary.addChangeVulnerabilitiesToSummary(vulnerableChanges, minSeverity)
issueFound ||= await printVulnerabilitiesBlock( printVulnerabilitiesBlock(vulnerableChanges, minSeverity, warnOnly)
vulnerableChanges,
minSeverity,
warnOnly
)
} }
if (config.license_check) { if (config.license_check) {
core.setOutput( core.setOutput(
@@ -218,12 +152,12 @@ async function run(): Promise<void> {
JSON.stringify(invalidLicenseChanges) JSON.stringify(invalidLicenseChanges)
) )
summary.addLicensesToSummary(invalidLicenseChanges, config) summary.addLicensesToSummary(invalidLicenseChanges, config)
issueFound ||= await printLicensesBlock(invalidLicenseChanges, warnOnly) printLicensesBlock(invalidLicenseChanges, warnOnly)
} }
if (config.deny_packages || config.deny_groups) { if (config.deny_packages || config.deny_groups) {
core.setOutput('denied-changes', JSON.stringify(deniedChanges)) core.setOutput('denied-changes', JSON.stringify(deniedChanges))
summary.addDeniedToSummary(deniedChanges) summary.addDeniedToSummary(deniedChanges)
issueFound ||= await printDeniedDependencies(deniedChanges, config) printDeniedDependencies(deniedChanges, config)
} }
if (config.show_openssf_scorecard) { if (config.show_openssf_scorecard) {
summary.addScorecardToSummary(scorecard, config) summary.addScorecardToSummary(scorecard, config)
@@ -232,16 +166,18 @@ async function run(): Promise<void> {
} }
core.setOutput('dependency-changes', JSON.stringify(changes)) core.setOutput('dependency-changes', JSON.stringify(changes))
summary.addScannedFiles(changes) summary.addScannedDependencies(changes)
printScannedDependencies(changes) printScannedDependencies(changes)
// include full summary in output; Actions will truncate if oversized // core.summary output must also be kept below 1024k
let rendered = core.summary.stringify() let rendered = core.summary.stringify()
if (rendered.length >= summary.MAX_SUMMARY_LENGTH) {
rendered = rendered.substring(0, summary.MAX_SUMMARY_LENGTH)
core.summary.clear()
core.summary.addRaw(rendered)
}
core.setOutput('comment-content', rendered) core.setOutput('comment-content', rendered)
// Handle large summaries by uploading as artifact
rendered = await handleLargeSummary(rendered)
// if the summary is oversized, replace with minimal version // if the summary is oversized, replace with minimal version
if (rendered.length >= MAX_COMMENT_LENGTH) { if (rendered.length >= MAX_COMMENT_LENGTH) {
core.debug( core.debug(
@@ -251,27 +187,16 @@ async function run(): Promise<void> {
} }
// update the PR comment if needed with the right-sized summary // update the PR comment if needed with the right-sized summary
await commentPr(rendered, config, issueFound) await commentPr(rendered, config)
} catch (error) { } catch (error) {
if (error instanceof RequestError && error.status === 404) { if (error instanceof RequestError && error.status === 404) {
core.setFailed( core.setFailed(
`Dependency review could not obtain dependency data for the specified owner, repository, or revision range.` `Dependency review could not obtain dependency data for the specified owner, repository, or revision range.`
) )
} else if (error instanceof RequestError && error.status === 403) { } else if (error instanceof RequestError && error.status === 403) {
let repoIsPrivate = false
if ('repository' in github.context.payload) {
const repo = github.context.payload.repository as RepoWithPrivate
repoIsPrivate = repo.private
}
if (repoIsPrivate) {
core.setFailed( core.setFailed(
`Dependency review is not supported on this repository. Please ensure that Dependency graph is enabled along with GitHub Advanced Security, see ${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/settings/security_analysis` `Dependency review is not supported on this repository. Please ensure that Dependency graph is enabled along with GitHub Advanced Security on private repositories, see https://github.com/${github.context.repo.owner}/${github.context.repo.repo}/settings/security_analysis`
) )
} else {
core.setFailed(
`Dependency review is not supported on this repository. Please ensure that Dependency graph is enabled, see ${github.context.serverUrl}/${github.context.repo.owner}/${github.context.repo.repo}/settings/security_analysis`
)
}
} else { } else {
if (error instanceof Error) { if (error instanceof Error) {
core.setFailed(error.message) core.setFailed(error.message)
@@ -280,29 +205,25 @@ async function run(): Promise<void> {
} }
} }
} finally { } finally {
try {
await core.summary.write() await core.summary.write()
} catch (error) {
core.warning(
`Failed to write job summary: ${error instanceof Error ? error.message : 'Unknown error'}`
)
}
} }
} }
async function printVulnerabilitiesBlock( function printVulnerabilitiesBlock(
addedChanges: Changes, addedChanges: Changes,
minSeverity: Severity, minSeverity: Severity,
warnOnly: boolean warnOnly: boolean
): Promise<boolean> { ): void {
return core.group('Vulnerabilities', async () => { let vulFound = false
let vulnFound = false core.group('Vulnerabilities', async () => {
if (addedChanges.length > 0) {
for (const change of addedChanges) { for (const change of addedChanges) {
vulnFound ||= printChangeVulnerabilities(change) printChangeVulnerabilities(change)
}
vulFound = true
} }
if (vulnFound) { if (vulFound) {
const msg = 'Dependency review detected vulnerable packages.' const msg = 'Dependency review detected vulnerable packages.'
if (warnOnly) { if (warnOnly) {
core.warning(msg) core.warning(msg)
@@ -314,12 +235,10 @@ async function printVulnerabilitiesBlock(
`Dependency review did not detect any vulnerable packages with severity level "${minSeverity}" or higher.` `Dependency review did not detect any vulnerable packages with severity level "${minSeverity}" or higher.`
) )
} }
return vulnFound
}) })
} }
function printChangeVulnerabilities(change: Change): boolean { function printChangeVulnerabilities(change: Change): void {
for (const vuln of change.vulnerabilities) { for (const vuln of change.vulnerabilities) {
core.info( core.info(
`${styles.bold.open}${change.manifest} » ${change.name}@${ `${styles.bold.open}${change.manifest} » ${change.name}@${
@@ -330,18 +249,14 @@ function printChangeVulnerabilities(change: Change): boolean {
) )
core.info(`${vuln.advisory_url}`) core.info(`${vuln.advisory_url}`)
} }
return change.vulnerabilities.length > 0
} }
async function printLicensesBlock( function printLicensesBlock(
invalidLicenseChanges: Record<string, Changes>, invalidLicenseChanges: Record<string, Changes>,
warnOnly: boolean warnOnly: boolean
): Promise<boolean> { ): void {
return core.group('Licenses', async () => { core.group('Licenses', async () => {
let issueFound = false
if (invalidLicenseChanges.forbidden.length > 0) { if (invalidLicenseChanges.forbidden.length > 0) {
issueFound = true
core.info('\nThe following dependencies have incompatible licenses:') core.info('\nThe following dependencies have incompatible licenses:')
printLicensesError(invalidLicenseChanges.forbidden) printLicensesError(invalidLicenseChanges.forbidden)
const msg = 'Dependency review detected incompatible licenses.' const msg = 'Dependency review detected incompatible licenses.'
@@ -352,7 +267,6 @@ async function printLicensesBlock(
} }
} }
if (invalidLicenseChanges.unresolved.length > 0) { if (invalidLicenseChanges.unresolved.length > 0) {
issueFound = true
core.warning( core.warning(
'\nThe validity of the licenses of the dependencies below could not be determined. Ensure that they are valid SPDX licenses:' '\nThe validity of the licenses of the dependencies below could not be determined. Ensure that they are valid SPDX licenses:'
) )
@@ -362,8 +276,6 @@ async function printLicensesBlock(
) )
} }
printNullLicenses(invalidLicenseChanges.unlicensed) printNullLicenses(invalidLicenseChanges.unlicensed)
return issueFound
}) })
} }
@@ -463,13 +375,11 @@ function printScannedDependencies(changes: Changes): void {
}) })
} }
async function printDeniedDependencies( function printDeniedDependencies(
changes: Changes, changes: Changes,
config: ConfigurationOptions config: ConfigurationOptions
): Promise<boolean> { ): void {
return core.group('Denied', async () => { core.group('Denied', async () => {
let issueFound = false
for (const denied of config.deny_packages) { for (const denied of config.deny_packages) {
core.info(`Config: ${denied}`) core.info(`Config: ${denied}`)
} }
@@ -478,15 +388,6 @@ async function printDeniedDependencies(
core.info(`Change: ${change.name}@${change.version} is denied`) core.info(`Change: ${change.name}@${change.version} is denied`)
core.info(`Change: ${change.package_url} is denied`) core.info(`Change: ${change.package_url} is denied`)
} }
if (changes.length > 0) {
issueFound = true
core.setFailed('Dependency review detected denied packages.')
} else {
core.info('Dependency review did not detect any denied packages')
}
return issueFound
}) })
} }
-5
View File
@@ -91,11 +91,6 @@ export const PullRequestSchema = z.object({
head: z.object({sha: z.string()}) head: z.object({sha: z.string()})
}) })
export const MergeGroupSchema = z.object({
base_sha: z.string(),
head_sha: z.string()
})
export const ConfigurationOptionsSchema = z export const ConfigurationOptionsSchema = z
.object({ .object({
fail_on_severity: SeveritySchema, fail_on_severity: SeveritySchema,
-4
View File
@@ -1,4 +0,0 @@
declare module 'spdx-satisfies' {
function spdxSatisfies(candidate: string, allowList: string[]): boolean
export = spdxSatisfies
}
-66
View File
@@ -1,66 +0,0 @@
import * as spdxlib from '@onebeyond/spdx-license-satisfies'
import spdxSatisfies from 'spdx-satisfies'
import parse from 'spdx-expression-parse'
/*
* NOTE: spdx-license-satisfies methods depend on spdx-expression-parse
* which throws errors in the presence of any syntax trouble, unknown
* license tokens, case sensitivity problems etc. to simplify handling
* you should pre-screen inputs to the satisfies* methods using isValid
*/
// accepts a pair of well-formed SPDX expressions. the
// candidate is tested against the constraint
export function satisfies(candidateExpr: string, allowList: string[]): boolean {
candidateExpr = cleanInvalidSPDX(candidateExpr)
try {
return spdxSatisfies(candidateExpr, allowList)
} catch (_) {
return false
}
}
// accepts an SPDX expression and a non-empty list of licenses (not expressions)
export function satisfiesAny(
candidateExpr: string,
licenses: string[]
): boolean {
candidateExpr = cleanInvalidSPDX(candidateExpr)
try {
return spdxlib.satisfiesAny(candidateExpr, licenses)
} catch (_) {
return false
}
}
// accepts an SPDX expression and a non-empty list of licenses (not expressions)
export function satisfiesAll(
candidateExpr: string,
licenses: string[]
): boolean {
candidateExpr = cleanInvalidSPDX(candidateExpr)
try {
return spdxlib.satisfiesAll(candidateExpr, licenses)
} catch (_) {
return false
}
}
// accepts any SPDX expression
export function isValid(spdxExpr: string): boolean {
spdxExpr = cleanInvalidSPDX(spdxExpr)
try {
parse(spdxExpr)
return true
} catch (_) {
return false
}
}
const replaceOtherRegex = /(?<![\w-])OTHER(?![\w-])/g
// adjusts license expressions to not include the invalid `OTHER`
// which ClearlyDefined adds to license strings
export function cleanInvalidSPDX(spdxExpr: string): string {
return spdxExpr.replace(replaceOtherRegex, 'LicenseRef-clearlydefined-OTHER')
}
+19 -48
View File
@@ -1,7 +1,7 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import {ConfigurationOptions, Changes, Change, Scorecard} from './schemas'
import {SummaryTableRow} from '@actions/core/lib/summary' import {SummaryTableRow} from '@actions/core/lib/summary'
import {InvalidLicenseChanges, InvalidLicenseChangeTypes} from './licenses' import {InvalidLicenseChanges, InvalidLicenseChangeTypes} from './licenses'
import {Change, Changes, ConfigurationOptions, Scorecard} from './schemas'
import {groupDependenciesByManifest, getManifestsSet, renderUrl} from './utils' import {groupDependenciesByManifest, getManifestsSet, renderUrl} from './utils'
const icons = { const icons = {
@@ -10,9 +10,9 @@ const icons = {
warning: '⚠️' warning: '⚠️'
} }
const MAX_SCANNED_FILES_BYTES = 1048576 export const MAX_SUMMARY_LENGTH = 1048576
// generates the DR report summary and caches it to the Action's core.summary. // generates the DR report summmary and caches it to the Action's core.summary.
// returns the DR summary string, ready to be posted as a PR comment if the // returns the DR summary string, ready to be posted as a PR comment if the
// final DR report is too large // final DR report is too large
export function addSummaryToSummary( export function addSummaryToSummary(
@@ -22,10 +22,6 @@ export function addSummaryToSummary(
scorecard: Scorecard, scorecard: Scorecard,
config: ConfigurationOptions config: ConfigurationOptions
): string { ): string {
if (config.deny_licenses && config.deny_licenses.length > 0) {
addDenyListsDeprecationWarningToSummary()
}
const out: string[] = [] const out: string[] = []
const scorecardWarnings = countScorecardWarnings(scorecard, config) const scorecardWarnings = countScorecardWarnings(scorecard, config)
@@ -110,13 +106,6 @@ export function addSummaryToSummary(
return out.join('\n') return out.join('\n')
} }
function addDenyListsDeprecationWarningToSummary(): void {
core.summary.addRaw(
`${icons.warning} <strong>Deprecation Warning</strong>: The <em>deny-licenses</em> option is deprecated for possible removal in the next major release. For more information, see issue 997.`,
true
)
}
function countScorecardWarnings( function countScorecardWarnings(
scorecard: Scorecard, scorecard: Scorecard,
config: ConfigurationOptions config: ConfigurationOptions
@@ -206,17 +195,19 @@ export function addLicensesToSummary(
if (config.allow_licenses && config.allow_licenses.length > 0) { if (config.allow_licenses && config.allow_licenses.length > 0) {
core.summary.addQuote( core.summary.addQuote(
`<details><summary><strong>Allowed Licenses</strong>:</summary> ${config.allow_licenses.join(', ')}</details>` `<strong>Allowed Licenses</strong>: ${config.allow_licenses.join(', ')}`
) )
} }
if (config.deny_licenses && config.deny_licenses.length > 0) { if (config.deny_licenses && config.deny_licenses.length > 0) {
core.summary.addQuote( core.summary.addQuote(
`<details><summary><strong>Denied Licenses</strong>:</summary> ${config.deny_licenses.join(', ')}</details>` `<strong>Denied Licenses</strong>: ${config.deny_licenses.join(', ')}`
) )
} }
if (config.allow_dependencies_licenses) { if (config.allow_dependencies_licenses) {
core.summary.addQuote( core.summary.addQuote(
`<details><summary><strong>Excluded from license check</strong>:</summary> ${config.allow_dependencies_licenses.join(', ')}</details>` `<strong>Excluded from license check</strong>: ${config.allow_dependencies_licenses.join(
', '
)}`
) )
} }
@@ -274,37 +265,20 @@ function formatLicense(license: string | null): string {
return license return license
} }
export function addScannedFiles(changes: Changes): void { export function addScannedDependencies(changes: Changes): void {
const manifests = Array.from( const dependencies = groupDependenciesByManifest(changes)
groupDependenciesByManifest(changes).keys() const manifests = dependencies.keys()
).sort()
let sf_size = 0 const summary = core.summary.addHeading('Scanned Manifest Files', 2)
let trunc_at = -1
for (const [index, entry] of manifests.entries()) { for (const manifest of manifests) {
if (sf_size + entry.length >= MAX_SCANNED_FILES_BYTES) { const deps = dependencies.get(manifest)
trunc_at = index if (deps) {
break const dependencyNames = deps.map(
dependency => `<li>${dependency.name}@${dependency.version}</li>`
)
summary.addDetails(manifest, `<ul>${dependencyNames.join('')}</ul>`)
} }
sf_size += entry.length
}
if (trunc_at >= 0) {
// truncate the manifests list if it will overflow the summary output
manifests.slice(0, trunc_at)
// if there's room between cutoff size and list size, add a warning
const size_diff = MAX_SCANNED_FILES_BYTES - sf_size
if (size_diff < 12) {
manifests.push('(truncated)')
}
}
const summary = core.summary.addHeading('Scanned Files', 2)
if (manifests.length === 0) {
summary.addRaw('None')
} else {
summary.addList(manifests)
} }
} }
@@ -330,9 +304,6 @@ export function addScorecardToSummary(
scorecard: Scorecard, scorecard: Scorecard,
config: ConfigurationOptions config: ConfigurationOptions
): void { ): void {
if (scorecard.dependencies.length === 0) {
return
}
core.summary.addHeading('OpenSSF Scorecard', 2) core.summary.addHeading('OpenSSF Scorecard', 2)
if (scorecard.dependencies.length > 10) { if (scorecard.dependencies.length > 10) {
core.summary.addRaw(`<details><summary>Scorecard details</summary>`, true) core.summary.addRaw(`<details><summary>Scorecard details</summary>`, true)
+10
View File
@@ -1,5 +1,6 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import {Octokit} from 'octokit' import {Octokit} from 'octokit'
import spdxParse from 'spdx-expression-parse'
import {Changes} from './schemas' import {Changes} from './schemas'
export function groupDependenciesByManifest( export function groupDependenciesByManifest(
@@ -33,6 +34,15 @@ export function renderUrl(url: string | null, text: string): string {
} }
} }
export function isSPDXValid(license: string): boolean {
try {
spdxParse(license)
return true
} catch (_) {
return false
}
}
function isEnterprise(): boolean { function isEnterprise(): boolean {
const serverUrl = new URL( const serverUrl = new URL(
process.env['GITHUB_SERVER_URL'] ?? 'https://github.com' process.env['GITHUB_SERVER_URL'] ?? 'https://github.com'
+1 -3
View File
@@ -5,9 +5,7 @@
"outDir": "./lib" /* Redirect output structure to the directory. */, "outDir": "./lib" /* Redirect output structure to the directory. */,
"strict": true /* Enable all strict type-checking options. */, "strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"typeRoots": [ "./node_modules/@types", "./types" ],
"types": [ "node", "jest", "spdx-license-satisfies" ]
}, },
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
-16
View File
@@ -1,16 +0,0 @@
declare module '@onebeyond/spdx-license-satisfies' {
export function satisfies(
candidateExpr: string,
constraintExpr: string
): boolean
export function satisfiesAny(
candidateExpr: string,
licenses: string[]
): boolean
export function satisfiesAll(
candidateExpr: string,
licenses: string[]
): boolean
}