-
Notifications
You must be signed in to change notification settings - Fork 533
/
index.ts
188 lines (171 loc) · 5.47 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { existsSync } from 'fs';
import { isLocalFolder } from '../../../../../lib/detect';
import {
EngineType,
IaCErrorCodes,
IacFileParsed,
IacFileParseFailure,
IacOrgSettings,
IaCTestFlags,
RulesOrigin,
SafeAnalyticsOutput,
TestReturnValue,
} from './types';
import { addIacAnalytics } from './analytics';
import { TestLimitReachedError } from './usage-tracking';
import { TestResult } from '../../../../../lib/snyk-test/legacy';
import {
applyCustomSeverities,
loadContentForFiles,
parseFiles,
scanFiles,
trackUsage,
} from './measurable-methods';
import { findAndLoadPolicy } from '../../../../../lib/policy';
import { ResultsProcessor } from './process-results';
import { generateProjectAttributes, generateTags } from '../../../monitor';
import {
getAllDirectoriesForPath,
getFilesForDirectory,
} from './directory-loader';
import { CustomError } from '../../../../../lib/errors';
import { getErrorStringCode } from './error-utils';
import { NoFilesToScanError } from './file-loader';
import { Tag } from '../../../../../lib/types';
// this method executes the local processing engine and then formats the results to adapt with the CLI output.
// this flow is the default GA flow for IAC scanning.
export async function test(
resultsProcessor: ResultsProcessor,
pathToScan: string,
options: IaCTestFlags,
iacOrgSettings: IacOrgSettings,
rulesOrigin: RulesOrigin,
): Promise<TestReturnValue> {
// Parse tags and attributes right now, so we can exit early if the user
// provided invalid values.
const tags = parseTags(options);
const attributes = parseAttributes(options);
const policy = await findAndLoadPolicy(pathToScan, 'iac', options);
let allParsedFiles: IacFileParsed[] = [],
allFailedFiles: IacFileParseFailure[] = [];
const allDirectories = getAllDirectoriesForPath(
pathToScan,
options.detectionDepth,
);
// we load and parse files directory by directory
// because we need all files in the same directory to share the same variable context for Terraform
for (const currentDirectory of allDirectories) {
const filePathsInDirectory = getFilesForDirectory(
pathToScan,
currentDirectory,
);
if (
currentDirectory === pathToScan &&
shouldLoadVarDefinitionsFile(options)
) {
const varDefinitionsFilePath = options['var-file'];
filePathsInDirectory.push(varDefinitionsFilePath);
}
const filesToParse = await loadContentForFiles(filePathsInDirectory);
const { parsedFiles, failedFiles } = await parseFiles(
filesToParse,
options,
);
allParsedFiles = allParsedFiles.concat(parsedFiles);
allFailedFiles = allFailedFiles.concat(failedFiles);
}
if (allParsedFiles.length === 0) {
if (allFailedFiles.length === 0) {
throw new NoFilesToScanError();
} else {
// we throw an array of errors in order to get the path of the files which generated an error
throw allFailedFiles.map((f) => f.err);
}
}
// Duplicate all the files and run them through the custom engine.
if (rulesOrigin !== RulesOrigin.Internal) {
allParsedFiles.push(
...allParsedFiles.map((file) => ({
...file,
engineType: EngineType.Custom,
})),
);
}
// NOTE: No file or parsed file data should leave this function.
let failures = isLocalFolder(pathToScan)
? allFailedFiles.map(removeFileContent)
: [];
const { scannedFiles, failedScans } = await scanFiles(allParsedFiles);
failures = [...failures, ...failedScans];
const resultsWithCustomSeverities = await applyCustomSeverities(
scannedFiles,
iacOrgSettings.customPolicies,
);
const { filteredIssues, ignoreCount } = await resultsProcessor.processResults(
resultsWithCustomSeverities,
policy,
tags,
attributes,
);
try {
await trackUsage(filteredIssues, iacOrgSettings.meta.org);
} catch (e) {
if (e instanceof TestLimitReachedError) {
throw e;
}
// If something has gone wrong, err on the side of allowing the user to
// run their tests by squashing the error.
}
addIacAnalytics(filteredIssues, {
ignoredIssuesCount: ignoreCount,
rulesOrigin,
});
// TODO: add support for proper typing of old TestResult interface.
return {
results: (filteredIssues as unknown) as TestResult[],
failures,
ignoreCount,
};
}
export function removeFileContent({
filePath,
fileType,
failureReason,
projectType,
}: IacFileParsed | IacFileParseFailure): SafeAnalyticsOutput {
return {
filePath,
fileType,
failureReason,
projectType,
};
}
export function parseTags(options: IaCTestFlags): Tag[] | undefined {
if (options.report) {
return generateTags(options);
}
}
function parseAttributes(options: IaCTestFlags) {
if (options.report) {
return generateProjectAttributes(options);
}
}
function shouldLoadVarDefinitionsFile(
options: IaCTestFlags,
): options is IaCTestFlags & { 'var-file': string } {
if (options['var-file']) {
if (!existsSync(options['var-file'])) {
throw new InvalidVarFilePath(options['var-file']);
}
return true;
}
return false;
}
export class InvalidVarFilePath extends CustomError {
constructor(path: string, message?: string) {
super(message || 'Invalid path to variable definitions file');
this.code = IaCErrorCodes.InvalidVarFilePath;
this.strCode = getErrorStringCode(this.code);
this.userMessage = `We were unable to locate a variable definitions file at: "${path}". The file at the provided path does not exist`;
}
}