-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
dockerValidator.ts
1823 lines (1641 loc) · 98.2 KB
/
dockerValidator.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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------------------------
* Copyright (c) Remy Suen. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import { TextDocument } from 'vscode-languageserver-textdocument';
import { Diagnostic, DiagnosticSeverity, DiagnosticTag, Position, Range, uinteger } from 'vscode-languageserver-types';
import { Dockerfile, Flag, Instruction, JSONInstruction, Add, Arg, Cmd, Copy, Entrypoint, From, Healthcheck, Onbuild, ModifiableInstruction, PropertyInstruction, Property, DockerfileParser, Directive, Keyword, Argument, Run } from 'dockerfile-ast';
import { ValidationCode, ValidationSeverity, ValidatorSettings } from './main';
export const KEYWORDS = [
"ADD",
"ARG",
"CMD",
"COPY",
"ENTRYPOINT",
"ENV",
"EXPOSE",
"FROM",
"HEALTHCHECK",
"LABEL",
"MAINTAINER",
"ONBUILD",
"RUN",
"SHELL",
"STOPSIGNAL",
"USER",
"VOLUME",
"WORKDIR"
];
export interface DockerfileDiagnostic extends Diagnostic {
/**
* Position of the instruction position in a document (zero-based).
* This may be null if the diagnostic is not for an instruction (for
* example, the diagnostic may be for a parser directive).
*/
instructionLine: uinteger | null;
}
/**
* A list of variables that are prepopulated when using the BuildKit
* backend.
*/
const PREDEFINED_VARIABLES = [
"TARGETPLATFORM",
"TARGETOS",
"TARGETARCH",
"TARGETVARIANT",
"BUILDPLATFORM",
"BUILDOS",
"BUILDARCH",
"BUILDVARIAN"
];
export class Validator {
private document: TextDocument;
private settings: ValidatorSettings = {
deprecatedMaintainer: ValidationSeverity.WARNING,
directiveCasing: ValidationSeverity.WARNING,
emptyContinuationLine: ValidationSeverity.WARNING,
instructionCasing: ValidationSeverity.WARNING,
instructionCmdMultiple: ValidationSeverity.WARNING,
instructionEntrypointMultiple: ValidationSeverity.WARNING,
instructionHealthcheckMultiple: ValidationSeverity.WARNING,
instructionJSONInSingleQuotes: ValidationSeverity.WARNING,
instructionWorkdirRelative: ValidationSeverity.WARNING
}
constructor(settings?: ValidatorSettings) {
if (settings) {
this.settings = settings;
}
}
private checkDirectives(dockerfile: Dockerfile, problems: Diagnostic[]) {
const duplicatedEscapes = [];
for (const directive of dockerfile.getDirectives()) {
if (directive.getDirective() === Directive.escape) {
duplicatedEscapes.push(directive);
}
}
if (duplicatedEscapes.length > 1) {
// multiple escape parser directives have been found
for (let i = 1; i < duplicatedEscapes.length; i++) {
problems.push(Validator.createDuplicatedEscapeDirective(duplicatedEscapes[i].getNameRange().start, duplicatedEscapes[i].getValueRange().end));
}
return
}
for (const directive of dockerfile.getDirectives()) {
const directiveName = directive.getDirective();
if (directiveName === Directive.escape) {
const value = directive.getValue();
if (value !== '\\' && value !== '`' && value !== "") {
// if the directive's value is invalid or isn't the empty string, flag it
const range = directive.getValueRange();
problems.push(Validator.createInvalidEscapeDirective(range.start, range.end, value));
}
if (directive.getName() !== Directive.escape) {
const range = directive.getNameRange();
const diagnostic = this.createLowercaseDirective(range.start, range.end);
if (diagnostic) {
problems.push(diagnostic);
}
}
}
}
}
/**
* Checks the arguments of the given instruction.
*
* @param instruction the instruction to validate
* @param problems an array of identified problems in the document
* @param expectedArgCount an array of expected number of arguments
* for the instruction, if its length is 1
* and its value is -1, any number of
* arguments greater than zero is valid
* @param validate the function to use to validate an argument
* @param createIncompleteDiagnostic the function to use to create a diagnostic
* if the number of arguments is incorrect
*/
private checkArguments(instruction: Instruction, problems: Diagnostic[], expectedArgCount: number[],
validate: Function, createIncompleteDiagnostic?: Function): void {
let args = instruction instanceof PropertyInstruction ? instruction.getPropertyArguments() : instruction.getArguments();
if (args.length === 0) {
if (instruction.getKeyword() !== Keyword.RUN) {
// all instructions are expected to have at least one argument
const range = instruction.getInstructionRange();
problems.push(Validator.createMissingArgument(range.start.line, range.start, range.end));
}
} else if (expectedArgCount[0] === -1) {
for (let i = 0; i < args.length; i++) {
let createInvalidDiagnostic = validate(i, args[i].getValue(), args[i].getRange());
if (createInvalidDiagnostic) {
let range = args[i].getRange();
problems.push(createInvalidDiagnostic(instruction.getInstructionRange().start.line, range.start, range.end, args[i].getValue()));
}
}
} else {
for (let i = 0; i < expectedArgCount.length; i++) {
if (expectedArgCount[i] === args.length) {
for (let j = 0; j < args.length; j++) {
let range = args[j].getRange();
let createInvalidDiagnostic = validate(j, args[j].getValue(), range);
if (createInvalidDiagnostic instanceof Function) {
problems.push(createInvalidDiagnostic(instruction.getInstructionRange().start.line, range.start, range.end, args[j].getValue()));
} else if (createInvalidDiagnostic !== null) {
problems.push(createInvalidDiagnostic);
}
}
return;
}
}
let range = args[args.length - 1].getRange();
if (createIncompleteDiagnostic) {
problems.push(createIncompleteDiagnostic(instruction.getInstructionRange().start.line, range.start, range.end));
} else {
problems.push(Validator.createExtraArgument(instruction.getInstructionRange().start.line, range.start, range.end));
}
}
}
private checkVariables(instruction: Instruction, problems: Diagnostic[]): void {
for (let variable of instruction.getVariables()) {
let modifier = variable.getModifier();
if (modifier !== null) {
switch (instruction.getKeyword()) {
case Keyword.CMD:
case Keyword.ENTRYPOINT:
case Keyword.RUN:
// allow shell expansions to go through for RUN instructions
break;
default:
if (modifier === "") {
problems.push(Validator.createVariableUnsupportedModifier(instruction.getRange().start.line, variable.getRange(), variable.toString(), modifier));
} else if (modifier !== '+' && modifier !== '-' && modifier !== '?') {
problems.push(Validator.createVariableUnsupportedModifier(instruction.getRange().start.line, variable.getModifierRange(), variable.toString(), modifier));
}
break;
}
}
}
}
private checkProperty(document: TextDocument, escapeChar: string, keyword: string, instructionLine: uinteger, property: Property, firstProperty: boolean, optionalValue: boolean, problems: Diagnostic[]): void {
let name = property.getName();
if (name === "") {
let range = property.getRange();
problems.push(Validator.createSyntaxMissingNames(instructionLine, range.start, range.end, keyword));
} else if (name.indexOf('=') !== -1) {
let nameRange = property.getNameRange();
let unescapedName = document.getText(nameRange);
let index = unescapedName.indexOf('=');
if (unescapedName.charAt(0) === '\'') {
problems.push(Validator.createSyntaxMissingSingleQuote(instructionLine, nameRange.start, document.positionAt(document.offsetAt(nameRange.start) + index), unescapedName.substring(0, unescapedName.indexOf('='))));
} else if (unescapedName.charAt(0) === '"') {
problems.push(Validator.createSyntaxMissingDoubleQuote(instructionLine, nameRange.start, document.positionAt(document.offsetAt(nameRange.start) + index), unescapedName.substring(0, unescapedName.indexOf('='))));
}
return;
}
let value = property.getValue();
if (value === null) {
if (!optionalValue) {
let range = property.getNameRange();
if (firstProperty) {
problems.push(Validator.createENVRequiresTwoArguments(instructionLine, range.start, range.end));
} else {
problems.push(Validator.createSyntaxMissingEquals(instructionLine, range.start, range.end, name));
}
}
} else if (value.charAt(0) === '"') {
let found = false;
for (let i = 1; i < value.length; i++) {
switch (value.charAt(i)) {
case escapeChar:
i++;
break;
case '"':
if (i === value.length - 1) {
found = true;
}
break;
}
}
if (!found) {
let range = property.getValueRange();
problems.push(Validator.createSyntaxMissingDoubleQuote(instructionLine, range.start, range.end, property.getUnescapedValue()));
}
} else if (value.charAt(0) === '\'' && value.charAt(value.length - 1) !== '\'') {
let range = property.getValueRange();
problems.push(Validator.createSyntaxMissingSingleQuote(instructionLine, range.start, range.end, value));
}
}
validate(document: TextDocument): Diagnostic[] {
this.document = document;
let problems: DockerfileDiagnostic[] = [];
let dockerfile = DockerfileParser.parse(document.getText());
this.checkDirectives(dockerfile, problems);
let instructions = dockerfile.getInstructions();
if (instructions.length === 0 || dockerfile.getARGs().length === instructions.length) {
// no instructions in this file, or only ARGs
problems.push(Validator.createNoSourceImage(document.positionAt(0), document.positionAt(0)));
}
let cmds: Cmd[] = [];
let entrypoints: Entrypoint[] = [];
let healthchecks: Healthcheck[] = [];
for (let instruction of instructions) {
if (instruction instanceof Cmd) {
cmds.push(instruction);
} else if (instruction instanceof Entrypoint) {
entrypoints.push(instruction);
} else if (instruction instanceof Healthcheck) {
healthchecks.push(instruction);
} else if (instruction instanceof From) {
this.createDuplicatesDiagnostics(problems, this.settings.instructionCmdMultiple, "CMD", cmds);
this.createDuplicatesDiagnostics(problems, this.settings.instructionEntrypointMultiple, "ENTRYPOINT", entrypoints);
this.createDuplicatesDiagnostics(problems, this.settings.instructionHealthcheckMultiple, "HEALTHCHECK", healthchecks);
cmds = [];
entrypoints = [];
healthchecks = [];
}
}
this.createDuplicatesDiagnostics(problems, this.settings.instructionCmdMultiple, "CMD", cmds);
this.createDuplicatesDiagnostics(problems, this.settings.instructionEntrypointMultiple, "ENTRYPOINT", entrypoints);
this.createDuplicatesDiagnostics(problems, this.settings.instructionHealthcheckMultiple, "HEALTHCHECK", healthchecks);
this.createDuplicateBuildStageNameDiagnostics(problems, dockerfile.getFROMs());
let escapeChar = dockerfile.getEscapeCharacter();
let hasFrom = false;
for (let instruction of dockerfile.getInstructions()) {
let keyword = instruction.getKeyword();
if (keyword === "FROM") {
hasFrom = true;
} else if (!hasFrom && keyword !== "ARG") {
// first non-ARG instruction is not a FROM
let range = instruction.getInstructionRange();
problems.push(Validator.createNoSourceImage(range.start, range.end));
hasFrom = true;
}
this.validateInstruction(document, escapeChar, instruction, keyword, false, problems);
this.checkVariables(instruction, problems);
}
for (let instruction of dockerfile.getOnbuildTriggers()) {
this.validateInstruction(document, escapeChar, instruction, instruction.getKeyword(), true, problems);
}
const ignoredLines = [];
for (const comment of dockerfile.getComments()) {
if (comment.getContent() === "dockerfile-utils: ignore") {
ignoredLines.push(comment.getRange().start.line);
}
}
problemsCheck: for (let i = 0; i < problems.length; i++) {
if (problems[i].instructionLine !== null) {
for (const ignoredLine of ignoredLines) {
if (ignoredLine + 1 === problems[i].instructionLine) {
problems.splice(i, 1);
i--;
continue problemsCheck;
}
}
}
}
return problems;
}
/**
* Retrieves the line numbers that corresponds to the content of
* here-documents in the given instruction. The line numbers are
* zero-based.
*
* @param instruction the instruction to check
* @returns an array of line numbers where content of
* here-documents are defined
*/
private getHeredocLines(instruction: Instruction): number[] {
if (instruction instanceof Copy || instruction instanceof Run) {
const lines: number[] = [];
for (const heredoc of instruction.getHeredocs()) {
const range = heredoc.getContentRange();
if (range !== null) {
for (let i = range.start.line; i <= range.end.line; i++) {
lines.push(i);
}
}
}
return lines;
}
return []
}
private validateInstruction(document: TextDocument, escapeChar: string, instruction: Instruction, keyword: string, isTrigger: boolean, problems: Diagnostic[]): void {
if (KEYWORDS.indexOf(keyword) === -1) {
let range = instruction.getInstructionRange();
// invalid instruction found
problems.push(Validator.createUnknownInstruction(range.start.line, range.start, range.end, keyword));
} else {
if (keyword !== instruction.getInstruction()) {
let range = instruction.getInstructionRange();
// warn about uppercase convention if the keyword doesn't match the actual instruction
let diagnostic = this.createUppercaseInstruction(range.start.line, range.start, range.end);
if (diagnostic) {
problems.push(diagnostic);
}
}
if (keyword === "MAINTAINER") {
let range = instruction.getInstructionRange();
let diagnostic = this.createMaintainerDeprecated(range.start.line, range.start, range.end);
if (diagnostic) {
problems.push(diagnostic);
}
}
const fullRange = instruction.getRange();
if (fullRange.start.line !== fullRange.end.line && !isTrigger) {
// if the instruction spans multiple lines, check for empty newlines
const content = document.getText();
const endingLine = fullRange.end.line;
const skippedLines = this.getHeredocLines(instruction);
let skipIndex = 0;
let start = -1;
for (let i = fullRange.start.line; i <= endingLine; i++) {
if (i === skippedLines[skipIndex]) {
skipIndex++;
continue;
}
const lineContent = content.substring(document.offsetAt(Position.create(i, 0)), document.offsetAt(Position.create(i + 1, 0)));
if (lineContent.trim().length === 0) {
if (start === -1) {
start = i;
continue;
}
} else if (start !== -1) {
const diagnostic = Validator.createEmptyContinuationLine(Position.create(start, 0), Position.create(i, 0), this.settings.emptyContinuationLine);
if (diagnostic) {
problems.push(diagnostic);
}
start = -1;
}
}
if (start !== -1) {
const diagnostic = Validator.createEmptyContinuationLine(Position.create(start, 0), Position.create(endingLine + 1, 0), this.settings.emptyContinuationLine);
if (diagnostic) {
problems.push(diagnostic);
}
start = -1;
}
}
switch (keyword) {
case "CMD":
this.checkJSONQuotes(instruction, problems);
break;
case "ENTRYPOINT":
case "RUN":
case "VOLUME":
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
this.checkJSONQuotes(instruction, problems);
break;
case "ARG":
this.checkArguments(instruction, problems, [-1], () => null);
let arg = instruction as Arg;
let argProperty = arg.getProperty();
if (argProperty) {
this.checkProperty(document, escapeChar, keyword, instruction.getRange().start.line, argProperty, true, true, problems);
}
break;
case "ENV":
case "LABEL":
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
let properties = (instruction as PropertyInstruction).getProperties();
if (properties.length === 1) {
this.checkProperty(document, escapeChar, keyword, instruction.getRange().start.line, properties[0], true, false, problems);
} else if (properties.length !== 0) {
for (let property of properties) {
this.checkProperty(document, escapeChar, keyword, instruction.getRange().start.line, property, false, false, problems);
}
}
break;
case "FROM":
const fromInstructionRange = instruction.getInstructionRange();
const fromFlags = (instruction as ModifiableInstruction).getFlags();
for (const flag of fromFlags) {
const flagName = flag.getName();
if (flagName !== "platform") {
const range = flag.getRange();
problems.push(Validator.createUnknownFromFlag(fromInstructionRange.start.line, range.start, flagName === "" ? range.end : flag.getNameRange().end, flag.getName()));
}
}
this.checkFlagValue(fromInstructionRange.start.line, fromFlags, [ "platform"], problems);
this.checkArguments(instruction, problems, [1, 3], function (index: number, argument: string, range: Range): Diagnostic | Function | null {
switch (index) {
case 0:
let variables = instruction.getVariables();
if (variables.length > 0) {
let variableRange = variables[0].getRange();
if (variableRange.start.line === range.start.line
&& variableRange.start.character === range.start.character
&& variableRange.end.line === range.end.line
&& variableRange.end.character === range.end.character) {
if (!variables[0].isDefined()) {
if (PREDEFINED_VARIABLES.indexOf(variables[0].getName()) !== -1) {
return null;
}
return Validator.createBaseNameEmpty(fromInstructionRange.start.line, variableRange, variables[0].toString());
}
}
return null;
}
let from = instruction as From;
let digestRange = from.getImageDigestRange();
const tagRange = from.getImageTagRange();
if (digestRange === null) {
if (tagRange === null) {
return null;
}
let tag = document.getText(tagRange);
if (tag === "") {
// no tag specified, just highlight the whole argument
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, range);
}
let tagRegexp = new RegExp(/^[\w][\w.-]{0,127}$/);
if (tagRegexp.test(tag)) {
return null;
}
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, from.getImageTagRange());
}
if (tagRange !== null) {
// specified an optional tag with the digest
if (tagRange.start.line === tagRange.end.line && tagRange.start.character === tagRange.end.character) {
// tag is empty, flag the whole argument as an error
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, range);
}
}
let digest = document.getText(digestRange);
let algorithmIndex = digest.indexOf(':');
if (algorithmIndex === -1) {
if (digest === "") {
// no digest specified, just highlight the whole argument
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, range);
}
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, from.getImageDigestRange());
}
let algorithmRegexp = new RegExp(/[A-Fa-f0-9_+.-]+/);
let algorithm = digest.substring(0, algorithmIndex);
if (!algorithmRegexp.test(algorithm)) {
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, from.getImageDigestRange());
}
let hex = digest.substring(algorithmIndex + 1);
let hexRegexp = new RegExp(/[A-Fa-f0-9]+/);
if (hexRegexp.test(hex)) {
return null;
}
return Validator.createInvalidReferenceFormat(fromInstructionRange.start.line, from.getImageDigestRange());
case 1:
return argument.toUpperCase() === "AS" ? null : Validator.createInvalidAs;
case 2:
argument = argument.toLowerCase();
let regexp = new RegExp(/^[a-z]([a-z0-9_\-.]*)*$/);
if (regexp.test(argument)) {
return null;
}
return Validator.createInvalidBuildStageName(fromInstructionRange.start.line, range, argument);;
default:
return null;
}
}, Validator.createRequiresOneOrThreeArguments);
break;
case "HEALTHCHECK":
let args = instruction.getArguments();
const healthcheckInstructionRange = instruction.getInstructionRange();
const healthcheckFlags = (instruction as ModifiableInstruction).getFlags();
if (args.length === 0) {
// all instructions are expected to have at least one argument
problems.push(Validator.createHEALTHCHECKRequiresAtLeastOneArgument(healthcheckInstructionRange.start.line, healthcheckInstructionRange));
} else {
const value = args[0].getValue();
const uppercase = value.toUpperCase();
if (uppercase === "NONE") {
// check that NONE doesn't have any arguments after it
if (args.length > 1) {
// get the next argument
const start = args[1].getRange().start;
// get the last argument
const end = args[args.length - 1].getRange().end;
// highlight everything after the NONE and warn the user
problems.push(Validator.createHealthcheckNoneUnnecessaryArgument(healthcheckInstructionRange.start.line, start, end));
}
// don't need to validate flags of a NONE
break;
} else if (uppercase === "CMD") {
if (args.length === 1) {
// this HEALTHCHECK has a CMD with no arguments
const range = args[0].getRange();
problems.push(Validator.createHealthcheckCmdArgumentMissing(healthcheckInstructionRange.start.line, range.start, range.end));
}
} else {
// unknown HEALTHCHECK type
problems.push(Validator.createHealthcheckTypeUnknown(healthcheckInstructionRange.start.line, args[0].getRange(), uppercase));
}
}
const validFlags = ["interval", "retries", "start-period", "timeout", "start-interval"];
for (const flag of healthcheckFlags) {
const flagName = flag.getName();
if (validFlags.indexOf(flagName) === -1) {
const range = flag.getRange();
problems.push(Validator.createUnknownHealthcheckFlag(healthcheckInstructionRange.start.line, range.start, flagName === "" ? range.end : flag.getNameRange().end, flag.getName()));
} else if (flagName === "retries") {
const value = flag.getValue();
if (value) {
const valueRange = flag.getValueRange();
const integer = parseInt(value);
// test for NaN or numbers with decimals
if (isNaN(integer) || value.indexOf('.') !== -1) {
problems.push(Validator.createInvalidSyntax(healthcheckInstructionRange.start.line, valueRange.start, valueRange.end, value));
} else if (integer < 1) {
problems.push(Validator.createFlagAtLeastOne(healthcheckInstructionRange.start.line, valueRange.start, valueRange.end, "--retries", integer.toString()));
}
}
}
}
this.checkFlagValue(healthcheckInstructionRange.start.line, healthcheckFlags, validFlags, problems);
this.checkFlagDuration(healthcheckInstructionRange.start.line, healthcheckFlags, ["interval", "start-period", "timeout", "start-interval"], problems);
this.checkDuplicateFlags(healthcheckInstructionRange.start.line, healthcheckFlags, validFlags, problems);
break;
case "ONBUILD":
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
let onbuild = instruction as Onbuild;
let trigger = onbuild.getTrigger();
switch (trigger) {
case "FROM":
case "MAINTAINER":
problems.push(Validator.createOnbuildTriggerDisallowed(onbuild.getInstructionRange().start.line, onbuild.getTriggerRange(), trigger));
break;
case "ONBUILD":
problems.push(Validator.createOnbuildChainingDisallowed(onbuild.getInstructionRange().start.line, onbuild.getTriggerRange()));
break;
}
break;
case "SHELL":
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
this.checkJSON(document, instruction as JSONInstruction, problems);
break;
case "STOPSIGNAL":
this.checkArguments(instruction, problems, [1], function (_index: number, argument: string) {
if (argument.indexOf("SIG") === 0 || argument.indexOf('$') != -1) {
return null;
}
for (var i = 0; i < argument.length; i++) {
if ('0' > argument.charAt(i) || '9' < argument.charAt(i)) {
return Validator.createInvalidStopSignal;
}
}
return null;
});
let stopsignalArgs = instruction.getExpandedArguments();
if (stopsignalArgs.length === 1) {
let value = stopsignalArgs[0].getValue();
let variables = instruction.getVariables();
if (variables.length === 0) {
if (value.indexOf('$') !== -1) {
const instructionRange = instruction.getInstructionRange();
let range = stopsignalArgs[0].getRange();
problems.push(Validator.createInvalidStopSignal(instructionRange.start.line, range.start, range.end, value));
}
} else {
for (let variable of variables) {
let variableRange = variable.getRange();
let variableDefinition = this.document.getText().substring(
this.document.offsetAt(variableRange.start),
this.document.offsetAt(variableRange.end)
);
// an un-expanded variable is here
if (value.includes(variableDefinition) && !variable.isBuildVariable() && !variable.isDefined()) {
const instructionRange = instruction.getInstructionRange();
let range = stopsignalArgs[0].getRange();
problems.push(Validator.createInvalidStopSignal(instructionRange.start.line, range.start, range.end, ""));
break;
}
}
}
}
break;
case "EXPOSE":
let exposeArgs = instruction.getArguments();
let exposeExpandedArgs = instruction.getExpandedArguments();
if (exposeExpandedArgs.length === 0) {
let range = instruction.getInstructionRange();
problems.push(Validator.createMissingArgument(range.start.line, range.start, range.end));
} else {
const regex = /^([0-9])+(-[0-9]+)?(:([0-9])+(-[0-9]*)?)?(\/(\w*))?(\/\w*)*$/;
argCheck: for (let i = 0; i < exposeExpandedArgs.length; i++) {
let value = exposeExpandedArgs[i].getValue()
if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
value = value.substring(1, value.length - 1);
}
const match = regex.exec(value);
if (match) {
if (match[7]) {
const protocol = match[7].toLowerCase();
if (protocol !== "" && protocol !== "tcp" && protocol !== "udp" && protocol !== "sctp") {
const range = exposeExpandedArgs[i].getRange();
const rangeStart = this.document.offsetAt(range.start);
const rawArg = this.document.getText().substring(
rangeStart, this.document.offsetAt(range.end)
);
const start = rangeStart + rawArg.indexOf(match[7].substring(0, 1));
const end = protocol.length === 1 ? rangeStart + start + 1 : rangeStart + rawArg.length;
problems.push(Validator.createInvalidProto(instruction.getInstructionRange().start.line, this.document.positionAt(start), this.document.positionAt(end), match[7]));
}
}
} else {
// see if we're referencing a variable here
if (value.charAt(0) === '$') {
continue argCheck;
}
problems.push(Validator.createInvalidPort(instruction.getInstructionRange().start.line, exposeExpandedArgs[i].getRange(), value));
}
}
}
break;
case "ADD":
const add = instruction as Add;
const addFlags = add.getFlags();
const addInstructionRange = instruction.getInstructionRange();
for (let flag of addFlags) {
const name = flag.getName();
const flagRange = flag.getRange();
if (name === "") {
problems.push(Validator.createUnknownAddFlag(addInstructionRange.start.line, flagRange.start, flagRange.end, name));
} else if (name === "link" || name === "keep-git-dir") {
const problem = this.checkFlagBoolean(addInstructionRange.start.line, flag);
if (problem !== null) {
problems.push(problem);
}
} else if (name !== "chmod" && name !== "chown" && name !== "checksum" && name !== "exclude") {
let range = flag.getNameRange();
problems.push(Validator.createUnknownAddFlag(addInstructionRange.start.line, flagRange.start, range.end, name));
}
}
const addDestinationDiagnostic = this.checkDestinationIsDirectory(add, Validator.createADDRequiresAtLeastTwoArguments, Validator.createADDDestinationNotDirectory);
if (addDestinationDiagnostic !== null) {
problems.push(addDestinationDiagnostic);
}
this.checkFlagValue(addInstructionRange.start.line, addFlags, ["chmod", "chown", "checksum", "exclude"], problems);
this.checkDuplicateFlags(addInstructionRange.start.line, addFlags, ["chmod", "chown", "checksum", "keep-git-dir", "link"], problems);
this.checkJSONQuotes(instruction, problems);
break;
case "COPY":
const copyInstructionRange = instruction.getInstructionRange();
let copy = instruction as Copy;
let flags = copy.getFlags();
if (flags.length > 0) {
for (let flag of flags) {
const name = flag.getName();
const flagRange = flag.getRange();
if (name === "") {
problems.push(Validator.createUnknownCopyFlag(copyInstructionRange.start.line, flagRange.start, flagRange.end, name));
} else if (name === "link") {
const problem = this.checkFlagBoolean(copyInstructionRange.start.line, flag);
if (problem !== null) {
problems.push(problem);
}
} else if (name !== "chmod" && name !== "chown" && name !== "from" && name !== "exclude") {
let range = flag.getNameRange();
problems.push(Validator.createUnknownCopyFlag(copyInstructionRange.start.line, flagRange.start, range.end, name));
}
}
let flag = copy.getFromFlag();
if (flag) {
let value = flag.getValue();
if (value !== null) {
let regexp = new RegExp(/^[a-zA-Z0-9].*$/);
if (!regexp.test(value)) {
let range = value === "" ? flag.getRange() : flag.getValueRange();
problems.push(Validator.createFlagInvalidFrom(copyInstructionRange.start.line, range.start, range.end, value));
}
}
}
}
const copyDestinationDiagnostic = this.checkDestinationIsDirectory(copy, Validator.createCOPYRequiresAtLeastTwoArguments, Validator.createCOPYDestinationNotDirectory);
if (copyDestinationDiagnostic !== null) {
problems.push(copyDestinationDiagnostic);
}
this.checkFlagValue(copyInstructionRange.start.line, flags, ["chmod", "chown", "from", "exclude"], problems);
this.checkDuplicateFlags(copyInstructionRange.start.line, flags, ["chmod", "chown", "from", "link"], problems);
this.checkJSONQuotes(instruction, problems);
break;
case "WORKDIR":
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
let content = instruction.getArgumentsContent();
if (content) {
// strip out any surrounding quotes
const first = content.substring(0, 1);
const last = content.substring(content.length - 1);
if ((first === '\'' && last === '\'') || (first === '"' && last === '"')) {
content = content.substring(1, content.length - 1);
}
let regexp = new RegExp(/^(\$|([a-zA-Z](\$|:(\$|\\|\/)))).*$/);
if (!content.startsWith('/') && !regexp.test(content)) {
let problem = this.createWORKDIRNotAbsolute(instruction.getInstructionRange().start.line, instruction.getArgumentsRange());
if (problem) {
problems.push(problem);
}
}
}
break;
default:
this.checkArguments(instruction, problems, [-1], function (): any {
return null;
});
break;
}
}
}
private hasHeredocs(args: Argument[]): boolean {
for (const arg of args) {
if (arg.getValue().startsWith("<<")) {
return true;
}
}
return false;
}
private getDestinationArgument(args: Argument[]): Argument {
if (this.hasHeredocs(args)) {
const initialLine = args[0].getRange().start.line;
let candidate: Argument | null = null;
for (let i = 1; i < args.length; i++) {
if (args[i].getRange().start.line === initialLine) {
candidate = args[i];
} else {
// stop searching once we're on another line
break;
}
}
return candidate;
}
return args[args.length - 1];
}
private checkDestinationIsDirectory(instruction: JSONInstruction, requiresTwoArgumentsFunction: (instructionLine: uinteger, range: Range) => Diagnostic, notDirectoryFunction: (instructionLine: uinteger, range: Range) => Diagnostic): Diagnostic | null {
if (instruction.getClosingBracket()) {
return this.checkJsonDestinationIsDirectory(instruction, requiresTwoArgumentsFunction, notDirectoryFunction);
}
const args = instruction.getArguments();
if (args.length === 1) {
return requiresTwoArgumentsFunction(instruction.getInstructionRange().start.line, args[0].getRange());
} else if (args.length === 0) {
const instructionRange = instruction.getInstructionRange();
return requiresTwoArgumentsFunction(instructionRange.start.line, instructionRange);
} else if (args.length > 2) {
const lastArg = this.getDestinationArgument(args);
if (lastArg === null) {
const instructionRange = instruction.getInstructionRange();
return requiresTwoArgumentsFunction(instructionRange.start.line, instructionRange);
} else if (this.hasHeredocs(args)) {
return null;
}
const variables = instruction.getVariables();
if (variables.length !== 0) {
const lastJsonStringOffset = this.document.offsetAt(lastArg.getRange().end);
const lastVarOffset = this.document.offsetAt(variables[variables.length - 1].getRange().end);
if (lastJsonStringOffset === lastVarOffset || lastJsonStringOffset -1 === lastVarOffset) {
return null;
}
}
const destination = lastArg.getValue();
const lastChar = destination.charAt(destination.length - 1);
if (lastChar !== '\\' && lastChar !== '/') {
return notDirectoryFunction(instruction.getInstructionRange().start.line, lastArg.getRange());
}
}
return null;
}
private createDuplicatesDiagnostics(problems: Diagnostic[], severity: ValidationSeverity, instruction: string, instructions: Instruction[]): void {
if (instructions.length > 1) {
// decrement length by 1 because we want to ignore the last one
for (let i = 0; i < instructions.length - 1; i++) {
const instructionRange = instructions[i].getInstructionRange();
const diagnostic = this.createMultipleInstructions(instructionRange.start.line, instructionRange, severity, instruction);
if (diagnostic) {
problems.push(diagnostic);
}
}
}
}
private createDuplicateBuildStageNameDiagnostics(problems: Diagnostic[], froms: From[]): void {
const names: any = {};
for (let from of froms) {
let name = from.getBuildStage();
if (name !== null) {
name = name.toLowerCase();
if (names[name] === undefined) {
names[name] = [from];
} else {
names[name].push(from);
}
}
}
for (const name in names) {
// duplicates found
if (names[name].length > 1) {
for (const from of names[name]) {
problems.push(Validator.createDuplicateBuildStageName(from.getInstructionRange().start.line, from.getBuildStageRange(), name));
}
}
}
}
private checkJsonDestinationIsDirectory(instruction: JSONInstruction, requiresTwoArgumentsFunction: (instructionLine: uinteger, range: Range) => Diagnostic, notDirectoryFunction: (instructionLine: uinteger, range: Range) => Diagnostic): Diagnostic | null {
const jsonStrings = instruction.getJSONStrings();
if (jsonStrings.length === 0) {
return requiresTwoArgumentsFunction(instruction.getInstructionRange().start.line, instruction.getArgumentsRange());
} else if (jsonStrings.length === 1) {
return requiresTwoArgumentsFunction(instruction.getInstructionRange().start.line, jsonStrings[0].getJSONRange());
} else if (jsonStrings.length > 2) {
const lastJsonString = jsonStrings[jsonStrings.length - 1];
const variables = instruction.getVariables();
if (variables.length !== 0) {
const lastVar = variables[variables.length - 1];
const lastJsonStringOffset = this.document.offsetAt(lastJsonString.getRange().end);
const lastVarOffset = this.document.offsetAt(lastVar.getRange().end);
if (lastJsonStringOffset === lastVarOffset || lastJsonStringOffset -1 === lastVarOffset) {
return null;
}
}
const destination = lastJsonString.getValue();
const lastChar = destination.charAt(destination.length - 2);
if (lastChar !== '\\' && lastChar !== '/') {
return notDirectoryFunction(instruction.getInstructionRange().start.line, jsonStrings[jsonStrings.length - 1].getJSONRange());
}
}
return null;
}
private checkFlagValue(instructionLine: uinteger, flags: Flag[], validFlagNames: string[], problems: Diagnostic[]): void {
for (let flag of flags) {
let flagName = flag.getName();
// only validate flags with the right name
if (flag.getValue() === null && validFlagNames.indexOf(flagName) !== -1) {
problems.push(Validator.createFlagMissingValue(instructionLine, flag.getNameRange(), flagName));
}
}
}
/**
* Checks that the given boolean flag is valid. A boolean flag should
* either have no value defined (--flag) or the value should
* case-insensitively be either "true" or "false" (--flag==tRUe is
* valid).
*/
private checkFlagBoolean(instructionLine: uinteger, flag: Flag): Diagnostic | null {
const flagValue = flag.getValue();
if (flagValue === "") {
return Validator.createFlagMissingValue(instructionLine, flag.getNameRange(), flag.getName());
} else if (flagValue !== null) {
const convertedFlagValue = flagValue.toLowerCase();
if (convertedFlagValue !== "true" && convertedFlagValue !== "false") {
return Validator.createFlagExpectedBooleanValue(instructionLine, flag.getValueRange(), flag.getName(), flagValue);
}
}
return null;
}
private checkFlagDuration(instructionLine: uinteger, flags: Flag[], validFlagNames: string[], problems: Diagnostic[]): void {
flagCheck: for (let flag of flags) {
let flagName = flag.getName();
// only validate flags with the right name
if (validFlagNames.indexOf(flagName) !== -1) {
let value = flag.getValue();
if (value !== null && value.length !== 0) {
switch (value.charAt(0)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
case '-':
break;
default:
let range = flag.getValueRange();
problems.push(Validator.createFlagInvalidDuration(instructionLine, range.start, range.end, value));
continue flagCheck;
}
let durationSpecified = false;
let start = 0;
let duration = 0;
let digitFound = false;
let hyphenFound = false;
let periodsDetected = 0;
durationParse: for (let i = 0; i < value.length; i++) {
durationSpecified = false;
switch (value.charAt(i)) {
case '-':
if (digitFound) {
let range = flag.getValueRange();
problems.push(Validator.createFlagUnknownUnit(instructionLine, range, value.charAt(i), value));
continue flagCheck;
} else if (hyphenFound) {
let range = flag.getValueRange();
problems.push(Validator.createFlagInvalidDuration(instructionLine, range.start, range.end, value));
continue flagCheck;
}
hyphenFound = true;
continue;
case '.':
periodsDetected++;
continue;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':