snyk
Version:
snyk library and cli utility
1,361 lines (1,210 loc) • 107 kB
JavaScript
"use strict";
exports.id = 741;
exports.ids = [741];
exports.modules = {
/***/ 80423:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertLegacyTestResultToNew = void 0;
function convertVulnerabilities(vulns) {
const issuesData = {};
const issues = [];
vulns.forEach((vuln) => {
issuesData[vuln.id] = {
id: vuln.id,
severity: vuln.severity,
title: vuln.title,
};
issues.push({
pkgName: vuln.packageName,
pkgVersion: vuln.version,
issueId: vuln.id,
// TODO: add fixInfo when needed
fixInfo: {},
});
});
return { issuesData, issues };
}
function convertLegacyTestResultToNew(testResult) {
const { issues, issuesData } = convertVulnerabilities(testResult.vulnerabilities);
return {
issuesData,
issues,
remediation: testResult.remediation,
// TODO: grab this once Ecosystems flow starts sending back ScanResult
depGraphData: {},
};
}
exports.convertLegacyTestResultToNew = convertLegacyTestResultToNew;
/***/ }),
/***/ 16898:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertLegacyTestResultToScanResult = void 0;
function convertLegacyTestResultToScanResult(testResult) {
if (!testResult.packageManager) {
throw new Error('Only results with packageManagers are supported for conversion');
}
return {
identity: {
type: testResult.packageManager,
// this is because not all plugins send it back today, but we should always have it
targetFile: testResult.targetFile || testResult.displayTargetFile,
},
name: testResult.projectName,
// TODO: grab this once Ecosystems flow starts sending back ScanResult
facts: [],
policy: testResult.policy,
// TODO: grab this once Ecosystems flow starts sending back ScanResult
target: {},
};
}
exports.convertLegacyTestResultToScanResult = convertLegacyTestResultToScanResult;
/***/ }),
/***/ 92730:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertLegacyTestResultToFixEntities = void 0;
const fs = __webpack_require__(57147);
const pathLib = __webpack_require__(71017);
const convert_legacy_test_result_to_new_1 = __webpack_require__(80423);
const convert_legacy_test_result_to_scan_result_1 = __webpack_require__(16898);
function convertLegacyTestResultToFixEntities(testResults, root, options) {
if (testResults instanceof Error) {
return [];
}
const oldResults = Array.isArray(testResults) ? testResults : [testResults];
return oldResults.map((res) => ({
options,
workspace: {
path: root,
readFile: async (path) => {
return fs.readFileSync(pathLib.resolve(root, path), 'utf8');
},
writeFile: async (path, content) => {
return fs.writeFileSync(pathLib.resolve(root, path), content, 'utf8');
},
},
scanResult: (0, convert_legacy_test_result_to_scan_result_1.convertLegacyTestResultToScanResult)(res),
testResult: (0, convert_legacy_test_result_to_new_1.convertLegacyTestResultToNew)(res),
}));
}
exports.convertLegacyTestResultToFixEntities = convertLegacyTestResultToFixEntities;
/***/ }),
/***/ 79898:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getDisplayPath = void 0;
const pathLib = __webpack_require__(71017);
const detect_1 = __webpack_require__(45318);
function getDisplayPath(path) {
if (!(0, detect_1.isLocalFolder)(path)) {
return path;
}
if (path === process.cwd()) {
return pathLib.parse(path).name;
}
return pathLib.relative(process.cwd(), path);
}
exports.getDisplayPath = getDisplayPath;
/***/ }),
/***/ 73741:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
const Debug = __webpack_require__(15158);
const snykFix = __webpack_require__(53776);
const ora = __webpack_require__(63395);
const snyk = __webpack_require__(9146);
const analytics = __webpack_require__(82744);
const convert_legacy_tests_results_to_fix_entities_1 = __webpack_require__(92730);
const format_test_error_1 = __webpack_require__(68214);
const process_command_args_1 = __webpack_require__(52369);
const validate_credentials_1 = __webpack_require__(4593);
const validate_test_options_1 = __webpack_require__(83476);
const set_default_test_options_1 = __webpack_require__(13285);
const validate_fix_command_is_supported_1 = __webpack_require__(16117);
const get_display_path_1 = __webpack_require__(79898);
const chalk_1 = __webpack_require__(32589);
const theme_1 = __webpack_require__(86988);
const check_paths_1 = __webpack_require__(94501);
const debug = Debug('snyk-fix');
const snykFixFeatureFlag = 'cliSnykFix';
async function fix(...args) {
const { options: rawOptions, paths } = await (0, process_command_args_1.processCommandArgs)(...args);
const options = (0, set_default_test_options_1.setDefaultTestOptions)(rawOptions);
debug(options);
await (0, validate_fix_command_is_supported_1.validateFixCommandIsSupported)(options);
if (!options.docker) {
(0, check_paths_1.checkOSSPaths)(paths, rawOptions);
}
(0, validate_test_options_1.validateTestOptions)(options);
(0, validate_credentials_1.validateCredentials)(options);
const results = [];
results.push(...(await runSnykTestLegacy(options, paths)));
// fix
debug(`Organization has ${snykFixFeatureFlag} feature flag enabled for experimental Snyk fix functionality`);
const vulnerableResults = results.filter((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,
});
setSnykFixAnalytics(fixSummary, meta, results, resultsByPlugin, vulnerableResults);
// `snyk test` did not return any test results
if (results.length === 0) {
throw new Error(fixSummary);
}
// `snyk test` returned no vulnerable results, so nothing to fix
if (vulnerableResults.length === 0) {
return fixSummary;
}
// `snyk test` returned vulnerable results
// however some errors occurred during `snyk fix` and nothing was fixed in the end
const anyFailed = meta.failed > 0;
const noneFixed = meta.fixed === 0;
if (anyFailed && noneFixed) {
throw new Error(fixSummary);
}
return fixSummary;
}
exports["default"] = fix;
/* @deprecated
* TODO: once project envelope is default all code below will be deleted
* we should be calling test via new Ecosystems instead
*/
async function runSnykTestLegacy(options, paths) {
const results = [];
const stdOutSpinner = ora({
isSilent: options.quiet,
stream: process.stdout,
});
const stdErrSpinner = ora({
isSilent: options.quiet,
stream: process.stdout,
});
stdErrSpinner.start();
stdOutSpinner.start();
for (const path of paths) {
let displayPath = path;
const spinnerMessage = `Running \`snyk test\` for ${displayPath}`;
try {
displayPath = (0, get_display_path_1.getDisplayPath)(path);
stdOutSpinner.text = spinnerMessage;
stdOutSpinner.render();
// Create a copy of the options so a specific test can
// modify them i.e. add `options.file` etc. We'll need
// these options later.
const snykTestOptions = {
...options,
path,
projectName: options['project-name'],
};
const testResults = [];
const testResultForPath = await snyk.test(path, { ...snykTestOptions, quiet: true });
testResults.push(...(Array.isArray(testResultForPath)
? testResultForPath
: [testResultForPath]));
const newRes = (0, convert_legacy_tests_results_to_fix_entities_1.convertLegacyTestResultToFixEntities)(testResults, path, options);
results.push(...newRes);
stdOutSpinner.stopAndPersist({
text: spinnerMessage,
symbol: `\n${theme_1.icon.RUN}`,
});
}
catch (error) {
const testError = (0, format_test_error_1.formatTestError)(error);
const userMessage = theme_1.color.status.error(`Failed! ${testError.message}.`) +
`\n Tip: run \`snyk test ${displayPath} -d\` for more information.`;
stdOutSpinner.stopAndPersist({
text: spinnerMessage,
symbol: `\n${theme_1.icon.RUN}`,
});
stdErrSpinner.stopAndPersist({
text: userMessage,
symbol: chalk_1.default.red(' '),
});
debug(userMessage);
}
}
stdOutSpinner.stop();
stdErrSpinner.stop();
return results;
}
function setSnykFixAnalytics(fixSummary, meta, snykTestResponses, resultsByPlugin, vulnerableResults) {
// Analytics # of projects
analytics.add('snykFixFailedProjects', meta.failed);
analytics.add('snykFixFixedProjects', meta.fixed);
analytics.add('snykFixTotalProjects', snykTestResponses.length);
analytics.add('snykFixVulnerableProjects', vulnerableResults.length);
// Analytics # of issues
analytics.add('snykFixFixableIssues', meta.fixableIssues);
analytics.add('snykFixFixedIssues', meta.fixedIssues);
analytics.add('snykFixTotalIssues', meta.totalIssues);
analytics.add('snykFixSummary', fixSummary);
// Analytics for errors
for (const plugin of Object.keys(resultsByPlugin)) {
const errors = [];
const failedToFix = resultsByPlugin[plugin].failed;
for (const failed of failedToFix) {
if ('error' in failed) {
errors.push(failed.error.message);
}
if ('changes' in failed) {
errors.push(...failed.changes.map((f) => JSON.stringify(f)));
}
}
analytics.add('snykFixErrors', { [plugin]: errors });
}
}
/***/ }),
/***/ 16117:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateFixCommandIsSupported = void 0;
const Debug = __webpack_require__(15158);
const ecosystems_1 = __webpack_require__(5168);
const feature_flags_1 = __webpack_require__(63011);
const not_supported_by_ecosystem_1 = __webpack_require__(72571);
const errors_1 = __webpack_require__(55191);
const chalk_1 = __webpack_require__(32589);
const debug = Debug('snyk-fix');
const snykFixFeatureFlag = 'cliSnykFix';
async function validateFixCommandIsSupported(options) {
if (options.docker) {
throw new not_supported_by_ecosystem_1.FeatureNotSupportedByEcosystemError('snyk fix', 'docker');
}
const ecosystem = (0, ecosystems_1.getEcosystemForTest)(options);
if (ecosystem) {
throw new not_supported_by_ecosystem_1.FeatureNotSupportedByEcosystemError('snyk fix', ecosystem);
}
const snykFixSupported = await (0, feature_flags_1.isFeatureFlagSupportedForOrg)(snykFixFeatureFlag, options.org);
debug('Feature flag check returned: ', snykFixSupported);
if (snykFixSupported.code === 401 || snykFixSupported.code === 403) {
throw (0, errors_1.AuthFailedError)(snykFixSupported.error, snykFixSupported.code);
}
if (!snykFixSupported.ok) {
const snykFixErrorMessage = chalk_1.default.red(`\`snyk fix\` is not supported${options.org ? ` for org '${options.org}'` : ''}.`) +
'\nSee documentation on how to enable this beta feature: https://docs.snyk.io/snyk-cli/fix-vulnerabilities-from-the-cli/automatic-remediation-with-snyk-fix#enabling-snyk-fix';
const unsupportedError = new Error(snykFixErrorMessage);
throw unsupportedError;
}
return true;
}
exports.validateFixCommandIsSupported = validateFixCommandIsSupported;
/***/ }),
/***/ 68214:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatTestError = void 0;
function formatTestError(error) {
// Possible error cases:
// - the test found some vulns. `error.message` is a
// JSON-stringified
// test result.
// - the flow failed, `error` is a real Error object.
// - the flow failed, `error` is a number or string
// describing the problem.
//
// To standardise this, make sure we use the best _object_ to
// describe the error.
let errorResponse;
if (error instanceof Error) {
errorResponse = error;
}
else if (typeof error !== 'object') {
errorResponse = new Error(error);
}
else {
try {
errorResponse = JSON.parse(error.message);
}
catch (unused) {
errorResponse = error;
}
}
return errorResponse;
}
exports.formatTestError = formatTestError;
/***/ }),
/***/ 13285:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setDefaultTestOptions = void 0;
const config_1 = __webpack_require__(25425);
function setDefaultTestOptions(options) {
const svpSupplied = (options['show-vulnerable-paths'] || '')
.toString()
.toLowerCase();
delete options['show-vulnerable-paths'];
const showVulnPaths = showVulnPathsMapping[svpSupplied] || 'some';
const maxVulnPaths = options['max-vulnerable-paths'];
return {
...options,
// org fallback to config unless specified
org: options.org || config_1.default.org,
// making `show-vulnerable-paths` 'some' by default.
showVulnPaths,
maxVulnPaths,
};
}
exports.setDefaultTestOptions = setDefaultTestOptions;
const showVulnPathsMapping = {
false: 'none',
none: 'none',
true: 'some',
some: 'some',
all: 'all',
};
/***/ }),
/***/ 4593:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateCredentials = void 0;
const api_token_1 = __webpack_require__(95181);
function validateCredentials(options) {
try {
(0, api_token_1.apiTokenExists)();
}
catch (err) {
if ((0, api_token_1.getOAuthToken)()) {
return;
}
else if (options.docker && (0, api_token_1.getDockerToken)()) {
options.testDepGraphDockerEndpoint = '/docker-jwt/test-dependencies';
options.isDockerUser = true;
}
else {
throw err;
}
}
}
exports.validateCredentials = validateCredentials;
/***/ }),
/***/ 83476:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.validateTestOptions = void 0;
const theme_1 = __webpack_require__(86988);
const common_1 = __webpack_require__(53110);
const fail_on_error_ts_1 = __webpack_require__(18195);
function validateTestOptions(options) {
if (options.severityThreshold &&
!validateSeverityThreshold(options.severityThreshold)) {
throw new Error('INVALID_SEVERITY_THRESHOLD');
}
if (options.failOn && !validateFailOn(options.failOn)) {
const error = new fail_on_error_ts_1.FailOnError();
throw theme_1.color.status.error(error.message);
}
}
exports.validateTestOptions = validateTestOptions;
function validateSeverityThreshold(severityThreshold) {
return common_1.SEVERITIES.map((s) => s.verboseName).indexOf(severityThreshold) > -1;
}
function validateFailOn(arg) {
return Object.keys(common_1.FAIL_ON).includes(arg);
}
/***/ }),
/***/ 18195:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FailOnError = void 0;
const custom_error_1 = __webpack_require__(17188);
const common_1 = __webpack_require__(53110);
const error_catalog_nodejs_public_1 = __webpack_require__(88404);
class FailOnError extends custom_error_1.CustomError {
constructor() {
super(FailOnError.ERROR_MESSAGE);
this.errorCatalog = new error_catalog_nodejs_public_1.CLI.InvalidFlagOptionError('');
}
}
exports.FailOnError = FailOnError;
FailOnError.ERROR_MESSAGE = 'Invalid fail on argument, please use one of: ' +
Object.keys(common_1.FAIL_ON).join(' | ');
/***/ }),
/***/ 72571:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FeatureNotSupportedByEcosystemError = void 0;
const custom_error_1 = __webpack_require__(17188);
const error_catalog_nodejs_public_1 = __webpack_require__(88404);
class FeatureNotSupportedByEcosystemError extends custom_error_1.CustomError {
constructor(feature, ecosystem) {
super(`Unsupported ecosystem ${ecosystem} for ${feature}.`);
this.code = 422;
this.feature = feature;
this.userMessage = `\`${feature}\` is not supported for ecosystem '${ecosystem}'`;
this.errorCatalog = new error_catalog_nodejs_public_1.Fix.UnsupportedEcosystemError('');
}
}
exports.FeatureNotSupportedByEcosystemError = FeatureNotSupportedByEcosystemError;
/***/ }),
/***/ 53776:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extractMeta = exports.groupEntitiesPerScanType = exports.fix = void 0;
const debugLib = __webpack_require__(15158);
const pMap = __webpack_require__(86301);
const ora = __webpack_require__(63395);
const chalk = __webpack_require__(98250);
const outputFormatter = __webpack_require__(70962);
const load_plugin_1 = __webpack_require__(65090);
const partition_by_vulnerable_1 = __webpack_require__(24957);
const error_to_user_message_1 = __webpack_require__(5258);
const total_issues_count_1 = __webpack_require__(41160);
const fixable_issues_1 = __webpack_require__(86635);
const debug = debugLib('snyk-fix:main');
async function fix(entities, options = {
dryRun: false,
quiet: false,
stripAnsi: false,
}) {
debug('Running snyk fix with options:', options);
const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
let resultsByPlugin = {};
const { vulnerable, notVulnerable: nothingToFix } = await (0, partition_by_vulnerable_1.partitionByVulnerable)(entities);
const entitiesPerType = groupEntitiesPerScanType(vulnerable);
const exceptions = {};
await pMap(Object.keys(entitiesPerType), async (scanType) => {
try {
const fixPlugin = (0, load_plugin_1.loadPlugin)(scanType);
const results = await fixPlugin(entitiesPerType[scanType], options);
resultsByPlugin = { ...resultsByPlugin, ...results };
}
catch (e) {
debug(`Failed to processes ${scanType}`, e);
exceptions[scanType] = {
originals: entitiesPerType[scanType],
userMessage: (0, error_to_user_message_1.convertErrorToUserMessage)(e),
};
}
}, {
concurrency: 3,
});
const fixSummary = await outputFormatter.showResultsSummary(nothingToFix, resultsByPlugin, exceptions, options, entities.length);
const meta = extractMeta(resultsByPlugin, exceptions);
spinner.start();
if (meta.fixed > 0) {
spinner.stopAndPersist({
text: 'Done',
symbol: chalk.green('✔'),
});
}
else {
spinner.stop();
}
return {
results: resultsByPlugin,
exceptions,
fixSummary,
meta,
};
}
exports.fix = fix;
function groupEntitiesPerScanType(entities) {
var _a, _b, _c;
const entitiesPerType = {};
for (const entity of entities) {
// TODO: group all node
const type = (_c = (_b = (_a = entity.scanResult) === null || _a === void 0 ? void 0 : _a.identity) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : 'missing-type';
if (entitiesPerType[type]) {
entitiesPerType[type].push(entity);
continue;
}
entitiesPerType[type] = [entity];
}
return entitiesPerType;
}
exports.groupEntitiesPerScanType = groupEntitiesPerScanType;
function extractMeta(resultsByPlugin, exceptions) {
const testResults = outputFormatter.getTestResults(resultsByPlugin, exceptions);
const issueData = testResults.map((i) => i.issuesData);
const failed = outputFormatter.calculateFailed(resultsByPlugin, exceptions);
const fixed = outputFormatter.calculateFixed(resultsByPlugin);
const totalIssueCount = (0, total_issues_count_1.getTotalIssueCount)(issueData);
const { count: fixableCount } = (0, fixable_issues_1.hasFixableIssues)(testResults);
const fixedIssueCount = outputFormatter.calculateFixedIssues(resultsByPlugin);
return {
fixed,
failed,
totalIssues: totalIssueCount,
fixableIssues: fixableCount,
fixedIssues: fixedIssueCount,
};
}
exports.extractMeta = extractMeta;
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 72353:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CommandFailedError = void 0;
const custom_error_1 = __webpack_require__(33129);
class CommandFailedError extends custom_error_1.CustomError {
constructor(customMessage, command) {
super(customMessage, custom_error_1.ERROR_CODES.CommandFailed);
this.command = command;
}
}
exports.CommandFailedError = CommandFailedError;
//# sourceMappingURL=command-failed-to-run-error.js.map
/***/ }),
/***/ 75391:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.contactSupportMessage = exports.reTryMessage = void 0;
exports.reTryMessage = 'Tip: Re-run in debug mode to see more information: DEBUG=*snyk* <COMMAND>';
exports.contactSupportMessage = 'If the issue persists contact support@snyk.io';
//# sourceMappingURL=common.js.map
/***/ }),
/***/ 33129:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ERROR_CODES = exports.CustomError = void 0;
class CustomError extends Error {
constructor(message, errorCode) {
super(message);
this.name = this.constructor.name;
this.innerError = undefined;
this.errorCode = errorCode;
}
}
exports.CustomError = CustomError;
var ERROR_CODES;
(function (ERROR_CODES) {
ERROR_CODES["UnsupportedTypeError"] = "G10";
ERROR_CODES["MissingRemediationData"] = "G11";
ERROR_CODES["MissingFileName"] = "G12";
ERROR_CODES["FailedToParseManifest"] = "G13";
ERROR_CODES["CommandFailed"] = "G14";
ERROR_CODES["NoFixesCouldBeApplied"] = "G15";
})(ERROR_CODES = exports.ERROR_CODES || (exports.ERROR_CODES = {}));
//# sourceMappingURL=custom-error.js.map
/***/ }),
/***/ 5258:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.convertErrorToUserMessage = void 0;
const unsupported_type_error_1 = __webpack_require__(1187);
function convertErrorToUserMessage(error) {
if (error instanceof unsupported_type_error_1.UnsupportedTypeError) {
return `${error.scanType} is not supported.`;
}
return error.message;
}
exports.convertErrorToUserMessage = convertErrorToUserMessage;
//# sourceMappingURL=error-to-user-message.js.map
/***/ }),
/***/ 84657:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FailedToParseManifest = void 0;
const custom_error_1 = __webpack_require__(33129);
class FailedToParseManifest extends custom_error_1.CustomError {
constructor() {
super('Failed to parse manifest', custom_error_1.ERROR_CODES.FailedToParseManifest);
}
}
exports.FailedToParseManifest = FailedToParseManifest;
//# sourceMappingURL=failed-to-parse-manifest.js.map
/***/ }),
/***/ 86920:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingFileNameError = void 0;
const custom_error_1 = __webpack_require__(33129);
class MissingFileNameError extends custom_error_1.CustomError {
constructor() {
super('Filename is missing from test result', custom_error_1.ERROR_CODES.MissingFileName);
}
}
exports.MissingFileNameError = MissingFileNameError;
//# sourceMappingURL=missing-file-name.js.map
/***/ }),
/***/ 95084:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MissingRemediationDataError = void 0;
const custom_error_1 = __webpack_require__(33129);
class MissingRemediationDataError extends custom_error_1.CustomError {
constructor() {
super('Remediation data is required to apply fixes', custom_error_1.ERROR_CODES.MissingRemediationData);
}
}
exports.MissingRemediationDataError = MissingRemediationDataError;
//# sourceMappingURL=missing-remediation-data.js.map
/***/ }),
/***/ 80799:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoFixesCouldBeAppliedError = void 0;
const custom_error_1 = __webpack_require__(33129);
class NoFixesCouldBeAppliedError extends custom_error_1.CustomError {
constructor(message, tip) {
super(message || 'No fixes could be applied', custom_error_1.ERROR_CODES.NoFixesCouldBeApplied);
this.tip = tip;
}
}
exports.NoFixesCouldBeAppliedError = NoFixesCouldBeAppliedError;
//# sourceMappingURL=no-fixes-applied.js.map
/***/ }),
/***/ 1187:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UnsupportedTypeError = void 0;
const custom_error_1 = __webpack_require__(33129);
class UnsupportedTypeError extends custom_error_1.CustomError {
constructor(scanType) {
super('Provided scan type is not supported', custom_error_1.ERROR_CODES.UnsupportedTypeError);
this.scanType = scanType;
}
}
exports.UnsupportedTypeError = UnsupportedTypeError;
//# sourceMappingURL=unsupported-type-error.js.map
/***/ }),
/***/ 86635:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.hasFixableIssues = void 0;
function hasFixableIssues(results) {
let hasFixes = false;
let count = 0;
for (const result of Object.values(results)) {
const { remediation } = result;
if (remediation) {
const { upgrade, pin, patch } = remediation;
const upgrades = Object.keys(upgrade);
const pins = Object.keys(pin);
if (pins.length || upgrades.length) {
hasFixes = true;
// pins & upgrades are mutually exclusive
count += getUpgradableIssues(pins.length ? pin : upgrade);
}
const patches = Object.keys(patch);
if (patches.length) {
hasFixes = true;
count += patches.length;
}
}
}
return {
hasFixes,
count,
};
}
exports.hasFixableIssues = hasFixableIssues;
function getUpgradableIssues(updates) {
const issues = [];
for (const id of Object.keys(updates)) {
issues.push(...updates[id].vulns);
}
return issues.length;
}
//# sourceMappingURL=fixable-issues.js.map
/***/ }),
/***/ 29748:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getIssueCountBySeverity = void 0;
function getIssueCountBySeverity(issueData) {
const total = {
low: [],
medium: [],
high: [],
critical: [],
};
for (const entry of issueData) {
for (const issue of Object.values(entry)) {
const { severity, id } = issue;
total[severity.toLowerCase()].push(id);
}
}
return total;
}
exports.getIssueCountBySeverity = getIssueCountBySeverity;
//# sourceMappingURL=issues-by-severity.js.map
/***/ }),
/***/ 41160:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getTotalIssueCount = void 0;
function getTotalIssueCount(issueData) {
let total = 0;
for (const entry of issueData) {
total += Object.keys(entry).length;
}
return total;
}
exports.getTotalIssueCount = getTotalIssueCount;
//# sourceMappingURL=total-issues-count.js.map
/***/ }),
/***/ 90686:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatDisplayName = void 0;
const pathLib = __webpack_require__(71017);
function formatDisplayName(path, identity) {
if (!identity.targetFile) {
return `${identity.type} project`;
}
// show paths relative to where `snyk fix` is running
return pathLib.relative(process.cwd(), pathLib.join(path, identity.targetFile));
}
exports.formatDisplayName = formatDisplayName;
//# sourceMappingURL=format-display-name.js.map
/***/ }),
/***/ 31998:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatFailed = void 0;
const types_1 = __webpack_require__(71538);
const error_to_user_message_1 = __webpack_require__(5258);
const format_with_changes_item_1 = __webpack_require__(38154);
const format_unresolved_item_1 = __webpack_require__(82187);
function formatFailed(failed) {
if ((0, types_1.isWithError)(failed)) {
return (0, format_unresolved_item_1.formatUnresolved)(failed.original, (0, error_to_user_message_1.convertErrorToUserMessage)(failed.error), failed.tip);
}
return (0, format_with_changes_item_1.formatChangesSummary)(failed.original, failed.changes);
}
exports.formatFailed = formatFailed;
//# sourceMappingURL=format-failed-item.js.map
/***/ }),
/***/ 82187:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatUnresolved = void 0;
const chalk = __webpack_require__(98250);
const format_display_name_1 = __webpack_require__(90686);
const show_results_summary_1 = __webpack_require__(70962);
function formatUnresolved(entity, userMessage, tip) {
const name = (0, format_display_name_1.formatDisplayName)(entity.workspace.path, entity.scanResult.identity);
const tipMessage = tip ? `\n${show_results_summary_1.PADDING_SPACE}Tip: ${tip}` : '';
const errorMessage = `${show_results_summary_1.PADDING_SPACE}${name}\n${show_results_summary_1.PADDING_SPACE}${chalk.red('✖')} ${chalk.red(userMessage)}`;
return errorMessage + tipMessage;
}
exports.formatUnresolved = formatUnresolved;
//# sourceMappingURL=format-unresolved-item.js.map
/***/ }),
/***/ 38154:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.formatChangesSummary = void 0;
const chalk = __webpack_require__(98250);
const format_display_name_1 = __webpack_require__(90686);
const show_results_summary_1 = __webpack_require__(70962);
/*
* Generate formatted output that describes what changes were applied, which failed.
*/
function formatChangesSummary(entity, changes) {
return `${show_results_summary_1.PADDING_SPACE}${(0, format_display_name_1.formatDisplayName)(entity.workspace.path, entity.scanResult.identity)}\n${changes.map((c) => formatAppliedChange(c)).join('\n')}`;
}
exports.formatChangesSummary = formatChangesSummary;
function formatAppliedChange(change) {
if (change.success === true) {
return `${show_results_summary_1.PADDING_SPACE}${chalk.green('✔')} ${change.userMessage}`;
}
if (change.success === false) {
return `${show_results_summary_1.PADDING_SPACE}${chalk.red('x')} ${chalk.red(change.userMessage)}\n${show_results_summary_1.PADDING_SPACE}Reason:${show_results_summary_1.PADDING_SPACE}${change.reason}${change.tip ? `.\n${show_results_summary_1.PADDING_SPACE}Tip: ${change.tip}` : undefined}`;
}
return '';
}
//# sourceMappingURL=format-with-changes-item.js.map
/***/ }),
/***/ 70962:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getTestResults = exports.generateIssueSummary = exports.getSeveritiesColour = exports.defaultSeverityColor = exports.severitiesColourMapping = exports.formatIssueCountBySeverity = exports.calculateFailed = exports.calculateFixedIssues = exports.calculateFixed = exports.generateOverallSummary = exports.generateUnresolvedSummary = exports.generateSuccessfulFixesSummary = exports.showResultsSummary = exports.PADDING_SPACE = void 0;
const chalk = __webpack_require__(98250);
const stripAnsi = __webpack_require__(71990);
const common_1 = __webpack_require__(75391);
const fixable_issues_1 = __webpack_require__(86635);
const issues_by_severity_1 = __webpack_require__(29748);
const total_issues_count_1 = __webpack_require__(41160);
const format_failed_item_1 = __webpack_require__(31998);
const format_with_changes_item_1 = __webpack_require__(38154);
const format_unresolved_item_1 = __webpack_require__(82187);
exports.PADDING_SPACE = ' '; // 2 spaces
async function showResultsSummary(nothingToFix, resultsByPlugin, exceptions, options, total) {
const successfulFixesSummary = generateSuccessfulFixesSummary(resultsByPlugin);
const { summary: unresolvedSummary, count: unresolvedCount } = generateUnresolvedSummary(resultsByPlugin, exceptions);
const { summary: overallSummary, count: changedCount } = generateOverallSummary(resultsByPlugin, exceptions, nothingToFix, options);
const getHelpText = `${common_1.reTryMessage}. ${common_1.contactSupportMessage}`;
// called without any `snyk test` results
if (total === 0) {
const summary = `\n${chalk.red(' ✖ No successful fixes')}`;
return options.stripAnsi ? stripAnsi(summary) : summary;
}
// 100% not vulnerable and had no errors/unsupported
if (nothingToFix.length === total && unresolvedCount === 0) {
const summary = `\n${chalk.green('✔ No vulnerable items to fix')}\n\n${overallSummary}`;
return options.stripAnsi ? stripAnsi(summary) : summary;
}
const summary = `\n${successfulFixesSummary}${unresolvedSummary}${unresolvedCount || changedCount ? `\n\n${overallSummary}` : ''}${unresolvedSummary ? `\n\n${getHelpText}` : ''}`;
return options.stripAnsi ? stripAnsi(summary) : summary;
}
exports.showResultsSummary = showResultsSummary;
function generateSuccessfulFixesSummary(resultsByPlugin) {
const sectionTitle = 'Successful fixes:';
const formattedTitleHeader = `${chalk.bold(sectionTitle)}`;
let summary = '';
for (const plugin of Object.keys(resultsByPlugin)) {
const fixedSuccessfully = resultsByPlugin[plugin].succeeded;
if (fixedSuccessfully.length > 0) {
summary +=
'\n\n' +
fixedSuccessfully
.map((s) => (0, format_with_changes_item_1.formatChangesSummary)(s.original, s.changes))
.join('\n\n');
}
}
if (summary) {
return formattedTitleHeader + summary;
}
return chalk.red(' ✖ No successful fixes\n');
}
exports.generateSuccessfulFixesSummary = generateSuccessfulFixesSummary;
function generateUnresolvedSummary(resultsByPlugin, exceptionsByScanType) {
const title = 'Unresolved items:';
const formattedTitle = `${chalk.bold(title)}`;
let summary = '';
let count = 0;
for (const plugin of Object.keys(resultsByPlugin)) {
const skipped = resultsByPlugin[plugin].skipped;
if (skipped.length > 0) {
count += skipped.length;
summary +=
'\n\n' +
skipped
.map((s) => (0, format_unresolved_item_1.formatUnresolved)(s.original, s.userMessage))
.join('\n\n');
}
const failed = resultsByPlugin[plugin].failed;
if (failed.length > 0) {
count += failed.length;
summary += '\n\n' + failed.map((s) => (0, format_failed_item_1.formatFailed)(s)).join('\n\n');
}
}
if (Object.keys(exceptionsByScanType).length) {
for (const ecosystem of Object.keys(exceptionsByScanType)) {
const unresolved = exceptionsByScanType[ecosystem];
count += unresolved.originals.length;
summary +=
'\n\n' +
unresolved.originals
.map((s) => (0, format_unresolved_item_1.formatUnresolved)(s, unresolved.userMessage))
.join('\n\n');
}
}
if (summary) {
return { summary: `\n\n${formattedTitle}${summary}`, count };
}
return { summary: '', count: 0 };
}
exports.generateUnresolvedSummary = generateUnresolvedSummary;
function generateOverallSummary(resultsByPlugin, exceptions, nothingToFix, options) {
const sectionTitle = 'Summary:';
const formattedTitleHeader = `${chalk.bold(sectionTitle)}`;
const fixed = calculateFixed(resultsByPlugin);
const failed = calculateFailed(resultsByPlugin, exceptions);
const dryRunText = options.dryRun
? chalk.hex('#EDD55E')(`${exports.PADDING_SPACE}Command run in ${chalk.bold('dry run')} mode. Fixes are not applied.\n`)
: '';
const notFixedMessage = failed > 0
? `${exports.PADDING_SPACE}${chalk.bold.red(failed)} items were not fixed\n`
: '';
const fixedMessage = fixed > 0
? `${exports.PADDING_SPACE}${chalk.green.bold(fixed)} items were successfully fixed\n`
: '';
const vulnsSummary = generateIssueSummary(resultsByPlugin, exceptions);
const notVulnerableSummary = nothingToFix.length > 0
? `${exports.PADDING_SPACE}${nothingToFix.length} items were not vulnerable\n`
: '';
return {
summary: `${formattedTitleHeader}\n\n${dryRunText}${notFixedMessage}${fixedMessage}${notVulnerableSummary}${vulnsSummary}`,
count: fixed + failed,
};
}
exports.generateOverallSummary = generateOverallSummary;
function calculateFixed(resultsByPlugin) {
let fixed = 0;
for (const plugin of Object.keys(resultsByPlugin)) {
fixed += resultsByPlugin[plugin].succeeded.length;
}
return fixed;
}
exports.calculateFixed = calculateFixed;
function calculateFixedIssues(resultsByPlugin) {
const fixedIssues = [];
for (const plugin of Object.keys(resultsByPlugin)) {
for (const entity of resultsByPlugin[plugin].succeeded) {
// count unique vulns fixed per scanned entity
// some fixed may need to be made in multiple places
// and would count multiple times otherwise.
const fixedPerEntity = new Set();
entity.changes
.filter((c) => c.success)
.forEach((c) => {
c.issueIds.map((i) => fixedPerEntity.add(i));
});
fixedIssues.push(...Array.from(fixedPerEntity));
}
}
return fixedIssues.length;
}
exports.calculateFixedIssues = calculateFixedIssues;
function calculateFailed(resultsByPlugin, exceptions) {
let failed = 0;
for (const plugin of Object.keys(resultsByPlugin)) {
const results = resultsByPlugin[plugin];
failed += results.failed.length + results.skipped.length;
}
if (Object.keys(exceptions).length) {
for (const ecosystem of Object.keys(exceptions)) {
const unresolved = exceptions[ecosystem];
failed += unresolved.originals.length;
}
}
return failed;
}
exports.calculateFailed = calculateFailed;
function formatIssueCountBySeverity({ critical, high, medium, low, }) {
const summary = [];
if (critical && critical > 0) {
summary.push(exports.severitiesColourMapping.critical.colorFunc(`${critical} Critical`));
}
if (high && high > 0) {
summary.push(exports.severitiesColourMapping.high.colorFunc(`${high} High`));
}
if (medium && medium > 0) {
summary.push(exports.severitiesColourMapping.medium.colorFunc(`${medium} Medium`));
}
if (low && low > 0) {
summary.push(exports.severitiesColourMapping.low.colorFunc(`${low} Low`));
}
return summary.join(' | ');
}
exports.formatIssueCountBySeverity = formatIssueCountBySeverity;
exports.severitiesColourMapping = {
low: {
colorFunc(text) {
return chalk.hex('#BCBBC8')(text);
},
},
medium: {
colorFunc(text) {
return chalk.hex('#EDD55E')(text);
},
},
high: {
colorFunc(text) {
return chalk.hex('#FF872F')(text);
},
},
critical: {
colorFunc(text) {
return chalk.hex('#FF0B0B')(text);
},
},
};
exports.defaultSeverityColor = {
colorFunc(text) {
return chalk.grey(text);
},
};
function getSeveritiesColour(severity) {
var _a;
return (_a = exports.severitiesColourMapping[severity]) !== null && _a !== void 0 ? _a : exports.defaultSeverityColor;
}
exports.getSeveritiesColour = getSeveritiesColour;
function generateIssueSummary(resultsByPlugin, exceptions) {
const testResults = getTestResults(resultsByPlugin, exceptions);
const issueData = testResults.map((i) => i.issuesData);
const bySeverity = (0, issues_by_severity_1.getIssueCountBySeverity)(issueData);
const issuesBySeverityMessage = formatIssueCountBySeverity({
critical: bySeverity.critical.length,
high: bySeverity.high.length,
medium: bySeverity.medium.length,
low: bySeverity.low.length,
});
// can't use .flat() or .flatMap() because it's not supported in Node 10
const issues = [];
for (const result of testResults) {
issues.push(...result.issues);
}
const totalIssueCount = (0, total_issues_count_1.getTotalIssueCount)(issueData);
let totalIssues = '';
if (totalIssueCount > 0) {
totalIssues = `${chalk.bold(totalIssueCount)} issues\n`;
if (issuesBySeverityMessage) {
totalIssues = `${chalk.bold(totalIssueCount)} issues: ${issuesBySeverityMessage}\n`;
}
}
const { count: fixableCount } = (0, fixable_issues_1.hasFixableIssues)(testResults);
const fixableIssues = fixableCount > 0 ? `${chalk.bold(fixableCount)} issues are fixable\n` : '';
const fixedIssueCount = calculateFixedIssues(resultsByPlugin);
const fixedIssuesSummary = fixedIssueCount > 0
? `${chalk.bold(fixedIssueCount)} issues were successfully fixed\n`
: '';
return `\n${exports.PADDING_SPACE}${totalIssues}${exports.PADDING_SPACE}${fixableIssues}${exports.PADDING_SPACE}${fixedIssuesSummary}`;
}
exports.generateIssueSummary = generateIssueSummary;
function getTestResults(resultsByPlugin, exceptionsByScanType) {
const testResults = [];
for (const plugin of Object.keys(resultsByPlugin)) {
const { skipped, failed, succeeded } = resultsByPlugin[plugin];
testResults.push(...skipped.map((i) => i.original.testResult));
testResults.push(...failed.map((i) => i.original.testResult));
testResults.push(...succeeded.map((i) => i.original.testResult));
}
if (Object.keys(exceptionsByScanType).length) {
for (const ecosystem of Object.keys(exceptionsByScanType)) {
const unresolved = exceptionsByScanType[ecosystem];
testResults.push(...unresolved.originals.map((i) => i.testResult));
}
}
return testResults;
}
exports.getTestResults = getTestResults;
//# sourceMappingURL=show-results-summary.js.map
/***/ }),
/***/ 24957:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.partitionByVulnerable = void 0;
function partitionByVulnerable(entities) {
const vulnerable = [];
const notVulnerable = [];
for (const entity of entities) {
const hasIssues = entity.testResult.issues.length > 0;
if (hasIssues) {
vulnerable.push(entity);
}
else {
notVulnerable.push(entity);
}
}
return { vulnerable, notVulnerable };
}
exports.partitionByVulnerable = partitionByVulnerable;
//# sourceMappingURL=partition-by-vulnerable.js.map
/***/ }),
/***/ 65090:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.loadPlugin = void 0;
const unsupported_type_error_1 = __webpack_require__(1187);
const python_1 = __webpack_require__(97090);
function loadPlugin(type) {
switch (type) {
case 'pip': {
return python_1.pythonFix;
}
case 'poetry': {
return python_1.pythonFix;
}
default: {
throw new unsupported_type_error_1.UnsupportedTypeError(type);
}
}
}
exports.loadPlugin = loadPlugin;
//# sourceMappingURL=load-plugin.js.map
/***/ }),
/***/ 96377:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkPackageToolSupported = void 0;
const chalk = __webpack_require__(98250);
const pipenvPipfileFix = __webpack_require__(91989);
const poetryFix = __webpack_require__(69671);
const ora = __webpack_require__(63395);
const supportFunc = {
pipenv: {
isInstalled: () => pipenvPipfileFix.isPipenvInstalled(),
isSupportedVersion: (version) => pipenvPipfileFix.isPipenvSupportedVersion(version),
},
poetry: {
isInstalled: () => poetryFix.isPoetryInstalled(),
isSupportedVersion: (version) => poetryFix.isPoetrySupportedVersion(version),
},
};
async function checkPackageToolSupported(packageManager, options) {
const { version } = await supportFunc[packageManager].isInstalled();
const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
spinner.clear();
spinner.text = `Checking ${packageManager} version`;
spinner.indent = 2;
spinner.start();
if (!version) {
spinner.stopAndPersist({
text: chalk.hex('#EDD55E')(`Could not detect ${packageManager} version, proceeding anyway. Some operations may fail.`),
symbol: chalk.hex('#EDD55E')('⚠️'),
});
return;
}
const { supported, versions } = supportFunc[packageManager].isSupportedVersion(version);
if (!supported) {
const spinnerMessage = ` ${version} ${packageManager} version detected. Currently the following ${packageManager} versions are supported: ${versions.join(',')}`;
spinner.stopAndPersist({
text: chalk.hex('#EDD55E')(spinnerMessage),
symbol: chalk.hex('#EDD55E')('⚠️'),
});
}
else {
spinner.stop();
}
}
exports.checkPackageToolSupported = checkPackageToolSupported;
//# sourceMappingURL=package-tool-supported.js.map
/***/ }),
/***/ 10774:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isRequirementsTxtManifest = exports.getHandlerType = void 0;
const pathLib = __webpack_require__(71017);
const supported_handler_types_1 = __webpack_require__(56394);
function getHandlerType(entity) {
const targetFile = entity.scanResult.identity.targetFile;
if (!targetFile) {
return null;
}
const packageManagerOverride = entity.options.packageManager;
if (packageManagerOverride) {
return getTypeFromPackageManager(packageManagerOverride);
}
const path = pathLib.parse(targetFile);
if (isRequirementsTxtManifest(targetFile)) {
return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS;
}
else if (['Pipfile'].includes(path.base)) {
return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.PIPFILE;
}
else if (['pyproject.toml', 'poetry.lock'].includes(path.base)) {
return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY;
}
return null;
}
exports.getHandlerType = getHandlerType;
function isRequirementsTxtManifest(targetFile) {
return targetFile.endsWith('.txt');
}
exports.isRequirementsTxtManifest = isRequirementsTxtManifest;
function getTypeFromPackageManager(packageManager) {
switch (packageManager) {
case 'pip':
return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS;
case 'poetry':
return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY;
default:
return null;
}
}
//# sourceMappingURL=get-handler-type.js.map
/***/ }),
/***/ 70145:
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isSuccessfulChange = exports.generateSuccessfulChanges = exports.generateFailedChanges = void 0;
func