@contrast/contrast 2.1.7 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -343,6 +343,45 @@ const auditAdvancedOptionDefinitionsForHelp = [
343
343
  i18n.__('constantsMavenSettingsPath')
344
344
  }
345
345
  ];
346
+ const sarifAdvancedOptionDefinitionsForHelp = [
347
+ ...sharedConnectionOptionDefinitions,
348
+ ...sharedCertOptionDefinitions
349
+ ];
350
+ const sarifOptionDefinitions = [
351
+ ...sarifAdvancedOptionDefinitionsForHelp,
352
+ {
353
+ name: 'help',
354
+ alias: 'h',
355
+ type: Boolean
356
+ },
357
+ {
358
+ name: 'application-id',
359
+ description: '{bold ' +
360
+ i18n.__('constantsRequired') +
361
+ '}: ' +
362
+ i18n.__('constantsApplicationId')
363
+ },
364
+ {
365
+ name: 'metadata',
366
+ description: '{bold ' +
367
+ i18n.__('constantsOptional') +
368
+ '}: ' +
369
+ i18n.__('constantsMetadata')
370
+ },
371
+ {
372
+ name: 'severity',
373
+ type: severity => parseSeverity(severity),
374
+ description: '{bold ' +
375
+ i18n.__('constantsOptional') +
376
+ '}: ' +
377
+ i18n.__('constantsSarifSeverity')
378
+ },
379
+ {
380
+ name: 'debug',
381
+ alias: 'd',
382
+ type: Boolean
383
+ }
384
+ ];
346
385
  const auditOptionDefinitions = [
347
386
  ...auditAdvancedOptionDefinitionsForHelp,
348
387
  {
@@ -509,12 +548,13 @@ const mainUsageGuide = commandLineUsage([
509
548
  { name: i18n.__('configName'), summary: i18n.__('helpConfigSummary') },
510
549
  { name: i18n.__('versionName'), summary: i18n.__('helpVersionSummary') },
511
550
  { name: i18n.__('auditName'), summary: i18n.__('helpAuditSummary') },
551
+ { name: i18n.__('sarifName'), summary: i18n.__('helpSarifSummary') },
512
552
  { name: i18n.__('scanName'), summary: i18n.__('helpScanSummary') },
513
553
  { name: i18n.__('assessName'), summary: i18n.__('assessSummary') },
514
554
  { name: i18n.__('lambdaName'), summary: i18n.__('helpLambdaSummary') },
515
555
  { name: i18n.__('helpName'), summary: i18n.__('helpSummary') },
516
556
  { name: i18n.__('learnName'), summary: i18n.__('helpLearnSummary') },
517
- // { name: i18n.__('sarifName'), summary: i18n.__('sarifSummary') },
557
+ { name: i18n.__('sarifName'), summary: i18n.__('sarifSummary') },
518
558
  {
519
559
  name: i18n.__('configGenerate'),
520
560
  summary: i18n.__('configGenerateSummary')
@@ -544,6 +584,8 @@ export const commandLineDefinitions = {
544
584
  auditOptionDefinitions,
545
585
  authOptionDefinitions,
546
586
  configOptionDefinitions,
587
+ sarifOptionDefinitions,
588
+ sarifAdvancedOptionDefinitionsForHelp,
547
589
  scanAdvancedOptionDefinitionsForHelp,
548
590
  auditAdvancedOptionDefinitionsForHelp,
549
591
  assessOptionDefinitions,
@@ -17,7 +17,7 @@ export const HIGH = 'HIGH';
17
17
  export const CRITICAL = 'CRITICAL';
18
18
  // App
19
19
  export const APP_NAME = 'contrast';
20
- const APP_VERSION = '2.1.7';
20
+ const APP_VERSION = '2.2.0';
21
21
  export const TIMEOUT = 120000;
22
22
  export const CRITICAL_PRIORITY = 1;
23
23
  export const HIGH_PRIORITY = 2;
@@ -52,6 +52,7 @@ export const en_locales = () => {
52
52
  failThresholdOptionErrorMessage: 'More than 0 vulnerabilities found',
53
53
  failSeverityOptionErrorMessage: ' FAIL - Results detected vulnerabilities over accepted severity level',
54
54
  constantsSeverity: 'Use with "contrast scan --fail --severity high" or "contrast audit --fail --severity high". Set the severity level to detect vulnerabilities or dependencies. Severity levels are critical, high, medium, low or note.',
55
+ constantsSarifSeverity: 'Set the severity level to filter the vulnerabilities included in the SARIF output. Severity levels are critical, high, medium, low or note.',
55
56
  constantsHeader: `Contrast CLI @ v${getAppVersion()}`,
56
57
  configHeader2: 'Config options',
57
58
  clearHeader: '-c, --clear',
@@ -67,6 +68,8 @@ export const en_locales = () => {
67
68
  constantsConfigUsageContents: 'view / clear the configuration',
68
69
  constantsPrerequisitesContent: 'To scan a Java binary project you will need a .jar, .war or a zip of multiple .jar or .war files for analysis\n' +
69
70
  'To scan source code you will need a .zip file containing the code for analysis',
71
+ constantsSarifPreRequisitesContent: 'To generate a SARIF file you will need the application-id of the application you want to generate the SARIF file for.\n' +
72
+ 'To get the application-id, go to the Contrast UI, select the application you want to generate the SARIF file for, and copy the application-id from the URL.',
70
73
  constantsUsage: 'Usage',
71
74
  constantsUsageCommandExample: 'contrast [command] [options]',
72
75
  constantsUsageCommandInfo: 'The file argument is optional. If no file is given, Contrast will search for a .jar, .war, .exe or .zip file in the working directory.\n',
@@ -90,6 +93,7 @@ export const en_locales = () => {
90
93
  scanLabel: "adds a label to the scan - defaults to 'Started by CLI tool at current date'",
91
94
  constantsIgnoreDev: 'Excludes developer dependencies from the results. All dependencies are included by default.',
92
95
  constantsCommands: 'Commands',
96
+ constantsSarifOptions: 'SARIF Options',
93
97
  constantsScanOptions: 'Scan Options',
94
98
  constantsAssessOptions: 'Assess Options',
95
99
  generatorConfigOptions: 'Generate Config Options',
@@ -114,6 +118,7 @@ export const en_locales = () => {
114
118
  helpScanSummary: 'Searches for a .jar, .war, .js, or .zip file in the working directory, uploads files for analysis, and returns the results. \n[scan --help for options] Java, .NET, .NET Core, JavaScript are supported. ',
115
119
  assessSummary: 'Reports vulnerabilities found at run-time on a server or microservice using a Contrast agent. \n [assess --help for options] Java, .NET, Node, Ruby, Python, Go, PHP are supported.',
116
120
  helpLambdaSummary: 'Performs a static security scan on an AWS lambda function. [lambda --help for options] AWS Lambda - Java & Python are supported. ',
121
+ helpSarifSummary: 'Generates a SARIF file (contrast.sarif) for Contrast Assess and Contrast SCA results for the specified application-id.',
117
122
  helpVersionSummary: 'Displays version of Contrast CLI',
118
123
  helpConfigSummary: 'Displays stored credentials',
119
124
  helpSummary: 'Displays usage guide',
@@ -171,6 +176,8 @@ export const en_locales = () => {
171
176
  foundDetailedVulnerabilities: chalk.bold('%s') + ' | ' + chalk.bold('%s') + ' | %s | %s | %s ',
172
177
  searchingScanFileDirectory: 'Searching for file to scan from %s...',
173
178
  searchingAuditFileDirectory: 'Searching for package manager files from %s...',
179
+ sarifHeader: 'Contrast SARIF CLI',
180
+ sarifHeaderMessage: "Use 'contrast sarif' to generate a SARIF file for the given application-id.",
174
181
  scanHeader: `Contrast Scan CLI`,
175
182
  assessHeader: `Contrast Assess CLI`,
176
183
  generateConfigHeader: `Contrast Generate Config`,
package/dist/index.js CHANGED
@@ -78,7 +78,7 @@ const start = async () => {
78
78
  return await processFingerprint(config, argvMain);
79
79
  }
80
80
  if (command === 'sarif') {
81
- return processSarif(config, argvMain);
81
+ return await processSarif(config, argvMain);
82
82
  }
83
83
  if (command === 'learn') {
84
84
  return processLearn();
@@ -1,17 +1,27 @@
1
- import { getAuditConfig } from '../audit/auditConfig.js';
1
+ import { getSarifConfig } from './sarifConfig.js';
2
2
  import { scaCVES } from './sarifScaClient.js';
3
- import { iastData } from './sarifIastClient.js';
3
+ import { checkApplicationAccess, iastData } from './sarifIastClient.js';
4
4
  import { writeCombinedSarif } from './sarifWriter.js';
5
+ import { logInfo } from '../common/logging.js';
6
+ import { sarifUsageGuide } from './help.js';
5
7
  // This filename could be set by a customer
6
8
  // Defaulted to be ingested in a GH workflow
7
- const outputFileName = 'contrast.sarif.json';
9
+ const outputFileName = 'contrast.sarif';
8
10
  export const processSarif = async (contrastConf, argvMain) => {
9
- console.log('Generating SARIF export');
10
- let config = await getAuditConfig(contrastConf, 'audit', argvMain);
11
+ if (argvMain.indexOf('--help') !== -1 || argvMain.indexOf('help') !== -1) {
12
+ printHelpMessage();
13
+ process.exit(0);
14
+ }
15
+ let config = await getSarifConfig(contrastConf, 'sarif', argvMain);
16
+ await checkApplicationAccess(config);
17
+ logInfo('Generating SARIF file');
11
18
  const scaVulns = await scaCVES(config);
12
- console.log(`Found ${scaVulns.length} SCA vulnerabilities`);
19
+ logInfo(`Found ${scaVulns.length} SCA vulnerabilities matching criteria`);
13
20
  const iastVulns = await iastData(config);
14
- console.log(`Found ${iastVulns.length} IAST vulnerabilities`);
21
+ logInfo(`Found ${iastVulns.length} IAST vulnerabilities matching criteria`);
15
22
  writeCombinedSarif(iastVulns, scaVulns, outputFileName);
16
- console.log('SARIF generated');
23
+ logInfo('contrast.sarif file generated successfully');
24
+ };
25
+ const printHelpMessage = () => {
26
+ logInfo(sarifUsageGuide);
17
27
  };
@@ -0,0 +1,52 @@
1
+ import commandLineUsage from 'command-line-usage';
2
+ import i18n from 'i18n';
3
+ import { commandLineDefinitions } from '../cliConstants.js';
4
+ import { commonHelpLinks } from '../common/commonHelp.js';
5
+ const { __ } = i18n;
6
+ export const sarifUsageGuide = commandLineUsage([
7
+ {
8
+ header: __('constantsHeader')
9
+ },
10
+ {
11
+ header: __('sarifHeader'),
12
+ content: [__('sarifHeaderMessage')]
13
+ },
14
+ {
15
+ header: __('constantsPrerequisitesHeader'),
16
+ content: [__('constantsSarifPreRequisitesContent')]
17
+ },
18
+ {
19
+ header: __('constantsSarifOptions'),
20
+ optionList: commandLineDefinitions.sarifOptionDefinitions,
21
+ hide: [
22
+ 'organization-id',
23
+ 'api-key',
24
+ 'authorization',
25
+ 'host',
26
+ 'proxy',
27
+ 'cert',
28
+ 'cacert',
29
+ 'key',
30
+ 'help',
31
+ 'ff',
32
+ 'cert-self-signed',
33
+ 'debug',
34
+ 'experimental',
35
+ 'tags',
36
+ 'sub-project',
37
+ 'code',
38
+ 'maven-settings-path',
39
+ 'language',
40
+ 'app-groups',
41
+ 'branch',
42
+ 'repo'
43
+ ]
44
+ },
45
+ {
46
+ header: __('constantsAdvancedOptions'),
47
+ optionList: commandLineDefinitions.sarifAdvancedOptionDefinitionsForHelp
48
+ },
49
+ commonHelpLinks()[0],
50
+ commonHelpLinks()[1],
51
+ commonHelpLinks()[2]
52
+ ]);
@@ -1,5 +1,15 @@
1
1
  import { buildBaseRequestOptions, ErrorType } from '../common/baseRequest.js';
2
2
  import { got } from 'got';
3
+ import { logDebug } from '../common/logging.js';
4
+ export function getApplicationAccess(config) {
5
+ const options = buildBaseRequestOptions(config, ErrorType.GENERIC);
6
+ options.url = getApplicationUrl(config, config.applicationId, config.organizationId);
7
+ logDebug(config, 'url: ' + options.url);
8
+ return got.get(options);
9
+ }
10
+ const getApplicationUrl = (config, applicationId, organizationId) => {
11
+ return `${config.host}/Contrast/api/ng/${organizationId}/applications/${applicationId}?expand=license`;
12
+ };
3
13
  const getAssessTraceIdsUrl = (config, offset, resultsLimit) => {
4
14
  return `${config.host}/Contrast/api/ng/${config.organizationId}/orgtraces/filter/?offset=${offset}&limit=${resultsLimit}`;
5
15
  };
@@ -8,9 +18,10 @@ export function getAssessTraceIds(config, offset, resultsLimit) {
8
18
  options.url = getAssessTraceIdsUrl(config, offset, resultsLimit);
9
19
  options.json = {
10
20
  applicationID: config.applicationId,
11
- // metadataFilters: sessionMetadata,
12
- severities: [config.severity]
21
+ metadataFilters: config.metadata ? config.metadata : [],
22
+ severities: config.severity ? [config.severity] : []
13
23
  };
24
+ logDebug(config, 'url: ' + options.url);
14
25
  return got.post(options);
15
26
  }
16
27
  const getAssessTraceDetailsUrl = (config, traceId) => {
@@ -19,6 +30,7 @@ const getAssessTraceDetailsUrl = (config, traceId) => {
19
30
  export function getAssessTraceDetails(config, traceId) {
20
31
  const options = buildBaseRequestOptions(config, ErrorType.GENERIC);
21
32
  options.url = getAssessTraceDetailsUrl(config, traceId);
33
+ logDebug(config, 'url: ' + options.url);
22
34
  return got.get(options);
23
35
  }
24
36
  const getAssessTraceEventsUrl = (config, traceId, eventId) => {
@@ -27,6 +39,7 @@ const getAssessTraceEventsUrl = (config, traceId, eventId) => {
27
39
  export function getAssessTraceEvents(config, traceId, eventId) {
28
40
  const options = buildBaseRequestOptions(config, ErrorType.GENERIC);
29
41
  options.url = getAssessTraceEventsUrl(config, traceId, eventId);
42
+ logDebug(config, 'url: ' + options.url);
30
43
  return got.get(options);
31
44
  }
32
45
  const getAssessTraceRoutesUrl = (config, traceId) => {
@@ -35,5 +48,15 @@ const getAssessTraceRoutesUrl = (config, traceId) => {
35
48
  export function getAssessTraceRoutes(config, traceId) {
36
49
  const options = buildBaseRequestOptions(config, ErrorType.GENERIC);
37
50
  options.url = getAssessTraceRoutesUrl(config, traceId);
51
+ logDebug(config, 'url: ' + options.url);
52
+ return got.get(options);
53
+ }
54
+ const getAssessAgentSessionFiltersUrl = (config) => {
55
+ return `${config.host}/Contrast/api/ng/${config.organizationId}/metadata/session/${config.applicationId}/filters`;
56
+ };
57
+ export function getAssessAgentSessionFilters(config) {
58
+ const options = buildBaseRequestOptions(config, ErrorType.GENERIC);
59
+ options.url = getAssessAgentSessionFiltersUrl(config);
60
+ logDebug(config, 'url: ' + options.url);
38
61
  return got.get(options);
39
62
  }
@@ -0,0 +1,8 @@
1
+ import { getCommandLineArgsCustom } from '../utils/parsedCLIOptions.js';
2
+ import { commandLineDefinitions } from '../cliConstants.js';
3
+ import { getAuth } from '../utils/paramsUtil/paramHandler.js';
4
+ export const getSarifConfig = async (contrastConf, command, argv) => {
5
+ const sarifParameters = await getCommandLineArgsCustom(contrastConf, command, argv, commandLineDefinitions.sarifOptionDefinitions);
6
+ const paramsAuth = getAuth(sarifParameters);
7
+ return { ...paramsAuth, ...sarifParameters };
8
+ };
@@ -1,36 +1,67 @@
1
- import { getAssessTraceDetails, getAssessTraceEvents, getAssessTraceIds, getAssessTraceRoutes } from './sarifAssessRequests.js';
1
+ import { getAssessAgentSessionFilters, getAssessTraceDetails, getAssessTraceEvents, getAssessTraceIds, getAssessTraceRoutes, getApplicationAccess } from './sarifAssessRequests.js';
2
+ import { logInfo, logDebug } from '../common/logging.js';
3
+ import { get } from 'http';
2
4
  const resultsLimit = 50;
3
5
  let offset = 0;
4
6
  export const iastData = async (config) => {
7
+ if (config.metadata) {
8
+ const filters = await getAgentSessionFilters(config);
9
+ logInfo(`Found ${filters.length} available filters`);
10
+ if (filters.length !== 0) {
11
+ config = convertMetadataInput(config, filters);
12
+ }
13
+ }
5
14
  const filteredTraceIds = await getTraceIds(config, offset, resultsLimit);
6
- console.log(`Found ${filteredTraceIds.length} traces`);
15
+ logInfo(`Found ${filteredTraceIds.length} traces`);
7
16
  let completeTraces = [];
8
17
  for (const traceId of filteredTraceIds) {
9
18
  const traceDetails = await getTraceDetails(config, traceId);
10
19
  const traceRoutes = await getTraceRoutes(config, traceId);
11
20
  let eventsWithFrames = [];
12
21
  if (traceDetails.events) {
22
+ logInfo(`Found ${traceDetails.events.length} events for trace ${traceId} getting further details`);
13
23
  for (const eventSummary of traceDetails.events) {
14
24
  const eventDetails = await getTraceEvents(config, traceId, eventSummary.eventId);
15
25
  eventsWithFrames.push(eventDetails);
16
26
  }
27
+ // Only push when we have actual events , is this right?
28
+ completeTraces.push({
29
+ trace: traceDetails,
30
+ events: eventsWithFrames,
31
+ routes: traceRoutes
32
+ });
17
33
  }
18
- completeTraces.push({
19
- trace: traceDetails,
20
- events: eventsWithFrames,
21
- routes: traceRoutes
22
- });
23
34
  }
24
35
  return completeTraces;
25
36
  };
37
+ export async function checkApplicationAccess(config) {
38
+ logInfo('Checking application access');
39
+ if (config.applicationId === undefined) {
40
+ logInfo('Application ID not specified - this is required for IAST vulnerability retrieval');
41
+ }
42
+ try {
43
+ const response = getApplicationAccess(config);
44
+ const json = await response.json();
45
+ if (json.application.license.level === 'Unlicensed') {
46
+ logInfo('Application is not licensed for Assess, please contact your administrator to enable Assess for this application.');
47
+ process.exit(1);
48
+ }
49
+ }
50
+ catch (e) {
51
+ logInfo('Error accessing application, ensure you have access to application:' +
52
+ config.applicationId);
53
+ process.exit(1);
54
+ }
55
+ }
26
56
  export async function getTraceIds(config, offset, resultsLimit) {
27
57
  let hasResults = true;
28
58
  let pivotedData = [];
59
+ // Will return all traces if no severity is specified
29
60
  while (hasResults) {
30
61
  const response = getAssessTraceIds(config, offset, resultsLimit);
31
62
  const responseBody = await response.json();
32
63
  if (responseBody.traces == null) {
33
- console.log('No libraries found');
64
+ logInfo('No libraries found');
34
65
  return pivotedData;
35
66
  }
36
67
  const result = responseBody.traces;
@@ -46,20 +77,45 @@ export async function getTraceIds(config, offset, resultsLimit) {
46
77
  return pivotedData;
47
78
  }
48
79
  export async function getTraceDetails(config, traceId) {
49
- console.log(`Getting trace details for ${traceId} of application ${config.applicationId}`);
80
+ logInfo(`Getting trace details for ${traceId} of application ${config.applicationId}`);
50
81
  const response = getAssessTraceDetails(config, traceId);
51
82
  const responseBody = await response.json();
52
83
  return responseBody.trace;
53
84
  }
54
85
  export async function getTraceEvents(config, traceId, eventId) {
55
86
  const response = getAssessTraceEvents(config, traceId, eventId);
56
- console.log(`Getting trace events for ${eventId} of trace ${traceId}`);
87
+ logDebug(`Getting trace events for ${eventId} of trace ${traceId}`);
57
88
  const responseBody = await response.json();
58
89
  return responseBody.event;
59
90
  }
60
91
  export async function getTraceRoutes(config, traceId) {
61
- console.log(`Getting trace route for ${traceId} of application ${config.applicationId}`);
92
+ logInfo(`Getting trace routes for ${traceId} of application ${config.applicationId}`);
62
93
  const response = getAssessTraceRoutes(config, traceId);
63
94
  const responseBody = await response.json();
64
95
  return responseBody.routes;
65
96
  }
97
+ export async function getAgentSessionFilters(config) {
98
+ const response = getAssessAgentSessionFilters(config);
99
+ const responseBody = await response.json();
100
+ return responseBody.filters;
101
+ }
102
+ export function convertMetadataInput(config, filterLabels) {
103
+ // Agent session filters response returns a list of filters each containing an id and label
104
+ // The user input metadata will contain a label, which must be replaced by the id
105
+ // to then be used in the traces endpoint
106
+ let updatedMetadataInput = [];
107
+ const inputList = config.metadata.split(',');
108
+ const metadataInput = inputList.map(item => {
109
+ return { label: item.split('=')[0], values: [item.split('=')[1]] };
110
+ });
111
+ metadataInput.forEach(item => {
112
+ const filterLabel = filterLabels.find(f => f.label.toLowerCase() === item.label.toLowerCase());
113
+ if (filterLabel) {
114
+ item.fieldId = filterLabel.id;
115
+ }
116
+ const newValue = { fieldID: item.fieldId, values: item.values };
117
+ updatedMetadataInput.push(newValue);
118
+ });
119
+ config.metadata = updatedMetadataInput;
120
+ return config;
121
+ }
@@ -1,5 +1,6 @@
1
1
  import { buildBaseRequestOptions, ErrorType } from '../common/baseRequest.js';
2
2
  import { got } from 'got';
3
+ import { logDebug } from '../common/logging.js';
3
4
  const getSCAVulnsUrl = (config, offset, resultsLimit) => {
4
5
  return `${config.host}/Contrast/api/ng/${config.organizationId}/libraries/filter?expand=skip_links,apps,quickFilters,vulns,status,usage_counts&offset=${offset}&limit=${resultsLimit}&sort=score`;
5
6
  };
@@ -16,10 +17,11 @@ export function getSCAVulns(config, offset, resultsLimit) {
16
17
  languages: [],
17
18
  licenses: [],
18
19
  status: [],
19
- severities: [config.severity],
20
+ severities: config.severity ? [config.severity] : [],
20
21
  tags: [],
21
22
  includeUnused: false,
22
23
  includeUsed: false
23
24
  };
25
+ logDebug(config, 'url: ' + options.url);
24
26
  return got.post(options);
25
27
  }
@@ -1,14 +1,16 @@
1
+ import { logInfo } from '../common/logging.js';
1
2
  import { getSCAVulns } from './sarifSCARequests.js';
2
3
  const resultsLimit = 50;
3
4
  let offset = 0;
4
5
  export const scaCVES = async (config) => {
5
6
  let hasResults = true;
6
7
  let pivotedData = [];
8
+ // Will return all CVEs if no severity is specified
7
9
  while (hasResults) {
8
10
  const response = getSCAVulns(config, offset, resultsLimit);
9
11
  const responseBody = await response.json();
10
12
  if (responseBody.libraries == null) {
11
- console.log('No libraries found');
13
+ logInfo('No libraries found');
12
14
  return pivotedData;
13
15
  }
14
16
  // Finds all libraries with a vulnerability of specified severity
@@ -22,7 +24,8 @@ export const scaCVES = async (config) => {
22
24
  // All vulns associated with the library will be returned,
23
25
  // so we must filter by severity again
24
26
  for (const vuln of result) {
25
- if (vuln.severityToUse.toLowerCase() === config.severity) {
27
+ if (config.severity == null ||
28
+ vuln.severityToUse.toLowerCase() === config.severity) {
26
29
  pivotedData.push(vuln);
27
30
  }
28
31
  }
@@ -1,4 +1,4 @@
1
- import { SarifBuilder, SarifRunBuilder, SarifResultBuilder } from 'node-sarif-builder';
1
+ import { SarifBuilder, SarifRunBuilder, SarifResultBuilder, SarifRuleBuilder } from 'node-sarif-builder';
2
2
  import fs from 'fs';
3
3
  export const mapSeverity = contrastSeverity => {
4
4
  switch (contrastSeverity.toLowerCase()) {
@@ -24,7 +24,7 @@ export const getFileFromTSDescription = description => {
24
24
  export const getLineFromTSDescription = description => {
25
25
  const regex = /\(.*:(\d*)\)/;
26
26
  const match = regex.exec(description);
27
- return match ? parseInt(match[1]) : 0;
27
+ return match ? parseInt(match[1]) : 1;
28
28
  };
29
29
  export const getLogicalLocationFromTSDescription = description => {
30
30
  const regex = /(.*)\([^]+:\d*\)/;
@@ -42,14 +42,20 @@ export const generateIastSarifRun = traces => {
42
42
  }
43
43
  for (const trace of traces) {
44
44
  let extractedString = null;
45
- if (trace.sink && trace.sink.label) {
46
- extractedString = getFileFromTSDescription(trace.sink.label);
45
+ if (trace.trace.sink && trace.trace.sink.label) {
46
+ extractedString = getFileFromTSDescription(trace.trace.sink.label);
47
47
  }
48
48
  const sarifResultBuilder = new SarifResultBuilder().initSimple({
49
49
  ruleId: trace.trace.rule_title,
50
50
  messageText: trace.trace.title,
51
51
  level: mapSeverity(trace.trace.severity)
52
52
  });
53
+ const sarifRuleBuilder = new SarifRuleBuilder().initSimple({
54
+ ruleId: trace.trace.rule_title,
55
+ shortDescriptionText: trace.trace.title,
56
+ fullDescriptionText: trace.trace.title
57
+ });
58
+ sarifRunBuilderIast.addRule(sarifRuleBuilder);
53
59
  if (extractedString) {
54
60
  sarifResultBuilder.setLocationArtifactUri({ uri: extractedString });
55
61
  }
@@ -78,8 +84,26 @@ export const generateIastSarifRun = traces => {
78
84
  return {
79
85
  locations: [
80
86
  {
87
+ location: {
88
+ physicalLocation: {
89
+ artifactLocation: {
90
+ uri: getFileFromTSDescription(event.stacktraces[0].description)
91
+ },
92
+ region: {
93
+ startLine: getLineFromTSDescription(event.stacktraces[0].description)
94
+ }
95
+ },
96
+ logicalLocations: [
97
+ {
98
+ fullyQualifiedName: getLogicalLocationFromTSDescription(event.stacktraces[0].description)
99
+ }
100
+ ]
101
+ },
81
102
  stack: {
82
- frames: event.stacktraces.map(stacktrace => {
103
+ frames: event.stacktraces
104
+ .filter(stacktrace => getFileFromTSDescription(stacktrace.description) !==
105
+ 'NOT AVAILABLE')
106
+ .map(stacktrace => {
83
107
  return {
84
108
  location: {
85
109
  physicalLocation: {
@@ -108,6 +132,22 @@ export const generateIastSarifRun = traces => {
108
132
  }
109
133
  }
110
134
  ];
135
+ sarifResultBuilder.result.locations = [];
136
+ sarifResultBuilder.result.locations.push({
137
+ physicalLocation: {
138
+ artifactLocation: {
139
+ uri: getFileFromTSDescription(trace.trace.sink.label)
140
+ },
141
+ region: {
142
+ startLine: getLineFromTSDescription(trace.trace.sink.label)
143
+ }
144
+ },
145
+ logicalLocations: [
146
+ {
147
+ fullyQualifiedName: getLogicalLocationFromTSDescription(trace.trace.sink.label)
148
+ }
149
+ ]
150
+ });
111
151
  sarifRunBuilderIast.addResult(sarifResultBuilder);
112
152
  }
113
153
  return sarifRunBuilderIast;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/contrast",
3
- "version": "2.1.7",
3
+ "version": "2.2.0",
4
4
  "description": "Contrast Security's command line tool",
5
5
  "exports": "./dist/index.js",
6
6
  "type": "module",
@@ -116,7 +116,7 @@
116
116
  "ts-node": "^10.9.2",
117
117
  "typescript": "5.1.6",
118
118
  "uuid": "9.0.0",
119
- "vitest": "0.33.0"
119
+ "vitest": "1.4.0"
120
120
  },
121
121
  "resolutions": {
122
122
  "faker": "5.5.3",