-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.ts
238 lines (182 loc) · 7.39 KB
/
validation.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import { mkdir, readFile, unlink, writeFile } from 'fs/promises';
import { join, normalize } from 'path';
import { platform } from 'os';
import { Uri, workspace } from 'vscode';
import { Document } from 'yaml';
import { getWorkspaceConfig, getWorkspaceResources } from './workspace';
import { VALIDATION_FILE_SUFFIX, DEFAULT_CONFIG_FILE_NAME, TMP_POLICY_FILE_SUFFIX } from '../constants';
import { raiseInvalidConfigError } from './errors';
import logger from '../utils/logger';
import globals from './globals';
import type { Folder } from './workspace';
export type ConfigurableValidator = {
parser: any;
loader: any;
validator: any;
};
export type ConfigFileOptions = {
commentBefore?: string;
};
// Use default map with full list of plugins so it's easier
// for users to work with newly generated validation configuration file.
const DEFAULT_PLUGIN_MAP = {
'open-policy-agent': true,
'resource-links': true,
'yaml-syntax': true,
'kubernetes-schema': true,
'pod-security-standards': false,
'practices': false,
'metadata': false,
};
// Having multiple roots, each with different config will make it inefficient to reconfigure
// validator multiple times for a single validation run. That's why we will need separate
// validator for each root (which will be reconfigured only when root related config changes).
const VALIDATORS = new Map<string, {config: string, validator: ConfigurableValidator}>();
export async function getValidator(validatorId: string, config?: any) {
const validatorItem = VALIDATORS.get(validatorId);
const validatorObj = validatorItem?.validator ?? await getConfigurableValidator();
const validator = validatorObj.validator;
const oldConfig = validatorItem?.config ?? null;
const newConfig = JSON.stringify(config);
// Reconfigure validator only if config has changed.
if (oldConfig !== newConfig) {
await validator.preload(config);
}
VALIDATORS.set(validatorId, {
config: newConfig,
validator: validatorObj,
});
return validator;
}
export async function validateFolder(root: Folder): Promise<Uri | null> {
const resources = await getWorkspaceResources(root);
logger.log(root.name, 'resources');
if(!resources.length) {
return null;
}
resources.forEach(resource => logger.log(resource.id, resource.name, resource.content));
const workspaceConfig = await getWorkspaceConfig(root);
if (workspaceConfig.isValid === false) {
if (workspaceConfig.type === 'remote') {
return null; // Error will be already shown by policy puller.
}
raiseInvalidConfigError(workspaceConfig, root);
return null;
}
logger.log(root.name, 'workspaceConfig', workspaceConfig);
const validator = await getValidator(root.id, workspaceConfig.config);
logger.log(root.name, 'validator', validator);
const result = await validator.validate({
resources: resources,
});
logger.log(root.name, 'result', result);
result.runs.forEach(run => {
run.results.forEach((result: any) => {
const location = result.locations.find(location => location.physicalLocation?.artifactLocation?.uriBaseId === 'SRCROOT');
if (location && location.physicalLocation.artifactLocation.uri) {
location.physicalLocation.artifactLocation.uri = normalizePathForWindows(location.physicalLocation.artifactLocation.uri);
}
});
});
const resultsFilePath = await saveValidationResults(result, root.id);
logger.log(root.name, 'resultsFilePath', resultsFilePath);
return Uri.file(resultsFilePath);
}
export async function getValidationResult(fileName: string) {
const filePath = getValidationResultPath(fileName);
try {
const resultsAsString = await readFile(filePath, 'utf8');
return JSON.parse(resultsAsString);
} catch (e) {
return null;
}
}
export async function saveValidationResults(results: any, fileName: string) {
await mkdir(globals.storagePath, { recursive: true });
const resultsAsString = JSON.stringify(results);
const filePath = getValidationResultPath(fileName);
await writeFile(filePath, resultsAsString);
return filePath;
}
export function getValidationResultPath(fileName: string) {
return normalize(join(globals.storagePath, `${fileName}${VALIDATION_FILE_SUFFIX}`));
}
export async function createTemporaryConfigFile(config: any, ownerRoot: Folder) {
const commentBefore = [
` The '${ownerRoot.name}' folder uses default validation configuration. This file is readonly.`,
` You can adjust configuration by generating local configuration file with 'Monokle: Bootstrap configuration' command`,
` or by pointing to existing Monokle configuration file in 'monokle.configurationPath' setting.`
].join('\n');
return saveConfig(config, globals.storagePath, `${ownerRoot.id}${TMP_POLICY_FILE_SUFFIX}`, {commentBefore});
}
export async function createDefaultConfigFile(ownerRootDir: string) {
const config = {
plugins: DEFAULT_PLUGIN_MAP,
};
const commentBefore = [
' This is default validation configuration. You can adjust it freely to suit your needs.',
' You can read more about Monokle validation configuration here:',
' https://github.com/kubeshop/monokle-core/blob/main/packages/validation/docs/configuration.md#monokle-validation-configuration.',
].join('\n');
return saveConfig(config, ownerRootDir, DEFAULT_CONFIG_FILE_NAME, {commentBefore});
}
export async function saveConfig(config: any, path: string, fileName: string, options?: ConfigFileOptions) {
const configDoc = new Document();
configDoc.contents = config;
if (options?.commentBefore) {
configDoc.commentBefore = options.commentBefore;
}
const dir = normalize(path);
const filePath = normalize(join(dir, fileName));
await mkdir(dir, { recursive: true });
await writeFile(filePath, configDoc.toString());
return Uri.file(filePath);
}
export async function removeConfig(path: string, fileName: string) {
try {
const dir = normalize(path);
const filePath = normalize(join(dir, fileName));
await unlink(filePath);
return true;
} catch (err) {
return false;
}
}
export async function clearResourceCache(root: Folder, resourceId: string) {
const validatorItem = VALIDATORS.get(root.id);
const parser = validatorItem?.validator?.parser;
logger.log('clearResourceCache', !!parser, root.name, resourceId);
if (parser) {
parser.clear([resourceId]);
}
}
export async function readConfig(path: string) {
const {readConfig} = await import('@monokle/validation');
return readConfig(path);
}
export async function getDefaultConfig() {
return (await getDefaultValidator()).config;
}
async function getDefaultValidator() {
const {createDefaultMonokleValidator} = await import('@monokle/validation');
return createDefaultMonokleValidator();
}
async function getConfigurableValidator() {
const {ResourceParser, SchemaLoader, MonokleValidator, createDefaultPluginLoader} = await import('@monokle/validation');
const parser = new ResourceParser();
const schemaLoader = new SchemaLoader();
return {
parser,
loader: schemaLoader,
validator: new MonokleValidator(createDefaultPluginLoader(parser, schemaLoader)),
};
}
// For some reason (according to specs? to be checked) SARIF extension doesn't like
// valid Windows paths, which are "C:\path\to\file.yaml". It expects them to have
// unix like separators, so "C:/path/to/file.yaml".
function normalizePathForWindows(path: string) {
if (platform() === 'win32') {
return path.replace(/\\/g, '/');
}
return path;
}