Compare commits
53 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5b971718e | |||
| f51df6d455 | |||
| cffae74507 | |||
| 2031cfc080 | |||
| d02fa39f79 | |||
| 4038a34c4b | |||
| a632b8386b | |||
| 57a3d46a7b | |||
| 5ecdc4b578 | |||
| e8c2f9a12c | |||
| 0e129e113c | |||
| aa60746a92 | |||
| e404798400 | |||
| 24398f008e | |||
| 7863651912 | |||
| 17d14c08d9 | |||
| dea54b4342 | |||
| 8cf743c0ea | |||
| b49f407d39 | |||
| f68b94a696 | |||
| 05fe457637 | |||
| 2ced98cbe8 | |||
| 3a8496cb71 | |||
| 0f22a01592 | |||
| 58be34364d | |||
| 9284e0c621 | |||
| 8b766562f0 | |||
| 43f5f029f5 | |||
| f0033fc4d6 | |||
| a6c34d8785 | |||
| b379e2e05f | |||
| 2e1cf54a50 | |||
| 68e9887ce6 | |||
| a7c7f3b9b1 | |||
| 539c79be65 | |||
| ee66ea100d | |||
| 2af9bac14d | |||
| 98884d411b | |||
| 76bfce5cd7 | |||
| d45151f498 | |||
| 774d14bf50 | |||
| 20b998d4e2 | |||
| ad048f729f | |||
| 1d60e0d095 | |||
| 35ccfd2548 | |||
| a2014a181b | |||
| 1a0268586f | |||
| 14edcb1b2a | |||
| 805c0b2856 | |||
| 125b995082 | |||
| 289863a7c4 | |||
| 0f943b29ae | |||
| 2440f520c8 |
@@ -0,0 +1,111 @@
|
||||
# Copilot Coding Agent Instructions
|
||||
|
||||
Trust these instructions. Only search the codebase if information here is incomplete or found to be in error.
|
||||
|
||||
## Repository Overview
|
||||
|
||||
**dependency-review-action** is a GitHub Action (TypeScript/Node.js 20) that scans pull requests for dependency changes, raising errors for vulnerabilities or invalid licenses. It queries the GitHub Dependency Review API, evaluates changes against configured rules, and produces job summaries and PR comments. The action entry point is `dist/index.js` (bundled via `ncc`). The repo is small (~15 source files, ~15 test files).
|
||||
|
||||
## Build & Validation Commands
|
||||
|
||||
For CI-parity installs and local validation, run `npm ci --ignore-scripts` before other commands. This is the install step used in CI; release workflows may follow different install instructions (see CONTRIBUTING).
|
||||
|
||||
| Task | Command | Notes |
|
||||
| ------------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Install | `npm ci --ignore-scripts` | ~45s. Use `--ignore-scripts` for CI-parity installs; release workflows may use `npm i` per CONTRIBUTING. |
|
||||
| Build | `npm run build` | Compiles `src/*.ts` → `lib/*.js` via `tsc -p tsconfig.build.json`. ~5s. |
|
||||
| Test | `npm test` | Runs Jest. ~8s. All tests should pass. |
|
||||
| Lint | `npm run lint` | ESLint on `src/**/*.ts`. Ignore the TS version warning—it still passes. |
|
||||
| Format check | `npm run format-check` | Prettier check on `**/*.ts`. |
|
||||
| Format fix | `npm run format` | Auto-fix formatting with Prettier. |
|
||||
| Package | `npm run package` | Bundles the action entrypoint (`package.json#main`) → `dist/index.js` via `ncc`. ~7s. Do NOT include `dist/` changes in non-release PRs. |
|
||||
| All | `npm run all` | Runs: build → format → lint → package → test (in that order). |
|
||||
|
||||
### Validation Sequence After Making Changes
|
||||
|
||||
Always run these commands in this order to validate changes:
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
npm run format-check
|
||||
npm run lint
|
||||
npm test
|
||||
```
|
||||
|
||||
If format-check fails, run `npm run format` to auto-fix, then re-check.
|
||||
|
||||
### CI Checks (`.github/workflows/ci.yml`)
|
||||
|
||||
CI runs on PRs (excluding `**.md` changes) with Node 20:
|
||||
|
||||
1. **test** job: `npm ci --ignore-scripts` → `npm test`
|
||||
2. **lint** job: `npm ci --ignore-scripts` → `npm run format-check` → `npm run lint`
|
||||
|
||||
Additional workflows: `dependency-review.yml` (self-test), `codeql.yml` (CodeQL analysis), `stale.yaml` (stale issues).
|
||||
|
||||
## Project Layout
|
||||
|
||||
```
|
||||
src/ # TypeScript source (edit these files)
|
||||
main.ts # Entry point — orchestrates the action (532 lines)
|
||||
schemas.ts # Zod schemas & TypeScript types for all data structures
|
||||
config.ts # Reads action inputs + external YAML config
|
||||
dependency-graph.ts # GitHub API client for dependency diff
|
||||
filter.ts # Filters changes by severity, scope, allowed advisories
|
||||
licenses.ts # License validation against allow/deny lists
|
||||
deny.ts # Package/group deny-listing logic
|
||||
purl.ts # Package URL (PURL) parser
|
||||
spdx.ts # SPDX license expression handling
|
||||
scorecard.ts # OpenSSF Scorecard integration
|
||||
summary.ts # Summary/report generation (736 lines, largest module)
|
||||
comment-pr.ts # Posts/updates PR comments with results
|
||||
git-refs.ts # Resolves base/head git refs from event payload
|
||||
utils.ts # Shared utilities (Octokit client, grouping helpers)
|
||||
lib/ # Compiled JS output (from `npm run build`). Gitignored.
|
||||
dist/ # Bundled action (from `npm run package`). Committed but do NOT include changes in normal PRs - only pull requests which are creating new releases should have these files changed.
|
||||
__tests__/ # Jest test files (*.test.ts)
|
||||
test-helpers.ts # setInput()/clearInputs() helpers for test env vars
|
||||
fixtures/ # YAML config samples and factory helpers
|
||||
create-test-change.ts # Factory for mock Change objects
|
||||
create-test-vulnerability.ts # Factory for mock vulnerability objects
|
||||
scripts/ # Dev/debug utilities (scan_pr for manual testing, create_summary.ts for preview)
|
||||
action.yml # Action metadata — inputs, outputs, and `runs.main: dist/index.js`
|
||||
```
|
||||
|
||||
### Configuration Files
|
||||
|
||||
| File | Purpose |
|
||||
| --------------------- | ---------------------------------------------------------------------------- |
|
||||
| `tsconfig.json` | Base TypeScript config (ES6 target, CommonJS, strict mode) |
|
||||
| `tsconfig.build.json` | Build config — extends base, includes only `src/`, outputs to `lib/` |
|
||||
| `jest.config.js` | Jest config — uses `ts-jest`, matches `**/*.test.ts` |
|
||||
| `.eslintrc.json` | ESLint — `plugin:github/recommended`, strict TS rules, no semicolons |
|
||||
| `.prettierrc.json` | Prettier — no semis, single quotes, no bracket spacing, trailing comma: none |
|
||||
| `.prettierignore` | Ignores `dist/`, `lib/`, `node_modules/` |
|
||||
|
||||
### Key TypeScript/Style Rules
|
||||
|
||||
- No semicolons (enforced by ESLint and Prettier)
|
||||
- Single quotes, no trailing commas
|
||||
- `@typescript-eslint/no-explicit-any: error` — never use `any`
|
||||
- `@typescript-eslint/explicit-function-return-type: error` — all functions need return types (expressions exempt)
|
||||
- Unused function parameters/args must be prefixed with `_` (e.g. `_unused`); unused variables should be removed
|
||||
- Use Zod schemas (in `src/schemas.ts`) for all data validation and type definitions
|
||||
- Config option defaults belong in Zod schemas, NOT in `action.yml`
|
||||
|
||||
### Testing Patterns
|
||||
|
||||
- Tests use Jest with `ts-jest` transform — no build step needed before running tests
|
||||
- Use `__tests__/test-helpers.ts` `setInput(name, value)` to mock action inputs (sets `INPUT_*` env vars)
|
||||
- Use `__tests__/fixtures/create-test-change.ts` and `create-test-vulnerability.ts` for test data factories
|
||||
- Test files follow `__tests__/<module>.test.ts` naming convention
|
||||
- Tests run directly against TypeScript source (not compiled JS)
|
||||
|
||||
### Important Notes
|
||||
|
||||
- The action runs on `node20` (declared in `action.yml`)
|
||||
- Source imports often use relative `../src/` paths (e.g. `import {readConfig} from '../src/config'`)
|
||||
- Adding a new action input requires changes in: `action.yml` (input definition), `src/schemas.ts` (Zod schema with default), `src/config.ts` (reading the input), and relevant source/test files
|
||||
- `dist/index.js` is committed for GitHub Actions but PR contributors should NOT include `dist/` changes — maintainers handle rebuilding
|
||||
- The `lib/` directory is gitignored
|
||||
- Scorecard tests make real HTTP calls to `api.securityscorecards.dev` and `deps.dev`
|
||||
@@ -1,51 +0,0 @@
|
||||
name: CI-update-dist
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
paths-ignore:
|
||||
- 'dist/**'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
update-dist:
|
||||
# Only run for the original DRA repository; otherwise when users create pull requests from their `main` branch
|
||||
# it would erroneously update `dist` on their branch (and the pull request)
|
||||
if: github.repository == 'actions/dependency-review-action'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Install npm dependencies
|
||||
run: |
|
||||
npm clean-install
|
||||
|
||||
- name: Build distribution
|
||||
run: |
|
||||
npm run build
|
||||
npm run package
|
||||
|
||||
# Commit and push changes; has no effect if the files did not change
|
||||
# Important: The push event will not trigger any other workflows, see
|
||||
# https://github.com/stefanzweifel/git-auto-commit-action?tab=readme-ov-file#commits-made-by-this-action-do-not-trigger-new-workflow-runs
|
||||
- name: Commit & push changes
|
||||
uses: stefanzweifel/git-auto-commit-action@28e16e81777b558cc906c8750092100bbb34c5e3 # v7.0.0
|
||||
with:
|
||||
commit_author: 'github-actions[bot] <github-actions[bot]@users.noreply.github.com>'
|
||||
commit_user_name: 'github-actions[bot]'
|
||||
commit_user_email: 'github-actions[bot]@users.noreply.github.com'
|
||||
commit_message: '[bot] Update dist directory [skip ci]'
|
||||
file_pattern: 'dist/'
|
||||
@@ -17,8 +17,8 @@ jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
@@ -30,8 +30,8 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
@@ -24,11 +24,11 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# 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
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
uses: github/codeql-action/analyze@v4
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
|
||||
@@ -10,6 +10,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 'Checkout Repository'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
- name: Dependency Review
|
||||
uses: ./
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9.1.0
|
||||
- uses: actions/stale@v10.2.0
|
||||
name: Clean up stale PRs and Issues
|
||||
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."
|
||||
|
||||
+20
-24
@@ -50,8 +50,7 @@ Before you begin, you need to have [Node.js](https://nodejs.org/en/) installed,
|
||||
|
||||
#### Manually testing for vulnerabilities
|
||||
|
||||
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):
|
||||
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):
|
||||
|
||||
<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">
|
||||
|
||||
@@ -106,38 +105,35 @@ Here are a few things you can do that will increase the likelihood of your pull
|
||||
|
||||
_Note: these instructions are for maintainers_
|
||||
|
||||
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.
|
||||
1. Update the dist files by running `npm run build` and `npm run package`
|
||||
1. Go to [Draft a new
|
||||
release](https://github.com/actions/dependency-review-action/releases/new)
|
||||
in the Releases page.
|
||||
1. Make sure that the `Publish this Action to the GitHub Marketplace`
|
||||
checkbox is enabled
|
||||
- Create a local branch based on the `main` of the upstream repo.
|
||||
- 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 dist files by running `npm run build` and `npm run package`
|
||||
- Submit a PR based on your branch and have another maintainer review/approve it.
|
||||
- Once merged, go to [Draft a new release](https://github.com/actions/dependency-review-action/releases/new) in the Releases page.
|
||||
- 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">
|
||||
|
||||
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`).
|
||||
4. Use a version number for the release title (e.g. "1.2.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`).
|
||||
- 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">
|
||||
|
||||
5. Add your release notes. If this is a major version make sure to
|
||||
include a small description of the biggest changes in the new version.
|
||||
6. Click "Publish Release".
|
||||
- Add your release notes. If this is a major version make sure to include details about any breaking changes in the new version.
|
||||
- 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 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.
|
||||
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.
|
||||
|
||||
To do this just checkout `main`, force-create a new annotated tag, and push it:
|
||||
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 update the major version branch:
|
||||
|
||||
```
|
||||
git tag -fa v4 -m "Updating v4 to 4.0.1"
|
||||
git push origin v4 --force
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git branch -f v4 HEAD
|
||||
git push origin v4
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
- [Overview](#overview)
|
||||
- [Viewing the results](#viewing-the-results)
|
||||
- [Installation](#installation)
|
||||
- [Installation (standard)](#installation-standard)
|
||||
- [Installation (GitHub Enterprise Server)](#installation-github-enterprise-server)
|
||||
- [Installation (standard)](#installation-standard)
|
||||
- [Installation (GitHub Enterprise Server)](#installation-github-enterprise-server)
|
||||
- [Configuration](#configuration)
|
||||
- [Configuration options](#configuration-options)
|
||||
- [Configuration methods](#configuration-methods)
|
||||
@@ -130,6 +130,7 @@ All configuration options are optional.
|
||||
| `warn-only`+ | When set to `true`, the action will log all vulnerabilities as warnings regardless of the severity, and the action will complete with a `success` status. This overrides the `fail-on-severity` option. | `true`, `false` | `false` |
|
||||
| `show-openssf-scorecard` | When set to `true`, the action will output information about all the known OpenSSF Scorecard scores for the dependencies changed in this pull request. | `true`, `false` | `true` |
|
||||
| `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 |
|
||||
| `show-patched-versions`\* | When set to `true`, the vulnerability summary table will include an additional column showing the first patched version for each vulnerability. This requires additional API calls to fetch advisory data. | `true`, `false` | `false` |
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
@@ -215,6 +216,7 @@ You can use an external configuration file to specify settings for this action.
|
||||
|
||||
3. Create the configuration file in the path you specified for `config-file`.
|
||||
4. In the configuration file, specify your chosen settings.
|
||||
|
||||
```yaml
|
||||
fail-on-severity: 'critical'
|
||||
allow-licenses:
|
||||
|
||||
@@ -253,6 +253,33 @@ test('it does not filter out changes that are on the exclusions list', async ()
|
||||
expect(invalidLicenses.forbidden.length).toEqual(0)
|
||||
})
|
||||
|
||||
test('it excludes scoped npm packages when namespace separator is percent-encoded', async () => {
|
||||
const scopedNpmChange: Change = {
|
||||
manifest: 'package.json',
|
||||
change_type: 'added',
|
||||
ecosystem: 'npm',
|
||||
name: '@lancedb/lancedb',
|
||||
version: '0.14.3',
|
||||
package_url: 'pkg:npm/%40lancedb/lancedb@0.14.3',
|
||||
license: 'Apache-2.0',
|
||||
source_repository_url: 'github.com/lancedb/lancedb',
|
||||
scope: 'runtime',
|
||||
vulnerabilities: []
|
||||
}
|
||||
const changes: Changes = [scopedNpmChange, rubyChange]
|
||||
const licensesConfig = {
|
||||
allow: ['BSD-3-Clause'],
|
||||
// user provides %2F-encoded version
|
||||
licenseExclusions: ['pkg:npm/%40lancedb%2Flancedb']
|
||||
}
|
||||
const invalidLicenses = await getInvalidLicenseChanges(
|
||||
changes,
|
||||
licensesConfig
|
||||
)
|
||||
// scoped package should be excluded, only rubyChange remains (allowed)
|
||||
expect(invalidLicenses.forbidden.length).toEqual(0)
|
||||
})
|
||||
|
||||
test('it does not fail when the packages dont have a valid PURL', async () => {
|
||||
const emptyPurlChange = pipChange
|
||||
emptyPurlChange.package_url = ''
|
||||
|
||||
+14
-3
@@ -132,9 +132,13 @@ describe('handleLargeSummary', () => {
|
||||
expect(result).toContain('actions/runs/12345')
|
||||
})
|
||||
|
||||
test('returns original summary and logs a warning when artifact handling fails', async () => {
|
||||
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(() => ({
|
||||
@@ -145,9 +149,16 @@ describe('handleLargeSummary', () => {
|
||||
|
||||
const result = await handleLargeSummary(largeSummary)
|
||||
|
||||
expect(result).toBe(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 handle large summary')
|
||||
expect.stringContaining('Failed to upload large summary as artifact')
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
+64
-1
@@ -1,5 +1,5 @@
|
||||
import {expect, test} from '@jest/globals'
|
||||
import {parsePURL} from '../src/purl'
|
||||
import {parsePURL, purlsMatch} from '../src/purl'
|
||||
|
||||
test('parsePURL returns an error if the purl does not start with "pkg:"', () => {
|
||||
const purl = 'not-a-purl'
|
||||
@@ -184,3 +184,66 @@ test('parsePURL table test', () => {
|
||||
expect(result).toEqual(example.expected)
|
||||
}
|
||||
})
|
||||
|
||||
test('purlsMatch matches identical PURLs', () => {
|
||||
const a = parsePURL('pkg:npm/@scope/name@1.0.0')
|
||||
const b = parsePURL('pkg:npm/@scope/name@2.0.0')
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch matches when namespace separator is percent-encoded', () => {
|
||||
// %2F-encoded separator puts everything in name with no namespace
|
||||
const encoded = parsePURL('pkg:npm/%40lancedb%2Flancedb')
|
||||
// literal / splits into namespace + name
|
||||
const literal = parsePURL('pkg:npm/%40lancedb/lancedb')
|
||||
expect(purlsMatch(encoded, literal)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch matches scoped npm packages regardless of encoding', () => {
|
||||
const a = parsePURL('pkg:npm/%40lancedb%2Flancedb')
|
||||
const b = parsePURL('pkg:npm/@lancedb/lancedb')
|
||||
const c = parsePURL('pkg:npm/%40lancedb/lancedb@0.14.3')
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
expect(purlsMatch(a, c)).toBe(true)
|
||||
expect(purlsMatch(b, c)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch does not match different packages', () => {
|
||||
const a = parsePURL('pkg:npm/@scope/foo')
|
||||
const b = parsePURL('pkg:npm/@scope/bar')
|
||||
expect(purlsMatch(a, b)).toBe(false)
|
||||
})
|
||||
|
||||
test('purlsMatch does not match different types', () => {
|
||||
const a = parsePURL('pkg:npm/@scope/name')
|
||||
const b = parsePURL('pkg:pypi/@scope/name')
|
||||
expect(purlsMatch(a, b)).toBe(false)
|
||||
})
|
||||
|
||||
test('purlsMatch matches packages without namespaces', () => {
|
||||
const a = parsePURL('pkg:npm/lodash@4.0.0')
|
||||
const b = parsePURL('pkg:npm/lodash@5.0.0')
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch is case-insensitive for GitHub Actions', () => {
|
||||
const a = parsePURL('pkg:githubactions/MyOrg/MyAction@1.0.0')
|
||||
const b = parsePURL('pkg:githubactions/myorg/myaction@1.0.0')
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch is case-insensitive for scoped npm packages', () => {
|
||||
const a = parsePURL('pkg:npm/@MyScope/MyPackage')
|
||||
const b = parsePURL('pkg:npm/@myscope/mypackage')
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
test('purlsMatch is case-insensitive for GitHub Actions with file paths', () => {
|
||||
const a = parsePURL(
|
||||
'pkg:githubactions/MyOrg/MyWorkflows/.github/workflows/general.yml'
|
||||
)
|
||||
const b = parsePURL(
|
||||
'pkg:githubactions/myorg/myworkflows/.github/workflows/general.yml'
|
||||
)
|
||||
expect(purlsMatch(a, b)).toBe(true)
|
||||
})
|
||||
|
||||
+383
-15
@@ -1,12 +1,25 @@
|
||||
import {expect, jest, test} from '@jest/globals'
|
||||
import {expect, jest, test, beforeEach} from '@jest/globals'
|
||||
import {Changes, ConfigurationOptions, Scorecard} from '../src/schemas'
|
||||
import * as summary from '../src/summary'
|
||||
import * as core from '@actions/core'
|
||||
import {createTestChange} from './fixtures/create-test-change'
|
||||
import {createTestVulnerability} from './fixtures/create-test-vulnerability'
|
||||
import * as utils from '../src/utils'
|
||||
|
||||
const mockOctokitRequest = jest.fn<any>()
|
||||
|
||||
beforeEach(() => {
|
||||
jest.spyOn(utils, 'octokitClient').mockReturnValue({
|
||||
request: mockOctokitRequest
|
||||
} as any)
|
||||
|
||||
mockOctokitRequest.mockResolvedValue({
|
||||
data: {vulnerabilities: []}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.restoreAllMocks()
|
||||
core.summary.emptyBuffer()
|
||||
})
|
||||
|
||||
@@ -34,7 +47,8 @@ const defaultConfig: ConfigurationOptions = {
|
||||
retry_on_snapshot_warnings_timeout: 120,
|
||||
warn_only: false,
|
||||
warn_on_openssf_scorecard_level: 3,
|
||||
show_openssf_scorecard: false
|
||||
show_openssf_scorecard: false,
|
||||
show_patched_versions: false
|
||||
}
|
||||
|
||||
const changesWithEmptyManifests: Changes = [
|
||||
@@ -315,19 +329,19 @@ test('uses checkmarks for vulnerabilities if only license issues were found', ()
|
||||
expect(text).toContain('✅ 0 package(s) with unknown licenses')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - only includes section if any vulnerabilities found', () => {
|
||||
summary.addChangeVulnerabilitiesToSummary(emptyChanges, 'low')
|
||||
test('addChangeVulnerabilitiesToSummary() - only includes section if any vulnerabilities found', async () => {
|
||||
await summary.addChangeVulnerabilitiesToSummary(emptyChanges, 'low')
|
||||
const text = core.summary.stringify()
|
||||
expect(text).toEqual('')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - includes all vulnerabilities', () => {
|
||||
test('addChangeVulnerabilitiesToSummary() - includes all vulnerabilities', async () => {
|
||||
const changes = [
|
||||
createTestChange({name: 'lodash'}),
|
||||
createTestChange({name: 'underscore', package_url: 'test-url'})
|
||||
]
|
||||
|
||||
summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).toContain('<h2>Vulnerabilities</h2>')
|
||||
@@ -335,7 +349,7 @@ test('addChangeVulnerabilitiesToSummary() - includes all vulnerabilities', () =>
|
||||
expect(text).toContain('underscore')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - includes advisory url if available', () => {
|
||||
test('addChangeVulnerabilitiesToSummary() - includes advisory url if available', async () => {
|
||||
const changes = [
|
||||
createTestChange({
|
||||
name: 'underscore',
|
||||
@@ -348,14 +362,14 @@ test('addChangeVulnerabilitiesToSummary() - includes advisory url if available',
|
||||
})
|
||||
]
|
||||
|
||||
summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).toContain('lodash')
|
||||
expect(text).toContain('<a href="test-url">test-summary</a>')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - groups vulnerabilities of a single package', () => {
|
||||
test('addChangeVulnerabilitiesToSummary() - groups vulnerabilities of a single package', async () => {
|
||||
const changes = [
|
||||
createTestChange({
|
||||
name: 'package-with-multiple-vulnerabilities',
|
||||
@@ -366,7 +380,7 @@ test('addChangeVulnerabilitiesToSummary() - groups vulnerabilities of a single p
|
||||
})
|
||||
]
|
||||
|
||||
summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text.match('package-with-multiple-vulnerabilities')).toHaveLength(1)
|
||||
@@ -374,10 +388,10 @@ test('addChangeVulnerabilitiesToSummary() - groups vulnerabilities of a single p
|
||||
expect(text).toContain('test-summary-2')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - prints severity statement if above low', () => {
|
||||
test('addChangeVulnerabilitiesToSummary() - prints severity statement if above low', async () => {
|
||||
const changes = [createTestChange()]
|
||||
|
||||
summary.addChangeVulnerabilitiesToSummary(changes, 'medium')
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'medium')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).toContain(
|
||||
@@ -385,15 +399,79 @@ 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 statement if it is set to "low"', async () => {
|
||||
const changes = [createTestChange()]
|
||||
|
||||
summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).not.toContain('Only included vulnerabilities')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - does not include patched version column by default', async () => {
|
||||
const changes = [createTestChange()]
|
||||
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).not.toContain('Patched Version')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - includes patched version column when enabled', async () => {
|
||||
const changes = [createTestChange()]
|
||||
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).toContain('Patched Version')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - skips patched version on GHES even when enabled', async () => {
|
||||
const originalUrl = process.env.GITHUB_SERVER_URL
|
||||
process.env.GITHUB_SERVER_URL = 'https://ghes.example.com'
|
||||
const warnSpy = jest.spyOn(core, 'warning')
|
||||
|
||||
const changes = [createTestChange()]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).not.toContain('Patched Version')
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
'show-patched-versions is not supported on GitHub Enterprise Server. The Patched Version column will be omitted.'
|
||||
)
|
||||
expect(mockOctokitRequest).not.toHaveBeenCalled()
|
||||
|
||||
process.env.GITHUB_SERVER_URL = originalUrl
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - works normally on GHES when patched versions disabled', async () => {
|
||||
const originalUrl = process.env.GITHUB_SERVER_URL
|
||||
process.env.GITHUB_SERVER_URL = 'https://ghes.example.com'
|
||||
|
||||
const changes = [createTestChange()]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', false)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).not.toContain('Patched Version')
|
||||
expect(mockOctokitRequest).not.toHaveBeenCalled()
|
||||
|
||||
process.env.GITHUB_SERVER_URL = originalUrl
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - works normally on GHES with default (no third arg)', async () => {
|
||||
const originalUrl = process.env.GITHUB_SERVER_URL
|
||||
process.env.GITHUB_SERVER_URL = 'https://ghes.example.com'
|
||||
|
||||
const changes = [createTestChange()]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low')
|
||||
|
||||
const text = core.summary.stringify()
|
||||
expect(text).not.toContain('Patched Version')
|
||||
expect(mockOctokitRequest).not.toHaveBeenCalled()
|
||||
|
||||
process.env.GITHUB_SERVER_URL = originalUrl
|
||||
})
|
||||
|
||||
test('addLicensesToSummary() - does not include entire section if no license issues found', () => {
|
||||
summary.addLicensesToSummary(emptyInvalidLicenseChanges, defaultConfig)
|
||||
const text = core.summary.stringify()
|
||||
@@ -508,3 +586,293 @@ test('addLicensesToSummary() - includes allowed dependency licences', () => {
|
||||
'<details><summary><strong>Excluded from license check</strong>:</summary> MIT, Apache-2.0</details>'
|
||||
)
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - handles multiple version ranges for same package', async () => {
|
||||
// Simulates GHSA-gwq6-fmvp-qp68 scenario with multiple version ranges
|
||||
const pkg8 = createTestChange({
|
||||
ecosystem: 'nuget',
|
||||
name: 'Microsoft.NetCore.App.Runtime.linux-arm',
|
||||
version: '8.0.1',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: 'GHSA-test-multi',
|
||||
advisory_summary: 'Test Multi-Range Advisory',
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
const pkg9 = createTestChange({
|
||||
ecosystem: 'nuget',
|
||||
name: 'Microsoft.NetCore.App.Runtime.linux-arm',
|
||||
version: '9.0.1',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: 'GHSA-test-multi',
|
||||
advisory_summary: 'Test Multi-Range Advisory',
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
// Mock API response with multiple version ranges for same package
|
||||
mockOctokitRequest.mockResolvedValueOnce({
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {
|
||||
ecosystem: 'NuGet',
|
||||
name: 'Microsoft.NetCore.App.Runtime.linux-arm'
|
||||
},
|
||||
vulnerable_version_range: '>= 8.0.0, <= 8.0.20',
|
||||
first_patched_version: '8.0.21'
|
||||
},
|
||||
{
|
||||
package: {
|
||||
ecosystem: 'NuGet',
|
||||
name: 'Microsoft.NetCore.App.Runtime.linux-arm'
|
||||
},
|
||||
vulnerable_version_range: '>= 9.0.0, <= 9.0.9',
|
||||
first_patched_version: '9.0.10'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const changes = [pkg8, pkg9]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
|
||||
// Both packages should have correct patched versions based on their version ranges
|
||||
expect(text).toContain('8.0.21')
|
||||
expect(text).toContain('9.0.10')
|
||||
expect(mockOctokitRequest).toHaveBeenCalledWith('GET /advisories/{ghsa_id}', {
|
||||
ghsa_id: 'GHSA-test-multi'
|
||||
})
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - handles RestSharp GHSA-4rr6-2v9v-wcpc case', async () => {
|
||||
const pkg = createTestChange({
|
||||
ecosystem: 'nuget',
|
||||
name: 'RestSharp',
|
||||
version: '111.4.1',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: 'GHSA-4rr6-2v9v-wcpc',
|
||||
advisory_summary:
|
||||
"CRLF Injection in RestSharp's `RestRequest.AddHeader` method",
|
||||
severity: 'moderate'
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
// Mock API response matching actual GitHub Advisory Database response
|
||||
mockOctokitRequest.mockResolvedValueOnce({
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {
|
||||
ecosystem: 'nuget',
|
||||
name: 'RestSharp'
|
||||
},
|
||||
vulnerable_version_range: '>= 107.0.0-preview.1, < 112.0.0',
|
||||
first_patched_version: '112.0.0'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const changes = [pkg]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
|
||||
// Should show the correct patched version
|
||||
expect(text).toContain('112.0.0')
|
||||
expect(text).not.toContain('N/A')
|
||||
expect(mockOctokitRequest).toHaveBeenCalledWith('GET /advisories/{ghsa_id}', {
|
||||
ghsa_id: 'GHSA-4rr6-2v9v-wcpc'
|
||||
})
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - handles version coercion for non-strict semver versions', async () => {
|
||||
// Test that versions like "8.0" (without patch version) can be coerced to "8.0.0"
|
||||
// for successful range matching in fail-open mode (patch selection)
|
||||
const pkg = createTestChange({
|
||||
ecosystem: 'npm',
|
||||
name: 'test-package',
|
||||
version: '8.0', // Non-strict semver version
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: 'GHSA-test-1234',
|
||||
advisory_summary: 'Test vulnerability',
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
mockOctokitRequest.mockResolvedValueOnce({
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {
|
||||
ecosystem: 'npm',
|
||||
name: 'test-package'
|
||||
},
|
||||
vulnerable_version_range: '>= 8.0.0, < 9.0.0',
|
||||
first_patched_version: '9.0.0'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const changes = [pkg]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
|
||||
// Should coerce "8.0" to "8.0.0" and successfully match the range,
|
||||
// showing the patched version instead of N/A
|
||||
expect(text).toContain('9.0.0')
|
||||
expect(text).not.toContain('N/A')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - handles invalid versions in fail-open mode', async () => {
|
||||
// Test that completely invalid versions that can't be coerced
|
||||
// still return N/A gracefully in fail-open mode
|
||||
const pkg = createTestChange({
|
||||
ecosystem: 'npm',
|
||||
name: 'test-package',
|
||||
version: 'invalid-version-string',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: 'GHSA-test-5678',
|
||||
advisory_summary: 'Test vulnerability',
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
|
||||
mockOctokitRequest.mockResolvedValueOnce({
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {
|
||||
ecosystem: 'npm',
|
||||
name: 'test-package'
|
||||
},
|
||||
vulnerable_version_range: '>= 1.0.0, < 2.0.0',
|
||||
first_patched_version: '2.0.0'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const changes = [pkg]
|
||||
await summary.addChangeVulnerabilitiesToSummary(changes, 'low', true)
|
||||
|
||||
const text = core.summary.stringify()
|
||||
|
||||
// Should show N/A since version can't be coerced or matched
|
||||
expect(text).toContain('N/A')
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - respects concurrency limit for API calls', async () => {
|
||||
// Create 15 packages with different vulnerabilities to test concurrency limiting
|
||||
const packages = Array.from({length: 15}, (_, i) =>
|
||||
createTestChange({
|
||||
ecosystem: 'npm',
|
||||
name: `package-${i}`,
|
||||
version: '1.0.0',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: `GHSA-test-${i.toString().padStart(4, '0')}`,
|
||||
advisory_summary: `Vulnerability ${i}`,
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
)
|
||||
|
||||
// Track concurrent calls
|
||||
let maxConcurrent = 0
|
||||
let currentConcurrent = 0
|
||||
|
||||
mockOctokitRequest.mockImplementation(async () => {
|
||||
currentConcurrent++
|
||||
maxConcurrent = Math.max(maxConcurrent, currentConcurrent)
|
||||
|
||||
// Simulate async API call with a small deterministic delay
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
|
||||
currentConcurrent--
|
||||
|
||||
return {
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {ecosystem: 'npm', name: 'test'},
|
||||
vulnerable_version_range: '>= 1.0.0, < 2.0.0',
|
||||
first_patched_version: '2.0.0'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await summary.addChangeVulnerabilitiesToSummary(packages, 'low', true)
|
||||
|
||||
// Verify that concurrency limit (10) was respected
|
||||
expect(maxConcurrent).toBeLessThanOrEqual(10)
|
||||
// Verify all 15 unique advisories were fetched
|
||||
expect(mockOctokitRequest).toHaveBeenCalledTimes(15)
|
||||
})
|
||||
|
||||
test('addChangeVulnerabilitiesToSummary() - completes all tasks even with varying durations', async () => {
|
||||
// Test that promise pool doesn't lose tasks when some complete faster than others
|
||||
const packages = Array.from({length: 20}, (_, i) =>
|
||||
createTestChange({
|
||||
ecosystem: 'npm',
|
||||
name: `package-${i}`,
|
||||
version: '1.0.0',
|
||||
vulnerabilities: [
|
||||
createTestVulnerability({
|
||||
advisory_ghsa_id: `GHSA-vary-${i.toString().padStart(4, '0')}`,
|
||||
advisory_summary: `Vulnerability ${i}`,
|
||||
severity: 'high'
|
||||
})
|
||||
]
|
||||
})
|
||||
)
|
||||
|
||||
const completedAdvisories = new Set<string>()
|
||||
|
||||
mockOctokitRequest.mockImplementation(
|
||||
async (path: string, params: {ghsa_id: string}) => {
|
||||
// Variable delay to simulate real-world API response times
|
||||
const delay = Math.random() * 50
|
||||
await new Promise(resolve => setTimeout(resolve, delay))
|
||||
|
||||
completedAdvisories.add(params.ghsa_id)
|
||||
|
||||
return {
|
||||
data: {
|
||||
vulnerabilities: [
|
||||
{
|
||||
package: {ecosystem: 'npm', name: 'test'},
|
||||
vulnerable_version_range: '>= 1.0.0, < 2.0.0',
|
||||
first_patched_version: '2.0.0'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
await summary.addChangeVulnerabilitiesToSummary(packages, 'low', true)
|
||||
|
||||
// Verify all 20 unique advisories were fetched and completed
|
||||
expect(completedAdvisories.size).toBe(20)
|
||||
expect(mockOctokitRequest).toHaveBeenCalledTimes(20)
|
||||
})
|
||||
|
||||
@@ -76,6 +76,9 @@ inputs:
|
||||
warn-on-openssf-scorecard-level:
|
||||
description: Numeric threshold for the OpenSSF Scorecard score. If the score is below this threshold, the action will warn you.
|
||||
required: false
|
||||
show-patched-versions:
|
||||
description: When set to `true`, the vulnerability summary table will include a column showing the first patched version for each vulnerability.
|
||||
required: false
|
||||
outputs:
|
||||
comment-content:
|
||||
description: Prepared dependency report comment
|
||||
|
||||
+32947
-6967
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+21
-105
@@ -360,6 +360,27 @@ SOFTWARE.
|
||||
|
||||
@azure/storage-common
|
||||
MIT
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2018 Microsoft
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
@fastify/busboy
|
||||
MIT
|
||||
@@ -1245,16 +1266,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
@vercel/ncc
|
||||
MIT
|
||||
Copyright 2018 ZEIT, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
abort-controller
|
||||
MIT
|
||||
MIT License
|
||||
@@ -2937,31 +2948,6 @@ PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
|
||||
|
||||
is-plain-object
|
||||
MIT
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014-2017, Jon Schlinkert.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
is-stream
|
||||
MIT
|
||||
MIT License
|
||||
@@ -3537,32 +3523,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
node-fetch
|
||||
MIT
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 David Frank
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
|
||||
|
||||
normalize-path
|
||||
MIT
|
||||
The MIT License (MIT)
|
||||
@@ -4441,9 +4401,6 @@ Apache-2.0
|
||||
limitations under the License.
|
||||
|
||||
|
||||
tr46
|
||||
MIT
|
||||
|
||||
traverse
|
||||
MIT/X11
|
||||
Copyright 2010 James Halliday (mail@substack.net)
|
||||
@@ -4626,47 +4583,6 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
webidl-conversions
|
||||
BSD-2-Clause
|
||||
# The BSD 2-Clause License
|
||||
|
||||
Copyright (c) 2014, Domenic Denicola
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
whatwg-url
|
||||
MIT
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015–2016 Sebastian Mayr
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
wrappy
|
||||
ISC
|
||||
The ISC License
|
||||
|
||||
Generated
+676
-317
File diff suppressed because it is too large
Load Diff
+6
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dependency-review-action",
|
||||
"version": "4.8.2",
|
||||
"version": "4.9.0",
|
||||
"private": true,
|
||||
"description": "A GitHub Action for Dependency Review",
|
||||
"main": "lib/main.js",
|
||||
@@ -25,7 +25,7 @@
|
||||
"author": "GitHub",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@actions/artifact": "^2.3.2",
|
||||
"@actions/artifact": "^5.0.1",
|
||||
"@actions/core": "^1.11.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@octokit/plugin-retry": "^6.1.0",
|
||||
@@ -36,7 +36,8 @@
|
||||
"got": "^14.4.7",
|
||||
"jest": "^29.7.0",
|
||||
"octokit": "^3.1.2",
|
||||
"spdx-expression-parse": "^3.0.1",
|
||||
"semver": "^7.7.4",
|
||||
"spdx-expression-parse": "^4.0.0",
|
||||
"spdx-satisfies": "^6.0.0",
|
||||
"ts-jest": "^29.4.1",
|
||||
"yaml": "^2.8.1",
|
||||
@@ -54,7 +55,7 @@
|
||||
"eslint-plugin-github": "^4.10.2",
|
||||
"eslint-plugin-jest": "^28.8.3",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"js-yaml": "^4.1.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"nodemon": "^3.1.10",
|
||||
"prettier": "3.6.2",
|
||||
"typescript": "^5.9.2"
|
||||
@@ -63,4 +64,4 @@
|
||||
"cross-spawn": ">=7.0.5",
|
||||
"@octokit/request-error@5.0.1": "5.1.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ const defaultConfig: ConfigurationOptions = {
|
||||
retry_on_snapshot_warnings_timeout: 120,
|
||||
warn_only: false,
|
||||
warn_on_openssf_scorecard_level: 3,
|
||||
show_openssf_scorecard: true
|
||||
show_openssf_scorecard: true,
|
||||
show_patched_versions: false
|
||||
}
|
||||
|
||||
const scorecard: Scorecard = {
|
||||
@@ -130,7 +131,7 @@ async function createSummary(
|
||||
scorecard,
|
||||
config
|
||||
)
|
||||
summary.addChangeVulnerabilitiesToSummary(
|
||||
await summary.addChangeVulnerabilitiesToSummary(
|
||||
vulnerabilities,
|
||||
config.fail_on_severity
|
||||
)
|
||||
|
||||
+3
-1
@@ -52,6 +52,7 @@ function readInlineConfig(): ConfigurationOptionsPartial {
|
||||
const warn_on_openssf_scorecard_level = getOptionalNumber(
|
||||
'warn-on-openssf-scorecard-level'
|
||||
)
|
||||
const show_patched_versions = getOptionalBoolean('show-patched-versions')
|
||||
|
||||
validateLicenses('allow-licenses', allow_licenses)
|
||||
validateLicenses('deny-licenses', deny_licenses)
|
||||
@@ -74,7 +75,8 @@ function readInlineConfig(): ConfigurationOptionsPartial {
|
||||
retry_on_snapshot_warnings_timeout,
|
||||
warn_only,
|
||||
show_openssf_scorecard,
|
||||
warn_on_openssf_scorecard_level
|
||||
warn_on_openssf_scorecard_level,
|
||||
show_patched_versions
|
||||
}
|
||||
|
||||
return Object.fromEntries(
|
||||
|
||||
+3
-6
@@ -1,6 +1,6 @@
|
||||
import {Change, Changes} from './schemas'
|
||||
import {octokitClient} from './utils'
|
||||
import {parsePURL, PackageURL} from './purl'
|
||||
import {parsePURL, PackageURL, purlsMatch} from './purl'
|
||||
import * as spdx from './spdx'
|
||||
|
||||
/**
|
||||
@@ -180,11 +180,8 @@ async function groupChanges(
|
||||
// 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
|
||||
licenseExclusions.findIndex(exclusion =>
|
||||
purlsMatch(exclusion, changeAsPackageURL)
|
||||
) !== -1
|
||||
) {
|
||||
return false
|
||||
|
||||
+35
-10
@@ -24,7 +24,7 @@ import {getRefs} from './git-refs'
|
||||
import {groupDependenciesByManifest} from './utils'
|
||||
import {commentPr, MAX_COMMENT_LENGTH} from './comment-pr'
|
||||
import {getDeniedChanges} from './deny'
|
||||
import * as artifact from '@actions/artifact'
|
||||
import {DefaultArtifactClient} from '@actions/artifact'
|
||||
import * as fs from 'fs'
|
||||
|
||||
import type {PayloadRepository} from '@actions/github/lib/interfaces.d'
|
||||
@@ -73,7 +73,14 @@ export async function handleLargeSummary(
|
||||
return summaryContent
|
||||
}
|
||||
|
||||
const artifactClient = new artifact.DefaultArtifactClient()
|
||||
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']
|
||||
|
||||
@@ -87,9 +94,9 @@ export async function handleLargeSummary(
|
||||
})
|
||||
|
||||
// Return a shorter summary with a link to the artifact
|
||||
const shortSummary = `# Dependency Review Summary
|
||||
const shortSummary = `${truncatedSummary}
|
||||
|
||||
The full dependency review summary is too large to display here. Please download the artifact named "${artifactName}" to view the complete report.
|
||||
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})`
|
||||
|
||||
@@ -99,9 +106,14 @@ The full dependency review summary is too large to display here. Please download
|
||||
return shortSummary
|
||||
} catch (error) {
|
||||
core.warning(
|
||||
`Failed to handle large summary: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
`Failed to upload large summary as artifact: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
)
|
||||
return summaryContent
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,8 +186,11 @@ async function run(): Promise<void> {
|
||||
)
|
||||
|
||||
// generate informational scorecard entries for all added changes in the PR
|
||||
const scorecardChanges = getScorecardChanges(changes)
|
||||
const scorecard = await getScorecardLevels(scorecardChanges)
|
||||
let scorecard: Scorecard = {dependencies: []}
|
||||
if (config.show_openssf_scorecard) {
|
||||
const scorecardChanges = getScorecardChanges(changes)
|
||||
scorecard = await getScorecardLevels(scorecardChanges)
|
||||
}
|
||||
|
||||
const minSummary = summary.addSummaryToSummary(
|
||||
vulnerableChanges,
|
||||
@@ -193,7 +208,11 @@ async function run(): Promise<void> {
|
||||
|
||||
if (config.vulnerability_check) {
|
||||
core.setOutput('vulnerable-changes', JSON.stringify(vulnerableChanges))
|
||||
summary.addChangeVulnerabilitiesToSummary(vulnerableChanges, minSeverity)
|
||||
await summary.addChangeVulnerabilitiesToSummary(
|
||||
vulnerableChanges,
|
||||
minSeverity,
|
||||
config.show_patched_versions
|
||||
)
|
||||
issueFound ||= await printVulnerabilitiesBlock(
|
||||
vulnerableChanges,
|
||||
minSeverity,
|
||||
@@ -268,7 +287,13 @@ async function run(): Promise<void> {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await core.summary.write()
|
||||
try {
|
||||
await core.summary.write()
|
||||
} catch (error) {
|
||||
core.warning(
|
||||
`Failed to write job summary: ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -70,3 +70,28 @@ export function parsePURL(purl: string): PackageURL {
|
||||
// we don't parse subpath or attributes, so we're done here
|
||||
return result
|
||||
}
|
||||
|
||||
// Returns the full name of a package, combining namespace and name.
|
||||
// This normalizes PURLs where the namespace separator '/' may have been
|
||||
// percent-encoded as '%2F', causing it to be parsed as part of the name
|
||||
// rather than splitting namespace and name.
|
||||
function fullName(purl: PackageURL): string | null {
|
||||
if (purl.namespace && purl.name) {
|
||||
return `${purl.namespace}/${purl.name}`
|
||||
}
|
||||
return purl.name ?? purl.namespace
|
||||
}
|
||||
|
||||
// Compare two PackageURLs for equality, ignoring version and normalizing
|
||||
// namespace/name splits. This handles the case where a PURL like
|
||||
// 'pkg:npm/%40scope%2Fname' is parsed as {namespace: null, name: '@scope/name'}
|
||||
// while 'pkg:npm/%40scope/name' is parsed as {namespace: '@scope', name: 'name'}.
|
||||
//
|
||||
// The comparison is case-insensitive because most ecosystems and registries
|
||||
// treat names that way (npm, PyPI, GitHub org/repo names, etc.).
|
||||
export function purlsMatch(a: PackageURL, b: PackageURL): boolean {
|
||||
if (a.type.toLowerCase() !== b.type.toLowerCase()) {
|
||||
return false
|
||||
}
|
||||
return fullName(a)?.toLowerCase() === fullName(b)?.toLowerCase()
|
||||
}
|
||||
|
||||
@@ -115,6 +115,7 @@ export const ConfigurationOptionsSchema = z
|
||||
retry_on_snapshot_warnings_timeout: z.number().default(120),
|
||||
show_openssf_scorecard: z.boolean().optional().default(true),
|
||||
warn_on_openssf_scorecard_level: z.number().default(3),
|
||||
show_patched_versions: z.boolean().default(false),
|
||||
comment_summary_in_pr: z
|
||||
.union([
|
||||
z.preprocess(
|
||||
|
||||
+317
-19
@@ -2,7 +2,14 @@ import * as core from '@actions/core'
|
||||
import {SummaryTableRow} from '@actions/core/lib/summary'
|
||||
import {InvalidLicenseChanges, InvalidLicenseChangeTypes} from './licenses'
|
||||
import {Change, Changes, ConfigurationOptions, Scorecard} from './schemas'
|
||||
import {groupDependenciesByManifest, getManifestsSet, renderUrl} from './utils'
|
||||
import {
|
||||
groupDependenciesByManifest,
|
||||
getManifestsSet,
|
||||
renderUrl,
|
||||
octokitClient,
|
||||
isEnterprise
|
||||
} from './utils'
|
||||
import * as semver from 'semver'
|
||||
|
||||
const icons = {
|
||||
check: '✅',
|
||||
@@ -11,6 +18,109 @@ const icons = {
|
||||
}
|
||||
|
||||
const MAX_SCANNED_FILES_BYTES = 1048576
|
||||
const API_CONCURRENCY_LIMIT = 10 // Limit concurrent API requests to avoid rate limiting
|
||||
|
||||
/**
|
||||
* Helper to check if a version falls within a vulnerable range.
|
||||
* Uses the `semver` library for proper prerelease handling and range parsing.
|
||||
*
|
||||
* @param version - The version to check (can be pre-trimmed).
|
||||
* @param range - The version range to check against (can be pre-trimmed and/or pre-normalized).
|
||||
* @param options - Configuration options.
|
||||
* @param options.preTrimmed - If true, assumes inputs are already trimmed (optimization).
|
||||
* @param options.preNormalized - If true, assumes range is already normalized (comma-to-space conversion done).
|
||||
* @param options.failClosed - If true, returns true (vulnerable) on errors; if false, returns false (no match).
|
||||
* @returns `true` if the version is considered within the vulnerable range (or on fail-closed), otherwise `false`.
|
||||
*/
|
||||
function versionInRange(
|
||||
version: string | undefined,
|
||||
range: string | undefined,
|
||||
options: {
|
||||
preTrimmed?: boolean
|
||||
preNormalized?: boolean
|
||||
failClosed?: boolean
|
||||
} = {}
|
||||
): boolean {
|
||||
const {preTrimmed = false, preNormalized = false, failClosed = true} = options
|
||||
|
||||
// Trim inputs if not pre-trimmed
|
||||
const trimmedVersion = preTrimmed ? version : version?.trim() || ''
|
||||
const trimmedRange = preTrimmed ? range : range?.trim() || ''
|
||||
|
||||
if (!trimmedVersion) {
|
||||
if (failClosed) {
|
||||
core.debug(
|
||||
`Empty or missing version for range "${range}". Treating as vulnerable (fail closed).`
|
||||
)
|
||||
}
|
||||
return failClosed
|
||||
}
|
||||
if (!trimmedRange) {
|
||||
if (failClosed) {
|
||||
core.debug(
|
||||
`Empty or missing version range for version "${version}". Treating as vulnerable (fail closed).`
|
||||
)
|
||||
}
|
||||
return failClosed
|
||||
}
|
||||
|
||||
// Convert GitHub API range format to semver-compatible format if not already normalized
|
||||
// GitHub uses: ">= 8.0.0, <= 8.0.20"
|
||||
// Semver accepts: ">= 8.0.0 <= 8.0.20" (operators may be followed by a space)
|
||||
const semverRange = preNormalized
|
||||
? trimmedRange
|
||||
: trimmedRange.replace(/,\s*/g, ' ')
|
||||
|
||||
// Validate version and range explicitly to enforce fail-closed semantics
|
||||
// semver.satisfies() typically returns false for invalid inputs without throwing
|
||||
let validVersion = semver.valid(trimmedVersion)
|
||||
const validRange = semver.validRange(semverRange)
|
||||
|
||||
// For fail-open mode (patch selection), try coercing invalid versions
|
||||
// to handle common real-world formats like "8.0", date-based versions, etc.
|
||||
if (!validVersion && !failClosed) {
|
||||
const coerced = semver.coerce(trimmedVersion)
|
||||
if (coerced) {
|
||||
validVersion = coerced.version
|
||||
core.debug(
|
||||
`Coerced version "${trimmedVersion}" to "${validVersion}" for range matching`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (!validVersion || !validRange) {
|
||||
if (failClosed) {
|
||||
const issues: string[] = []
|
||||
if (!validVersion) issues.push('version')
|
||||
if (!validRange) issues.push('version range')
|
||||
core.debug(
|
||||
`Invalid ${issues.join(' and ')}: version="${version}", range="${range}". Treating as vulnerable (fail closed).`
|
||||
)
|
||||
}
|
||||
return failClosed
|
||||
}
|
||||
|
||||
// Both version and range are valid; perform the satisfies check
|
||||
// Only include prereleases when the version being checked is itself a prerelease
|
||||
// to avoid changing range semantics globally
|
||||
const isPrerelease = semver.prerelease(validVersion) !== null
|
||||
return semver.satisfies(validVersion, validRange, {
|
||||
includePrerelease: isPrerelease
|
||||
})
|
||||
}
|
||||
|
||||
function extractPatchVersionId(patchData: unknown): string | null {
|
||||
// Handle string format (current API response)
|
||||
if (typeof patchData === 'string') return patchData
|
||||
|
||||
// Handle object format with identifier field (for backward compatibility)
|
||||
if (patchData && typeof patchData === 'object' && 'identifier' in patchData) {
|
||||
const id = (patchData as {identifier: unknown}).identifier
|
||||
return typeof id === 'string' ? id : null
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// generates the DR report summary and caches it to the Action's core.summary.
|
||||
// returns the DR summary string, ready to be posted as a PR comment if the
|
||||
@@ -132,21 +242,142 @@ function countScorecardWarnings(
|
||||
)
|
||||
}
|
||||
|
||||
export function addChangeVulnerabilitiesToSummary(
|
||||
/**
|
||||
* Execute promises with a concurrency limit to avoid overwhelming APIs.
|
||||
* @param tasks - Array of functions that return promises
|
||||
* @param limit - Maximum number of concurrent promises
|
||||
*/
|
||||
async function promisePool(
|
||||
tasks: (() => Promise<void>)[],
|
||||
limit: number
|
||||
): Promise<void> {
|
||||
const executing: Set<Promise<void>> = new Set()
|
||||
|
||||
for (const task of tasks) {
|
||||
// Execute task and clean up
|
||||
const wrappedPromise = (async () => {
|
||||
await task()
|
||||
})()
|
||||
|
||||
executing.add(wrappedPromise)
|
||||
|
||||
// When promise completes, remove it from the executing set
|
||||
wrappedPromise.finally(() => {
|
||||
executing.delete(wrappedPromise)
|
||||
})
|
||||
|
||||
// Wait if we've hit the concurrency limit
|
||||
if (executing.size >= limit) {
|
||||
await Promise.race(executing)
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all remaining promises
|
||||
await Promise.all(executing)
|
||||
}
|
||||
|
||||
export async function addChangeVulnerabilitiesToSummary(
|
||||
vulnerableChanges: Changes,
|
||||
severity: string
|
||||
): void {
|
||||
severity: string,
|
||||
showPatchedVersions = false
|
||||
): Promise<void> {
|
||||
if (vulnerableChanges.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const rows: SummaryTableRow[] = []
|
||||
|
||||
const manifests = getManifestsSet(vulnerableChanges)
|
||||
|
||||
// Build set of unique advisories to query
|
||||
const advisorySet = new Set<string>()
|
||||
if (showPatchedVersions) {
|
||||
if (isEnterprise()) {
|
||||
core.warning(
|
||||
'show-patched-versions is not supported on GitHub Enterprise Server. The Patched Version column will be omitted.'
|
||||
)
|
||||
showPatchedVersions = false
|
||||
} else {
|
||||
for (const pkg of vulnerableChanges) {
|
||||
for (const vuln of pkg.vulnerabilities) {
|
||||
advisorySet.add(vuln.advisory_ghsa_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Query GitHub API for patch info with concurrency limiting
|
||||
// Store all vulnerability entries (may be multiple per package with different ranges)
|
||||
// Pre-normalize ecosystem, package name, and range to avoid repeated work in rendering
|
||||
const patchInfo: Record<
|
||||
string,
|
||||
{
|
||||
eco: string
|
||||
pkg: string
|
||||
range: string
|
||||
patch: string
|
||||
ecoLower: string
|
||||
pkgLower: string
|
||||
normalizedRange: string
|
||||
}[]
|
||||
> = {}
|
||||
const apiClient = octokitClient()
|
||||
|
||||
// Create tasks for promise pool
|
||||
const tasks = Array.from(advisorySet).map(advId => async () => {
|
||||
try {
|
||||
core.debug(`Fetching advisory data for ${advId}`)
|
||||
const apiResult = await apiClient.request('GET /advisories/{ghsa_id}', {
|
||||
ghsa_id: advId
|
||||
})
|
||||
|
||||
patchInfo[advId] = []
|
||||
const vulnList = apiResult.data.vulnerabilities || []
|
||||
core.debug(`Found ${vulnList.length} vulnerability entries for ${advId}`)
|
||||
|
||||
for (const v of vulnList) {
|
||||
if (v.package && v.package.ecosystem) {
|
||||
const normalizedEco = v.package.ecosystem.toLowerCase()
|
||||
const pkgName = v.package.name || ''
|
||||
const vulnRange = v.vulnerable_version_range || ''
|
||||
const patchVerId = extractPatchVersionId(v.first_patched_version)
|
||||
if (patchVerId) {
|
||||
// Pre-normalize and cache values to avoid repeated work in rendering loop
|
||||
const trimmedRange = vulnRange.trim()
|
||||
const normalizedRange = trimmedRange.replace(/,\s*/g, ' ')
|
||||
patchInfo[advId].push({
|
||||
eco: normalizedEco,
|
||||
pkg: pkgName,
|
||||
range: vulnRange,
|
||||
patch: patchVerId,
|
||||
ecoLower: normalizedEco, // Ecosystem already normalized to lowercase
|
||||
pkgLower: pkgName.toLowerCase(),
|
||||
normalizedRange
|
||||
})
|
||||
core.debug(
|
||||
`Added patch info for ${pkgName} (${normalizedEco}): ${patchVerId} for range ${vulnRange}`
|
||||
)
|
||||
} else {
|
||||
core.debug(
|
||||
`No patch version found for ${pkgName} (${normalizedEco}) in ${advId}`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
const errorMessage = e instanceof Error ? e.message : String(e)
|
||||
core.debug(`API call failed for ${advId}: ${errorMessage}`)
|
||||
patchInfo[advId] = []
|
||||
}
|
||||
})
|
||||
|
||||
// Execute API calls with concurrency limit
|
||||
await promisePool(tasks, API_CONCURRENCY_LIMIT)
|
||||
|
||||
core.summary.addHeading('Vulnerabilities', 2)
|
||||
|
||||
for (const manifest of manifests) {
|
||||
// Create fresh rows array for each manifest to avoid accumulation
|
||||
const rows: SummaryTableRow[] = []
|
||||
|
||||
for (const change of vulnerableChanges.filter(
|
||||
pkg => pkg.manifest === manifest
|
||||
)) {
|
||||
@@ -157,33 +388,100 @@ export function addChangeVulnerabilitiesToSummary(
|
||||
previous_package === change.name &&
|
||||
previous_version === change.version
|
||||
|
||||
// Look up patch version by matching package name, ecosystem, and version range
|
||||
let patchVer = 'N/A'
|
||||
const advisoryEntries = patchInfo[vuln.advisory_ghsa_id]
|
||||
if (advisoryEntries && advisoryEntries.length > 0) {
|
||||
const ecoLowercase = change.ecosystem.toLowerCase()
|
||||
const packageLowercase = change.name.toLowerCase()
|
||||
const normalizedChangeVersion = change.version.trim()
|
||||
core.debug(
|
||||
`Looking up patch for ${change.name}@${change.version} (${ecoLowercase}) in ${vuln.advisory_ghsa_id}`
|
||||
)
|
||||
|
||||
// Find matching entry by ecosystem, package name (case-insensitive), and version range
|
||||
// Use pre-normalized values from cache to avoid repeated lowercasing and range conversion
|
||||
let foundEntry:
|
||||
| {eco: string; pkg: string; range: string; patch: string}
|
||||
| undefined
|
||||
for (const vulnEntry of advisoryEntries) {
|
||||
if (vulnEntry.ecoLower !== ecoLowercase) continue
|
||||
if (vulnEntry.pkgLower !== packageLowercase) continue
|
||||
|
||||
// Use fail-open (failClosed: false) for patch selection to avoid
|
||||
// incorrectly matching on invalid ranges
|
||||
// Use preTrimmed and preNormalized optimizations since we've done both
|
||||
const isInRange = versionInRange(
|
||||
normalizedChangeVersion,
|
||||
vulnEntry.normalizedRange,
|
||||
{preTrimmed: true, preNormalized: true, failClosed: false}
|
||||
)
|
||||
|
||||
if (isInRange) {
|
||||
foundEntry = vulnEntry
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (foundEntry) {
|
||||
patchVer = foundEntry.patch
|
||||
core.debug(
|
||||
`Found patch version ${patchVer} for ${change.name}@${change.version}`
|
||||
)
|
||||
} else {
|
||||
const maxLoggedEntries = 5
|
||||
const entriesPreview = advisoryEntries
|
||||
.slice(0, maxLoggedEntries)
|
||||
.map(
|
||||
entry =>
|
||||
`${entry.eco}:${entry.pkg} ${entry.range} -> ${entry.patch}`
|
||||
)
|
||||
core.debug(
|
||||
`No matching patch found for ${change.name}@${change.version}. Available entries (showing up to ${Math.min(advisoryEntries.length, maxLoggedEntries)} of ${advisoryEntries.length}): ${entriesPreview.join('; ')}`
|
||||
)
|
||||
}
|
||||
} else {
|
||||
core.debug(`No advisory data available for ${vuln.advisory_ghsa_id}`)
|
||||
}
|
||||
|
||||
if (!sameAsPrevious) {
|
||||
rows.push([
|
||||
const row: SummaryTableRow = [
|
||||
renderUrl(change.source_repository_url, change.name),
|
||||
change.version,
|
||||
renderUrl(vuln.advisory_url, vuln.advisory_summary),
|
||||
vuln.severity
|
||||
])
|
||||
]
|
||||
if (showPatchedVersions) {
|
||||
row.push(patchVer)
|
||||
}
|
||||
rows.push(row)
|
||||
} else {
|
||||
rows.push([
|
||||
const row: SummaryTableRow = [
|
||||
{data: '', colspan: '2'},
|
||||
renderUrl(vuln.advisory_url, vuln.advisory_summary),
|
||||
vuln.severity
|
||||
])
|
||||
]
|
||||
if (showPatchedVersions) {
|
||||
row.push(patchVer)
|
||||
}
|
||||
rows.push(row)
|
||||
}
|
||||
previous_package = change.name
|
||||
previous_version = change.version
|
||||
}
|
||||
}
|
||||
core.summary.addHeading(`<em>${manifest}</em>`, 4).addTable([
|
||||
[
|
||||
{data: 'Name', header: true},
|
||||
{data: 'Version', header: true},
|
||||
{data: 'Vulnerability', header: true},
|
||||
{data: 'Severity', header: true}
|
||||
],
|
||||
...rows
|
||||
])
|
||||
const headerRow: SummaryTableRow = [
|
||||
{data: 'Name', header: true},
|
||||
{data: 'Version', header: true},
|
||||
{data: 'Vulnerability', header: true},
|
||||
{data: 'Severity', header: true}
|
||||
]
|
||||
if (showPatchedVersions) {
|
||||
headerRow.push({data: 'Patched Version', header: true})
|
||||
}
|
||||
core.summary
|
||||
.addHeading(`<em>${manifest}</em>`, 4)
|
||||
.addTable([headerRow, ...rows])
|
||||
}
|
||||
|
||||
if (severity !== 'low') {
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ export function renderUrl(url: string | null, text: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function isEnterprise(): boolean {
|
||||
export function isEnterprise(): boolean {
|
||||
const serverUrl = new URL(
|
||||
process.env['GITHUB_SERVER_URL'] ?? 'https://github.com'
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user