Skip to content

Commit

Permalink
fix: point to the correct projects collection in the platform
Browse files Browse the repository at this point in the history
When a user runs a scan inside a git repo we pointed to the wrong projects collection, in this PR we fix this issue.
  • Loading branch information
YairZ101 committed Mar 28, 2022
1 parent 6eaa3a9 commit 0a98806
Show file tree
Hide file tree
Showing 10 changed files with 81 additions and 22 deletions.
7 changes: 5 additions & 2 deletions src/cli/commands/test/iac-local-execution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,22 +130,25 @@ export async function test(
);

let projectPublicIds: Record<string, string> = {};
let gitRemoteUrl: string | undefined;

if (options.report) {
projectPublicIds = await formatAndShareResults({
({ projectPublicIds, gitRemoteUrl } = await formatAndShareResults({
results: resultsWithCustomSeverities,
options,
orgPublicId,
policy,
tags,
attributes,
});
}));
}

const formattedResults = formatScanResults(
resultsWithCustomSeverities,
options,
iacOrgSettings.meta,
projectPublicIds,
gitRemoteUrl,
);

const { filteredIssues, ignoreCount } = filterIgnoredIssues(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function formatScanResults(
options: IaCTestFlags,
meta: TestMeta,
projectPublicIds: Record<string, string>,
gitRemoteUrl?: string,
): FormattedResult[] {
try {
const groupedByFile = scanResults.reduce((memo, scanResult) => {
Expand All @@ -35,6 +36,7 @@ export function formatScanResults(
...res.result.cloudConfigResults,
);
} else {
res.meta.gitRemoteUrl = gitRemoteUrl;
res.meta.projectId = projectPublicIds[res.targetFile];
memo[scanResult.filePath] = res;
}
Expand Down
4 changes: 2 additions & 2 deletions src/cli/commands/test/iac-local-execution/share-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Policy } from '../../../../lib/policy/find-and-load-policy';
import { ProjectAttributes, Tag } from '../../../../lib/types';
import { FeatureFlagError } from './assert-iac-options-flag';
import { formatShareResults } from './share-results-formatter';
import { IacFileScanResult, IaCTestFlags } from './types';
import { IacFileScanResult, IaCTestFlags, ShareResultsOutput } from './types';

export async function formatAndShareResults({
results,
Expand All @@ -20,7 +20,7 @@ export async function formatAndShareResults({
policy: Policy | undefined;
tags?: Tag[];
attributes?: ProjectAttributes;
}): Promise<Record<string, string>> {
}): Promise<ShareResultsOutput> {
const isCliReportEnabled = await isFeatureFlagSupportedForOrg(
'iacCliShareResults',
orgPublicId,
Expand Down
6 changes: 6 additions & 0 deletions src/cli/commands/test/iac-local-execution/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export interface TestMeta {
ignoreSettings?: IgnoreSettings | null;
projectId?: string;
policy?: string;
gitRemoteUrl?: string;
}

export interface OpaWasmInstance {
Expand Down Expand Up @@ -400,3 +401,8 @@ export enum PerformanceAnalyticsKey {
CacheCleanup = 'cache-cleanup-ms',
Total = 'total-iac-ms',
}

export interface ShareResultsOutput {
projectPublicIds: { [targetFile: string]: string };
gitRemoteUrl?: string;
}
31 changes: 18 additions & 13 deletions src/cli/commands/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ import chalk from 'chalk';
import { MissingArgError } from '../../../lib/errors';

import * as snyk from '../../../lib';
import { IacFileInDirectory, Options, TestOptions } from '../../../lib/types';
import {
IacFileInDirectory,
IacOutputMeta,
Options,
TestOptions,
} from '../../../lib/types';
import { MethodArgs } from '../../args';
import { TestCommandResult } from '../../commands/types';
import { LegacyVulnApiResult, TestResult } from '../../../lib/snyk-test/legacy';
Expand All @@ -17,7 +22,10 @@ import {
summariseVulnerableResults,
} from '../../../lib/formatters';
import * as utils from './utils';
import { getIacDisplayErrorFileOutput } from '../../../lib/formatters/iac-output';
import {
getIacDisplayErrorFileOutput,
shareResultsOutput,
} from '../../../lib/formatters/iac-output';
import { getEcosystemForTest, testEcosystem } from '../../../lib/ecosystems';
import { hasFixes, hasPatches, hasUpgrades } from '../../../lib/vuln-helpers';
import { FailOn } from '../../../lib/snyk-test/common';
Expand All @@ -43,7 +51,6 @@ import {
containsSpotlightVulnIds,
notificationForSpotlightVulns,
} from '../../../lib/spotlight-vuln-notification';
import config from '../../../lib/config';
import { isIacShareResultsOptions } from './iac-local-execution/assert-iac-options-flag';
import { assertIaCOptionsFlags } from './iac-local-execution/assert-iac-options-flag';

Expand Down Expand Up @@ -95,6 +102,7 @@ export default async function test(

// Holds an array of scanned file metadata for output.
let iacScanFailures: IacFileInDirectory[] | undefined;
let iacOutputMeta: IacOutputMeta | undefined;

// Promise waterfall to test all other paths sequentially
for (const path of paths) {
Expand All @@ -110,8 +118,11 @@ export default async function test(
if (options.iac) {
assertIaCOptionsFlags(process.argv);
const { results, failures } = await iacTest(path, testOpts);
testOpts.org = results[0]?.org;
testOpts.projectName = results[0]?.projectName;
iacOutputMeta = {
orgName: results[0]?.org,
projectName: results[0]?.projectName,
gitRemoteUrl: results[0]?.meta?.gitRemoteUrl,
};
res = results;
iacScanFailures = failures;
} else {
Expand Down Expand Up @@ -297,10 +308,7 @@ export default async function test(
response += spotlightVulnsMsg;

if (isIacShareResultsOptions(options)) {
response +=
chalk.bold.white(
`Your test results are available at: ${config.ROOT}/org/${resultOptions[0].org}/projects under the name ${resultOptions[0].projectName}`,
) + EOL;
response += chalk.bold.white(shareResultsOutput(iacOutputMeta!)) + EOL;
}

const error = new Error(response) as any;
Expand All @@ -322,10 +330,7 @@ export default async function test(
);

if (isIacShareResultsOptions(options)) {
response +=
chalk.bold.white(
`Your test results are available at: ${config.ROOT}/org/${resultOptions[0].org}/projects under the name ${resultOptions[0].projectName}`,
) + EOL;
response += chalk.bold.white(shareResultsOutput(iacOutputMeta!)) + EOL;
}

return TestCommandResult.createHumanReadableTestCommandResult(
Expand Down
15 changes: 14 additions & 1 deletion src/lib/formatters/iac-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import { printPath } from './remediation-based-format-issues';
import { titleCaseText } from './legacy-format-issue';
import * as sarif from 'sarif';
import { colorTextBySeverity } from '../../lib/snyk-test/common';
import { IacFileInDirectory } from '../../lib/types';
import { IacFileInDirectory, IacOutputMeta } from '../../lib/types';
import { isLocalFolder } from '../../lib/detect';
import { getSeverityValue } from './get-severity-value';
import { getIssueLevel } from './sarif-output';
import { getVersion } from '../version';
import config from '../config';
const debug = Debug('iac-output');

function formatIacIssue(
Expand Down Expand Up @@ -317,3 +318,15 @@ function getPathRelativeToRepoRoot(
const fullPath = pathLib.resolve(basePath, filePath).replace(/\\/g, '/');
return fullPath.replace(repoRoot, '');
}

export function shareResultsOutput(iacOutputMeta: IacOutputMeta): string {
let projectName: string = iacOutputMeta.projectName;
if (iacOutputMeta?.gitRemoteUrl) {
// from "http://github.com/snyk/cli.git" to "snyk/cli"
projectName = iacOutputMeta.gitRemoteUrl.replace(
/^https?:\/\/github.com\/(.*)\.git$/,
'$1',
);
}
return `Your test results are available at: ${config.ROOT}/org/${iacOutputMeta.orgName}/projects under the name ${projectName}`;
}
5 changes: 3 additions & 2 deletions src/lib/iac/cli-share-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getAuthHeader } from '../api-token';
import {
IacShareResultsFormat,
IaCTestFlags,
ShareResultsOutput,
} from '../../cli/commands/test/iac-local-execution/types';
import { convertIacResultToScanResult } from './envelope-formatters';
import { Policy } from '../policy/find-and-load-policy';
Expand All @@ -30,7 +31,7 @@ export async function shareResults({
tags?: Tag[];
attributes?: ProjectAttributes;
options?: IaCTestFlags;
}): Promise<Record<string, string>> {
}): Promise<ShareResultsOutput> {
const gitTarget = (await getInfo(false)) as GitTarget;
const scanResults = results.map((result) =>
convertIacResultToScanResult(result, policy, gitTarget, options),
Expand Down Expand Up @@ -72,5 +73,5 @@ export async function shareResults({
);
}

return body;
return { projectPublicIds: body, gitRemoteUrl: gitTarget?.remoteUrl };
}
6 changes: 6 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,9 @@ export interface IacFileInDirectory {
projectType?: IacProjectTypes;
failureReason?: string;
}

export interface IacOutputMeta {
projectName: string;
orgName: string;
gitRemoteUrl?: string;
}
2 changes: 1 addition & 1 deletion test/jest/acceptance/iac/cli-share-results.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('CLI Share Results', () => {
expect(exitCode).toBe(1);

expect(stdout).toContain(
`Your test results are available at: http://localhost:${server.getPort()}/org/test-org/projects under the name arm`,
`Your test results are available at: http://localhost:${server.getPort()}/org/test-org/projects under the name snyk/cli`,
);
});

Expand Down
25 changes: 24 additions & 1 deletion test/jest/unit/lib/formatters/iac-output.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { createSarifOutputForIac } from '../../../../../src/lib/formatters/iac-output';
import {
createSarifOutputForIac,
shareResultsOutput,
} from '../../../../../src/lib/formatters/iac-output';
import {
IacTestResponse,
AnnotatedIacIssue,
Expand Down Expand Up @@ -106,3 +109,23 @@ describe('createSarifOutputForIac', () => {
expect(location?.physicalLocation?.region).not.toBeDefined();
});
});

describe('shareResultsOutput', () => {
it('returns the correct output when gitRemoteUrl is specified', () => {
const output = shareResultsOutput({
projectName: 'test-project',
orgName: 'test-org',
gitRemoteUrl: 'http://github.com/test/repo.git',
});

expect(output).toContain('under the name test/repo');
});
it('returns the correct output when gitRemoteUrl is not specified', () => {
const output = shareResultsOutput({
projectName: 'test-project',
orgName: 'test-org',
});

expect(output).toContain('under the name test-project');
});
});

0 comments on commit 0a98806

Please sign in to comment.