From 3df0248385e09a1562ebdd55bcf5b1935e738b87 Mon Sep 17 00:00:00 2001 From: Luke Watts Date: Mon, 9 Sep 2024 09:31:43 +0200 Subject: [PATCH] chore: apply prettier changes --- dangerfile.js | 3 +- packages/iac-cli-alert/src/index.ts | 3 +- packages/snyk-fix/src/index.ts | 10 +- .../snyk-fix/src/lib/issues/fixable-issues.ts | 4 +- .../src/lib/issues/issues-by-severity.ts | 9 +- .../output-formatters/show-results-summary.ts | 22 +- .../snyk-fix/src/partition-by-vulnerable.ts | 7 +- .../src/plugins/package-tool-supported.ts | 5 +- .../plugins/python/handlers/is-supported.ts | 4 +- .../extract-version-provenance.ts | 5 +- .../python/handlers/pip-requirements/index.ts | 13 +- .../update-dependencies/generate-pins.ts | 5 +- .../update-dependencies/index.ts | 6 +- .../requirements-file-parser.ts | 3 +- .../update-dependencies/pipenv-add.ts | 12 +- .../python/handlers/validate-required-data.ts | 4 +- packages/snyk-fix/src/plugins/python/index.ts | 10 +- .../python/map-entities-per-handler-type.ts | 4 +- .../update-dependencies.spec.ts | 18 +- .../poetry/update-dependencies.spec.ts | 6 +- .../test/helpers/generate-entity-to-fix.ts | 4 +- .../unit/lib/issues/fixable-issues.spec.ts | 16 +- packages/snyk-protect/src/lib/index.ts | 11 +- packages/snyk-protect/test/util/runCommand.ts | 8 +- src/cli/args.ts | 6 +- src/cli/commands/about.ts | 5 +- .../fix/convert-legacy-test-result-to-new.ts | 4 +- src/cli/commands/fix/index.ts | 17 +- src/cli/commands/monitor/index.ts | 4 +- src/cli/commands/process-command-args.ts | 11 +- src/cli/commands/test/iac/index.ts | 32 +- .../test/iac/local-execution/file-parser.ts | 6 +- .../test/iac/local-execution/file-scanner.ts | 19 +- .../test/iac/local-execution/file-utils.ts | 5 +- .../test/iac/local-execution/index.ts | 2 +- .../test/iac/local-execution/local-cache.ts | 4 +- .../iac/local-execution/measurable-methods.ts | 8 +- .../parsers/terraform-plan-parser.ts | 5 +- .../process-results/results-formatter.ts | 31 +- .../share-results-formatter.ts | 29 +- src/cli/commands/test/index.ts | 6 +- src/cli/main.ts | 2 +- src/lib/common.ts | 3 +- src/lib/config/index.ts | 4 +- src/lib/ecosystems/monitor.ts | 15 +- src/lib/ecosystems/resolve-test-facts.ts | 7 +- src/lib/ecosystems/unmanaged/utils.ts | 3 +- src/lib/errors/legacy-errors.js | 2 +- .../iac-output/text/failures/list.ts | 11 +- .../iac-output/text/issues-list/index.ts | 5 +- src/lib/formatters/iac-output/text/utils.ts | 5 +- .../formatters/open-source-sarif-output.ts | 4 +- .../formatters/test/format-test-results.ts | 4 +- src/lib/iac/drift/driftctl.ts | 7 +- .../test/v2/analytics/iac-cloud-context.ts | 5 +- src/lib/iac/test/v2/analytics/iac-type.ts | 39 +- src/lib/iac/test/v2/index.ts | 7 +- src/lib/iac/test/v2/json.ts | 5 +- src/lib/iac/test/v2/output.ts | 4 +- src/lib/index.js | 4 +- src/lib/monitor/dev-count-analysis.ts | 6 +- src/lib/monitor/index.ts | 6 +- src/lib/plugins/get-multi-plugin-result.ts | 40 +- .../plugins/nodejs-plugin/npm-lock-parser.ts | 5 +- .../nodejs-plugin/npm-workspaces-parser.ts | 6 +- src/lib/plugins/sast/analysis.ts | 6 +- src/lib/plugins/sast/format/output-format.ts | 6 +- src/lib/plugins/sast/index.ts | 5 +- src/lib/protect-update-notification.ts | 10 +- src/lib/request/snyk-http-client.ts | 4 +- src/lib/snyk-test/assemble-payloads.ts | 5 +- src/lib/snyk-test/legacy.ts | 4 +- src/lib/snyk-test/run-test.ts | 23 +- src/lib/spinner.ts | 4 +- test/acceptance/fake-server.ts | 9 +- .../acceptance/cli-json-file-output.spec.ts | 5 +- test/jest/acceptance/cli-json-output.spec.ts | 2 +- test/jest/acceptance/https.spec.ts | 5 +- test/jest/acceptance/iac/helpers.ts | 2 +- test/jest/acceptance/snyk-apps/config.spec.ts | 16 +- .../acceptance/snyk-code/snyk-code.spec.ts | 12 +- .../snyk-config-environment.spec.ts | 8 +- .../snyk-container/container.spec.ts | 24 +- .../snyk-ignore/snyk-ignore.spec.ts | 12 +- .../snyk-sbom-test/all-projects.spec.ts | 28 +- .../basic-test-all-languages.spec.ts | 18 +- .../cli/commands/test/iac/v2/index.spec.ts | 12 +- test/jest/unit/cli/commands/types.spec.ts | 19 +- test/jest/unit/dev-count-analysis.spec.ts | 29 +- .../unit/iac/cli-share-results.fixtures.ts | 7 +- test/jest/unit/iac/cli-share-results.spec.ts | 27 +- test/jest/unit/iac/directory-loader.spec.ts | 15 +- .../iac/file-parser.kubernetes.fixtures.ts | 15 +- test/jest/unit/iac/file-parser.spec.ts | 3 +- test/jest/unit/iac/file-scanner.spec.ts | 20 +- .../unit/iac/results-formatter.fixtures.ts | 14 +- test/jest/unit/iac/rules/oci-pull.spec.ts | 8 +- test/jest/unit/iac/service-mappings.spec.ts | 16 +- test/jest/unit/iac/url-utils.spec.ts | 24 +- test/jest/unit/lib/analytics/utils.ts | 4 +- .../ecosystems/resolve-monitor.facts.spec.ts | 4 +- .../lib/formatters/get-sarif-result.spec.ts | 18 +- .../iac-output/text/formatters.spec.ts | 31 +- .../iac-output/text/test-summary.spec.ts | 16 +- .../open-source-sarif-output.spec.ts | 9 +- test/jest/unit/lib/iac/test/v2/sarif.spec.ts | 5 +- .../plugins/yarn-workspaces-parser.spec.ts | 7 +- test/jest/unit/metrics.spec.ts | 8 +- test/jest/unit/policy-display.spec.ts | 6 +- .../unit/snyk-code/snyk-code-test.spec.ts | 19 +- test/setup.js | 2 +- test/tap/cli-monitor.acceptance.test.ts | 6 +- .../cli-monitor.all-projects.spec.ts | 1257 +++++++++-------- .../cli-test/cli-test.all-projects.spec.ts | 585 ++++---- test/tap/cli-test/cli-test.composer.spec.ts | 490 ++++--- test/tap/cli-test/cli-test.docker.spec.ts | 789 +++++------ test/tap/cli-test/cli-test.elixir.spec.ts | 204 ++- test/tap/cli-test/cli-test.generic.spec.ts | 207 ++- test/tap/cli-test/cli-test.go.spec.ts | 600 ++++---- test/tap/cli-test/cli-test.gradle.spec.ts | 423 +++--- test/tap/cli-test/cli-test.maven.spec.ts | 361 +++-- test/tap/cli-test/cli-test.npm.spec.ts | 522 ++++--- test/tap/cli-test/cli-test.nuget.spec.ts | 929 ++++++------ test/tap/cli-test/cli-test.python.spec.ts | 531 ++++--- test/tap/cli-test/cli-test.ruby.spec.ts | 992 +++++++------ test/tap/cli-test/cli-test.sbt.spec.ts | 12 +- .../cli-test/cli-test.yarn-workspaces.spec.ts | 639 ++++----- test/tap/cli-test/cli-test.yarn.spec.ts | 652 +++++---- test/tap/cli-test/sarif-schema-2.1.0.js | 3 +- test/tap/container.test.ts | 6 +- test/tap/proxy.test.js | 8 +- test/tap/remote-package.test.ts | 35 +- test/tap/run-test.test.ts | 6 +- test/tap/sub-process.test.js | 30 +- test/tap/user-config.test.ts | 24 +- test/tap/vulnerable-path-output.js | 24 +- ts-binary-wrapper/src/common.ts | 10 +- .../test/acceptance/basic.spec.ts | 9 +- .../test/util/prepareEnvironment.ts | 2 +- 139 files changed, 5062 insertions(+), 5425 deletions(-) diff --git a/dangerfile.js b/dangerfile.js index dfa65f1ee2..cd298cb1be 100644 --- a/dangerfile.js +++ b/dangerfile.js @@ -4,7 +4,8 @@ const fs = require('fs'); const MAX_COMMIT_MESSAGE_LENGTH = 72; function checkCommitMessage(commitMessage, url) { - const firstLineRegex = /^Merge.*|(feat|fix|chore|test|docs|refactor|revert)(\([a-z0-9-_]+\))?:(.+)$/; + const firstLineRegex = + /^Merge.*|(feat|fix|chore|test|docs|refactor|revert)(\([a-z0-9-_]+\))?:(.+)$/; if (!firstLineRegex.test(commitMessage)) { fail( `"[${commitMessage}](${url})" is not using a valid commit message format. For commit guidelines, see: [CONTRIBUTING](https://github.com/snyk/snyk/blob/main/CONTRIBUTING.md#creating-commits).`, diff --git a/packages/iac-cli-alert/src/index.ts b/packages/iac-cli-alert/src/index.ts index 06fb89c2d1..761c738633 100644 --- a/packages/iac-cli-alert/src/index.ts +++ b/packages/iac-cli-alert/src/index.ts @@ -43,8 +43,7 @@ async function discoverConsecutiveFailures( async function sendSlackAlert() { console.log('IaC smoke tests failed. Sending Slack alert...'); const args: IncomingWebhookDefaultArguments = { - text: - 'Infrastructure as Code Smoke Tests jobs failed. \n Core functionality in the IaC+ CLI flows may not be working as expected. \n \n ', + text: 'Infrastructure as Code Smoke Tests jobs failed. \n Core functionality in the IaC+ CLI flows may not be working as expected. \n \n ', }; await slackWebhook.send(args); console.log('Slack alert sent.'); diff --git a/packages/snyk-fix/src/index.ts b/packages/snyk-fix/src/index.ts index 9f2eed3b1f..11815fdc4c 100644 --- a/packages/snyk-fix/src/index.ts +++ b/packages/snyk-fix/src/index.ts @@ -42,10 +42,8 @@ export async function fix( const spinner = ora({ isSilent: options.quiet, stream: process.stdout }); let resultsByPlugin: FixHandlerResultByPlugin = {}; - const { - vulnerable, - notVulnerable: nothingToFix, - } = await partitionByVulnerable(entities); + const { vulnerable, notVulnerable: nothingToFix } = + await partitionByVulnerable(entities); const entitiesPerType = groupEntitiesPerScanType(vulnerable); const exceptions: ErrorsByEcoSystem = {}; await pMap( @@ -94,9 +92,7 @@ export async function fix( }; } -export function groupEntitiesPerScanType( - entities: EntityToFix[], -): { +export function groupEntitiesPerScanType(entities: EntityToFix[]): { [type: string]: EntityToFix[]; } { const entitiesPerType: { diff --git a/packages/snyk-fix/src/lib/issues/fixable-issues.ts b/packages/snyk-fix/src/lib/issues/fixable-issues.ts index 942bf9100c..0557f84a4f 100644 --- a/packages/snyk-fix/src/lib/issues/fixable-issues.ts +++ b/packages/snyk-fix/src/lib/issues/fixable-issues.ts @@ -1,8 +1,6 @@ import { DependencyPins, DependencyUpdates, TestResult } from '../../types'; -export function hasFixableIssues( - results: TestResult[], -): { +export function hasFixableIssues(results: TestResult[]): { hasFixes: boolean; count: number; } { diff --git a/packages/snyk-fix/src/lib/issues/issues-by-severity.ts b/packages/snyk-fix/src/lib/issues/issues-by-severity.ts index 01c6eba474..904b0c4c8a 100644 --- a/packages/snyk-fix/src/lib/issues/issues-by-severity.ts +++ b/packages/snyk-fix/src/lib/issues/issues-by-severity.ts @@ -1,8 +1,11 @@ import { IssuesData } from '../../types'; -export function getIssueCountBySeverity( - issueData: IssuesData[], -): { low: string[]; medium: string[]; high: string[]; critical: string[] } { +export function getIssueCountBySeverity(issueData: IssuesData[]): { + low: string[]; + medium: string[]; + high: string[]; + critical: string[]; +} { const total = { low: [], medium: [], diff --git a/packages/snyk-fix/src/lib/output-formatters/show-results-summary.ts b/packages/snyk-fix/src/lib/output-formatters/show-results-summary.ts index 7ad83b0eaa..72728d00cc 100644 --- a/packages/snyk-fix/src/lib/output-formatters/show-results-summary.ts +++ b/packages/snyk-fix/src/lib/output-formatters/show-results-summary.ts @@ -25,22 +25,12 @@ export async function showResultsSummary( options: FixOptions, total: number, ): Promise { - const successfulFixesSummary = generateSuccessfulFixesSummary( - resultsByPlugin, - ); - const { - summary: unresolvedSummary, - count: unresolvedCount, - } = generateUnresolvedSummary(resultsByPlugin, exceptions); - const { - summary: overallSummary, - count: changedCount, - } = generateOverallSummary( - resultsByPlugin, - exceptions, - nothingToFix, - options, - ); + const successfulFixesSummary = + generateSuccessfulFixesSummary(resultsByPlugin); + const { summary: unresolvedSummary, count: unresolvedCount } = + generateUnresolvedSummary(resultsByPlugin, exceptions); + const { summary: overallSummary, count: changedCount } = + generateOverallSummary(resultsByPlugin, exceptions, nothingToFix, options); const getHelpText = `${reTryMessage}. ${contactSupportMessage}`; diff --git a/packages/snyk-fix/src/partition-by-vulnerable.ts b/packages/snyk-fix/src/partition-by-vulnerable.ts index 6dd7d75c5d..600a8227ed 100644 --- a/packages/snyk-fix/src/partition-by-vulnerable.ts +++ b/packages/snyk-fix/src/partition-by-vulnerable.ts @@ -1,8 +1,9 @@ import { EntityToFix } from './types'; -export function partitionByVulnerable( - entities: EntityToFix[], -): { vulnerable: EntityToFix[]; notVulnerable: EntityToFix[] } { +export function partitionByVulnerable(entities: EntityToFix[]): { + vulnerable: EntityToFix[]; + notVulnerable: EntityToFix[]; +} { const vulnerable: EntityToFix[] = []; const notVulnerable: EntityToFix[] = []; diff --git a/packages/snyk-fix/src/plugins/package-tool-supported.ts b/packages/snyk-fix/src/plugins/package-tool-supported.ts index e7e26447e8..64ac669a5b 100644 --- a/packages/snyk-fix/src/plugins/package-tool-supported.ts +++ b/packages/snyk-fix/src/plugins/package-tool-supported.ts @@ -42,9 +42,8 @@ export async function checkPackageToolSupported( return; } - const { supported, versions } = supportFunc[ - packageManager - ].isSupportedVersion(version); + const { supported, versions } = + supportFunc[packageManager].isSupportedVersion(version); if (!supported) { const spinnerMessage = ` ${version} ${packageManager} version detected. Currently the following ${packageManager} versions are supported: ${versions.join( ',', diff --git a/packages/snyk-fix/src/plugins/python/handlers/is-supported.ts b/packages/snyk-fix/src/plugins/python/handlers/is-supported.ts index dfacc00fe8..765f1c0a8b 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/is-supported.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/is-supported.ts @@ -33,9 +33,7 @@ export async function isSupported( return { supported: true }; } -export async function partitionByFixable( - entities: EntityToFix[], -): Promise<{ +export async function partitionByFixable(entities: EntityToFix[]): Promise<{ skipped: Array>; fixable: EntityToFix[]; }> { diff --git a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/extract-version-provenance.ts b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/extract-version-provenance.ts index f562b3136b..7a5c820958 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/extract-version-provenance.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/extract-version-provenance.ts @@ -31,9 +31,8 @@ export async function extractProvenance( ...provenance, [relativeTargetFileName]: parseRequirementsFile(requirementsTxt), }; - const { containsRequire, matches } = await containsRequireDirective( - requirementsTxt, - ); + const { containsRequire, matches } = + await containsRequireDirective(requirementsTxt); if (containsRequire) { for (const match of matches) { const requiredFilePath = match[2]; diff --git a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/index.ts b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/index.ts index 9111cf9c5c..5107f9190f 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/index.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/index.ts @@ -253,9 +253,7 @@ function filterOutAppliedUpgrades( return pinRemediation; } -function sortByDirectory( - entities: EntityToFix[], -): { +function sortByDirectory(entities: EntityToFix[]): { [dir: string]: Array<{ entity: EntityToFix; dir: string; @@ -274,9 +272,7 @@ function sortByDirectory( return groupBy(sorted, 'dir'); } -export async function selectFileForPinning( - entity: EntityToFix, -): Promise<{ +export async function selectFileForPinning(entity: EntityToFix): Promise<{ fileName: string; fileContent: string; }> { @@ -287,9 +283,8 @@ export async function selectFileForPinning( let fileName = base; let requirementsTxt = await workspace.readFile(targetFile); - const { containsRequire, matches } = await containsRequireDirective( - requirementsTxt, - ); + const { containsRequire, matches } = + await containsRequireDirective(requirementsTxt); const constraintsMatch = matches.filter((m) => m.includes('c')); if (containsRequire && constraintsMatch[0]) { // prefer to pin in constraints file if present diff --git a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/generate-pins.ts b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/generate-pins.ts index 2c8474e776..df2eed6de0 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/generate-pins.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/generate-pins.ts @@ -31,9 +31,8 @@ export function generatePins( const pinnedRequirements = Object.keys(standardizedPins) .map((pkgNameAtVersion) => { const [pkgName, version] = pkgNameAtVersion.split('@'); - const newVersion = standardizedPins[pkgNameAtVersion].upgradeTo.split( - '@', - )[1]; + const newVersion = + standardizedPins[pkgNameAtVersion].upgradeTo.split('@')[1]; const newRequirement = `${standardizePackageName( pkgName, )}>=${newVersion}`; diff --git a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/index.ts b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/index.ts index b8930ac9c2..c29807a40c 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/index.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/index.ts @@ -25,10 +25,8 @@ export function updateDependencies( updatedManifest: string; changes: FixChangesSummary[]; } { - const { - requirements, - endsWithNewLine: shouldEndWithNewLine, - } = parsedRequirementsData; + const { requirements, endsWithNewLine: shouldEndWithNewLine } = + parsedRequirementsData; if (!requirements.length) { debug( 'Error: Expected to receive parsed manifest data. Is manifest empty?', diff --git a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/requirements-file-parser.ts b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/requirements-file-parser.ts index ec5dd6dbef..9b7bfeee7f 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/requirements-file-parser.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pip-requirements/update-dependencies/requirements-file-parser.ts @@ -63,7 +63,8 @@ function extractDependencyDataFromLine( // Regex to match against a Python package specifier. Any invalid lines (or // lines we can't handle) should have been returned this point. - const regex = /([A-Z0-9-._]*)(!=|===|==|>=|<=|>|<|~=)(\d*\.?\d*\.?\d*[A-Z0-9]*)(.*)/i; + const regex = + /([A-Z0-9-._]*)(!=|===|==|>=|<=|>|<|~=)(\d*\.?\d*\.?\d*[A-Z0-9]*)(.*)/i; const result = regex.exec(requirementText); if (result !== null) { requirement.name = standardizePackageName(result[1]); diff --git a/packages/snyk-fix/src/plugins/python/handlers/pipenv-pipfile/update-dependencies/pipenv-add.ts b/packages/snyk-fix/src/plugins/python/handlers/pipenv-pipfile/update-dependencies/pipenv-add.ts index 9aabdd5392..c6560d5362 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/pipenv-pipfile/update-dependencies/pipenv-add.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/pipenv-pipfile/update-dependencies/pipenv-add.ts @@ -30,14 +30,10 @@ export async function pipenvAdd( const targetFilePath = pathLib.resolve(entity.workspace.path, targetFile); const { dir } = pathLib.parse(targetFilePath); if (!options.dryRun && upgrades.length) { - const { - stderr, - stdout, - command, - exitCode, - } = await pipenvPipfileFix.pipenvInstall(dir, upgrades, { - python: entity.options.command, - }); + const { stderr, stdout, command, exitCode } = + await pipenvPipfileFix.pipenvInstall(dir, upgrades, { + python: entity.options.command, + }); debug('`pipenv add` returned:', { stderr, stdout, command }); if (exitCode !== 0) { pipenvCommand = command; diff --git a/packages/snyk-fix/src/plugins/python/handlers/validate-required-data.ts b/packages/snyk-fix/src/plugins/python/handlers/validate-required-data.ts index 5da56e3769..808ab636bc 100644 --- a/packages/snyk-fix/src/plugins/python/handlers/validate-required-data.ts +++ b/packages/snyk-fix/src/plugins/python/handlers/validate-required-data.ts @@ -3,9 +3,7 @@ import { MissingFileNameError } from '../../../lib/errors/missing-file-name'; import { NoFixesCouldBeAppliedError } from '../../../lib/errors/no-fixes-applied'; import { EntityToFix, RemediationChanges, Workspace } from '../../../types'; -export function validateRequiredData( - entity: EntityToFix, -): { +export function validateRequiredData(entity: EntityToFix): { remediation: RemediationChanges; targetFile: string; workspace: Workspace; diff --git a/packages/snyk-fix/src/plugins/python/index.ts b/packages/snyk-fix/src/plugins/python/index.ts index 5a4a2695ae..901b30cdb7 100644 --- a/packages/snyk-fix/src/plugins/python/index.ts +++ b/packages/snyk-fix/src/plugins/python/index.ts @@ -30,9 +30,8 @@ export async function pythonFix( }, }; const results = handlerResult.python; - const { entitiesPerType, skipped: notSupported } = mapEntitiesPerHandlerType( - entities, - ); + const { entitiesPerType, skipped: notSupported } = + mapEntitiesPerHandlerType(entities); results.skipped.push(...notSupported); spinner.stopAndPersist({ @@ -57,9 +56,8 @@ export async function pythonFix( const handler = loadHandler(projectType as SUPPORTED_HANDLER_TYPES); // drop unsupported Python entities early so only potentially fixable items get // attempted to be fixed - const { fixable, skipped: notFixable } = await partitionByFixable( - projectsToFix, - ); + const { fixable, skipped: notFixable } = + await partitionByFixable(projectsToFix); results.skipped.push(...notFixable); const { failed, skipped, succeeded } = await handler(fixable, options); diff --git a/packages/snyk-fix/src/plugins/python/map-entities-per-handler-type.ts b/packages/snyk-fix/src/plugins/python/map-entities-per-handler-type.ts index 91ed5c2136..1809a71256 100644 --- a/packages/snyk-fix/src/plugins/python/map-entities-per-handler-type.ts +++ b/packages/snyk-fix/src/plugins/python/map-entities-per-handler-type.ts @@ -6,9 +6,7 @@ import { SUPPORTED_HANDLER_TYPES } from './supported-handler-types'; const debug = debugLib('snyk-fix:python'); -export function mapEntitiesPerHandlerType( - entities: EntityToFix[], -): { +export function mapEntitiesPerHandlerType(entities: EntityToFix[]): { skipped: Array>; entitiesPerType: { [projectType in SUPPORTED_HANDLER_TYPES]: EntityToFix[]; diff --git a/packages/snyk-fix/test/acceptance/plugins/python/handlers/pipenv-pipfile/update-dependencies.spec.ts b/packages/snyk-fix/test/acceptance/plugins/python/handlers/pipenv-pipfile/update-dependencies.spec.ts index 434eaae7a5..18fa23d23c 100644 --- a/packages/snyk-fix/test/acceptance/plugins/python/handlers/pipenv-pipfile/update-dependencies.spec.ts +++ b/packages/snyk-fix/test/acceptance/plugins/python/handlers/pipenv-pipfile/update-dependencies.spec.ts @@ -164,8 +164,7 @@ describe('fix Pipfile Python projects', () => { issueIds: ['vuln-id'], reason: 'Locking failed', success: false, - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', to: 'django@2.0.1', userMessage: 'Failed to upgrade django from 1.6.1 to 2.0.1', }, @@ -174,8 +173,7 @@ describe('fix Pipfile Python projects', () => { issueIds: [], reason: 'Locking failed', success: false, - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', to: 'transitive@1.1.1', userMessage: 'Failed to pin transitive from 1.0.0 to 1.1.1', }, @@ -263,8 +261,7 @@ describe('fix Pipfile Python projects', () => { success: false, reason: err, userMessage: 'Failed to upgrade django from 1.6.1 to 2.0.1', - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', issueIds: ['vuln-id'], from: 'django@1.6.1', to: 'django@2.0.1', @@ -273,8 +270,7 @@ describe('fix Pipfile Python projects', () => { success: false, reason: err, userMessage: 'Failed to pin transitive from 1.0.0 to 1.1.1', - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', issueIds: [], from: 'transitive@1.0.0', to: 'transitive@1.1.1', @@ -716,8 +712,7 @@ describe('fix Pipfile Python projects (fix sequentially)', () => { issueIds: ['vuln-id'], reason: err, success: false, - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', to: 'django@2.0.1', userMessage: 'Failed to upgrade django from 1.6.1 to 2.0.1', }, @@ -726,8 +721,7 @@ describe('fix Pipfile Python projects (fix sequentially)', () => { issueIds: [], reason: err, success: false, - tip: - 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', + tip: 'Try running `pipenv install django==2.0.1 transitive==1.1.1`', to: 'transitive@1.1.1', userMessage: 'Failed to pin transitive from 1.0.0 to 1.1.1', }, diff --git a/packages/snyk-fix/test/acceptance/plugins/python/handlers/poetry/update-dependencies.spec.ts b/packages/snyk-fix/test/acceptance/plugins/python/handlers/poetry/update-dependencies.spec.ts index 195f7a3433..5ce5b18bfe 100644 --- a/packages/snyk-fix/test/acceptance/plugins/python/handlers/poetry/update-dependencies.spec.ts +++ b/packages/snyk-fix/test/acceptance/plugins/python/handlers/poetry/update-dependencies.spec.ts @@ -170,8 +170,7 @@ describe('fix Poetry Python projects', () => { issueIds: ['VULN-six'], reason: err, success: false, - tip: - 'Try running `poetry install six==2.0.1 transitive==1.1.1`', + tip: 'Try running `poetry install six==2.0.1 transitive==1.1.1`', to: 'six@2.0.1', userMessage: 'Failed to upgrade six from 1.1.6 to 2.0.1', }, @@ -180,8 +179,7 @@ describe('fix Poetry Python projects', () => { issueIds: [], reason: err, success: false, - tip: - 'Try running `poetry install six==2.0.1 transitive==1.1.1`', + tip: 'Try running `poetry install six==2.0.1 transitive==1.1.1`', to: 'transitive@1.1.1', userMessage: 'Failed to pin transitive from 1.0.0 to 1.1.1', }, diff --git a/packages/snyk-fix/test/helpers/generate-entity-to-fix.ts b/packages/snyk-fix/test/helpers/generate-entity-to-fix.ts index fb5a7a9192..1ef8664e32 100644 --- a/packages/snyk-fix/test/helpers/generate-entity-to-fix.ts +++ b/packages/snyk-fix/test/helpers/generate-entity-to-fix.ts @@ -25,7 +25,7 @@ export function generateEntityToFix( : { issues: [], issuesData: {}, - depGraphData: ('' as unknown) as DepGraphData, + depGraphData: '' as unknown as DepGraphData, }; const workspace = generateWorkspace(contents, path); const cliTestOptions = { @@ -112,7 +112,7 @@ export function generateTestResult(): TestResult { title: 'Fake vuln', }, }, - depGraphData: ('' as unknown) as DepGraphData, + depGraphData: '' as unknown as DepGraphData, remediation: { unresolved: [], upgrade: {}, diff --git a/packages/snyk-fix/test/unit/lib/issues/fixable-issues.spec.ts b/packages/snyk-fix/test/unit/lib/issues/fixable-issues.spec.ts index 3e7de595c7..9743fa10e5 100644 --- a/packages/snyk-fix/test/unit/lib/issues/fixable-issues.spec.ts +++ b/packages/snyk-fix/test/unit/lib/issues/fixable-issues.spec.ts @@ -7,7 +7,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: { @@ -39,7 +39,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: {}, @@ -71,7 +71,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: {}, @@ -103,7 +103,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: { @@ -146,7 +146,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: {}, @@ -169,7 +169,7 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: {}, @@ -202,12 +202,12 @@ describe('hasFixableIssues', () => { { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, }, { issues: [], issuesData: {}, - depGraphData: ({} as unknown) as DepGraphData, + depGraphData: {} as unknown as DepGraphData, remediation: { ignore: {}, patch: {}, diff --git a/packages/snyk-protect/src/lib/index.ts b/packages/snyk-protect/src/lib/index.ts index c9ef95bc79..ad83ca463a 100644 --- a/packages/snyk-protect/src/lib/index.ts +++ b/packages/snyk-protect/src/lib/index.ts @@ -61,10 +61,8 @@ async function protect(projectFolderPath: string) { } }); - const packageAtVersionsToPatches: Map< - string, - VulnPatches[] - > = await getAllPatches(vulnIdAndPackageNames, packageNameToVersionsMap); + const packageAtVersionsToPatches: Map = + await getAllPatches(vulnIdAndPackageNames, packageNameToVersionsMap); if (packageAtVersionsToPatches.size === 0) { console.log('Nothing to patch.'); @@ -77,9 +75,8 @@ async function protect(projectFolderPath: string) { const patchedModules: PatchedModule[] = []; foundPhysicalPackages.forEach((fpp) => { const packageNameAtVersion = `${fpp.packageName}@${fpp.packageVersion}`; - const vuldIdAndPatches = packageAtVersionsToPatches.get( - packageNameAtVersion, - ); + const vuldIdAndPatches = + packageAtVersionsToPatches.get(packageNameAtVersion); vuldIdAndPatches?.forEach((vp) => { vp.patches.forEach((patchDiffs) => { patchDiffs.patchDiffs.forEach((diff) => { diff --git a/packages/snyk-protect/test/util/runCommand.ts b/packages/snyk-protect/test/util/runCommand.ts index c4238e3a5d..e0bd3e81d7 100644 --- a/packages/snyk-protect/test/util/runCommand.ts +++ b/packages/snyk-protect/test/util/runCommand.ts @@ -34,12 +34,8 @@ const runCommand = ( cli.on('close', (code) => { resolve({ code: code || 0, - stdout: Buffer.concat(stdout) - .toString('utf-8') - .trim(), - stderr: Buffer.concat(stderr) - .toString('utf-8') - .trim(), + stdout: Buffer.concat(stdout).toString('utf-8').trim(), + stderr: Buffer.concat(stderr).toString('utf-8').trim(), }); }); }); diff --git a/src/cli/args.ts b/src/cli/args.ts index d95d88d7b7..19697c5063 100644 --- a/src/cli/args.ts +++ b/src/cli/args.ts @@ -200,9 +200,9 @@ export function args(rawArgv: string[]): Args { } // TODO: eventually all arguments should be transformed like this. - const argumentsToTransform: Array> = [ + const argumentsToTransform: Array< + Partial + > = [ 'package-manager', 'packages-folder', 'severity-threshold', diff --git a/src/cli/commands/about.ts b/src/cli/commands/about.ts index 59513be71f..6bc1e58d59 100644 --- a/src/cli/commands/about.ts +++ b/src/cli/commands/about.ts @@ -11,8 +11,9 @@ export default function about(): void { `${licenseNotice.name} \u00B7 ${licenseNotice.version} \u00B7 ${licenseNotice.license}`, ); console.log( - `Author(s): ${licenseNotice.author || - 'Not filled'} \u00B7 Package: ${licenseNotice.source || ''}`, + `Author(s): ${ + licenseNotice.author || 'Not filled' + } \u00B7 Package: ${licenseNotice.source || ''}`, ); console.log(`${licenseNotice.licenseText || ''}`); // WTFPL is not required the embed its license text console.log('\n+-+-+-+-+-+-+'); diff --git a/src/cli/commands/fix/convert-legacy-test-result-to-new.ts b/src/cli/commands/fix/convert-legacy-test-result-to-new.ts index b51b5b49ac..69bfdbf150 100644 --- a/src/cli/commands/fix/convert-legacy-test-result-to-new.ts +++ b/src/cli/commands/fix/convert-legacy-test-result-to-new.ts @@ -5,9 +5,7 @@ import { TestResult as LegacyTestResult, } from '../../../lib/snyk-test/legacy'; -function convertVulnerabilities( - vulns: AnnotatedIssue[], -): { +function convertVulnerabilities(vulns: AnnotatedIssue[]): { issuesData: IssuesData; issues: Issue[]; } { diff --git a/src/cli/commands/fix/index.ts b/src/cli/commands/fix/index.ts index 8be98702dc..f1656a7edf 100644 --- a/src/cli/commands/fix/index.ts +++ b/src/cli/commands/fix/index.ts @@ -52,14 +52,15 @@ export default async function fix(...args: MethodArgs): Promise { (res) => Object.keys(res.testResult.issues).length, ); const { dryRun, quiet, sequential: sequentialFix } = options; - const { fixSummary, meta, results: resultsByPlugin } = await snykFix.fix( - results, - { - dryRun, - quiet, - sequentialFix, - }, - ); + const { + fixSummary, + meta, + results: resultsByPlugin, + } = await snykFix.fix(results, { + dryRun, + quiet, + sequentialFix, + }); setSnykFixAnalytics( fixSummary, diff --git a/src/cli/commands/monitor/index.ts b/src/cli/commands/monitor/index.ts index 4a60e28729..4bbdafae21 100644 --- a/src/cli/commands/monitor/index.ts +++ b/src/cli/commands/monitor/index.ts @@ -353,8 +353,8 @@ export default async function monitor(...args0: MethodArgs): Promise { res.data && res.data.userMessage ? chalk.bold.red(res.data.userMessage) : res.data - ? res.data.message - : 'Unknown error occurred.'; + ? res.data.message + : 'Unknown error occurred.'; return ( chalk.bold.white('\nMonitoring ' + res.path + '...\n\n') + errorMessage diff --git a/src/cli/commands/process-command-args.ts b/src/cli/commands/process-command-args.ts index f3a7c815cd..5bbe3ba932 100644 --- a/src/cli/commands/process-command-args.ts +++ b/src/cli/commands/process-command-args.ts @@ -1,12 +1,13 @@ import { Options } from '../../lib/types'; -export function processCommandArgs( - ...args -): { paths: string[]; options: Options & CommandOptions } { - let options = ({} as any) as Options & CommandOptions; +export function processCommandArgs(...args): { + paths: string[]; + options: Options & CommandOptions; +} { + let options = {} as any as Options & CommandOptions; if (typeof args[args.length - 1] === 'object') { - options = (args.pop() as any) as Options & CommandOptions; + options = args.pop() as any as Options & CommandOptions; } args = args.filter(Boolean); diff --git a/src/cli/commands/test/iac/index.ts b/src/cli/commands/test/iac/index.ts index 74edfebaa6..31b16f5e06 100644 --- a/src/cli/commands/test/iac/index.ts +++ b/src/cli/commands/test/iac/index.ts @@ -16,7 +16,9 @@ import { buildOutput, buildSpinner, printHeader } from './output'; import { InvalidArgumentError } from './local-execution/assert-iac-options-flag'; import { IaCTestFlags } from './local-execution/types'; -export default async function(...args: MethodArgs): Promise { +export default async function ( + ...args: MethodArgs +): Promise { const { options: originalOptions, paths } = processCommandArgs(...args); const options = setDefaultTestOptions(originalOptions); @@ -48,22 +50,18 @@ export default async function(...args: MethodArgs): Promise { printHeader(options); - const { - iacOutputMeta, - iacScanFailures, - iacIgnoredIssuesCount, - results, - } = await scan( - iacOrgSettings, - options, - testSpinner, - paths, - orgPublicId, - buildOciRegistry, - projectRoot, - remoteRepoUrl, - targetName, - ); + const { iacOutputMeta, iacScanFailures, iacIgnoredIssuesCount, results } = + await scan( + iacOrgSettings, + options, + testSpinner, + paths, + orgPublicId, + buildOciRegistry, + projectRoot, + remoteRepoUrl, + targetName, + ); return buildOutput({ results, diff --git a/src/cli/commands/test/iac/local-execution/file-parser.ts b/src/cli/commands/test/iac/local-execution/file-parser.ts index c6ec787b2a..e4127744b7 100644 --- a/src/cli/commands/test/iac/local-execution/file-parser.ts +++ b/src/cli/commands/test/iac/local-execution/file-parser.ts @@ -46,10 +46,8 @@ export async function parseFiles( ); if (tfFileData.length > 0) { - const { - parsedFiles: parsedTfFiles, - failedFiles: failedTfFiles, - } = parseTerraformFiles(tfFileData); + const { parsedFiles: parsedTfFiles, failedFiles: failedTfFiles } = + parseTerraformFiles(tfFileData); parsedFiles = parsedFiles.concat(parsedTfFiles); failedFiles = failedFiles.concat(failedTfFiles); } diff --git a/src/cli/commands/test/iac/local-execution/file-scanner.ts b/src/cli/commands/test/iac/local-execution/file-scanner.ts index 9c1ba083f0..399d129631 100644 --- a/src/cli/commands/test/iac/local-execution/file-scanner.ts +++ b/src/cli/commands/test/iac/local-execution/file-scanner.ts @@ -14,9 +14,7 @@ import { getErrorStringCode } from './error-utils'; import { IacFileInDirectory } from '../../../../../lib/types'; import { SEVERITIES } from '../../../../../lib/snyk-test/common'; -export async function scanFiles( - parsedFiles: Array, -): Promise<{ +export async function scanFiles(parsedFiles: Array): Promise<{ scannedFiles: IacFileScanResult[]; failedScans: IacFileInDirectory[]; }> { @@ -27,9 +25,8 @@ export async function scanFiles( const policyEngine = await getPolicyEngine(parsedFile.engineType); const result = policyEngine.scanFile(parsedFile); if (parsedFile.engineType === EngineType.Custom) { - const { validatedResult, invalidIssues } = validateResultFromCustomRules( - result, - ); + const { validatedResult, invalidIssues } = + validateResultFromCustomRules(result); validatedResult.violatedPolicies.forEach((policy) => { // custom rules will have a remediation field that is a string, so we need to map it to the resolve field. if (typeof policy.remediation === 'string') { @@ -54,9 +51,7 @@ async function getPolicyEngine(engineType: EngineType): Promise { return policyEngineCache[engineType]!; } -export function validateResultFromCustomRules( - result: IacFileScanResult, -): { +export function validateResultFromCustomRules(result: IacFileScanResult): { validatedResult: IacFileScanResult; invalidIssues: IacFileInDirectory[]; } { @@ -124,10 +119,8 @@ let policyEngineCache: { [key in EngineType]: PolicyEngine | null } = { async function buildPolicyEngine( engineType: EngineType, ): Promise { - const [ - policyEngineCoreDataPath, - policyEngineMetaDataPath, - ] = getLocalCachePath(engineType); + const [policyEngineCoreDataPath, policyEngineMetaDataPath] = + getLocalCachePath(engineType); try { const wasmFile = fs.readFileSync(policyEngineCoreDataPath); diff --git a/src/cli/commands/test/iac/local-execution/file-utils.ts b/src/cli/commands/test/iac/local-execution/file-utils.ts index 72e1dfe400..99d2a3f1b2 100644 --- a/src/cli/commands/test/iac/local-execution/file-utils.ts +++ b/src/cli/commands/test/iac/local-execution/file-utils.ts @@ -11,10 +11,7 @@ import { readdirSync } from 'fs'; import { join } from 'path'; function hashData(s: string): string { - const hashedData = crypto - .createHash('sha1') - .update(s) - .digest('hex'); + const hashedData = crypto.createHash('sha1').update(s).digest('hex'); return hashedData; } diff --git a/src/cli/commands/test/iac/local-execution/index.ts b/src/cli/commands/test/iac/local-execution/index.ts index b9a4cdbd9b..97a4d081ab 100644 --- a/src/cli/commands/test/iac/local-execution/index.ts +++ b/src/cli/commands/test/iac/local-execution/index.ts @@ -134,7 +134,7 @@ export async function test( // TODO: add support for proper typing of old TestResult interface. return { - results: (filteredIssues as unknown) as TestResult[], + results: filteredIssues as unknown as TestResult[], failures, ignoreCount, }; diff --git a/src/cli/commands/test/iac/local-execution/local-cache.ts b/src/cli/commands/test/iac/local-execution/local-cache.ts index 62858c1935..2ddbcd8556 100644 --- a/src/cli/commands/test/iac/local-execution/local-cache.ts +++ b/src/cli/commands/test/iac/local-execution/local-cache.ts @@ -14,9 +14,7 @@ import envPaths from 'env-paths'; const debug = Debug('iac-local-cache'); const cachePath = config.CACHE_PATH ?? envPaths('snyk').cache; -const uuid = Math.random() - .toString(36) - .substring(2); +const uuid = Math.random().toString(36).substring(2); export const LOCAL_POLICY_ENGINE_DIR = cachePath + '/iac-data/' + uuid; const KUBERNETES_POLICY_ENGINE_WASM_PATH = path.join( diff --git a/src/cli/commands/test/iac/local-execution/measurable-methods.ts b/src/cli/commands/test/iac/local-execution/measurable-methods.ts index 313f40f5b3..72dce0a248 100644 --- a/src/cli/commands/test/iac/local-execution/measurable-methods.ts +++ b/src/cli/commands/test/iac/local-execution/measurable-methods.ts @@ -18,12 +18,12 @@ type Awaited = T extends PromiseLike ? U : T; // the compiler to be happy, so we need to unwrap it with the messy // Awaiter> rather than just using ReturnType directly. export function asyncPerformanceAnalyticsDecorator< - T extends (...args: any[]) => Promise + T extends (...args: any[]) => Promise, >( measurableMethod: T, analyticsKey: PerformanceAnalyticsKey, ): (...args: Parameters) => Promise>> { - return async function(...args) { + return async function (...args) { const startTime = Date.now(); const returnValue = await measurableMethod(...args); const durationMs = Date.now() - startTime; @@ -33,12 +33,12 @@ export function asyncPerformanceAnalyticsDecorator< } export function performanceAnalyticsDecorator< - T extends (...args: any[]) => any + T extends (...args: any[]) => any, >( measurableMethod: T, analyticsKey: PerformanceAnalyticsKey, ): (...args: Parameters) => ReturnType { - return function(...args) { + return function (...args) { const startTime = Date.now(); const returnValue = measurableMethod(...args); const durationMs = Date.now() - startTime; diff --git a/src/cli/commands/test/iac/local-execution/parsers/terraform-plan-parser.ts b/src/cli/commands/test/iac/local-execution/parsers/terraform-plan-parser.ts index f739c82c33..e1e3c82e1d 100644 --- a/src/cli/commands/test/iac/local-execution/parsers/terraform-plan-parser.ts +++ b/src/cli/commands/test/iac/local-execution/parsers/terraform-plan-parser.ts @@ -118,9 +118,8 @@ function referencedResourcesResolver( resolvedResource[key] = resourceExpressions[key]; } } - scanInput[inputKey][type][ - getResourceName(index, name) - ] = resolvedResource; + scanInput[inputKey][type][getResourceName(index, name)] = + resolvedResource; } } diff --git a/src/cli/commands/test/iac/local-execution/process-results/results-formatter.ts b/src/cli/commands/test/iac/local-execution/process-results/results-formatter.ts index 17d9832891..70cc3709f0 100644 --- a/src/cli/commands/test/iac/local-execution/process-results/results-formatter.ts +++ b/src/cli/commands/test/iac/local-execution/process-results/results-formatter.ts @@ -31,20 +31,23 @@ export function formatScanResults( gitRemoteUrl?: string, ): FormattedResult[] { try { - const groupedByFile = scanResults.reduce((memo, scanResult) => { - const res = formatScanResult(scanResult, meta, options, projectRoot); - - if (memo[scanResult.filePath]) { - memo[scanResult.filePath].result.cloudConfigResults.push( - ...res.result.cloudConfigResults, - ); - } else { - res.meta.gitRemoteUrl = gitRemoteUrl; - res.meta.projectId = projectPublicIds[res.targetFile]; - memo[scanResult.filePath] = res; - } - return memo; - }, {} as { [key: string]: FormattedResult }); + const groupedByFile = scanResults.reduce( + (memo, scanResult) => { + const res = formatScanResult(scanResult, meta, options, projectRoot); + + if (memo[scanResult.filePath]) { + memo[scanResult.filePath].result.cloudConfigResults.push( + ...res.result.cloudConfigResults, + ); + } else { + res.meta.gitRemoteUrl = gitRemoteUrl; + res.meta.projectId = projectPublicIds[res.targetFile]; + memo[scanResult.filePath] = res; + } + return memo; + }, + {} as { [key: string]: FormattedResult }, + ); return Object.values(groupedByFile); } catch (e) { throw new FailedToFormatResults(); diff --git a/src/cli/commands/test/iac/local-execution/process-results/share-results-formatter.ts b/src/cli/commands/test/iac/local-execution/process-results/share-results-formatter.ts index d9f264940b..13ac834b9d 100644 --- a/src/cli/commands/test/iac/local-execution/process-results/share-results-formatter.ts +++ b/src/cli/commands/test/iac/local-execution/process-results/share-results-formatter.ts @@ -30,19 +30,22 @@ export function formatShareResults( } function groupByFilePath(scanResults: IacFileScanResult[]) { - const groupedByFilePath = scanResults.reduce((memo, scanResult) => { - scanResult.violatedPolicies.forEach((violatedPolicy) => { - violatedPolicy.docId = scanResult.docId; - }); - if (memo[scanResult.filePath]) { - memo[scanResult.filePath].violatedPolicies.push( - ...scanResult.violatedPolicies, - ); - } else { - memo[scanResult.filePath] = scanResult; - } - return memo; - }, {} as Record); + const groupedByFilePath = scanResults.reduce( + (memo, scanResult) => { + scanResult.violatedPolicies.forEach((violatedPolicy) => { + violatedPolicy.docId = scanResult.docId; + }); + if (memo[scanResult.filePath]) { + memo[scanResult.filePath].violatedPolicies.push( + ...scanResult.violatedPolicies, + ); + } else { + memo[scanResult.filePath] = scanResult; + } + return memo; + }, + {} as Record, + ); return Object.values(groupedByFilePath); } diff --git a/src/cli/commands/test/index.ts b/src/cli/commands/test/index.ts index fb638f3c3f..a0c9df8fd4 100644 --- a/src/cli/commands/test/index.ts +++ b/src/cli/commands/test/index.ts @@ -80,10 +80,8 @@ export default async function test( validateTestOptions(options); validateCredentials(options); - const packageJsonPathsWithSnykDepForProtect: string[] = getPackageJsonPathsContainingSnykDependency( - options.file, - paths, - ); + const packageJsonPathsWithSnykDepForProtect: string[] = + getPackageJsonPathsContainingSnykDependency(options.file, paths); analytics.add( 'upgradable-snyk-protect-paths', diff --git a/src/cli/main.ts b/src/cli/main.ts index 86d6d56070..b03d6f1d2c 100755 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -274,7 +274,7 @@ export async function main(): Promise { modeValidation(globalArgs); // TODO: fix this, we do transformation to options and teh type doesn't reflect it validateUnsupportedOptionCombinations( - (globalArgs.options as unknown) as AllSupportedCliOptions, + globalArgs.options as unknown as AllSupportedCliOptions, ); if (globalArgs.options['group-issues'] && globalArgs.options['iac']) { diff --git a/src/lib/common.ts b/src/lib/common.ts index 94b579feeb..f81dda1fe7 100644 --- a/src/lib/common.ts +++ b/src/lib/common.ts @@ -48,8 +48,7 @@ export function testPlatformSupport() { if (analytics.allowAnalytics()) { const sentryError = new Error('Unsupported Platform: ' + currentPlatform); Sentry.init({ - dsn: - 'https://3e845233db8c4f43b4c4b9245f1d7bd6@o30291.ingest.sentry.io/4504599528079360', + dsn: 'https://3e845233db8c4f43b4c4b9245f1d7bd6@o30291.ingest.sentry.io/4504599528079360', release: version.getVersion(), }); Sentry.captureException(sentryError); diff --git a/src/lib/config/index.ts b/src/lib/config/index.ts index a81d7b7a13..05a966fcc8 100644 --- a/src/lib/config/index.ts +++ b/src/lib/config/index.ts @@ -39,9 +39,7 @@ interface Config { } // TODO: fix the types! -const config = (snykConfig.loadConfig( - __dirname + '/../..', -) as unknown) as Config; +const config = snykConfig.loadConfig(__dirname + '/../..') as unknown as Config; const defaultApiUrl = 'https://api.snyk.io'; const configDefinedApiUrl = userConfig.get('endpoint'); diff --git a/src/lib/ecosystems/monitor.ts b/src/lib/ecosystems/monitor.ts index 591ba68db3..1d95921bf3 100644 --- a/src/lib/ecosystems/monitor.ts +++ b/src/lib/ecosystems/monitor.ts @@ -133,10 +133,8 @@ async function monitorDependencies( for (const [path, scanResults] of Object.entries(scans)) { await spinner(`Monitoring dependencies in ${path}`); for (const scanResult of scanResults) { - const monitorDependenciesRequest = await generateMonitorDependenciesRequest( - scanResult, - options, - ); + const monitorDependenciesRequest = + await generateMonitorDependenciesRequest(scanResult, options); const configOrg = config.org ? decodeURIComponent(config.org) : undefined; @@ -154,9 +152,8 @@ async function monitorDependencies( }, }; try { - const response = await makeRequest( - payload, - ); + const response = + await makeRequest(payload); results.push({ ...response, path, @@ -239,8 +236,8 @@ export async function getFormattedMonitorOutput( res.data && res.data.userMessage ? chalk.bold.red(res.data.userMessage) : res.data - ? res.data.message - : 'Unknown error occurred.'; + ? res.data.message + : 'Unknown error occurred.'; return ( chalk.bold.white('\nMonitoring ' + res.path + '...\n\n') + errorMessage diff --git a/src/lib/ecosystems/resolve-test-facts.ts b/src/lib/ecosystems/resolve-test-facts.ts index 85eb24ef67..fef1753f08 100644 --- a/src/lib/ecosystems/resolve-test-facts.ts +++ b/src/lib/ecosystems/resolve-test-facts.ts @@ -185,11 +185,8 @@ export async function resolveAndTestFactsUnmanagedDeps( extractAndApplyPluginAnalytics(scanResult.analytics, id); } - const { - start_time, - dep_graph_data, - component_details, - } = await pollDepGraphAttributes(id, orgId); + const { start_time, dep_graph_data, component_details } = + await pollDepGraphAttributes(id, orgId); const { issues, diff --git a/src/lib/ecosystems/unmanaged/utils.ts b/src/lib/ecosystems/unmanaged/utils.ts index 24b073ee4a..892f9ccd34 100644 --- a/src/lib/ecosystems/unmanaged/utils.ts +++ b/src/lib/ecosystems/unmanaged/utils.ts @@ -109,7 +109,8 @@ export async function getOrgDefaultContext(): Promise { } export function isUUID(str) { - const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + const uuidRegex = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; return uuidRegex.test(str); } diff --git a/src/lib/errors/legacy-errors.js b/src/lib/errors/legacy-errors.js index c7d8ab12ff..5c0b944ea3 100644 --- a/src/lib/errors/legacy-errors.js +++ b/src/lib/errors/legacy-errors.js @@ -71,7 +71,7 @@ module.exports = function error(command) { return Promise.reject(e); }; -module.exports.message = function(error) { +module.exports.message = function (error) { let message = error; // defaults to a string (which is super unlikely) if (error instanceof Error) { if (error.code === 'VULNS') { diff --git a/src/lib/formatters/iac-output/text/failures/list.ts b/src/lib/formatters/iac-output/text/failures/list.ts index ad590f0ee4..adb8ad9dd5 100644 --- a/src/lib/formatters/iac-output/text/failures/list.ts +++ b/src/lib/formatters/iac-output/text/failures/list.ts @@ -77,9 +77,8 @@ export function formatIacTestWarnings(testWarnings: IaCTestWarning[]): string { } function formatWarningsList(testWarnings: IaCTestWarning[]): string { - const testWarningsByReasonAndPath = groupTestWarningsByReasonAndPath( - testWarnings, - ); + const testWarningsByReasonAndPath = + groupTestWarningsByReasonAndPath(testWarnings); return Object.values(testWarningsByReasonAndPath) .map((testWarning) => { @@ -96,9 +95,9 @@ type groupedIacTestWarnings = { expressions: string[]; }; -function groupTestWarningsByReasonAndPath( - testWarnings: IaCTestWarning[], -): { [key: string]: groupedIacTestWarnings } { +function groupTestWarningsByReasonAndPath(testWarnings: IaCTestWarning[]): { + [key: string]: groupedIacTestWarnings; +} { return testWarnings.reduce( (groupedWarnings: { [key: string]: groupedIacTestWarnings }, warning) => { const reasonAndPath = `${warning.warningReason}${warning.filePath}`; diff --git a/src/lib/formatters/iac-output/text/issues-list/index.ts b/src/lib/formatters/iac-output/text/issues-list/index.ts index 9acaea8891..3a8d7cb747 100644 --- a/src/lib/formatters/iac-output/text/issues-list/index.ts +++ b/src/lib/formatters/iac-output/text/issues-list/index.ts @@ -30,9 +30,8 @@ export function getIacDisplayedIssues( const severitySectionsOutput = Object.values(SEVERITY) .filter((severity) => !!resultsBySeverity[severity]) .map((severity) => { - const severityResults: FormattedOutputResult[] = resultsBySeverity[ - severity - ]!; + const severityResults: FormattedOutputResult[] = + resultsBySeverity[severity]!; const titleOutput = colors.title( `${capitalize(severity)} Severity Issues: ${severityResults.length}`, diff --git a/src/lib/formatters/iac-output/text/utils.ts b/src/lib/formatters/iac-output/text/utils.ts index 71a5be1f39..af50fb2533 100644 --- a/src/lib/formatters/iac-output/text/utils.ts +++ b/src/lib/formatters/iac-output/text/utils.ts @@ -39,11 +39,10 @@ export const maxLineWidth = process.stdout.columns export const countSuppressedIssues = ( suppressedIssues: Record, ): number => { - return Object.values(suppressedIssues).reduce(function( + return Object.values(suppressedIssues).reduce(function ( count, resourcesForRuleId, ) { return (count += resourcesForRuleId.length); - }, - 0); + }, 0); }; diff --git a/src/lib/formatters/open-source-sarif-output.ts b/src/lib/formatters/open-source-sarif-output.ts index 0388674197..52e68a00bf 100644 --- a/src/lib/formatters/open-source-sarif-output.ts +++ b/src/lib/formatters/open-source-sarif-output.ts @@ -106,6 +106,6 @@ function getIntroducedThrough(vuln: AnnotatedIssue) { return vuln.from.length > 2 ? `${firstFrom}, ${secondFrom} and others` : vuln.from.length === 2 - ? `${firstFrom} and ${secondFrom}` - : firstFrom; + ? `${firstFrom} and ${secondFrom}` + : firstFrom; } diff --git a/src/lib/formatters/test/format-test-results.ts b/src/lib/formatters/test/format-test-results.ts index dff3d27d18..5354c861dd 100644 --- a/src/lib/formatters/test/format-test-results.ts +++ b/src/lib/formatters/test/format-test-results.ts @@ -355,9 +355,7 @@ function getDockerRemediationDocsLink(dockerAdvice: string, config): string { ); } -export function groupVulnerabilities( - vulns, -): { +export function groupVulnerabilities(vulns): { [vulnId: string]: GroupedVuln; } { return vulns.reduce((map, curr) => { diff --git a/src/lib/iac/drift/driftctl.ts b/src/lib/iac/drift/driftctl.ts index 7462bf7b25..7f960f5c86 100644 --- a/src/lib/iac/drift/driftctl.ts +++ b/src/lib/iac/drift/driftctl.ts @@ -331,7 +331,7 @@ async function download(url, destination: string): Promise { await spinner('Downloading...'); return new Promise((resolve, reject) => { - makeRequest(payload, function(err, res, body) { + makeRequest(payload, function (err, res, body) { try { if (err) { reject( @@ -368,10 +368,7 @@ function validateChecksum(body: string) { return; } - const computedHash = crypto - .createHash('sha256') - .update(body) - .digest('hex'); + const computedHash = crypto.createHash('sha256').update(body).digest('hex'); const givenHash = driftctlChecksums[driftctlFileName()]; if (computedHash != givenHash) { diff --git a/src/lib/iac/test/v2/analytics/iac-cloud-context.ts b/src/lib/iac/test/v2/analytics/iac-cloud-context.ts index 1477f92512..96c0aedb5c 100644 --- a/src/lib/iac/test/v2/analytics/iac-cloud-context.ts +++ b/src/lib/iac/test/v2/analytics/iac-cloud-context.ts @@ -23,9 +23,8 @@ export function getIacCloudContext( let iacCloudContextSuppressedIssuesCount = 0; const suppressedIssues = testOutput.results?.scanAnalytics?.suppressedResults; if (suppressedIssues) { - iacCloudContextSuppressedIssuesCount = countSuppressedIssues( - suppressedIssues, - ); + iacCloudContextSuppressedIssuesCount = + countSuppressedIssues(suppressedIssues); } return { diff --git a/src/lib/iac/test/v2/analytics/iac-type.ts b/src/lib/iac/test/v2/analytics/iac-type.ts index 0ebb5b4178..928d4e5013 100644 --- a/src/lib/iac/test/v2/analytics/iac-type.ts +++ b/src/lib/iac/test/v2/analytics/iac-type.ts @@ -2,15 +2,13 @@ import { SEVERITY } from '../../../../snyk-test/legacy'; import { ResourceKind, TestOutput } from '../scan/results'; export function getIacType(testOutput: TestOutput): IacType { - const resourcesCountByPackageManager = getResourcesCountByPackageManager( - testOutput, - ); + const resourcesCountByPackageManager = + getResourcesCountByPackageManager(testOutput); const filesCountByPackageManager = getFilesCountByPackageManager(testOutput); - const vulnAnalyticsByPackageManager = getVulnerabilityAnalyticsByPackageManager( - testOutput, - ); + const vulnAnalyticsByPackageManager = + getVulnerabilityAnalyticsByPackageManager(testOutput); return Object.keys(resourcesCountByPackageManager).reduce( (acc, packageManager) => { @@ -68,19 +66,22 @@ function getFilesCountByPackageManager( } return Object.entries( - testOutput.results.resources.reduce((acc, resource) => { - const packageManager = resource.kind; - - if (!acc[packageManager]) { - acc[packageManager] = new Set(); - } - - if (resource.file) { - acc[packageManager].add(resource.file); - } - - return acc; - }, {} as { [packageManager in PackageManager]: Set }), + testOutput.results.resources.reduce( + (acc, resource) => { + const packageManager = resource.kind; + + if (!acc[packageManager]) { + acc[packageManager] = new Set(); + } + + if (resource.file) { + acc[packageManager].add(resource.file); + } + + return acc; + }, + {} as { [packageManager in PackageManager]: Set }, + ), ).reduce((acc, [packageManager, filesSet]) => { acc[packageManager] = filesSet.size; diff --git a/src/lib/iac/test/v2/index.ts b/src/lib/iac/test/v2/index.ts index fdc6f1d5bd..7b915960b7 100644 --- a/src/lib/iac/test/v2/index.ts +++ b/src/lib/iac/test/v2/index.ts @@ -7,11 +7,8 @@ import { addIacAnalytics } from './analytics'; export { TestConfig } from './types'; export async function test(testConfig: TestConfig): Promise { - const { - policyEnginePath, - rulesBundlePath, - rulesClientURL, - } = await initLocalCache(testConfig); + const { policyEnginePath, rulesBundlePath, rulesClientURL } = + await initLocalCache(testConfig); const testOutput = await scan( testConfig, diff --git a/src/lib/iac/test/v2/json.ts b/src/lib/iac/test/v2/json.ts index 5724b1e3d3..effb37bec4 100644 --- a/src/lib/iac/test/v2/json.ts +++ b/src/lib/iac/test/v2/json.ts @@ -254,9 +254,8 @@ function vulnerabilitiesToResult( vulnerabilitiesToKind(passedVulnerabilities); const ignoreSettings = testOutput.settings.ignoreSettings; const meta = orgSettingsToMeta(testOutput, ignoreSettings); - const infrastructureAsCodeIssues = vulnerabilitiesToIacIssues( - vulnerabilities, - ); + const infrastructureAsCodeIssues = + vulnerabilitiesToIacIssues(vulnerabilities); const infrastructureAsCodeSuccesses = passedVulnerabilitiesToIacSuccesses( passedVulnerabilities, ); diff --git a/src/lib/iac/test/v2/output.ts b/src/lib/iac/test/v2/output.ts index 82d3bbe023..f937503a88 100644 --- a/src/lib/iac/test/v2/output.ts +++ b/src/lib/iac/test/v2/output.ts @@ -252,8 +252,8 @@ export class NoSuccessfulScansError extends FormattedCustomError { const message = options.json ? responseData.json : options.sarif - ? responseData.sarif - : firstErr.message; + ? responseData.sarif + : firstErr.message; super( message, isText diff --git a/src/lib/index.js b/src/lib/index.js index ed815a014e..e1e3ad811c 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -16,10 +16,10 @@ const apiToken = require('./api-token'); Object.defineProperty(snyk, 'api', { enumerable: true, configurable: true, - get: function() { + get: function () { return apiToken.api(); }, - set: function(value) { + set: function (value) { snykConfig.api = value; }, }); diff --git a/src/lib/monitor/dev-count-analysis.ts b/src/lib/monitor/dev-count-analysis.ts index afe941a5ae..c13589950f 100644 --- a/src/lib/monitor/dev-count-analysis.ts +++ b/src/lib/monitor/dev-count-analysis.ts @@ -21,10 +21,8 @@ export async function getContributors( repoPath: process.cwd(), }, ): Promise { - const timestampStartOfContributingDeveloperPeriod = getTimestampStartOfContributingDevTimeframe( - endDate, - periodDays, - ); + const timestampStartOfContributingDeveloperPeriod = + getTimestampStartOfContributingDevTimeframe(endDate, periodDays); const gitLogResults = await runGitLog( timestampStartOfContributingDeveloperPeriod, Math.floor(endDate.getTime() / 1000), diff --git a/src/lib/monitor/index.ts b/src/lib/monitor/index.ts index c54085d6d9..beca7aa38d 100644 --- a/src/lib/monitor/index.ts +++ b/src/lib/monitor/index.ts @@ -437,10 +437,8 @@ async function monitorDepGraphFromDepTree( treeMissingDeps = missingDeps; } - const depGraph: depGraphLib.DepGraph = await depGraphLib.legacy.depTreeToGraph( - depTree, - packageManager, - ); + const depGraph: depGraphLib.DepGraph = + await depGraphLib.legacy.depTreeToGraph(depTree, packageManager); const target = await projectMetadata.getInfo(scannedProject, meta, depTree); if (isGitTarget(target) && target.branch) { diff --git a/src/lib/plugins/get-multi-plugin-result.ts b/src/lib/plugins/get-multi-plugin-result.ts index f5943c231f..aac5fae1ef 100644 --- a/src/lib/plugins/get-multi-plugin-result.ts +++ b/src/lib/plugins/get-multi-plugin-result.ts @@ -75,10 +75,8 @@ export async function getMultiPluginResult( let unprocessedFilesfromWorkspaces = targetFiles; if (featureFlags.has(PNPM_FEATURE_FLAG)) { - const { - scannedProjects: scannedPnpmResults, - unprocessedFiles, - } = await processWorkspacesProjects(root, options, targetFiles, 'pnpm'); + const { scannedProjects: scannedPnpmResults, unprocessedFiles } = + await processWorkspacesProjects(root, options, targetFiles, 'pnpm'); unprocessedFilesfromWorkspaces = unprocessedFiles; allResults.push(...scannedPnpmResults); } @@ -94,15 +92,13 @@ export async function getMultiPluginResult( ); allResults.push(...scannedYarnResults); - const { - scannedProjects: scannedNpmResults, - unprocessedFiles, - } = await processWorkspacesProjects( - root, - options, - unprocessedFilesFromYarn, - 'npm', - ); + const { scannedProjects: scannedNpmResults, unprocessedFiles } = + await processWorkspacesProjects( + root, + options, + unprocessedFilesFromYarn, + 'npm', + ); allResults.push(...scannedNpmResults); debug(`Not part of a workspace: ${unprocessedFiles.join(', ')}}`); @@ -132,17 +128,19 @@ export async function getMultiPluginResult( resultWithScannedProjects = inspectRes; } - const pluginResultWithCustomScannedProjects = convertMultiResultToMultiCustom( - resultWithScannedProjects, - optionsClone.packageManager, - optionsClone.file, - ); + const pluginResultWithCustomScannedProjects = + convertMultiResultToMultiCustom( + resultWithScannedProjects, + optionsClone.packageManager, + optionsClone.file, + ); // annotate the package manager, project name & targetFile to be used // for test & monitor // TODO: refactor how we display meta to not have to do this - (options as any).projectNames = resultWithScannedProjects.scannedProjects.map( - (scannedProject) => scannedProject?.depTree?.name, - ); + (options as any).projectNames = + resultWithScannedProjects.scannedProjects.map( + (scannedProject) => scannedProject?.depTree?.name, + ); allResults.push(...pluginResultWithCustomScannedProjects.scannedProjects); } catch (error) { diff --git a/src/lib/plugins/nodejs-plugin/npm-lock-parser.ts b/src/lib/plugins/nodejs-plugin/npm-lock-parser.ts index ff92b87b33..f4af62dbda 100644 --- a/src/lib/plugins/nodejs-plugin/npm-lock-parser.ts +++ b/src/lib/plugins/nodejs-plugin/npm-lock-parser.ts @@ -55,9 +55,8 @@ export async function parse( debug(resolveModuleSpinnerLabel); const strictOutOfSync = options.strictOutOfSync !== false; - const lockfileVersion = lockFileParser.getLockfileVersionFromFile( - lockFileFullPath, - ); + const lockfileVersion = + lockFileParser.getLockfileVersionFromFile(lockFileFullPath); if ( lockfileVersion === NodeLockfileVersion.YarnLockV1 || lockfileVersion === NodeLockfileVersion.YarnLockV2 || diff --git a/src/lib/plugins/nodejs-plugin/npm-workspaces-parser.ts b/src/lib/plugins/nodejs-plugin/npm-workspaces-parser.ts index 0131f54d31..0eacd63abf 100644 --- a/src/lib/plugins/nodejs-plugin/npm-workspaces-parser.ts +++ b/src/lib/plugins/nodejs-plugin/npm-workspaces-parser.ts @@ -166,9 +166,9 @@ export function packageJsonBelongsToWorkspace( const workspaceRootFolder = pathUtil.dirname( workspaceRoot.replace(/\\/g, '/'), ); - const workspacesGlobs = ( - workspacesMap[workspaceRoot].workspaces || [] - ).map((workspace) => pathUtil.join(workspaceRootFolder, workspace)); + const workspacesGlobs = (workspacesMap[workspaceRoot].workspaces || []).map( + (workspace) => pathUtil.join(workspaceRootFolder, workspace), + ); const match = micromatch.isMatch( packageJsonFileName.replace(/\\/g, '/'), diff --git a/src/lib/plugins/sast/analysis.ts b/src/lib/plugins/sast/analysis.ts index d6b4472693..a35f3f88c5 100644 --- a/src/lib/plugins/sast/analysis.ts +++ b/src/lib/plugins/sast/analysis.ts @@ -252,9 +252,9 @@ function parseSecurityResults(codeAnalysis: Log): Log { return codeAnalysis; } -function getSecurityRulesMap( - rules: ReportingDescriptor[], -): { [ruleId: string]: ReportingDescriptor[] } { +function getSecurityRulesMap(rules: ReportingDescriptor[]): { + [ruleId: string]: ReportingDescriptor[]; +} { const securityRulesMap = rules.reduce((acc, rule) => { const { id: ruleId, properties } = rule; const isSecurityRule = properties?.categories?.some( diff --git a/src/lib/plugins/sast/format/output-format.ts b/src/lib/plugins/sast/format/output-format.ts index 9eb2ad7c51..0bef86d3dd 100644 --- a/src/lib/plugins/sast/format/output-format.ts +++ b/src/lib/plugins/sast/format/output-format.ts @@ -136,9 +136,9 @@ function getIssues( return issues; } -function getRulesMap( - rules: Sarif.ReportingDescriptor[], -): { [ruleId: string]: Sarif.ReportingDescriptor } { +function getRulesMap(rules: Sarif.ReportingDescriptor[]): { + [ruleId: string]: Sarif.ReportingDescriptor; +} { const rulesMapByID = rules.reduce((acc, rule) => { acc[rule.id] = rule; return acc; diff --git a/src/lib/plugins/sast/index.ts b/src/lib/plugins/sast/index.ts index 5207e2ddbd..ad0151cdda 100644 --- a/src/lib/plugins/sast/index.ts +++ b/src/lib/plugins/sast/index.ts @@ -124,8 +124,9 @@ export const codePlugin: EcosystemPlugin = { } debug( chalk.bold.red( - `requestId: ${requestId} statusCode:${error.code || - error.statusCode}, message: ${error.statusText || error.message}`, + `requestId: ${requestId} statusCode:${ + error.code || error.statusCode + }, message: ${error.statusText || error.message}`, ), ); throw err; diff --git a/src/lib/protect-update-notification.ts b/src/lib/protect-update-notification.ts index 07c19eb9bf..4ca1954179 100644 --- a/src/lib/protect-update-notification.ts +++ b/src/lib/protect-update-notification.ts @@ -87,9 +87,8 @@ export function getPackageJsonPathsContainingSnykDependency( directoryWithPackageJson, 'package.json', ); - const packageJsonContainsSnykDep = checkPackageJsonForSnykDependency( - packageJsonPath, - ); + const packageJsonContainsSnykDep = + checkPackageJsonForSnykDependency(packageJsonPath); if (packageJsonContainsSnykDep) { packageJsonPathsWithSnykDepForProtect.push(packageJsonPath); } @@ -99,9 +98,8 @@ export function getPackageJsonPathsContainingSnykDependency( paths.forEach((testPath) => { if (packageJsonFileExistsInDirectory(testPath)) { const packageJsonPath = path.resolve(testPath, 'package.json'); - const packageJsonContainsSnykDep = checkPackageJsonForSnykDependency( - packageJsonPath, - ); + const packageJsonContainsSnykDep = + checkPackageJsonForSnykDependency(packageJsonPath); if (packageJsonContainsSnykDep) { packageJsonPathsWithSnykDepForProtect.push(packageJsonPath); } diff --git a/src/lib/request/snyk-http-client.ts b/src/lib/request/snyk-http-client.ts index c0b7501915..73e3994607 100644 --- a/src/lib/request/snyk-http-client.ts +++ b/src/lib/request/snyk-http-client.ts @@ -17,9 +17,7 @@ interface RequestInfo { family?: number; } -export async function snykHttpClient( - requestInfo: RequestInfo, -): Promise<{ +export async function snykHttpClient(requestInfo: RequestInfo): Promise<{ res: needle.NeedleResponse; body: any; }> { diff --git a/src/lib/snyk-test/assemble-payloads.ts b/src/lib/snyk-test/assemble-payloads.ts index 5ad8bc6267..76527108af 100644 --- a/src/lib/snyk-test/assemble-payloads.ts +++ b/src/lib/snyk-test/assemble-payloads.ts @@ -56,8 +56,9 @@ export async function assembleEcosystemPayloads( payloads.push({ method: 'POST', - url: `${config.API}${options.testDepGraphDockerEndpoint || - '/test-dependencies'}`, + url: `${config.API}${ + options.testDepGraphDockerEndpoint || '/test-dependencies' + }`, json: true, headers: { 'x-is-ci': isCI(), diff --git a/src/lib/snyk-test/legacy.ts b/src/lib/snyk-test/legacy.ts index df0bd06239..bbd88f80b2 100644 --- a/src/lib/snyk-test/legacy.ts +++ b/src/lib/snyk-test/legacy.ts @@ -407,7 +407,7 @@ function convertTestDepGraphResultToLegacy( const pkgAndVersion = (pkgInfo.pkg.name + '@' + pkgInfo.pkg.version) as string; - const annotatedIssue = (Object.assign( + const annotatedIssue = Object.assign( {}, binariesVulns.issuesData[pkgIssue.issueId], { @@ -419,7 +419,7 @@ function convertTestDepGraphResultToLegacy( version: pkgInfo.pkg.version as string, nearestFixedInVersion: pkgIssue.fixInfo.nearestFixedInVersion, }, - ) as any) as AnnotatedIssue; // TODO(kyegupov): get rid of forced type assertion + ) as any as AnnotatedIssue; // TODO(kyegupov): get rid of forced type assertion vulns.push(annotatedIssue); } } diff --git a/src/lib/snyk-test/run-test.ts b/src/lib/snyk-test/run-test.ts index c38c98ca7b..2bdcac7f1d 100644 --- a/src/lib/snyk-test/run-test.ts +++ b/src/lib/snyk-test/run-test.ts @@ -429,7 +429,7 @@ async function parseRes( // refactor to separate if (depGraph && pkgManager) { res = convertTestDepGraphResultToLegacy( - (res as any) as TestDepGraphResponse, // Double "as" required by Typescript for dodgy assertions + res as any as TestDepGraphResponse, // Double "as" required by Typescript for dodgy assertions depGraph, pkgManager, options, @@ -634,9 +634,9 @@ async function assembleLocalPayloads( if (!options.json && !options.quiet) { console.warn( chalk.bold.red( - `${icon.ISSUE} ${failedResults.length}/${failedResults.length + - deps.scannedProjects - .length} potential projects failed to get dependencies.`, + `${icon.ISSUE} ${failedResults.length}/${ + failedResults.length + deps.scannedProjects.length + } potential projects failed to get dependencies.`, ), ); failedResults.forEach((f) => { @@ -694,12 +694,10 @@ async function assembleLocalPayloads( // prefer dep-graph fallback on dep tree // TODO: clean up once dep-graphs only - const pkg: - | DepTree - | depGraphLib.DepGraph - | undefined = scannedProject.depGraph - ? scannedProject.depGraph - : scannedProject.depTree; + const pkg: DepTree | depGraphLib.DepGraph | undefined = + scannedProject.depGraph + ? scannedProject.depGraph + : scannedProject.depTree; if (options['print-deps']) { if (scannedProject.depGraph) { @@ -888,8 +886,9 @@ async function assembleRemotePayloads(root, options): Promise { addPackageAnalytics(pkg.name, pkg.version); const encodedName = encodeURIComponent(pkg.name + '@' + pkg.version); // options.vulnEndpoint is only used by `snyk protect` (i.e. local filesystem tests) - const url = `${config.API}${options.vulnEndpoint || - `/vuln/${options.packageManager}`}/${encodedName}`; + const url = `${config.API}${ + options.vulnEndpoint || `/vuln/${options.packageManager}` + }/${encodedName}`; return [ { method: 'GET', diff --git a/src/lib/spinner.ts b/src/lib/spinner.ts index 2c1789fe56..bb0128716a 100644 --- a/src/lib/spinner.ts +++ b/src/lib/spinner.ts @@ -92,7 +92,7 @@ function createSpinner(opt: SpinnerOptions): Spinner | false { let delay = typeof opt.delay === 'number' ? opt.delay : 2; - const interval = (setInterval(() => { + const interval = setInterval(() => { if (--delay >= 0) { return; } @@ -100,7 +100,7 @@ function createSpinner(opt: SpinnerOptions): Spinner | false { const c = sprite[s]; str.write(c + ' ' + (opt.label || '') + CR); wrote = true; - }, ms) as unknown) as NodeJS.Timer; + }, ms) as unknown as NodeJS.Timer; const unref = typeof opt.unref === 'boolean' ? opt.unref : true; if (unref && typeof interval.unref === 'function') { diff --git a/test/acceptance/fake-server.ts b/test/acceptance/fake-server.ts index 97ade2d51a..5e61592f66 100644 --- a/test/acceptance/fake-server.ts +++ b/test/acceptance/fake-server.ts @@ -489,8 +489,7 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => { isMonitored: true, trialStarted: true, licensesPolicy: {}, - uri: - 'http://example-url/project/project-public-id/history/snapshot-public-id', + uri: 'http://example-url/project/project-public-id/history/snapshot-public-id', projectName: 'test-project', }); }); @@ -720,8 +719,7 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => { version: '1.0', }, links: { - self: - '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests?version=2023-08-31~beta', + self: '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests?version=2023-08-31~beta', related: '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests/4b341b8a-4697-4e35-928b-4b9ae37f8ea8?version=2023-08-31~beta', }, @@ -763,8 +761,7 @@ export const fakeServer = (basePath: string, snykToken: string): FakeServer => { }, }, links: { - self: - '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests/4b341b8a-4697-4e35-928b-4b9ae37f8ea8?version=2023-08-31~beta', + self: '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests/4b341b8a-4697-4e35-928b-4b9ae37f8ea8?version=2023-08-31~beta', related: '/rest/orgs/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/sbom_tests/4b341b8a-4697-4e35-928b-4b9ae37f8ea8/results?version=2023-08-31~beta', }, diff --git a/test/jest/acceptance/cli-json-file-output.spec.ts b/test/jest/acceptance/cli-json-file-output.spec.ts index 28f5138920..ec01fa175b 100644 --- a/test/jest/acceptance/cli-json-file-output.spec.ts +++ b/test/jest/acceptance/cli-json-file-output.spec.ts @@ -74,9 +74,8 @@ describe('test --json-file-output', () => { const reference = response.result.issuesData['SNYK-ALPINE319-OPENSSL-6148881'] .references[0]; - response.result.issuesData[ - 'SNYK-ALPINE319-OPENSSL-6148881' - ].references = new Array(420000).fill(reference); + response.result.issuesData['SNYK-ALPINE319-OPENSSL-6148881'].references = + new Array(420000).fill(reference); server.setCustomResponse(response); diff --git a/test/jest/acceptance/cli-json-output.spec.ts b/test/jest/acceptance/cli-json-output.spec.ts index 1fb65b7b3f..abbd1567e1 100644 --- a/test/jest/acceptance/cli-json-output.spec.ts +++ b/test/jest/acceptance/cli-json-output.spec.ts @@ -113,7 +113,7 @@ describe('test --json', () => { let hasReferenceCount = false; const p = new Parser(); - p.onValue = function(value) { + p.onValue = function (value) { if (this.key === 'path' && value === imageName) { hasExpectedPathString = true; } else if (this.key === 'vulnerabilities') { diff --git a/test/jest/acceptance/https.spec.ts b/test/jest/acceptance/https.spec.ts index a69737e07e..669854fbe9 100644 --- a/test/jest/acceptance/https.spec.ts +++ b/test/jest/acceptance/https.spec.ts @@ -71,10 +71,7 @@ describe('https', () => { expect(code).toBe(0); // get rid of the first entry which has another User Agent - server - .getRequests() - .reverse() - .pop(); + server.getRequests().reverse().pop(); for (const r of server.getRequests()) { expect(r.headers['user-agent']).toContain('snyk-cli/'); diff --git a/test/jest/acceptance/iac/helpers.ts b/test/jest/acceptance/iac/helpers.ts index 1e0fd3a3f2..f89652b8a3 100644 --- a/test/jest/acceptance/iac/helpers.ts +++ b/test/jest/acceptance/iac/helpers.ts @@ -69,7 +69,7 @@ export async function run( }, cwd: cwd ?? join(root, 'test/fixtures'), }, - function(err, stdout, stderr) { + function (err, stdout, stderr) { // err.code indicates the shell exited with non-zero code // which is in our case a success and we resolve. if (err && typeof err.code !== 'number') { diff --git a/test/jest/acceptance/snyk-apps/config.spec.ts b/test/jest/acceptance/snyk-apps/config.spec.ts index 789118bc55..69b7b4a490 100644 --- a/test/jest/acceptance/snyk-apps/config.spec.ts +++ b/test/jest/acceptance/snyk-apps/config.spec.ts @@ -34,9 +34,7 @@ describe('config', () => { SNYK_API_REST_URL: 'http://localhost:' + port + baseURL, }; - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `apps create --org=${testData.orgId} --name=${testData.appName} --redirect-uris=${testData.redirectURIs} --scopes=${testData.scopes} --experimental`, { env }, ); @@ -50,9 +48,7 @@ describe('config', () => { SNYK_API_REST_URL: 'http://localhost:' + port + '/wrongbase', }; - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `apps create --org=${testData.orgId} --name=${testData.appName} --redirect-uris=${testData.redirectURIs} --scopes=${testData.scopes} --experimental`, { env }, ); @@ -66,9 +62,7 @@ describe('config', () => { SNYK_API_V3_URL: 'http://localhost:' + port + baseURL, }; - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `apps create --org=${testData.orgId} --name=${testData.appName} --redirect-uris=${testData.redirectURIs} --scopes=${testData.scopes} --experimental`, { env }, ); @@ -83,9 +77,7 @@ describe('config', () => { SNYK_API_V3_URL: 'http://localhost:' + port + baseURL, }; - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `apps create --org=${testData.orgId} --name=${testData.appName} --redirect-uris=${testData.redirectURIs} --scopes=${testData.scopes} --experimental`, { env }, ); diff --git a/test/jest/acceptance/snyk-code/snyk-code.spec.ts b/test/jest/acceptance/snyk-code/snyk-code.spec.ts index 7088b730d7..1e7a376422 100644 --- a/test/jest/acceptance/snyk-code/snyk-code.spec.ts +++ b/test/jest/acceptance/snyk-code/snyk-code.spec.ts @@ -329,8 +329,8 @@ describe('snyk code test', () => { }, ); - const actualCodeSecurityIssues = JSON.parse(stdout)?.runs[0] - ?.results?.length; + const actualCodeSecurityIssues = + JSON.parse(stdout)?.runs[0]?.results?.length; expect(actualCodeSecurityIssues).toEqual( expectedCodeSecurityIssues, ); @@ -350,8 +350,8 @@ describe('snyk code test', () => { }, ); - const actualCodeSecurityIssues = JSON.parse(stdout)?.runs[0] - ?.results?.length; + const actualCodeSecurityIssues = + JSON.parse(stdout)?.runs[0]?.results?.length; expect(actualCodeSecurityIssues).toEqual( expectedHighCodeSecurityIssues, ); @@ -432,8 +432,8 @@ describe('snyk code test', () => { }, ); - const actualCodeSecurityIssues = JSON.parse(stdout)?.runs[0]?.results - ?.length; + const actualCodeSecurityIssues = + JSON.parse(stdout)?.runs[0]?.results?.length; expect(actualCodeSecurityIssues).toEqual(expectedCodeSecurityIssues); }); diff --git a/test/jest/acceptance/snyk-config/snyk-config-environment.spec.ts b/test/jest/acceptance/snyk-config/snyk-config-environment.spec.ts index ef4aaf31b1..aae2b74350 100644 --- a/test/jest/acceptance/snyk-config/snyk-config-environment.spec.ts +++ b/test/jest/acceptance/snyk-config/snyk-config-environment.spec.ts @@ -51,10 +51,10 @@ describe('snyk config environment', () => { }); it('fail with an invalid env alias', async () => { - const { - code, - stderr, - } = await runSnykCLI(`config environment randomEnvName`, { env: env }); + const { code, stderr } = await runSnykCLI( + `config environment randomEnvName`, + { env: env }, + ); expect(stderr).toEqual(''); expect(code).toEqual(2); }); diff --git a/test/jest/acceptance/snyk-container/container.spec.ts b/test/jest/acceptance/snyk-container/container.spec.ts index e9b2ee8b19..0ae1f4210d 100644 --- a/test/jest/acceptance/snyk-container/container.spec.ts +++ b/test/jest/acceptance/snyk-container/container.spec.ts @@ -40,8 +40,7 @@ describe('snyk container', () => { id: 'base-files@11.1+deb11u7', info: { name: 'base-files', - purl: - 'pkg:deb/debian/base-files@11.1%2Bdeb11u7?distro=debian-bullseye', + purl: 'pkg:deb/debian/base-files@11.1%2Bdeb11u7?distro=debian-bullseye', version: '11.1+deb11u7', }, }, @@ -57,8 +56,7 @@ describe('snyk container', () => { id: 'tzdata@2021a-1+deb11u10', info: { name: 'tzdata', - purl: - 'pkg:deb/debian/tzdata@2021a-1%2Bdeb11u10?distro=debian-bullseye', + purl: 'pkg:deb/debian/tzdata@2021a-1%2Bdeb11u10?distro=debian-bullseye', version: '2021a-1+deb11u10', }, }, @@ -268,11 +266,7 @@ DepGraph end`, }, meta: { org: 'test-org', isPublic: false }, }); - const { - code, - stdout, - stderr, - } = await runSnykCLIWithDebug( + const { code, stdout, stderr } = await runSnykCLIWithDebug( `container sbom --org=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --format=spdx2.3+json ${TEST_DISTROLESS_STATIC_IMAGE}`, { env }, ); @@ -300,11 +294,7 @@ DepGraph end`, }, meta: { org: 'test-org', isPublic: false }, }); - const { - code, - stdout, - stderr, - } = await runSnykCLIWithDebug( + const { code, stdout, stderr } = await runSnykCLIWithDebug( `container sbom --org=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --format=cyclonedx1.4+json ${TEST_DISTROLESS_STATIC_IMAGE}`, { env }, ); @@ -336,11 +326,7 @@ DepGraph end`, }, meta: { org: 'test-org', isPublic: false }, }); - const { - code, - stdout, - stderr, - } = await runSnykCLIWithDebug( + const { code, stdout, stderr } = await runSnykCLIWithDebug( `container sbom --org=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --format=cyclonedx1.5+json ${TEST_DISTROLESS_STATIC_IMAGE}`, { env }, ); diff --git a/test/jest/acceptance/snyk-ignore/snyk-ignore.spec.ts b/test/jest/acceptance/snyk-ignore/snyk-ignore.spec.ts index 014f709363..d179c547d0 100644 --- a/test/jest/acceptance/snyk-ignore/snyk-ignore.spec.ts +++ b/test/jest/acceptance/snyk-ignore/snyk-ignore.spec.ts @@ -83,9 +83,7 @@ describe('snyk ignore', () => { it('create a policy file with exclude, using custom group', async () => { const project = await createProjectFromWorkspace('empty'); - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `ignore --file-path=**/deps/**/*.ts --file-path-group=code --policy-path=${project.path()}`, { cwd: project.path(), env: env }, ); @@ -128,9 +126,7 @@ describe('snyk ignore', () => { it('write a policy file for exclude by providing group, expiry and reason', async () => { const project = await createProjectFromWorkspace('empty'); - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `ignore --file-path=**/deps/**/*.ts --file-path-group=code --reason=unknown-reason --expiry=2099-12-24 --policy-path=${project.path()}`, { cwd: project.path(), env: env }, ); @@ -175,9 +171,7 @@ describe('snyk ignore', () => { code: ['**/deps/**/*.ts'], }); - const { - code, - } = await runSnykCLI( + const { code } = await runSnykCLI( `ignore --file-path=**/deps/**/*.ts --file-path-group=code --reason=unknown-reason --expiry=2099-12-24`, { cwd: project.path(), env: env }, ); diff --git a/test/jest/acceptance/snyk-sbom-test/all-projects.spec.ts b/test/jest/acceptance/snyk-sbom-test/all-projects.spec.ts index 3437539705..0b935b29d9 100644 --- a/test/jest/acceptance/snyk-sbom-test/all-projects.spec.ts +++ b/test/jest/acceptance/snyk-sbom-test/all-projects.spec.ts @@ -44,11 +44,7 @@ describe('snyk sbom test (mocked server only)', () => { 'npm-sbom-cdx15.json', ); - const { - code, - stdout, - stderr, - } = await runSnykCLI( + const { code, stdout, stderr } = await runSnykCLI( `sbom test --org aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --experimental --file ${fileToTest}`, { env }, ); @@ -82,11 +78,7 @@ describe('snyk sbom test (mocked server only)', () => { 'npm-sbom-cdx15.json', ); - const { - code, - stdout, - stderr, - } = await runSnykCLI( + const { code, stdout, stderr } = await runSnykCLI( `sbom test --org aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --experimental --file ${fileToTest} --json`, { env }, ); @@ -119,10 +111,7 @@ describe('snyk sbom test (mocked server only)', () => { 'npm-sbom-cdx15.json', ); - const { - stdout, - stderr, - } = await runSnykCLI( + const { stdout, stderr } = await runSnykCLI( `sbom test --org aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --file ${fileToTest}`, { env }, ); @@ -135,10 +124,7 @@ describe('snyk sbom test (mocked server only)', () => { }); test('missing file flag', async () => { - const { - stdout, - stderr, - } = await runSnykCLI( + const { stdout, stderr } = await runSnykCLI( `sbom test --org aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --experimental`, { env }, ); @@ -152,11 +138,7 @@ describe('snyk sbom test (mocked server only)', () => { test('bad SBOM input', async () => { const fileToTest = path.resolve(getFixturePath('sbom'), 'bad-sbom.json'); - const { - code, - stdout, - stderr, - } = await runSnykCLI( + const { code, stdout, stderr } = await runSnykCLI( `sbom test --org aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --experimental --file ${fileToTest}`, { env }, ); diff --git a/test/jest/acceptance/snyk-test/basic-test-all-languages.spec.ts b/test/jest/acceptance/snyk-test/basic-test-all-languages.spec.ts index 044d44aefb..c5acd5de11 100644 --- a/test/jest/acceptance/snyk-test/basic-test-all-languages.spec.ts +++ b/test/jest/acceptance/snyk-test/basic-test-all-languages.spec.ts @@ -80,7 +80,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { const project = await createProjectFromWorkspace('pip-app'); let pythonCommand = 'python'; - await runCommand(pythonCommand, ['--version']).catch(function() { + await runCommand(pythonCommand, ['--version']).catch(function () { pythonCommand = 'python3'; }); @@ -126,7 +126,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { const project = await createProjectFromWorkspace('pip-app'); let wrongPythonCommand = 'pthon'; - await runCommand(wrongPythonCommand, ['--version']).catch(function() { + await runCommand(wrongPythonCommand, ['--version']).catch(function () { wrongPythonCommand = 'pthon3'; }); @@ -143,7 +143,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { const project = await createProjectFromWorkspace('pipenv-app'); let pythonCommand = 'python'; - await runCommand(pythonCommand, ['--version']).catch(function() { + await runCommand(pythonCommand, ['--version']).catch(function () { pythonCommand = 'python3'; }); @@ -240,7 +240,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { 'run `snyk test` on a nuget project using v2 dotnet runtime resolution logic for $fixture', async ({ fixture, targetFile }) => { let prerequisite = await runCommand('dotnet', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); @@ -292,7 +292,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { test('run `snyk test` on a nuget project using v2 dotnet runtime resolution logic with a custom output path', async () => { let prerequisite = await runCommand('dotnet', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); @@ -349,7 +349,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { 'run `snyk test` on a nuget project using v2 dotnet runtime resolution logic with explicit target framework $targetFramework', async ({ targetFramework }) => { let prerequisite = await runCommand('dotnet', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); @@ -436,7 +436,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { test('run `snyk test` on a hex project', async () => { const prerequisite = await runCommand('mix', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); @@ -456,7 +456,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { test('run `snyk test` on a composer project', async () => { const prerequisite = await runCommand('composer', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); @@ -476,7 +476,7 @@ describe('`snyk test` of basic projects for each language/ecosystem', () => { test('run `snyk test` on a sbt project', async () => { const prerequisite = await runCommand('sbt', ['--version']).catch( - function() { + function () { return { code: 1, stderr: '', stdout: '' }; }, ); diff --git a/test/jest/unit/cli/commands/test/iac/v2/index.spec.ts b/test/jest/unit/cli/commands/test/iac/v2/index.spec.ts index 2426fabd53..b58ad34eab 100644 --- a/test/jest/unit/cli/commands/test/iac/v2/index.spec.ts +++ b/test/jest/unit/cli/commands/test/iac/v2/index.spec.ts @@ -138,8 +138,7 @@ describe('test', () => { "Test Failures\n\n The Snyk CLI couldn't find any valid IaC configuration files to scan\n Path: invalid_file.txt", formattedUserMessage: "Test Failures\n\n The Snyk CLI couldn't find any valid IaC configuration files to scan\n Path: invalid_file.txt", - json: - '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', + json: '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', jsonStringifiedResults: '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', sarifStringifiedResults: `{\n "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",\n "version": "2.1.0",\n "runs": [\n {\n "originalUriBaseIds": {\n "PROJECTROOT": {\n "uri": "${ @@ -190,8 +189,7 @@ describe('test', () => { ), jsonStringifiedResults: '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', - json: - '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', + json: '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', }), ); }); @@ -255,8 +253,7 @@ describe('test', () => { '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', formattedUserMessage: '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', - json: - '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', + json: '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', jsonStringifiedResults: '[\n {\n "ok": false,\n "code": 2114,\n "error": "",\n "path": "invalid_file.txt"\n }\n]', sarifStringifiedResults: `{\n "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",\n "version": "2.1.0",\n "runs": [\n {\n "originalUriBaseIds": {\n "PROJECTROOT": {\n "uri": "${ @@ -310,8 +307,7 @@ describe('test', () => { ), jsonStringifiedResults: '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', - json: - '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', + json: '[\n {\n "ok": false,\n "code": 2114,\n "error": "no loadable input: path/to/test",\n "path": "path/to/test"\n }\n]', }), ); }); diff --git a/test/jest/unit/cli/commands/types.spec.ts b/test/jest/unit/cli/commands/types.spec.ts index 7ea68e10c3..18a9786460 100644 --- a/test/jest/unit/cli/commands/types.spec.ts +++ b/test/jest/unit/cli/commands/types.spec.ts @@ -14,27 +14,26 @@ test('createHumanReadableTestCommandResult', () => { }); test('createJsonTestCommandResult', () => { - const result = TestCommandResult.createJsonTestCommandResult( - '{ json result}', - ); + const result = + TestCommandResult.createJsonTestCommandResult('{ json result}'); expect(result.toString()).toEqual('{ json result}'); expect(result.getDisplayResults()).toEqual('{ json result}'); expect(result.getJsonResult()).toEqual('{ json result}'); }); test('CommandResult is a HumanReadableTestCommandResult', () => { - const result: CommandResult = TestCommandResult.createHumanReadableTestCommandResult( - 'hr result', - '{ json result}', - ); + const result: CommandResult = + TestCommandResult.createHumanReadableTestCommandResult( + 'hr result', + '{ json result}', + ); expect(result.toString()).toEqual('hr result'); expect(result.getDisplayResults()).toEqual('hr result'); }); test('CommandResult is a JsonTestCommandResult', () => { - const result: CommandResult = TestCommandResult.createJsonTestCommandResult( - '{ json result}', - ); + const result: CommandResult = + TestCommandResult.createJsonTestCommandResult('{ json result}'); expect(result.toString()).toEqual('{ json result}'); expect(result.getDisplayResults()).toEqual('{ json result}'); }); diff --git a/test/jest/unit/dev-count-analysis.spec.ts b/test/jest/unit/dev-count-analysis.spec.ts index c9c994364d..babb90b390 100644 --- a/test/jest/unit/dev-count-analysis.spec.ts +++ b/test/jest/unit/dev-count-analysis.spec.ts @@ -25,10 +25,11 @@ describe('cli dev count via git log analysis', () => { const timestampEpochSecondsEndOfPeriod = Math.floor( TIMESTAMP_TO_TEST / 1000, ); - const timestampEpochSecondsStartOfPeriod = getTimestampStartOfContributingDevTimeframe( - new Date(TIMESTAMP_TO_TEST), - 10, - ); + const timestampEpochSecondsStartOfPeriod = + getTimestampStartOfContributingDevTimeframe( + new Date(TIMESTAMP_TO_TEST), + 10, + ); const withMergesGitLogCommand = `git --no-pager log --pretty=tformat:"%H${SERIOUS_DELIMITER}%an${SERIOUS_DELIMITER}%ae${SERIOUS_DELIMITER}%aI${SERIOUS_DELIMITER}%s" --after="${timestampEpochSecondsStartOfPeriod}" --until="${timestampEpochSecondsEndOfPeriod}" --max-count=${MAX_COMMITS_IN_GIT_LOG}`; const withMergesGitLogStdout: string = await execShell( @@ -123,15 +124,13 @@ describe('cli dev count via git log analysis', () => { expect(uniqueAuthors.has('someemail-1@somedomain.com')).toBeTruthy(); expect(uniqueAuthors.has('someemail-2@somedomain.com')).toBeTruthy(); - const mostRecentCommitTimestampSomeEmail1 = stats.getMostRecentCommitTimestamp( - 'someemail-1@somedomain.com', - ); + const mostRecentCommitTimestampSomeEmail1 = + stats.getMostRecentCommitTimestamp('someemail-1@somedomain.com'); expect(mostRecentCommitTimestampSomeEmail1).toEqual( '2020-02-06T11:43:11+00:00', ); - const mostRecentCommitTimestampSomeEmail2 = stats.getMostRecentCommitTimestamp( - 'someemail-2@somedomain.com', - ); + const mostRecentCommitTimestampSomeEmail2 = + stats.getMostRecentCommitTimestamp('someemail-2@somedomain.com'); expect(mostRecentCommitTimestampSomeEmail2).toEqual( '2020-02-02T23:31:13+02:00', ); @@ -183,15 +182,13 @@ describe('cli dev count via git log analysis', () => { expect(uniqueAuthors).toContain('someemail-1@somedomain.com'); expect(uniqueAuthors).toContain('someemail-2@somedomain.com'); - const mostRecentCommitTimestampSomeEmail1 = stats.getMostRecentCommitTimestamp( - 'someemail-1@somedomain.com', - ); + const mostRecentCommitTimestampSomeEmail1 = + stats.getMostRecentCommitTimestamp('someemail-1@somedomain.com'); expect(mostRecentCommitTimestampSomeEmail1).toEqual( '2020-02-06T11:43:11+00:00', ); - const mostRecentCommitTimestampSomeEmail2 = stats.getMostRecentCommitTimestamp( - 'someemail-2@somedomain.com', - ); + const mostRecentCommitTimestampSomeEmail2 = + stats.getMostRecentCommitTimestamp('someemail-2@somedomain.com'); expect(mostRecentCommitTimestampSomeEmail2).toEqual( '2020-02-02T23:31:13+02:00', ); diff --git a/test/jest/unit/iac/cli-share-results.fixtures.ts b/test/jest/unit/iac/cli-share-results.fixtures.ts index ae31a2cd2d..9c9943875a 100644 --- a/test/jest/unit/iac/cli-share-results.fixtures.ts +++ b/test/jest/unit/iac/cli-share-results.fixtures.ts @@ -169,8 +169,8 @@ export const expectedEnvelopeFormatterResults = [ }, ]; -export const expectedEnvelopeFormatterResultsWithPolicy = expectedEnvelopeFormatterResults.map( - (result) => { +export const expectedEnvelopeFormatterResultsWithPolicy = + expectedEnvelopeFormatterResults.map((result) => { return { ...result, policy: `# Snyk (https://snyk.io) policy file, patches or ignores known vulnerabilities. @@ -183,8 +183,7 @@ ignore: patch: {} `, }; - }, -); + }); export const createEnvelopeFormatterResultsWithTargetRef = ( targetReference: string, diff --git a/test/jest/unit/iac/cli-share-results.spec.ts b/test/jest/unit/iac/cli-share-results.spec.ts index 5d9bddb7e7..f0e63d29b1 100644 --- a/test/jest/unit/iac/cli-share-results.spec.ts +++ b/test/jest/unit/iac/cli-share-results.spec.ts @@ -13,7 +13,9 @@ import * as snykPolicyLib from 'snyk-policy'; describe('CLI Share Results', () => { let snykPolicy: Policy; let requestSpy: jest.SpiedFunction; - let envelopeFormattersSpy: jest.SpiedFunction; + let envelopeFormattersSpy: jest.SpiedFunction< + typeof envelopeFormatters.convertIacResultToScanResult + >; beforeAll(async () => { snykPolicy = await snykPolicyLib.load('test/jest/unit/iac/fixtures'); @@ -52,10 +54,8 @@ describe('CLI Share Results', () => { expect(firstCall[0]).toEqual(scanResults[0]); expect(secondCall[0]).toEqual(scanResults[1]); - const [ - firstCallResult, - secondCallResult, - ] = envelopeFormattersSpy.mock.results; + const [firstCallResult, secondCallResult] = + envelopeFormattersSpy.mock.results; expect(firstCallResult.value).toEqual(expectedEnvelopeFormatterResults[0]); expect(secondCallResult.value).toEqual(expectedEnvelopeFormatterResults[1]); @@ -79,10 +79,8 @@ describe('CLI Share Results', () => { expect(firstCall[0]).toEqual(scanResults[0]); expect(secondCall[0]).toEqual(scanResults[1]); - const [ - firstCallResult, - secondCallResult, - ] = envelopeFormattersSpy.mock.results; + const [firstCallResult, secondCallResult] = + envelopeFormattersSpy.mock.results; expect(firstCallResult.value).toEqual( expectedEnvelopeFormatterResultsWithPolicy[0], @@ -95,9 +93,8 @@ describe('CLI Share Results', () => { describe('when given a target reference', () => { it("should include it in the Envelope's ScanResult interface", async () => { const testTargetRef = 'test-target-ref'; - const expectedEnvelopeFormatterResults = createEnvelopeFormatterResultsWithTargetRef( - testTargetRef, - ); + const expectedEnvelopeFormatterResults = + createEnvelopeFormatterResultsWithTargetRef(testTargetRef); await shareResults({ results: scanResults, @@ -118,10 +115,8 @@ describe('CLI Share Results', () => { expect(firstCall[0]).toEqual(scanResults[0]); expect(secondCall[0]).toEqual(scanResults[1]); - const [ - firstCallResult, - secondCallResult, - ] = envelopeFormattersSpy.mock.results; + const [firstCallResult, secondCallResult] = + envelopeFormattersSpy.mock.results; expect(firstCallResult.value).toEqual( expectedEnvelopeFormatterResults[0], ); diff --git a/test/jest/unit/iac/directory-loader.spec.ts b/test/jest/unit/iac/directory-loader.spec.ts index cbb35f17f6..09051e9791 100644 --- a/test/jest/unit/iac/directory-loader.spec.ts +++ b/test/jest/unit/iac/directory-loader.spec.ts @@ -114,13 +114,11 @@ describe('getAllDirectoriesForPath', () => { mockFs({ [level1Directory]: { [path.basename(level2Directory)]: { - [path.basename( - level2FileStub.filePath, - )]: level2FileStub.fileContent, + [path.basename(level2FileStub.filePath)]: + level2FileStub.fileContent, [path.basename(level3Directory)]: { - [path.basename( - level3FileStub.filePath, - )]: level3FileStub.fileContent, + [path.basename(level3FileStub.filePath)]: + level3FileStub.fileContent, }, }, }, @@ -130,9 +128,8 @@ describe('getAllDirectoriesForPath', () => { describe('with 1 directory', () => { describe('with 2 directories', () => { it('returns the files at level 2', () => { - const directoryFilePaths = getAllDirectoriesForPath( - level1Directory, - ); + const directoryFilePaths = + getAllDirectoriesForPath(level1Directory); const level2Dir = path.join( level1Directory, path.basename(level2Directory), diff --git a/test/jest/unit/iac/file-parser.kubernetes.fixtures.ts b/test/jest/unit/iac/file-parser.kubernetes.fixtures.ts index f70688caf1..c163d30bec 100644 --- a/test/jest/unit/iac/file-parser.kubernetes.fixtures.ts +++ b/test/jest/unit/iac/file-parser.kubernetes.fixtures.ts @@ -213,13 +213,14 @@ export const insufficientIndentationYamlErrorFileDataStub: IacFileData = { filePath: 'dont-care', fileType: 'yml', }; -export const expectedInsufficientIndentationYamlErrorFileParsingResult: IacFileParsed = { - ...insufficientIndentationYamlErrorFileDataStub, - docId: 0, - projectType: IacProjectType.CLOUDFORMATION, - engineType: EngineType.CloudFormation, - jsonContent: yamlWithInsufficientIndentationFileJSON, -}; +export const expectedInsufficientIndentationYamlErrorFileParsingResult: IacFileParsed = + { + ...insufficientIndentationYamlErrorFileDataStub, + docId: 0, + projectType: IacProjectType.CLOUDFORMATION, + engineType: EngineType.CloudFormation, + jsonContent: yamlWithInsufficientIndentationFileJSON, + }; export const expectedKubernetesYamlParsingResult: IacFileParsed = { ...kubernetesYamlFileDataStub, diff --git a/test/jest/unit/iac/file-parser.spec.ts b/test/jest/unit/iac/file-parser.spec.ts index 1f86d74455..71b1b7e9fc 100644 --- a/test/jest/unit/iac/file-parser.spec.ts +++ b/test/jest/unit/iac/file-parser.spec.ts @@ -144,7 +144,8 @@ describe('parseFiles', () => { [ { fileStub: insufficientIndentationYamlErrorFileDataStub, - expectedParsingResult: expectedInsufficientIndentationYamlErrorFileParsingResult, + expectedParsingResult: + expectedInsufficientIndentationYamlErrorFileParsingResult, }, ], ])( diff --git a/test/jest/unit/iac/file-scanner.spec.ts b/test/jest/unit/iac/file-scanner.spec.ts index 3ce4263c5d..7ccf601037 100644 --- a/test/jest/unit/iac/file-scanner.spec.ts +++ b/test/jest/unit/iac/file-scanner.spec.ts @@ -152,9 +152,8 @@ describe('validateResultFromCustomRules', () => { }; it('does not filter out valid policies', () => { - const { validatedResult, invalidIssues } = validateResultFromCustomRules( - result, - ); + const { validatedResult, invalidIssues } = + validateResultFromCustomRules(result); expect(validatedResult.violatedPolicies).toEqual( expect.arrayContaining([ expect.objectContaining({ publicId: 'CUSTOM-RULE-VALID' }), @@ -164,9 +163,8 @@ describe('validateResultFromCustomRules', () => { }); it('filters out policies with invalid severity', () => { - const { validatedResult, invalidIssues } = validateResultFromCustomRules( - result, - ); + const { validatedResult, invalidIssues } = + validateResultFromCustomRules(result); expect(validatedResult.violatedPolicies).not.toEqual( expect.arrayContaining([ expect.objectContaining({ publicId: 'CUSTOM-RULE-INVALID-SEVERITY' }), @@ -184,9 +182,8 @@ describe('validateResultFromCustomRules', () => { }); it('filters out policies with lowercase publicId', () => { - const { validatedResult, invalidIssues } = validateResultFromCustomRules( - result, - ); + const { validatedResult, invalidIssues } = + validateResultFromCustomRules(result); expect(validatedResult.violatedPolicies).not.toEqual( expect.arrayContaining([ expect.objectContaining({ @@ -206,9 +203,8 @@ describe('validateResultFromCustomRules', () => { }); it('filters out policies with conflicting publicId', () => { - const { validatedResult, invalidIssues } = validateResultFromCustomRules( - result, - ); + const { validatedResult, invalidIssues } = + validateResultFromCustomRules(result); expect(validatedResult.violatedPolicies).not.toEqual( expect.arrayContaining([ expect.objectContaining({ publicId: 'SNYK-CC-CUSTOM-RULE-INVALID' }), diff --git a/test/jest/unit/iac/results-formatter.fixtures.ts b/test/jest/unit/iac/results-formatter.fixtures.ts index 72644890a7..ad9a8c17a2 100644 --- a/test/jest/unit/iac/results-formatter.fixtures.ts +++ b/test/jest/unit/iac/results-formatter.fixtures.ts @@ -179,18 +179,16 @@ export const expectedFormattedResultsWithLineNumber = generateFormattedResults({ withLineNumber: true, }, }); -export const expectedFormattedResultsWithoutLineNumber = generateFormattedResults( - { +export const expectedFormattedResultsWithoutLineNumber = + generateFormattedResults({ cloudConfigResultsOptions: { withLineNumber: false, }, - }, -); -export const expectedFormattedResultsGeneratedByCustomRules = generateFormattedResults( - { + }); +export const expectedFormattedResultsGeneratedByCustomRules = + generateFormattedResults({ cloudConfigResultsOptions: { isGeneratedByCustomRule: true, }, packageManager: IacProjectType.CUSTOM, - }, -); + }); diff --git a/test/jest/unit/iac/rules/oci-pull.spec.ts b/test/jest/unit/iac/rules/oci-pull.spec.ts index 2bf3e4da75..efa07f9f59 100644 --- a/test/jest/unit/iac/rules/oci-pull.spec.ts +++ b/test/jest/unit/iac/rules/oci-pull.spec.ts @@ -66,25 +66,25 @@ describe('extractOCIRegistryURLComponents', () => { }); }); - it('throws an error if a URL with an empty registry host is provided', function() { + it('throws an error if a URL with an empty registry host is provided', function () { expect(() => { extractOCIRegistryURLComponents('https:///repository:0.2.0'); }).toThrow(InvalidRemoteRegistryURLError); }); - it('throws an error if a URL without a path is provided', function() { + it('throws an error if a URL without a path is provided', function () { expect(() => { extractOCIRegistryURLComponents('https://registry'); }).toThrow(InvalidRemoteRegistryURLError); }); - it('throws an error if a URL with an empty path is provided', function() { + it('throws an error if a URL with an empty path is provided', function () { expect(() => { extractOCIRegistryURLComponents('https://registry/'); }).toThrow(InvalidRemoteRegistryURLError); }); - it('throws an error if a URL with an empty repository name is provided', function() { + it('throws an error if a URL with an empty repository name is provided', function () { expect(() => { extractOCIRegistryURLComponents('https://registry/:'); }).toThrow(InvalidRemoteRegistryURLError); diff --git a/test/jest/unit/iac/service-mappings.spec.ts b/test/jest/unit/iac/service-mappings.spec.ts index b0c0ddc3dd..f4631b59e4 100644 --- a/test/jest/unit/iac/service-mappings.spec.ts +++ b/test/jest/unit/iac/service-mappings.spec.ts @@ -6,27 +6,27 @@ import { verifyServiceMappingExists, } from '../../../../src/lib/iac/service-mappings'; -describe('service-mappings', function() { - describe('validation', function() { - it('throws an error when an unknown service is used', function() { +describe('service-mappings', function () { + describe('validation', function () { + it('throws an error when an unknown service is used', function () { expect(() => { verifyServiceMappingExists(['no-such-service']); }).toThrow(InvalidServiceError); }); - it('throws an error when an empty service list is used', function() { + it('throws an error when an empty service list is used', function () { expect(() => { verifyServiceMappingExists([]); }).toThrow(InvalidServiceError); }); - it('does not throw an error when a known service is used', function() { + it('does not throw an error when a known service is used', function () { expect(() => { verifyServiceMappingExists(Array.from(services2resources.keys())); }).not.toThrow(InvalidServiceError); }); }); - describe('ignore pattern creation', function() { - it('should create the correct pattern', function() { + describe('ignore pattern creation', function () { + it('should create the correct pattern', function () { const service = Array.from(services2resources.keys())[0]; const pattern = createIgnorePattern([service]); let expected = '*'; @@ -36,7 +36,7 @@ describe('service-mappings', function() { expect(pattern).toBe(expected); }); - it('should not include the same ignore pattern replicated multiple times', function() { + it('should not include the same ignore pattern replicated multiple times', function () { const services = new Map>([ ['service1', ['duplicate']], ['service2', ['duplicate']], diff --git a/test/jest/unit/iac/url-utils.spec.ts b/test/jest/unit/iac/url-utils.spec.ts index 8adc32341a..c5b8874e18 100644 --- a/test/jest/unit/iac/url-utils.spec.ts +++ b/test/jest/unit/iac/url-utils.spec.ts @@ -1,14 +1,14 @@ import { isValidUrl } from '../../../../src/cli/commands/test/iac/local-execution/url-utils'; -describe('url-utils.ts', function() { - describe('isValidUrl', function() { - describe('Given a valid URL', function() { - describe('With a protocol - it returns true', function() { +describe('url-utils.ts', function () { + describe('isValidUrl', function () { + describe('Given a valid URL', function () { + describe('With a protocol - it returns true', function () { it.each([ 'https://valid.io/url', 'https://valid.io/url:latest', 'https://valid.io/url:0.1.0', - ])('%s', function(urlStr) { + ])('%s', function (urlStr) { // Act const result = isValidUrl(urlStr); @@ -17,10 +17,10 @@ describe('url-utils.ts', function() { }); }); - describe('Without a protocol - it returns true', function() { + describe('Without a protocol - it returns true', function () { it.each(['valid.io/url', 'valid.io/url:latest', 'valid.io/url:0.1.0'])( '%s', - function(urlStr) { + function (urlStr) { // Act const result = isValidUrl(urlStr); @@ -31,13 +31,13 @@ describe('url-utils.ts', function() { }); }); - describe('When given an invalid URL', function() { - describe('With a protocol - it returns false', function() { + describe('When given an invalid URL', function () { + describe('With a protocol - it returns false', function () { it.each([ 'http://an/invalid/url', 'https://an-invalid-url', 'http://:an_invalid/url', - ])('%s', function(urlStr: string) { + ])('%s', function (urlStr: string) { const result = isValidUrl(urlStr); // Assert @@ -45,10 +45,10 @@ describe('url-utils.ts', function() { }); }); - describe('Without a protocol - it returns false', function() { + describe('Without a protocol - it returns false', function () { it.each(['an/invalid/url', 'an-invalid-url', ':an_invalid/url'])( '%s', - function(urlStr: string) { + function (urlStr: string) { const result = isValidUrl(urlStr); // Assert diff --git a/test/jest/unit/lib/analytics/utils.ts b/test/jest/unit/lib/analytics/utils.ts index 35119a9a09..eaab89e703 100644 --- a/test/jest/unit/lib/analytics/utils.ts +++ b/test/jest/unit/lib/analytics/utils.ts @@ -6,10 +6,10 @@ import { ArgsOptions } from '../../../../../src/cli/args'; * @returns a ArgsOptions[] with just the stuff we need for the tests. */ export function argsFrom(args: { [key: string]: string }): ArgsOptions[] { - const fullArgs = ([ + const fullArgs = [ { ...args, }, - ] as any) as ArgsOptions[]; + ] as any as ArgsOptions[]; return fullArgs; } diff --git a/test/jest/unit/lib/ecosystems/resolve-monitor.facts.spec.ts b/test/jest/unit/lib/ecosystems/resolve-monitor.facts.spec.ts index a67bcc3dfb..237c09d1c1 100644 --- a/test/jest/unit/lib/ecosystems/resolve-monitor.facts.spec.ts +++ b/test/jest/unit/lib/ecosystems/resolve-monitor.facts.spec.ts @@ -267,12 +267,12 @@ describe('resolve and test facts', () => { path: 'random-fake-path', }); - await resolveAndMonitorFacts(scanResults, ({ + await resolveAndMonitorFacts(scanResults, { 'project-tags': 'tag1=value1,tag2=value2,tag3=value3', 'project-business-criticality': 'medium', 'project-environment': 'saas', 'project-lifecycle': 'development', - } as unknown) as Options); + } as unknown as Options); expect(httpClientSpy).toHaveBeenCalledTimes(1); expect(httpClientSpy).toBeCalledWith( expect.objectContaining({ diff --git a/test/jest/unit/lib/formatters/get-sarif-result.spec.ts b/test/jest/unit/lib/formatters/get-sarif-result.spec.ts index e2da748b26..c45c7464ef 100644 --- a/test/jest/unit/lib/formatters/get-sarif-result.spec.ts +++ b/test/jest/unit/lib/formatters/get-sarif-result.spec.ts @@ -2,11 +2,13 @@ import { getResults } from '../../../../../src/lib/formatters/get-sarif-result'; import { SEVERITY, TestResult } from '../../../../../src/lib/snyk-test/legacy'; describe('Retrieving sarif result', () => { - const cases: Array<[ - string, - { path: string; displayTargetFile?: string }, - { resultLocationUri: string }, - ]> = [ + const cases: Array< + [ + string, + { path: string; displayTargetFile?: string }, + { resultLocationUri: string }, + ] + > = [ [ 'should return the path given there is no target file present', { path: 'alpine' }, @@ -20,8 +22,7 @@ describe('Retrieving sarif result', () => { [ 'should return the path without colon characters given there is no target file present and the path contains a digest', { - path: - 'alpine@sha256:c0669ef34cdc14332c0f1ab0c2c01acb91d96014b172f1a76f3a39e63d1f0bda', + path: 'alpine@sha256:c0669ef34cdc14332c0f1ab0c2c01acb91d96014b172f1a76f3a39e63d1f0bda', }, { resultLocationUri: @@ -49,8 +50,7 @@ describe('Retrieving sarif result', () => { fixes: undefined, level: 'error', message: { - text: - 'This file introduces a vulnerable expat package with a critical severity vulnerability.', + text: 'This file introduces a vulnerable expat package with a critical severity vulnerability.', }, locations: [ { diff --git a/test/jest/unit/lib/formatters/iac-output/text/formatters.spec.ts b/test/jest/unit/lib/formatters/iac-output/text/formatters.spec.ts index 9b636c0add..049b17d2ac 100644 --- a/test/jest/unit/lib/formatters/iac-output/text/formatters.spec.ts +++ b/test/jest/unit/lib/formatters/iac-output/text/formatters.spec.ts @@ -80,22 +80,23 @@ describe('formatSnykIacTestTestData', () => { 'utf-8', ), ); - const snykIacTestOutputWithSuppressionsFixture: SnykIacTestOutput = JSON.parse( - fs.readFileSync( - path.join( - __dirname, - '..', - '..', - '..', - '..', - 'iac', - 'process-results', - 'fixtures', - 'snyk-iac-test-results-with-suppressions.json', + const snykIacTestOutputWithSuppressionsFixture: SnykIacTestOutput = + JSON.parse( + fs.readFileSync( + path.join( + __dirname, + '..', + '..', + '..', + '..', + 'iac', + 'process-results', + 'fixtures', + 'snyk-iac-test-results-with-suppressions.json', + ), + 'utf-8', ), - 'utf-8', - ), - ); + ); const testDataFixture: IacTestData = JSON.parse( fs.readFileSync( diff --git a/test/jest/unit/lib/formatters/iac-output/text/test-summary.spec.ts b/test/jest/unit/lib/formatters/iac-output/text/test-summary.spec.ts index fab20b555d..86b0bb2396 100644 --- a/test/jest/unit/lib/formatters/iac-output/text/test-summary.spec.ts +++ b/test/jest/unit/lib/formatters/iac-output/text/test-summary.spec.ts @@ -82,10 +82,10 @@ describe('formatIacTestSummary', () => { ${colors.failure.bold('✗')} Files with issues: ${colors.info.bold('3')} Ignored issues: ${colors.info.bold('3')} Total issues: ${colors.info.bold('22')} [ ${colors.severities.critical( - '0 critical', - )}, ${colors.severities.high('5 high')}, ${colors.severities.medium( - '4 medium', - )}, ${colors.severities.low('13 low')} ]`, + '0 critical', + )}, ${colors.severities.high('5 high')}, ${colors.severities.medium( + '4 medium', + )}, ${colors.severities.low('13 low')} ]`, ); expect(result).not.toContain('suppressed issues'); @@ -106,10 +106,10 @@ ${colors.failure.bold('✗')} Files with issues: ${colors.info.bold('3')} Ignored issues: ${colors.info.bold('3')} Cloud context - suppressed issues: ${colors.info.bold('42')} Total issues: ${colors.info.bold('22')} [ ${colors.severities.critical( - '0 critical', - )}, ${colors.severities.high('5 high')}, ${colors.severities.medium( - '4 medium', - )}, ${colors.severities.low('13 low')} ]`, + '0 critical', + )}, ${colors.severities.high('5 high')}, ${colors.severities.medium( + '4 medium', + )}, ${colors.severities.low('13 low')} ]`, ); }); }); diff --git a/test/jest/unit/lib/formatters/open-source-sarif-output.spec.ts b/test/jest/unit/lib/formatters/open-source-sarif-output.spec.ts index e7c5fefa87..bb7c2e42df 100644 --- a/test/jest/unit/lib/formatters/open-source-sarif-output.spec.ts +++ b/test/jest/unit/lib/formatters/open-source-sarif-output.spec.ts @@ -32,10 +32,11 @@ describe('createSarifOutputForOpenSource', () => { displayTargetFile: `${time}/${lockFileName}`, }); const sarif = createSarifOutputForOpenSource([testFile]); - const uri = sarif.runs?.[0]?.results?.[0].locations?.[0]?.physicalLocation?.artifactLocation?.uri?.replace( - `${time}/`, - '', - ); + const uri = + sarif.runs?.[0]?.results?.[0].locations?.[0]?.physicalLocation?.artifactLocation?.uri?.replace( + `${time}/`, + '', + ); expect(uri).toMatchSnapshot(); }), ); diff --git a/test/jest/unit/lib/iac/test/v2/sarif.spec.ts b/test/jest/unit/lib/iac/test/v2/sarif.spec.ts index ec201a2be0..5b80513428 100644 --- a/test/jest/unit/lib/iac/test/v2/sarif.spec.ts +++ b/test/jest/unit/lib/iac/test/v2/sarif.spec.ts @@ -40,9 +40,8 @@ describe('convertEngineToSarifResults', () => { integratedSarifOutputFixtureContent, ); - integratedSarifOutputFixture.runs[0].originalUriBaseIds!.PROJECTROOT.uri = pathToFileURL( - process.cwd() + '/', - ).href; + integratedSarifOutputFixture.runs[0].originalUriBaseIds!.PROJECTROOT.uri = + pathToFileURL(process.cwd() + '/').href; it('returns expected SARIF result', () => { const result = convertEngineToSarifResults(snykIacTestFixture); diff --git a/test/jest/unit/lib/plugins/yarn-workspaces-parser.spec.ts b/test/jest/unit/lib/plugins/yarn-workspaces-parser.spec.ts index a5ddc944c4..69809837e0 100644 --- a/test/jest/unit/lib/plugins/yarn-workspaces-parser.spec.ts +++ b/test/jest/unit/lib/plugins/yarn-workspaces-parser.spec.ts @@ -10,9 +10,10 @@ const yarnWorkspacesMap = { }; const yarnWorkspacesMapWindows = { - 'C:\\snyk\\test\\acceptance\\workspaces\\yarn-workspace-out-of-sync\\package.json': { - workspaces: ['packages'], - }, + 'C:\\snyk\\test\\acceptance\\workspaces\\yarn-workspace-out-of-sync\\package.json': + { + workspaces: ['packages'], + }, 'C:\\snyk\\test\\acceptance\\workspaces\\yarn-workspace\\package.json': { workspaces: ['libs/*/**', 'tools/*'], }, diff --git a/test/jest/unit/metrics.spec.ts b/test/jest/unit/metrics.spec.ts index 43729bbfb5..7e3a98c955 100644 --- a/test/jest/unit/metrics.spec.ts +++ b/test/jest/unit/metrics.spec.ts @@ -1,8 +1,10 @@ const debugMock: string[][] = []; jest.mock('debug', () => { - const factory = (key) => (...args) => { - debugMock.push([key, ...args]); - }; + const factory = + (key) => + (...args) => { + debugMock.push([key, ...args]); + }; factory.default = factory; return factory; }); diff --git a/test/jest/unit/policy-display.spec.ts b/test/jest/unit/policy-display.spec.ts index f47995b388..4e5406a710 100644 --- a/test/jest/unit/policy-display.spec.ts +++ b/test/jest/unit/policy-display.spec.ts @@ -19,11 +19,7 @@ it('test sensibly bails if gets an old .snyk format', async () => { .slice(3) .join('\n'); - const expected = expectedFileString - .trim() - .split('\n') - .slice(3) - .join('\n'); + const expected = expectedFileString.trim().split('\n').slice(3).join('\n'); expect(result).toEqual(expected); }); diff --git a/test/jest/unit/snyk-code/snyk-code-test.spec.ts b/test/jest/unit/snyk-code/snyk-code-test.spec.ts index 445d1a9db5..571b447e9c 100644 --- a/test/jest/unit/snyk-code/snyk-code-test.spec.ts +++ b/test/jest/unit/snyk-code/snyk-code-test.spec.ts @@ -313,24 +313,21 @@ describe('Test snyk code', () => { it.each([ { - name: - 'should write only sarif result to file when only `--sarif-file-output` is used', + name: 'should write only sarif result to file when only `--sarif-file-output` is used', options: { 'sarif-file-output': true, 'json-file-output': false, }, }, { - name: - 'should write only json result to file when only `--json-file-output` is used', + name: 'should write only json result to file when only `--json-file-output` is used', options: { 'sarif-file-output': false, 'json-file-output': true, }, }, { - name: - 'should write sarif and json results to file when `--sarif-file-output` and `--json-file-output` are used', + name: 'should write sarif and json results to file when `--sarif-file-output` and `--json-file-output` are used', options: { 'sarif-file-output': true, 'json-file-output': true, @@ -560,9 +557,8 @@ describe('Test snyk code', () => { await ecosystems.testEcosystem('code', ['some/path'], options); } catch (error) { const errMessage = error.message.trim(); - const expectedOutput = jsonStringifyLargeObject( - sampleSarifResponse, - ).trim(); + const expectedOutput = + jsonStringifyLargeObject(sampleSarifResponse).trim(); // exit code 1 expect(error.code).toBe('VULNS'); @@ -595,9 +591,8 @@ describe('Test snyk code', () => { await snykTest('some/path', options); } catch (error) { const errMessage = error.message.trim(); - const expectedOutput = jsonStringifyLargeObject( - sampleSarifResponse, - ).trim(); + const expectedOutput = + jsonStringifyLargeObject(sampleSarifResponse).trim(); // exit code 1 expect(error.code).toBe('VULNS'); diff --git a/test/setup.js b/test/setup.js index c9f3123d27..961d37f08e 100644 --- a/test/setup.js +++ b/test/setup.js @@ -8,7 +8,7 @@ const { } = require('./jest/util/fipsTestHelper'); const { runSnykCLI } = require('./jest/util/runSnykCLI'); -module.exports = async function() { +module.exports = async function () { if (process.env.TEST_SNYK_COMMAND) { process.env.TEST_SNYK_COMMAND = getCliBinaryPath(); } diff --git a/test/tap/cli-monitor.acceptance.test.ts b/test/tap/cli-monitor.acceptance.test.ts index 48d36bb5e3..57ba729297 100644 --- a/test/tap/cli-monitor.acceptance.test.ts +++ b/test/tap/cli-monitor.acceptance.test.ts @@ -263,9 +263,9 @@ if (!isWindows) { async inspect() { return { plugin: { name: 'sbt' }, - package: require(getWorkspacePath( - 'sbt-simple-struts/monitor-graph-result.json', - )), + package: require( + getWorkspacePath('sbt-simple-struts/monitor-graph-result.json'), + ), }; }, }; diff --git a/test/tap/cli-monitor/cli-monitor.all-projects.spec.ts b/test/tap/cli-monitor/cli-monitor.all-projects.spec.ts index 841733b8d6..0a91bf47ed 100644 --- a/test/tap/cli-monitor/cli-monitor.all-projects.spec.ts +++ b/test/tap/cli-monitor/cli-monitor.all-projects.spec.ts @@ -12,687 +12,692 @@ interface AcceptanceTests { export const AllProjectsTests: AcceptanceTests = { language: 'Mixed', tests: { - '`monitor mono-repo-with-ignores --all-projects` respects .snyk policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.monitor('mono-repo-with-ignores', { - allProjects: true, - detectionDepth: 2, - }); - const requests = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); - let policyCount = 0; - requests.forEach((req) => { - const vulnerableFolderPath = - process.platform === 'win32' - ? 'vulnerable\\package-lock.json' - : 'vulnerable/package-lock.json'; - - if (req.body.targetFileRelativePath.endsWith(vulnerableFolderPath)) { - t.match( - req.body.policy, - 'npm:node-uuid:20160328', - 'body contains policy', - ); - policyCount += 1; - } - }); - t.equal(policyCount, 1, 'one policy found'); - }, - '`monitor monorepo-bad-project --all-projects`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - const spyPlugin = sinon.spy(params.plugins, 'loadPlugin'); - t.teardown(spyPlugin.restore); - let result; - try { - await params.cli.monitor('monorepo-bad-project', { + '`monitor mono-repo-with-ignores --all-projects` respects .snyk policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.monitor('mono-repo-with-ignores', { allProjects: true, + detectionDepth: 2, }); - } catch (error) { - result = error.message; - } - t.ok(spyPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin'); - t.ok(spyPlugin.withArgs('yarn').calledOnce, 'calls npm plugin'); - t.ok(spyPlugin.withArgs('maven').notCalled, 'did not call maven plugin'); - - t.match( - result, - 'rubygems/graph/some/project-id', - 'rubygems project was monitored', - ); - t.match( - result, - 'Dependency snyk@* was not found in yarn.lock', - 'yarn project had an error and we displayed it', - ); + const requests = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); + let policyCount = 0; + requests.forEach((req) => { + const vulnerableFolderPath = + process.platform === 'win32' + ? 'vulnerable\\package-lock.json' + : 'vulnerable/package-lock.json'; - const request = params.server.popRequest(); + if (req.body.targetFileRelativePath.endsWith(vulnerableFolderPath)) { + t.match( + req.body.policy, + 'npm:node-uuid:20160328', + 'body contains policy', + ); + policyCount += 1; + } + }); + t.equal(policyCount, 1, 'one policy found'); + }, + '`monitor monorepo-bad-project --all-projects`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const spyPlugin = sinon.spy(params.plugins, 'loadPlugin'); + t.teardown(spyPlugin.restore); + let result; + try { + await params.cli.monitor('monorepo-bad-project', { + allProjects: true, + }); + } catch (error) { + result = error.message; + } + t.ok( + spyPlugin.withArgs('rubygems').calledOnce, + 'calls rubygems plugin', + ); + t.ok(spyPlugin.withArgs('yarn').calledOnce, 'calls npm plugin'); + t.ok( + spyPlugin.withArgs('maven').notCalled, + 'did not call maven plugin', + ); - t.match( - request.url, - '/api/v1/monitor/rubygems/graph', - 'puts at correct url', - ); - t.notOk(request.body.targetFile, "doesn't send the targetFile"); - t.equal(request.method, 'PUT', 'makes PUT request'); - t.equal( - request.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - }, - '`monitor monorepo-with-nuget --all-projects sends same payload as --file`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); + t.match( + result, + 'rubygems/graph/some/project-id', + 'rubygems project was monitored', + ); + t.match( + result, + 'Dependency snyk@* was not found in yarn.lock', + 'yarn project had an error and we displayed it', + ); - // mock go plugin becuase CI tooling doesn't have go installed - const mockPlugin = { - async inspect() { - return { - plugin: { - targetFile: 'Gopkg.lock', - name: 'snyk-go-plugin', - runtime: 'go', - }, - package: {}, - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('golangdep').returns(mockPlugin); - loadPlugin.callThrough(); // don't mock other plugins + const request = params.server.popRequest(); - await params.cli.monitor('monorepo-with-nuget', { - allProjects: true, - detectionDepth: 4, - }); + t.match( + request.url, + '/api/v1/monitor/rubygems/graph', + 'puts at correct url', + ); + t.notOk(request.body.targetFile, "doesn't send the targetFile"); + t.equal(request.method, 'PUT', 'makes PUT request'); + t.equal( + request.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + }, + '`monitor monorepo-with-nuget --all-projects sends same payload as --file`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); - const [ - projectAssetsAll, - cocoapodsAll, - golangdepAll, - npmAll, - packageConfigAll, - paketAll, - ] = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); + // mock go plugin becuase CI tooling doesn't have go installed + const mockPlugin = { + async inspect() { + return { + plugin: { + targetFile: 'Gopkg.lock', + name: 'snyk-go-plugin', + runtime: 'go', + }, + package: {}, + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('golangdep').returns(mockPlugin); + loadPlugin.callThrough(); // don't mock other plugins - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`, - }); - const projectAssetsFile = params.server.popRequest(); + await params.cli.monitor('monorepo-with-nuget', { + allProjects: true, + detectionDepth: 4, + }); - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `src${path.sep}cocoapods-app${path.sep}Podfile.lock`, - }); - const cocoapodsFile = params.server.popRequest(); + const [ + projectAssetsAll, + cocoapodsAll, + golangdepAll, + npmAll, + packageConfigAll, + paketAll, + ] = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `src${path.sep}frontend${path.sep}Gopkg.lock`, - }); - const golangdepFile = params.server.popRequest(); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`, + }); + const projectAssetsFile = params.server.popRequest(); - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `src${path.sep}paymentservice${path.sep}package-lock.json`, - }); - const npmFile = params.server.popRequest(); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `src${path.sep}cocoapods-app${path.sep}Podfile.lock`, + }); + const cocoapodsFile = params.server.popRequest(); - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `test${path.sep}nuget-app-4${path.sep}packages.config`, - }); - const packageConfigFile = params.server.popRequest(); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `src${path.sep}frontend${path.sep}Gopkg.lock`, + }); + const golangdepFile = params.server.popRequest(); - params.server.restore(); - await params.cli.monitor('monorepo-with-nuget', { - file: `test${path.sep}paket-app${path.sep}paket.dependencies`, - }); - const paketFile = params.server.popRequest(); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `src${path.sep}paymentservice${path.sep}package-lock.json`, + }); + const npmFile = params.server.popRequest(); - t.same( - projectAssetsAll.body, - projectAssetsFile.body, - `same body for --all-projects and --file=src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`, - ); - t.same( - cocoapodsAll.body, - cocoapodsFile.body, - `same body for --all-projects and --file=src${path.sep}cocoapods-app${path.sep}Podfile.lock`, - ); - t.same( - golangdepAll.body, - golangdepFile.body, - `same body for --all-projects and --file=src${path.sep}frontend${path.sep}Gopkg.lock`, - ); - t.same( - npmAll.body, - npmFile.body, - `same body for --all-projects and --file=src${path.sep}paymentservice${path.sep}package-lock.json`, - ); - t.same( - packageConfigAll.body, - packageConfigFile.body, - `same body for --all-projects and --file=test${path.sep}nuget-app-4${path.sep}packages.config`, - ); - t.same( - paketAll.body, - paketFile.body, - `same body for --all-projects and --file=test${path.sep}paket-app${path.sep}paket.dependencies`, - ); - }, - '`monitor mono-repo-go/hello-dep --all-projects sends same body as --file`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - // mock plugin becuase CI tooling doesn't have go installed - const mockPlugin = { - async inspect() { - return { - plugin: { - targetFile: 'Gopkg.lock', - name: 'snyk-go-plugin', - runtime: 'go', - }, - package: {}, - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('golangdep').returns(mockPlugin); - await params.cli.monitor('mono-repo-go/hello-dep', { - allProjects: true, - }); - const allProjectsBody = params.server.popRequest(); - await params.cli.monitor('mono-repo-go/hello-dep', { - file: 'Gopkg.lock', - }); - const fileBody = params.server.popRequest(); - t.same( - allProjectsBody.body, - fileBody.body, - 'same body for --all-projects and --file=mono-repo-go/hello-dep/Gopkg.lock', - ); - }, - '`monitor mono-repo-go/hello-mod --all-projects sends same body as --file`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - // mock plugin becuase CI tooling doesn't have go installed - const mockPlugin = { - async inspect() { - return { - plugin: { - targetFile: 'go.mod', - name: 'snyk-go-plugin', - runtime: 'go', - }, - package: {}, - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gomodules').returns(mockPlugin); - await params.cli.monitor('mono-repo-go/hello-mod', { - allProjects: true, - }); - const allProjectsBody = params.server.popRequest(); - await params.cli.monitor('mono-repo-go/hello-mod', { - file: 'go.mod', - }); - const fileBody = params.server.popRequest(); - t.same( - allProjectsBody.body, - fileBody.body, - 'same body for --all-projects and --file=mono-repo-go/hello-mod/go.mod', - ); - }, - '`monitor mono-repo-go/hello-vendor --all-projects sends same body as --file`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - // mock plugin becuase CI tooling doesn't have go installed - const mockPlugin = { - async inspect() { - return { - plugin: { - targetFile: 'vendor/vendor.json', - name: 'snyk-go-plugin', - runtime: 'go', - }, - package: {}, - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('govendor').returns(mockPlugin); - await params.cli.monitor('mono-repo-go/hello-vendor', { - allProjects: true, - }); - const allProjectsBody = params.server.popRequest(); - await params.cli.monitor('mono-repo-go/hello-vendor', { - file: 'vendor/vendor.json', - }); - const fileBody = params.server.popRequest(); - t.same( - allProjectsBody.body, - fileBody.body, - 'same body for --all-projects and --file=mono-repo-go/hello-vendor/vendor/vendor.json', - ); - }, - '`monitor mono-repo-go with --all-projects and --detection-depth=3`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - // mock plugin becuase CI tooling doesn't have go installed - const mockPlugin = { - async inspect() { - return { - plugin: { - name: 'mock', - }, - package: {}, - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('golangdep').returns(mockPlugin); - loadPlugin.withArgs('gomodules').returns(mockPlugin); - loadPlugin.withArgs('govendor').returns(mockPlugin); - loadPlugin.callThrough(); // don't mock npm plugin - const result = await params.cli.monitor('mono-repo-go', { - allProjects: true, - detectionDepth: 3, - }); - t.match(result, 'golangdep/some/project-id', 'dep project was monitored'); - t.match(result, 'gomodules/some/project-id', 'mod project was monitored'); - t.match(result, 'npm/graph/some/project-id', 'npm project was monitored'); - t.match( - result, - 'govendor/some/project-id', - 'vendor project was monitored', - ); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `test${path.sep}nuget-app-4${path.sep}packages.config`, + }); + const packageConfigFile = params.server.popRequest(); - const requests = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); - t.equal(requests.length, 4, 'correct amount of monitor requests'); + params.server.restore(); + await params.cli.monitor('monorepo-with-nuget', { + file: `test${path.sep}paket-app${path.sep}paket.dependencies`, + }); + const paketFile = params.server.popRequest(); - requests.forEach((req) => { + t.same( + projectAssetsAll.body, + projectAssetsFile.body, + `same body for --all-projects and --file=src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`, + ); + t.same( + cocoapodsAll.body, + cocoapodsFile.body, + `same body for --all-projects and --file=src${path.sep}cocoapods-app${path.sep}Podfile.lock`, + ); + t.same( + golangdepAll.body, + golangdepFile.body, + `same body for --all-projects and --file=src${path.sep}frontend${path.sep}Gopkg.lock`, + ); + t.same( + npmAll.body, + npmFile.body, + `same body for --all-projects and --file=src${path.sep}paymentservice${path.sep}package-lock.json`, + ); + t.same( + packageConfigAll.body, + packageConfigFile.body, + `same body for --all-projects and --file=test${path.sep}nuget-app-4${path.sep}packages.config`, + ); + t.same( + paketAll.body, + paketFile.body, + `same body for --all-projects and --file=test${path.sep}paket-app${path.sep}paket.dependencies`, + ); + }, + '`monitor mono-repo-go/hello-dep --all-projects sends same body as --file`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + // mock plugin becuase CI tooling doesn't have go installed + const mockPlugin = { + async inspect() { + return { + plugin: { + targetFile: 'Gopkg.lock', + name: 'snyk-go-plugin', + runtime: 'go', + }, + package: {}, + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('golangdep').returns(mockPlugin); + await params.cli.monitor('mono-repo-go/hello-dep', { + allProjects: true, + }); + const allProjectsBody = params.server.popRequest(); + await params.cli.monitor('mono-repo-go/hello-dep', { + file: 'Gopkg.lock', + }); + const fileBody = params.server.popRequest(); + t.same( + allProjectsBody.body, + fileBody.body, + 'same body for --all-projects and --file=mono-repo-go/hello-dep/Gopkg.lock', + ); + }, + '`monitor mono-repo-go/hello-mod --all-projects sends same body as --file`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + // mock plugin becuase CI tooling doesn't have go installed + const mockPlugin = { + async inspect() { + return { + plugin: { + targetFile: 'go.mod', + name: 'snyk-go-plugin', + runtime: 'go', + }, + package: {}, + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gomodules').returns(mockPlugin); + await params.cli.monitor('mono-repo-go/hello-mod', { + allProjects: true, + }); + const allProjectsBody = params.server.popRequest(); + await params.cli.monitor('mono-repo-go/hello-mod', { + file: 'go.mod', + }); + const fileBody = params.server.popRequest(); + t.same( + allProjectsBody.body, + fileBody.body, + 'same body for --all-projects and --file=mono-repo-go/hello-mod/go.mod', + ); + }, + '`monitor mono-repo-go/hello-vendor --all-projects sends same body as --file`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + // mock plugin becuase CI tooling doesn't have go installed + const mockPlugin = { + async inspect() { + return { + plugin: { + targetFile: 'vendor/vendor.json', + name: 'snyk-go-plugin', + runtime: 'go', + }, + package: {}, + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('govendor').returns(mockPlugin); + await params.cli.monitor('mono-repo-go/hello-vendor', { + allProjects: true, + }); + const allProjectsBody = params.server.popRequest(); + await params.cli.monitor('mono-repo-go/hello-vendor', { + file: 'vendor/vendor.json', + }); + const fileBody = params.server.popRequest(); + t.same( + allProjectsBody.body, + fileBody.body, + 'same body for --all-projects and --file=mono-repo-go/hello-vendor/vendor/vendor.json', + ); + }, + '`monitor mono-repo-go with --all-projects and --detection-depth=3`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + // mock plugin becuase CI tooling doesn't have go installed + const mockPlugin = { + async inspect() { + return { + plugin: { + name: 'mock', + }, + package: {}, + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('golangdep').returns(mockPlugin); + loadPlugin.withArgs('gomodules').returns(mockPlugin); + loadPlugin.withArgs('govendor').returns(mockPlugin); + loadPlugin.callThrough(); // don't mock npm plugin + const result = await params.cli.monitor('mono-repo-go', { + allProjects: true, + detectionDepth: 3, + }); t.match( - req.url, - /\/api\/v1\/monitor\/(npm\/graph|golangdep|gomodules|govendor)/, - 'puts at correct url', + result, + 'golangdep/some/project-id', + 'dep project was monitored', ); - t.notOk(req.body.targetFile, "doesn't send the targetFile"); - t.equal(req.method, 'PUT', 'makes PUT request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match( + result, + 'gomodules/some/project-id', + 'mod project was monitored', ); - }); - }, - '`monitor gradle-monorepo with --all-projects`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - const simpleGradleGraph = depGraphLib.createFromJSON({ - schemaVersion: '1.2.0', - pkgManager: { - name: 'gradle', - }, - pkgs: [ - { - id: 'gradle-monorepo@0.0.0', - info: { - name: 'gradle-monorepo', - version: '0.0.0', - }, + t.match( + result, + 'npm/graph/some/project-id', + 'npm project was monitored', + ); + t.match( + result, + 'govendor/some/project-id', + 'vendor project was monitored', + ); + + const requests = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); + t.equal(requests.length, 4, 'correct amount of monitor requests'); + + requests.forEach((req) => { + t.match( + req.url, + /\/api\/v1\/monitor\/(npm\/graph|golangdep|gomodules|govendor)/, + 'puts at correct url', + ); + t.notOk(req.body.targetFile, "doesn't send the targetFile"); + t.equal(req.method, 'PUT', 'makes PUT request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + }); + }, + '`monitor gradle-monorepo with --all-projects`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const simpleGradleGraph = depGraphLib.createFromJSON({ + schemaVersion: '1.2.0', + pkgManager: { + name: 'gradle', }, - ], - graph: { - rootNodeId: 'root-node', - nodes: [ + pkgs: [ { - nodeId: 'root-node', - pkgId: 'gradle-monorepo@0.0.0', - deps: [], + id: 'gradle-monorepo@0.0.0', + info: { + name: 'gradle-monorepo', + version: '0.0.0', + }, }, ], - }, - }); - const plugin = { - async inspect() { - return { - plugin: { - name: 'bundled:gradle', - runtime: 'unknown', - meta: {}, - }, - scannedProjects: [ + graph: { + rootNodeId: 'root-node', + nodes: [ { - meta: { - gradleProjectName: 'root-proj', - versionBuildInfo: { - gradleVersion: '6.5', + nodeId: 'root-node', + pkgId: 'gradle-monorepo@0.0.0', + deps: [], + }, + ], + }, + }); + const plugin = { + async inspect() { + return { + plugin: { + name: 'bundled:gradle', + runtime: 'unknown', + meta: {}, + }, + scannedProjects: [ + { + meta: { + gradleProjectName: 'root-proj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - { - meta: { - gradleProjectName: 'root-proj/subproj', - versionBuildInfo: { - gradleVersion: '6.5', + { + meta: { + gradleProjectName: 'root-proj/subproj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - ], - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); - loadPlugin.callThrough(); - const result = await params.cli.monitor('gradle-monorepo', { - allProjects: true, - detectionDepth: 3, - d: true, - }); - t.match( - result, - 'gradle/graph/some/project-id', - 'gradle project was monitored', - ); - t.match( - result, - 'npm/graph/some/project-id', - 'gradle project was monitored', - ); - - const requests = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); - t.equal(requests.length, 3, 'correct amount of monitor requests'); - requests.forEach((req) => { + ], + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); + loadPlugin.callThrough(); + const result = await params.cli.monitor('gradle-monorepo', { + allProjects: true, + detectionDepth: 3, + d: true, + }); t.match( - req.url, - /\/api\/v1\/monitor\/(npm\/graph|gradle\/graph)/, - 'puts at correct url', + result, + 'gradle/graph/some/project-id', + 'gradle project was monitored', ); - t.notOk(req.body.targetFile, "doesn't send the targetFile"); - t.equal(req.method, 'PUT', 'makes PUT request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match( + result, + 'npm/graph/some/project-id', + 'gradle project was monitored', ); - }); - }, - '`monitor kotlin-monorepo --all-projects` scans kotlin files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const simpleGradleGraph = depGraphLib.createFromJSON({ - schemaVersion: '1.2.0', - pkgManager: { - name: 'gradle', - }, - pkgs: [ - { - id: 'gradle-monorepo@0.0.0', - info: { - name: 'gradle-monorepo', - version: '0.0.0', - }, + + const requests = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); + t.equal(requests.length, 3, 'correct amount of monitor requests'); + requests.forEach((req) => { + t.match( + req.url, + /\/api\/v1\/monitor\/(npm\/graph|gradle\/graph)/, + 'puts at correct url', + ); + t.notOk(req.body.targetFile, "doesn't send the targetFile"); + t.equal(req.method, 'PUT', 'makes PUT request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + }); + }, + '`monitor kotlin-monorepo --all-projects` scans kotlin files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const simpleGradleGraph = depGraphLib.createFromJSON({ + schemaVersion: '1.2.0', + pkgManager: { + name: 'gradle', }, - ], - graph: { - rootNodeId: 'root-node', - nodes: [ + pkgs: [ { - nodeId: 'root-node', - pkgId: 'gradle-monorepo@0.0.0', - deps: [], + id: 'gradle-monorepo@0.0.0', + info: { + name: 'gradle-monorepo', + version: '0.0.0', + }, }, ], - }, - }); - const plugin = { - async inspect() { - return { - plugin: { - name: 'bundled:gradle', - runtime: 'unknown', - meta: {}, - }, - scannedProjects: [ + graph: { + rootNodeId: 'root-node', + nodes: [ { - meta: { - gradleProjectName: 'root-proj', - versionBuildInfo: { - gradleVersion: '6.5', + nodeId: 'root-node', + pkgId: 'gradle-monorepo@0.0.0', + deps: [], + }, + ], + }, + }); + const plugin = { + async inspect() { + return { + plugin: { + name: 'bundled:gradle', + runtime: 'unknown', + meta: {}, + }, + scannedProjects: [ + { + meta: { + gradleProjectName: 'root-proj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - { - meta: { - gradleProjectName: 'root-proj/subproj', - versionBuildInfo: { - gradleVersion: '6.5', + { + meta: { + gradleProjectName: 'root-proj/subproj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - ], - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); - loadPlugin.callThrough(); + ], + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); + loadPlugin.callThrough(); - const result = await params.cli.monitor('kotlin-monorepo', { - allProjects: true, - detectionDepth: 3, - }); - t.ok(loadPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin'); - t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); + const result = await params.cli.monitor('kotlin-monorepo', { + allProjects: true, + detectionDepth: 3, + }); + t.ok( + loadPlugin.withArgs('rubygems').calledOnce, + 'calls rubygems plugin', + ); + t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); - t.match( - result, - 'gradle/graph/some/project-id', - 'gradle project was monitored', - ); - t.match( - result, - 'rubygems/graph/some/project-id', - 'rubygems project was monitored', - ); + t.match( + result, + 'gradle/graph/some/project-id', + 'gradle project was monitored', + ); + t.match( + result, + 'rubygems/graph/some/project-id', + 'rubygems project was monitored', + ); - const requests = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); - t.equal(requests.length, 3, 'correct amount of monitor requests'); - requests.forEach((req) => { + const requests = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); + t.equal(requests.length, 3, 'correct amount of monitor requests'); + requests.forEach((req) => { + t.match( + req.url, + /\/api\/v1\/monitor\/(rubygems\/graph|gradle\/graph)/, + 'puts at correct url', + ); + t.notOk(req.body.targetFile, "doesn't send the targetFile"); + t.equal(req.method, 'PUT', 'makes PUT request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + }); + }, + '`monitor mono-repo-poetry with --all-projects --detection-depth=2`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const result = await params.cli.monitor('mono-repo-poetry', { + allProjects: true, + detectionDepth: 2, + }); t.match( - req.url, - /\/api\/v1\/monitor\/(rubygems\/graph|gradle\/graph)/, - 'puts at correct url', + result, + 'npm/graph/some/project-id', + 'npm project was monitored ', ); - t.notOk(req.body.targetFile, "doesn't send the targetFile"); - t.equal(req.method, 'PUT', 'makes PUT request'); + t.match( + result, + 'poetry/graph/some/project-id', + 'poetry project was monitored ', + ); + const requests = params.server.popRequests(2); + requests.forEach((request) => { + const urlOk = + request.url === '/api/v1/monitor/npm' || + '/api/v1/monitor/poetry/graph'; + t.ok(urlOk, 'puts at correct url'); + t.equal(request.method, 'PUT', 'makes PUT request'); + t.equal( + request.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + }); + }, + 'monitor yarn-workspaces --all-projects --detection-depth=5 finds Yarn workspaces, Npm and Yarn projects': + (params, utils) => async (t) => { + t.teardown(() => { + loadPlugin.restore(); + }); + utils.chdirWorkspaces(); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + + const result = await params.cli.monitor('yarn-workspaces', { + allProjects: true, + detectionDepth: 5, + }); + // the parser is used directly t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + loadPlugin.withArgs('yarn').callCount, + 1, + 'loads plugin for yarn as we detect a Yarn projevct inside a workspace', ); - }); - }, - '`monitor mono-repo-poetry with --all-projects --detection-depth=2`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const result = await params.cli.monitor('mono-repo-poetry', { - allProjects: true, - detectionDepth: 2, - }); - t.match( - result, - 'npm/graph/some/project-id', - 'npm project was monitored ', - ); - t.match( - result, - 'poetry/graph/some/project-id', - 'poetry project was monitored ', - ); - const requests = params.server.popRequests(2); - requests.forEach((request) => { - const urlOk = - request.url === '/api/v1/monitor/npm' || - '/api/v1/monitor/poetry/graph'; - t.ok(urlOk, 'puts at correct url'); - t.equal(request.method, 'PUT', 'makes PUT request'); t.equal( - request.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + loadPlugin.withArgs('npm').callCount, + 1, + 'calls npm plugin once', ); - }); - }, - 'monitor yarn-workspaces --all-projects --detection-depth=5 finds Yarn workspaces, Npm and Yarn projects': ( - params, - utils, - ) => async (t) => { - t.teardown(() => { - loadPlugin.restore(); - }); - utils.chdirWorkspaces(); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - - const result = await params.cli.monitor('yarn-workspaces', { - allProjects: true, - detectionDepth: 5, - }); - // the parser is used directly - t.equal( - loadPlugin.withArgs('yarn').callCount, - 1, - 'loads plugin for yarn as we detect a Yarn projevct inside a workspace', - ); - t.equal(loadPlugin.withArgs('npm').callCount, 1, 'calls npm plugin once'); - t.match( - result, - 'Monitoring yarn-workspaces (package.json)', - 'yarn workspace root was monitored', - ); - t.match( - result, - 'Monitoring yarn-workspaces (apple-lib)', - 'yarn workspace was monitored', - ); - t.match( - result, - 'Monitoring yarn-workspaces (apples)', - 'yarn workspace was monitored', - ); - t.match( - result, - 'Monitoring yarn-workspaces (tomatoes)', - 'yarn workspace was monitored', - ); - t.match( - result, - 'Monitoring yarn-workspaces (not-in-a-workspace)', - 'npm project was monitored', - ); - t.match( - result, - 'Monitoring yarn-workspaces (not-part-of-workspace)', - 'yarn project was monitored', - ); - - const requests = params.server - .getRequests() - .filter((req) => req.url.includes('/monitor/')); - t.equal(requests.length, 6, 'correct amount of monitor requests'); - let policyCount = 0; - const applesWorkspace = - process.platform === 'win32' - ? '\\apples\\package.json' - : 'apples/package.json'; - const tomatoesWorkspace = - process.platform === 'win32' - ? '\\tomatoes\\package.json' - : 'tomatoes/package.json'; - const rootWorkspace = - process.platform === 'win32' - ? '\\yarn-workspaces\\package.json' - : 'yarn-workspaces/package.json'; - requests.forEach((req) => { t.match( - req.url, - /\/api\/v1\/monitor\/(yarn\/graph|npm\/graph)/, - 'puts at correct url', + result, + 'Monitoring yarn-workspaces (package.json)', + 'yarn workspace root was monitored', ); - t.equal(req.method, 'PUT', 'makes PUT request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match( + result, + 'Monitoring yarn-workspaces (apple-lib)', + 'yarn workspace was monitored', ); - if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { + t.match( + result, + 'Monitoring yarn-workspaces (apples)', + 'yarn workspace was monitored', + ); + t.match( + result, + 'Monitoring yarn-workspaces (tomatoes)', + 'yarn workspace was monitored', + ); + t.match( + result, + 'Monitoring yarn-workspaces (not-in-a-workspace)', + 'npm project was monitored', + ); + t.match( + result, + 'Monitoring yarn-workspaces (not-part-of-workspace)', + 'yarn project was monitored', + ); + + const requests = params.server + .getRequests() + .filter((req) => req.url.includes('/monitor/')); + t.equal(requests.length, 6, 'correct amount of monitor requests'); + let policyCount = 0; + const applesWorkspace = + process.platform === 'win32' + ? '\\apples\\package.json' + : 'apples/package.json'; + const tomatoesWorkspace = + process.platform === 'win32' + ? '\\tomatoes\\package.json' + : 'tomatoes/package.json'; + const rootWorkspace = + process.platform === 'win32' + ? '\\yarn-workspaces\\package.json' + : 'yarn-workspaces/package.json'; + requests.forEach((req) => { t.match( - req.body.policy, - 'npm:node-uuid:20160328', - 'policy is as expected', + req.url, + /\/api\/v1\/monitor\/(yarn\/graph|npm\/graph)/, + 'puts at correct url', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } else if ( - req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) - ) { - t.notOk(req.body.policy, 'body does not contain policy'); - } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20111130', - 'policy is as expected', + t.equal(req.method, 'PUT', 'makes PUT request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } - }); - t.equal(policyCount, 2, '2 policies found in a workspace'); - }, + if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20160328', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } else if ( + req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) + ) { + t.notOk(req.body.policy, 'body does not contain policy'); + } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20111130', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } + }); + t.equal(policyCount, 2, '2 policies found in a workspace'); + }, }, }; diff --git a/test/tap/cli-test/cli-test.all-projects.spec.ts b/test/tap/cli-test/cli-test.all-projects.spec.ts index 5188458327..6d4a0e1bac 100644 --- a/test/tap/cli-test/cli-test.all-projects.spec.ts +++ b/test/tap/cli-test/cli-test.all-projects.spec.ts @@ -32,322 +32,317 @@ const simpleGradleGraph = depGraphLib.createFromJSON({ export const AllProjectsTests: AcceptanceTests = { language: 'Mixed', tests: { - '`test gradle-with-orphaned-build-file --all-projects` warns user': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - plugin: { - name: 'bundled:gradle', - runtime: 'unknown', - meta: {}, - }, - scannedProjects: [ - { - meta: { - gradleProjectName: 'root-proj', - versionBuildInfo: { - gradleVersion: '6.5', + '`test gradle-with-orphaned-build-file --all-projects` warns user': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + plugin: { + name: 'bundled:gradle', + runtime: 'unknown', + meta: {}, + }, + scannedProjects: [ + { + meta: { + gradleProjectName: 'root-proj', + versionBuildInfo: { + gradleVersion: '6.5', + }, + targetFile: 'build.gradle', }, - targetFile: 'build.gradle', + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - { - meta: { - gradleProjectName: 'root-proj/subproj', - versionBuildInfo: { - gradleVersion: '6.5', + { + meta: { + gradleProjectName: 'root-proj/subproj', + versionBuildInfo: { + gradleVersion: '6.5', + }, + targetFile: 'subproj/build.gradle', }, - targetFile: 'subproj/build.gradle', + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - ], - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - loadPlugin.returns(plugin); - t.teardown(loadPlugin.restore); + ], + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + loadPlugin.returns(plugin); + t.teardown(loadPlugin.restore); - // read data from console.log - let stdoutMessages = ''; - const stubConsoleLog = (msg: string) => (stdoutMessages += msg); - const stubbedConsole = sinon - .stub(console, 'warn') - .callsFake(stubConsoleLog); - const result: CommandResult = await params.cli.test( - 'gradle-with-orphaned-build-file', - { - allProjects: true, - detectionDepth: 3, - }, - ); - t.same( - stdoutMessages, - `${icon.ISSUE} 1/3 detected Gradle manifests did not return dependencies. ` + - 'They may have errored or were not included as part of a multi-project build. You may need to scan them individually with --file=path/to/file. Run with `-d` for more info.', - ); - stubbedConsole.restore(); - t.ok(stubbedConsole.calledOnce); - t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); + // read data from console.log + let stdoutMessages = ''; + const stubConsoleLog = (msg: string) => (stdoutMessages += msg); + const stubbedConsole = sinon + .stub(console, 'warn') + .callsFake(stubConsoleLog); + const result: CommandResult = await params.cli.test( + 'gradle-with-orphaned-build-file', + { + allProjects: true, + detectionDepth: 3, + }, + ); + t.same( + stdoutMessages, + `${icon.ISSUE} 1/3 detected Gradle manifests did not return dependencies. ` + + 'They may have errored or were not included as part of a multi-project build. You may need to scan them individually with --file=path/to/file. Run with `-d` for more info.', + ); + stubbedConsole.restore(); + t.ok(stubbedConsole.calledOnce); + t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); - t.match( - result.getDisplayResults(), - 'Tested 2 projects', - 'Detected 2 projects', - ); - }, - '`test kotlin-monorepo --all-projects` scans kotlin files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - plugin: { - name: 'bundled:gradle', - runtime: 'unknown', - meta: {}, - }, - scannedProjects: [ - { - meta: { - gradleProjectName: 'root-proj', - versionBuildInfo: { - gradleVersion: '6.5', + t.match( + result.getDisplayResults(), + 'Tested 2 projects', + 'Detected 2 projects', + ); + }, + '`test kotlin-monorepo --all-projects` scans kotlin files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + plugin: { + name: 'bundled:gradle', + runtime: 'unknown', + meta: {}, + }, + scannedProjects: [ + { + meta: { + gradleProjectName: 'root-proj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - { - meta: { - gradleProjectName: 'root-proj/subproj', - versionBuildInfo: { - gradleVersion: '6.5', + { + meta: { + gradleProjectName: 'root-proj/subproj', + versionBuildInfo: { + gradleVersion: '6.5', + }, }, + depGraph: simpleGradleGraph, }, - depGraph: simpleGradleGraph, - }, - ], - }; - }, - }; - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - loadPlugin.withArgs('gradle').returns(plugin); - loadPlugin.callThrough(); - t.teardown(loadPlugin.restore); + ], + }; + }, + }; + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + loadPlugin.withArgs('gradle').returns(plugin); + loadPlugin.callThrough(); + t.teardown(loadPlugin.restore); - const result: CommandResult = await params.cli.test('kotlin-monorepo', { - allProjects: true, - detectionDepth: 3, - }); - t.ok(loadPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin'); - t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); + const result: CommandResult = await params.cli.test('kotlin-monorepo', { + allProjects: true, + detectionDepth: 3, + }); + t.ok( + loadPlugin.withArgs('rubygems').calledOnce, + 'calls rubygems plugin', + ); + t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin'); - const backendRequests = params.server.popRequests(2); - t.equal(backendRequests.length, 2); + const backendRequests = params.server.popRequests(2); + t.equal(backendRequests.length, 2); - backendRequests.forEach((req) => { - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + backendRequests.forEach((req) => { + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); + t.ok(req.body.depGraph, 'body contains depGraph'); + t.match( + req.body.depGraph.pkgManager.name, + /(gradle|rubygems)/, + 'depGraph has package manager', + ); + }); + t.match( + result.getDisplayResults(), + 'Tested 3 projects', + 'Detected 3 projects', ); - t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); - t.ok(req.body.depGraph, 'body contains depGraph'); t.match( - req.body.depGraph.pkgManager.name, - /(gradle|rubygems)/, - 'depGraph has package manager', + result.getDisplayResults(), + 'Package manager: rubygems', + 'contains package manager rubygems', + ); + t.match( + result.getDisplayResults(), + 'Package manager: gradle', + 'contains package manager gradle', + ); + t.match( + result.getDisplayResults(), + 'Target file: Gemfile.lock', + 'contains target file Gemfile.lock', + ); + t.match( + result.getDisplayResults(), + 'Target file: build.gradle.kts', + 'contains target file build.gradle.kts', + ); + }, + 'test yarn-workspaces-v2-resolutions --all-projects --detection-depth=5 --strict-out-of-sync=false (yarn v2 with resolutions)': + (params, utils) => async (t) => { + // Yarn workspaces for Yarn 2 is only supported on Node 10+ + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspaces-v2-resolutions', { + allProjects: true, + detectionDepth: 5, + strictOutOfSync: false, + printDeps: true, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + t.match( + result.getDisplayResults(), + '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', + 'correctly showing dep number', + ); + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 3 projects, no vulnerable paths were found.', + 'no vulnerable paths found as both policies detected and applied.', + ); + }, + 'test --all-projects --detection-depth=5 finds Yarn workspaces & Npm projects': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspaces', { + allProjects: true, + detectionDepth: 5, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + const output = result.getDisplayResults(); + t.match(output, 'Package manager: yarn\n'); + t.match(output, 'Package manager: npm\n'); + t.match( + output, + 'Target file: not-part-of-workspace/package-lock.json', + 'npm project in outside of yarn workspace is in output', + ); + t.match( + output, + 'Target file: not-part-of-workspace-yarn/yarn.lock', + 'yarn project outside of workspace is in the output', + ); + t.match( + output, + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + output, + 'Project name: tomatoes', + 'workspace yarn project in output', + ); + t.match( + output, + 'Project name: apples', + 'workspace yarn project in output', + ); + t.match( + output, + 'Project name: apple-lib', + 'workspace yarn project in output', ); - }); - t.match( - result.getDisplayResults(), - 'Tested 3 projects', - 'Detected 3 projects', - ); - t.match( - result.getDisplayResults(), - 'Package manager: rubygems', - 'contains package manager rubygems', - ); - t.match( - result.getDisplayResults(), - 'Package manager: gradle', - 'contains package manager gradle', - ); - t.match( - result.getDisplayResults(), - 'Target file: Gemfile.lock', - 'contains target file Gemfile.lock', - ); - t.match( - result.getDisplayResults(), - 'Target file: build.gradle.kts', - 'contains target file build.gradle.kts', - ); - }, - 'test yarn-workspaces-v2-resolutions --all-projects --detection-depth=5 --strict-out-of-sync=false (yarn v2 with resolutions)': ( - params, - utils, - ) => async (t) => { - // Yarn workspaces for Yarn 2 is only supported on Node 10+ - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspaces-v2-resolutions', { - allProjects: true, - detectionDepth: 5, - strictOutOfSync: false, - printDeps: true, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - t.match( - result.getDisplayResults(), - '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', - 'correctly showing dep number', - ); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 3 projects, no vulnerable paths were found.', - 'no vulnerable paths found as both policies detected and applied.', - ); - }, - 'test --all-projects --detection-depth=5 finds Yarn workspaces & Npm projects': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspaces', { - allProjects: true, - detectionDepth: 5, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - const output = result.getDisplayResults(); - t.match(output, 'Package manager: yarn\n'); - t.match(output, 'Package manager: npm\n'); - t.match( - output, - 'Target file: not-part-of-workspace/package-lock.json', - 'npm project in outside of yarn workspace is in output', - ); - t.match( - output, - 'Target file: not-part-of-workspace-yarn/yarn.lock', - 'yarn project outside of workspace is in the output', - ); - t.match( - output, - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - output, - 'Project name: tomatoes', - 'workspace yarn project in output', - ); - t.match( - output, - 'Project name: apples', - 'workspace yarn project in output', - ); - t.match( - output, - 'Project name: apple-lib', - 'workspace yarn project in output', - ); - - t.match( - output, - 'Tested 6 projects, no vulnerable paths were found.', - 'tested 4 workspace projects, 1 npm project and 1 yarn project', - ); - let policyCount = 0; - const applesWorkspace = - process.platform === 'win32' - ? '\\apples\\package.json' - : 'apples/package.json'; - const tomatoesWorkspace = - process.platform === 'win32' - ? '\\tomatoes\\package.json' - : 'tomatoes/package.json'; - const rootWorkspace = - process.platform === 'win32' - ? '\\yarn-workspaces\\package.json' - : 'yarn-workspaces/package.json'; - - const backendRequests = params.server.popRequests(6); - t.equal(backendRequests.length, 6); - backendRequests.forEach((req) => { - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match( + output, + 'Tested 6 projects, no vulnerable paths were found.', + 'tested 4 workspace projects, 1 npm project and 1 yarn project', ); - t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); - t.ok(req.body.depGraph, 'body contains depGraph'); + let policyCount = 0; + const applesWorkspace = + process.platform === 'win32' + ? '\\apples\\package.json' + : 'apples/package.json'; + const tomatoesWorkspace = + process.platform === 'win32' + ? '\\tomatoes\\package.json' + : 'tomatoes/package.json'; + const rootWorkspace = + process.platform === 'win32' + ? '\\yarn-workspaces\\package.json' + : 'yarn-workspaces/package.json'; - if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20160328', - 'policy is as expected', + const backendRequests = params.server.popRequests(6); + t.equal(backendRequests.length, 6); + + backendRequests.forEach((req) => { + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } else if ( - req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) - ) { - t.notOk(req.body.policy, 'body does not contain policy'); - } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { + t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); + t.ok(req.body.depGraph, 'body contains depGraph'); + + if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20160328', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } else if ( + req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) + ) { + t.notOk(req.body.policy, 'body does not contain policy'); + } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20111130', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } t.match( - req.body.policy, - 'npm:node-uuid:20111130', - 'policy is as expected', + req.body.depGraph.pkgManager.name, + /(yarn|npm)/, + 'depGraph has package manager', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } - t.match( - req.body.depGraph.pkgManager.name, - /(yarn|npm)/, - 'depGraph has package manager', - ); - }); - t.equal(policyCount, 2, '2 policies found in a workspace'); - }, + }); + t.equal(policyCount, 2, '2 policies found in a workspace'); + }, }, }; diff --git a/test/tap/cli-test/cli-test.composer.spec.ts b/test/tap/cli-test/cli-test.composer.spec.ts index 3572b4662d..7a140a2872 100644 --- a/test/tap/cli-test/cli-test.composer.spec.ts +++ b/test/tap/cli-test/cli-test.composer.spec.ts @@ -5,274 +5,262 @@ import { AcceptanceTests } from '../cli-test.acceptance.test'; export const ComposerTests: AcceptanceTests = { language: 'Composer', tests: { - '`test composer-app --file=composer.lock`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + '`test composer-app --file=composer.lock`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('composer').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('composer').returns(plugin); + await params.cli.test('composer-app', { + file: 'composer.lock', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'composer'); + t.same( + spyPlugin.getCall(0).args, + [ + 'composer-app', + 'composer.lock', + { + args: null, + file: 'composer.lock', + org: null, + projectName: null, + packageManager: 'composer', + path: 'composer-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls composer plugin', + ); + }, - await params.cli.test('composer-app', { - file: 'composer.lock', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'composer'); - t.same( - spyPlugin.getCall(0).args, - [ - 'composer-app', - 'composer.lock', - { - args: null, - file: 'composer.lock', - org: null, - projectName: null, - packageManager: 'composer', - path: 'composer-app', - showVulnPaths: 'some', + '`test composer-app` auto-detects composer.lock': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls composer plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test composer-app` auto-detects composer.lock': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('composer').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('composer').returns(plugin); + await params.cli.test('composer-app'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'composer'); + t.same( + spyPlugin.getCall(0).args, + [ + 'composer-app', + 'composer.lock', + { + args: null, + file: 'composer.lock', + org: null, + projectName: null, + packageManager: 'composer', + path: 'composer-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls composer plugin', + ); + }, - await params.cli.test('composer-app'); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'composer'); - t.same( - spyPlugin.getCall(0).args, - [ - 'composer-app', - 'composer.lock', - { - args: null, - file: 'composer.lock', - org: null, - projectName: null, - packageManager: 'composer', - path: 'composer-app', - showVulnPaths: 'some', + '`test composer-app --file=composer.lock --dev`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls composer plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test composer-app --file=composer.lock --dev`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('composer').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('composer').returns(plugin); + await params.cli.test('composer-app', { + file: 'composer.lock', + dev: true, + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'composer'); + t.same( + spyPlugin.getCall(0).args, + [ + 'composer-app', + 'composer.lock', + { + args: null, + dev: true, + file: 'composer.lock', + org: null, + projectName: null, + packageManager: 'composer', + path: 'composer-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls composer plugin', + ); + }, - await params.cli.test('composer-app', { - file: 'composer.lock', - dev: true, - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'composer'); - t.same( - spyPlugin.getCall(0).args, - [ - 'composer-app', - 'composer.lock', - { - args: null, - dev: true, - file: 'composer.lock', - org: null, - projectName: null, - packageManager: 'composer', - path: 'composer-app', - showVulnPaths: 'some', + '`test composer-app golang-app nuget-app` auto-detects all three projects': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls composer plugin', - ); - }, - - '`test composer-app golang-app nuget-app` auto-detects all three projects': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('composer').returns(plugin); - loadPlugin.withArgs('golangdep').returns(plugin); - loadPlugin.withArgs('nuget').returns(plugin); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('composer').returns(plugin); + loadPlugin.withArgs('golangdep').returns(plugin); + loadPlugin.withArgs('nuget').returns(plugin); - await params.cli.test('composer-app', 'golang-app', 'nuget-app', { - org: 'test-org', - }); - // assert three API calls made - const reqs = params.server - .getRequests() - .filter((r) => r.url === '/api/v1/test-dep-graph?org=test-org'); + await params.cli.test('composer-app', 'golang-app', 'nuget-app', { + org: 'test-org', + }); + // assert three API calls made + const reqs = params.server + .getRequests() + .filter((r) => r.url === '/api/v1/test-dep-graph?org=test-org'); - t.same( - reqs.map((r) => r.method), - ['POST', 'POST', 'POST'], - 'all post requests', - ); + t.same( + reqs.map((r) => r.method), + ['POST', 'POST', 'POST'], + 'all post requests', + ); - t.same( - reqs.map((r) => r.headers['x-snyk-cli-version']), - [params.versionNumber, params.versionNumber, params.versionNumber], - 'all send version number', - ); + t.same( + reqs.map((r) => r.headers['x-snyk-cli-version']), + [params.versionNumber, params.versionNumber, params.versionNumber], + 'all send version number', + ); - t.equal(reqs.length, 3, 'all urls are present'); + t.equal(reqs.length, 3, 'all urls are present'); - t.same( - reqs.map((r) => r.body.depGraph.pkgManager.name).sort(), - ['composer', 'golangdep', 'nuget'], - 'all urls are present', - ); + t.same( + reqs.map((r) => r.body.depGraph.pkgManager.name).sort(), + ['composer', 'golangdep', 'nuget'], + 'all urls are present', + ); - // assert three spyPlugin calls, each with a different app - const calls = spyPlugin.getCalls().sort((call1: any, call2: any) => { - return call1.args[0] < call2.args[1] - ? -1 - : call1.args[0] > call2.args[0] - ? 1 - : 0; - }); - t.same( - calls[0].args, - [ - 'composer-app', - 'composer.lock', - { - args: null, - org: 'test-org', - file: 'composer.lock', - projectName: null, - packageManager: 'composer', - path: 'composer-app', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls composer plugin', - ); - t.same( - calls[1].args, - [ - 'golang-app', - 'Gopkg.lock', - { - args: null, - org: 'test-org', - file: 'Gopkg.lock', - projectName: null, - packageManager: 'golangdep', - path: 'golang-app', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls golangdep plugin', - ); - t.same( - calls[2].args, - [ - 'nuget-app', - 'project.assets.json', - { - args: null, - org: 'test-org', - file: 'project.assets.json', - projectName: null, - packageManager: 'nuget', - path: 'nuget-app', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + // assert three spyPlugin calls, each with a different app + const calls = spyPlugin.getCalls().sort((call1: any, call2: any) => { + return call1.args[0] < call2.args[1] + ? -1 + : call1.args[0] > call2.args[0] + ? 1 + : 0; + }); + t.same( + calls[0].args, + [ + 'composer-app', + 'composer.lock', + { + args: null, + org: 'test-org', + file: 'composer.lock', + projectName: null, + packageManager: 'composer', + path: 'composer-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls composer plugin', + ); + t.same( + calls[1].args, + [ + 'golang-app', + 'Gopkg.lock', + { + args: null, + org: 'test-org', + file: 'Gopkg.lock', + projectName: null, + packageManager: 'golangdep', + path: 'golang-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golangdep plugin', + ); + t.same( + calls[2].args, + [ + 'nuget-app', + 'project.assets.json', + { + args: null, + org: 'test-org', + file: 'project.assets.json', + projectName: null, + packageManager: 'nuget', + path: 'nuget-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.docker.spec.ts b/test/tap/cli-test/cli-test.docker.spec.ts index 81bdd430c6..caaa59682c 100644 --- a/test/tap/cli-test/cli-test.docker.spec.ts +++ b/test/tap/cli-test/cli-test.docker.spec.ts @@ -77,14 +77,48 @@ export const DockerTests: AcceptanceTests = { ); }, - '`test foo:latest --docker --platform=linux/amd64`': (params) => async ( - t, - ) => { - const spyPlugin = stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { + '`test foo:latest --docker --platform=linux/amd64`': + (params) => async (t) => { + const spyPlugin = stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { type: 'dockerfileAnalysis', data: {} }, + ], + identity: { + type: 'deb', + args: { + platform: 'linux/amd64', + }, + }, + target: { + image: 'docker-image|ubuntu', + }, + }, + ], + }, + t, + ); + + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dependencies', 'posts to correct url'); + t.same( + req.body, + { + scanResult: { facts: [ { type: 'depGraph', data: {} }, { type: 'dockerfileAnalysis', data: {} }, @@ -99,60 +133,25 @@ export const DockerTests: AcceptanceTests = { image: 'docker-image|ubuntu', }, }, - ], - }, - t, - ); - - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dependencies', 'posts to correct url'); - t.same( - req.body, - { - scanResult: { - facts: [ - { type: 'depGraph', data: {} }, - { type: 'dockerfileAnalysis', data: {} }, - ], - identity: { - type: 'deb', - args: { - platform: 'linux/amd64', - }, - }, - target: { - image: 'docker-image|ubuntu', - }, }, - }, - 'sends correct payload', - ); - t.same( - spyPlugin.getCall(0).args, - [ - { - docker: true, - 'exclude-app-vulns': false, - org: 'explicit-org', - projectName: null, - packageManager: null, - path: 'foo:latest', - showVulnPaths: 'some', - }, - ], - 'calls docker plugin with expected arguments', - ); - }, + 'sends correct payload', + ); + t.same( + spyPlugin.getCall(0).args, + [ + { + docker: true, + 'exclude-app-vulns': false, + org: 'explicit-org', + projectName: null, + packageManager: null, + path: 'foo:latest', + showVulnPaths: 'some', + }, + ], + 'calls docker plugin with expected arguments', + ); + }, '`test foo:latest --docker vulnerable paths`': (params) => async (t) => { stubDockerPluginResponse( @@ -307,58 +306,87 @@ export const DockerTests: AcceptanceTests = { ); }, - '`test foo:latest --docker --file=Dockerfile remediation advice`': ( - params, - ) => async (t) => { - stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { - facts: [ - { type: 'depGraph', data: {} }, - { type: 'dockerfileAnalysis', data: {} }, - ], - identity: { - type: 'deb', + '`test foo:latest --docker --file=Dockerfile remediation advice`': + (params) => async (t) => { + stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { type: 'dockerfileAnalysis', data: {} }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', + }, }, - target: { - image: 'docker-image|ubuntu', + ], + }, + t, + ); + const vulns = require( + getFixturePath('docker/find-result-remediation.json'), + ); + params.server.setNextResponse(vulns); + + try { + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + file: 'Dockerfile', + }); + t.fail('should have found vuln'); + } catch (err) { + const msg = err.message; + t.match(msg, 'Base Image'); + t.match(msg, 'Recommendations for base image upgrade'); + } + }, + + '`test foo:latest --docker` doesnt collect policy from cwd': + (params, utils) => async (t) => { + utils.chdirWorkspaces('npm-package-policy'); + const spyPlugin = stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { type: 'dockerfileAnalysis', data: {} }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', + }, }, - }, - ], - }, - t, - ); - const vulns = require(getFixturePath( - 'docker/find-result-remediation.json', - )); - params.server.setNextResponse(vulns); + ], + }, + t, + ); - try { await params.cli.test('foo:latest', { docker: true, org: 'explicit-org', - file: 'Dockerfile', }); - t.fail('should have found vuln'); - } catch (err) { - const msg = err.message; - t.match(msg, 'Base Image'); - t.match(msg, 'Recommendations for base image upgrade'); - } - }, - - '`test foo:latest --docker` doesnt collect policy from cwd': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces('npm-package-policy'); - const spyPlugin = stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dependencies', 'posts to correct url'); + t.same( + req.body, + { + scanResult: { facts: [ { type: 'depGraph', data: {} }, { type: 'dockerfileAnalysis', data: {} }, @@ -370,74 +398,68 @@ export const DockerTests: AcceptanceTests = { image: 'docker-image|ubuntu', }, }, - ], - }, - t, - ); - - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dependencies', 'posts to correct url'); - t.same( - req.body, - { - scanResult: { - facts: [ - { type: 'depGraph', data: {} }, - { type: 'dockerfileAnalysis', data: {} }, - ], - identity: { - type: 'deb', - }, - target: { - image: 'docker-image|ubuntu', - }, }, - }, - 'sends correct payload', - ); - t.same( - spyPlugin.getCall(0).args, - [ + 'sends correct payload', + ); + t.same( + spyPlugin.getCall(0).args, + [ + { + docker: true, + 'exclude-app-vulns': false, + org: 'explicit-org', + projectName: null, + packageManager: null, + path: 'foo:latest', + showVulnPaths: 'some', + }, + ], + 'calls docker plugin with expected arguments', + ); + const policyString = req.body.scanResult.policy; + t.notOk(policyString, 'policy not sent'); + }, + + '`test foo:latest --docker` supports custom policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const policyString = fs.readFileSync( + path.join('npm-package-policy/custom-location', '.snyk'), + 'utf8', + ); + const spyPlugin = stubDockerPluginResponse( + params.ecoSystemPlugins, { - docker: true, - 'exclude-app-vulns': false, - org: 'explicit-org', - projectName: null, - packageManager: null, - path: 'foo:latest', - showVulnPaths: 'some', + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { type: 'dockerfileAnalysis', data: {} }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', + }, + policy: policyString, + }, + ], }, - ], - 'calls docker plugin with expected arguments', - ); - const policyString = req.body.scanResult.policy; - t.notOk(policyString, 'policy not sent'); - }, + t, + ); - '`test foo:latest --docker` supports custom policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const policyString = fs.readFileSync( - path.join('npm-package-policy/custom-location', '.snyk'), - 'utf8', - ); - const spyPlugin = stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + 'policy-path': 'npm-package-policy/custom-location', + }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dependencies', 'posts to correct url'); + t.same( + req.body, + { + scanResult: { facts: [ { type: 'depGraph', data: {} }, { type: 'dockerfileAnalysis', data: {} }, @@ -450,54 +472,26 @@ export const DockerTests: AcceptanceTests = { }, policy: policyString, }, - ], - }, - t, - ); - - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - 'policy-path': 'npm-package-policy/custom-location', - }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dependencies', 'posts to correct url'); - t.same( - req.body, - { - scanResult: { - facts: [ - { type: 'depGraph', data: {} }, - { type: 'dockerfileAnalysis', data: {} }, - ], - identity: { - type: 'deb', - }, - target: { - image: 'docker-image|ubuntu', - }, - policy: policyString, }, - }, - 'sends correct payload', - ); - t.same( - spyPlugin.getCall(0).args, - [ - { - docker: true, - 'exclude-app-vulns': false, - org: 'explicit-org', - projectName: null, - packageManager: null, - path: 'foo:latest', - showVulnPaths: 'some', - 'policy-path': 'npm-package-policy/custom-location', - }, - ], - 'calls docker plugin with expected arguments', - ); - }, + 'sends correct payload', + ); + t.same( + spyPlugin.getCall(0).args, + [ + { + docker: true, + 'exclude-app-vulns': false, + org: 'explicit-org', + projectName: null, + packageManager: null, + path: 'foo:latest', + showVulnPaths: 'some', + 'policy-path': 'npm-package-policy/custom-location', + }, + ], + 'calls docker plugin with expected arguments', + ); + }, '`test foo:latest --docker with binaries`': (params) => async (t) => { const spyPlugin = stubDockerPluginResponse( @@ -580,218 +574,213 @@ export const DockerTests: AcceptanceTests = { ); }, - '`test foo:latest --docker with binaries vulnerabilities`': ( - params, - ) => async (t) => { - stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { - facts: [ - { type: 'depGraph', data: {} }, - { type: 'dockerfileAnalysis', data: {} }, - { - type: 'keyBinariesHashes', - data: [ - '9191fbcdcc737314df97c5016a841199b743ac3fa9959dfade38e17bfdaf30b5', - ], + '`test foo:latest --docker with binaries vulnerabilities`': + (params) => async (t) => { + stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { type: 'dockerfileAnalysis', data: {} }, + { + type: 'keyBinariesHashes', + data: [ + '9191fbcdcc737314df97c5016a841199b743ac3fa9959dfade38e17bfdaf30b5', + ], + }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', }, - ], - identity: { - type: 'deb', - }, - target: { - image: 'docker-image|ubuntu', }, - }, - ], - }, - t, - ); - - const vulns = require(getFixturePath('docker/find-result-binaries.json')); - params.server.setNextResponse(vulns); - - try { - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - }); - t.fail('should have found vuln'); - } catch (err) { - const msg = err.message; - t.match( - msg, - 'Tested 3 dependencies for known vulnerabilities, found 3 vulnerabilities', - ); - t.match(msg, 'From: bzip2/libbz2-1.0@1.0.6-8.1'); - t.match( - msg, - 'From: apt/libapt-pkg5.0@1.6.3ubuntu0.1 > bzip2/libbz2-1.0@1.0.6-8.1', - ); - t.match( - msg, - 'Info: https://security.snyk.io/vuln/SNYK-UPSTREAM-NODE-72359', + ], + }, + t, ); - t.notOk( - msg.includes('vulnerable paths'), - 'docker should not includes number of vulnerable paths', + + const vulns = require( + getFixturePath('docker/find-result-binaries.json'), ); - t.match(msg, 'Detected 2 vulnerabilities for node@5.10.1'); - t.match(msg, 'High severity vulnerability found in node'); - t.match(msg, 'Fixed in: 5.13.1'); - t.match(msg, 'Fixed in: 5.15.1'); - } - }, + params.server.setNextResponse(vulns); - '`test foo:latest --docker with dockerfile instructions`': ( - params, - ) => async (t) => { - stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { - facts: [ - { type: 'depGraph', data: {} }, - { - type: 'dockerfileAnalysis', - data: { - dockerfilePackages: { - bzip2: { - installCommand: 'test installCommand', + try { + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + }); + t.fail('should have found vuln'); + } catch (err) { + const msg = err.message; + t.match( + msg, + 'Tested 3 dependencies for known vulnerabilities, found 3 vulnerabilities', + ); + t.match(msg, 'From: bzip2/libbz2-1.0@1.0.6-8.1'); + t.match( + msg, + 'From: apt/libapt-pkg5.0@1.6.3ubuntu0.1 > bzip2/libbz2-1.0@1.0.6-8.1', + ); + t.match( + msg, + 'Info: https://security.snyk.io/vuln/SNYK-UPSTREAM-NODE-72359', + ); + t.notOk( + msg.includes('vulnerable paths'), + 'docker should not includes number of vulnerable paths', + ); + t.match(msg, 'Detected 2 vulnerabilities for node@5.10.1'); + t.match(msg, 'High severity vulnerability found in node'); + t.match(msg, 'Fixed in: 5.13.1'); + t.match(msg, 'Fixed in: 5.15.1'); + } + }, + + '`test foo:latest --docker with dockerfile instructions`': + (params) => async (t) => { + stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { + type: 'dockerfileAnalysis', + data: { + dockerfilePackages: { + bzip2: { + installCommand: 'test installCommand', + }, }, }, }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', }, - ], - identity: { - type: 'deb', - }, - target: { - image: 'docker-image|ubuntu', }, - }, - ], - }, - t, - ); - - const vulns = require(getFixturePath( - 'docker/find-result-remediation.json', - )); - params.server.setNextResponse(vulns); + ], + }, + t, + ); - try { - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - }); - t.fail('should have found vuln'); - } catch (err) { - const msg = err.message; - t.match(msg, "Image layer: 'test installCommand'"); - } - }, + const vulns = require( + getFixturePath('docker/find-result-remediation.json'), + ); + params.server.setNextResponse(vulns); - '`test foo:latest --docker with auto detected instructions`': ( - params, - ) => async (t) => { - stubDockerPluginResponse( - params.ecoSystemPlugins, - { - scanResults: [ - { - facts: [ - { type: 'depGraph', data: {} }, - { - type: 'autoDetectedUserInstructions', - data: { - dockerfilePackages: { - bzip2: { - installCommand: 'test installCommand', + try { + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + }); + t.fail('should have found vuln'); + } catch (err) { + const msg = err.message; + t.match(msg, "Image layer: 'test installCommand'"); + } + }, + + '`test foo:latest --docker with auto detected instructions`': + (params) => async (t) => { + stubDockerPluginResponse( + params.ecoSystemPlugins, + { + scanResults: [ + { + facts: [ + { type: 'depGraph', data: {} }, + { + type: 'autoDetectedUserInstructions', + data: { + dockerfilePackages: { + bzip2: { + installCommand: 'test installCommand', + }, }, }, }, + ], + identity: { + type: 'deb', + }, + target: { + image: 'docker-image|ubuntu', }, - ], - identity: { - type: 'deb', - }, - target: { - image: 'docker-image|ubuntu', }, - }, - ], - }, - t, - ); + ], + }, + t, + ); - const vulns = require(getFixturePath( - 'docker/find-result-remediation.json', - )); - params.server.setNextResponse(vulns); + const vulns = require( + getFixturePath('docker/find-result-remediation.json'), + ); + params.server.setNextResponse(vulns); - try { - await params.cli.test('foo:latest', { - docker: true, - org: 'explicit-org', - }); - t.fail('should have found vuln'); - } catch (err) { - const msg = err.message; - t.match(msg, "Image layer: 'test installCommand'"); - } - }, + try { + await params.cli.test('foo:latest', { + docker: true, + org: 'explicit-org', + }); + t.fail('should have found vuln'); + } catch (err) { + const msg = err.message; + t.match(msg, "Image layer: 'test installCommand'"); + } + }, '`container test alpine --sarif `': (params, utils) => async (t) => { const testableObject = await testSarif(t, utils, params, { sarif: true, }); const results = JSON.parse(testableObject.message); - const sarifResults = require(getFixturePath( - 'docker/sarif-container-result.json', - )); - t.same(results, sarifResults, 'stdout containing sarif results'); - t.end(); - }, - - '`container test alpine --file=Dockerfile --sarif `': ( - params, - utils, - ) => async (t) => { - const testableObject = await testSarif(t, utils, params, { - sarif: true, - file: 'Dockerfile', - }); - const results = JSON.parse(testableObject.message); - const sarifResults = require(getFixturePath( - 'docker/sarif-with-file-container-result.json', - )); + const sarifResults = require( + getFixturePath('docker/sarif-container-result.json'), + ); t.same(results, sarifResults, 'stdout containing sarif results'); t.end(); }, - '`test --docker --file=Dockerfile --sarif --sarif-output-file`': ( - params, - utils, - ) => async (t) => { - const testableObject = await testSarif(t, utils, params, { - sarif: true, - 'sarif-output-file': 'sarif-test-file.json', - }); - const results = JSON.parse(testableObject.message); - const sarifStringifiedResults = JSON.parse( - testableObject.sarifStringifiedResults, - ); - t.same( - results, - sarifStringifiedResults, - 'stdout and stringified sarif results are the same', - ); - t.end(); - }, + '`container test alpine --file=Dockerfile --sarif `': + (params, utils) => async (t) => { + const testableObject = await testSarif(t, utils, params, { + sarif: true, + file: 'Dockerfile', + }); + const results = JSON.parse(testableObject.message); + const sarifResults = require( + getFixturePath('docker/sarif-with-file-container-result.json'), + ); + t.same(results, sarifResults, 'stdout containing sarif results'); + t.end(); + }, + + '`test --docker --file=Dockerfile --sarif --sarif-output-file`': + (params, utils) => async (t) => { + const testableObject = await testSarif(t, utils, params, { + sarif: true, + 'sarif-output-file': 'sarif-test-file.json', + }); + const results = JSON.parse(testableObject.message); + const sarifStringifiedResults = JSON.parse( + testableObject.sarifStringifiedResults, + ); + t.same( + results, + sarifStringifiedResults, + 'stdout and stringified sarif results are the same', + ); + t.end(); + }, '`test --docker doesnotexist`': (params) => async (t) => { try { diff --git a/test/tap/cli-test/cli-test.elixir.spec.ts b/test/tap/cli-test/cli-test.elixir.spec.ts index 2c0ba7323c..fc0ab7ddb3 100644 --- a/test/tap/cli-test/cli-test.elixir.spec.ts +++ b/test/tap/cli-test/cli-test.elixir.spec.ts @@ -5,116 +5,112 @@ import * as depGraphLib from '@snyk/dep-graph'; export const ElixirTests: AcceptanceTests = { language: 'Elixir', tests: { - '`test elixir --file=mix.exs`': (params, utils, snykHttpClient) => async ( - t, - ) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - scannedProjects: await getScannedProjects(), - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'mix.exs', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('hex').returns(plugin); - - await params.cli.test('elixir-hex', { - file: 'mix.exs', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'hex'); - t.equal(req.body.targetFile, 'mix.exs', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'elixir-hex', - 'mix.exs', - { - args: null, - file: 'mix.exs', - org: null, - projectName: null, - packageManager: 'hex', - path: 'elixir-hex', - showVulnPaths: 'some', + '`test elixir --file=mix.exs`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + scannedProjects: await getScannedProjects(), + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'mix.exs', + }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('hex').returns(plugin); - '`test elixir-hex` auto-detects hex': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - scannedProjects: await getScannedProjects(), - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'mix.exs', + await params.cli.test('elixir-hex', { + file: 'mix.exs', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'hex'); + t.equal(req.body.targetFile, 'mix.exs', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'elixir-hex', + 'mix.exs', + { + args: null, + file: 'mix.exs', + org: null, + projectName: null, + packageManager: 'hex', + path: 'elixir-hex', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + snykHttpClient, + ], + 'calls golang plugin', + ); + }, - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('hex').returns(plugin); + '`test elixir-hex` auto-detects hex': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + scannedProjects: await getScannedProjects(), + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'mix.exs', + }, + }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - await params.cli.test('elixir-hex'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('hex').returns(plugin); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'hex'); - t.equal(req.body.targetFile, 'mix.exs', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'elixir-hex', - 'mix.exs', - { - args: null, - file: 'mix.exs', - org: null, - projectName: null, - packageManager: 'hex', - path: 'elixir-hex', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls elixir-hex plugin', - ); - }, + await params.cli.test('elixir-hex'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'hex'); + t.equal(req.body.targetFile, 'mix.exs', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'elixir-hex', + 'mix.exs', + { + args: null, + file: 'mix.exs', + org: null, + projectName: null, + packageManager: 'hex', + path: 'elixir-hex', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls elixir-hex plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.generic.spec.ts b/test/tap/cli-test/cli-test.generic.spec.ts index 46dfec3a54..cb96d8d448 100644 --- a/test/tap/cli-test/cli-test.generic.spec.ts +++ b/test/tap/cli-test/cli-test.generic.spec.ts @@ -56,64 +56,58 @@ export const GenericTests: AcceptanceTests = { } }, - 'userMessage and error code correctly bubbles with npm': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('npm-package', { org: 'missing-org' }); - t.fail('expect to err'); - } catch (err) { - t.equal( - err.userMessage, - 'Org missing-org was not found or you may not have the correct permissions', - 'got correct err message', - ); - t.equal(err.code, 404); - } - t.end(); - }, + 'userMessage and error code correctly bubbles with npm': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('npm-package', { org: 'missing-org' }); + t.fail('expect to err'); + } catch (err) { + t.equal( + err.userMessage, + 'Org missing-org was not found or you may not have the correct permissions', + 'got correct err message', + ); + t.equal(err.code, 404); + } + t.end(); + }, - 'userMessage and error code correctly bubbles with npm and json output': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('npm-package', { - org: 'missing-org', - json: true, - }); - t.fail('expect to err'); - } catch (err) { - t.match( - err.jsonStringifiedResults, - 'Org missing-org was not found or you may not have the correct permissions', - 'got correct err message', - ); - t.equal(err.code, 404); - } - t.end(); - }, + 'userMessage and error code correctly bubbles with npm and json output': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('npm-package', { + org: 'missing-org', + json: true, + }); + t.fail('expect to err'); + } catch (err) { + t.match( + err.jsonStringifiedResults, + 'Org missing-org was not found or you may not have the correct permissions', + 'got correct err message', + ); + t.equal(err.code, 404); + } + t.end(); + }, - 'userMessage correctly bubbles with everything other than npm': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('ruby-app', { org: 'missing-org' }); - t.fail('expect to err'); - } catch (err) { - t.equal( - err.userMessage, - 'Org missing-org was not found or you may not have the correct permissions', - 'got correct err message', - ); - } - t.end(); - }, + 'userMessage correctly bubbles with everything other than npm': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('ruby-app', { org: 'missing-org' }); + t.fail('expect to err'); + } catch (err) { + t.equal( + err.userMessage, + 'Org missing-org was not found or you may not have the correct permissions', + 'got correct err message', + ); + } + t.end(); + }, /** * Remote package `test` @@ -143,46 +137,43 @@ export const GenericTests: AcceptanceTests = { t.notMatch(output, 'snyk wizard', 'does not suggest `snyk wizard`'); }, - '`test sinatra --registry=rubygems` sends remote Rubygems request:': ( - params, - ) => async (t) => { - await params.cli.test('sinatra', { registry: 'rubygems', org: 'ACME' }); - const req = params.server.popRequest(); - t.equal(req.method, 'GET', 'makes GET request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/vuln/rubygems/sinatra', 'gets from correct url'); - t.equal(req.query.org, 'ACME', 'org sent as a query in request'); - }, + '`test sinatra --registry=rubygems` sends remote Rubygems request:': + (params) => async (t) => { + await params.cli.test('sinatra', { registry: 'rubygems', org: 'ACME' }); + const req = params.server.popRequest(); + t.equal(req.method, 'GET', 'makes GET request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/vuln/rubygems/sinatra', 'gets from correct url'); + t.equal(req.query.org, 'ACME', 'org sent as a query in request'); + }, /** * Local source `test` */ - '`test /` test for non-existent with path specified': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('/'); - t.fail('should have failed'); - } catch (err) { - t.pass('throws err'); - t.match( - err.message, - 'Could not detect supported target files in /.' + - '\nPlease see our documentation for supported' + - ' languages and target files: ' + - 'https://snyk.co/udVgQ' + - ' and make sure you' + - ' are in the right directory.', - ); - } - }, + '`test /` test for non-existent with path specified': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('/'); + t.fail('should have failed'); + } catch (err) { + t.pass('throws err'); + t.match( + err.message, + 'Could not detect supported target files in /.' + + '\nPlease see our documentation for supported' + + ' languages and target files: ' + + 'https://snyk.co/udVgQ' + + ' and make sure you' + + ' are in the right directory.', + ); + } + }, '`test empty --file=readme.md`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -294,26 +285,24 @@ export const GenericTests: AcceptanceTests = { }); }, - '`test npm-package-with-git-url ` handles git url with patch policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces('npm-package-with-git-url'); - const vulns = readJSON( - getFixturePath('npm-package-with-git-url/test-graph-result.json'), - ); - params.server.setNextResponse(vulns); - try { - await params.cli.test(); - t.fail('should fail'); - } catch (res) { - params.server.popRequest(); + '`test npm-package-with-git-url ` handles git url with patch policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces('npm-package-with-git-url'); + const vulns = readJSON( + getFixturePath('npm-package-with-git-url/test-graph-result.json'), + ); + params.server.setNextResponse(vulns); + try { + await params.cli.test(); + t.fail('should fail'); + } catch (res) { + params.server.popRequest(); - t.match(res.message, 'for known vulnerabilities', 'found results'); + t.match(res.message, 'for known vulnerabilities', 'found results'); - t.match(res.message, 'Local Snyk policy: found', 'found policy file'); - } - }, + t.match(res.message, 'Local Snyk policy: found', 'found policy file'); + } + }, '`test --insecure`': (params, utils) => async (t) => { t.plan(2); diff --git a/test/tap/cli-test/cli-test.go.spec.ts b/test/tap/cli-test/cli-test.go.spec.ts index 58997114e6..ceb65de473 100644 --- a/test/tap/cli-test/cli-test.go.spec.ts +++ b/test/tap/cli-test/cli-test.go.spec.ts @@ -4,335 +4,317 @@ import { AcceptanceTests } from '../cli-test.acceptance.test'; export const GoTests: AcceptanceTests = { language: 'Go', tests: { - '`test golang-gomodules --file=go.mod`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'go.mod', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gomodules').returns(plugin); - - await params.cli.test('golang-gomodules', { - file: 'go.mod', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'gomodules'); - t.equal(req.body.targetFile, 'go.mod', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-gomodules', - 'go.mod', - { - args: null, - file: 'go.mod', - org: null, - projectName: null, - packageManager: 'gomodules', - path: 'golang-gomodules', - showVulnPaths: 'some', + '`test golang-gomodules --file=go.mod`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'go.mod', + }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test golang-app` auto-detects golang-gomodules': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'go.mod', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gomodules').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gomodules').returns(plugin); + await params.cli.test('golang-gomodules', { + file: 'go.mod', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'gomodules'); + t.equal(req.body.targetFile, 'go.mod', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-gomodules', + 'go.mod', + { + args: null, + file: 'go.mod', + org: null, + projectName: null, + packageManager: 'gomodules', + path: 'golang-gomodules', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang plugin', + ); + }, - await params.cli.test('golang-gomodules'); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'gomodules'); - t.equal(req.body.targetFile, 'go.mod', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-gomodules', - 'go.mod', - { - args: null, - file: 'go.mod', - org: null, - projectName: null, - packageManager: 'gomodules', - path: 'golang-gomodules', - showVulnPaths: 'some', + '`test golang-app` auto-detects golang-gomodules': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'go.mod', + }, + }; }, - snykHttpClient, - ], - 'calls golang-gomodules plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test golang-app --file=Gopkg.lock`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'Gopkg.lock', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gomodules').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('golangdep').returns(plugin); + await params.cli.test('golang-gomodules'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'gomodules'); + t.equal(req.body.targetFile, 'go.mod', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-gomodules', + 'go.mod', + { + args: null, + file: 'go.mod', + org: null, + projectName: null, + packageManager: 'gomodules', + path: 'golang-gomodules', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang-gomodules plugin', + ); + }, - await params.cli.test('golang-app', { - file: 'Gopkg.lock', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'golangdep'); - t.equal(req.body.targetFile, 'Gopkg.lock', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-app', - 'Gopkg.lock', - { - args: null, - file: 'Gopkg.lock', - org: null, - projectName: null, - packageManager: 'golangdep', - path: 'golang-app', - showVulnPaths: 'some', + '`test golang-app --file=Gopkg.lock`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'Gopkg.lock', + }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test golang-app --file=vendor/vendor.json`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'vendor/vendor.json', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('golangdep').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('govendor').returns(plugin); + await params.cli.test('golang-app', { + file: 'Gopkg.lock', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'golangdep'); + t.equal(req.body.targetFile, 'Gopkg.lock', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-app', + 'Gopkg.lock', + { + args: null, + file: 'Gopkg.lock', + org: null, + projectName: null, + packageManager: 'golangdep', + path: 'golang-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang plugin', + ); + }, - await params.cli.test('golang-app', { - file: 'vendor/vendor.json', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'govendor'); - t.equal(req.body.targetFile, 'vendor/vendor.json', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-app', - 'vendor/vendor.json', - { - args: null, - file: 'vendor/vendor.json', - org: null, - projectName: null, - packageManager: 'govendor', - path: 'golang-app', - showVulnPaths: 'some', + '`test golang-app --file=vendor/vendor.json`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'vendor/vendor.json', + }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test golang-app` auto-detects golang/dep': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'Gopkg.lock', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('govendor').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('golangdep').returns(plugin); + await params.cli.test('golang-app', { + file: 'vendor/vendor.json', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'govendor'); + t.equal(req.body.targetFile, 'vendor/vendor.json', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-app', + 'vendor/vendor.json', + { + args: null, + file: 'vendor/vendor.json', + org: null, + projectName: null, + packageManager: 'govendor', + path: 'golang-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang plugin', + ); + }, - await params.cli.test('golang-app'); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'golangdep'); - t.equal(req.body.targetFile, 'Gopkg.lock', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-app', - 'Gopkg.lock', - { - args: null, - file: 'Gopkg.lock', - org: null, - projectName: null, - packageManager: 'golangdep', - path: 'golang-app', - showVulnPaths: 'some', + '`test golang-app` auto-detects golang/dep': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'Gopkg.lock', + }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test golang-app-govendor` auto-detects govendor': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('golangdep').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('govendor').returns(plugin); + await params.cli.test('golang-app'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'golangdep'); + t.equal(req.body.targetFile, 'Gopkg.lock', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-app', + 'Gopkg.lock', + { + args: null, + file: 'Gopkg.lock', + org: null, + projectName: null, + packageManager: 'golangdep', + path: 'golang-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang plugin', + ); + }, - await params.cli.test('golang-app-govendor'); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'govendor'); - t.same( - spyPlugin.getCall(0).args, - [ - 'golang-app-govendor', - 'vendor/vendor.json', - { - args: null, - file: 'vendor/vendor.json', - org: null, - projectName: null, - packageManager: 'govendor', - path: 'golang-app-govendor', - showVulnPaths: 'some', + '`test golang-app-govendor` auto-detects govendor': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls golang plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('govendor').returns(plugin); + + await params.cli.test('golang-app-govendor'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'govendor'); + t.same( + spyPlugin.getCall(0).args, + [ + 'golang-app-govendor', + 'vendor/vendor.json', + { + args: null, + file: 'vendor/vendor.json', + org: null, + projectName: null, + packageManager: 'govendor', + path: 'golang-app-govendor', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls golang plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.gradle.spec.ts b/test/tap/cli-test/cli-test.gradle.spec.ts index 258748eba5..4848900ed1 100644 --- a/test/tap/cli-test/cli-test.gradle.spec.ts +++ b/test/tap/cli-test/cli-test.gradle.spec.ts @@ -6,52 +6,50 @@ import { CommandResult } from '../../../src/cli/commands/types'; export const GradleTests: AcceptanceTests = { language: 'Gradle', tests: { - '`test gradle-kotlin-dsl-app` returns correct meta': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); + '`test gradle-kotlin-dsl-app` returns correct meta': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; + }, + }; + sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); - const commandResult: CommandResult = await params.cli.test( - 'gradle-kotlin-dsl-app', - ); - const res: string = commandResult.getDisplayResults(); - const meta = res.slice(res.indexOf('Organization:')).split('\n'); - t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); - t.match( - meta[1], - /Package manager:\s+gradle/, - 'package manager displayed', - ); - t.match( - meta[2], - /Target file:\s+build.gradle.kts/, - 'target file displayed', - ); - t.match(meta[3], /Open source:\s+no/, 'open source displayed'); - t.match( - meta[4], - /Project path:\s+gradle-kotlin-dsl-app/, - 'path displayed', - ); - t.notMatch( - meta[5], - /Local Snyk policy:\s+found/, - 'local policy not displayed', - ); - }, + const commandResult: CommandResult = await params.cli.test( + 'gradle-kotlin-dsl-app', + ); + const res: string = commandResult.getDisplayResults(); + const meta = res.slice(res.indexOf('Organization:')).split('\n'); + t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); + t.match( + meta[1], + /Package manager:\s+gradle/, + 'package manager displayed', + ); + t.match( + meta[2], + /Target file:\s+build.gradle.kts/, + 'target file displayed', + ); + t.match(meta[3], /Open source:\s+no/, 'open source displayed'); + t.match( + meta[4], + /Project path:\s+gradle-kotlin-dsl-app/, + 'path displayed', + ); + t.notMatch( + meta[5], + /Local Snyk policy:\s+found/, + 'local policy not displayed', + ); + }, '`test gradle-app` returns correct meta': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -92,187 +90,188 @@ export const GradleTests: AcceptanceTests = { ); }, - '`test gradle-app --all-sub-projects` sends `allSubProjects` argument to plugin': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { plugin: { name: 'gradle' }, package: {} }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); + '`test gradle-app --all-sub-projects` sends `allSubProjects` argument to plugin': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { plugin: { name: 'gradle' }, package: {} }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); - await params.cli.test('gradle-app', { - allSubProjects: true, - }); - t.ok(((spyPlugin.args[0] as any)[2] as any).allSubProjects); - }, - '`test gradle-app --all-sub-projects` with policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { plugin: { name: 'gradle' }, package: {} }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); - - await params.cli.test('gradle-app', { - allSubProjects: true, - }); - t.ok(((spyPlugin.args[0] as any)[2] as any).allSubProjects); + await params.cli.test('gradle-app', { + allSubProjects: true, + }); + t.ok(((spyPlugin.args[0] as any)[2] as any).allSubProjects); + }, + '`test gradle-app --all-sub-projects` with policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { plugin: { name: 'gradle' }, package: {} }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); - let policyCount = 0; - params.server - .getRequests() - .filter((r) => r.url === '/api/v1/test-dep-graph?org=') - .forEach((req) => { - if ( - req.body.displayTargetFile.endsWith('gradle-multi-project/subproj') - ) { - // TODO: this should return 1 policy when fixed - // uncomment then - // t.match( - // req.body.policy, - // 'SNYK-JAVA-ORGBOUNCYCASTLE-32364', - // 'policy is found & sent', - // ); - t.ok( - req.body.policy, - undefined, - 'policy is not found even though it should be', - ); - policyCount += 1; - } - t.match(req.url, '/test-dep-graph', 'posts to correct url'); + await params.cli.test('gradle-app', { + allSubProjects: true, }); - // TODO: this should return 1 policy when fixed - t.equal(policyCount, 0, 'one sub-project policy found & sent'); - }, + t.ok(((spyPlugin.args[0] as any)[2] as any).allSubProjects); - '`test gradle-app` plugin fails to return package or scannedProjects': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { plugin: { name: 'gradle' } }; - }, - }; - sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); + let policyCount = 0; + params.server + .getRequests() + .filter((r) => r.url === '/api/v1/test-dep-graph?org=') + .forEach((req) => { + if ( + req.body.displayTargetFile.endsWith( + 'gradle-multi-project/subproj', + ) + ) { + // TODO: this should return 1 policy when fixed + // uncomment then + // t.match( + // req.body.policy, + // 'SNYK-JAVA-ORGBOUNCYCASTLE-32364', + // 'policy is found & sent', + // ); + t.ok( + req.body.policy, + undefined, + 'policy is not found even though it should be', + ); + policyCount += 1; + } + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + }); + // TODO: this should return 1 policy when fixed + t.equal(policyCount, 0, 'one sub-project policy found & sent'); + }, - try { - await params.cli.test('gradle-app', {}); - t.fail('expected error'); - } catch (error) { - t.match( - error, - /error getting dependencies from gradle plugin: neither 'package' nor 'scannedProjects' were found/, - 'error found', - ); - } - }, + '`test gradle-app` plugin fails to return package or scannedProjects': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { plugin: { name: 'gradle' } }; + }, + }; + sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); - '`test gradle-app --all-sub-projects` returns correct multi tree meta': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect(): Promise { - return { - plugin: { - meta: { - allSubProjectNames: ['a', 'b'], - }, - name: 'gradle', - }, - scannedProjects: [ - { - depTree: { - name: 'tree0', - version: '1.0.0', - dependencies: { dep1: { name: 'dep1', version: '1' } }, + try { + await params.cli.test('gradle-app', {}); + t.fail('expected error'); + } catch (error) { + t.match( + error, + /error getting dependencies from gradle plugin: neither 'package' nor 'scannedProjects' were found/, + 'error found', + ); + } + }, + + '`test gradle-app --all-sub-projects` returns correct multi tree meta': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect(): Promise { + return { + plugin: { + meta: { + allSubProjectNames: ['a', 'b'], }, + name: 'gradle', }, - { - depTree: { - name: 'tree1', - version: '2.0.0', - dependencies: { dep1: { name: 'dep2', version: '2' } }, + scannedProjects: [ + { + depTree: { + name: 'tree0', + version: '1.0.0', + dependencies: { dep1: { name: 'dep1', version: '1' } }, + }, }, - }, - ], - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('gradle').returns(plugin); - - const commandResult: CommandResult = await params.cli.test('gradle-app', { - allSubProjects: true, - }); - const res = commandResult.getDisplayResults(); - t.ok( - ((spyPlugin.args[0] as any)[2] as any).allSubProjects, - '`allSubProjects` option is sent', - ); + { + depTree: { + name: 'tree1', + version: '2.0.0', + dependencies: { dep1: { name: 'dep2', version: '2' } }, + }, + }, + ], + }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('gradle').returns(plugin); - const tests = res - .split('Testing gradle-app...') - .filter((s) => !!s.trim()); - t.equal(tests.length, 2, 'two projects tested independently'); - t.match( - res, - /Tested 2 projects/, - 'number projects tested displayed properly', - ); - t.notMatch( - res, - /use --all-sub-projects flag to scan all sub-projects/, - 'all-sub-projects flag is NOT suggested as we already scanned with it', - ); - for (let i = 0; i < tests.length; i++) { - const meta = tests[i] - .slice(tests[i].indexOf('Organization:')) - .split('\n'); - t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); - t.match( - meta[1], - /Package manager:\s+gradle/, - 'package manager displayed', + const commandResult: CommandResult = await params.cli.test( + 'gradle-app', + { + allSubProjects: true, + }, ); + const res = commandResult.getDisplayResults(); + t.ok( + ((spyPlugin.args[0] as any)[2] as any).allSubProjects, + '`allSubProjects` option is sent', + ); + + const tests = res + .split('Testing gradle-app...') + .filter((s) => !!s.trim()); + t.equal(tests.length, 2, 'two projects tested independently'); t.match( - meta[2], - /Target file:\s+build.gradle/, - 'target file displayed', + res, + /Tested 2 projects/, + 'number projects tested displayed properly', ); - t.match(meta[3], /Project name:\s+tree/, 'sub-project displayed'); - t.match(meta[3], `tree${i}`, 'sub-project displayed'); - t.match(meta[4], /Open source:\s+no/, 'open source displayed'); - t.match(meta[5], /Project path:\s+gradle-app/, 'path displayed'); t.notMatch( - meta[6], - /Local Snyk policy:\s+found/, - 'local policy not displayed', + res, + /use --all-sub-projects flag to scan all sub-projects/, + 'all-sub-projects flag is NOT suggested as we already scanned with it', ); - } - }, + for (let i = 0; i < tests.length; i++) { + const meta = tests[i] + .slice(tests[i].indexOf('Organization:')) + .split('\n'); + t.match( + meta[0], + /Organization:\s+test-org/, + 'organization displayed', + ); + t.match( + meta[1], + /Package manager:\s+gradle/, + 'package manager displayed', + ); + t.match( + meta[2], + /Target file:\s+build.gradle/, + 'target file displayed', + ); + t.match(meta[3], /Project name:\s+tree/, 'sub-project displayed'); + t.match(meta[3], `tree${i}`, 'sub-project displayed'); + t.match(meta[4], /Open source:\s+no/, 'open source displayed'); + t.match(meta[5], /Project path:\s+gradle-app/, 'path displayed'); + t.notMatch( + meta[6], + /Local Snyk policy:\s+found/, + 'local policy not displayed', + ); + } + }, }, }; diff --git a/test/tap/cli-test/cli-test.maven.spec.ts b/test/tap/cli-test/cli-test.maven.spec.ts index d44ac34a49..92005c4a8b 100644 --- a/test/tap/cli-test/cli-test.maven.spec.ts +++ b/test/tap/cli-test/cli-test.maven.spec.ts @@ -23,203 +23,192 @@ function stubExec(t, execOutputFile) { export const MavenTests: AcceptanceTests = { language: 'Maven', tests: { - '`test maven-app --file=pom.xml --dev` sends package info': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - stubExec(t, 'maven-app/mvn-dep-tree-stdout.txt'); - await params.cli.test('maven-app', { - file: 'pom.xml', - org: 'nobelprize.org', - dev: true, - }); + '`test maven-app --file=pom.xml --dev` sends package info': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + stubExec(t, 'maven-app/mvn-dep-tree-stdout.txt'); + await params.cli.test('maven-app', { + file: 'pom.xml', + org: 'nobelprize.org', + dev: true, + }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal( - req.query.org, - 'nobelprize.org', - 'org sent as a query in request', - ); - t.match(req.body.targetFile, undefined, 'target is undefined'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal( + req.query.org, + 'nobelprize.org', + 'org sent as a query in request', + ); + t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = depGraphLib.createFromJSON(req.body.depGraph); - t.equal( - depGraph.rootPkg.name, - 'com.mycompany.app:maven-app', - 'root name', - ); - const pkgs = depGraph.getPkgs().map((x) => `${x.name}@${x.version}`); - t.ok(pkgs.indexOf('com.mycompany.app:maven-app@1.0-SNAPSHOT') >= 0); - t.ok(pkgs.indexOf('axis:axis@1.4') >= 0); - t.ok(pkgs.indexOf('junit:junit@3.8.2') >= 0); - }, + const depGraph = depGraphLib.createFromJSON(req.body.depGraph); + t.equal( + depGraph.rootPkg.name, + 'com.mycompany.app:maven-app', + 'root name', + ); + const pkgs = depGraph.getPkgs().map((x) => `${x.name}@${x.version}`); + t.ok(pkgs.indexOf('com.mycompany.app:maven-app@1.0-SNAPSHOT') >= 0); + t.ok(pkgs.indexOf('axis:axis@1.4') >= 0); + t.ok(pkgs.indexOf('junit:junit@3.8.2') >= 0); + }, - '`test maven-app-with-jars --file=example.jar` sends package info': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('maven').returns(plugin); + '`test maven-app-with-jars --file=example.jar` sends package info': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('maven').returns(plugin); - await params.cli.test('maven-app-with-jars', { - file: 'example.jar', - }); + await params.cli.test('maven-app-with-jars', { + file: 'example.jar', + }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); - t.equal(req.body.depGraph.pkgManager.name, 'maven'); - t.same( - spyPlugin.getCall(0).args, - [ - 'maven-app-with-jars', - 'example.jar', - { - args: null, - file: 'example.jar', - org: null, - projectName: null, - packageManager: 'maven', - path: 'maven-app-with-jars', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls mvn plugin', - ); - }, + t.equal(req.body.depGraph.pkgManager.name, 'maven'); + t.same( + spyPlugin.getCall(0).args, + [ + 'maven-app-with-jars', + 'example.jar', + { + args: null, + file: 'example.jar', + org: null, + projectName: null, + packageManager: 'maven', + path: 'maven-app-with-jars', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls mvn plugin', + ); + }, - '`test maven-app-with-jars --file=example.war` sends package info': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('maven').returns(plugin); + '`test maven-app-with-jars --file=example.war` sends package info': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('maven').returns(plugin); - await params.cli.test('maven-app-with-jars', { - file: 'example.war', - }); + await params.cli.test('maven-app-with-jars', { + file: 'example.war', + }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); - t.equal(req.body.depGraph.pkgManager.name, 'maven'); - t.same( - spyPlugin.getCall(0).args, - [ - 'maven-app-with-jars', - 'example.war', - { - args: null, - file: 'example.war', - org: null, - projectName: null, - packageManager: 'maven', - path: 'maven-app-with-jars', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls mvn plugin', - ); - }, + t.equal(req.body.depGraph.pkgManager.name, 'maven'); + t.same( + spyPlugin.getCall(0).args, + [ + 'maven-app-with-jars', + 'example.war', + { + args: null, + file: 'example.war', + org: null, + projectName: null, + packageManager: 'maven', + path: 'maven-app-with-jars', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls mvn plugin', + ); + }, - '`test maven-app-with-jars --scan-all-unmanaged` sends package info': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('maven').returns(plugin); - await params.cli.test('maven-app-with-jars', { - scanAllUnmanaged: true, - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - t.equal(req.body.depGraph.pkgManager.name, 'maven'); - t.same( - spyPlugin.getCall(0).args, - [ - 'maven-app-with-jars', - undefined, // no specified target file - { - args: null, - // file: undefined, no file - org: null, - projectName: null, - packageManager: 'maven', - path: 'maven-app-with-jars', - showVulnPaths: 'some', - scanAllUnmanaged: true, + '`test maven-app-with-jars --scan-all-unmanaged` sends package info': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls mvn plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('maven').returns(plugin); + await params.cli.test('maven-app-with-jars', { + scanAllUnmanaged: true, + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + t.equal(req.body.depGraph.pkgManager.name, 'maven'); + t.same( + spyPlugin.getCall(0).args, + [ + 'maven-app-with-jars', + undefined, // no specified target file + { + args: null, + // file: undefined, no file + org: null, + projectName: null, + packageManager: 'maven', + path: 'maven-app-with-jars', + showVulnPaths: 'some', + scanAllUnmanaged: true, + }, + snykHttpClient, + ], + 'calls mvn plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.npm.spec.ts b/test/tap/cli-test/cli-test.npm.spec.ts index 6f62bf5919..6cbcd81f72 100644 --- a/test/tap/cli-test/cli-test.npm.spec.ts +++ b/test/tap/cli-test/cli-test.npm.spec.ts @@ -5,21 +5,20 @@ import { getFixturePath } from '../../jest/util/getFixturePath'; export const NpmTests: AcceptanceTests = { language: 'NPM', tests: { - '`test npm-package with custom --project-name`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package', { - 'project-name': 'custom-project-name', - }); - const req = params.server.popRequest(); - t.match( - req.body.projectNameOverride, - 'custom-project-name', - 'custom project name is passed', - ); - t.match(req.body.targetFile, undefined, 'target is undefined'); - }, + '`test npm-package with custom --project-name`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package', { + 'project-name': 'custom-project-name', + }); + const req = params.server.popRequest(); + t.match( + req.body.projectNameOverride, + 'custom-project-name', + 'custom project name is passed', + ); + t.match(req.body.targetFile, undefined, 'target is undefined'); + }, '`test npm-package with lockfile v2`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -45,18 +44,18 @@ export const NpmTests: AcceptanceTests = { ); }, - '`test npm-package with lockfile v3 bundled deps`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const res = await params.cli.test('npm-package-lockfile-v3-bundled-deps'); - t.match( - res, - /Tested 570 dependencies for known vulnerabilities/, - 'should succeed scanning npm lock v3 with bundled deps', - ); - }, + '`test npm-package with lockfile v3 bundled deps`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const res = await params.cli.test( + 'npm-package-lockfile-v3-bundled-deps', + ); + t.match( + res, + /Tested 570 dependencies for known vulnerabilities/, + 'should succeed scanning npm lock v3 with bundled deps', + ); + }, 'test npm-package remoteUrl': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -77,29 +76,27 @@ export const NpmTests: AcceptanceTests = { delete process.env.GIT_DIR; }, - 'test npm-package remoteUrl with --remote-repo-url': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - process.env.GIT_DIR = 'npm-package/gitdir'; - await params.cli.test('npm-package', { - 'remote-repo-url': 'foo', - }); - const req = params.server.popRequest(); - t.equal( - req.body.target.remoteUrl, - 'foo', - 'specified remoteUrl is passed', - ); - t.equal( - req.body.target.branch, - 'master', - 'correct branch passed to request', - ); + 'test npm-package remoteUrl with --remote-repo-url': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + process.env.GIT_DIR = 'npm-package/gitdir'; + await params.cli.test('npm-package', { + 'remote-repo-url': 'foo', + }); + const req = params.server.popRequest(); + t.equal( + req.body.target.remoteUrl, + 'foo', + 'specified remoteUrl is passed', + ); + t.equal( + req.body.target.branch, + 'master', + 'correct branch passed to request', + ); - delete process.env.GIT_DIR; - }, + delete process.env.GIT_DIR; + }, '`test --file=protect/package.json`': (params) => async (t) => { const res = await params.cli.test(getFixturePath('protect'), { @@ -112,27 +109,37 @@ export const NpmTests: AcceptanceTests = { ); }, - '`test npm-package-policy` returns correct meta': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - const commandResult: CommandResult = await params.cli.test( - 'npm-package-policy', - ); - const res = commandResult.getDisplayResults(); - const meta = res.slice(res.indexOf('Organization:')).split('\n'); - t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); - t.match(meta[1], /Package manager:\s+npm/, 'package manager displayed'); - t.match(meta[2], /Target file:\s+package.json/, 'target file displayed'); - t.match( - meta[3], - /Project name:\s+custom-policy-location-package/, - 'project name displayed', - ); - t.match(meta[4], /Open source:\s+no/, 'open source displayed'); - t.match(meta[5], /Project path:\s+npm-package-policy/, 'path displayed'); - t.match(meta[6], /Local Snyk policy:\s+found/, 'local policy displayed'); - }, + '`test npm-package-policy` returns correct meta': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const commandResult: CommandResult = + await params.cli.test('npm-package-policy'); + const res = commandResult.getDisplayResults(); + const meta = res.slice(res.indexOf('Organization:')).split('\n'); + t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); + t.match(meta[1], /Package manager:\s+npm/, 'package manager displayed'); + t.match( + meta[2], + /Target file:\s+package.json/, + 'target file displayed', + ); + t.match( + meta[3], + /Project name:\s+custom-policy-location-package/, + 'project name displayed', + ); + t.match(meta[4], /Open source:\s+no/, 'open source displayed'); + t.match( + meta[5], + /Project path:\s+npm-package-policy/, + 'path displayed', + ); + t.match( + meta[6], + /Local Snyk policy:\s+found/, + 'local policy displayed', + ); + }, '`test npm-package` sends pkg info': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -149,212 +156,191 @@ export const NpmTests: AcceptanceTests = { ); }, - '`test npm-package --file=package-lock.json ` sends pkg info': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package', { file: 'package-lock.json' }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), - 'depGraph looks fine', - ); - }, + '`test npm-package --file=package-lock.json ` sends pkg info': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package', { file: 'package-lock.json' }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), + 'depGraph looks fine', + ); + }, - '`test npm-package --file=package-lock.json --dev` sends pkg info': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package', { - file: 'package-lock.json', - dev: true, - }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'npm-package@1.0.0', - 'ms@0.7.1', - 'debug@2.2.0', - 'object-assign@4.1.1', - ].sort(), - 'depGraph looks fine', - ); - }, + '`test npm-package --file=package-lock.json --dev` sends pkg info': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package', { + file: 'package-lock.json', + dev: true, + }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'npm-package@1.0.0', + 'ms@0.7.1', + 'debug@2.2.0', + 'object-assign@4.1.1', + ].sort(), + 'depGraph looks fine', + ); + }, - '`test npm-out-of-sync` out of sync fails': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('npm-out-of-sync', { dev: true }); - t.fail('Should fail'); - } catch (e) { - t.equal( - e.message, - '\nTesting npm-out-of-sync...\n\n' + - 'Dependency snyk was not found in package-lock.json.' + - ' Your package.json and package-lock.json are probably out of sync.' + - ' Please run "npm install" and try again.', - 'Contains enough info about err', + '`test npm-out-of-sync` out of sync fails': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('npm-out-of-sync', { dev: true }); + t.fail('Should fail'); + } catch (e) { + t.equal( + e.message, + '\nTesting npm-out-of-sync...\n\n' + + 'Dependency snyk was not found in package-lock.json.' + + ' Your package.json and package-lock.json are probably out of sync.' + + ' Please run "npm install" and try again.', + 'Contains enough info about err', + ); + } + }, + + '`test npm-out-of-sync --strict-out-of-sync=false` passes': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-out-of-sync', { + dev: true, + strictOutOfSync: false, + }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'npm-package@1.0.0', + 'object-assign@4.1.1', + 'rewire@^4.0.1', + 'snyk@*', + 'to-array@0.1.4', + ].sort(), + 'depGraph looks fine', ); - } - }, + }, - '`test npm-out-of-sync --strict-out-of-sync=false` passes': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-out-of-sync', { - dev: true, - strictOutOfSync: false, - }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'npm-package@1.0.0', - 'object-assign@4.1.1', - 'rewire@^4.0.1', - 'snyk@*', - 'to-array@0.1.4', - ].sort(), - 'depGraph looks fine', - ); - }, + '`test npm-package-shrinkwrap --file=package-lock.json` with npm-shrinkwrap errors': + (params, utils) => async (t) => { + t.plan(1); + utils.chdirWorkspaces(); + try { + await params.cli.test('npm-package-shrinkwrap', { + file: 'package-lock.json', + }); + t.fail('Should fail'); + } catch (e) { + t.match( + e.message, + '--file=package.json', + 'Contains enough info about err', + ); + } + }, - '`test npm-package-shrinkwrap --file=package-lock.json` with npm-shrinkwrap errors': ( - params, - utils, - ) => async (t) => { - t.plan(1); - utils.chdirWorkspaces(); - try { - await params.cli.test('npm-package-shrinkwrap', { + '`test npm-package-with-subfolder --file=package-lock.json ` picks top-level files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package-with-subfolder', { file: 'package-lock.json', }); - t.fail('Should fail'); - } catch (e) { - t.match( - e.message, - '--file=package.json', - 'Contains enough info about err', + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package-top-level@1.0.0', 'to-array@0.1.4'].sort(), + 'depGraph looks fine', ); - } - }, - - '`test npm-package-with-subfolder --file=package-lock.json ` picks top-level files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package-with-subfolder', { - file: 'package-lock.json', - }); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package-top-level@1.0.0', 'to-array@0.1.4'].sort(), - 'depGraph looks fine', - ); - }, + }, - '`test npm-package-with-subfolder --file=subfolder/package-lock.json ` picks subfolder files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package-with-subfolder', { - file: 'subfolder/package-lock.json', - }); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package-subfolder@1.0.0', 'to-array@0.1.4'].sort(), - 'depGraph looks fine', - ); - }, - '`test npm-package-with-overrides` correctly completes test': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package-with-overrides'); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).includes('semver@6.0.0'), - false, - 'override pkg original version not present', - ); - t.same( - depGraph.pkgs.map((p) => p.id).includes('semver@7.5.2'), - true, - 'override pkg is correct version', - ); - }, - '`test npm-lock-v2-with-npm-prefixed-sub-dep-version` correctly completes test': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-lock-v2-with-npm-prefixed-sub-dep-version'); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).includes('string-width-cjs@4.2.3'), - true, - 'npm prefixed subdep has a numbered version', - ); - }, - '`test npm-lock-v2-with-simple-version-range-override` correctly completes test': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-lock-v2-with-simple-version-range-override'); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.notOk( - depGraph.pkgs - .map((p) => p.id) - .find((el: string) => el.startsWith('uuid@8')), - 'no uuid version matching ^8', - ); - t.ok( - depGraph.pkgs - .map((p) => p.id) - .find((el: string) => el.startsWith('uuid@9')), - 'uuid version matching ^9', - ); - }, - '`test npm-package-with-dist-tag-subdependency` correctly completes test': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('npm-package-with-dist-tag-subdependency'); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).includes('cdktf-cli@0.20.3'), - true, - 'npm subdep with dist tag has a numbered version', - ); - }, + '`test npm-package-with-subfolder --file=subfolder/package-lock.json ` picks subfolder files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package-with-subfolder', { + file: 'subfolder/package-lock.json', + }); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package-subfolder@1.0.0', 'to-array@0.1.4'].sort(), + 'depGraph looks fine', + ); + }, + '`test npm-package-with-overrides` correctly completes test': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package-with-overrides'); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).includes('semver@6.0.0'), + false, + 'override pkg original version not present', + ); + t.same( + depGraph.pkgs.map((p) => p.id).includes('semver@7.5.2'), + true, + 'override pkg is correct version', + ); + }, + '`test npm-lock-v2-with-npm-prefixed-sub-dep-version` correctly completes test': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-lock-v2-with-npm-prefixed-sub-dep-version'); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).includes('string-width-cjs@4.2.3'), + true, + 'npm prefixed subdep has a numbered version', + ); + }, + '`test npm-lock-v2-with-simple-version-range-override` correctly completes test': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-lock-v2-with-simple-version-range-override'); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.notOk( + depGraph.pkgs + .map((p) => p.id) + .find((el: string) => el.startsWith('uuid@8')), + 'no uuid version matching ^8', + ); + t.ok( + depGraph.pkgs + .map((p) => p.id) + .find((el: string) => el.startsWith('uuid@9')), + 'uuid version matching ^9', + ); + }, + '`test npm-package-with-dist-tag-subdependency` correctly completes test': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('npm-package-with-dist-tag-subdependency'); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).includes('cdktf-cli@0.20.3'), + true, + 'npm subdep with dist tag has a numbered version', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.nuget.spec.ts b/test/tap/cli-test/cli-test.nuget.spec.ts index aeda4cf03c..63720cce6f 100644 --- a/test/tap/cli-test/cli-test.nuget.spec.ts +++ b/test/tap/cli-test/cli-test.nuget.spec.ts @@ -24,505 +24,478 @@ export const NugetTests: AcceptanceTests = { } }, - '`test nuget-app-2 auto-detects project.assets.json`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'project.assets.json', - }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app-2'); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app-2', - 'project.assets.json', - { - args: null, - file: 'project.assets.json', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app-2', - showVulnPaths: 'some', + '`test nuget-app-2 auto-detects project.assets.json`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'project.assets.json', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test nuget-app-2.1 auto-detects obj/project.assets.json`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'obj/project.assets.json', + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app-2'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app-2', + 'project.assets.json', + { + args: null, + file: 'project.assets.json', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app-2', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app-2.1'); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app-2.1', - 'obj/project.assets.json', - { - args: null, - file: 'obj/project.assets.json', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app-2.1', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test nuget-app-2.1 auto-detects obj/project.assets.json`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'obj/project.assets.json', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test nuget-app-4 auto-detects packages.config`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'paket.dependencies', - targetRuntime: 'net465s', + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app-2.1'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app-2.1', + 'obj/project.assets.json', + { + args: null, + file: 'obj/project.assets.json', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app-2.1', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app-4'); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app-4', - 'packages.config', - { - args: null, - file: 'packages.config', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app-4', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test nuget-app-4 auto-detects packages.config`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'paket.dependencies', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test nuget-app --file=project.assets.json`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'project.assets.json', - targetRuntime: 'net465s', + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app-4'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app-4', + 'packages.config', + { + args: null, + file: 'packages.config', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app-4', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app', { - file: 'project.assets.json', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.targetFile, 'project.assets.json', 'specifies target'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app', - 'project.assets.json', - { - args: null, - file: 'project.assets.json', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test nuget-app --file=project.assets.json`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'project.assets.json', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, - - '`test nuget-app --file=packages.config`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'packages.config', - targetRuntime: 'net465s', + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app', { + file: 'project.assets.json', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.targetFile, 'project.assets.json', 'specifies target'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app', + 'project.assets.json', + { + args: null, + file: 'project.assets.json', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app', { - file: 'packages.config', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.targetFile, 'packages.config', 'specifies target'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app', - 'packages.config', - { - args: null, - file: 'packages.config', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test nuget-app --file=packages.config`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'packages.config', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, - - '`test nuget-app --file=project.json`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'testplugin', - runtime: 'testruntime', - targetFile: 'project.json', + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app', { + file: 'packages.config', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.targetFile, 'packages.config', 'specifies target'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app', + 'packages.config', + { + args: null, + file: 'packages.config', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('nuget-app', { - file: 'project.json', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.targetFile, 'project.json', 'specifies target'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'nuget-app', - 'project.json', - { - args: null, - file: 'project.json', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'nuget-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test nuget-app --file=project.json`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'testplugin', + runtime: 'testruntime', + targetFile: 'project.json', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, - - '`test paket-app auto-detects paket.dependencies`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'paket.dependencies', - targetRuntime: 'net465s', + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('nuget-app', { + file: 'project.json', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.targetFile, 'project.json', 'specifies target'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'nuget-app', + 'project.json', + { + args: null, + file: 'project.json', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'nuget-app', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('paket').returns(plugin); - - await params.cli.test('paket-app'); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'paket'); - t.same( - spyPlugin.getCall(0).args, - [ - 'paket-app', - 'paket.dependencies', - { - args: null, - file: 'paket.dependencies', - org: null, - projectName: null, - packageManager: 'paket', - path: 'paket-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test paket-app auto-detects paket.dependencies`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'paket.dependencies', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test paket-obj-app auto-detects obj/project.assets.json if exists`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'paket.dependencies', - targetRuntime: 'net465s', + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('paket').returns(plugin); + + await params.cli.test('paket-app'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'paket'); + t.same( + spyPlugin.getCall(0).args, + [ + 'paket-app', + 'paket.dependencies', + { + args: null, + file: 'paket.dependencies', + org: null, + projectName: null, + packageManager: 'paket', + path: 'paket-app', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('nuget').returns(plugin); - - await params.cli.test('paket-obj-app'); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'nuget'); - t.same( - spyPlugin.getCall(0).args, - [ - 'paket-obj-app', - 'obj/project.assets.json', - { - args: null, - file: 'obj/project.assets.json', - org: null, - projectName: null, - packageManager: 'nuget', - path: 'paket-obj-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test paket-obj-app auto-detects obj/project.assets.json if exists`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'paket.dependencies', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test paket-app --file=paket.dependencies`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { - name: 'snyk-nuget-plugin', - targetFile: 'paket.dependencies', - targetRuntime: 'net465s', + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('nuget').returns(plugin); + + await params.cli.test('paket-obj-app'); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'nuget'); + t.same( + spyPlugin.getCall(0).args, + [ + 'paket-obj-app', + 'obj/project.assets.json', + { + args: null, + file: 'obj/project.assets.json', + org: null, + projectName: null, + packageManager: 'nuget', + path: 'paket-obj-app', + showVulnPaths: 'some', }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('paket').returns(plugin); - - await params.cli.test('paket-app', { - file: 'paket.dependencies', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'paket'); - t.equal(req.body.targetFile, 'paket.dependencies', 'specifies target'); - t.same( - spyPlugin.getCall(0).args, - [ - 'paket-app', - 'paket.dependencies', - { - args: null, - file: 'paket.dependencies', - org: null, - projectName: null, - packageManager: 'paket', - path: 'paket-app', - showVulnPaths: 'some', + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, + + '`test paket-app --file=paket.dependencies`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { + name: 'snyk-nuget-plugin', + targetFile: 'paket.dependencies', + targetRuntime: 'net465s', + }, + }; }, - snykHttpClient, - ], - 'calls nuget plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('paket').returns(plugin); + + await params.cli.test('paket-app', { + file: 'paket.dependencies', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'paket'); + t.equal(req.body.targetFile, 'paket.dependencies', 'specifies target'); + t.same( + spyPlugin.getCall(0).args, + [ + 'paket-app', + 'paket.dependencies', + { + args: null, + file: 'paket.dependencies', + org: null, + projectName: null, + packageManager: 'paket', + path: 'paket-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls nuget plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.python.spec.ts b/test/tap/cli-test/cli-test.python.spec.ts index 16f7158636..6b073b1310 100644 --- a/test/tap/cli-test/cli-test.python.spec.ts +++ b/test/tap/cli-test/cli-test.python.spec.ts @@ -6,297 +6,284 @@ import { loadJson } from '../../utils'; export const PythonTests: AcceptanceTests = { language: 'Python', tests: { - '`test pip-app --file=requirements.txt`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - package: {}, - plugin: { name: 'testplugin', runtime: 'testruntime' }, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); - - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('pip').returns(plugin); - - await params.cli.test('pip-app', { - file: 'requirements.txt', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'pip'); - t.same( - spyPlugin.getCall(0).args, - [ - 'pip-app', - 'requirements.txt', - { - args: null, - file: 'requirements.txt', - org: null, - projectName: null, - packageManager: 'pip', - path: 'pip-app', - showVulnPaths: 'some', + '`test pip-app --file=requirements.txt`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + package: {}, + plugin: { name: 'testplugin', runtime: 'testruntime' }, + }; }, - snykHttpClient, - ], - 'calls python plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test pipenv-app --file=Pipfile`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - plugin: { - targetFile: 'Pipfile', - name: 'snyk-python-plugin', - runtime: 'Python', - }, - package: {}, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('pip').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('pip').returns(plugin); + await params.cli.test('pip-app', { + file: 'requirements.txt', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'pip'); + t.same( + spyPlugin.getCall(0).args, + [ + 'pip-app', + 'requirements.txt', + { + args: null, + file: 'requirements.txt', + org: null, + projectName: null, + packageManager: 'pip', + path: 'pip-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls python plugin', + ); + }, - await params.cli.test('pipenv-app', { - file: 'Pipfile', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.targetFile, 'Pipfile', 'specifies target'); - t.equal(req.body.depGraph.pkgManager.name, 'pip'); - t.same( - spyPlugin.getCall(0).args, - [ - 'pipenv-app', - 'Pipfile', - { - args: null, - file: 'Pipfile', - org: null, - projectName: null, - packageManager: 'pip', - path: 'pipenv-app', - showVulnPaths: 'some', + '`test pipenv-app --file=Pipfile`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + plugin: { + targetFile: 'Pipfile', + name: 'snyk-python-plugin', + runtime: 'Python', + }, + package: {}, + }; }, - snykHttpClient, - ], - 'calls python plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - '`test pip-app-transitive-vuln --file=requirements.txt (actionableCliRemediation=false)`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return loadJson('./pip-app-transitive-vuln/inspect-result.json'); - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('pip').returns(plugin); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('pip').returns(plugin); - - params.server.setNextResponse( - loadJson('./pip-app-transitive-vuln/response-without-remediation.json'), - ); - try { - await params.cli.test('pip-app-transitive-vuln', { - file: 'requirements.txt', + await params.cli.test('pipenv-app', { + file: 'Pipfile', }); - t.fail('should throw, since there are vulns'); - } catch (e) { + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); t.equal( - e.message.trim(), - fs - .readFileSync('pip-app-transitive-vuln/cli-output.txt', 'utf8') - .trim(), + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - } - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'pip'); - t.same( - spyPlugin.getCall(0).args, - [ - 'pip-app-transitive-vuln', - 'requirements.txt', - { - args: null, - file: 'requirements.txt', - org: null, - projectName: null, - packageManager: 'pip', - path: 'pip-app-transitive-vuln', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls python plugin', - ); - }, + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.targetFile, 'Pipfile', 'specifies target'); + t.equal(req.body.depGraph.pkgManager.name, 'pip'); + t.same( + spyPlugin.getCall(0).args, + [ + 'pipenv-app', + 'Pipfile', + { + args: null, + file: 'Pipfile', + org: null, + projectName: null, + packageManager: 'pip', + path: 'pipenv-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls python plugin', + ); + }, - '`test pip-app-transitive-vuln --file=requirements.txt (actionableCliRemediation=true)`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return loadJson('./pip-app-transitive-vuln/inspect-result.json'); - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + '`test pip-app-transitive-vuln --file=requirements.txt (actionableCliRemediation=false)`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return loadJson('./pip-app-transitive-vuln/inspect-result.json'); + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('pip').returns(plugin); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('pip').returns(plugin); - params.server.setNextResponse( - loadJson('./pip-app-transitive-vuln/response-with-remediation.json'), - ); - try { - await params.cli.test('pip-app-transitive-vuln', { - file: 'requirements.txt', - }); - t.fail('should throw, since there are vulns'); - } catch (e) { - t.equal( - e.message.trim(), - fs - .readFileSync( - 'pip-app-transitive-vuln/cli-output-actionable-remediation.txt', - 'utf8', - ) - .trim(), + params.server.setNextResponse( + loadJson( + './pip-app-transitive-vuln/response-without-remediation.json', + ), ); - } - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.depGraph.pkgManager.name, 'pip'); - t.same( - spyPlugin.getCall(0).args, - [ - 'pip-app-transitive-vuln', - 'requirements.txt', - { - args: null, + try { + await params.cli.test('pip-app-transitive-vuln', { file: 'requirements.txt', - org: null, - projectName: null, - packageManager: 'pip', - path: 'pip-app-transitive-vuln', - showVulnPaths: 'some', - }, - snykHttpClient, - ], - 'calls python plugin', - ); - }, - '`test setup_py-app --file=setup.py`': ( - params, - utils, - snykHttpClient, - ) => async (t) => { - utils.chdirWorkspaces(); - const plugin = { - async inspect() { - return { - plugin: { - targetFile: 'setup.py', - name: 'snyk-python-plugin', - runtime: 'Python', + }); + t.fail('should throw, since there are vulns'); + } catch (e) { + t.equal( + e.message.trim(), + fs + .readFileSync('pip-app-transitive-vuln/cli-output.txt', 'utf8') + .trim(), + ); + } + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'pip'); + t.same( + spyPlugin.getCall(0).args, + [ + 'pip-app-transitive-vuln', + 'requirements.txt', + { + args: null, + file: 'requirements.txt', + org: null, + projectName: null, + packageManager: 'pip', + path: 'pip-app-transitive-vuln', + showVulnPaths: 'some', }, - package: {}, - }; - }, - }; - const spyPlugin = sinon.spy(plugin, 'inspect'); + snykHttpClient, + ], + 'calls python plugin', + ); + }, - const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); - t.teardown(loadPlugin.restore); - loadPlugin.withArgs('pip').returns(plugin); + '`test pip-app-transitive-vuln --file=requirements.txt (actionableCliRemediation=true)`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return loadJson('./pip-app-transitive-vuln/inspect-result.json'); + }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); - await params.cli.test('setup_py-app', { - file: 'setup.py', - }); + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('pip').returns(plugin); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.equal(req.body.targetFile, 'setup.py', 'specifies target'); - t.equal(req.body.depGraph.pkgManager.name, 'pip'); - t.same( - spyPlugin.getCall(0).args, - [ - 'setup_py-app', - 'setup.py', - { - args: null, - file: 'setup.py', - org: null, - projectName: null, - packageManager: 'pip', - path: 'setup_py-app', - showVulnPaths: 'some', + params.server.setNextResponse( + loadJson('./pip-app-transitive-vuln/response-with-remediation.json'), + ); + try { + await params.cli.test('pip-app-transitive-vuln', { + file: 'requirements.txt', + }); + t.fail('should throw, since there are vulns'); + } catch (e) { + t.equal( + e.message.trim(), + fs + .readFileSync( + 'pip-app-transitive-vuln/cli-output-actionable-remediation.txt', + 'utf8', + ) + .trim(), + ); + } + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.depGraph.pkgManager.name, 'pip'); + t.same( + spyPlugin.getCall(0).args, + [ + 'pip-app-transitive-vuln', + 'requirements.txt', + { + args: null, + file: 'requirements.txt', + org: null, + projectName: null, + packageManager: 'pip', + path: 'pip-app-transitive-vuln', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls python plugin', + ); + }, + '`test setup_py-app --file=setup.py`': + (params, utils, snykHttpClient) => async (t) => { + utils.chdirWorkspaces(); + const plugin = { + async inspect() { + return { + plugin: { + targetFile: 'setup.py', + name: 'snyk-python-plugin', + runtime: 'Python', + }, + package: {}, + }; }, - snykHttpClient, - ], - 'calls python plugin', - ); - }, + }; + const spyPlugin = sinon.spy(plugin, 'inspect'); + + const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); + t.teardown(loadPlugin.restore); + loadPlugin.withArgs('pip').returns(plugin); + + await params.cli.test('setup_py-app', { + file: 'setup.py', + }); + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.equal(req.body.targetFile, 'setup.py', 'specifies target'); + t.equal(req.body.depGraph.pkgManager.name, 'pip'); + t.same( + spyPlugin.getCall(0).args, + [ + 'setup_py-app', + 'setup.py', + { + args: null, + file: 'setup.py', + org: null, + projectName: null, + packageManager: 'pip', + path: 'setup_py-app', + showVulnPaths: 'some', + }, + snykHttpClient, + ], + 'calls python plugin', + ); + }, }, }; diff --git a/test/tap/cli-test/cli-test.ruby.spec.ts b/test/tap/cli-test/cli-test.ruby.spec.ts index 9b2e614ec7..1438adaca1 100644 --- a/test/tap/cli-test/cli-test.ruby.spec.ts +++ b/test/tap/cli-test/cli-test.ruby.spec.ts @@ -8,18 +8,17 @@ import * as path from 'path'; export const RubyTests: AcceptanceTests = { language: 'Ruby', tests: { - '`test ruby-app-no-lockfile --file=Gemfile`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('ruby-app-no-lockfile', { file: 'Gemfile' }); - t.fail('should have failed'); - } catch (err) { - t.pass('throws err'); - t.match(err.message, 'Please run `bundle install`', 'shows err'); - } - }, + '`test ruby-app-no-lockfile --file=Gemfile`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('ruby-app-no-lockfile', { file: 'Gemfile' }); + t.fail('should have failed'); + } catch (err) { + t.pass('throws err'); + t.match(err.message, 'Please run `bundle install`', 'shows err'); + } + }, '`test ruby-app --file=Gemfile.lock`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -43,133 +42,125 @@ export const RubyTests: AcceptanceTests = { ); }, - '`test ruby-app-custom-names --file=123.gemfile.lock --package-manager=rubygems`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('ruby-app-custom-names', { - file: '123.gemfile.lock', - packageManager: 'rubygems', - }); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - - const depGraph = req.body.depGraph; - t.equal(depGraph.pkgManager.name, 'rubygems'); - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'crass@1.0.4', - 'lynx@0.4.0', - 'mini_portile2@2.3.0', - 'nokogiri@1.8.5', - 'nokogumbo@1.5.0', - 'ruby-app-custom-names@', - 'sanitize@4.6.2', - 'yard@0.8.0', - ].sort(), - 'depGraph looks fine', - ); - }, - '`test ruby-app-custom-names --file=123.gemfile --package-manager=rubygems`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('ruby-app-custom-names', { - file: '123.gemfile', - packageManager: 'rubygems', - }); - - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); + '`test ruby-app-custom-names --file=123.gemfile.lock --package-manager=rubygems`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('ruby-app-custom-names', { + file: '123.gemfile.lock', + packageManager: 'rubygems', + }); - const depGraph = req.body.depGraph; - t.equal(depGraph.pkgManager.name, 'rubygems'); - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'crass@1.0.4', - 'lynx@0.4.0', - 'mini_portile2@2.3.0', - 'nokogiri@1.8.5', - 'nokogumbo@1.5.0', - 'ruby-app-custom-names@', - 'sanitize@4.6.2', - 'yard@0.8.0', - ].sort(), - 'depGraph looks fine', - ); - }, + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); - '`test ruby-app-custom-names --file=gemfiles/Gemfile.rails-2.3.6 --package-manager=rubygems`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { + const depGraph = req.body.depGraph; + t.equal(depGraph.pkgManager.name, 'rubygems'); + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'crass@1.0.4', + 'lynx@0.4.0', + 'mini_portile2@2.3.0', + 'nokogiri@1.8.5', + 'nokogumbo@1.5.0', + 'ruby-app-custom-names@', + 'sanitize@4.6.2', + 'yard@0.8.0', + ].sort(), + 'depGraph looks fine', + ); + }, + '`test ruby-app-custom-names --file=123.gemfile --package-manager=rubygems`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); await params.cli.test('ruby-app-custom-names', { - file: 'gemfiles/Gemfile.rails-2.3.6', + file: '123.gemfile', packageManager: 'rubygems', }); - } catch (e) { - t.match( - e.message, - 'if this is a custom file name re-run with --file=path/to/custom.gemfile.lock --package-manager=rubygems', + + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - } - }, + t.match(req.url, '/test-dep-graph', 'posts to correct url'); - '`test ruby-app-custom-names --file=gemfiles/Gemfile.rails-2.4.5.lock --package-manager=rubygems`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('ruby-app-custom-names', { - file: 'gemfiles/Gemfile.rails-2.4.5.lock', - packageManager: 'rubygems', - }); + const depGraph = req.body.depGraph; + t.equal(depGraph.pkgManager.name, 'rubygems'); + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'crass@1.0.4', + 'lynx@0.4.0', + 'mini_portile2@2.3.0', + 'nokogiri@1.8.5', + 'nokogumbo@1.5.0', + 'ruby-app-custom-names@', + 'sanitize@4.6.2', + 'yard@0.8.0', + ].sort(), + 'depGraph looks fine', + ); + }, + + '`test ruby-app-custom-names --file=gemfiles/Gemfile.rails-2.3.6 --package-manager=rubygems`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('ruby-app-custom-names', { + file: 'gemfiles/Gemfile.rails-2.3.6', + packageManager: 'rubygems', + }); + } catch (e) { + t.match( + e.message, + 'if this is a custom file name re-run with --file=path/to/custom.gemfile.lock --package-manager=rubygems', + ); + } + }, + + '`test ruby-app-custom-names --file=gemfiles/Gemfile.rails-2.4.5.lock --package-manager=rubygems`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('ruby-app-custom-names', { + file: 'gemfiles/Gemfile.rails-2.4.5.lock', + packageManager: 'rubygems', + }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); - const depGraph = req.body.depGraph; - t.equal(depGraph.pkgManager.name, 'rubygems'); - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'crass@1.0.4', - 'lynx@0.4.0', - 'mini_portile2@2.3.0', - 'nokogiri@1.8.5', - 'nokogumbo@1.5.0', - 'ruby-app-custom-names@', - 'sanitize@4.6.2', - 'yard@0.8.0', - ].sort(), - 'depGraph looks fine', - ); - }, + const depGraph = req.body.depGraph; + t.equal(depGraph.pkgManager.name, 'rubygems'); + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'crass@1.0.4', + 'lynx@0.4.0', + 'mini_portile2@2.3.0', + 'nokogiri@1.8.5', + 'nokogumbo@1.5.0', + 'ruby-app-custom-names@', + 'sanitize@4.6.2', + 'yard@0.8.0', + ].sort(), + 'depGraph looks fine', + ); + }, '`test ruby-app` meta when no vulns': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -240,297 +231,282 @@ export const RubyTests: AcceptanceTests = { } }, - '`test ruby-app-thresholds --severity-threshold=low --json`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); + '`test ruby-app-thresholds --severity-threshold=low --json`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-low-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'low', - json: true, - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'low'); - - const res = JSON.parse(err.message); - - const expected = getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-result-low-severity.json', + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-low-severity.json', + ), ); - t.same( - omit(res, ['vulnerabilities']), - omit(expected, ['vulnerabilities']), - 'metadata is ok', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'low', + json: true, + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'low'); + + const res = JSON.parse(err.message); + + const expected = getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-result-low-severity.json', + ); + + t.same( + omit(res, ['vulnerabilities']), + omit(expected, ['vulnerabilities']), + 'metadata is ok', + ); + t.same( + sortBy(res.vulnerabilities, 'id'), + sortBy(expected.vulnerabilities, 'id'), + 'vulns are the same', + ); + } + }, + + '`test ruby-app-thresholds --severity-threshold=medium`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-medium-severity.json', + ), ); - t.same( - sortBy(res.vulnerabilities, 'id'), - sortBy(expected.vulnerabilities, 'id'), - 'vulns are the same', - ); - } - }, - - '`test ruby-app-thresholds --severity-threshold=medium`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-medium-severity.json', - ), - ); - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'medium', - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'medium'); - - const res = err.message; - - t.match( - res, - 'Tested 7 dependencies for known vulnerabilities, found 5 vulnerabilities, 6 vulnerable paths', - '5 vulns', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'medium', + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'medium'); + + const res = err.message; + + t.match( + res, + 'Tested 7 dependencies for known vulnerabilities, found 5 vulnerabilities, 6 vulnerable paths', + '5 vulns', + ); + } + }, + + '`test ruby-app-thresholds --ignore-policy`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-medium-severity.json', + ), ); - } - }, - '`test ruby-app-thresholds --ignore-policy`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-medium-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - 'ignore-policy': true, - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.ignorePolicy, 'true'); - t.end(); - } - }, - - '`test ruby-app-thresholds --severity-threshold=medium --json`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-medium-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'medium', - json: true, - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'medium'); - - const res = JSON.parse(err.message); - - const expected = getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-result-medium-severity.json', + try { + await params.cli.test('ruby-app-thresholds', { + 'ignore-policy': true, + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.ignorePolicy, 'true'); + t.end(); + } + }, + + '`test ruby-app-thresholds --severity-threshold=medium --json`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-medium-severity.json', + ), ); - t.same( - omit(res, ['vulnerabilities']), - omit(expected, ['vulnerabilities']), - 'metadata is ok', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'medium', + json: true, + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'medium'); + + const res = JSON.parse(err.message); + + const expected = getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-result-medium-severity.json', + ); + + t.same( + omit(res, ['vulnerabilities']), + omit(expected, ['vulnerabilities']), + 'metadata is ok', + ); + t.same( + sortBy(res.vulnerabilities, 'id'), + sortBy(expected.vulnerabilities, 'id'), + 'vulns are the same', + ); + } + }, + + '`test ruby-app-thresholds --severity-threshold=high': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-high-severity.json', + ), ); - t.same( - sortBy(res.vulnerabilities, 'id'), - sortBy(expected.vulnerabilities, 'id'), - 'vulns are the same', - ); - } - }, - - '`test ruby-app-thresholds --severity-threshold=high': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-high-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'high', - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'high'); - - const res = err.message; - - t.match( - res, - 'Tested 7 dependencies for known vulnerabilities, found 3 vulnerabilities, 4 vulnerable paths', - '3 vulns', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'high', + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'high'); + + const res = err.message; + + t.match( + res, + 'Tested 7 dependencies for known vulnerabilities, found 3 vulnerabilities, 4 vulnerable paths', + '3 vulns', + ); + } + }, + + '`test ruby-app-thresholds --severity-threshold=high --json`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-high-severity.json', + ), ); - } - }, - '`test ruby-app-thresholds --severity-threshold=high --json`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-high-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'high', - json: true, - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'high'); - - const res = JSON.parse(err.message); - - const expected = getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-result-high-severity.json', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'high', + json: true, + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'high'); + + const res = JSON.parse(err.message); + + const expected = getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-result-high-severity.json', + ); + + t.same( + omit(res, ['vulnerabilities']), + omit(expected, ['vulnerabilities']), + 'metadata is ok', + ); + t.same( + sortBy(res.vulnerabilities, 'id'), + sortBy(expected.vulnerabilities, 'id'), + 'vulns are the same', + ); + } + }, + + '`test ruby-app-thresholds --severity-threshold=critical': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-critical-severity.json', + ), ); - t.same( - omit(res, ['vulnerabilities']), - omit(expected, ['vulnerabilities']), - 'metadata is ok', + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'critical', + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'critical'); + + const res = err.message; + + t.match( + res, + 'Tested 7 dependencies for known vulnerabilities, found 1 vulnerability, 2 vulnerable paths', + '1 vuln', + ); + } + }, + + '`test ruby-app-thresholds --severity-threshold=critical --json`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-graph-result-critical-severity.json', + ), ); - t.same( - sortBy(res.vulnerabilities, 'id'), - sortBy(expected.vulnerabilities, 'id'), - 'vulns are the same', - ); - } - }, - - '`test ruby-app-thresholds --severity-threshold=critical': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-critical-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'critical', - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'critical'); - - const res = err.message; - - t.match( - res, - 'Tested 7 dependencies for known vulnerabilities, found 1 vulnerability, 2 vulnerable paths', - '1 vuln', - ); - } - }, - - '`test ruby-app-thresholds --severity-threshold=critical --json`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-graph-result-critical-severity.json', - ), - ); - - try { - await params.cli.test('ruby-app-thresholds', { - severityThreshold: 'critical', - json: true, - }); - t.fail('should have thrown'); - } catch (err) { - const req = params.server.popRequest(); - t.equal(req.query.severityThreshold, 'critical'); - - const res = JSON.parse(err.message); - - const expected = getWorkspaceJSON( - 'ruby-app-thresholds', - 'test-result-critical-severity.json', - ); - - t.same( - omit(res, ['vulnerabilities']), - omit(expected, ['vulnerabilities']), - 'metadata is ok', - ); - t.same( - sortBy(res.vulnerabilities, 'id'), - sortBy(expected.vulnerabilities, 'id'), - 'vulns are the same', - ); - } - }, + try { + await params.cli.test('ruby-app-thresholds', { + severityThreshold: 'critical', + json: true, + }); + t.fail('should have thrown'); + } catch (err) { + const req = params.server.popRequest(); + t.equal(req.query.severityThreshold, 'critical'); + + const res = JSON.parse(err.message); + + const expected = getWorkspaceJSON( + 'ruby-app-thresholds', + 'test-result-critical-severity.json', + ); + + t.same( + omit(res, ['vulnerabilities']), + omit(expected, ['vulnerabilities']), + 'metadata is ok', + ); + t.same( + sortBy(res.vulnerabilities, 'id'), + sortBy(expected.vulnerabilities, 'id'), + 'vulns are the same', + ); + } + }, '`test ruby-app-policy`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -565,43 +541,42 @@ export const RubyTests: AcceptanceTests = { } }, - '`test ruby-app-policy` with cloud ignores': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - - params.server.setNextResponse( - getWorkspaceJSON( - 'ruby-app-policy', - 'test-graph-result-cloud-ignore.json', - ), - ); - - try { - await params.cli.test('ruby-app-policy', { - json: true, - }); - t.fail('should have thrown'); - } catch (err) { - const res = JSON.parse(err.message); + '`test ruby-app-policy` with cloud ignores': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); - const expected = getWorkspaceJSON( - 'ruby-app-policy', - 'test-result-cloud-ignore.json', + params.server.setNextResponse( + getWorkspaceJSON( + 'ruby-app-policy', + 'test-graph-result-cloud-ignore.json', + ), ); - t.same( - omit(res, ['vulnerabilities']), - omit(expected, ['vulnerabilities']), - 'metadata is ok', - ); - t.same( - sortBy(res.vulnerabilities, 'id'), - sortBy(expected.vulnerabilities, 'id'), - 'vulns are the same', - ); - } - }, + try { + await params.cli.test('ruby-app-policy', { + json: true, + }); + t.fail('should have thrown'); + } catch (err) { + const res = JSON.parse(err.message); + + const expected = getWorkspaceJSON( + 'ruby-app-policy', + 'test-result-cloud-ignore.json', + ); + + t.same( + omit(res, ['vulnerabilities']), + omit(expected, ['vulnerabilities']), + 'metadata is ok', + ); + t.same( + sortBy(res.vulnerabilities, 'id'), + sortBy(expected.vulnerabilities, 'id'), + 'vulns are the same', + ); + } + }, '`test ruby-app-no-vulns`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -649,44 +624,44 @@ export const RubyTests: AcceptanceTests = { t.same(res, expected, '--json output is the same'); }, - '`test` returns correct meta when target file specified': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const commandResult: CommandResult = await params.cli.test('ruby-app', { - file: 'Gemfile.lock', - }); - const res = commandResult.getDisplayResults(); - const meta = res.slice(res.indexOf('Organization:')).split('\n'); - t.match(meta[2], /Target file:\s+Gemfile.lock/, 'target file displayed'); - }, + '`test` returns correct meta when target file specified': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const commandResult: CommandResult = await params.cli.test('ruby-app', { + file: 'Gemfile.lock', + }); + const res = commandResult.getDisplayResults(); + const meta = res.slice(res.indexOf('Organization:')).split('\n'); + t.match( + meta[2], + /Target file:\s+Gemfile.lock/, + 'target file displayed', + ); + }, - '`test ruby-gem-no-lockfile --file=ruby-gem.gemspec`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('ruby-gem-no-lockfile', { - file: 'ruby-gem.gemspec', - }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); + '`test ruby-gem-no-lockfile --file=ruby-gem.gemspec`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('ruby-gem-no-lockfile', { + file: 'ruby-gem.gemspec', + }); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); - const depGraph = req.body.depGraph; - t.equal(depGraph.pkgManager.name, 'rubygems'); - t.same( - depGraph.pkgs.map((p) => p.id), - ['ruby-gem-no-lockfile@'], - 'no deps as we dont really support gemspecs yet', - ); - }, + const depGraph = req.body.depGraph; + t.equal(depGraph.pkgManager.name, 'rubygems'); + t.same( + depGraph.pkgs.map((p) => p.id), + ['ruby-gem-no-lockfile@'], + 'no deps as we dont really support gemspecs yet', + ); + }, '`test ruby-gem --file=ruby-gem.gemspec`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -732,31 +707,30 @@ export const RubyTests: AcceptanceTests = { t.notOk(req.body.targetFile, 'does not specify target'); }, - '`test monorepo --file=sub-ruby-app/Gemfile`': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - await params.cli.test('monorepo', { file: 'sub-ruby-app/Gemfile' }); + '`test monorepo --file=sub-ruby-app/Gemfile`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('monorepo', { file: 'sub-ruby-app/Gemfile' }); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); - const depGraph = req.body.depGraph; - t.equal(depGraph.pkgManager.name, 'rubygems'); - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['monorepo@', 'json@2.0.2', 'lynx@0.4.0'].sort(), - 'depGraph looks fine', - ); + const depGraph = req.body.depGraph; + t.equal(depGraph.pkgManager.name, 'rubygems'); + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['monorepo@', 'json@2.0.2', 'lynx@0.4.0'].sort(), + 'depGraph looks fine', + ); - t.notOk(req.body.targetFile, 'does not specify target'); - }, + t.notOk(req.body.targetFile, 'does not specify target'); + }, '`test empty --file=Gemfile`': (params, utils) => async (t) => { utils.chdirWorkspaces(); @@ -772,20 +746,18 @@ export const RubyTests: AcceptanceTests = { ); } }, - '`test large-mono-repo --file=bundler-app/Gemfile`': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const res = await params.cli.test('large-mono-repo', { - file: 'bundler-app/Gemfile', - }); - t.match( - res.getDisplayResults(), - '--all-projects', - 'Suggest using --all-projects', - ); - }, + '`test large-mono-repo --file=bundler-app/Gemfile`': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const res = await params.cli.test('large-mono-repo', { + file: 'bundler-app/Gemfile', + }); + t.match( + res.getDisplayResults(), + '--all-projects', + 'Suggest using --all-projects', + ); + }, '`test monorepo --all-projects`': (params, utils) => async (t) => { utils.chdirWorkspaces(); diff --git a/test/tap/cli-test/cli-test.sbt.spec.ts b/test/tap/cli-test/cli-test.sbt.spec.ts index 20e23734b7..be89fd3ca6 100644 --- a/test/tap/cli-test/cli-test.sbt.spec.ts +++ b/test/tap/cli-test/cli-test.sbt.spec.ts @@ -15,9 +15,9 @@ export const SbtTests: AcceptanceTests = { async inspect() { return { plugin: { name: 'sbt' }, - package: require(getWorkspacePath( - 'sbt-simple-struts/dep-tree.json', - )), + package: require( + getWorkspacePath('sbt-simple-struts/dep-tree.json'), + ), }; }, }; @@ -39,9 +39,9 @@ export const SbtTests: AcceptanceTests = { } catch (err) { const res = JSON.parse(err.message); - const expected = require(getWorkspacePath( - 'sbt-simple-struts/legacy-res-json.json', - )); + const expected = require( + getWorkspacePath('sbt-simple-struts/legacy-res-json.json'), + ); t.same( omit(res, ['vulnerabilities', 'packageManager']), diff --git a/test/tap/cli-test/cli-test.yarn-workspaces.spec.ts b/test/tap/cli-test/cli-test.yarn-workspaces.spec.ts index a98ef2abf3..bd44a4ea60 100644 --- a/test/tap/cli-test/cli-test.yarn-workspaces.spec.ts +++ b/test/tap/cli-test/cli-test.yarn-workspaces.spec.ts @@ -6,342 +6,331 @@ export const YarnWorkspacesTests: AcceptanceTests = { language: 'Yarn', tests: { // yarn lockfile based testing is only supported for node 4+ - '`test yarn-workspace-out-of-sync --yarn-workspaces` out of sync fails': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('yarn-workspace-out-of-sync', { + '`test yarn-workspace-out-of-sync --yarn-workspaces` out of sync fails': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('yarn-workspace-out-of-sync', { + dev: true, + yarnWorkspaces: true, + detectionDepth: 3, + }); + t.fail('Should fail'); + } catch (e) { + t.equal( + e.message, + '\nTesting yarn-workspace-out-of-sync...\n\n' + + 'Dependency snyk@1.320.0 was not found in yarn.lock.' + + ' Your package.json and yarn.lock are probably out of sync.' + + ' Please run "yarn install" and try again.', + 'Contains enough info about err', + ); + } + }, + '`test yarn-workspace-out-of-sync --yarn-workspaces --strict-out-of-sync=false --dev` passes': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspace-out-of-sync', { dev: true, + strictOutOfSync: false, yarnWorkspaces: true, - detectionDepth: 3, }); - t.fail('Should fail'); - } catch (e) { - t.equal( - e.message, - '\nTesting yarn-workspace-out-of-sync...\n\n' + - 'Dependency snyk@1.320.0 was not found in yarn.lock.' + - ' Your package.json and yarn.lock are probably out of sync.' + - ' Please run "yarn install" and try again.', - 'Contains enough info about err', + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', ); - } - }, - '`test yarn-workspace-out-of-sync --yarn-workspaces --strict-out-of-sync=false --dev` passes': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspace-out-of-sync', { - dev: true, - strictOutOfSync: false, - yarnWorkspaces: true, - }); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 3 projects, no vulnerable paths were found.', - 'no vulnerable paths found as both policies detected and applied.', - ); - }, - 'test --yarn-workspaces --detection-depth=5': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspaces', { - yarnWorkspaces: true, - detectionDepth: 5, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - t.match( - result.getDisplayResults(), - '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', - 'correctly showing dep number', - ); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apple-lib', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 4 projects, no vulnerable paths were found.', - 'no vulnerable paths found as both policies detected and applied.', - ); - let policyCount = 0; - const applesWorkspace = - process.platform === 'win32' - ? '\\apples\\package.json' - : 'apples/package.json'; - const tomatoesWorkspace = - process.platform === 'win32' - ? '\\tomatoes\\package.json' - : 'tomatoes/package.json'; - const rootWorkspace = - process.platform === 'win32' - ? '\\yarn-workspaces\\package.json' - : 'yarn-workspaces/package.json'; - - params.server.popRequests(4).forEach((req) => { - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 3 projects, no vulnerable paths were found.', + 'no vulnerable paths found as both policies detected and applied.', + ); + }, + 'test --yarn-workspaces --detection-depth=5': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspaces', { + yarnWorkspaces: true, + detectionDepth: 5, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + t.match( + result.getDisplayResults(), + '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', + 'correctly showing dep number', + ); + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', ); - t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); - t.ok(req.body.depGraph, 'body contains depGraph'); + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: apple-lib', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 4 projects, no vulnerable paths were found.', + 'no vulnerable paths found as both policies detected and applied.', + ); + let policyCount = 0; + const applesWorkspace = + process.platform === 'win32' + ? '\\apples\\package.json' + : 'apples/package.json'; + const tomatoesWorkspace = + process.platform === 'win32' + ? '\\tomatoes\\package.json' + : 'tomatoes/package.json'; + const rootWorkspace = + process.platform === 'win32' + ? '\\yarn-workspaces\\package.json' + : 'yarn-workspaces/package.json'; - if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20160328', - 'policy is as expected', + params.server.popRequests(4).forEach((req) => { + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } else if ( - req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) - ) { - t.notOk(req.body.policy, 'body does not contain policy'); - } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20111130', - 'policy is as expected', + t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); + t.ok(req.body.depGraph, 'body contains depGraph'); + + if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20160328', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } else if ( + req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) + ) { + t.notOk(req.body.policy, 'body does not contain policy'); + } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20111130', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } + t.equal( + req.body.depGraph.pkgManager.name, + 'yarn', + 'depGraph has package manager', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } - t.equal( - req.body.depGraph.pkgManager.name, - 'yarn', - 'depGraph has package manager', + }); + t.equal(policyCount, 2, '2 policies found in a workspace'); + }, + 'test --yarn-workspaces --detection-depth=5 --strict-out-of-sync=false (yarn v2)': + (params, utils) => async (t) => { + // Yarn workspaces for Yarn 2 is only supported on Node 10+ + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspaces-v2', { + yarnWorkspaces: true, + detectionDepth: 5, + strictOutOfSync: false, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + t.match( + result.getDisplayResults(), + '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', + 'correctly showing dep number', ); - }); - t.equal(policyCount, 2, '2 policies found in a workspace'); - }, - 'test --yarn-workspaces --detection-depth=5 --strict-out-of-sync=false (yarn v2)': ( - params, - utils, - ) => async (t) => { - // Yarn workspaces for Yarn 2 is only supported on Node 10+ - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspaces-v2', { - yarnWorkspaces: true, - detectionDepth: 5, - strictOutOfSync: false, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - t.match( - result.getDisplayResults(), - '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', - 'correctly showing dep number', - ); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 3 projects, no vulnerable paths were found.', - 'no vulnerable paths found as both policies detected and applied.', - ); - }, - 'test --yarn-workspaces --detection-depth=5 --strict-out-of-sync=false (yarn v2 with resolutions)': ( - params, - utils, - ) => async (t) => { - // Yarn workspaces for Yarn 2 is only supported on Node 10+ - utils.chdirWorkspaces(); - const result = await params.cli.test('yarn-workspaces-v2-resolutions', { - yarnWorkspaces: true, - detectionDepth: 5, - strictOutOfSync: false, - printDeps: true, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - console.log(result.getDisplayResults()); - t.match( - result.getDisplayResults(), - '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', - 'correctly showing dep number', - ); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 3 projects, no vulnerable paths were found.', - 'no vulnerable paths found as both policies detected and applied.', - ); - }, - 'test --yarn-workspaces --detection-depth=5 multiple workspaces found': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - const result = await params.cli.test({ - yarnWorkspaces: true, - detectionDepth: 5, - strictOutOfSync: false, - }); - const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); - // the parser is used directly - t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); - t.teardown(() => { - loadPlugin.restore(); - }); - t.match( - result.getDisplayResults(), - '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', - 'correctly showing dep number', - ); - t.match(result.getDisplayResults(), 'Package manager: yarn\n'); - t.match( - result.getDisplayResults(), - 'Project name: package.json', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: tomatoes', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Project name: apples', - 'yarn project in output', - ); - t.match( - result.getDisplayResults(), - 'Tested 13 projects, no vulnerable paths were found.', - 'Tested 13 projects', - ); - let policyCount = 0; - const applesWorkspace = - process.platform === 'win32' - ? '\\apples\\package.json' - : 'apples/package.json'; - const tomatoesWorkspace = - process.platform === 'win32' - ? '\\tomatoes\\package.json' - : 'tomatoes/package.json'; - const rootWorkspace = - process.platform === 'win32' - ? '\\yarn-workspaces\\package.json' - : 'yarn-workspaces/package.json'; - - params.server.popRequests(6).forEach((req) => { - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', ); - t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); - t.ok(req.body.depGraph, 'body contains depGraph'); - if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20160328', - 'policy is as expected', + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 3 projects, no vulnerable paths were found.', + 'no vulnerable paths found as both policies detected and applied.', + ); + }, + 'test --yarn-workspaces --detection-depth=5 --strict-out-of-sync=false (yarn v2 with resolutions)': + (params, utils) => async (t) => { + // Yarn workspaces for Yarn 2 is only supported on Node 10+ + utils.chdirWorkspaces(); + const result = await params.cli.test('yarn-workspaces-v2-resolutions', { + yarnWorkspaces: true, + detectionDepth: 5, + strictOutOfSync: false, + printDeps: true, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + console.log(result.getDisplayResults()); + t.match( + result.getDisplayResults(), + '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', + 'correctly showing dep number', + ); + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 3 projects, no vulnerable paths were found.', + 'no vulnerable paths found as both policies detected and applied.', + ); + }, + 'test --yarn-workspaces --detection-depth=5 multiple workspaces found': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + const result = await params.cli.test({ + yarnWorkspaces: true, + detectionDepth: 5, + strictOutOfSync: false, + }); + const loadPlugin = sinon.spy(params.plugins, 'loadPlugin'); + // the parser is used directly + t.ok(loadPlugin.withArgs('yarn').notCalled, 'skips load plugin'); + t.teardown(() => { + loadPlugin.restore(); + }); + t.match( + result.getDisplayResults(), + '✔ Tested 1 dependencies for known vulnerabilities, no vulnerable paths found.', + 'correctly showing dep number', + ); + t.match(result.getDisplayResults(), 'Package manager: yarn\n'); + t.match( + result.getDisplayResults(), + 'Project name: package.json', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: tomatoes', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Project name: apples', + 'yarn project in output', + ); + t.match( + result.getDisplayResults(), + 'Tested 13 projects, no vulnerable paths were found.', + 'Tested 13 projects', + ); + let policyCount = 0; + const applesWorkspace = + process.platform === 'win32' + ? '\\apples\\package.json' + : 'apples/package.json'; + const tomatoesWorkspace = + process.platform === 'win32' + ? '\\tomatoes\\package.json' + : 'tomatoes/package.json'; + const rootWorkspace = + process.platform === 'win32' + ? '\\yarn-workspaces\\package.json' + : 'yarn-workspaces/package.json'; + + params.server.popRequests(6).forEach((req) => { + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } else if ( - req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) - ) { - t.notOk(req.body.policy, 'body does not contain policy'); - } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { - t.match( - req.body.policy, - 'npm:node-uuid:20111130', - 'policy is as expected', + t.match(req.url, '/api/v1/test-dep-graph', 'posts to correct url'); + t.ok(req.body.depGraph, 'body contains depGraph'); + if (req.body.targetFileRelativePath.endsWith(applesWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20160328', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } else if ( + req.body.targetFileRelativePath.endsWith(tomatoesWorkspace) + ) { + t.notOk(req.body.policy, 'body does not contain policy'); + } else if (req.body.targetFileRelativePath.endsWith(rootWorkspace)) { + t.match( + req.body.policy, + 'npm:node-uuid:20111130', + 'policy is as expected', + ); + t.ok(req.body.policy, 'body contains policy'); + policyCount += 1; + } + t.equal( + req.body.depGraph.pkgManager.name, + 'yarn', + 'depGraph has package manager', ); - t.ok(req.body.policy, 'body contains policy'); - policyCount += 1; - } - t.equal( - req.body.depGraph.pkgManager.name, - 'yarn', - 'depGraph has package manager', - ); - }); - t.equal(policyCount, 2, '2 policies found in a workspace'); - }, + }); + t.equal(policyCount, 2, '2 policies found in a workspace'); + }, }, }; diff --git a/test/tap/cli-test/cli-test.yarn.spec.ts b/test/tap/cli-test/cli-test.yarn.spec.ts index c0126fcc43..19ac47360e 100644 --- a/test/tap/cli-test/cli-test.yarn.spec.ts +++ b/test/tap/cli-test/cli-test.yarn.spec.ts @@ -4,318 +4,314 @@ export const YarnTests: AcceptanceTests = { language: 'Yarn', tests: { // yarn lockfile based testing is only supported for node 4+ - '`test yarn-out-of-sync` out of sync fails': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces(); - try { - await params.cli.test('yarn-out-of-sync', { dev: true }); - t.fail('Should fail'); - } catch (e) { - t.equal( - e.message, - '\nTesting yarn-out-of-sync...\n\n' + - 'Dependency snyk@* was not found in yarn.lock.' + - ' Your package.json and yarn.lock are probably out of sync.' + - ' Please run "yarn install" and try again.', - 'Contains enough info about err', - ); - } - }, + '`test yarn-out-of-sync` out of sync fails': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + try { + await params.cli.test('yarn-out-of-sync', { dev: true }); + t.fail('Should fail'); + } catch (e) { + t.equal( + e.message, + '\nTesting yarn-out-of-sync...\n\n' + + 'Dependency snyk@* was not found in yarn.lock.' + + ' Your package.json and yarn.lock are probably out of sync.' + + ' Please run "yarn install" and try again.', + 'Contains enough info about err', + ); + } + }, - '`test yarn-out-of-sync --strict-out-of-sync=false` passes': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('yarn-out-of-sync', { - dev: true, - strictOutOfSync: false, - }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'acorn-jsx@3.0.1', - 'acorn@3.3.0', - 'acorn@5.7.3', - 'ajv-keywords@2.1.1', - 'ajv@5.5.2', - 'ansi-escapes@3.1.0', - 'ansi-regex@2.1.1', - 'ansi-regex@3.0.0', - 'ansi-styles@2.2.1', - 'ansi-styles@3.2.1', - 'argparse@1.0.10', - 'array-union@1.0.2', - 'array-uniq@1.0.3', - 'arrify@1.0.1', - 'babel-code-frame@6.26.0', - 'balanced-match@1.0.0', - 'brace-expansion@1.1.11', - 'buffer-from@1.1.1', - 'caller-path@0.1.0', - 'callsites@0.2.0', - 'chalk@1.1.3', - 'chalk@2.4.1', - 'chardet@0.4.2', - 'circular-json@0.3.3', - 'cli-cursor@2.1.0', - 'cli-width@2.2.0', - 'co@4.6.0', - 'color-convert@1.9.3', - 'color-name@1.1.3', - 'concat-map@0.0.1', - 'concat-stream@1.6.2', - 'core-util-is@1.0.2', - 'cross-spawn@5.1.0', - 'debug@3.2.5', - 'deep-is@0.1.3', - 'del@2.2.2', - 'doctrine@2.1.0', - 'escape-string-regexp@1.0.5', - 'eslint-scope@3.7.3', - 'eslint-visitor-keys@1.0.0', - 'eslint@4.19.1', - 'espree@3.5.4', - 'esprima@4.0.1', - 'esquery@1.0.1', - 'esrecurse@4.2.1', - 'estraverse@4.2.0', - 'esutils@2.0.2', - 'external-editor@2.2.0', - 'fast-deep-equal@1.1.0', - 'fast-json-stable-stringify@2.0.0', - 'fast-levenshtein@2.0.6', - 'figures@2.0.0', - 'file-entry-cache@2.0.0', - 'flat-cache@1.3.0', - 'fs.realpath@1.0.0', - 'functional-red-black-tree@1.0.1', - 'glob@7.1.3', - 'globals@11.7.0', - 'globby@5.0.0', - 'graceful-fs@4.1.11', - 'has-ansi@2.0.0', - 'has-flag@3.0.0', - 'iconv-lite@0.4.24', - 'ignore@3.3.10', - 'imurmurhash@0.1.4', - 'inflight@1.0.6', - 'inherits@2.0.3', - 'inquirer@3.3.0', - 'is-fullwidth-code-point@2.0.0', - 'is-path-cwd@1.0.0', - 'is-path-in-cwd@1.0.1', - 'is-path-inside@1.0.1', - 'is-promise@2.1.0', - 'is-resolvable@1.1.0', - 'isarray@1.0.0', - 'isexe@2.0.0', - 'js-tokens@3.0.2', - 'js-yaml@3.12.0', - 'json-schema-traverse@0.3.1', - 'json-stable-stringify-without-jsonify@1.0.1', - 'levn@0.3.0', - 'lodash@4.17.11', - 'lru-cache@4.1.3', - 'mimic-fn@1.2.0', - 'minimatch@3.0.4', - 'minimist@0.0.8', - 'mkdirp@0.5.1', - 'ms@2.1.1', - 'mute-stream@0.0.7', - 'natural-compare@1.4.0', - 'npm-package@1.0.0', - 'object-assign@4.1.1', - 'once@1.4.0', - 'onetime@2.0.1', - 'optionator@0.8.2', - 'os-tmpdir@1.0.2', - 'path-is-absolute@1.0.1', - 'path-is-inside@1.0.2', - 'pify@2.3.0', - 'pinkie-promise@2.0.1', - 'pinkie@2.0.4', - 'pluralize@7.0.0', - 'prelude-ls@1.1.2', - 'process-nextick-args@2.0.0', - 'progress@2.0.0', - 'pseudomap@1.0.2', - 'readable-stream@2.3.6', - 'regexpp@1.1.0', - 'require-uncached@1.0.3', - 'resolve-from@1.0.1', - 'restore-cursor@2.0.0', - 'rewire@4.0.1', - 'rimraf@2.6.2', - 'run-async@2.3.0', - 'rx-lite-aggregates@4.0.8', - 'rx-lite@4.0.8', - 'safe-buffer@5.1.2', - 'safer-buffer@2.1.2', - 'semver@5.5.1', - 'shebang-command@1.2.0', - 'shebang-regex@1.0.0', - 'signal-exit@3.0.2', - 'slice-ansi@1.0.0', - 'snyk@*', - 'sprintf-js@1.0.3', - 'string-width@2.1.1', - 'string_decoder@1.1.1', - 'strip-ansi@3.0.1', - 'strip-ansi@4.0.0', - 'strip-json-comments@2.0.1', - 'supports-color@2.0.0', - 'supports-color@5.5.0', - 'table@4.0.2', - 'text-table@0.2.0', - 'through@2.3.8', - 'tmp@0.0.33', - 'to-array@0.1.4', - 'type-check@0.3.2', - 'typedarray@0.0.6', - 'util-deprecate@1.0.2', - 'which@1.3.1', - 'wordwrap@1.0.0', - 'wrappy@1.0.2', - 'write@0.2.1', - 'yallist@2.1.2', - ].sort(), - 'depGraph looks fine', - ); - }, - '`test yarn-package --file=yarn-package/yarn.lock ` sends pkg info & policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test({ file: 'yarn-package/yarn.lock' }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.policy, 'npm:debug:20170905', 'policy is found & sent'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), - 'depGraph looks fine', - ); - }, - '`test yarn-package --file=yarn.lock ` sends pkg info & policy': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('yarn-package', { file: 'yarn.lock' }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.policy, 'npm:debug:20170905', 'policy is found & sent'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), - 'depGraph looks fine', - ); - }, - '`test yarn-package` sends pkg info & policy': (params, utils) => async ( - t, - ) => { - utils.chdirWorkspaces('yarn-package'); - await params.cli.test(); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.policy, 'npm:debug:20170905', 'policy is found & sent'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), - 'depGraph looks fine', - ); - }, + '`test yarn-out-of-sync --strict-out-of-sync=false` passes': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('yarn-out-of-sync', { + dev: true, + strictOutOfSync: false, + }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'acorn-jsx@3.0.1', + 'acorn@3.3.0', + 'acorn@5.7.3', + 'ajv-keywords@2.1.1', + 'ajv@5.5.2', + 'ansi-escapes@3.1.0', + 'ansi-regex@2.1.1', + 'ansi-regex@3.0.0', + 'ansi-styles@2.2.1', + 'ansi-styles@3.2.1', + 'argparse@1.0.10', + 'array-union@1.0.2', + 'array-uniq@1.0.3', + 'arrify@1.0.1', + 'babel-code-frame@6.26.0', + 'balanced-match@1.0.0', + 'brace-expansion@1.1.11', + 'buffer-from@1.1.1', + 'caller-path@0.1.0', + 'callsites@0.2.0', + 'chalk@1.1.3', + 'chalk@2.4.1', + 'chardet@0.4.2', + 'circular-json@0.3.3', + 'cli-cursor@2.1.0', + 'cli-width@2.2.0', + 'co@4.6.0', + 'color-convert@1.9.3', + 'color-name@1.1.3', + 'concat-map@0.0.1', + 'concat-stream@1.6.2', + 'core-util-is@1.0.2', + 'cross-spawn@5.1.0', + 'debug@3.2.5', + 'deep-is@0.1.3', + 'del@2.2.2', + 'doctrine@2.1.0', + 'escape-string-regexp@1.0.5', + 'eslint-scope@3.7.3', + 'eslint-visitor-keys@1.0.0', + 'eslint@4.19.1', + 'espree@3.5.4', + 'esprima@4.0.1', + 'esquery@1.0.1', + 'esrecurse@4.2.1', + 'estraverse@4.2.0', + 'esutils@2.0.2', + 'external-editor@2.2.0', + 'fast-deep-equal@1.1.0', + 'fast-json-stable-stringify@2.0.0', + 'fast-levenshtein@2.0.6', + 'figures@2.0.0', + 'file-entry-cache@2.0.0', + 'flat-cache@1.3.0', + 'fs.realpath@1.0.0', + 'functional-red-black-tree@1.0.1', + 'glob@7.1.3', + 'globals@11.7.0', + 'globby@5.0.0', + 'graceful-fs@4.1.11', + 'has-ansi@2.0.0', + 'has-flag@3.0.0', + 'iconv-lite@0.4.24', + 'ignore@3.3.10', + 'imurmurhash@0.1.4', + 'inflight@1.0.6', + 'inherits@2.0.3', + 'inquirer@3.3.0', + 'is-fullwidth-code-point@2.0.0', + 'is-path-cwd@1.0.0', + 'is-path-in-cwd@1.0.1', + 'is-path-inside@1.0.1', + 'is-promise@2.1.0', + 'is-resolvable@1.1.0', + 'isarray@1.0.0', + 'isexe@2.0.0', + 'js-tokens@3.0.2', + 'js-yaml@3.12.0', + 'json-schema-traverse@0.3.1', + 'json-stable-stringify-without-jsonify@1.0.1', + 'levn@0.3.0', + 'lodash@4.17.11', + 'lru-cache@4.1.3', + 'mimic-fn@1.2.0', + 'minimatch@3.0.4', + 'minimist@0.0.8', + 'mkdirp@0.5.1', + 'ms@2.1.1', + 'mute-stream@0.0.7', + 'natural-compare@1.4.0', + 'npm-package@1.0.0', + 'object-assign@4.1.1', + 'once@1.4.0', + 'onetime@2.0.1', + 'optionator@0.8.2', + 'os-tmpdir@1.0.2', + 'path-is-absolute@1.0.1', + 'path-is-inside@1.0.2', + 'pify@2.3.0', + 'pinkie-promise@2.0.1', + 'pinkie@2.0.4', + 'pluralize@7.0.0', + 'prelude-ls@1.1.2', + 'process-nextick-args@2.0.0', + 'progress@2.0.0', + 'pseudomap@1.0.2', + 'readable-stream@2.3.6', + 'regexpp@1.1.0', + 'require-uncached@1.0.3', + 'resolve-from@1.0.1', + 'restore-cursor@2.0.0', + 'rewire@4.0.1', + 'rimraf@2.6.2', + 'run-async@2.3.0', + 'rx-lite-aggregates@4.0.8', + 'rx-lite@4.0.8', + 'safe-buffer@5.1.2', + 'safer-buffer@2.1.2', + 'semver@5.5.1', + 'shebang-command@1.2.0', + 'shebang-regex@1.0.0', + 'signal-exit@3.0.2', + 'slice-ansi@1.0.0', + 'snyk@*', + 'sprintf-js@1.0.3', + 'string-width@2.1.1', + 'string_decoder@1.1.1', + 'strip-ansi@3.0.1', + 'strip-ansi@4.0.0', + 'strip-json-comments@2.0.1', + 'supports-color@2.0.0', + 'supports-color@5.5.0', + 'table@4.0.2', + 'text-table@0.2.0', + 'through@2.3.8', + 'tmp@0.0.33', + 'to-array@0.1.4', + 'type-check@0.3.2', + 'typedarray@0.0.6', + 'util-deprecate@1.0.2', + 'which@1.3.1', + 'wordwrap@1.0.0', + 'wrappy@1.0.2', + 'write@0.2.1', + 'yallist@2.1.2', + ].sort(), + 'depGraph looks fine', + ); + }, + '`test yarn-package --file=yarn-package/yarn.lock ` sends pkg info & policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test({ file: 'yarn-package/yarn.lock' }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match( + req.body.policy, + 'npm:debug:20170905', + 'policy is found & sent', + ); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), + 'depGraph looks fine', + ); + }, + '`test yarn-package --file=yarn.lock ` sends pkg info & policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('yarn-package', { file: 'yarn.lock' }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match( + req.body.policy, + 'npm:debug:20170905', + 'policy is found & sent', + ); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), + 'depGraph looks fine', + ); + }, + '`test yarn-package` sends pkg info & policy': + (params, utils) => async (t) => { + utils.chdirWorkspaces('yarn-package'); + await params.cli.test(); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match( + req.body.policy, + 'npm:debug:20170905', + 'policy is found & sent', + ); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['npm-package@1.0.0', 'ms@0.7.1', 'debug@2.2.0'].sort(), + 'depGraph looks fine', + ); + }, - '`test yarn-package --file=yarn.lock --dev` sends pkg info': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('yarn-package', { file: 'yarn.lock', dev: true }); - const req = params.server.popRequest(); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - [ - 'npm-package@1.0.0', - 'ms@0.7.1', - 'debug@2.2.0', - 'object-assign@4.1.1', - ].sort(), - 'depGraph looks fine', - ); - }, + '`test yarn-package --file=yarn.lock --dev` sends pkg info': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('yarn-package', { file: 'yarn.lock', dev: true }); + const req = params.server.popRequest(); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + [ + 'npm-package@1.0.0', + 'ms@0.7.1', + 'debug@2.2.0', + 'object-assign@4.1.1', + ].sort(), + 'depGraph looks fine', + ); + }, - '`test yarn-package-with-subfolder --file=yarn.lock ` picks top-level files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('yarn-package-with-subfolder', { - file: 'yarn.lock', - }); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['yarn-package-top-level@1.0.0', 'to-array@0.1.4'].sort(), - 'depGraph looks fine', - ); - }, + '`test yarn-package-with-subfolder --file=yarn.lock ` picks top-level files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('yarn-package-with-subfolder', { + file: 'yarn.lock', + }); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['yarn-package-top-level@1.0.0', 'to-array@0.1.4'].sort(), + 'depGraph looks fine', + ); + }, - '`test yarn-package-with-subfolder --file=subfolder/yarn.lock` picks subfolder files': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces(); - await params.cli.test('yarn-package-with-subfolder', { - file: 'subfolder/yarn.lock', - }); - const req = params.server.popRequest(); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['yarn-package-subfolder@1.0.0', 'to-array@0.1.4'].sort(), - 'depGraph looks fine', - ); - }, + '`test yarn-package-with-subfolder --file=subfolder/yarn.lock` picks subfolder files': + (params, utils) => async (t) => { + utils.chdirWorkspaces(); + await params.cli.test('yarn-package-with-subfolder', { + file: 'subfolder/yarn.lock', + }); + const req = params.server.popRequest(); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['yarn-package-subfolder@1.0.0', 'to-array@0.1.4'].sort(), + 'depGraph looks fine', + ); + }, - '`test` on a yarn package does work and displays appropriate text': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces('yarn-app'); - await params.cli.test(); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['yarn-app-one@1.0.0', 'marked@0.3.6', 'moment@2.18.1'].sort(), - 'depGraph looks fine', - ); - }, + '`test` on a yarn package does work and displays appropriate text': + (params, utils) => async (t) => { + utils.chdirWorkspaces('yarn-app'); + await params.cli.test(); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['yarn-app-one@1.0.0', 'marked@0.3.6', 'moment@2.18.1'].sort(), + 'depGraph looks fine', + ); + }, '`test` on a yarn v2 package': (params, utils) => async (t) => { utils.chdirWorkspaces('yarn-v2'); await params.cli.test(); @@ -336,27 +332,25 @@ export const YarnTests: AcceptanceTests = { ); }, - '`test` on a yarn lock v2 package - uses yarn v3': ( - params, - utils, - ) => async (t) => { - utils.chdirWorkspaces('yarn-lock-v2-vuln'); - await params.cli.test(); - const req = params.server.popRequest(); - t.equal(req.method, 'POST', 'makes POST request'); - t.equal( - req.headers['x-snyk-cli-version'], - params.versionNumber, - 'sends version number', - ); - t.match(req.url, '/test-dep-graph', 'posts to correct url'); - t.match(req.body.targetFile, undefined, 'target is undefined'); - const depGraph = req.body.depGraph; - t.same( - depGraph.pkgs.map((p) => p.id).sort(), - ['yarn-3-vuln@1.0.0', 'lodash@4.17.0'].sort(), - 'depGraph looks fine', - ); - }, + '`test` on a yarn lock v2 package - uses yarn v3': + (params, utils) => async (t) => { + utils.chdirWorkspaces('yarn-lock-v2-vuln'); + await params.cli.test(); + const req = params.server.popRequest(); + t.equal(req.method, 'POST', 'makes POST request'); + t.equal( + req.headers['x-snyk-cli-version'], + params.versionNumber, + 'sends version number', + ); + t.match(req.url, '/test-dep-graph', 'posts to correct url'); + t.match(req.body.targetFile, undefined, 'target is undefined'); + const depGraph = req.body.depGraph; + t.same( + depGraph.pkgs.map((p) => p.id).sort(), + ['yarn-3-vuln@1.0.0', 'lodash@4.17.0'].sort(), + 'depGraph looks fine', + ); + }, }, }; diff --git a/test/tap/cli-test/sarif-schema-2.1.0.js b/test/tap/cli-test/sarif-schema-2.1.0.js index 071247cd17..9173284ef6 100644 --- a/test/tap/cli-test/sarif-schema-2.1.0.js +++ b/test/tap/cli-test/sarif-schema-2.1.0.js @@ -2,8 +2,7 @@ module.exports = { $schema: 'http://json-schema.org/draft-07/schema#', title: 'Static Analysis Results Format (SARIF) Version 2.1.0 JSON Schema', - $id: - 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json', + $id: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json', description: 'Static Analysis Results Format (SARIF) Version 2.1.0 JSON Schema: a standard format for the output of static analysis tools.', additionalProperties: false, diff --git a/test/tap/container.test.ts b/test/tap/container.test.ts index 20b93423c3..de8ca10ad9 100644 --- a/test/tap/container.test.ts +++ b/test/tap/container.test.ts @@ -59,13 +59,15 @@ const stubMeta: MonitorMeta = { test('isContainer returns false if image name is undefined', (t) => { t.plan(1); - const scannedProject: ScannedProject = stubScannedProjectContainerWithNoImageName(); + const scannedProject: ScannedProject = + stubScannedProjectContainerWithNoImageName(); t.notOk(container.isContainer(scannedProject)); }); test('isContainer returns false if image name is empty', (t) => { t.plan(1); - const scannedProject: ScannedProject = stubScannedProjectContainerWithEmptyImageName(); + const scannedProject: ScannedProject = + stubScannedProjectContainerWithEmptyImageName(); t.notOk(container.isContainer(scannedProject)); }); diff --git a/test/tap/proxy.test.js b/test/tap/proxy.test.js index e133444c53..ddf060f42a 100644 --- a/test/tap/proxy.test.js +++ b/test/tap/proxy.test.js @@ -31,7 +31,7 @@ test('request respects proxy environment variables', async (t) => { }); process.env.http_proxy = `http://localhost:${proxyPort}`; - const proxy = http.createServer(function(req, res) { + const proxy = http.createServer(function (req, res) { t.equal(req.url, httpRequestHost + requestPath, 'http_proxy url ok'); res.end(); }); @@ -58,7 +58,7 @@ test('request respects proxy environment variables', async (t) => { }); process.env.HTTP_PROXY = `http://localhost:${proxyPort}`; - const proxy = http.createServer(function(req, res) { + const proxy = http.createServer(function (req, res) { t.equal(req.url, httpRequestHost + requestPath, 'HTTP_PROXY url ok'); res.end(); }); @@ -107,7 +107,7 @@ test('request respects proxy environment variables', async (t) => { 'Proxy-agent: Node.js-Proxy\r\n' + 'Connection: close\r\n' + '\r\n', - function() { + function () { cltSocket.end(); }, ); @@ -159,7 +159,7 @@ test('request respects proxy environment variables', async (t) => { 'Proxy-agent: Node.js-Proxy\r\n' + 'Connection: close\r\n' + '\r\n', - function() { + function () { cltSocket.end(); }, ); diff --git a/test/tap/remote-package.test.ts b/test/tap/remote-package.test.ts index 23650e6b3b..54dbcd2659 100644 --- a/test/tap/remote-package.test.ts +++ b/test/tap/remote-package.test.ts @@ -79,10 +79,7 @@ test('multiple test arguments', async (t) => { try { const commandResult: CommandResult = await cli.test('semver@4', 'qs@6'); const res = commandResult.getDisplayResults(); - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.equal( lastLine, 'Tested 2 projects, no vulnerable paths were found.', @@ -97,10 +94,7 @@ test('multiple test arguments', async (t) => { t.fail(res); } catch (error) { const res = error.message; - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.equal( lastLine, 'Tested 2 projects, 1 contained vulnerable paths.', @@ -113,10 +107,7 @@ test('multiple test arguments', async (t) => { t.fail(res); } catch (error) { const res = error.message; - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.equal( lastLine, 'Tested 2 projects, 1 contained vulnerable paths.', @@ -129,10 +120,7 @@ test('multiple test arguments', async (t) => { t.fail(res); } catch (error) { const res = error.message; - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.equal( lastLine, 'Tested 2 projects, 2 contained vulnerable paths.', @@ -147,10 +135,7 @@ test('test for existing remote package with dev-deps only with --dev', async (t) dev: true, }); const res = commandResult.getDisplayResults(); - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.same( lastLine, '✔ Tested lodash@4.17.11 for known vulnerabilities, no vulnerable paths found.', @@ -171,10 +156,7 @@ test('test for existing remote package with dev-deps only', async (t) => { dev: false, }); const res = commandResult.getDisplayResults(); - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.same( lastLine, @@ -193,10 +175,7 @@ test('test for non-existing', async (t) => { t.fail('should fail, instead received ' + res); } catch (error) { const res = error.message; - const lastLine = res - .trim() - .split('\n') - .pop(); + const lastLine = res.trim().split('\n').pop(); t.same( lastLine, 'Internal server error', diff --git a/test/tap/run-test.test.ts b/test/tap/run-test.test.ts index 83f52e705e..5ab808ca80 100644 --- a/test/tap/run-test.test.ts +++ b/test/tap/run-test.test.ts @@ -40,9 +40,9 @@ before('setup', async (t) => { }); test('runTest annotates results with remediation data when using node_modules', async (t) => { - const vulns = require(getFixturePath( - 'npm-package-with-git-url/test-graph-result.json', - )); + const vulns = require( + getFixturePath('npm-package-with-git-url/test-graph-result.json'), + ); server.setNextResponse(vulns); const result = await runTest( diff --git a/test/tap/sub-process.test.js b/test/tap/sub-process.test.js index 7775d8b9f8..e521c4a788 100644 --- a/test/tap/sub-process.test.js +++ b/test/tap/sub-process.test.js @@ -43,56 +43,56 @@ function isSupported() { } } -test('sub-process.execute executes sub processes', function(t) { +test('sub-process.execute executes sub processes', function (t) { if (isSupported()) { - t.test('runs in shell', function(t) { + t.test('runs in shell', function (t) { t.plan(1); subProcess .execute('echo', [shellVar]) - .then(function(result) { + .then(function (result) { t.not(result.trim(), shellVar, 'evaluates shell variable'); }) .catch(t.fail); }); } - t.test('successful execution', function(t) { + t.test('successful execution', function (t) { t.plan(2); subProcess .execute(script('stdout-echo'), ['hello world']) - .then(function(result) { + .then(function (result) { t.match(result, 'hello world', 'should resolve with stdout'); }) .catch(t.fail); subProcess .execute(script('stderr-echo'), ['hello error']) - .then(function(result) { + .then(function (result) { t.match(result, 'hello error', 'should resolve with stderr'); }) .catch(t.fail); }); - t.test('error during execution', function(t) { + t.test('error during execution', function (t) { t.plan(2); subProcess .execute(script('stdout-echo-fail'), ['hello world']) - .then(function() { + .then(function () { t.fail('should not have resolved'); }) - .catch(function(err) { + .catch(function (err) { t.match(err, 'hello world', 'should reject with standard output'); }); subProcess .execute(script('stderr-echo-fail'), ['hello error']) - .then(function() { + .then(function () { t.fail('should not have resolved'); }) - .catch(function(err) { + .catch(function (err) { t.match( err, 'hello error', @@ -101,14 +101,14 @@ test('sub-process.execute executes sub processes', function(t) { }); }); - t.test('options', function(t) { - t.test('options.cwd', function(t) { + t.test('options', function (t) { + t.test('options.cwd', function (t) { t.plan(2); const explicitWorkDir = path.resolve(path.join(__dirname, 'support')); subProcess .execute(script('pwd'), [], { cwd: explicitWorkDir }) - .then(function(result) { + .then(function (result) { t.match(result, explicitWorkDir, 'specifies the working directory'); }) .catch(t.fail); @@ -116,7 +116,7 @@ test('sub-process.execute executes sub processes', function(t) { const currentWorkDir = process.cwd(); subProcess .execute(script('pwd'), []) - .then(function(result) { + .then(function (result) { t.match( result, currentWorkDir, diff --git a/test/tap/user-config.test.ts b/test/tap/user-config.test.ts index a12d1f0053..2dd2b02b8f 100644 --- a/test/tap/user-config.test.ts +++ b/test/tap/user-config.test.ts @@ -9,26 +9,26 @@ test('can unset config values', async (t) => { config('foo' as any).catch(t.pass); await config() - .then(function(v) { + .then(function (v) { before = v; return config('set', 'foo=10'); }) - .then(function(v) { + .then(function (v) { t.pass('value set ' + v); return config('get', 'foo'); }) - .then(function(value) { + .then(function (value) { t.equal(value, '10', 'got value from config'); return config('unset', 'foo'); }) - .then(function() { + .then(function () { return config(); }) - .then(function(all) { + .then(function (all) { t.equal(before, all, 'final config matches'); config('unset', 'bar'); }) - .catch(function(e) { + .catch(function (e) { t.fail(e); }); }); @@ -41,26 +41,26 @@ test('can set config values with = inside', async (t) => { config('foo' as any).catch(t.pass); await config() - .then(function(v) { + .then(function (v) { before = v; return config('set', 'foo=10='); }) - .then(function(v) { + .then(function (v) { t.pass('value set ' + v); return config('get', 'foo'); }) - .then(function(value) { + .then(function (value) { t.equal(value, '10=', 'got value from config'); return config('unset', 'foo'); }) - .then(function() { + .then(function () { return config(); }) - .then(function(all) { + .then(function (all) { t.equal(before, all, 'final config matches'); config('unset', 'bar'); }) - .catch(function(e) { + .catch(function (e) { t.fail(e); }); }); diff --git a/test/tap/vulnerable-path-output.js b/test/tap/vulnerable-path-output.js index 85da036ee2..6389389f37 100644 --- a/test/tap/vulnerable-path-output.js +++ b/test/tap/vulnerable-path-output.js @@ -7,32 +7,32 @@ const cli = require('../cli/commands'); const snyk = require('..'); const { getFixturePath } = require('../jest/util/getFixturePath'); -sinon.stub(snyk, 'test', function() { +sinon.stub(snyk, 'test', function () { return require(getFixturePath('more-vuln-paths-than-vulns')); }); -tap.tearDown(function() { +tap.tearDown(function () { snyk.test.restore(); }); -test('"snyk test --show-vulnerable-paths=false"', function(t) { +test('"snyk test --show-vulnerable-paths=false"', function (t) { const options = { 'show-vulnerable-paths': 'false' }; return cli .test('more-vuln-paths-than-vulns', options) - .then(function() { + .then(function () { t.fail('Should have found vulns!'); }) - .catch(function(res) { + .catch(function (res) { const vulnUrls = res.message .match(/^- info: (.*)$/gm) - .map(function(result) { + .map(function (result) { return result.replace(/^- info:\s*/, ''); }); t.assert( _(vulnUrls) .countBy() // count the occurrances of each vulnUrl .values() - .every(function(occurances) { + .every(function (occurances) { return occurances === 1; }), 'displays each vuln only once', @@ -49,23 +49,23 @@ test('"snyk test --show-vulnerable-paths=false"', function(t) { }); }); -test('"snyk test"', function(t) { +test('"snyk test"', function (t) { return cli .test('more-vuln-paths-than-vulns') - .then(function() { + .then(function () { t.fail('Should have found vulns!'); }) - .catch(function(res) { + .catch(function (res) { const vulnUrls = res.message .match(/^- info: (.*)$/gm) - .map(function(result) { + .map(function (result) { return result.replace(/^- info:\s*/, ''); }); t.assert( _(vulnUrls) .countBy() // count the occurrances of each vulnUrl .values() - .some(function(occurances) { + .some(function (occurances) { return occurances > 1; }), 'duplicates vuln data for each vulnerable-path', diff --git a/ts-binary-wrapper/src/common.ts b/ts-binary-wrapper/src/common.ts index 793e487f30..91fe853142 100644 --- a/ts-binary-wrapper/src/common.ts +++ b/ts-binary-wrapper/src/common.ts @@ -72,10 +72,7 @@ export function determineBinaryName(platform: string, arch: string): string { let isAlpine = false; try { const result = spawnSync('cat /etc/os-release', { shell: true }); - isAlpine = result.stdout - .toString() - .toLowerCase() - .includes('id=alpine'); + isAlpine = result.stdout.toString().toLowerCase().includes('id=alpine'); } catch { isAlpine = false; } @@ -241,7 +238,7 @@ export function downloadExecutable( filename: string, filenameShasum: string, ): Promise { - return new Promise(function(resolve) { + return new Promise(function (resolve) { const options = new URL(downloadUrl); const temp = path.join(__dirname, Date.now().toString()); const fileStream = fs.createWriteStream(temp); @@ -331,8 +328,7 @@ export async function logError( // init error reporting const version = getCurrentVersion(versionFile); Sentry.init({ - dsn: - 'https://3e845233db8c4f43b4c4b9245f1d7bd6@o30291.ingest.sentry.io/4504599528079360', + dsn: 'https://3e845233db8c4f43b4c4b9245f1d7bd6@o30291.ingest.sentry.io/4504599528079360', release: version, }); diff --git a/ts-binary-wrapper/test/acceptance/basic.spec.ts b/ts-binary-wrapper/test/acceptance/basic.spec.ts index b55858bc4f..4e3d915ac6 100644 --- a/ts-binary-wrapper/test/acceptance/basic.spec.ts +++ b/ts-binary-wrapper/test/acceptance/basic.spec.ts @@ -105,12 +105,9 @@ describe('Basic acceptance test', () => { expect(resultIndex.status).toEqual(0); // The binary wrapper should not output anything to stdout // Assert the only stdout is from the CLI --version flag - expect( - resultIndex.stdout - .toString() - .split(' ')[0] - .trim(), - ).toEqual(cliVersionForTesting); + expect(resultIndex.stdout.toString().split(' ')[0].trim()).toEqual( + cliVersionForTesting, + ); fs.unlinkSync(executable); }); diff --git a/ts-binary-wrapper/test/util/prepareEnvironment.ts b/ts-binary-wrapper/test/util/prepareEnvironment.ts index cd624529fa..55bc4fe3ca 100644 --- a/ts-binary-wrapper/test/util/prepareEnvironment.ts +++ b/ts-binary-wrapper/test/util/prepareEnvironment.ts @@ -77,7 +77,7 @@ export class TestEnvironmentSetup { } if (process.argv.includes('exec')) { - (async function() { + (async function () { const env = new TestEnvironmentSetup(); await env.prepareEnvironment('1.1080.0'); });