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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
|
import is from '@sindresorhus/is';
import { getLanguageList, getManagerList } from '../modules/manager';
import { configRegexPredicate, isConfigRegex, regEx } from '../util/regex';
import * as template from '../util/template';
import {
hasValidSchedule,
hasValidTimezone,
} from '../workers/repository/update/branch/schedule';
import { migrateConfig } from './migration';
import { getOptions } from './options';
import { resolveConfigPresets } from './presets';
import type {
RenovateConfig,
RenovateOptions,
ValidationMessage,
ValidationResult,
} from './types';
import * as managerValidator from './validation-helpers/managers';
const options = getOptions();
let optionTypes: Record<string, RenovateOptions['type']>;
let optionParents: Record<string, RenovateOptions['parent']>;
const managerList = getManagerList();
const topLevelObjects = getLanguageList().concat(getManagerList());
const ignoredNodes = [
'$schema',
'depType',
'npmToken',
'packageFile',
'forkToken',
'repository',
'vulnerabilityAlertsOnly',
'vulnerabilityAlert',
'isVulnerabilityAlert',
'copyLocalLibs', // deprecated - functionality is now enabled by default
'prBody', // deprecated
'minimumConfidence', // undocumented feature flag
];
const tzRe = regEx(/^:timezone\((.+)\)$/);
const rulesRe = regEx(/p.*Rules\[\d+\]$/);
function isManagerPath(parentPath: string): boolean {
return (
regEx(/^regexManagers\[[0-9]+]$/).test(parentPath) ||
managerList.includes(parentPath)
);
}
function isIgnored(key: string): boolean {
return ignoredNodes.includes(key);
}
function validateAliasObject(val: Record<string, unknown>): true | string {
for (const [key, value] of Object.entries(val)) {
if (!is.urlString(value)) {
return key;
}
}
return true;
}
function validatePlainObject(val: Record<string, unknown>): true | string {
for (const [key, value] of Object.entries(val)) {
if (!is.string(value)) {
return key;
}
}
return true;
}
function getUnsupportedEnabledManagers(enabledManagers: string[]): string[] {
return enabledManagers.filter(
(manager) => !getManagerList().includes(manager)
);
}
function getDeprecationMessage(option: string): string | undefined {
const deprecatedOptions: Record<string, string | undefined> = {
branchName: `Direct editing of branchName is now deprecated. Please edit branchPrefix, additionalBranchPrefix, or branchTopic instead`,
commitMessage: `Direct editing of commitMessage is now deprecated. Please edit commitMessage's subcomponents instead.`,
prTitle: `Direct editing of prTitle is now deprecated. Please edit commitMessage subcomponents instead as they will be passed through to prTitle.`,
};
return deprecatedOptions[option];
}
export function getParentName(parentPath: string | undefined): string {
return parentPath
? parentPath
.replace(regEx(/\.?encrypted$/), '')
.replace(regEx(/\[\d+\]$/), '')
.split('.')
.pop()!
: '.';
}
export async function validateConfig(
config: RenovateConfig,
isPreset?: boolean,
parentPath?: string
): Promise<ValidationResult> {
if (!optionTypes) {
optionTypes = {};
options.forEach((option) => {
optionTypes[option.name] = option.type;
});
}
if (!optionParents) {
optionParents = {};
options.forEach((option) => {
if (option.parent) {
optionParents[option.name] = option.parent;
}
});
}
let errors: ValidationMessage[] = [];
let warnings: ValidationMessage[] = [];
for (const [key, val] of Object.entries(config)) {
const currentPath = parentPath ? `${parentPath}.${key}` : key;
// istanbul ignore if
if (key === '__proto__') {
errors.push({
topic: 'Config security error',
message: '__proto__',
});
continue;
}
if (parentPath && topLevelObjects.includes(key)) {
errors.push({
topic: 'Configuration Error',
message: `The "${key}" object can only be configured at the top level of a config but was found inside "${parentPath}"`,
});
}
if (key === 'enabledManagers' && val) {
const unsupportedManagers = getUnsupportedEnabledManagers(
val as string[]
);
if (is.nonEmptyArray(unsupportedManagers)) {
errors.push({
topic: 'Configuration Error',
message: `The following managers configured in enabledManagers are not supported: "${unsupportedManagers.join(
', '
)}"`,
});
}
}
if (key === 'fileMatch') {
if (parentPath === undefined) {
errors.push({
topic: 'Config error',
message: `"fileMatch" may not be defined at the top level of a config and must instead be within a manager block`,
});
} else if (!isManagerPath(parentPath)) {
warnings.push({
topic: 'Config warning',
message: `"fileMatch" must be configured in a manager block and not here: ${parentPath}`,
});
}
}
if (
!isIgnored(key) && // We need to ignore some reserved keys
!(is as any).function(val) // Ignore all functions
) {
if (getDeprecationMessage(key)) {
warnings.push({
topic: 'Deprecation Warning',
message: getDeprecationMessage(key)!,
});
}
const templateKeys = [
'branchName',
'commitBody',
'commitMessage',
'prTitle',
'semanticCommitScope',
];
if ((key.endsWith('Template') || templateKeys.includes(key)) && val) {
try {
// TODO: validate string #7154
let res = template.compile((val as string).toString(), config, false);
res = template.compile(res, config, false);
template.compile(res, config, false);
} catch (err) {
errors.push({
topic: 'Configuration Error',
message: `Invalid template in config path: ${currentPath}`,
});
}
}
const parentName = getParentName(parentPath);
if (
!isPreset &&
optionParents[key] &&
optionParents[key] !== parentName
) {
// TODO: types (#7154)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const message = `${key} should only be configured within a "${optionParents[key]}" object. Was found in ${parentName}`;
warnings.push({
topic: `${parentPath ? `${parentPath}.` : ''}${key}`,
message,
});
}
if (!optionTypes[key]) {
errors.push({
topic: 'Configuration Error',
message: `Invalid configuration option: ${currentPath}`,
});
} else if (key === 'schedule') {
const [validSchedule, errorMessage] = hasValidSchedule(val as string[]);
if (!validSchedule) {
errors.push({
topic: 'Configuration Error',
message: `Invalid ${currentPath}: \`${errorMessage}\``,
});
}
} else if (
['allowedVersions', 'matchCurrentVersion'].includes(key) &&
isConfigRegex(val)
) {
if (!configRegexPredicate(val)) {
errors.push({
topic: 'Configuration Error',
message: `Invalid regExp for ${currentPath}: \`${val}\``,
});
}
} else if (
key === 'matchCurrentValue' &&
is.string(val) &&
!configRegexPredicate(val)
) {
errors.push({
topic: 'Configuration Error',
message: `Invalid regExp for ${currentPath}: \`${val}\``,
});
} else if (key === 'timezone' && val !== null) {
const [validTimezone, errorMessage] = hasValidTimezone(val as string);
if (!validTimezone) {
errors.push({
topic: 'Configuration Error',
message: `${currentPath}: ${errorMessage}`,
});
}
} else if (val !== null) {
const type = optionTypes[key];
if (type === 'boolean') {
if (val !== true && val !== false) {
errors.push({
topic: 'Configuration Error',
message: `Configuration option \`${currentPath}\` should be boolean. Found: ${JSON.stringify(
val
)} (${typeof val})`,
});
}
} else if (type === 'integer') {
if (!is.number(val)) {
errors.push({
topic: 'Configuration Error',
message: `Configuration option \`${currentPath}\` should be an integer. Found: ${JSON.stringify(
val
)} (${typeof val})`,
});
}
} else if (type === 'array' && val) {
if (is.array(val)) {
for (const [subIndex, subval] of val.entries()) {
if (is.object(subval)) {
const subValidation = await validateConfig(
subval as RenovateConfig,
isPreset,
`${currentPath}[${subIndex}]`
);
warnings = warnings.concat(subValidation.warnings);
errors = errors.concat(subValidation.errors);
}
}
if (key === 'extends') {
for (const subval of val) {
if (is.string(subval)) {
if (
parentName === 'packageRules' &&
subval.startsWith('group:')
) {
warnings.push({
topic: 'Configuration Warning',
message: `${currentPath}: you should not extend "group:" presets`,
});
}
if (tzRe.test(subval)) {
const [, timezone] = tzRe.exec(subval)!;
const [validTimezone, errorMessage] =
hasValidTimezone(timezone);
if (!validTimezone) {
errors.push({
topic: 'Configuration Error',
message: `${currentPath}: ${errorMessage}`,
});
}
}
} else {
errors.push({
topic: 'Configuration Warning',
message: `${currentPath}: preset value is not a string`,
});
}
}
}
const selectors = [
'matchFiles',
'matchPaths',
'matchLanguages',
'matchBaseBranches',
'matchManagers',
'matchDatasources',
'matchDepTypes',
'matchDepNames',
'matchDepPatterns',
'matchPackageNames',
'matchPackagePatterns',
'matchPackagePrefixes',
'excludeDepNames',
'excludeDepPatterns',
'excludePackageNames',
'excludePackagePatterns',
'excludePackagePrefixes',
'matchCurrentValue',
'matchCurrentVersion',
'matchSourceUrlPrefixes',
'matchSourceUrls',
'matchUpdateTypes',
];
if (key === 'packageRules') {
for (const [subIndex, packageRule] of val.entries()) {
if (is.object(packageRule)) {
const resolvedRule = migrateConfig({
packageRules: [
await resolveConfigPresets(
packageRule as RenovateConfig,
config
),
],
}).migratedConfig.packageRules![0];
errors.push(
...managerValidator.check({ resolvedRule, currentPath })
);
const selectorLength = Object.keys(resolvedRule).filter(
(ruleKey) => selectors.includes(ruleKey)
).length;
if (!selectorLength) {
const message = `${currentPath}[${subIndex}]: Each packageRule must contain at least one match* or exclude* selector. Rule: ${JSON.stringify(
packageRule
)}`;
errors.push({
topic: 'Configuration Error',
message,
});
}
if (selectorLength === Object.keys(resolvedRule).length) {
const message = `${currentPath}[${subIndex}]: Each packageRule must contain at least one non-match* or non-exclude* field. Rule: ${JSON.stringify(
packageRule
)}`;
warnings.push({
topic: 'Configuration Error',
message,
});
}
// It's too late to apply any of these options once you already have updates determined
const preLookupOptions = [
'allowedVersions',
'extractVersion',
'followTag',
'ignoreDeps',
'ignoreUnstable',
'rangeStrategy',
'registryUrls',
'respectLatest',
'rollbackPrs',
'separateMajorMinor',
'separateMinorPatch',
'separateMultipleMajor',
'versioning',
];
if (is.nonEmptyArray(resolvedRule.matchUpdateTypes)) {
for (const option of preLookupOptions) {
if (resolvedRule[option] !== undefined) {
const message = `${currentPath}[${subIndex}]: packageRules cannot combine both matchUpdateTypes and ${option}. Rule: ${JSON.stringify(
packageRule
)}`;
errors.push({
topic: 'Configuration Error',
message,
});
}
}
}
} else {
errors.push({
topic: 'Configuration Error',
message: `${currentPath} must contain JSON objects`,
});
}
}
}
if (key === 'regexManagers') {
const allowedKeys = [
'description',
'fileMatch',
'matchStrings',
'matchStringsStrategy',
'depNameTemplate',
'packageNameTemplate',
'datasourceTemplate',
'versioningTemplate',
'registryUrlTemplate',
'currentValueTemplate',
'extractVersionTemplate',
'autoReplaceStringTemplate',
'depTypeTemplate',
];
// TODO: fix types #7154
for (const regexManager of val as any[]) {
if (
Object.keys(regexManager).some(
(k) => !allowedKeys.includes(k)
)
) {
const disallowedKeys = Object.keys(regexManager).filter(
(k) => !allowedKeys.includes(k)
);
errors.push({
topic: 'Configuration Error',
message: `Regex Manager contains disallowed fields: ${disallowedKeys.join(
', '
)}`,
});
} else if (is.nonEmptyArray(regexManager.fileMatch)) {
if (is.nonEmptyArray(regexManager.matchStrings)) {
let validRegex = false;
for (const matchString of regexManager.matchStrings) {
try {
regEx(matchString);
validRegex = true;
} catch (e) {
errors.push({
topic: 'Configuration Error',
message: `Invalid regExp for ${currentPath}: \`${String(
matchString
)}\``,
});
}
}
if (validRegex) {
const mandatoryFields = [
'depName',
'currentValue',
'datasource',
];
for (const field of mandatoryFields) {
if (
!regexManager[`${field}Template`] &&
!regexManager.matchStrings.some(
(matchString: string) =>
matchString.includes(`(?<${field}>`)
)
) {
errors.push({
topic: 'Configuration Error',
message: `Regex Managers must contain ${field}Template configuration or regex group named ${field}`,
});
}
}
}
} else {
errors.push({
topic: 'Configuration Error',
message: `Each Regex Manager must contain a non-empty matchStrings array`,
});
}
} else {
errors.push({
topic: 'Configuration Error',
message: `Each Regex Manager must contain a non-empty fileMatch array`,
});
}
}
}
if (
[
'matchPackagePatterns',
'excludePackagePatterns',
'matchDepPatterns',
'excludeDepPatterns',
].includes(key)
) {
for (const pattern of val as string[]) {
if (pattern !== '*') {
try {
regEx(pattern);
} catch (e) {
errors.push({
topic: 'Configuration Error',
message: `Invalid regExp for ${currentPath}: \`${pattern}\``,
});
}
}
}
}
if (key === 'fileMatch') {
for (const fileMatch of val as string[]) {
try {
regEx(fileMatch);
} catch (e) {
errors.push({
topic: 'Configuration Error',
message: `Invalid regExp for ${currentPath}: \`${fileMatch}\``,
});
}
}
}
if (
(selectors.includes(key) ||
key === 'matchCurrentVersion' ||
key === 'matchCurrentValue') &&
// TODO: can be undefined ? #7154
!rulesRe.test(parentPath!) && // Inside a packageRule
(parentPath || !isPreset) // top level in a preset
) {
errors.push({
topic: 'Configuration Error',
message: `${currentPath}: ${key} should be inside a \`packageRule\` only`,
});
}
} else {
errors.push({
topic: 'Configuration Error',
message: `Configuration option \`${currentPath}\` should be a list (Array)`,
});
}
} else if (type === 'string') {
if (!is.string(val)) {
errors.push({
topic: 'Configuration Error',
message: `Configuration option \`${currentPath}\` should be a string`,
});
}
} else if (
type === 'object' &&
currentPath !== 'compatibility' &&
currentPath !== 'constraints' &&
currentPath !== 'force.constraints'
) {
if (is.plainObject(val)) {
if (key === 'registryAliases') {
const res = validateAliasObject(val);
if (res !== true) {
errors.push({
topic: 'Configuration Error',
message: `Invalid \`${currentPath}.${key}.${res}\` configuration: value is not a url`,
});
}
} else if (
['customEnvVariables', 'migratePresets', 'secrets'].includes(key)
) {
const res = validatePlainObject(val);
if (res !== true) {
errors.push({
topic: 'Configuration Error',
message: `Invalid \`${currentPath}.${key}.${res}\` configuration: value is not a string`,
});
}
} else {
const ignoredObjects = options
.filter((option) => option.freeChoice)
.map((option) => option.name);
if (!ignoredObjects.includes(key)) {
const subValidation = await validateConfig(
val,
isPreset,
currentPath
);
warnings = warnings.concat(subValidation.warnings);
errors = errors.concat(subValidation.errors);
}
}
} else {
errors.push({
topic: 'Configuration Error',
message: `Configuration option \`${currentPath}\` should be a json object`,
});
}
}
}
}
}
function sortAll(a: ValidationMessage, b: ValidationMessage): number {
// istanbul ignore else: currently never happen
if (a.topic === b.topic) {
return a.message > b.message ? 1 : -1;
}
// istanbul ignore next: currently never happen
return a.topic > b.topic ? 1 : -1;
}
errors.sort(sortAll);
warnings.sort(sortAll);
return { errors, warnings };
}
|