Compare commits

..

4 Commits

Author SHA1 Message Date
Federico Builes c1ca5596b7 adding build 2024-02-20 18:42:22 +01:00
Federico Builes b10d06b43a revert to previous behavior 2024-02-20 18:35:23 +01:00
Federico Builes 2531a75f65 dont generate output 2024-02-20 18:30:11 +01:00
Federico Builes 11de043a62 PR comments should not be posted by default 2024-02-20 17:54:34 +01:00
19 changed files with 77 additions and 804 deletions
+4 -1
View File
@@ -2,5 +2,8 @@
"name": "Dependency Review Action",
"image": "mcr.microsoft.com/devcontainers/typescript-node:18",
"postCreateCommand": "npm install",
"remoteUser": "node"
"remoteUser": "node",
"features": {
"ghcr.io/devcontainers/features/ruby:1": {}
}
}
+3 -5
View File
@@ -17,12 +17,10 @@ jobs:
with:
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-issue-label: "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
days-before-pr-stale: 180 # when the PR is considered stale
days-before-pr-close: 15 # when the PR is closed by the bot
days-before-issue-stale: 180 # when the issue is considered stale
days-before-issue-close: 15 # when the issue is closed by the bot
days-before-pr-close: 15 # when the PR is closed by the bot,
days-before-issue-stale: 180 # prevents issues from being tagged by the bot
days-before-issue-close: 15 # prevents issues from being closed by the bot
exempt-assignees: 'advanced-security-dependency-graph'
ascending: true
+1 -7
View File
@@ -77,11 +77,9 @@ $ GITHUB_TOKEN=<token> ./scripts/scan_pr --config-file my_custom_config.yml <pr_
Here are a few things you can do that will increase the likelihood of your pull request being accepted:
- Add unit tests for new features.
- Write tests.
- Keep your change as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
- Add examples of the usage to [examples.md](examples.md)
- Link to a sample PR in a custom repository running your version of the Action.
## Cutting a new release
@@ -118,10 +116,6 @@ git tag -fa v4 -m "Updating v4 to 4.0.1"
git push origin v4 --force
```
## 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 [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.
## Resources
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
+3 -24
View File
@@ -77,14 +77,12 @@ Configure this action by either inlining these options in your workflow file, or
| `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 |
| `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. | `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 permission `pull-requests: write`. | `always`, `on-failure`, `never` | `never` |
| `deny-packages` | Any number of packages to block in a PR. | 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 |
| `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-timeout`\* | Maximum amount of time (in seconds) to retry the action while waiting for dependency submission actions to complete. | Any positive integer | 120 |
| `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-levels` | 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 |
\*not supported for use with GitHub Enterprise Server
@@ -152,7 +150,7 @@ For more examples of how to use this action and its configuration options, see t
### Considerations
- Checking for licenses is not supported on Enterprise Server as the API does not return license information.
- The `allow-licenses` and `deny-licenses` options are mutually exclusive; an error will be raised if you provide both.
- The action will only accept one of the two `license` parameters; an error will be raised if you provide both.
- We don't have license information for all of your dependents. If we can't detect the license for a dependency **we will inform you, but the action won't fail**.
## Blocking pull requests
@@ -161,26 +159,7 @@ The Dependency Review GitHub Action check will only block a pull request from be
## Outputs
- `comment-content` is generated with the same content as would be present in a Dependency Review Action comment.
- `dependency-changes` holds all dependency changes in a JSON format. The following outputs are subsets of `dependency-changes` filtered based on the configuration:
- `vulnerable-changes` holds information about dependency changes with vulnerable dependencies in a JSON format.
- `invalid-license-changes` holds information about invalid or non-compliant license dependency changes in a JSON format.
- `denied-changes` holds information about denied dependency changes in a JSON format.
> [!NOTE]
> Action outputs are unicode strings [with a 1MB size limit](https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#outputs-for-docker-container-and-javascript-actions).
> [!IMPORTANT]
> If you use these outputs in a run-step, you must store the ouput data in an envrioment variable instead of using the output directly. Using an output directly might break shell scripts. For example:
>
> ```yaml
> env:
> VULNERABLE_CHANGES: ${{ steps.review.outputs.vulnerable-changes }}
> run: |
> echo "$VULNERABLE_CHANGES" | jq
> ```
>
> instead of direct `echo '${{ steps.review.outputs.vulnerable-changes }}'`. See [examples](docs/examples.md) for more.
`comment-content` is generated with the same content as would be present in a Dependency Review Action comment.
## Getting help
-40
View File
@@ -1,40 +0,0 @@
import {expect, test} from '@jest/globals'
import {Change, Changes} from '../src/schemas'
import {getScorecardLevels, getProjectUrl} from '../src/scorecard'
const npmChange: Change = {
manifest: 'package.json',
change_type: 'added',
ecosystem: 'npm',
name: 'type-is',
version: '1.6.18',
package_url: 'pkg:npm/type-is@1.6.18',
license: 'MIT',
source_repository_url: 'github.com/jshttp/type-is',
scope: 'runtime',
vulnerabilities: [
{
severity: 'critical',
advisory_ghsa_id: 'first-random_string',
advisory_summary: 'very dangerous',
advisory_url: 'github.com/future-funk'
}
]
}
test('Get scorecard from API', async () => {
const changes: Changes = [npmChange]
const scorecard = await getScorecardLevels(changes)
expect(scorecard).not.toBeNull()
expect(scorecard.dependencies).toHaveLength(1)
expect(scorecard.dependencies[0].scorecard?.score).toBeGreaterThan(0)
})
test('Get project URL from deps.dev API', async () => {
const result = await getProjectUrl(
npmChange.ecosystem,
npmChange.name,
npmChange.version
)
expect(result).not.toBeNull()
})
+2 -36
View File
@@ -1,5 +1,5 @@
import {expect, jest, test} from '@jest/globals'
import {Changes, ConfigurationOptions, Scorecard} from '../src/schemas'
import {Changes, ConfigurationOptions} from '../src/schemas'
import * as summary from '../src/summary'
import * as core from '@actions/core'
import {createTestChange} from './fixtures/create-test-change'
@@ -16,9 +16,6 @@ const emptyInvalidLicenseChanges = {
unresolved: [],
unlicensed: []
}
const emptyScorecard: Scorecard = {
dependencies: []
}
const defaultConfig: ConfigurationOptions = {
vulnerability_check: true,
license_check: true,
@@ -32,9 +29,7 @@ const defaultConfig: ConfigurationOptions = {
comment_summary_in_pr: true,
retry_on_snapshot_warnings: false,
retry_on_snapshot_warnings_timeout: 120,
warn_only: false,
warn_on_openssf_scorecard_level: 3,
show_openssf_scorecard: false
warn_only: false
}
const changesWithEmptyManifests: Changes = [
@@ -76,32 +71,11 @@ const changesWithEmptyManifests: Changes = [
}
]
const scorecard: Scorecard = {
dependencies: [
{
change: {
change_type: 'added',
manifest: '',
ecosystem: 'unknown',
name: 'castore',
version: '0.1.17',
package_url: 'pkg:hex/castore@0.1.17',
license: null,
source_repository_url: null,
scope: 'runtime',
vulnerabilities: []
},
scorecard: null
}
]
}
test('prints headline as h1', () => {
summary.addSummaryToSummary(
emptyChanges,
emptyInvalidLicenseChanges,
emptyChanges,
scorecard,
defaultConfig
)
const text = core.summary.stringify()
@@ -114,7 +88,6 @@ test('only includes "No vulnerabilities or license issues found"-message if both
emptyChanges,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
defaultConfig
)
const text = core.summary.stringify()
@@ -128,7 +101,6 @@ test('only includes "No vulnerabilities found"-message if "license_check" is set
emptyChanges,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
config
)
const text = core.summary.stringify()
@@ -142,7 +114,6 @@ test('only includes "No license issues found"-message if "vulnerability_check" i
emptyChanges,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
config
)
const text = core.summary.stringify()
@@ -155,7 +126,6 @@ test('groups dependencies with empty manifest paths together', () => {
changesWithEmptyManifests,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
defaultConfig
)
summary.addScannedDependencies(changesWithEmptyManifests)
@@ -173,7 +143,6 @@ test('does not include status section if nothing was found', () => {
emptyChanges,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
defaultConfig
)
const text = core.summary.stringify()
@@ -196,7 +165,6 @@ test('includes count and status icons for all findings', () => {
vulnerabilities,
licenseIssues,
emptyChanges,
emptyScorecard,
defaultConfig
)
@@ -216,7 +184,6 @@ test('uses checkmarks for license issues if only vulnerabilities were found', ()
vulnerabilities,
emptyInvalidLicenseChanges,
emptyChanges,
emptyScorecard,
defaultConfig
)
@@ -240,7 +207,6 @@ test('uses checkmarks for vulnerabilities if only license issues were found', ()
emptyChanges,
licenseIssues,
emptyChanges,
emptyScorecard,
defaultConfig
)
-16
View File
@@ -65,25 +65,9 @@ inputs:
description: When set to `true` this action will always complete with success, overriding the `fail-on-severity` parameter.
required: false
default: false
show-openssf-scorecard:
description: Show a summary of the OpenSSF Scorecard scores.
required: false
default: true
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
default: 3
outputs:
comment-content:
description: Prepared dependency report comment
dependency-changes:
description: All dependency changes (JSON)
vulnerable-changes:
description: Vulnerable dependency changes (JSON)
invalid-license-changes:
description: Invalid license dependency changes (JSON)
denied-changes:
description: Denied dependency changes (JSON)
runs:
using: 'node20'
Generated Vendored
+20 -311
View File
@@ -56,15 +56,10 @@ const retryingOctokit = githubUtils.GitHub.plugin(retry.retry);
const octo = new retryingOctokit(githubUtils.getOctokitOptions(core.getInput('repo-token', { required: true })));
// Comment Marker to identify an existing comment to update, so we don't spam the PR with comments
const COMMENT_MARKER = '<!-- dependency-review-pr-comment-marker -->';
function commentPr(summary, config) {
function commentPr(summary) {
return __awaiter(this, void 0, void 0, function* () {
const commentContent = summary.stringify();
core.setOutput('comment-content', commentContent);
if (!(config.comment_summary_in_pr === 'always' ||
(config.comment_summary_in_pr === 'on-failure' &&
process.exitCode === core.ExitCode.Failure))) {
return;
}
if (!github.context.payload.pull_request) {
core.warning('Not in the context of a pull request. Skipping comment creation.');
return;
@@ -565,7 +560,6 @@ const request_error_1 = __nccwpck_require__(537);
const config_1 = __nccwpck_require__(6373);
const filter_1 = __nccwpck_require__(134);
const licenses_1 = __nccwpck_require__(3247);
const scorecard_1 = __nccwpck_require__(307);
const summary = __importStar(__nccwpck_require__(8608));
const git_refs_1 = __nccwpck_require__(1086);
const utils_1 = __nccwpck_require__(918);
@@ -636,35 +630,29 @@ function run() {
core.debug(`Filtered Changes: ${JSON.stringify(filteredChanges)}`);
core.debug(`Config Deny Packages: ${JSON.stringify(config)}`);
const deniedChanges = yield (0, deny_1.getDeniedChanges)(filteredChanges, config.deny_packages, config.deny_groups);
const scorecard = yield (0, scorecard_1.getScorecardLevels)(filteredChanges);
summary.addSummaryToSummary(vulnerableChanges, invalidLicenseChanges, deniedChanges, scorecard, config);
summary.addSummaryToSummary(vulnerableChanges, invalidLicenseChanges, deniedChanges, config);
if (snapshot_warnings) {
summary.addSnapshotWarnings(config, snapshot_warnings);
}
if (config.vulnerability_check) {
core.setOutput('vulnerable-changes', JSON.stringify(vulnerableChanges));
summary.addChangeVulnerabilitiesToSummary(vulnerableChanges, minSeverity);
printVulnerabilitiesBlock(vulnerableChanges, minSeverity, warnOnly);
}
if (config.license_check) {
core.setOutput('invalid-license-changes', JSON.stringify(invalidLicenseChanges));
summary.addLicensesToSummary(invalidLicenseChanges, config);
printLicensesBlock(invalidLicenseChanges, warnOnly);
}
if (config.deny_packages || config.deny_groups) {
core.setOutput('denied-changes', JSON.stringify(deniedChanges));
summary.addDeniedToSummary(deniedChanges);
printDeniedDependencies(deniedChanges, config);
}
if (config.show_openssf_scorecard) {
summary.addScorecardToSummary(scorecard, config);
printScorecardBlock(scorecard, config);
createScorecardWarnings(scorecard, config);
}
core.setOutput('dependency-changes', JSON.stringify(changes));
summary.addScannedDependencies(changes);
printScannedDependencies(changes);
yield (0, comment_pr_1.commentPr)(core.summary, config);
if (config.comment_summary_in_pr === 'always' ||
(config.comment_summary_in_pr === 'on-failure' &&
process.exitCode === core.ExitCode.Failure)) {
yield (0, comment_pr_1.commentPr)(core.summary);
}
}
catch (error) {
if (error instanceof request_error_1.RequestError && error.status === 404) {
@@ -751,20 +739,6 @@ function printNullLicenses(changes) {
core.info(`${ansi_styles_1.default.bold.open}${change.manifest} » ${change.name}@${change.version}${ansi_styles_1.default.bold.close}`);
}
}
function printScorecardBlock(scorecard, config) {
core.group('Scorecard', () => __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d;
if (scorecard) {
for (const dependency of scorecard.dependencies) {
if (((_a = dependency.scorecard) === null || _a === void 0 ? void 0 : _a.score) &&
((_b = dependency.scorecard) === null || _b === void 0 ? void 0 : _b.score) < config.warn_on_openssf_scorecard_level) {
core.info(`${ansi_styles_1.default.color.red.open}${dependency.change.ecosystem}/${dependency.change.name}: OpenSSF Scorecard Score: ${(_c = dependency === null || dependency === void 0 ? void 0 : dependency.scorecard) === null || _c === void 0 ? void 0 : _c.score}${ansi_styles_1.default.red.close}`);
}
core.info(`${dependency.change.ecosystem}/${dependency.change.name}: OpenSSF Scorecard Score: ${(_d = dependency === null || dependency === void 0 ? void 0 : dependency.scorecard) === null || _d === void 0 ? void 0 : _d.score}`);
}
}
}));
}
function renderSeverity(severity) {
const color = {
critical: 'red',
@@ -812,20 +786,6 @@ function printDeniedDependencies(changes, config) {
}
}));
}
function createScorecardWarnings(scorecards, config) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
// Iterate through the list of scorecards, and if the score is less than the threshold, send a warning
for (const dependency of scorecards.dependencies) {
if (((_a = dependency.scorecard) === null || _a === void 0 ? void 0 : _a.score) &&
((_b = dependency.scorecard) === null || _b === void 0 ? void 0 : _b.score) < config.warn_on_openssf_scorecard_level) {
core.warning(`${dependency.change.ecosystem}/${dependency.change.name} has an OpenSSF Scorecard of ${(_c = dependency.scorecard) === null || _c === void 0 ? void 0 : _c.score}, which is less than this repository's threshold of ${config.warn_on_openssf_scorecard_level}.`, {
title: 'OpenSSF Scorecard Warning'
});
}
}
});
}
run();
@@ -860,7 +820,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ScorecardSchema = exports.ScorecardApiSchema = exports.ComparisonResponseSchema = exports.ChangesSchema = exports.ConfigurationOptionsSchema = exports.PullRequestSchema = exports.ChangeSchema = exports.SeveritySchema = exports.SCOPES = exports.SEVERITIES = void 0;
exports.ComparisonResponseSchema = exports.ChangesSchema = exports.ConfigurationOptionsSchema = exports.PullRequestSchema = exports.ChangeSchema = exports.SeveritySchema = exports.SCOPES = exports.SEVERITIES = void 0;
const z = __importStar(__nccwpck_require__(3301));
exports.SEVERITIES = ['critical', 'high', 'moderate', 'low'];
exports.SCOPES = ['unknown', 'runtime', 'development'];
@@ -907,8 +867,6 @@ exports.ConfigurationOptionsSchema = z
head_ref: z.string().optional(),
retry_on_snapshot_warnings: z.boolean().default(false),
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),
comment_summary_in_pr: z
.union([
z.preprocess(val => (val === 'true' ? true : val === 'false' ? false : val), z.boolean()),
@@ -952,152 +910,6 @@ exports.ComparisonResponseSchema = z.object({
changes: z.array(exports.ChangeSchema),
snapshot_warnings: z.string()
});
exports.ScorecardApiSchema = z.object({
date: z.string(),
repo: z
.object({
name: z.string(),
commit: z.string()
})
.nullish(),
scorecard: z
.object({
version: z.string(),
commit: z.string()
})
.nullish(),
checks: z
.array(z.object({
name: z.string(),
documentation: z.object({
shortDescription: z.string(),
url: z.string()
}),
score: z.string(),
reason: z.string(),
details: z.array(z.string())
}))
.nullish(),
score: z.number().nullish()
});
exports.ScorecardSchema = z.object({
dependencies: z.array(z.object({
change: exports.ChangeSchema,
scorecard: exports.ScorecardApiSchema.nullish()
}))
});
/***/ }),
/***/ 307:
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getProjectUrl = exports.getScorecardLevels = void 0;
const core = __importStar(__nccwpck_require__(2186));
function getScorecardLevels(changes) {
return __awaiter(this, void 0, void 0, function* () {
const data = { dependencies: [] };
for (const change of changes) {
const ecosystem = change.ecosystem;
const packageName = change.name;
const version = change.version;
//Get the project repository
let repositoryUrl = change.source_repository_url;
//If the repository_url includes the protocol, remove it
if (repositoryUrl === null || repositoryUrl === void 0 ? void 0 : repositoryUrl.startsWith('https://')) {
repositoryUrl = repositoryUrl.replace('https://', '');
}
// If GitHub API doesn't have the repository URL, query deps.dev for it.
if (repositoryUrl) {
// Call the deps.dev API to get the repository URL from there
repositoryUrl = yield getProjectUrl(ecosystem, packageName, version);
}
// Get the scorecard API response from the scorecards API
let scorecardApi = null;
if (repositoryUrl) {
try {
scorecardApi = yield getScorecard(repositoryUrl);
}
catch (error) {
core.debug(`Error querying for scorecard: ${error.message}`);
}
}
data.dependencies.push({
change,
scorecard: scorecardApi
});
}
return data;
});
}
exports.getScorecardLevels = getScorecardLevels;
function getScorecard(repositoryUrl) {
return __awaiter(this, void 0, void 0, function* () {
const apiRoot = 'https://api.securityscorecards.dev/';
let scorecardResponse = {};
const url = `${apiRoot}/projects/${repositoryUrl}`;
const response = yield fetch(url);
if (response.ok) {
scorecardResponse = yield response.json();
}
else {
core.debug(`Couldn't get scorecard data for ${repositoryUrl}`);
}
return scorecardResponse;
});
}
function getProjectUrl(ecosystem, packageName, version) {
return __awaiter(this, void 0, void 0, function* () {
core.debug(`Getting deps.dev data for ${packageName} ${version}`);
const depsDevAPIRoot = 'https://api.deps.dev';
const url = `${depsDevAPIRoot}/v3alpha/systems/${ecosystem}/packages/${packageName}/versions/${version}`;
const response = yield fetch(url);
if (response.ok) {
const data = yield response.json();
if (data.relatedProjects.length > 0) {
return data.relatedProjects[0].projectKey.id;
}
}
return '';
});
}
exports.getProjectUrl = getProjectUrl;
/***/ }),
@@ -1131,7 +943,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.addDeniedToSummary = exports.addSnapshotWarnings = exports.addScorecardToSummary = exports.addScannedDependencies = exports.addLicensesToSummary = exports.addChangeVulnerabilitiesToSummary = exports.addSummaryToSummary = void 0;
exports.addDeniedToSummary = exports.addSnapshotWarnings = exports.addScannedDependencies = exports.addLicensesToSummary = exports.addChangeVulnerabilitiesToSummary = exports.addSummaryToSummary = void 0;
const core = __importStar(__nccwpck_require__(2186));
const utils_1 = __nccwpck_require__(918);
const icons = {
@@ -1139,24 +951,19 @@ const icons = {
cross: '❌',
warning: '⚠️'
};
function addSummaryToSummary(vulnerableChanges, invalidLicenseChanges, deniedChanges, scorecard, config) {
const scorecardWarnings = countScorecardWarnings(scorecard, config);
const licenseIssues = countLicenseIssues(invalidLicenseChanges);
function addSummaryToSummary(vulnerableChanges, invalidLicenseChanges, deniedChanges, config) {
core.summary.addHeading('Dependency Review', 1);
if (vulnerableChanges.length === 0 &&
licenseIssues === 0 &&
deniedChanges.length === 0 &&
scorecardWarnings === 0) {
const issueTypes = [
config.vulnerability_check ? 'vulnerabilities' : '',
config.license_check ? 'license issues' : '',
config.show_openssf_scorecard ? 'OpenSSF Scorecard issues' : ''
];
if (issueTypes.filter(Boolean).length === 0) {
core.summary.addRaw(`${icons.check} No issues found.`);
countLicenseIssues(invalidLicenseChanges) === 0 &&
deniedChanges.length === 0) {
if (!config.license_check) {
core.summary.addRaw(`${icons.check} No vulnerabilities found.`);
}
else if (!config.vulnerability_check) {
core.summary.addRaw(`${icons.check} No license issues found.`);
}
else {
core.summary.addRaw(`${icons.check} No ${issueTypes.filter(Boolean).join(' or ')} found.`);
core.summary.addRaw(`${icons.check} No vulnerabilities or license issues found.`);
}
return;
}
@@ -1179,26 +986,11 @@ function addSummaryToSummary(vulnerableChanges, invalidLicenseChanges, deniedCha
? [
`${checkOrWarnIcon(deniedChanges.length)} ${deniedChanges.length} package(s) denied.`
]
: []),
...(config.show_openssf_scorecard && scorecardWarnings > 0
? [
`${checkOrWarnIcon(scorecardWarnings)} ${scorecardWarnings ? scorecardWarnings : 'No'} packages with OpenSSF Scorecard issues.`
]
: [])
])
.addRaw('See the Details below.');
}
exports.addSummaryToSummary = addSummaryToSummary;
function countScorecardWarnings(scorecard, config) {
return scorecard.dependencies.reduce((total, dependency) => {
var _a, _b;
return total +
(((_a = dependency.scorecard) === null || _a === void 0 ? void 0 : _a.score) &&
((_b = dependency.scorecard) === null || _b === void 0 ? void 0 : _b.score) < config.warn_on_openssf_scorecard_level
? 1
: 0);
}, 0);
}
function addChangeVulnerabilitiesToSummary(vulnerableChanges, severity) {
if (vulnerableChanges.length === 0) {
return;
@@ -1332,49 +1124,6 @@ function snapshotWarningRecommendation(config, warnings) {
}
return 'Re-running this action after a short time may resolve the issue.';
}
function addScorecardToSummary(scorecard, config) {
var _a, _b, _c, _d, _e, _f, _g, _h;
core.summary.addHeading('OpenSSF Scorecard', 2);
if (scorecard.dependencies.length > 10) {
core.summary.addRaw(`<details><summary>Scorecard details</summary>`, true);
}
core.summary.addRaw(`<table><tr><th>Package</th><th>Version</th><th>Score</th><th>Details</th></tr>`, true);
for (const dependency of scorecard.dependencies) {
core.debug('Adding scorecard to summary');
core.debug(`Overall score ${(_a = dependency.scorecard) === null || _a === void 0 ? void 0 : _a.score}`);
// Set the icon based on the overall score value
let overallIcon = '';
if ((_b = dependency.scorecard) === null || _b === void 0 ? void 0 : _b.score) {
overallIcon =
((_c = dependency.scorecard) === null || _c === void 0 ? void 0 : _c.score) < config.warn_on_openssf_scorecard_level
? ':warning:'
: ':green_circle:';
}
//Add a row for the dependency
core.summary.addRaw(`<tr><td>${dependency.change.source_repository_url ? `<a href="https://${dependency.change.source_repository_url}">` : ''} ${dependency.change.ecosystem}/${dependency.change.name} ${dependency.change.source_repository_url ? `</a>` : ''}</td><td>${dependency.change.version}</td>
<td>${overallIcon} ${((_d = dependency.scorecard) === null || _d === void 0 ? void 0 : _d.score) === undefined || ((_e = dependency.scorecard) === null || _e === void 0 ? void 0 : _e.score) === null ? 'Unknown' : (_f = dependency.scorecard) === null || _f === void 0 ? void 0 : _f.score}</td>`, false);
//Add details table in the last column
if (((_g = dependency.scorecard) === null || _g === void 0 ? void 0 : _g.checks) !== undefined) {
let detailsTable = '<table><tr><th>Check</th><th>Score</th><th>Reason</th></tr>';
for (const check of ((_h = dependency.scorecard) === null || _h === void 0 ? void 0 : _h.checks) || []) {
const icon = parseFloat(check.score) < config.warn_on_openssf_scorecard_level
? ':warning:'
: ':green_circle:';
detailsTable += `<tr><td>${check.name}</td><td>${icon} ${check.score}</td><td>${check.reason}</td></tr>`;
}
detailsTable += `</table>`;
core.summary.addRaw(`<td><details><summary>Details</summary>${detailsTable}</details></td></tr>`, true);
}
else {
core.summary.addRaw('<td>Unknown</td></tr>', true);
}
}
core.summary.addRaw(`</table>`);
if (scorecard.dependencies.length > 10) {
core.summary.addRaw(`</details>`);
}
}
exports.addScorecardToSummary = addScorecardToSummary;
function addSnapshotWarnings(config, warnings) {
core.summary.addHeading('Snapshot Warnings', 2);
core.summary.addQuote(`${icons.warning}: ${warnings}`);
@@ -49738,8 +49487,6 @@ function readInlineConfig() {
const retry_on_snapshot_warnings = getOptionalBoolean('retry-on-snapshot-warnings');
const retry_on_snapshot_warnings_timeout = getOptionalNumber('retry-on-snapshot-warnings-timeout');
const warn_only = getOptionalBoolean('warn-only');
const show_openssf_scorecard = getOptionalBoolean('show-openssf-scorecard');
const warn_on_openssf_scorecard_level = getOptionalNumber('warn-on-openssf-scorecard-level');
validatePURL(allow_dependencies_licenses);
validateLicenses('allow-licenses', allow_licenses);
validateLicenses('deny-licenses', deny_licenses);
@@ -49759,9 +49506,7 @@ function readInlineConfig() {
comment_summary_in_pr,
retry_on_snapshot_warnings,
retry_on_snapshot_warnings_timeout,
warn_only,
show_openssf_scorecard,
warn_on_openssf_scorecard_level
warn_only
};
return Object.fromEntries(Object.entries(keys).filter(([_, value]) => value !== undefined));
}
@@ -50012,7 +49757,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ScorecardSchema = exports.ScorecardApiSchema = exports.ComparisonResponseSchema = exports.ChangesSchema = exports.ConfigurationOptionsSchema = exports.PullRequestSchema = exports.ChangeSchema = exports.SeveritySchema = exports.SCOPES = exports.SEVERITIES = void 0;
exports.ComparisonResponseSchema = exports.ChangesSchema = exports.ConfigurationOptionsSchema = exports.PullRequestSchema = exports.ChangeSchema = exports.SeveritySchema = exports.SCOPES = exports.SEVERITIES = void 0;
const z = __importStar(__nccwpck_require__(3301));
exports.SEVERITIES = ['critical', 'high', 'moderate', 'low'];
exports.SCOPES = ['unknown', 'runtime', 'development'];
@@ -50059,8 +49804,6 @@ exports.ConfigurationOptionsSchema = z
head_ref: z.string().optional(),
retry_on_snapshot_warnings: z.boolean().default(false),
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),
comment_summary_in_pr: z
.union([
z.preprocess(val => (val === 'true' ? true : val === 'false' ? false : val), z.boolean()),
@@ -50104,40 +49847,6 @@ exports.ComparisonResponseSchema = z.object({
changes: z.array(exports.ChangeSchema),
snapshot_warnings: z.string()
});
exports.ScorecardApiSchema = z.object({
date: z.string(),
repo: z
.object({
name: z.string(),
commit: z.string()
})
.nullish(),
scorecard: z
.object({
version: z.string(),
commit: z.string()
})
.nullish(),
checks: z
.array(z.object({
name: z.string(),
documentation: z.object({
shortDescription: z.string(),
url: z.string()
}),
score: z.string(),
reason: z.string(),
details: z.array(z.string())
}))
.nullish(),
score: z.number().nullish()
});
exports.ScorecardSchema = z.object({
dependencies: z.array(z.object({
change: exports.ChangeSchema,
scorecard: exports.ScorecardApiSchema.nullish()
}))
});
/***/ }),
Generated Vendored
+1 -1
View File
File diff suppressed because one or more lines are too long
+5 -14
View File
@@ -166,8 +166,7 @@ jobs:
## Getting the results of the action in a later step
- `comment-content` contains the output of the results comment for the entire run.
`dependency-changes`, `vulnerable-changes`, `invalid-license-changes` and `denied-changes` are all JSON objects that allow you to access individual sets of changes.
Using the `comment-content` output you can get the results of the action in a workflow step.
```yaml
name: 'Dependency Review'
@@ -193,18 +192,10 @@ jobs:
# make sure this step runs even if the previous failed
if: ${{ failure() && steps.review.conclusion == 'failure' }}
shell: bash
env: # store comment HTML data in an environment variable
COMMENT: ${{ steps.review.outputs.comment-content }}
run: | # do something with the comment:
echo "$COMMENT"
- name: 'List vulnerable dependencies'
# make sure this step runs even if the previous failed
if: ${{ failure() && steps.review.conclusion == 'failure' }}
shell: bash
env: # store JSON data in an environment variable
VULNERABLE_CHANGES: ${{ steps.review.outputs.vulnerable-changes }}
run: | # do something with the JSON:
echo "$VULNERABLE_CHANGES" | jq '.[].package_url'
env:
comment: ${{ steps.review.outputs.comment-content }}
run: |
echo "$comment" # do something with the comment
```
## Exclude dependencies from the license check
+14 -14
View File
@@ -1,12 +1,12 @@
{
"name": "dependency-review-action",
"version": "4.2.3",
"version": "4.1.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dependency-review-action",
"version": "4.2.3",
"version": "4.1.2",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.1",
@@ -35,10 +35,10 @@
"esbuild-register": "^3.5.0",
"eslint": "^8.56.0",
"eslint-plugin-github": "^4.10.1",
"eslint-plugin-jest": "^27.9.0",
"eslint-plugin-jest": "^27.6.3",
"eslint-plugin-prettier": "^5.1.3",
"js-yaml": "^4.1.0",
"nodemon": "^3.1.0",
"nodemon": "^3.0.3",
"prettier": "3.2.5",
"typescript": "^5.3.3"
}
@@ -2089,9 +2089,9 @@
}
},
"node_modules/@types/node": {
"version": "20.11.28",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.28.tgz",
"integrity": "sha512-M/GPWVS2wLkSkNHVeLkrF2fD5Lx5UC4PxA0uZcKc6QqbIQUJyW1jVjueJYi1z8n0I5PxYrtpnPnWglE+y9A0KA==",
"version": "20.11.19",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.19.tgz",
"integrity": "sha512-7xMnVEcZFu0DikYjWOlRq7NTPETrm7teqUT2WkQjrTIkEgUyyGdWsj/Zg8bEJt5TNklzbPD1X3fqfsHw3SpapQ==",
"dependencies": {
"undici-types": "~5.26.4"
}
@@ -3811,9 +3811,9 @@
}
},
"node_modules/eslint-plugin-jest": {
"version": "27.9.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.9.0.tgz",
"integrity": "sha512-QIT7FH7fNmd9n4se7FFKHbsLKGQiw885Ds6Y/sxKgCZ6natwCsXdgPOADnYVxN2QrRweF0FZWbJ6S7Rsn7llug==",
"version": "27.6.3",
"resolved": "https://registry.npmjs.org/eslint-plugin-jest/-/eslint-plugin-jest-27.6.3.tgz",
"integrity": "sha512-+YsJFVH6R+tOiO3gCJon5oqn4KWc+mDq2leudk8mrp8RFubLOo9CVyi3cib4L7XMpxExmkmBZQTPDYVBzgpgOA==",
"dev": true,
"dependencies": {
"@typescript-eslint/utils": "^5.10.0"
@@ -3822,7 +3822,7 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"peerDependencies": {
"@typescript-eslint/eslint-plugin": "^5.0.0 || ^6.0.0 || ^7.0.0",
"@typescript-eslint/eslint-plugin": "^5.0.0 || ^6.0.0",
"eslint": "^7.0.0 || ^8.0.0",
"jest": "*"
},
@@ -6144,9 +6144,9 @@
"integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ=="
},
"node_modules/nodemon": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz",
"integrity": "sha512-xqlktYlDMCepBJd43ZQhjWwMw2obW/JRvkrLxq5RCNcuDDX1DbcPT+qT1IlIIdf+DhnWs90JpTMe+Y5KxOchvA==",
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.3.tgz",
"integrity": "sha512-7jH/NXbFPxVaMwmBCC2B9F/V6X1VkEdNgx3iu9jji8WxWcvhMWkmhNWhI5077zknOnZnBzba9hZP6bCPJLSReQ==",
"dev": true,
"dependencies": {
"chokidar": "^3.5.2",
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "dependency-review-action",
"version": "4.2.3",
"version": "4.1.2",
"private": true,
"description": "A GitHub Action for Dependency Review",
"main": "lib/main.js",
@@ -51,10 +51,10 @@
"esbuild-register": "^3.5.0",
"eslint": "^8.56.0",
"eslint-plugin-github": "^4.10.1",
"eslint-plugin-jest": "^27.9.0",
"eslint-plugin-jest": "^27.6.3",
"eslint-plugin-prettier": "^5.1.3",
"js-yaml": "^4.1.0",
"nodemon": "^3.1.0",
"nodemon": "^3.0.3",
"prettier": "3.2.5",
"typescript": "^5.3.3"
}
+3 -31
View File
@@ -6,7 +6,7 @@
* npx ts-node scripts/create_summary.ts
*/
import {Change, Changes, ConfigurationOptions, Scorecard} from '../src/schemas'
import {Change, Changes, ConfigurationOptions} from '../src/schemas'
import {createTestChange} from '../__tests__/fixtures/create-test-change'
import {InvalidLicenseChanges} from '../src/licenses'
import * as fs from 'fs'
@@ -33,29 +33,7 @@ const defaultConfig: ConfigurationOptions = {
comment_summary_in_pr: true,
retry_on_snapshot_warnings: false,
retry_on_snapshot_warnings_timeout: 120,
warn_only: false,
warn_on_openssf_scorecard_level: 3,
show_openssf_scorecard: true
}
const scorecard: Scorecard = {
dependencies: [
{
change: {
change_type: 'added',
manifest: '',
ecosystem: 'unknown',
name: 'castore',
version: '0.1.17',
package_url: 'pkg:hex/castore@0.1.17',
license: null,
source_repository_url: null,
scope: 'runtime',
vulnerabilities: []
},
scorecard: null
}
]
warn_only: false
}
const tmpDir = path.resolve(__dirname, '../tmp')
@@ -123,13 +101,7 @@ async function createSummary(
config: ConfigurationOptions,
fileName: string
): Promise<void> {
summary.addSummaryToSummary(
vulnerabilities,
licenseIssues,
denied,
scorecard,
config
)
summary.addSummaryToSummary(vulnerabilities, licenseIssues, denied, config)
summary.addChangeVulnerabilitiesToSummary(
vulnerabilities,
config.fail_on_severity
+1 -15
View File
@@ -3,7 +3,6 @@ import * as core from '@actions/core'
import * as githubUtils from '@actions/github/lib/utils'
import * as retry from '@octokit/plugin-retry'
import {RequestError} from '@octokit/request-error'
import {ConfigurationOptions} from './schemas'
const retryingOctokit = githubUtils.GitHub.plugin(retry.retry)
const octo = new retryingOctokit(
@@ -13,24 +12,11 @@ const octo = new retryingOctokit(
// Comment Marker to identify an existing comment to update, so we don't spam the PR with comments
const COMMENT_MARKER = '<!-- dependency-review-pr-comment-marker -->'
export async function commentPr(
summary: typeof core.summary,
config: ConfigurationOptions
): Promise<void> {
export async function commentPr(summary: typeof core.summary): Promise<void> {
const commentContent = summary.stringify()
core.setOutput('comment-content', commentContent)
if (
!(
config.comment_summary_in_pr === 'always' ||
(config.comment_summary_in_pr === 'on-failure' &&
process.exitCode === core.ExitCode.Failure)
)
) {
return
}
if (!github.context.payload.pull_request) {
core.warning(
'Not in the context of a pull request. Skipping comment creation.'
+1 -7
View File
@@ -48,10 +48,6 @@ function readInlineConfig(): ConfigurationOptionsPartial {
'retry-on-snapshot-warnings-timeout'
)
const warn_only = getOptionalBoolean('warn-only')
const show_openssf_scorecard = getOptionalBoolean('show-openssf-scorecard')
const warn_on_openssf_scorecard_level = getOptionalNumber(
'warn-on-openssf-scorecard-level'
)
validatePURL(allow_dependencies_licenses)
validateLicenses('allow-licenses', allow_licenses)
@@ -73,9 +69,7 @@ function readInlineConfig(): ConfigurationOptionsPartial {
comment_summary_in_pr,
retry_on_snapshot_warnings,
retry_on_snapshot_warnings_timeout,
warn_only,
show_openssf_scorecard,
warn_on_openssf_scorecard_level
warn_only
}
return Object.fromEntries(
+8 -67
View File
@@ -3,13 +3,7 @@ import * as dependencyGraph from './dependency-graph'
import * as github from '@actions/github'
import styles from 'ansi-styles'
import {RequestError} from '@octokit/request-error'
import {
Change,
Severity,
Changes,
ConfigurationOptions,
Scorecard
} from './schemas'
import {Change, Severity, Changes, ConfigurationOptions} from './schemas'
import {readConfig} from '../src/config'
import {
filterChangesBySeverity,
@@ -17,7 +11,6 @@ import {
filterAllowedAdvisories
} from '../src/filter'
import {getInvalidLicenseChanges} from './licenses'
import {getScorecardLevels} from './scorecard'
import * as summary from './summary'
import {getRefs} from './git-refs'
@@ -125,13 +118,10 @@ async function run(): Promise<void> {
config.deny_groups
)
const scorecard = await getScorecardLevels(filteredChanges)
summary.addSummaryToSummary(
vulnerableChanges,
invalidLicenseChanges,
deniedChanges,
scorecard,
config
)
@@ -140,33 +130,27 @@ async function run(): Promise<void> {
}
if (config.vulnerability_check) {
core.setOutput('vulnerable-changes', JSON.stringify(vulnerableChanges))
summary.addChangeVulnerabilitiesToSummary(vulnerableChanges, minSeverity)
printVulnerabilitiesBlock(vulnerableChanges, minSeverity, warnOnly)
}
if (config.license_check) {
core.setOutput(
'invalid-license-changes',
JSON.stringify(invalidLicenseChanges)
)
summary.addLicensesToSummary(invalidLicenseChanges, config)
printLicensesBlock(invalidLicenseChanges, warnOnly)
}
if (config.deny_packages || config.deny_groups) {
core.setOutput('denied-changes', JSON.stringify(deniedChanges))
summary.addDeniedToSummary(deniedChanges)
printDeniedDependencies(deniedChanges, config)
}
if (config.show_openssf_scorecard) {
summary.addScorecardToSummary(scorecard, config)
printScorecardBlock(scorecard, config)
createScorecardWarnings(scorecard, config)
}
core.setOutput('dependency-changes', JSON.stringify(changes))
summary.addScannedDependencies(changes)
printScannedDependencies(changes)
await commentPr(core.summary, config)
if (
config.comment_summary_in_pr === 'always' ||
(config.comment_summary_in_pr === 'on-failure' &&
process.exitCode === core.ExitCode.Failure)
) {
await commentPr(core.summary)
}
} catch (error) {
if (error instanceof RequestError && error.status === 404) {
core.setFailed(
@@ -279,29 +263,6 @@ function printNullLicenses(changes: Changes): void {
}
}
function printScorecardBlock(
scorecard: Scorecard,
config: ConfigurationOptions
): void {
core.group('Scorecard', async () => {
if (scorecard) {
for (const dependency of scorecard.dependencies) {
if (
dependency.scorecard?.score &&
dependency.scorecard?.score < config.warn_on_openssf_scorecard_level
) {
core.info(
`${styles.color.red.open}${dependency.change.ecosystem}/${dependency.change.name}: OpenSSF Scorecard Score: ${dependency?.scorecard?.score}${styles.red.close}`
)
}
core.info(
`${dependency.change.ecosystem}/${dependency.change.name}: OpenSSF Scorecard Score: ${dependency?.scorecard?.score}`
)
}
}
})
}
function renderSeverity(
severity: 'critical' | 'high' | 'moderate' | 'low'
): string {
@@ -370,24 +331,4 @@ function printDeniedDependencies(
})
}
async function createScorecardWarnings(
scorecards: Scorecard,
config: ConfigurationOptions
): Promise<void> {
// Iterate through the list of scorecards, and if the score is less than the threshold, send a warning
for (const dependency of scorecards.dependencies) {
if (
dependency.scorecard?.score &&
dependency.scorecard?.score < config.warn_on_openssf_scorecard_level
) {
core.warning(
`${dependency.change.ecosystem}/${dependency.change.name} has an OpenSSF Scorecard of ${dependency.scorecard?.score}, which is less than this repository's threshold of ${config.warn_on_openssf_scorecard_level}.`,
{
title: 'OpenSSF Scorecard Warning'
}
)
}
}
}
run()
-44
View File
@@ -51,8 +51,6 @@ export const ConfigurationOptionsSchema = z
head_ref: z.string().optional(),
retry_on_snapshot_warnings: z.boolean().default(false),
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),
comment_summary_in_pr: z
.union([
z.preprocess(
@@ -102,51 +100,9 @@ export const ComparisonResponseSchema = z.object({
snapshot_warnings: z.string()
})
export const ScorecardApiSchema = z.object({
date: z.string(),
repo: z
.object({
name: z.string(),
commit: z.string()
})
.nullish(),
scorecard: z
.object({
version: z.string(),
commit: z.string()
})
.nullish(),
checks: z
.array(
z.object({
name: z.string(),
documentation: z.object({
shortDescription: z.string(),
url: z.string()
}),
score: z.string(),
reason: z.string(),
details: z.array(z.string())
})
)
.nullish(),
score: z.number().nullish()
})
export const ScorecardSchema = z.object({
dependencies: z.array(
z.object({
change: ChangeSchema,
scorecard: ScorecardApiSchema.nullish()
})
)
})
export type Change = z.infer<typeof ChangeSchema>
export type Changes = z.infer<typeof ChangesSchema>
export type ComparisonResponse = z.infer<typeof ComparisonResponseSchema>
export type ConfigurationOptions = z.infer<typeof ConfigurationOptionsSchema>
export type Severity = z.infer<typeof SeveritySchema>
export type Scope = (typeof SCOPES)[number]
export type Scorecard = z.infer<typeof ScorecardSchema>
export type ScorecardApi = z.infer<typeof ScorecardApiSchema>
-73
View File
@@ -1,73 +0,0 @@
import {Change, Scorecard, ScorecardApi} from './schemas'
import * as core from '@actions/core'
export async function getScorecardLevels(
changes: Change[]
): Promise<Scorecard> {
const data: Scorecard = {dependencies: []} as Scorecard
for (const change of changes) {
const ecosystem = change.ecosystem
const packageName = change.name
const version = change.version
//Get the project repository
let repositoryUrl = change.source_repository_url
//If the repository_url includes the protocol, remove it
if (repositoryUrl?.startsWith('https://')) {
repositoryUrl = repositoryUrl.replace('https://', '')
}
// If GitHub API doesn't have the repository URL, query deps.dev for it.
if (repositoryUrl) {
// Call the deps.dev API to get the repository URL from there
repositoryUrl = await getProjectUrl(ecosystem, packageName, version)
}
// Get the scorecard API response from the scorecards API
let scorecardApi: ScorecardApi | null = null
if (repositoryUrl) {
try {
scorecardApi = await getScorecard(repositoryUrl)
} catch (error: unknown) {
core.debug(`Error querying for scorecard: ${(error as Error).message}`)
}
}
data.dependencies.push({
change,
scorecard: scorecardApi
})
}
return data
}
async function getScorecard(repositoryUrl: string): Promise<ScorecardApi> {
const apiRoot = 'https://api.securityscorecards.dev/'
let scorecardResponse: ScorecardApi = {} as ScorecardApi
const url = `${apiRoot}/projects/${repositoryUrl}`
const response = await fetch(url)
if (response.ok) {
scorecardResponse = await response.json()
} else {
core.debug(`Couldn't get scorecard data for ${repositoryUrl}`)
}
return scorecardResponse
}
export async function getProjectUrl(
ecosystem: string,
packageName: string,
version: string
): Promise<string> {
core.debug(`Getting deps.dev data for ${packageName} ${version}`)
const depsDevAPIRoot = 'https://api.deps.dev'
const url = `${depsDevAPIRoot}/v3alpha/systems/${ecosystem}/packages/${packageName}/versions/${version}`
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (data.relatedProjects.length > 0) {
return data.relatedProjects[0].projectKey.id
}
}
return ''
}
+8 -95
View File
@@ -1,5 +1,5 @@
import * as core from '@actions/core'
import {ConfigurationOptions, Changes, Change, Scorecard} from './schemas'
import {ConfigurationOptions, Changes, Change} from './schemas'
import {SummaryTableRow} from '@actions/core/lib/summary'
import {InvalidLicenseChanges, InvalidLicenseChangeTypes} from './licenses'
import {groupDependenciesByManifest, getManifestsSet, renderUrl} from './utils'
@@ -14,30 +14,22 @@ export function addSummaryToSummary(
vulnerableChanges: Changes,
invalidLicenseChanges: InvalidLicenseChanges,
deniedChanges: Changes,
scorecard: Scorecard,
config: ConfigurationOptions
): void {
const scorecardWarnings = countScorecardWarnings(scorecard, config)
const licenseIssues = countLicenseIssues(invalidLicenseChanges)
core.summary.addHeading('Dependency Review', 1)
if (
vulnerableChanges.length === 0 &&
licenseIssues === 0 &&
deniedChanges.length === 0 &&
scorecardWarnings === 0
countLicenseIssues(invalidLicenseChanges) === 0 &&
deniedChanges.length === 0
) {
const issueTypes = [
config.vulnerability_check ? 'vulnerabilities' : '',
config.license_check ? 'license issues' : '',
config.show_openssf_scorecard ? 'OpenSSF Scorecard issues' : ''
]
if (issueTypes.filter(Boolean).length === 0) {
core.summary.addRaw(`${icons.check} No issues found.`)
if (!config.license_check) {
core.summary.addRaw(`${icons.check} No vulnerabilities found.`)
} else if (!config.vulnerability_check) {
core.summary.addRaw(`${icons.check} No license issues found.`)
} else {
core.summary.addRaw(
`${icons.check} No ${issueTypes.filter(Boolean).join(' or ')} found.`
`${icons.check} No vulnerabilities or license issues found.`
)
}
@@ -73,31 +65,11 @@ export function addSummaryToSummary(
deniedChanges.length
} package(s) denied.`
]
: []),
...(config.show_openssf_scorecard && scorecardWarnings > 0
? [
`${checkOrWarnIcon(scorecardWarnings)} ${scorecardWarnings ? scorecardWarnings : 'No'} packages with OpenSSF Scorecard issues.`
]
: [])
])
.addRaw('See the Details below.')
}
function countScorecardWarnings(
scorecard: Scorecard,
config: ConfigurationOptions
): number {
return scorecard.dependencies.reduce(
(total, dependency) =>
total +
(dependency.scorecard?.score &&
dependency.scorecard?.score < config.warn_on_openssf_scorecard_level
? 1
: 0),
0
)
}
export function addChangeVulnerabilitiesToSummary(
vulnerableChanges: Changes,
severity: string
@@ -277,65 +249,6 @@ function snapshotWarningRecommendation(
return 'Re-running this action after a short time may resolve the issue.'
}
export function addScorecardToSummary(
scorecard: Scorecard,
config: ConfigurationOptions
): void {
core.summary.addHeading('OpenSSF Scorecard', 2)
if (scorecard.dependencies.length > 10) {
core.summary.addRaw(`<details><summary>Scorecard details</summary>`, true)
}
core.summary.addRaw(
`<table><tr><th>Package</th><th>Version</th><th>Score</th><th>Details</th></tr>`,
true
)
for (const dependency of scorecard.dependencies) {
core.debug('Adding scorecard to summary')
core.debug(`Overall score ${dependency.scorecard?.score}`)
// Set the icon based on the overall score value
let overallIcon = ''
if (dependency.scorecard?.score) {
overallIcon =
dependency.scorecard?.score < config.warn_on_openssf_scorecard_level
? ':warning:'
: ':green_circle:'
}
//Add a row for the dependency
core.summary.addRaw(
`<tr><td>${dependency.change.source_repository_url ? `<a href="https://${dependency.change.source_repository_url}">` : ''} ${dependency.change.ecosystem}/${dependency.change.name} ${dependency.change.source_repository_url ? `</a>` : ''}</td><td>${dependency.change.version}</td>
<td>${overallIcon} ${dependency.scorecard?.score === undefined || dependency.scorecard?.score === null ? 'Unknown' : dependency.scorecard?.score}</td>`,
false
)
//Add details table in the last column
if (dependency.scorecard?.checks !== undefined) {
let detailsTable =
'<table><tr><th>Check</th><th>Score</th><th>Reason</th></tr>'
for (const check of dependency.scorecard?.checks || []) {
const icon =
parseFloat(check.score) < config.warn_on_openssf_scorecard_level
? ':warning:'
: ':green_circle:'
detailsTable += `<tr><td>${check.name}</td><td>${icon} ${check.score}</td><td>${check.reason}</td></tr>`
}
detailsTable += `</table>`
core.summary.addRaw(
`<td><details><summary>Details</summary>${detailsTable}</details></td></tr>`,
true
)
} else {
core.summary.addRaw('<td>Unknown</td></tr>', true)
}
}
core.summary.addRaw(`</table>`)
if (scorecard.dependencies.length > 10) {
core.summary.addRaw(`</details>`)
}
}
export function addSnapshotWarnings(
config: ConfigurationOptions,
warnings: string