741.index.js 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816
  1. "use strict";
  2. exports.id = 741;
  3. exports.ids = [741];
  4. exports.modules = {
  5. /***/ 80423:
  6. /***/ ((__unused_webpack_module, exports) => {
  7. Object.defineProperty(exports, "__esModule", ({ value: true }));
  8. exports.convertLegacyTestResultToNew = void 0;
  9. function convertVulnerabilities(vulns) {
  10. const issuesData = {};
  11. const issues = [];
  12. vulns.forEach((vuln) => {
  13. issuesData[vuln.id] = {
  14. id: vuln.id,
  15. severity: vuln.severity,
  16. title: vuln.title,
  17. };
  18. issues.push({
  19. pkgName: vuln.packageName,
  20. pkgVersion: vuln.version,
  21. issueId: vuln.id,
  22. // TODO: add fixInfo when needed
  23. fixInfo: {},
  24. });
  25. });
  26. return { issuesData, issues };
  27. }
  28. function convertLegacyTestResultToNew(testResult) {
  29. const { issues, issuesData } = convertVulnerabilities(testResult.vulnerabilities);
  30. return {
  31. issuesData,
  32. issues,
  33. remediation: testResult.remediation,
  34. // TODO: grab this once Ecosystems flow starts sending back ScanResult
  35. depGraphData: {},
  36. };
  37. }
  38. exports.convertLegacyTestResultToNew = convertLegacyTestResultToNew;
  39. /***/ }),
  40. /***/ 16898:
  41. /***/ ((__unused_webpack_module, exports) => {
  42. Object.defineProperty(exports, "__esModule", ({ value: true }));
  43. exports.convertLegacyTestResultToScanResult = void 0;
  44. function convertLegacyTestResultToScanResult(testResult) {
  45. if (!testResult.packageManager) {
  46. throw new Error('Only results with packageManagers are supported for conversion');
  47. }
  48. return {
  49. identity: {
  50. type: testResult.packageManager,
  51. // this is because not all plugins send it back today, but we should always have it
  52. targetFile: testResult.targetFile || testResult.displayTargetFile,
  53. },
  54. name: testResult.projectName,
  55. // TODO: grab this once Ecosystems flow starts sending back ScanResult
  56. facts: [],
  57. policy: testResult.policy,
  58. // TODO: grab this once Ecosystems flow starts sending back ScanResult
  59. target: {},
  60. };
  61. }
  62. exports.convertLegacyTestResultToScanResult = convertLegacyTestResultToScanResult;
  63. /***/ }),
  64. /***/ 92730:
  65. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  66. Object.defineProperty(exports, "__esModule", ({ value: true }));
  67. exports.convertLegacyTestResultToFixEntities = void 0;
  68. const fs = __webpack_require__(35747);
  69. const pathLib = __webpack_require__(85622);
  70. const convert_legacy_test_result_to_new_1 = __webpack_require__(80423);
  71. const convert_legacy_test_result_to_scan_result_1 = __webpack_require__(16898);
  72. function convertLegacyTestResultToFixEntities(testResults, root, options) {
  73. if (testResults instanceof Error) {
  74. return [];
  75. }
  76. const oldResults = Array.isArray(testResults) ? testResults : [testResults];
  77. return oldResults.map((res) => ({
  78. options,
  79. workspace: {
  80. path: root,
  81. readFile: async (path) => {
  82. return fs.readFileSync(pathLib.resolve(root, path), 'utf8');
  83. },
  84. writeFile: async (path, content) => {
  85. return fs.writeFileSync(pathLib.resolve(root, path), content, 'utf8');
  86. },
  87. },
  88. scanResult: convert_legacy_test_result_to_scan_result_1.convertLegacyTestResultToScanResult(res),
  89. testResult: convert_legacy_test_result_to_new_1.convertLegacyTestResultToNew(res),
  90. }));
  91. }
  92. exports.convertLegacyTestResultToFixEntities = convertLegacyTestResultToFixEntities;
  93. /***/ }),
  94. /***/ 79898:
  95. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  96. Object.defineProperty(exports, "__esModule", ({ value: true }));
  97. exports.getDisplayPath = void 0;
  98. const pathLib = __webpack_require__(85622);
  99. const detect_1 = __webpack_require__(45318);
  100. function getDisplayPath(path) {
  101. if (!detect_1.isLocalFolder(path)) {
  102. return path;
  103. }
  104. if (path === process.cwd()) {
  105. return pathLib.parse(path).name;
  106. }
  107. return pathLib.relative(process.cwd(), path);
  108. }
  109. exports.getDisplayPath = getDisplayPath;
  110. /***/ }),
  111. /***/ 73741:
  112. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  113. Object.defineProperty(exports, "__esModule", ({ value: true }));
  114. const Debug = __webpack_require__(15158);
  115. const snykFix = __webpack_require__(53776);
  116. const ora = __webpack_require__(63395);
  117. const snyk = __webpack_require__(9146);
  118. const analytics = __webpack_require__(82744);
  119. const convert_legacy_tests_results_to_fix_entities_1 = __webpack_require__(92730);
  120. const format_test_error_1 = __webpack_require__(68214);
  121. const process_command_args_1 = __webpack_require__(52369);
  122. const validate_credentials_1 = __webpack_require__(4593);
  123. const validate_test_options_1 = __webpack_require__(83476);
  124. const set_default_test_options_1 = __webpack_require__(13285);
  125. const validate_fix_command_is_supported_1 = __webpack_require__(16117);
  126. const get_display_path_1 = __webpack_require__(79898);
  127. const chalk_1 = __webpack_require__(32589);
  128. const theme_1 = __webpack_require__(86988);
  129. const check_paths_1 = __webpack_require__(94501);
  130. const debug = Debug('snyk-fix');
  131. const snykFixFeatureFlag = 'cliSnykFix';
  132. async function fix(...args) {
  133. const { options: rawOptions, paths } = await process_command_args_1.processCommandArgs(...args);
  134. const options = set_default_test_options_1.setDefaultTestOptions(rawOptions);
  135. debug(options);
  136. await validate_fix_command_is_supported_1.validateFixCommandIsSupported(options);
  137. if (!options.docker) {
  138. check_paths_1.checkOSSPaths(paths, rawOptions);
  139. }
  140. validate_test_options_1.validateTestOptions(options);
  141. validate_credentials_1.validateCredentials(options);
  142. const results = [];
  143. results.push(...(await runSnykTestLegacy(options, paths)));
  144. // fix
  145. debug(`Organization has ${snykFixFeatureFlag} feature flag enabled for experimental Snyk fix functionality`);
  146. const vulnerableResults = results.filter((res) => Object.keys(res.testResult.issues).length);
  147. const { dryRun, quiet, sequential: sequentialFix } = options;
  148. const { fixSummary, meta, results: resultsByPlugin } = await snykFix.fix(results, {
  149. dryRun,
  150. quiet,
  151. sequentialFix,
  152. });
  153. setSnykFixAnalytics(fixSummary, meta, results, resultsByPlugin, vulnerableResults);
  154. // `snyk test` did not return any test results
  155. if (results.length === 0) {
  156. throw new Error(fixSummary);
  157. }
  158. // `snyk test` returned no vulnerable results, so nothing to fix
  159. if (vulnerableResults.length === 0) {
  160. return fixSummary;
  161. }
  162. // `snyk test` returned vulnerable results
  163. // however some errors occurred during `snyk fix` and nothing was fixed in the end
  164. const anyFailed = meta.failed > 0;
  165. const noneFixed = meta.fixed === 0;
  166. if (anyFailed && noneFixed) {
  167. throw new Error(fixSummary);
  168. }
  169. return fixSummary;
  170. }
  171. exports.default = fix;
  172. /* @deprecated
  173. * TODO: once project envelope is default all code below will be deleted
  174. * we should be calling test via new Ecosystems instead
  175. */
  176. async function runSnykTestLegacy(options, paths) {
  177. const results = [];
  178. const stdOutSpinner = ora({
  179. isSilent: options.quiet,
  180. stream: process.stdout,
  181. });
  182. const stdErrSpinner = ora({
  183. isSilent: options.quiet,
  184. stream: process.stdout,
  185. });
  186. stdErrSpinner.start();
  187. stdOutSpinner.start();
  188. for (const path of paths) {
  189. let displayPath = path;
  190. const spinnerMessage = `Running \`snyk test\` for ${displayPath}`;
  191. try {
  192. displayPath = get_display_path_1.getDisplayPath(path);
  193. stdOutSpinner.text = spinnerMessage;
  194. stdOutSpinner.render();
  195. // Create a copy of the options so a specific test can
  196. // modify them i.e. add `options.file` etc. We'll need
  197. // these options later.
  198. const snykTestOptions = {
  199. ...options,
  200. path,
  201. projectName: options['project-name'],
  202. };
  203. const testResults = [];
  204. const testResultForPath = await snyk.test(path, { ...snykTestOptions, quiet: true });
  205. testResults.push(...(Array.isArray(testResultForPath)
  206. ? testResultForPath
  207. : [testResultForPath]));
  208. const newRes = convert_legacy_tests_results_to_fix_entities_1.convertLegacyTestResultToFixEntities(testResults, path, options);
  209. results.push(...newRes);
  210. stdOutSpinner.stopAndPersist({
  211. text: spinnerMessage,
  212. symbol: `\n${theme_1.icon.RUN}`,
  213. });
  214. }
  215. catch (error) {
  216. const testError = format_test_error_1.formatTestError(error);
  217. const userMessage = theme_1.color.status.error(`Failed! ${testError.message}.`) +
  218. `\n Tip: run \`snyk test ${displayPath} -d\` for more information.`;
  219. stdOutSpinner.stopAndPersist({
  220. text: spinnerMessage,
  221. symbol: `\n${theme_1.icon.RUN}`,
  222. });
  223. stdErrSpinner.stopAndPersist({
  224. text: userMessage,
  225. symbol: chalk_1.default.red(' '),
  226. });
  227. debug(userMessage);
  228. }
  229. }
  230. stdOutSpinner.stop();
  231. stdErrSpinner.stop();
  232. return results;
  233. }
  234. function setSnykFixAnalytics(fixSummary, meta, snykTestResponses, resultsByPlugin, vulnerableResults) {
  235. // Analytics # of projects
  236. analytics.add('snykFixFailedProjects', meta.failed);
  237. analytics.add('snykFixFixedProjects', meta.fixed);
  238. analytics.add('snykFixTotalProjects', snykTestResponses.length);
  239. analytics.add('snykFixVulnerableProjects', vulnerableResults.length);
  240. // Analytics # of issues
  241. analytics.add('snykFixFixableIssues', meta.fixableIssues);
  242. analytics.add('snykFixFixedIssues', meta.fixedIssues);
  243. analytics.add('snykFixTotalIssues', meta.totalIssues);
  244. analytics.add('snykFixSummary', fixSummary);
  245. // Analytics for errors
  246. for (const plugin of Object.keys(resultsByPlugin)) {
  247. const errors = [];
  248. const failedToFix = resultsByPlugin[plugin].failed;
  249. for (const failed of failedToFix) {
  250. if ('error' in failed) {
  251. errors.push(failed.error.message);
  252. }
  253. if ('changes' in failed) {
  254. errors.push(...failed.changes.map((f) => JSON.stringify(f)));
  255. }
  256. }
  257. analytics.add('snykFixErrors', { [plugin]: errors });
  258. }
  259. }
  260. /***/ }),
  261. /***/ 16117:
  262. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  263. Object.defineProperty(exports, "__esModule", ({ value: true }));
  264. exports.validateFixCommandIsSupported = void 0;
  265. const Debug = __webpack_require__(15158);
  266. const ecosystems_1 = __webpack_require__(5168);
  267. const feature_flags_1 = __webpack_require__(63011);
  268. const not_supported_by_ecosystem_1 = __webpack_require__(72571);
  269. const errors_1 = __webpack_require__(55191);
  270. const chalk_1 = __webpack_require__(32589);
  271. const debug = Debug('snyk-fix');
  272. const snykFixFeatureFlag = 'cliSnykFix';
  273. async function validateFixCommandIsSupported(options) {
  274. if (options.docker) {
  275. throw new not_supported_by_ecosystem_1.FeatureNotSupportedByEcosystemError('snyk fix', 'docker');
  276. }
  277. const ecosystem = ecosystems_1.getEcosystemForTest(options);
  278. if (ecosystem) {
  279. throw new not_supported_by_ecosystem_1.FeatureNotSupportedByEcosystemError('snyk fix', ecosystem);
  280. }
  281. const snykFixSupported = await feature_flags_1.isFeatureFlagSupportedForOrg(snykFixFeatureFlag, options.org);
  282. debug('Feature flag check returned: ', snykFixSupported);
  283. if (snykFixSupported.code === 401 || snykFixSupported.code === 403) {
  284. throw errors_1.AuthFailedError(snykFixSupported.error, snykFixSupported.code);
  285. }
  286. if (!snykFixSupported.ok) {
  287. const snykFixErrorMessage = chalk_1.default.red(`\`snyk fix\` is not supported${options.org ? ` for org '${options.org}'` : ''}.`) +
  288. '\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';
  289. const unsupportedError = new Error(snykFixErrorMessage);
  290. throw unsupportedError;
  291. }
  292. return true;
  293. }
  294. exports.validateFixCommandIsSupported = validateFixCommandIsSupported;
  295. /***/ }),
  296. /***/ 68214:
  297. /***/ ((__unused_webpack_module, exports) => {
  298. Object.defineProperty(exports, "__esModule", ({ value: true }));
  299. exports.formatTestError = void 0;
  300. function formatTestError(error) {
  301. // Possible error cases:
  302. // - the test found some vulns. `error.message` is a
  303. // JSON-stringified
  304. // test result.
  305. // - the flow failed, `error` is a real Error object.
  306. // - the flow failed, `error` is a number or string
  307. // describing the problem.
  308. //
  309. // To standardise this, make sure we use the best _object_ to
  310. // describe the error.
  311. let errorResponse;
  312. if (error instanceof Error) {
  313. errorResponse = error;
  314. }
  315. else if (typeof error !== 'object') {
  316. errorResponse = new Error(error);
  317. }
  318. else {
  319. try {
  320. errorResponse = JSON.parse(error.message);
  321. }
  322. catch (unused) {
  323. errorResponse = error;
  324. }
  325. }
  326. return errorResponse;
  327. }
  328. exports.formatTestError = formatTestError;
  329. /***/ }),
  330. /***/ 13285:
  331. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  332. Object.defineProperty(exports, "__esModule", ({ value: true }));
  333. exports.setDefaultTestOptions = void 0;
  334. const config_1 = __webpack_require__(25425);
  335. function setDefaultTestOptions(options) {
  336. const svpSupplied = (options['show-vulnerable-paths'] || '')
  337. .toString()
  338. .toLowerCase();
  339. delete options['show-vulnerable-paths'];
  340. return {
  341. ...options,
  342. // org fallback to config unless specified
  343. org: options.org || config_1.default.org,
  344. // making `show-vulnerable-paths` 'some' by default.
  345. showVulnPaths: showVulnPathsMapping[svpSupplied] || 'some',
  346. };
  347. }
  348. exports.setDefaultTestOptions = setDefaultTestOptions;
  349. const showVulnPathsMapping = {
  350. false: 'none',
  351. none: 'none',
  352. true: 'some',
  353. some: 'some',
  354. all: 'all',
  355. };
  356. /***/ }),
  357. /***/ 4593:
  358. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  359. Object.defineProperty(exports, "__esModule", ({ value: true }));
  360. exports.validateCredentials = void 0;
  361. const api_token_1 = __webpack_require__(95181);
  362. function validateCredentials(options) {
  363. try {
  364. api_token_1.apiTokenExists();
  365. }
  366. catch (err) {
  367. if (api_token_1.getOAuthToken()) {
  368. return;
  369. }
  370. else if (options.docker && api_token_1.getDockerToken()) {
  371. options.testDepGraphDockerEndpoint = '/docker-jwt/test-dependencies';
  372. options.isDockerUser = true;
  373. }
  374. else {
  375. throw err;
  376. }
  377. }
  378. }
  379. exports.validateCredentials = validateCredentials;
  380. /***/ }),
  381. /***/ 83476:
  382. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  383. Object.defineProperty(exports, "__esModule", ({ value: true }));
  384. exports.validateTestOptions = void 0;
  385. const theme_1 = __webpack_require__(86988);
  386. const common_1 = __webpack_require__(53110);
  387. const fail_on_error_ts_1 = __webpack_require__(18195);
  388. function validateTestOptions(options) {
  389. if (options.severityThreshold &&
  390. !validateSeverityThreshold(options.severityThreshold)) {
  391. throw new Error('INVALID_SEVERITY_THRESHOLD');
  392. }
  393. if (options.failOn && !validateFailOn(options.failOn)) {
  394. const error = new fail_on_error_ts_1.FailOnError();
  395. throw theme_1.color.status.error(error.message);
  396. }
  397. }
  398. exports.validateTestOptions = validateTestOptions;
  399. function validateSeverityThreshold(severityThreshold) {
  400. return common_1.SEVERITIES.map((s) => s.verboseName).indexOf(severityThreshold) > -1;
  401. }
  402. function validateFailOn(arg) {
  403. return Object.keys(common_1.FAIL_ON).includes(arg);
  404. }
  405. /***/ }),
  406. /***/ 18195:
  407. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  408. Object.defineProperty(exports, "__esModule", ({ value: true }));
  409. exports.FailOnError = void 0;
  410. const custom_error_1 = __webpack_require__(17188);
  411. const common_1 = __webpack_require__(53110);
  412. class FailOnError extends custom_error_1.CustomError {
  413. constructor() {
  414. super(FailOnError.ERROR_MESSAGE);
  415. }
  416. }
  417. exports.FailOnError = FailOnError;
  418. FailOnError.ERROR_MESSAGE = 'Invalid fail on argument, please use one of: ' +
  419. Object.keys(common_1.FAIL_ON).join(' | ');
  420. /***/ }),
  421. /***/ 72571:
  422. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  423. Object.defineProperty(exports, "__esModule", ({ value: true }));
  424. exports.FeatureNotSupportedByEcosystemError = void 0;
  425. const custom_error_1 = __webpack_require__(17188);
  426. class FeatureNotSupportedByEcosystemError extends custom_error_1.CustomError {
  427. constructor(feature, ecosystem) {
  428. super(`Unsupported ecosystem ${ecosystem} for ${feature}.`);
  429. this.code = 422;
  430. this.feature = feature;
  431. this.userMessage = `\`${feature}\` is not supported for ecosystem '${ecosystem}'`;
  432. }
  433. }
  434. exports.FeatureNotSupportedByEcosystemError = FeatureNotSupportedByEcosystemError;
  435. /***/ }),
  436. /***/ 63011:
  437. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  438. Object.defineProperty(exports, "__esModule", ({ value: true }));
  439. exports.hasFeatureFlag = exports.isFeatureFlagSupportedForOrg = void 0;
  440. const request_1 = __webpack_require__(52050);
  441. const api_token_1 = __webpack_require__(95181);
  442. const config_1 = __webpack_require__(25425);
  443. const common_1 = __webpack_require__(53110);
  444. const errors_1 = __webpack_require__(55191);
  445. async function isFeatureFlagSupportedForOrg(featureFlag, org) {
  446. const response = await request_1.makeRequest({
  447. method: 'GET',
  448. headers: {
  449. Authorization: api_token_1.getAuthHeader(),
  450. },
  451. qs: common_1.assembleQueryString({ org }),
  452. url: `${config_1.default.API}/cli-config/feature-flags/${featureFlag}`,
  453. gzip: true,
  454. json: true,
  455. });
  456. return response.body;
  457. }
  458. exports.isFeatureFlagSupportedForOrg = isFeatureFlagSupportedForOrg;
  459. async function hasFeatureFlag(featureFlag, options) {
  460. const { code, error, ok } = await isFeatureFlagSupportedForOrg(featureFlag, options.org);
  461. if (code === 401 || code === 403) {
  462. throw errors_1.AuthFailedError(error, code);
  463. }
  464. return ok;
  465. }
  466. exports.hasFeatureFlag = hasFeatureFlag;
  467. /***/ }),
  468. /***/ 53776:
  469. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  470. Object.defineProperty(exports, "__esModule", ({ value: true }));
  471. exports.extractMeta = exports.groupEntitiesPerScanType = exports.fix = void 0;
  472. const debugLib = __webpack_require__(15158);
  473. const pMap = __webpack_require__(54270);
  474. const ora = __webpack_require__(63395);
  475. const chalk = __webpack_require__(98250);
  476. const outputFormatter = __webpack_require__(70962);
  477. const load_plugin_1 = __webpack_require__(65090);
  478. const partition_by_vulnerable_1 = __webpack_require__(24957);
  479. const error_to_user_message_1 = __webpack_require__(5258);
  480. const total_issues_count_1 = __webpack_require__(41160);
  481. const fixable_issues_1 = __webpack_require__(86635);
  482. const debug = debugLib('snyk-fix:main');
  483. async function fix(entities, options = {
  484. dryRun: false,
  485. quiet: false,
  486. stripAnsi: false,
  487. }) {
  488. debug('Running snyk fix with options:', options);
  489. const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
  490. let resultsByPlugin = {};
  491. const { vulnerable, notVulnerable: nothingToFix, } = await partition_by_vulnerable_1.partitionByVulnerable(entities);
  492. const entitiesPerType = groupEntitiesPerScanType(vulnerable);
  493. const exceptions = {};
  494. await pMap(Object.keys(entitiesPerType), async (scanType) => {
  495. try {
  496. const fixPlugin = load_plugin_1.loadPlugin(scanType);
  497. const results = await fixPlugin(entitiesPerType[scanType], options);
  498. resultsByPlugin = { ...resultsByPlugin, ...results };
  499. }
  500. catch (e) {
  501. debug(`Failed to processes ${scanType}`, e);
  502. exceptions[scanType] = {
  503. originals: entitiesPerType[scanType],
  504. userMessage: error_to_user_message_1.convertErrorToUserMessage(e),
  505. };
  506. }
  507. }, {
  508. concurrency: 3,
  509. });
  510. const fixSummary = await outputFormatter.showResultsSummary(nothingToFix, resultsByPlugin, exceptions, options, entities.length);
  511. const meta = extractMeta(resultsByPlugin, exceptions);
  512. spinner.start();
  513. if (meta.fixed > 0) {
  514. spinner.stopAndPersist({
  515. text: 'Done',
  516. symbol: chalk.green('✔'),
  517. });
  518. }
  519. else {
  520. spinner.stop();
  521. }
  522. return {
  523. results: resultsByPlugin,
  524. exceptions,
  525. fixSummary,
  526. meta,
  527. };
  528. }
  529. exports.fix = fix;
  530. function groupEntitiesPerScanType(entities) {
  531. var _a, _b, _c;
  532. const entitiesPerType = {};
  533. for (const entity of entities) {
  534. // TODO: group all node
  535. 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';
  536. if (entitiesPerType[type]) {
  537. entitiesPerType[type].push(entity);
  538. continue;
  539. }
  540. entitiesPerType[type] = [entity];
  541. }
  542. return entitiesPerType;
  543. }
  544. exports.groupEntitiesPerScanType = groupEntitiesPerScanType;
  545. function extractMeta(resultsByPlugin, exceptions) {
  546. const testResults = outputFormatter.getTestResults(resultsByPlugin, exceptions);
  547. const issueData = testResults.map((i) => i.issuesData);
  548. const failed = outputFormatter.calculateFailed(resultsByPlugin, exceptions);
  549. const fixed = outputFormatter.calculateFixed(resultsByPlugin);
  550. const totalIssueCount = total_issues_count_1.getTotalIssueCount(issueData);
  551. const { count: fixableCount } = fixable_issues_1.hasFixableIssues(testResults);
  552. const fixedIssueCount = outputFormatter.calculateFixedIssues(resultsByPlugin);
  553. return {
  554. fixed,
  555. failed,
  556. totalIssues: totalIssueCount,
  557. fixableIssues: fixableCount,
  558. fixedIssues: fixedIssueCount,
  559. };
  560. }
  561. exports.extractMeta = extractMeta;
  562. //# sourceMappingURL=index.js.map
  563. /***/ }),
  564. /***/ 72353:
  565. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  566. Object.defineProperty(exports, "__esModule", ({ value: true }));
  567. exports.CommandFailedError = void 0;
  568. const custom_error_1 = __webpack_require__(33129);
  569. class CommandFailedError extends custom_error_1.CustomError {
  570. constructor(customMessage, command) {
  571. super(customMessage, custom_error_1.ERROR_CODES.CommandFailed);
  572. this.command = command;
  573. }
  574. }
  575. exports.CommandFailedError = CommandFailedError;
  576. //# sourceMappingURL=command-failed-to-run-error.js.map
  577. /***/ }),
  578. /***/ 75391:
  579. /***/ ((__unused_webpack_module, exports) => {
  580. Object.defineProperty(exports, "__esModule", ({ value: true }));
  581. exports.contactSupportMessage = exports.reTryMessage = void 0;
  582. exports.reTryMessage = 'Tip: Re-run in debug mode to see more information: DEBUG=*snyk* <COMMAND>';
  583. exports.contactSupportMessage = 'If the issue persists contact support@snyk.io';
  584. //# sourceMappingURL=common.js.map
  585. /***/ }),
  586. /***/ 33129:
  587. /***/ ((__unused_webpack_module, exports) => {
  588. Object.defineProperty(exports, "__esModule", ({ value: true }));
  589. exports.ERROR_CODES = exports.CustomError = void 0;
  590. class CustomError extends Error {
  591. constructor(message, errorCode) {
  592. super(message);
  593. this.name = this.constructor.name;
  594. this.innerError = undefined;
  595. this.errorCode = errorCode;
  596. }
  597. }
  598. exports.CustomError = CustomError;
  599. var ERROR_CODES;
  600. (function (ERROR_CODES) {
  601. ERROR_CODES["UnsupportedTypeError"] = "G10";
  602. ERROR_CODES["MissingRemediationData"] = "G11";
  603. ERROR_CODES["MissingFileName"] = "G12";
  604. ERROR_CODES["FailedToParseManifest"] = "G13";
  605. ERROR_CODES["CommandFailed"] = "G14";
  606. ERROR_CODES["NoFixesCouldBeApplied"] = "G15";
  607. })(ERROR_CODES = exports.ERROR_CODES || (exports.ERROR_CODES = {}));
  608. //# sourceMappingURL=custom-error.js.map
  609. /***/ }),
  610. /***/ 5258:
  611. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  612. Object.defineProperty(exports, "__esModule", ({ value: true }));
  613. exports.convertErrorToUserMessage = void 0;
  614. const unsupported_type_error_1 = __webpack_require__(90361);
  615. function convertErrorToUserMessage(error) {
  616. if (error instanceof unsupported_type_error_1.UnsupportedTypeError) {
  617. return `${error.scanType} is not supported.`;
  618. }
  619. return error.message;
  620. }
  621. exports.convertErrorToUserMessage = convertErrorToUserMessage;
  622. //# sourceMappingURL=error-to-user-message.js.map
  623. /***/ }),
  624. /***/ 84657:
  625. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  626. Object.defineProperty(exports, "__esModule", ({ value: true }));
  627. exports.FailedToParseManifest = void 0;
  628. const custom_error_1 = __webpack_require__(33129);
  629. class FailedToParseManifest extends custom_error_1.CustomError {
  630. constructor() {
  631. super('Failed to parse manifest', custom_error_1.ERROR_CODES.FailedToParseManifest);
  632. }
  633. }
  634. exports.FailedToParseManifest = FailedToParseManifest;
  635. //# sourceMappingURL=failed-to-parse-manifest.js.map
  636. /***/ }),
  637. /***/ 86920:
  638. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  639. Object.defineProperty(exports, "__esModule", ({ value: true }));
  640. exports.MissingFileNameError = void 0;
  641. const custom_error_1 = __webpack_require__(33129);
  642. class MissingFileNameError extends custom_error_1.CustomError {
  643. constructor() {
  644. super('Filename is missing from test result', custom_error_1.ERROR_CODES.MissingFileName);
  645. }
  646. }
  647. exports.MissingFileNameError = MissingFileNameError;
  648. //# sourceMappingURL=missing-file-name.js.map
  649. /***/ }),
  650. /***/ 95084:
  651. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  652. Object.defineProperty(exports, "__esModule", ({ value: true }));
  653. exports.MissingRemediationDataError = void 0;
  654. const custom_error_1 = __webpack_require__(33129);
  655. class MissingRemediationDataError extends custom_error_1.CustomError {
  656. constructor() {
  657. super('Remediation data is required to apply fixes', custom_error_1.ERROR_CODES.MissingRemediationData);
  658. }
  659. }
  660. exports.MissingRemediationDataError = MissingRemediationDataError;
  661. //# sourceMappingURL=missing-remediation-data.js.map
  662. /***/ }),
  663. /***/ 80799:
  664. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  665. Object.defineProperty(exports, "__esModule", ({ value: true }));
  666. exports.NoFixesCouldBeAppliedError = void 0;
  667. const custom_error_1 = __webpack_require__(33129);
  668. class NoFixesCouldBeAppliedError extends custom_error_1.CustomError {
  669. constructor(message, tip) {
  670. super(message || 'No fixes could be applied', custom_error_1.ERROR_CODES.NoFixesCouldBeApplied);
  671. this.tip = tip;
  672. }
  673. }
  674. exports.NoFixesCouldBeAppliedError = NoFixesCouldBeAppliedError;
  675. //# sourceMappingURL=no-fixes-applied.js.map
  676. /***/ }),
  677. /***/ 90361:
  678. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  679. Object.defineProperty(exports, "__esModule", ({ value: true }));
  680. exports.UnsupportedTypeError = void 0;
  681. const custom_error_1 = __webpack_require__(33129);
  682. class UnsupportedTypeError extends custom_error_1.CustomError {
  683. constructor(scanType) {
  684. super('Provided scan type is not supported', custom_error_1.ERROR_CODES.UnsupportedTypeError);
  685. this.scanType = scanType;
  686. }
  687. }
  688. exports.UnsupportedTypeError = UnsupportedTypeError;
  689. //# sourceMappingURL=unsupported-type-error.js.map
  690. /***/ }),
  691. /***/ 86635:
  692. /***/ ((__unused_webpack_module, exports) => {
  693. Object.defineProperty(exports, "__esModule", ({ value: true }));
  694. exports.hasFixableIssues = void 0;
  695. function hasFixableIssues(results) {
  696. let hasFixes = false;
  697. let count = 0;
  698. for (const result of Object.values(results)) {
  699. const { remediation } = result;
  700. if (remediation) {
  701. const { upgrade, pin, patch } = remediation;
  702. const upgrades = Object.keys(upgrade);
  703. const pins = Object.keys(pin);
  704. if (pins.length || upgrades.length) {
  705. hasFixes = true;
  706. // pins & upgrades are mutually exclusive
  707. count += getUpgradableIssues(pins.length ? pin : upgrade);
  708. }
  709. const patches = Object.keys(patch);
  710. if (patches.length) {
  711. hasFixes = true;
  712. count += patches.length;
  713. }
  714. }
  715. }
  716. return {
  717. hasFixes,
  718. count,
  719. };
  720. }
  721. exports.hasFixableIssues = hasFixableIssues;
  722. function getUpgradableIssues(updates) {
  723. const issues = [];
  724. for (const id of Object.keys(updates)) {
  725. issues.push(...updates[id].vulns);
  726. }
  727. return issues.length;
  728. }
  729. //# sourceMappingURL=fixable-issues.js.map
  730. /***/ }),
  731. /***/ 29748:
  732. /***/ ((__unused_webpack_module, exports) => {
  733. Object.defineProperty(exports, "__esModule", ({ value: true }));
  734. exports.getIssueCountBySeverity = void 0;
  735. function getIssueCountBySeverity(issueData) {
  736. const total = {
  737. low: [],
  738. medium: [],
  739. high: [],
  740. critical: [],
  741. };
  742. for (const entry of issueData) {
  743. for (const issue of Object.values(entry)) {
  744. const { severity, id } = issue;
  745. total[severity.toLowerCase()].push(id);
  746. }
  747. }
  748. return total;
  749. }
  750. exports.getIssueCountBySeverity = getIssueCountBySeverity;
  751. //# sourceMappingURL=issues-by-severity.js.map
  752. /***/ }),
  753. /***/ 41160:
  754. /***/ ((__unused_webpack_module, exports) => {
  755. Object.defineProperty(exports, "__esModule", ({ value: true }));
  756. exports.getTotalIssueCount = void 0;
  757. function getTotalIssueCount(issueData) {
  758. let total = 0;
  759. for (const entry of issueData) {
  760. total += Object.keys(entry).length;
  761. }
  762. return total;
  763. }
  764. exports.getTotalIssueCount = getTotalIssueCount;
  765. //# sourceMappingURL=total-issues-count.js.map
  766. /***/ }),
  767. /***/ 90686:
  768. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  769. Object.defineProperty(exports, "__esModule", ({ value: true }));
  770. exports.formatDisplayName = void 0;
  771. const pathLib = __webpack_require__(85622);
  772. function formatDisplayName(path, identity) {
  773. if (!identity.targetFile) {
  774. return `${identity.type} project`;
  775. }
  776. // show paths relative to where `snyk fix` is running
  777. return pathLib.relative(process.cwd(), pathLib.join(path, identity.targetFile));
  778. }
  779. exports.formatDisplayName = formatDisplayName;
  780. //# sourceMappingURL=format-display-name.js.map
  781. /***/ }),
  782. /***/ 31998:
  783. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  784. Object.defineProperty(exports, "__esModule", ({ value: true }));
  785. exports.formatFailed = void 0;
  786. const types_1 = __webpack_require__(71538);
  787. const error_to_user_message_1 = __webpack_require__(5258);
  788. const format_with_changes_item_1 = __webpack_require__(38154);
  789. const format_unresolved_item_1 = __webpack_require__(82187);
  790. function formatFailed(failed) {
  791. if (types_1.isWithError(failed)) {
  792. return format_unresolved_item_1.formatUnresolved(failed.original, error_to_user_message_1.convertErrorToUserMessage(failed.error), failed.tip);
  793. }
  794. return format_with_changes_item_1.formatChangesSummary(failed.original, failed.changes);
  795. }
  796. exports.formatFailed = formatFailed;
  797. //# sourceMappingURL=format-failed-item.js.map
  798. /***/ }),
  799. /***/ 82187:
  800. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  801. Object.defineProperty(exports, "__esModule", ({ value: true }));
  802. exports.formatUnresolved = void 0;
  803. const chalk = __webpack_require__(98250);
  804. const format_display_name_1 = __webpack_require__(90686);
  805. const show_results_summary_1 = __webpack_require__(70962);
  806. function formatUnresolved(entity, userMessage, tip) {
  807. const name = format_display_name_1.formatDisplayName(entity.workspace.path, entity.scanResult.identity);
  808. const tipMessage = tip ? `\n${show_results_summary_1.PADDING_SPACE}Tip: ${tip}` : '';
  809. const errorMessage = `${show_results_summary_1.PADDING_SPACE}${name}\n${show_results_summary_1.PADDING_SPACE}${chalk.red('✖')} ${chalk.red(userMessage)}`;
  810. return errorMessage + tipMessage;
  811. }
  812. exports.formatUnresolved = formatUnresolved;
  813. //# sourceMappingURL=format-unresolved-item.js.map
  814. /***/ }),
  815. /***/ 38154:
  816. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  817. Object.defineProperty(exports, "__esModule", ({ value: true }));
  818. exports.formatChangesSummary = void 0;
  819. const chalk = __webpack_require__(98250);
  820. const format_display_name_1 = __webpack_require__(90686);
  821. const show_results_summary_1 = __webpack_require__(70962);
  822. /*
  823. * Generate formatted output that describes what changes were applied, which failed.
  824. */
  825. function formatChangesSummary(entity, changes) {
  826. return `${show_results_summary_1.PADDING_SPACE}${format_display_name_1.formatDisplayName(entity.workspace.path, entity.scanResult.identity)}\n${changes.map((c) => formatAppliedChange(c)).join('\n')}`;
  827. }
  828. exports.formatChangesSummary = formatChangesSummary;
  829. function formatAppliedChange(change) {
  830. if (change.success === true) {
  831. return `${show_results_summary_1.PADDING_SPACE}${chalk.green('✔')} ${change.userMessage}`;
  832. }
  833. if (change.success === false) {
  834. 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}`;
  835. }
  836. return '';
  837. }
  838. //# sourceMappingURL=format-with-changes-item.js.map
  839. /***/ }),
  840. /***/ 70962:
  841. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  842. Object.defineProperty(exports, "__esModule", ({ value: true }));
  843. 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;
  844. const chalk = __webpack_require__(98250);
  845. const stripAnsi = __webpack_require__(71990);
  846. const common_1 = __webpack_require__(75391);
  847. const fixable_issues_1 = __webpack_require__(86635);
  848. const issues_by_severity_1 = __webpack_require__(29748);
  849. const total_issues_count_1 = __webpack_require__(41160);
  850. const format_failed_item_1 = __webpack_require__(31998);
  851. const format_with_changes_item_1 = __webpack_require__(38154);
  852. const format_unresolved_item_1 = __webpack_require__(82187);
  853. exports.PADDING_SPACE = ' '; // 2 spaces
  854. async function showResultsSummary(nothingToFix, resultsByPlugin, exceptions, options, total) {
  855. const successfulFixesSummary = generateSuccessfulFixesSummary(resultsByPlugin);
  856. const { summary: unresolvedSummary, count: unresolvedCount, } = generateUnresolvedSummary(resultsByPlugin, exceptions);
  857. const { summary: overallSummary, count: changedCount, } = generateOverallSummary(resultsByPlugin, exceptions, nothingToFix, options);
  858. const getHelpText = `${common_1.reTryMessage}. ${common_1.contactSupportMessage}`;
  859. // called without any `snyk test` results
  860. if (total === 0) {
  861. const summary = `\n${chalk.red(' ✖ No successful fixes')}`;
  862. return options.stripAnsi ? stripAnsi(summary) : summary;
  863. }
  864. // 100% not vulnerable and had no errors/unsupported
  865. if (nothingToFix.length === total && unresolvedCount === 0) {
  866. const summary = `\n${chalk.green('✔ No vulnerable items to fix')}\n\n${overallSummary}`;
  867. return options.stripAnsi ? stripAnsi(summary) : summary;
  868. }
  869. const summary = `\n${successfulFixesSummary}${unresolvedSummary}${unresolvedCount || changedCount ? `\n\n${overallSummary}` : ''}${unresolvedSummary ? `\n\n${getHelpText}` : ''}`;
  870. return options.stripAnsi ? stripAnsi(summary) : summary;
  871. }
  872. exports.showResultsSummary = showResultsSummary;
  873. function generateSuccessfulFixesSummary(resultsByPlugin) {
  874. const sectionTitle = 'Successful fixes:';
  875. const formattedTitleHeader = `${chalk.bold(sectionTitle)}`;
  876. let summary = '';
  877. for (const plugin of Object.keys(resultsByPlugin)) {
  878. const fixedSuccessfully = resultsByPlugin[plugin].succeeded;
  879. if (fixedSuccessfully.length > 0) {
  880. summary +=
  881. '\n\n' +
  882. fixedSuccessfully
  883. .map((s) => format_with_changes_item_1.formatChangesSummary(s.original, s.changes))
  884. .join('\n\n');
  885. }
  886. }
  887. if (summary) {
  888. return formattedTitleHeader + summary;
  889. }
  890. return chalk.red(' ✖ No successful fixes\n');
  891. }
  892. exports.generateSuccessfulFixesSummary = generateSuccessfulFixesSummary;
  893. function generateUnresolvedSummary(resultsByPlugin, exceptionsByScanType) {
  894. const title = 'Unresolved items:';
  895. const formattedTitle = `${chalk.bold(title)}`;
  896. let summary = '';
  897. let count = 0;
  898. for (const plugin of Object.keys(resultsByPlugin)) {
  899. const skipped = resultsByPlugin[plugin].skipped;
  900. if (skipped.length > 0) {
  901. count += skipped.length;
  902. summary +=
  903. '\n\n' +
  904. skipped
  905. .map((s) => format_unresolved_item_1.formatUnresolved(s.original, s.userMessage))
  906. .join('\n\n');
  907. }
  908. const failed = resultsByPlugin[plugin].failed;
  909. if (failed.length > 0) {
  910. count += failed.length;
  911. summary += '\n\n' + failed.map((s) => format_failed_item_1.formatFailed(s)).join('\n\n');
  912. }
  913. }
  914. if (Object.keys(exceptionsByScanType).length) {
  915. for (const ecosystem of Object.keys(exceptionsByScanType)) {
  916. const unresolved = exceptionsByScanType[ecosystem];
  917. count += unresolved.originals.length;
  918. summary +=
  919. '\n\n' +
  920. unresolved.originals
  921. .map((s) => format_unresolved_item_1.formatUnresolved(s, unresolved.userMessage))
  922. .join('\n\n');
  923. }
  924. }
  925. if (summary) {
  926. return { summary: `\n\n${formattedTitle}${summary}`, count };
  927. }
  928. return { summary: '', count: 0 };
  929. }
  930. exports.generateUnresolvedSummary = generateUnresolvedSummary;
  931. function generateOverallSummary(resultsByPlugin, exceptions, nothingToFix, options) {
  932. const sectionTitle = 'Summary:';
  933. const formattedTitleHeader = `${chalk.bold(sectionTitle)}`;
  934. const fixed = calculateFixed(resultsByPlugin);
  935. const failed = calculateFailed(resultsByPlugin, exceptions);
  936. const dryRunText = options.dryRun
  937. ? chalk.hex('#EDD55E')(`${exports.PADDING_SPACE}Command run in ${chalk.bold('dry run')} mode. Fixes are not applied.\n`)
  938. : '';
  939. const notFixedMessage = failed > 0
  940. ? `${exports.PADDING_SPACE}${chalk.bold.red(failed)} items were not fixed\n`
  941. : '';
  942. const fixedMessage = fixed > 0
  943. ? `${exports.PADDING_SPACE}${chalk.green.bold(fixed)} items were successfully fixed\n`
  944. : '';
  945. const vulnsSummary = generateIssueSummary(resultsByPlugin, exceptions);
  946. const notVulnerableSummary = nothingToFix.length > 0
  947. ? `${exports.PADDING_SPACE}${nothingToFix.length} items were not vulnerable\n`
  948. : '';
  949. return {
  950. summary: `${formattedTitleHeader}\n\n${dryRunText}${notFixedMessage}${fixedMessage}${notVulnerableSummary}${vulnsSummary}`,
  951. count: fixed + failed,
  952. };
  953. }
  954. exports.generateOverallSummary = generateOverallSummary;
  955. function calculateFixed(resultsByPlugin) {
  956. let fixed = 0;
  957. for (const plugin of Object.keys(resultsByPlugin)) {
  958. fixed += resultsByPlugin[plugin].succeeded.length;
  959. }
  960. return fixed;
  961. }
  962. exports.calculateFixed = calculateFixed;
  963. function calculateFixedIssues(resultsByPlugin) {
  964. const fixedIssues = [];
  965. for (const plugin of Object.keys(resultsByPlugin)) {
  966. for (const entity of resultsByPlugin[plugin].succeeded) {
  967. // count unique vulns fixed per scanned entity
  968. // some fixed may need to be made in multiple places
  969. // and would count multiple times otherwise.
  970. const fixedPerEntity = new Set();
  971. entity.changes
  972. .filter((c) => c.success)
  973. .forEach((c) => {
  974. c.issueIds.map((i) => fixedPerEntity.add(i));
  975. });
  976. fixedIssues.push(...Array.from(fixedPerEntity));
  977. }
  978. }
  979. return fixedIssues.length;
  980. }
  981. exports.calculateFixedIssues = calculateFixedIssues;
  982. function calculateFailed(resultsByPlugin, exceptions) {
  983. let failed = 0;
  984. for (const plugin of Object.keys(resultsByPlugin)) {
  985. const results = resultsByPlugin[plugin];
  986. failed += results.failed.length + results.skipped.length;
  987. }
  988. if (Object.keys(exceptions).length) {
  989. for (const ecosystem of Object.keys(exceptions)) {
  990. const unresolved = exceptions[ecosystem];
  991. failed += unresolved.originals.length;
  992. }
  993. }
  994. return failed;
  995. }
  996. exports.calculateFailed = calculateFailed;
  997. function formatIssueCountBySeverity({ critical, high, medium, low, }) {
  998. const summary = [];
  999. if (critical && critical > 0) {
  1000. summary.push(exports.severitiesColourMapping.critical.colorFunc(`${critical} Critical`));
  1001. }
  1002. if (high && high > 0) {
  1003. summary.push(exports.severitiesColourMapping.high.colorFunc(`${high} High`));
  1004. }
  1005. if (medium && medium > 0) {
  1006. summary.push(exports.severitiesColourMapping.medium.colorFunc(`${medium} Medium`));
  1007. }
  1008. if (low && low > 0) {
  1009. summary.push(exports.severitiesColourMapping.low.colorFunc(`${low} Low`));
  1010. }
  1011. return summary.join(' | ');
  1012. }
  1013. exports.formatIssueCountBySeverity = formatIssueCountBySeverity;
  1014. exports.severitiesColourMapping = {
  1015. low: {
  1016. colorFunc(text) {
  1017. return chalk.hex('#BCBBC8')(text);
  1018. },
  1019. },
  1020. medium: {
  1021. colorFunc(text) {
  1022. return chalk.hex('#EDD55E')(text);
  1023. },
  1024. },
  1025. high: {
  1026. colorFunc(text) {
  1027. return chalk.hex('#FF872F')(text);
  1028. },
  1029. },
  1030. critical: {
  1031. colorFunc(text) {
  1032. return chalk.hex('#FF0B0B')(text);
  1033. },
  1034. },
  1035. };
  1036. exports.defaultSeverityColor = {
  1037. colorFunc(text) {
  1038. return chalk.grey(text);
  1039. },
  1040. };
  1041. function getSeveritiesColour(severity) {
  1042. var _a;
  1043. return (_a = exports.severitiesColourMapping[severity]) !== null && _a !== void 0 ? _a : exports.defaultSeverityColor;
  1044. }
  1045. exports.getSeveritiesColour = getSeveritiesColour;
  1046. function generateIssueSummary(resultsByPlugin, exceptions) {
  1047. const testResults = getTestResults(resultsByPlugin, exceptions);
  1048. const issueData = testResults.map((i) => i.issuesData);
  1049. const bySeverity = issues_by_severity_1.getIssueCountBySeverity(issueData);
  1050. const issuesBySeverityMessage = formatIssueCountBySeverity({
  1051. critical: bySeverity.critical.length,
  1052. high: bySeverity.high.length,
  1053. medium: bySeverity.medium.length,
  1054. low: bySeverity.low.length,
  1055. });
  1056. // can't use .flat() or .flatMap() because it's not supported in Node 10
  1057. const issues = [];
  1058. for (const result of testResults) {
  1059. issues.push(...result.issues);
  1060. }
  1061. const totalIssueCount = total_issues_count_1.getTotalIssueCount(issueData);
  1062. let totalIssues = '';
  1063. if (totalIssueCount > 0) {
  1064. totalIssues = `${chalk.bold(totalIssueCount)} issues\n`;
  1065. if (issuesBySeverityMessage) {
  1066. totalIssues = `${chalk.bold(totalIssueCount)} issues: ${issuesBySeverityMessage}\n`;
  1067. }
  1068. }
  1069. const { count: fixableCount } = fixable_issues_1.hasFixableIssues(testResults);
  1070. const fixableIssues = fixableCount > 0 ? `${chalk.bold(fixableCount)} issues are fixable\n` : '';
  1071. const fixedIssueCount = calculateFixedIssues(resultsByPlugin);
  1072. const fixedIssuesSummary = fixedIssueCount > 0
  1073. ? `${chalk.bold(fixedIssueCount)} issues were successfully fixed\n`
  1074. : '';
  1075. return `\n${exports.PADDING_SPACE}${totalIssues}${exports.PADDING_SPACE}${fixableIssues}${exports.PADDING_SPACE}${fixedIssuesSummary}`;
  1076. }
  1077. exports.generateIssueSummary = generateIssueSummary;
  1078. function getTestResults(resultsByPlugin, exceptionsByScanType) {
  1079. const testResults = [];
  1080. for (const plugin of Object.keys(resultsByPlugin)) {
  1081. const { skipped, failed, succeeded } = resultsByPlugin[plugin];
  1082. testResults.push(...skipped.map((i) => i.original.testResult));
  1083. testResults.push(...failed.map((i) => i.original.testResult));
  1084. testResults.push(...succeeded.map((i) => i.original.testResult));
  1085. }
  1086. if (Object.keys(exceptionsByScanType).length) {
  1087. for (const ecosystem of Object.keys(exceptionsByScanType)) {
  1088. const unresolved = exceptionsByScanType[ecosystem];
  1089. testResults.push(...unresolved.originals.map((i) => i.testResult));
  1090. }
  1091. }
  1092. return testResults;
  1093. }
  1094. exports.getTestResults = getTestResults;
  1095. //# sourceMappingURL=show-results-summary.js.map
  1096. /***/ }),
  1097. /***/ 24957:
  1098. /***/ ((__unused_webpack_module, exports) => {
  1099. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1100. exports.partitionByVulnerable = void 0;
  1101. function partitionByVulnerable(entities) {
  1102. const vulnerable = [];
  1103. const notVulnerable = [];
  1104. for (const entity of entities) {
  1105. const hasIssues = entity.testResult.issues.length > 0;
  1106. if (hasIssues) {
  1107. vulnerable.push(entity);
  1108. }
  1109. else {
  1110. notVulnerable.push(entity);
  1111. }
  1112. }
  1113. return { vulnerable, notVulnerable };
  1114. }
  1115. exports.partitionByVulnerable = partitionByVulnerable;
  1116. //# sourceMappingURL=partition-by-vulnerable.js.map
  1117. /***/ }),
  1118. /***/ 65090:
  1119. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1120. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1121. exports.loadPlugin = void 0;
  1122. const unsupported_type_error_1 = __webpack_require__(90361);
  1123. const python_1 = __webpack_require__(97090);
  1124. function loadPlugin(type) {
  1125. switch (type) {
  1126. case 'pip': {
  1127. return python_1.pythonFix;
  1128. }
  1129. case 'poetry': {
  1130. return python_1.pythonFix;
  1131. }
  1132. default: {
  1133. throw new unsupported_type_error_1.UnsupportedTypeError(type);
  1134. }
  1135. }
  1136. }
  1137. exports.loadPlugin = loadPlugin;
  1138. //# sourceMappingURL=load-plugin.js.map
  1139. /***/ }),
  1140. /***/ 96377:
  1141. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1142. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1143. exports.checkPackageToolSupported = void 0;
  1144. const chalk = __webpack_require__(98250);
  1145. const pipenvPipfileFix = __webpack_require__(91989);
  1146. const poetryFix = __webpack_require__(69671);
  1147. const ora = __webpack_require__(63395);
  1148. const supportFunc = {
  1149. pipenv: {
  1150. isInstalled: () => pipenvPipfileFix.isPipenvInstalled(),
  1151. isSupportedVersion: (version) => pipenvPipfileFix.isPipenvSupportedVersion(version),
  1152. },
  1153. poetry: {
  1154. isInstalled: () => poetryFix.isPoetryInstalled(),
  1155. isSupportedVersion: (version) => poetryFix.isPoetrySupportedVersion(version),
  1156. },
  1157. };
  1158. async function checkPackageToolSupported(packageManager, options) {
  1159. const { version } = await supportFunc[packageManager].isInstalled();
  1160. const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
  1161. spinner.clear();
  1162. spinner.text = `Checking ${packageManager} version`;
  1163. spinner.indent = 2;
  1164. spinner.start();
  1165. if (!version) {
  1166. spinner.stopAndPersist({
  1167. text: chalk.hex('#EDD55E')(`Could not detect ${packageManager} version, proceeding anyway. Some operations may fail.`),
  1168. symbol: chalk.hex('#EDD55E')('⚠️'),
  1169. });
  1170. return;
  1171. }
  1172. const { supported, versions } = supportFunc[packageManager].isSupportedVersion(version);
  1173. if (!supported) {
  1174. const spinnerMessage = ` ${version} ${packageManager} version detected. Currently the following ${packageManager} versions are supported: ${versions.join(',')}`;
  1175. spinner.stopAndPersist({
  1176. text: chalk.hex('#EDD55E')(spinnerMessage),
  1177. symbol: chalk.hex('#EDD55E')('⚠️'),
  1178. });
  1179. }
  1180. else {
  1181. spinner.stop();
  1182. }
  1183. }
  1184. exports.checkPackageToolSupported = checkPackageToolSupported;
  1185. //# sourceMappingURL=package-tool-supported.js.map
  1186. /***/ }),
  1187. /***/ 10774:
  1188. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1189. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1190. exports.isRequirementsTxtManifest = exports.getHandlerType = void 0;
  1191. const pathLib = __webpack_require__(85622);
  1192. const supported_handler_types_1 = __webpack_require__(56394);
  1193. function getHandlerType(entity) {
  1194. const targetFile = entity.scanResult.identity.targetFile;
  1195. if (!targetFile) {
  1196. return null;
  1197. }
  1198. const packageManagerOverride = entity.options.packageManager;
  1199. if (packageManagerOverride) {
  1200. return getTypeFromPackageManager(packageManagerOverride);
  1201. }
  1202. const path = pathLib.parse(targetFile);
  1203. if (isRequirementsTxtManifest(targetFile)) {
  1204. return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS;
  1205. }
  1206. else if (['Pipfile'].includes(path.base)) {
  1207. return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.PIPFILE;
  1208. }
  1209. else if (['pyproject.toml', 'poetry.lock'].includes(path.base)) {
  1210. return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY;
  1211. }
  1212. return null;
  1213. }
  1214. exports.getHandlerType = getHandlerType;
  1215. function isRequirementsTxtManifest(targetFile) {
  1216. return targetFile.endsWith('.txt');
  1217. }
  1218. exports.isRequirementsTxtManifest = isRequirementsTxtManifest;
  1219. function getTypeFromPackageManager(packageManager) {
  1220. switch (packageManager) {
  1221. case 'pip':
  1222. return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS;
  1223. case 'poetry':
  1224. return supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY;
  1225. default:
  1226. return null;
  1227. }
  1228. }
  1229. //# sourceMappingURL=get-handler-type.js.map
  1230. /***/ }),
  1231. /***/ 70145:
  1232. /***/ ((__unused_webpack_module, exports) => {
  1233. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1234. exports.isSuccessfulChange = exports.generateSuccessfulChanges = exports.generateFailedChanges = void 0;
  1235. function generateFailedChanges(attemptedUpdates, pins, error, command) {
  1236. const changes = [];
  1237. for (const pkgAtVersion of Object.keys(pins)) {
  1238. const pin = pins[pkgAtVersion];
  1239. if (!attemptedUpdates
  1240. .map((update) => update.replace('==', '@'))
  1241. .includes(pin.upgradeTo)) {
  1242. continue;
  1243. }
  1244. const updatedMessage = pin.isTransitive ? 'pin' : 'upgrade';
  1245. const newVersion = pin.upgradeTo.split('@')[1];
  1246. const [pkgName, version] = pkgAtVersion.split('@');
  1247. changes.push({
  1248. success: false,
  1249. reason: error.message,
  1250. userMessage: `Failed to ${updatedMessage} ${pkgName} from ${version} to ${newVersion}`,
  1251. tip: command ? `Try running \`${command}\`` : undefined,
  1252. issueIds: pin.vulns,
  1253. from: pkgAtVersion,
  1254. to: `${pkgName}@${newVersion}`,
  1255. });
  1256. }
  1257. return changes;
  1258. }
  1259. exports.generateFailedChanges = generateFailedChanges;
  1260. function generateSuccessfulChanges(appliedUpgrades, pins) {
  1261. const changes = [];
  1262. for (const pkgAtVersion of Object.keys(pins)) {
  1263. const pin = pins[pkgAtVersion];
  1264. if (!appliedUpgrades
  1265. .map((upgrade) => upgrade.replace('==', '@'))
  1266. .includes(pin.upgradeTo)) {
  1267. continue;
  1268. }
  1269. const updatedMessage = pin.isTransitive ? 'Pinned' : 'Upgraded';
  1270. const newVersion = pin.upgradeTo.split('@')[1];
  1271. const [pkgName, version] = pkgAtVersion.split('@');
  1272. changes.push({
  1273. success: true,
  1274. userMessage: `${updatedMessage} ${pkgName} from ${version} to ${newVersion}`,
  1275. issueIds: pin.vulns,
  1276. from: pkgAtVersion,
  1277. to: `${pkgName}@${newVersion}`,
  1278. });
  1279. }
  1280. return changes;
  1281. }
  1282. exports.generateSuccessfulChanges = generateSuccessfulChanges;
  1283. function isSuccessfulChange(change) {
  1284. return change.success === true;
  1285. }
  1286. exports.isSuccessfulChange = isSuccessfulChange;
  1287. //# sourceMappingURL=attempted-changes-summary.js.map
  1288. /***/ }),
  1289. /***/ 60174:
  1290. /***/ ((__unused_webpack_module, exports) => {
  1291. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1292. exports.partitionByFixable = exports.isSupported = exports.projectTypeSupported = void 0;
  1293. function projectTypeSupported(res) {
  1294. return !('reason' in res);
  1295. }
  1296. exports.projectTypeSupported = projectTypeSupported;
  1297. async function isSupported(entity) {
  1298. const remediationData = entity.testResult.remediation;
  1299. if (!remediationData) {
  1300. return { supported: false, reason: 'No remediation data available' };
  1301. }
  1302. if (!remediationData.pin || Object.keys(remediationData.pin).length === 0) {
  1303. return {
  1304. supported: false,
  1305. reason: 'There is no actionable remediation to apply',
  1306. };
  1307. }
  1308. return { supported: true };
  1309. }
  1310. exports.isSupported = isSupported;
  1311. async function partitionByFixable(entities) {
  1312. const fixable = [];
  1313. const skipped = [];
  1314. for (const entity of entities) {
  1315. const isSupportedResponse = await isSupported(entity);
  1316. if (projectTypeSupported(isSupportedResponse)) {
  1317. fixable.push(entity);
  1318. continue;
  1319. }
  1320. skipped.push({
  1321. original: entity,
  1322. userMessage: isSupportedResponse.reason,
  1323. });
  1324. }
  1325. return { fixable, skipped };
  1326. }
  1327. exports.partitionByFixable = partitionByFixable;
  1328. //# sourceMappingURL=is-supported.js.map
  1329. /***/ }),
  1330. /***/ 9744:
  1331. /***/ ((__unused_webpack_module, exports) => {
  1332. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1333. exports.containsRequireDirective = void 0;
  1334. /* Requires like -r, -c are not supported at the moment, as multiple files
  1335. * would have to be identified and fixed together
  1336. * https://pip.pypa.io/en/stable/reference/pip_install/#options
  1337. */
  1338. async function containsRequireDirective(requirementsTxt) {
  1339. const allMatches = [];
  1340. const REQUIRE_PATTERN = new RegExp(/^[^\S\n]*-(r|c)\s+(.+)/, 'gm');
  1341. const matches = getAllMatchedGroups(REQUIRE_PATTERN, requirementsTxt);
  1342. for (const match of matches) {
  1343. if (match && match.length > 1) {
  1344. allMatches.push(match);
  1345. }
  1346. }
  1347. return { containsRequire: allMatches.length > 0, matches: allMatches };
  1348. }
  1349. exports.containsRequireDirective = containsRequireDirective;
  1350. function getAllMatchedGroups(re, str) {
  1351. const groups = [];
  1352. let match;
  1353. while ((match = re.exec(str))) {
  1354. groups.push(match);
  1355. }
  1356. return groups;
  1357. }
  1358. //# sourceMappingURL=contains-require-directive.js.map
  1359. /***/ }),
  1360. /***/ 85844:
  1361. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1362. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1363. exports.extractProvenance = void 0;
  1364. const path = __webpack_require__(85622);
  1365. const debugLib = __webpack_require__(15158);
  1366. const requirements_file_parser_1 = __webpack_require__(67285);
  1367. const contains_require_directive_1 = __webpack_require__(9744);
  1368. const debug = debugLib('snyk-fix:python:extract-version-provenance');
  1369. async function extractProvenance(workspace, rootDir, dir, fileName, provenance = {}) {
  1370. const requirementsFileName = path.join(dir, fileName);
  1371. const requirementsTxt = await workspace.readFile(requirementsFileName);
  1372. // keep all provenance paths with `/` as a separator
  1373. const relativeTargetFileName = path
  1374. .normalize(path.relative(rootDir, requirementsFileName))
  1375. .replace(path.sep, '/');
  1376. provenance = {
  1377. ...provenance,
  1378. [relativeTargetFileName]: requirements_file_parser_1.parseRequirementsFile(requirementsTxt),
  1379. };
  1380. const { containsRequire, matches } = await contains_require_directive_1.containsRequireDirective(requirementsTxt);
  1381. if (containsRequire) {
  1382. for (const match of matches) {
  1383. const requiredFilePath = match[2];
  1384. if (provenance[requiredFilePath]) {
  1385. debug('Detected recursive require directive, skipping');
  1386. continue;
  1387. }
  1388. const { dir: requireDir, base } = path.parse(path.join(dir, requiredFilePath));
  1389. provenance = {
  1390. ...provenance,
  1391. ...(await extractProvenance(workspace, rootDir, requireDir, base, provenance)),
  1392. };
  1393. }
  1394. }
  1395. return provenance;
  1396. }
  1397. exports.extractProvenance = extractProvenance;
  1398. //# sourceMappingURL=extract-version-provenance.js.map
  1399. /***/ }),
  1400. /***/ 81065:
  1401. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1402. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1403. exports.selectFileForPinning = exports.applyAllFixes = exports.fixIndividualRequirementsTxt = exports.pipRequirementsTxt = void 0;
  1404. const debugLib = __webpack_require__(15158);
  1405. const pathLib = __webpack_require__(85622);
  1406. const sortBy = __webpack_require__(58254);
  1407. const groupBy = __webpack_require__(20276);
  1408. const update_dependencies_1 = __webpack_require__(5860);
  1409. const no_fixes_applied_1 = __webpack_require__(80799);
  1410. const extract_version_provenance_1 = __webpack_require__(85844);
  1411. const requirements_file_parser_1 = __webpack_require__(67285);
  1412. const standardize_package_name_1 = __webpack_require__(78078);
  1413. const contains_require_directive_1 = __webpack_require__(9744);
  1414. const validate_required_data_1 = __webpack_require__(57894);
  1415. const format_display_name_1 = __webpack_require__(90686);
  1416. const debug = debugLib('snyk-fix:python:requirements.txt');
  1417. async function pipRequirementsTxt(fixable, options) {
  1418. debug(`Preparing to fix ${fixable.length} Python requirements.txt projects`);
  1419. const handlerResult = {
  1420. succeeded: [],
  1421. failed: [],
  1422. skipped: [],
  1423. };
  1424. const ordered = sortByDirectory(fixable);
  1425. let fixedFilesCache = {};
  1426. for (const dir of Object.keys(ordered)) {
  1427. debug(`Fixing entities in directory ${dir}`);
  1428. const entitiesPerDirectory = ordered[dir].map((e) => e.entity);
  1429. const { failed, succeeded, skipped, fixedCache } = await fixAll(entitiesPerDirectory, options, fixedFilesCache);
  1430. fixedFilesCache = {
  1431. ...fixedFilesCache,
  1432. ...fixedCache,
  1433. };
  1434. handlerResult.succeeded.push(...succeeded);
  1435. handlerResult.failed.push(...failed);
  1436. handlerResult.skipped.push(...skipped);
  1437. }
  1438. return handlerResult;
  1439. }
  1440. exports.pipRequirementsTxt = pipRequirementsTxt;
  1441. async function fixAll(entities, options, fixedCache) {
  1442. const handlerResult = {
  1443. succeeded: [],
  1444. failed: [],
  1445. skipped: [],
  1446. };
  1447. for (const entity of entities) {
  1448. const targetFile = entity.scanResult.identity.targetFile;
  1449. try {
  1450. const { dir, base } = pathLib.parse(targetFile);
  1451. // parse & join again to support correct separator
  1452. const filePath = pathLib.normalize(pathLib.join(dir, base));
  1453. if (Object.keys(fixedCache).includes(pathLib.normalize(pathLib.join(dir, base)))) {
  1454. handlerResult.succeeded.push({
  1455. original: entity,
  1456. changes: [
  1457. {
  1458. success: true,
  1459. userMessage: `Fixed through ${format_display_name_1.formatDisplayName(entity.workspace.path, {
  1460. type: entity.scanResult.identity.type,
  1461. targetFile: fixedCache[filePath].fixedIn,
  1462. })}`,
  1463. issueIds: getFixedEntityIssues(fixedCache[filePath].issueIds, entity.testResult.issues),
  1464. },
  1465. ],
  1466. });
  1467. continue;
  1468. }
  1469. const { changes, fixedMeta } = await applyAllFixes(entity, options);
  1470. if (!changes.length) {
  1471. debug('Manifest has not changed!');
  1472. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  1473. }
  1474. // keep issues were successfully fixed unique across files that are part of the same project
  1475. // the test result is for 1 entry entity.
  1476. const uniqueIssueIds = new Set();
  1477. for (const c of changes) {
  1478. c.issueIds.map((i) => uniqueIssueIds.add(i));
  1479. }
  1480. Object.keys(fixedMeta).forEach((f) => {
  1481. fixedCache[f] = {
  1482. fixedIn: targetFile,
  1483. issueIds: Array.from(uniqueIssueIds),
  1484. };
  1485. });
  1486. handlerResult.succeeded.push({ original: entity, changes });
  1487. }
  1488. catch (e) {
  1489. debug(`Failed to fix ${targetFile}.\nERROR: ${e}`);
  1490. handlerResult.failed.push({ original: entity, error: e });
  1491. }
  1492. }
  1493. return { ...handlerResult, fixedCache };
  1494. }
  1495. // TODO: optionally verify the deps install
  1496. async function fixIndividualRequirementsTxt(workspace, dir, entryFileName, fileName, remediation, parsedRequirements, options, directUpgradesOnly) {
  1497. const entryFilePath = pathLib.normalize(pathLib.join(dir, entryFileName));
  1498. const fullFilePath = pathLib.normalize(pathLib.join(dir, fileName));
  1499. const { updatedManifest, changes } = update_dependencies_1.updateDependencies(parsedRequirements, remediation.pin, directUpgradesOnly, entryFilePath !== fullFilePath
  1500. ? format_display_name_1.formatDisplayName(workspace.path, {
  1501. type: 'pip',
  1502. targetFile: fullFilePath,
  1503. })
  1504. : undefined);
  1505. if (!changes.length) {
  1506. return { changes };
  1507. }
  1508. if (!options.dryRun) {
  1509. debug('Writing changes to file');
  1510. await workspace.writeFile(pathLib.join(dir, fileName), updatedManifest);
  1511. }
  1512. else {
  1513. debug('Skipping writing changes to file in --dry-run mode');
  1514. }
  1515. return { changes };
  1516. }
  1517. exports.fixIndividualRequirementsTxt = fixIndividualRequirementsTxt;
  1518. async function applyAllFixes(entity, options) {
  1519. const { remediation, targetFile: entryFileName, workspace, } = validate_required_data_1.validateRequiredData(entity);
  1520. const fixedMeta = {};
  1521. const { dir, base } = pathLib.parse(entryFileName);
  1522. const provenance = await extract_version_provenance_1.extractProvenance(workspace, dir, dir, base);
  1523. const upgradeChanges = [];
  1524. /* Apply all upgrades first across all files that are included */
  1525. for (const fileName of Object.keys(provenance)) {
  1526. const skipApplyingPins = true;
  1527. const { changes } = await fixIndividualRequirementsTxt(workspace, dir, base, fileName, remediation, provenance[fileName], options, skipApplyingPins);
  1528. upgradeChanges.push(...changes);
  1529. fixedMeta[pathLib.normalize(pathLib.join(dir, fileName))] = upgradeChanges;
  1530. }
  1531. /* Apply all left over remediation as pins in the entry targetFile */
  1532. const toPin = filterOutAppliedUpgrades(remediation, upgradeChanges);
  1533. const directUpgradesOnly = false;
  1534. const fileForPinning = await selectFileForPinning(entity);
  1535. const { changes: pinnedChanges } = await fixIndividualRequirementsTxt(workspace, dir, base, fileForPinning.fileName, toPin, requirements_file_parser_1.parseRequirementsFile(fileForPinning.fileContent), options, directUpgradesOnly);
  1536. return { changes: [...upgradeChanges, ...pinnedChanges], fixedMeta };
  1537. }
  1538. exports.applyAllFixes = applyAllFixes;
  1539. function filterOutAppliedUpgrades(remediation, upgradeChanges) {
  1540. const pinRemediation = {
  1541. ...remediation,
  1542. pin: {},
  1543. };
  1544. const pins = remediation.pin;
  1545. const normalizedAppliedRemediation = upgradeChanges
  1546. .map((c) => {
  1547. var _a;
  1548. if (c.success && c.from) {
  1549. const [pkgName, versionAndMore] = (_a = c.from) === null || _a === void 0 ? void 0 : _a.split('@');
  1550. return `${standardize_package_name_1.standardizePackageName(pkgName)}@${versionAndMore}`;
  1551. }
  1552. return false;
  1553. })
  1554. .filter(Boolean);
  1555. for (const pkgAtVersion of Object.keys(pins)) {
  1556. const [pkgName, versionAndMore] = pkgAtVersion.split('@');
  1557. if (!normalizedAppliedRemediation.includes(`${standardize_package_name_1.standardizePackageName(pkgName)}@${versionAndMore}`)) {
  1558. pinRemediation.pin[pkgAtVersion] = pins[pkgAtVersion];
  1559. }
  1560. }
  1561. return pinRemediation;
  1562. }
  1563. function sortByDirectory(entities) {
  1564. const mapped = entities.map((e) => ({
  1565. entity: e,
  1566. ...pathLib.parse(e.scanResult.identity.targetFile),
  1567. }));
  1568. const sorted = sortBy(mapped, 'dir');
  1569. return groupBy(sorted, 'dir');
  1570. }
  1571. async function selectFileForPinning(entity) {
  1572. const targetFile = entity.scanResult.identity.targetFile;
  1573. const { dir, base } = pathLib.parse(targetFile);
  1574. const { workspace } = entity;
  1575. // default to adding pins in the scanned file
  1576. let fileName = base;
  1577. let requirementsTxt = await workspace.readFile(targetFile);
  1578. const { containsRequire, matches } = await contains_require_directive_1.containsRequireDirective(requirementsTxt);
  1579. const constraintsMatch = matches.filter((m) => m.includes('c'));
  1580. if (containsRequire && constraintsMatch[0]) {
  1581. // prefer to pin in constraints file if present
  1582. fileName = constraintsMatch[0][2];
  1583. requirementsTxt = await workspace.readFile(pathLib.join(dir, fileName));
  1584. }
  1585. return { fileContent: requirementsTxt, fileName };
  1586. }
  1587. exports.selectFileForPinning = selectFileForPinning;
  1588. function getFixedEntityIssues(fixedIssueIds, issues) {
  1589. const fixed = [];
  1590. for (const { issueId } of issues) {
  1591. if (fixedIssueIds.includes(issueId)) {
  1592. fixed.push(issueId);
  1593. }
  1594. }
  1595. return fixed;
  1596. }
  1597. //# sourceMappingURL=index.js.map
  1598. /***/ }),
  1599. /***/ 57584:
  1600. /***/ ((__unused_webpack_module, exports) => {
  1601. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1602. exports.applyUpgrades = void 0;
  1603. function applyUpgrades(originalRequirements, upgradedRequirements) {
  1604. const updated = [];
  1605. for (const requirement of originalRequirements) {
  1606. const { originalText } = requirement;
  1607. if (upgradedRequirements[originalText]) {
  1608. updated.push(upgradedRequirements[originalText]);
  1609. }
  1610. else {
  1611. updated.push(originalText);
  1612. }
  1613. }
  1614. return updated;
  1615. }
  1616. exports.applyUpgrades = applyUpgrades;
  1617. //# sourceMappingURL=apply-upgrades.js.map
  1618. /***/ }),
  1619. /***/ 40853:
  1620. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1621. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1622. exports.calculateRelevantFixes = void 0;
  1623. const is_defined_1 = __webpack_require__(38122);
  1624. const standardize_package_name_1 = __webpack_require__(78078);
  1625. function calculateRelevantFixes(requirements, updates, type) {
  1626. const lowerCasedUpdates = {};
  1627. const topLevelDeps = requirements.map(({ name }) => name).filter(is_defined_1.isDefined);
  1628. Object.keys(updates).forEach((update) => {
  1629. const { upgradeTo } = updates[update];
  1630. const [pkgName] = update.split('@');
  1631. const isTransitive = topLevelDeps.indexOf(standardize_package_name_1.standardizePackageName(pkgName)) < 0;
  1632. if (type === 'transitive-pins' ? isTransitive : !isTransitive) {
  1633. const [name, newVersion] = upgradeTo.split('@');
  1634. lowerCasedUpdates[update] = {
  1635. ...updates[update],
  1636. upgradeTo: `${standardize_package_name_1.standardizePackageName(name)}@${newVersion}`,
  1637. };
  1638. }
  1639. });
  1640. return lowerCasedUpdates;
  1641. }
  1642. exports.calculateRelevantFixes = calculateRelevantFixes;
  1643. //# sourceMappingURL=calculate-relevant-fixes.js.map
  1644. /***/ }),
  1645. /***/ 2694:
  1646. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1647. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1648. exports.generatePins = void 0;
  1649. const calculate_relevant_fixes_1 = __webpack_require__(40853);
  1650. const is_defined_1 = __webpack_require__(38122);
  1651. const standardize_package_name_1 = __webpack_require__(78078);
  1652. function generatePins(requirements, updates, referenceFileInChanges) {
  1653. // Lowercase the upgrades object. This might be overly defensive, given that
  1654. // we control this input internally, but its a low cost guard rail. Outputs a
  1655. // mapping of upgrade to -> from, instead of the nested upgradeTo object.
  1656. const standardizedPins = calculate_relevant_fixes_1.calculateRelevantFixes(requirements, updates, 'transitive-pins');
  1657. if (Object.keys(standardizedPins).length === 0) {
  1658. return {
  1659. pinnedRequirements: [],
  1660. changes: [],
  1661. };
  1662. }
  1663. const changes = [];
  1664. const pinnedRequirements = Object.keys(standardizedPins)
  1665. .map((pkgNameAtVersion) => {
  1666. const [pkgName, version] = pkgNameAtVersion.split('@');
  1667. const newVersion = standardizedPins[pkgNameAtVersion].upgradeTo.split('@')[1];
  1668. const newRequirement = `${standardize_package_name_1.standardizePackageName(pkgName)}>=${newVersion}`;
  1669. changes.push({
  1670. from: `${pkgName}@${version}`,
  1671. to: `${pkgName}@${newVersion}`,
  1672. issueIds: standardizedPins[pkgNameAtVersion].vulns,
  1673. success: true,
  1674. userMessage: `Pinned ${standardize_package_name_1.standardizePackageName(pkgName)} from ${version} to ${newVersion}${referenceFileInChanges ? ` (pinned in ${referenceFileInChanges})` : ''}`,
  1675. });
  1676. return `${newRequirement} # not directly required, pinned by Snyk to avoid a vulnerability`;
  1677. })
  1678. .filter(is_defined_1.isDefined);
  1679. return {
  1680. pinnedRequirements,
  1681. changes,
  1682. };
  1683. }
  1684. exports.generatePins = generatePins;
  1685. //# sourceMappingURL=generate-pins.js.map
  1686. /***/ }),
  1687. /***/ 86047:
  1688. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1689. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1690. exports.generateUpgrades = void 0;
  1691. const standardize_package_name_1 = __webpack_require__(78078);
  1692. const calculate_relevant_fixes_1 = __webpack_require__(40853);
  1693. function generateUpgrades(requirements, updates, referenceFileInChanges) {
  1694. // Lowercase the upgrades object. This might be overly defensive, given that
  1695. // we control this input internally, but its a low cost guard rail. Outputs a
  1696. // mapping of upgrade to -> from, instead of the nested upgradeTo object.
  1697. const normalizedUpgrades = calculate_relevant_fixes_1.calculateRelevantFixes(requirements, updates, 'direct-upgrades');
  1698. if (Object.keys(normalizedUpgrades).length === 0) {
  1699. return {
  1700. updatedRequirements: {},
  1701. changes: [],
  1702. };
  1703. }
  1704. const changes = [];
  1705. const updatedRequirements = {};
  1706. requirements.map(({ name, originalName, versionComparator, version, originalText, extras, }) => {
  1707. // Defensive patching; if any of these are undefined, return
  1708. if (typeof name === 'undefined' ||
  1709. typeof versionComparator === 'undefined' ||
  1710. typeof version === 'undefined' ||
  1711. originalText === '') {
  1712. return;
  1713. }
  1714. // Check if we have an upgrade; if we do, replace the version string with
  1715. // the upgrade, but keep the rest of the content
  1716. const upgrade = Object.keys(normalizedUpgrades).filter((packageVersionUpgrade) => {
  1717. const [pkgName, versionAndMore] = packageVersionUpgrade.split('@');
  1718. return `${standardize_package_name_1.standardizePackageName(pkgName)}@${versionAndMore}`.startsWith(`${standardize_package_name_1.standardizePackageName(name)}@${version}`);
  1719. })[0];
  1720. if (!upgrade) {
  1721. return;
  1722. }
  1723. const newVersion = normalizedUpgrades[upgrade].upgradeTo.split('@')[1];
  1724. const updatedRequirement = `${originalName}${versionComparator}${newVersion}`;
  1725. changes.push({
  1726. issueIds: normalizedUpgrades[upgrade].vulns,
  1727. from: `${originalName}@${version}`,
  1728. to: `${originalName}@${newVersion}`,
  1729. success: true,
  1730. userMessage: `Upgraded ${originalName} from ${version} to ${newVersion}${referenceFileInChanges
  1731. ? ` (upgraded in ${referenceFileInChanges})`
  1732. : ''}`,
  1733. });
  1734. updatedRequirements[originalText] = `${updatedRequirement}${extras ? extras : ''}`;
  1735. });
  1736. return {
  1737. updatedRequirements,
  1738. changes,
  1739. };
  1740. }
  1741. exports.generateUpgrades = generateUpgrades;
  1742. //# sourceMappingURL=generate-upgrades.js.map
  1743. /***/ }),
  1744. /***/ 5860:
  1745. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1746. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1747. exports.updateDependencies = void 0;
  1748. const debugLib = __webpack_require__(15158);
  1749. const generate_pins_1 = __webpack_require__(2694);
  1750. const apply_upgrades_1 = __webpack_require__(57584);
  1751. const generate_upgrades_1 = __webpack_require__(86047);
  1752. const failed_to_parse_manifest_1 = __webpack_require__(84657);
  1753. const debug = debugLib('snyk-fix:python:update-dependencies');
  1754. /*
  1755. * Given contents of manifest file(s) and a set of upgrades, apply the given
  1756. * upgrades to a manifest and return the upgraded manifest.
  1757. *
  1758. * Currently only supported for `requirements.txt` - at least one file named
  1759. * `requirements.txt` must be in the manifests.
  1760. */
  1761. function updateDependencies(parsedRequirementsData, updates, directUpgradesOnly = false, referenceFileInChanges) {
  1762. const { requirements, endsWithNewLine: shouldEndWithNewLine, } = parsedRequirementsData;
  1763. if (!requirements.length) {
  1764. debug('Error: Expected to receive parsed manifest data. Is manifest empty?');
  1765. throw new failed_to_parse_manifest_1.FailedToParseManifest();
  1766. }
  1767. debug('Finished parsing manifest');
  1768. const { updatedRequirements, changes: upgradedChanges } = generate_upgrades_1.generateUpgrades(requirements, updates, referenceFileInChanges);
  1769. debug('Finished generating upgrades to apply');
  1770. let pinnedRequirements = [];
  1771. let pinChanges = [];
  1772. if (!directUpgradesOnly) {
  1773. ({ pinnedRequirements, changes: pinChanges } = generate_pins_1.generatePins(requirements, updates, referenceFileInChanges));
  1774. debug('Finished generating pins to apply');
  1775. }
  1776. let updatedManifest = [
  1777. ...apply_upgrades_1.applyUpgrades(requirements, updatedRequirements),
  1778. ...pinnedRequirements,
  1779. ].join('\n');
  1780. // This is a bit of a hack, but an easy one to follow. If a file ends with a
  1781. // new line, ensure we keep it this way. Don't hijack customers formatting.
  1782. if (shouldEndWithNewLine) {
  1783. updatedManifest += '\n';
  1784. }
  1785. debug('Finished applying changes to manifest');
  1786. return {
  1787. updatedManifest,
  1788. changes: [...pinChanges, ...upgradedChanges],
  1789. };
  1790. }
  1791. exports.updateDependencies = updateDependencies;
  1792. //# sourceMappingURL=index.js.map
  1793. /***/ }),
  1794. /***/ 38122:
  1795. /***/ ((__unused_webpack_module, exports) => {
  1796. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1797. exports.isDefined = void 0;
  1798. // TS is not capable of determining when Array.filter has removed undefined
  1799. // values without a manual Type Guard, so thats what this does
  1800. function isDefined(t) {
  1801. return typeof t !== 'undefined';
  1802. }
  1803. exports.isDefined = isDefined;
  1804. //# sourceMappingURL=is-defined.js.map
  1805. /***/ }),
  1806. /***/ 67285:
  1807. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1808. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1809. exports.parseRequirementsFile = void 0;
  1810. const debugLib = __webpack_require__(15158);
  1811. const standardize_package_name_1 = __webpack_require__(78078);
  1812. const debug = debugLib('snyk-fix:python:requirements-file-parser');
  1813. function parseRequirementsFile(requirementsFile) {
  1814. const endsWithNewLine = requirementsFile.endsWith('\n');
  1815. const lines = requirementsFile.replace(/\n$/, '').split('\n');
  1816. const requirements = [];
  1817. lines.map((requirementText, line) => {
  1818. const requirement = extractDependencyDataFromLine(requirementText, line);
  1819. if (requirement) {
  1820. requirements.push(requirement);
  1821. }
  1822. });
  1823. return { requirements, endsWithNewLine };
  1824. }
  1825. exports.parseRequirementsFile = parseRequirementsFile;
  1826. function extractDependencyDataFromLine(requirementText, line) {
  1827. try {
  1828. const requirement = { originalText: requirementText, line };
  1829. const trimmedText = requirementText.trim();
  1830. // Quick returns for cases we cannot remediate
  1831. // - Empty line i.e. ''
  1832. // - 'editable' packages i.e. '-e git://git.myproject.org/MyProject.git#egg=MyProject'
  1833. // - Comments i.e. # This is a comment
  1834. // - Local files i.e. file:../../lib/project#egg=MyProject
  1835. if (requirementText === '' ||
  1836. trimmedText.startsWith('-e') ||
  1837. trimmedText.startsWith('#') ||
  1838. trimmedText.startsWith('file:')) {
  1839. return requirement;
  1840. }
  1841. // Regex to match against a Python package specifier. Any invalid lines (or
  1842. // lines we can't handle) should have been returned this point.
  1843. const regex = /([A-Z0-9-._]*)(!=|===|==|>=|<=|>|<|~=)(\d*\.?\d*\.?\d*[A-Z0-9]*)(.*)/i;
  1844. const result = regex.exec(requirementText);
  1845. if (result !== null) {
  1846. requirement.name = standardize_package_name_1.standardizePackageName(result[1]);
  1847. requirement.originalName = result[1];
  1848. requirement.versionComparator = result[2];
  1849. requirement.version = result[3];
  1850. requirement.extras = result[4];
  1851. }
  1852. if (!(requirement.version && requirement.name)) {
  1853. throw new Error('Failed to extract dependency data');
  1854. }
  1855. return requirement;
  1856. }
  1857. catch (err) {
  1858. debug({ error: err.message, requirementText, line }, 'failed to parse requirement');
  1859. return { originalText: requirementText, line };
  1860. }
  1861. }
  1862. //# sourceMappingURL=requirements-file-parser.js.map
  1863. /***/ }),
  1864. /***/ 28006:
  1865. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1866. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1867. exports.pipenvPipfile = void 0;
  1868. const debugLib = __webpack_require__(15158);
  1869. const ora = __webpack_require__(63395);
  1870. const package_tool_supported_1 = __webpack_require__(96377);
  1871. const update_dependencies_1 = __webpack_require__(21110);
  1872. const debug = debugLib('snyk-fix:python:Pipfile');
  1873. async function pipenvPipfile(fixable, options) {
  1874. debug(`Preparing to fix ${fixable.length} Python Pipfile projects`);
  1875. const handlerResult = {
  1876. succeeded: [],
  1877. failed: [],
  1878. skipped: [],
  1879. };
  1880. await package_tool_supported_1.checkPackageToolSupported('pipenv', options);
  1881. for (const [index, entity] of fixable.entries()) {
  1882. const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
  1883. const spinnerMessage = `Fixing Pipfile ${index + 1}/${fixable.length}`;
  1884. spinner.text = spinnerMessage;
  1885. spinner.start();
  1886. const { failed, succeeded, skipped } = await update_dependencies_1.updateDependencies(entity, options);
  1887. handlerResult.succeeded.push(...succeeded);
  1888. handlerResult.failed.push(...failed);
  1889. handlerResult.skipped.push(...skipped);
  1890. spinner.stop();
  1891. }
  1892. return handlerResult;
  1893. }
  1894. exports.pipenvPipfile = pipenvPipfile;
  1895. //# sourceMappingURL=index.js.map
  1896. /***/ }),
  1897. /***/ 13755:
  1898. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1899. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1900. exports.generateUpgrades = void 0;
  1901. const standardize_package_name_1 = __webpack_require__(78078);
  1902. const validate_required_data_1 = __webpack_require__(57894);
  1903. function generateUpgrades(entity) {
  1904. const { remediation } = validate_required_data_1.validateRequiredData(entity);
  1905. const { pin: pins } = remediation;
  1906. const upgrades = [];
  1907. for (const pkgAtVersion of Object.keys(pins)) {
  1908. const pin = pins[pkgAtVersion];
  1909. const newVersion = pin.upgradeTo.split('@')[1];
  1910. const [pkgName] = pkgAtVersion.split('@');
  1911. upgrades.push(`${standardize_package_name_1.standardizePackageName(pkgName)}==${newVersion}`);
  1912. }
  1913. return { upgrades };
  1914. }
  1915. exports.generateUpgrades = generateUpgrades;
  1916. //# sourceMappingURL=generate-upgrades.js.map
  1917. /***/ }),
  1918. /***/ 21110:
  1919. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  1920. Object.defineProperty(exports, "__esModule", ({ value: true }));
  1921. exports.updateDependencies = void 0;
  1922. const debugLib = __webpack_require__(15158);
  1923. const no_fixes_applied_1 = __webpack_require__(80799);
  1924. const generate_upgrades_1 = __webpack_require__(13755);
  1925. const pipenv_add_1 = __webpack_require__(22629);
  1926. const attempted_changes_summary_1 = __webpack_require__(70145);
  1927. const debug = debugLib('snyk-fix:python:Pipfile');
  1928. function chooseFixStrategy(options) {
  1929. return options.sequentialFix ? fixSequentially : fixAll;
  1930. }
  1931. async function updateDependencies(entity, options) {
  1932. const handlerResult = await chooseFixStrategy(options)(entity, options);
  1933. return handlerResult;
  1934. }
  1935. exports.updateDependencies = updateDependencies;
  1936. async function fixAll(entity, options) {
  1937. const handlerResult = {
  1938. succeeded: [],
  1939. failed: [],
  1940. skipped: [],
  1941. };
  1942. const changes = [];
  1943. try {
  1944. const { upgrades } = await generate_upgrades_1.generateUpgrades(entity);
  1945. if (!upgrades.length) {
  1946. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError('Failed to calculate package updates to apply');
  1947. }
  1948. // TODO: for better support we need to:
  1949. // 1. parse the manifest and extract original requirements, version spec etc
  1950. // 2. swap out only the version and retain original spec
  1951. // 3. re-lock the lockfile
  1952. // Currently this is not possible as there is no Pipfile parser that would do this.
  1953. // update prod dependencies first
  1954. if (upgrades.length) {
  1955. changes.push(...(await pipenv_add_1.pipenvAdd(entity, options, upgrades)));
  1956. }
  1957. if (!changes.length) {
  1958. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  1959. }
  1960. if (!changes.some((c) => attempted_changes_summary_1.isSuccessfulChange(c))) {
  1961. handlerResult.failed.push({
  1962. original: entity,
  1963. changes,
  1964. });
  1965. }
  1966. else {
  1967. handlerResult.succeeded.push({
  1968. original: entity,
  1969. changes,
  1970. });
  1971. }
  1972. }
  1973. catch (error) {
  1974. debug(`Failed to fix ${entity.scanResult.identity.targetFile}.\nERROR: ${error}`);
  1975. handlerResult.failed.push({
  1976. original: entity,
  1977. error,
  1978. tip: error.tip,
  1979. });
  1980. }
  1981. return handlerResult;
  1982. }
  1983. async function fixSequentially(entity, options) {
  1984. const handlerResult = {
  1985. succeeded: [],
  1986. failed: [],
  1987. skipped: [],
  1988. };
  1989. const { upgrades } = await generate_upgrades_1.generateUpgrades(entity);
  1990. // TODO: for better support we need to:
  1991. // 1. parse the manifest and extract original requirements, version spec etc
  1992. // 2. swap out only the version and retain original spec
  1993. // 3. re-lock the lockfile
  1994. // at the moment we do not parse Pipfile and therefore can't tell the difference
  1995. // between prod & dev updates
  1996. const changes = [];
  1997. try {
  1998. if (!upgrades.length) {
  1999. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError('Failed to calculate package updates to apply');
  2000. }
  2001. // update prod dependencies first
  2002. if (upgrades.length) {
  2003. for (const upgrade of upgrades) {
  2004. changes.push(...(await pipenv_add_1.pipenvAdd(entity, options, [upgrade])));
  2005. }
  2006. }
  2007. if (!changes.length) {
  2008. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2009. }
  2010. if (!changes.some((c) => attempted_changes_summary_1.isSuccessfulChange(c))) {
  2011. handlerResult.failed.push({
  2012. original: entity,
  2013. changes,
  2014. });
  2015. }
  2016. else {
  2017. handlerResult.succeeded.push({
  2018. original: entity,
  2019. changes,
  2020. });
  2021. }
  2022. }
  2023. catch (error) {
  2024. debug(`Failed to fix ${entity.scanResult.identity.targetFile}.\nERROR: ${error}`);
  2025. handlerResult.failed.push({
  2026. original: entity,
  2027. tip: error.tip,
  2028. error,
  2029. });
  2030. }
  2031. return handlerResult;
  2032. }
  2033. //# sourceMappingURL=index.js.map
  2034. /***/ }),
  2035. /***/ 22629:
  2036. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2037. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2038. exports.pipenvAdd = void 0;
  2039. const pathLib = __webpack_require__(85622);
  2040. const pipenvPipfileFix = __webpack_require__(91989);
  2041. const debugLib = __webpack_require__(15158);
  2042. const validate_required_data_1 = __webpack_require__(57894);
  2043. const attempted_changes_summary_1 = __webpack_require__(70145);
  2044. const command_failed_to_run_error_1 = __webpack_require__(72353);
  2045. const no_fixes_applied_1 = __webpack_require__(80799);
  2046. const debug = debugLib('snyk-fix:python:pipenvAdd');
  2047. async function pipenvAdd(entity, options, upgrades) {
  2048. const changes = [];
  2049. let pipenvCommand;
  2050. const { remediation, targetFile } = validate_required_data_1.validateRequiredData(entity);
  2051. try {
  2052. const targetFilePath = pathLib.resolve(entity.workspace.path, targetFile);
  2053. const { dir } = pathLib.parse(targetFilePath);
  2054. if (!options.dryRun && upgrades.length) {
  2055. const { stderr, stdout, command, exitCode, } = await pipenvPipfileFix.pipenvInstall(dir, upgrades, {
  2056. python: entity.options.command,
  2057. });
  2058. debug('`pipenv add` returned:', { stderr, stdout, command });
  2059. if (exitCode !== 0) {
  2060. pipenvCommand = command;
  2061. throwPipenvError(stderr, stdout, command);
  2062. }
  2063. }
  2064. changes.push(...attempted_changes_summary_1.generateSuccessfulChanges(upgrades, remediation.pin));
  2065. }
  2066. catch (error) {
  2067. changes.push(...attempted_changes_summary_1.generateFailedChanges(upgrades, remediation.pin, error, pipenvCommand));
  2068. }
  2069. return changes;
  2070. }
  2071. exports.pipenvAdd = pipenvAdd;
  2072. function throwPipenvError(stderr, stdout, command) {
  2073. const incompatibleDeps = 'There are incompatible versions in the resolved dependencies';
  2074. const lockingFailed = 'Locking failed';
  2075. const versionNotFound = 'Could not find a version that matches';
  2076. const errorsToBubbleUp = [incompatibleDeps, lockingFailed, versionNotFound];
  2077. for (const error of errorsToBubbleUp) {
  2078. if (stderr.toLowerCase().includes(error.toLowerCase()) ||
  2079. stdout.toLowerCase().includes(error.toLowerCase())) {
  2080. throw new command_failed_to_run_error_1.CommandFailedError(error, command);
  2081. }
  2082. }
  2083. const SOLVER_PROBLEM = /SolverProblemError(.* version solving failed)/gms;
  2084. const solverProblemError = SOLVER_PROBLEM.exec(stderr) || SOLVER_PROBLEM.exec(stdout);
  2085. if (solverProblemError) {
  2086. throw new command_failed_to_run_error_1.CommandFailedError(solverProblemError[0].trim(), command);
  2087. }
  2088. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2089. }
  2090. //# sourceMappingURL=pipenv-add.js.map
  2091. /***/ }),
  2092. /***/ 60428:
  2093. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2094. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2095. exports.poetry = void 0;
  2096. const debugLib = __webpack_require__(15158);
  2097. const ora = __webpack_require__(63395);
  2098. const package_tool_supported_1 = __webpack_require__(96377);
  2099. const update_dependencies_1 = __webpack_require__(61526);
  2100. const debug = debugLib('snyk-fix:python:Poetry');
  2101. async function poetry(fixable, options) {
  2102. debug(`Preparing to fix ${fixable.length} Python Poetry projects`);
  2103. const handlerResult = {
  2104. succeeded: [],
  2105. failed: [],
  2106. skipped: [],
  2107. };
  2108. await package_tool_supported_1.checkPackageToolSupported('poetry', options);
  2109. for (const [index, entity] of fixable.entries()) {
  2110. const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
  2111. const spinnerMessage = `Fixing pyproject.toml ${index + 1}/${fixable.length}`;
  2112. spinner.text = spinnerMessage;
  2113. spinner.start();
  2114. const { failed, succeeded, skipped } = await update_dependencies_1.updateDependencies(entity, options);
  2115. handlerResult.succeeded.push(...succeeded);
  2116. handlerResult.failed.push(...failed);
  2117. handlerResult.skipped.push(...skipped);
  2118. spinner.stop();
  2119. }
  2120. return handlerResult;
  2121. }
  2122. exports.poetry = poetry;
  2123. //# sourceMappingURL=index.js.map
  2124. /***/ }),
  2125. /***/ 84204:
  2126. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2127. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2128. exports.generateUpgrades = void 0;
  2129. const pathLib = __webpack_require__(85622);
  2130. const toml = __webpack_require__(35424);
  2131. const debugLib = __webpack_require__(15158);
  2132. const validate_required_data_1 = __webpack_require__(57894);
  2133. const standardize_package_name_1 = __webpack_require__(78078);
  2134. const debug = debugLib('snyk-fix:python:Poetry');
  2135. async function generateUpgrades(entity) {
  2136. var _a, _b;
  2137. const { remediation, targetFile } = validate_required_data_1.validateRequiredData(entity);
  2138. const pins = remediation.pin;
  2139. const targetFilePath = pathLib.resolve(entity.workspace.path, targetFile);
  2140. const { dir } = pathLib.parse(targetFilePath);
  2141. const pyProjectTomlRaw = await entity.workspace.readFile(pathLib.resolve(dir, 'pyproject.toml'));
  2142. const pyProjectToml = toml.parse(pyProjectTomlRaw);
  2143. const prodTopLevelDeps = Object.keys((_a = pyProjectToml.tool.poetry.dependencies) !== null && _a !== void 0 ? _a : {}).map((dep) => standardize_package_name_1.standardizePackageName(dep));
  2144. const devTopLevelDeps = Object.keys((_b = pyProjectToml.tool.poetry['dev-dependencies']) !== null && _b !== void 0 ? _b : {}).map((dep) => standardize_package_name_1.standardizePackageName(dep));
  2145. const upgrades = [];
  2146. const devUpgrades = [];
  2147. for (const pkgAtVersion of Object.keys(pins)) {
  2148. const pin = pins[pkgAtVersion];
  2149. const newVersion = pin.upgradeTo.split('@')[1];
  2150. const [pkgName] = pkgAtVersion.split('@');
  2151. const upgrade = `${standardize_package_name_1.standardizePackageName(pkgName)}==${newVersion}`;
  2152. if (pin.isTransitive || prodTopLevelDeps.includes(pkgName)) {
  2153. // transitive and it could have come from a dev or prod dep
  2154. // since we can't tell right now let be pinned into production deps
  2155. upgrades.push(upgrade);
  2156. }
  2157. else if (prodTopLevelDeps.includes(pkgName)) {
  2158. upgrades.push(upgrade);
  2159. }
  2160. else if (entity.options.dev && devTopLevelDeps.includes(pkgName)) {
  2161. devUpgrades.push(upgrade);
  2162. }
  2163. else {
  2164. debug(`Could not determine what type of upgrade ${upgrade} is. When choosing between: transitive upgrade, production or dev direct upgrade. `);
  2165. }
  2166. }
  2167. return { upgrades, devUpgrades };
  2168. }
  2169. exports.generateUpgrades = generateUpgrades;
  2170. //# sourceMappingURL=generate-upgrades.js.map
  2171. /***/ }),
  2172. /***/ 61526:
  2173. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2174. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2175. exports.updateDependencies = void 0;
  2176. const debugLib = __webpack_require__(15158);
  2177. const generate_upgrades_1 = __webpack_require__(84204);
  2178. const poetry_add_1 = __webpack_require__(24881);
  2179. const no_fixes_applied_1 = __webpack_require__(80799);
  2180. const attempted_changes_summary_1 = __webpack_require__(70145);
  2181. const debug = debugLib('snyk-fix:python:Poetry');
  2182. function chooseFixStrategy(options) {
  2183. return options.sequentialFix ? fixSequentially : fixAll;
  2184. }
  2185. async function updateDependencies(entity, options) {
  2186. const handlerResult = await chooseFixStrategy(options)(entity, options);
  2187. return handlerResult;
  2188. }
  2189. exports.updateDependencies = updateDependencies;
  2190. async function fixAll(entity, options) {
  2191. const handlerResult = {
  2192. succeeded: [],
  2193. failed: [],
  2194. skipped: [],
  2195. };
  2196. const { upgrades, devUpgrades } = await generate_upgrades_1.generateUpgrades(entity);
  2197. // TODO: for better support we need to:
  2198. // 1. parse the manifest and extract original requirements, version spec etc
  2199. // 2. swap out only the version and retain original spec
  2200. // 3. re-lock the lockfile
  2201. const changes = [];
  2202. try {
  2203. if (![...upgrades, ...devUpgrades].length) {
  2204. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError('Failed to calculate package updates to apply');
  2205. }
  2206. // update prod dependencies first
  2207. if (upgrades.length) {
  2208. changes.push(...(await poetry_add_1.poetryAdd(entity, options, upgrades)));
  2209. }
  2210. // update dev dependencies second
  2211. if (devUpgrades.length) {
  2212. const installDev = true;
  2213. changes.push(...(await poetry_add_1.poetryAdd(entity, options, devUpgrades, installDev)));
  2214. }
  2215. if (!changes.length) {
  2216. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2217. }
  2218. if (!changes.some((c) => attempted_changes_summary_1.isSuccessfulChange(c))) {
  2219. handlerResult.failed.push({
  2220. original: entity,
  2221. changes,
  2222. });
  2223. }
  2224. else {
  2225. handlerResult.succeeded.push({
  2226. original: entity,
  2227. changes,
  2228. });
  2229. }
  2230. }
  2231. catch (error) {
  2232. debug(`Failed to fix ${entity.scanResult.identity.targetFile}.\nERROR: ${error}`);
  2233. handlerResult.failed.push({
  2234. original: entity,
  2235. tip: error.tip,
  2236. error,
  2237. });
  2238. }
  2239. return handlerResult;
  2240. }
  2241. async function fixSequentially(entity, options) {
  2242. const handlerResult = {
  2243. succeeded: [],
  2244. failed: [],
  2245. skipped: [],
  2246. };
  2247. const { upgrades, devUpgrades } = await generate_upgrades_1.generateUpgrades(entity);
  2248. // TODO: for better support we need to:
  2249. // 1. parse the manifest and extract original requirements, version spec etc
  2250. // 2. swap out only the version and retain original spec
  2251. // 3. re-lock the lockfile
  2252. const changes = [];
  2253. try {
  2254. if (![...upgrades, ...devUpgrades].length) {
  2255. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError('Failed to calculate package updates to apply');
  2256. }
  2257. // update prod dependencies first
  2258. if (upgrades.length) {
  2259. for (const upgrade of upgrades) {
  2260. changes.push(...(await poetry_add_1.poetryAdd(entity, options, [upgrade])));
  2261. }
  2262. }
  2263. // update dev dependencies second
  2264. if (devUpgrades.length) {
  2265. for (const upgrade of devUpgrades) {
  2266. const installDev = true;
  2267. changes.push(...(await poetry_add_1.poetryAdd(entity, options, [upgrade], installDev)));
  2268. }
  2269. }
  2270. if (!changes.length) {
  2271. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2272. }
  2273. if (!changes.some((c) => attempted_changes_summary_1.isSuccessfulChange(c))) {
  2274. handlerResult.failed.push({
  2275. original: entity,
  2276. changes,
  2277. });
  2278. }
  2279. else {
  2280. handlerResult.succeeded.push({
  2281. original: entity,
  2282. changes,
  2283. });
  2284. }
  2285. }
  2286. catch (error) {
  2287. debug(`Failed to fix ${entity.scanResult.identity.targetFile}.\nERROR: ${error}`);
  2288. handlerResult.failed.push({
  2289. original: entity,
  2290. tip: error.tip,
  2291. error,
  2292. });
  2293. }
  2294. return handlerResult;
  2295. }
  2296. //# sourceMappingURL=index.js.map
  2297. /***/ }),
  2298. /***/ 24881:
  2299. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2300. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2301. exports.poetryAdd = void 0;
  2302. const pathLib = __webpack_require__(85622);
  2303. const debugLib = __webpack_require__(15158);
  2304. const poetryFix = __webpack_require__(69671);
  2305. const validate_required_data_1 = __webpack_require__(57894);
  2306. const attempted_changes_summary_1 = __webpack_require__(70145);
  2307. const command_failed_to_run_error_1 = __webpack_require__(72353);
  2308. const no_fixes_applied_1 = __webpack_require__(80799);
  2309. const debug = debugLib('snyk-fix:python:poetryAdd');
  2310. async function poetryAdd(entity, options, upgrades, dev) {
  2311. var _a;
  2312. const changes = [];
  2313. let poetryCommand;
  2314. const { remediation, targetFile } = validate_required_data_1.validateRequiredData(entity);
  2315. try {
  2316. const targetFilePath = pathLib.resolve(entity.workspace.path, targetFile);
  2317. const { dir } = pathLib.parse(targetFilePath);
  2318. if (!options.dryRun && upgrades.length) {
  2319. const { stderr, stdout, command, exitCode } = await poetryFix.poetryAdd(dir, upgrades, {
  2320. dev,
  2321. python: (_a = entity.options.command) !== null && _a !== void 0 ? _a : undefined,
  2322. });
  2323. debug('`poetry add` returned:', { stderr, stdout, command });
  2324. if (exitCode !== 0) {
  2325. poetryCommand = command;
  2326. throwPoetryError(stderr, stdout, command);
  2327. }
  2328. }
  2329. changes.push(...attempted_changes_summary_1.generateSuccessfulChanges(upgrades, remediation.pin));
  2330. }
  2331. catch (error) {
  2332. changes.push(...attempted_changes_summary_1.generateFailedChanges(upgrades, remediation.pin, error, poetryCommand));
  2333. }
  2334. return changes;
  2335. }
  2336. exports.poetryAdd = poetryAdd;
  2337. function throwPoetryError(stderr, stdout, command) {
  2338. const ALREADY_UP_TO_DATE = 'No dependencies to install or update';
  2339. const INCOMPATIBLE_PYTHON = new RegExp(/Python requirement (.*) is not compatible/g, 'gm');
  2340. const SOLVER_PROBLEM = /SolverProblemError(.* version solving failed)/gms;
  2341. const incompatiblePythonError = INCOMPATIBLE_PYTHON.exec(stderr) || SOLVER_PROBLEM.exec(stdout);
  2342. if (incompatiblePythonError) {
  2343. throw new command_failed_to_run_error_1.CommandFailedError(`The current project's Python requirement ${incompatiblePythonError[1]} is not compatible with some of the required packages`, command);
  2344. }
  2345. const solverProblemError = SOLVER_PROBLEM.exec(stderr) || SOLVER_PROBLEM.exec(stdout);
  2346. if (solverProblemError) {
  2347. throw new command_failed_to_run_error_1.CommandFailedError(solverProblemError[0].trim(), command);
  2348. }
  2349. if (stderr.includes(ALREADY_UP_TO_DATE) ||
  2350. stdout.includes(ALREADY_UP_TO_DATE)) {
  2351. throw new command_failed_to_run_error_1.CommandFailedError('No dependencies could be updated as they seem to be at the correct versions. Make sure installed dependencies in the environment match those in the lockfile by running `poetry update`', command);
  2352. }
  2353. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2354. }
  2355. //# sourceMappingURL=poetry-add.js.map
  2356. /***/ }),
  2357. /***/ 57894:
  2358. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2359. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2360. exports.validateRequiredData = void 0;
  2361. const missing_remediation_data_1 = __webpack_require__(95084);
  2362. const missing_file_name_1 = __webpack_require__(86920);
  2363. const no_fixes_applied_1 = __webpack_require__(80799);
  2364. function validateRequiredData(entity) {
  2365. const { remediation } = entity.testResult;
  2366. if (!remediation) {
  2367. throw new missing_remediation_data_1.MissingRemediationDataError();
  2368. }
  2369. const { targetFile } = entity.scanResult.identity;
  2370. if (!targetFile) {
  2371. throw new missing_file_name_1.MissingFileNameError();
  2372. }
  2373. const { workspace } = entity;
  2374. if (!workspace) {
  2375. throw new no_fixes_applied_1.NoFixesCouldBeAppliedError();
  2376. }
  2377. return { targetFile, remediation, workspace };
  2378. }
  2379. exports.validateRequiredData = validateRequiredData;
  2380. //# sourceMappingURL=validate-required-data.js.map
  2381. /***/ }),
  2382. /***/ 97090:
  2383. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2384. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2385. exports.pythonFix = void 0;
  2386. const debugLib = __webpack_require__(15158);
  2387. const pMap = __webpack_require__(54270);
  2388. const ora = __webpack_require__(63395);
  2389. const chalk = __webpack_require__(98250);
  2390. const load_handler_1 = __webpack_require__(7073);
  2391. const map_entities_per_handler_type_1 = __webpack_require__(78646);
  2392. const is_supported_1 = __webpack_require__(60174);
  2393. const debug = debugLib('snyk-fix:python');
  2394. async function pythonFix(entities, options) {
  2395. const spinner = ora({ isSilent: options.quiet, stream: process.stdout });
  2396. const spinnerMessage = 'Looking for supported Python items';
  2397. spinner.text = spinnerMessage;
  2398. spinner.start();
  2399. const handlerResult = {
  2400. python: {
  2401. succeeded: [],
  2402. failed: [],
  2403. skipped: [],
  2404. },
  2405. };
  2406. const results = handlerResult.python;
  2407. const { entitiesPerType, skipped: notSupported } = map_entities_per_handler_type_1.mapEntitiesPerHandlerType(entities);
  2408. results.skipped.push(...notSupported);
  2409. spinner.stopAndPersist({
  2410. text: spinnerMessage,
  2411. symbol: chalk.green('\n✔'),
  2412. });
  2413. await pMap(Object.keys(entitiesPerType), async (projectType) => {
  2414. const projectsToFix = entitiesPerType[projectType];
  2415. if (!projectsToFix.length) {
  2416. return;
  2417. }
  2418. const processingMessage = `Processing ${projectsToFix.length} ${projectType} items`;
  2419. const processedMessage = `Processed ${projectsToFix.length} ${projectType} items`;
  2420. spinner.text = processingMessage;
  2421. spinner.render();
  2422. try {
  2423. const handler = load_handler_1.loadHandler(projectType);
  2424. // drop unsupported Python entities early so only potentially fixable items get
  2425. // attempted to be fixed
  2426. const { fixable, skipped: notFixable } = await is_supported_1.partitionByFixable(projectsToFix);
  2427. results.skipped.push(...notFixable);
  2428. const { failed, skipped, succeeded } = await handler(fixable, options);
  2429. results.failed.push(...failed);
  2430. results.skipped.push(...skipped);
  2431. results.succeeded.push(...succeeded);
  2432. }
  2433. catch (e) {
  2434. debug(`Failed to fix ${projectsToFix.length} ${projectType} projects.\nError: ${e.message}`);
  2435. results.failed.push(...generateFailed(projectsToFix, e));
  2436. }
  2437. spinner.stopAndPersist({
  2438. text: processedMessage,
  2439. symbol: chalk.green('✔'),
  2440. });
  2441. }, {
  2442. concurrency: 5,
  2443. });
  2444. return handlerResult;
  2445. }
  2446. exports.pythonFix = pythonFix;
  2447. function generateFailed(projectsToFix, error) {
  2448. const failed = [];
  2449. for (const project of projectsToFix) {
  2450. failed.push({ original: project, error: error });
  2451. }
  2452. return failed;
  2453. }
  2454. //# sourceMappingURL=index.js.map
  2455. /***/ }),
  2456. /***/ 7073:
  2457. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2458. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2459. exports.loadHandler = void 0;
  2460. const pip_requirements_1 = __webpack_require__(81065);
  2461. const pipenv_pipfile_1 = __webpack_require__(28006);
  2462. const poetry_1 = __webpack_require__(60428);
  2463. const supported_handler_types_1 = __webpack_require__(56394);
  2464. function loadHandler(type) {
  2465. switch (type) {
  2466. case supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS: {
  2467. return pip_requirements_1.pipRequirementsTxt;
  2468. }
  2469. case supported_handler_types_1.SUPPORTED_HANDLER_TYPES.PIPFILE: {
  2470. return pipenv_pipfile_1.pipenvPipfile;
  2471. }
  2472. case supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY: {
  2473. return poetry_1.poetry;
  2474. }
  2475. default: {
  2476. throw new Error('No handler available for requested project type');
  2477. }
  2478. }
  2479. }
  2480. exports.loadHandler = loadHandler;
  2481. //# sourceMappingURL=load-handler.js.map
  2482. /***/ }),
  2483. /***/ 78646:
  2484. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2485. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2486. exports.mapEntitiesPerHandlerType = void 0;
  2487. const debugLib = __webpack_require__(15158);
  2488. const get_handler_type_1 = __webpack_require__(10774);
  2489. const supported_handler_types_1 = __webpack_require__(56394);
  2490. const debug = debugLib('snyk-fix:python');
  2491. function mapEntitiesPerHandlerType(entities) {
  2492. const entitiesPerType = {
  2493. [supported_handler_types_1.SUPPORTED_HANDLER_TYPES.REQUIREMENTS]: [],
  2494. [supported_handler_types_1.SUPPORTED_HANDLER_TYPES.PIPFILE]: [],
  2495. [supported_handler_types_1.SUPPORTED_HANDLER_TYPES.POETRY]: [],
  2496. };
  2497. const skipped = [];
  2498. for (const entity of entities) {
  2499. const type = get_handler_type_1.getHandlerType(entity);
  2500. if (type) {
  2501. entitiesPerType[type].push(entity);
  2502. continue;
  2503. }
  2504. const userMessage = `${entity.scanResult.identity.targetFile} is not supported`;
  2505. debug(userMessage);
  2506. skipped.push({ original: entity, userMessage });
  2507. }
  2508. return { entitiesPerType, skipped };
  2509. }
  2510. exports.mapEntitiesPerHandlerType = mapEntitiesPerHandlerType;
  2511. //# sourceMappingURL=map-entities-per-handler-type.js.map
  2512. /***/ }),
  2513. /***/ 78078:
  2514. /***/ ((__unused_webpack_module, exports) => {
  2515. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2516. exports.standardizePackageName = void 0;
  2517. /*
  2518. * https://www.python.org/dev/peps/pep-0426/#name
  2519. * All comparisons of distribution names MUST be case insensitive,
  2520. * and MUST consider hyphens and underscores to be equivalent.
  2521. *
  2522. */
  2523. function standardizePackageName(name) {
  2524. return name.replace('_', '-').toLowerCase();
  2525. }
  2526. exports.standardizePackageName = standardizePackageName;
  2527. //# sourceMappingURL=standardize-package-name.js.map
  2528. /***/ }),
  2529. /***/ 56394:
  2530. /***/ ((__unused_webpack_module, exports) => {
  2531. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2532. exports.SUPPORTED_HANDLER_TYPES = void 0;
  2533. var SUPPORTED_HANDLER_TYPES;
  2534. (function (SUPPORTED_HANDLER_TYPES) {
  2535. // shortname = display name
  2536. SUPPORTED_HANDLER_TYPES["REQUIREMENTS"] = "requirements.txt";
  2537. SUPPORTED_HANDLER_TYPES["PIPFILE"] = "Pipfile";
  2538. SUPPORTED_HANDLER_TYPES["POETRY"] = "pyproject.toml";
  2539. })(SUPPORTED_HANDLER_TYPES = exports.SUPPORTED_HANDLER_TYPES || (exports.SUPPORTED_HANDLER_TYPES = {}));
  2540. //# sourceMappingURL=supported-handler-types.js.map
  2541. /***/ }),
  2542. /***/ 71538:
  2543. /***/ ((__unused_webpack_module, exports) => {
  2544. Object.defineProperty(exports, "__esModule", ({ value: true }));
  2545. exports.isWithError = void 0;
  2546. function isWithError(r) {
  2547. return 'error' in r;
  2548. }
  2549. exports.isWithError = isWithError;
  2550. //# sourceMappingURL=types.js.map
  2551. /***/ })
  2552. };
  2553. ;
  2554. //# sourceMappingURL=741.index.js.map