-
Notifications
You must be signed in to change notification settings - Fork 163
/
rule_expression.go
1075 lines (938 loc) · 28.8 KB
/
rule_expression.go
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
package actionlint
import (
"strconv"
"strings"
)
//go:generate go run ./scripts/generate-availability ./availability.go
type typedExpr struct {
ty ExprType
pos Pos
}
// RuleExpression is a rule checker to check expression syntax in string values of workflow syntax.
// It checks syntax and semantics of the expressions including type checks and functions/contexts
// definitions. For more details see
// - https://docs.github.com/en/actions/learn-github-actions/contexts
// - https://docs.github.com/en/actions/learn-github-actions/expressions
type RuleExpression struct {
RuleBase
matrixTy *ObjectType
stepsTy *ObjectType
needsTy *ObjectType
secretsTy *ObjectType
inputsTy *ObjectType
dispatchInputsTy *ObjectType
jobsTy *ObjectType
workflow *Workflow
localActions *LocalActionsCache
localWorkflows *LocalReusableWorkflowCache
}
// NewRuleExpression creates new RuleExpression instance.
func NewRuleExpression(actionsCache *LocalActionsCache, workflowCache *LocalReusableWorkflowCache) *RuleExpression {
return &RuleExpression{
RuleBase: RuleBase{
name: "expression",
desc: "Syntax and semantics checks for expressions embedded with ${{ }} syntax",
},
matrixTy: nil,
stepsTy: nil,
needsTy: nil,
secretsTy: nil,
inputsTy: nil,
dispatchInputsTy: nil,
jobsTy: nil,
workflow: nil,
localActions: actionsCache,
localWorkflows: workflowCache,
}
}
// VisitWorkflowPre is callback when visiting Workflow node before visiting its children.
func (rule *RuleExpression) VisitWorkflowPre(n *Workflow) error {
rule.checkString(n.Name, "")
for _, e := range n.On {
switch e := e.(type) {
case *WebhookEvent:
rule.checkStrings(e.Types, "")
rule.checkWebhookEventFilter(e.Branches)
rule.checkWebhookEventFilter(e.BranchesIgnore)
rule.checkWebhookEventFilter(e.Tags)
rule.checkWebhookEventFilter(e.TagsIgnore)
rule.checkWebhookEventFilter(e.Paths)
rule.checkWebhookEventFilter(e.PathsIgnore)
rule.checkStrings(e.Workflows, "")
case *ScheduledEvent:
rule.checkStrings(e.Cron, "")
case *WorkflowDispatchEvent:
ity := NewEmptyStrictObjectType()
for id, i := range e.Inputs {
rule.checkString(i.Description, "")
rule.checkString(i.Default, "")
rule.checkBool(i.Required, "")
rule.checkStrings(i.Options, "")
var ty ExprType
switch i.Type {
case WorkflowDispatchEventInputTypeBoolean:
ty = BoolType{}
case WorkflowDispatchEventInputTypeNumber:
ty = NumberType{}
case WorkflowDispatchEventInputTypeString, WorkflowDispatchEventInputTypeChoice, WorkflowDispatchEventInputTypeEnvironment:
ty = StringType{}
default:
ty = AnyType{}
}
ity.Props[id] = ty
}
rule.dispatchInputsTy = ity
case *RepositoryDispatchEvent:
rule.checkStrings(e.Types, "")
case *WorkflowCallEvent:
ity := NewEmptyStrictObjectType()
// Set `inputs` context object before checking inputs since input's default values can refer `inputs` context.
// inputs:
// input1:
// type: string
// input2:
// type: string
// default: ${{ inputs.input1 }}
rule.inputsTy = ity
for _, i := range e.Inputs {
rule.checkString(i.Description, "")
// Check default value before setting type to `ity` because referring myself should cause an error.
// inputs:
// recursive:
// type: string
// default: ${{ inputs.recursive }}
ts := rule.checkString(i.Default, "on.workflow_call.inputs.<inputs_id>.default")
var ty ExprType
switch i.Type {
case WorkflowCallEventInputTypeString:
ty = StringType{}
case WorkflowCallEventInputTypeBoolean:
ty = BoolType{}
if len(ts) == 1 && i.Default.IsExpressionAssigned() {
switch ts[0].ty.(type) {
case BoolType, AnyType:
// ok
default:
rule.Errorf(i.Default.Pos, "type of input %q must be bool but found type %s", i.Name.Value, ts[0].ty.String())
}
}
case WorkflowCallEventInputTypeNumber:
ty = NumberType{}
if len(ts) == 1 && i.Default.IsExpressionAssigned() {
switch ts[0].ty.(type) {
case NumberType, AnyType:
// ok
default:
rule.Errorf(i.Default.Pos, "type of input %q must be number but found type %s", i.Name.Value, ts[0].ty.String())
}
}
default:
ty = AnyType{}
}
ity.Props[i.ID] = ty
}
// When no secret is passed, secrets may be inherited from a caller of the workflow.
// So `secrets` context must be typed as { string => string }. `e.Secrets` is nil when `secrets:` does not
// exist. When `e.Secrets` is an empty map, `secrets:` exists but it has no child.
if e.Secrets != nil {
sty := NewEmptyStrictObjectType()
for id, s := range e.Secrets {
sty.Props[id] = StringType{}
rule.checkString(s.Description, "")
}
rule.secretsTy = sty
}
for _, o := range e.Outputs {
rule.checkString(o.Description, "")
// o.Value will be checked in VisitWorkflowPost
}
}
}
rule.checkString(n.RunName, "run-name")
rule.checkEnv(n.Env, "env")
rule.checkDefaults(n.Defaults, "")
rule.checkConcurrency(n.Concurrency, "concurrency")
rule.workflow = n
return nil
}
// VisitWorkflowPost is callback when visiting Workflow node after visiting its children
func (rule *RuleExpression) VisitWorkflowPost(n *Workflow) error {
if e, ok := n.FindWorkflowCallEvent(); ok {
rule.checkWorkflowCallOutputs(e.Outputs, n.Jobs)
}
rule.workflow = nil
return nil
}
// VisitJobPre is callback when visiting Job node before visiting its children.
func (rule *RuleExpression) VisitJobPre(n *Job) error {
// Type of needs must be resolved before resolving type of matrix because `needs` context can
// be used in matrix configuration.
rule.needsTy = rule.calcNeedsType(n)
// Set matrix type at start of VisitJobPre() because matrix values are available in
// jobs.<job_id> section. For example:
// jobs:
// foo:
// strategy:
// matrix:
// os: [ubuntu-latest, macos-latest, windows-latest]
// runs-on: ${{ matrix.os }}
if n.Strategy != nil && n.Strategy.Matrix != nil {
// Check and guess type of the matrix
rule.matrixTy = rule.checkMatrix(n.Strategy.Matrix)
}
rule.checkString(n.Name, "jobs.<job_id>.name")
rule.checkStrings(n.Needs, "")
if n.RunsOn != nil {
if n.RunsOn.LabelsExpr != nil {
if ty := rule.checkOneExpression(n.RunsOn.LabelsExpr, "runner label at \"runs-on\" section", "jobs.<job_id>.runs-on"); ty != nil {
switch ty.(type) {
case *ArrayType, StringType, AnyType:
// OK
default:
rule.Errorf(n.RunsOn.LabelsExpr.Pos, "type of expression at \"runs-on\" must be string or array but found type %q", ty.String())
}
}
} else {
for _, l := range n.RunsOn.Labels {
rule.checkString(l, "jobs.<job_id>.runs-on")
}
}
rule.checkString(n.RunsOn.Group, "jobs.<job_id>.runs-on")
}
rule.checkConcurrency(n.Concurrency, "jobs.<job_id>.concurrency")
rule.checkEnv(n.Env, "jobs.<job_id>.env")
rule.checkDefaults(n.Defaults, "jobs.<job_id>.defaults.run")
rule.checkIfCondition(n.If, "jobs.<job_id>.if")
if n.Strategy != nil {
// Note: Types in "jobs.<job_id>.strategy.matrix" were checked `checkMatrix`
rule.checkBool(n.Strategy.FailFast, "jobs.<job_id>.strategy")
rule.checkInt(n.Strategy.MaxParallel, "jobs.<job_id>.strategy")
}
rule.checkBool(n.ContinueOnError, "jobs.<job_id>.continue-on-error")
rule.checkFloat(n.TimeoutMinutes, "jobs.<job_id>.timeout-minutes")
rule.checkContainer(n.Container, "jobs.<job_id>.container", "")
if n.Services != nil {
rule.checkObjectExpression(n.Services.Expression, "services", "jobs.<job_id>.services")
for _, s := range n.Services.Value {
rule.checkContainer(s.Container, "jobs.<job_id>.services", "<service_id>")
}
}
rule.checkWorkflowCall(n.WorkflowCall)
rule.stepsTy = NewEmptyStrictObjectType()
return nil
}
// VisitJobPost is callback when visiting Job node after visiting its children
func (rule *RuleExpression) VisitJobPost(n *Job) error {
// 'environment' and 'outputs' sections are evaluated after all steps are run
if n.Environment != nil {
rule.checkString(n.Environment.Name, "jobs.<job_id>.environment")
rule.checkString(n.Environment.URL, "jobs.<job_id>.environment.url")
}
for _, output := range n.Outputs {
rule.checkString(output.Value, "jobs.<job_id>.outputs.<output_id>")
}
rule.matrixTy = nil
rule.stepsTy = nil
rule.needsTy = nil
return nil
}
// VisitStep is callback when visiting Step node.
func (rule *RuleExpression) VisitStep(n *Step) error {
rule.checkString(n.Name, "jobs.<job_id>.steps.name")
rule.checkIfCondition(n.If, "jobs.<job_id>.steps.if")
var spec *String
switch e := n.Exec.(type) {
case *ExecRun:
rule.checkScriptString(e.Run, "jobs.<job_id>.steps.run")
rule.checkString(e.Shell, "")
rule.checkString(e.WorkingDirectory, "jobs.<job_id>.steps.working-directory")
case *ExecAction:
rule.checkString(e.Uses, "")
for n, i := range e.Inputs {
if e.Uses != nil && strings.HasPrefix(e.Uses.Value, "actions/github-script@") && n == "script" {
rule.checkScriptString(i.Value, "jobs.<job_id>.steps.with")
} else {
rule.checkString(i.Value, "jobs.<job_id>.steps.with")
}
}
rule.checkString(e.Entrypoint, "")
rule.checkString(e.Args, "")
spec = e.Uses
}
rule.checkEnv(n.Env, "jobs.<job_id>.steps.env") // env: at step level can refer 'env' context (#158)
rule.checkBool(n.ContinueOnError, "jobs.<job_id>.steps.continue-on-error")
rule.checkFloat(n.TimeoutMinutes, "jobs.<job_id>.steps.timeout-minutes")
if n.ID != nil {
if n.ID.ContainsExpression() {
rule.checkString(n.ID, "")
rule.stepsTy.Loose()
}
// Step ID is case insensitive
id := strings.ToLower(n.ID.Value)
rule.stepsTy.Props[id] = NewStrictObjectType(map[string]ExprType{
"outputs": rule.getActionOutputsType(spec),
"conclusion": StringType{},
"outcome": StringType{},
})
}
return nil
}
// Get type of `outputs.<output name>`
func (rule *RuleExpression) getActionOutputsType(spec *String) *ObjectType {
if spec == nil {
return NewMapObjectType(StringType{})
}
if strings.HasPrefix(spec.Value, "./") {
meta, _, err := rule.localActions.FindMetadata(spec.Value)
if err != nil {
rule.Error(spec.Pos, err.Error())
return NewMapObjectType(StringType{})
}
if meta == nil {
return NewMapObjectType(StringType{})
}
return typeOfActionOutputs(meta)
}
// github-script action allows to set any outputs through calling `core.setOutput` directly.
// So any `outputs.*` properties should be accepted (#104)
if strings.HasPrefix(spec.Value, "actions/github-script@") {
return NewEmptyObjectType()
}
// When the action run at this step is a popular action, we know what outputs are set by it.
// Set the output names to `steps.{step_id}.outputs.{name}`.
if meta, ok := PopularActions[spec.Value]; ok {
return typeOfActionOutputs(meta)
}
return NewMapObjectType(StringType{})
}
func (rule *RuleExpression) getWorkflowCallOutputsType(call *WorkflowCall) *ObjectType {
if call.Uses == nil {
return NewMapObjectType(StringType{})
}
m, err := rule.localWorkflows.FindMetadata(call.Uses.Value)
if err != nil {
rule.Error(call.Uses.Pos, err.Error())
return NewMapObjectType(StringType{})
}
if m == nil {
return NewMapObjectType(StringType{})
}
p := make(map[string]ExprType, len(m.Outputs))
for n := range m.Outputs {
p[n] = StringType{}
}
return NewStrictObjectType(p)
}
func (rule *RuleExpression) checkOneExpression(s *String, what, workflowKey string) ExprType {
// checkString is not available since it checks types for embedding values into a string
if s == nil {
return nil
}
ts, ok := rule.checkExprsIn(s.Value, s.Pos, s.Quoted, false, workflowKey)
if !ok {
return nil
}
if len(ts) != 1 {
// This case should be unreachable since only one ${{ }} is included is checked by parser
rule.Errorf(s.Pos, "one ${{ }} expression should be included in %q value but got %d expressions", what, len(ts))
return nil
}
return ts[0].ty
}
func (rule *RuleExpression) checkObjectTy(ty ExprType, pos *Pos, what string) ExprType {
if ty == nil {
return nil
}
switch ty.(type) {
case *ObjectType, AnyType:
return ty
default:
rule.Errorf(pos, "type of expression at %q must be object but found type %s", what, ty.String())
return nil
}
}
func (rule *RuleExpression) checkArrayTy(ty ExprType, pos *Pos, what string) ExprType {
if ty == nil {
return nil
}
switch ty.(type) {
case *ArrayType, AnyType:
return ty
default:
rule.Errorf(pos, "type of expression at %q must be array but found type %s", what, ty.String())
return nil
}
}
func (rule *RuleExpression) checkNumberTy(ty ExprType, pos *Pos, what string) ExprType {
if ty == nil {
return nil
}
switch ty.(type) {
case NumberType, AnyType:
return ty
default:
rule.Errorf(pos, "type of expression at %q must be number but found type %s", what, ty.String())
return nil
}
}
func (rule *RuleExpression) checkObjectExpression(s *String, what, workflowKey string) ExprType {
ty := rule.checkOneExpression(s, what, workflowKey)
if ty == nil {
return nil
}
return rule.checkObjectTy(ty, s.Pos, what)
}
func (rule *RuleExpression) checkArrayExpression(s *String, what, workflowKey string) ExprType {
ty := rule.checkOneExpression(s, what, workflowKey)
if ty == nil {
return nil
}
return rule.checkArrayTy(ty, s.Pos, what)
}
func (rule *RuleExpression) checkNumberExpression(s *String, what, workflowKey string) ExprType {
ty := rule.checkOneExpression(s, what, workflowKey)
if ty == nil {
return nil
}
return rule.checkNumberTy(ty, s.Pos, what)
}
func (rule *RuleExpression) checkEnv(env *Env, workflowKey string) {
if env == nil {
return
}
if env.Vars != nil {
for _, e := range env.Vars {
rule.checkString(e.Name, workflowKey)
rule.checkString(e.Value, workflowKey)
}
return
}
// When form of "env: ${{...}}"
rule.checkObjectExpression(env.Expression, "env", workflowKey)
}
func (rule *RuleExpression) checkContainer(c *Container, workflowKey, childWorkflowKeyPrefix string) {
if c == nil {
return
}
childWorkflowKey := workflowKey
if childWorkflowKeyPrefix != "" {
childWorkflowKey += "." + childWorkflowKeyPrefix
}
rule.checkString(c.Image, workflowKey)
if c.Credentials != nil {
k := childWorkflowKey + ".credentials" // e.g. jobs.<job_id>.container.credentials
rule.checkString(c.Credentials.Username, k)
rule.checkString(c.Credentials.Password, k)
}
rule.checkEnv(c.Env, workflowKey+".env.<env_id>") // e.g. jobs.<job_id>.container.env.<env_id>
rule.checkStrings(c.Ports, workflowKey)
rule.checkStrings(c.Volumes, workflowKey)
rule.checkString(c.Options, workflowKey)
}
func (rule *RuleExpression) checkConcurrency(c *Concurrency, workflowKey string) {
if c == nil {
return
}
rule.checkString(c.Group, workflowKey)
rule.checkBool(c.CancelInProgress, workflowKey)
}
func (rule *RuleExpression) checkDefaults(d *Defaults, workflowKey string) {
if d == nil || d.Run == nil {
return
}
rule.checkString(d.Run.Shell, workflowKey)
rule.checkString(d.Run.WorkingDirectory, workflowKey)
}
func (rule *RuleExpression) checkWorkflowCall(c *WorkflowCall) {
if c == nil || c.Uses == nil {
return
}
rule.checkString(c.Uses, "")
m, err := rule.localWorkflows.FindMetadata(c.Uses.Value)
if err != nil {
rule.Error(c.Uses.Pos, err.Error())
}
for n, i := range c.Inputs {
ts := rule.checkString(i.Value, "jobs.<job_id>.with.<with_id>")
if m == nil {
continue
}
mi, ok := m.Inputs[n]
if !ok || mi == nil {
continue
}
if _, ok := mi.Type.(AnyType); ok {
continue
}
v := strings.TrimSpace(i.Value.Value)
var ty ExprType = StringType{}
switch len(ts) {
case 0:
switch v {
case "null":
ty = NullType{}
case "true", "false":
ty = BoolType{}
default:
if _, err := strconv.ParseFloat(v, 64); err == nil {
ty = NumberType{}
}
}
case 1:
if i.Value.IsExpressionAssigned() {
ty = ts[0].ty
}
}
if !mi.Type.Assignable(ty) {
rule.Errorf(
i.Value.Pos,
"input %q is typed as %s by reusable workflow %q. %s value cannot be assigned",
mi.Name,
mi.Type.String(),
c.Uses.Value,
ty.String(),
)
}
}
for _, s := range c.Secrets {
rule.checkString(s.Value, "jobs.<job_id>.secrets.<secrets_id>")
}
}
func (rule *RuleExpression) checkWebhookEventFilter(f *WebhookEventFilter) {
if f == nil {
return
}
rule.checkStrings(f.Values, "")
}
func (rule *RuleExpression) checkStrings(ss []*String, workflowKey string) {
for _, s := range ss {
rule.checkString(s, workflowKey)
}
}
func (rule *RuleExpression) checkIfCondition(str *String, workflowKey string) {
if str == nil {
return
}
// Note:
// https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions#jobsjob_idif
//
// > When you use expressions in an if conditional, you may omit the expression syntax (${{ }})
// > because GitHub automatically evaluates the if conditional as an expression, unless the
// > expression contains any operators. If the expression contains any operators, the expression
// > must be contained within ${{ }} to explicitly mark it for evaluation.
//
// This document is actually wrong. I confirmed that any strings without surrounding in ${{ }}
// are evaluated.
//
// - run: echo 'run'
// if: '!false'
// - run: echo 'not run'
// if: '!true'
// - run: echo 'run'
// if: false || true
// - run: echo 'run'
// if: true && true
// - run: echo 'not run'
// if: true && false
var condTy ExprType
if str.ContainsExpression() {
ts := rule.checkString(str, workflowKey)
if len(ts) == 1 {
if str.IsExpressionAssigned() {
condTy = ts[0].ty
}
}
} else {
src := str.Value + "}}" // }} is necessary since lexer lexes it as end of tokens
line, col := str.Pos.Line, str.Pos.Col
p := NewExprParser()
expr, err := p.Parse(NewExprLexer(src))
if err != nil {
rule.exprError(err, line, col)
return
}
if ty, ok := rule.checkSemanticsOfExprNode(expr, line, col, false, workflowKey); ok {
condTy = ty
}
}
if condTy != nil && !(BoolType{}).Assignable(condTy) {
rule.Errorf(str.Pos, "\"if\" condition should be type \"bool\" but got type %q", condTy.String())
}
}
func (rule *RuleExpression) checkTemplateEvaluatedType(ts []typedExpr) {
for _, t := range ts {
switch t.ty.(type) {
case *ObjectType, *ArrayType, NullType:
rule.Errorf(&t.pos, "object, array, and null values should not be evaluated in template with ${{ }} but evaluating the value of type %s", t.ty)
}
}
}
func (rule *RuleExpression) checkString(str *String, workflowKey string) []typedExpr {
if str == nil {
return nil
}
ts, ok := rule.checkExprsIn(str.Value, str.Pos, str.Quoted, false, workflowKey)
if !ok {
return nil
}
rule.checkTemplateEvaluatedType(ts)
return ts
}
func (rule *RuleExpression) checkScriptString(str *String, workflowKey string) {
if str == nil {
return
}
ts, ok := rule.checkExprsIn(str.Value, str.Pos, str.Quoted, true, workflowKey)
if !ok {
return
}
rule.checkTemplateEvaluatedType(ts)
}
func (rule *RuleExpression) checkBool(b *Bool, workflowKey string) {
if b == nil || b.Expression == nil {
return
}
ty := rule.checkOneExpression(b.Expression, "bool value", workflowKey)
if ty == nil {
return
}
switch ty.(type) {
case BoolType, AnyType:
// ok
default:
rule.Errorf(b.Expression.Pos, "type of expression must be bool but found type %s", ty.String())
}
}
func (rule *RuleExpression) checkInt(i *Int, workflowKey string) {
if i == nil {
return
}
rule.checkNumberExpression(i.Expression, "integer value", workflowKey)
}
func (rule *RuleExpression) checkFloat(f *Float, workflowKey string) {
if f == nil {
return
}
rule.checkNumberExpression(f.Expression, "float number value", workflowKey)
}
func (rule *RuleExpression) checkExprsIn(s string, pos *Pos, quoted, checkUntrusted bool, workflowKey string) ([]typedExpr, bool) {
// TODO: Line number is not correct when the string contains newlines.
line, col := pos.Line, pos.Col
if quoted {
col++ // when the string is quoted like 'foo' or "foo", column should be incremented
}
offset := 0
ts := []typedExpr{}
for {
idx := strings.Index(s, "${{")
if idx == -1 {
break
}
start := idx + 3 // 3 means removing "${{"
s = s[start:]
offset += start
col := col + offset
ty, offsetAfter, ok := rule.checkSemantics(s, line, col, checkUntrusted, workflowKey)
if !ok {
return nil, false
}
if ty == nil || offsetAfter == 0 {
return nil, true
}
ts = append(ts, typedExpr{ty, Pos{line, col - 3}})
s = s[offsetAfter:]
offset += offsetAfter
}
return ts, true
}
func (rule *RuleExpression) exprError(err *ExprError, lineBase, colBase int) {
pos := convertExprLineColToPos(err.Line, err.Column, lineBase, colBase)
rule.Error(pos, err.Message)
}
func (rule *RuleExpression) checkSemanticsOfExprNode(expr ExprNode, line, col int, checkUntrusted bool, workflowKey string) (ExprType, bool) {
var v []string
if rule.config != nil {
v = rule.config.ConfigVariables
}
c := NewExprSemanticsChecker(checkUntrusted, v)
if rule.matrixTy != nil {
c.UpdateMatrix(rule.matrixTy)
}
if rule.stepsTy != nil {
c.UpdateSteps(rule.stepsTy)
}
if rule.needsTy != nil {
c.UpdateNeeds(rule.needsTy)
}
if rule.secretsTy != nil {
c.UpdateSecrets(rule.secretsTy)
}
if rule.inputsTy != nil {
c.UpdateInputs(rule.inputsTy)
}
if rule.dispatchInputsTy != nil {
c.UpdateDispatchInputs(rule.dispatchInputsTy)
}
if rule.jobsTy != nil {
c.UpdateJobs(rule.jobsTy)
}
if workflowKey != "" {
ctx, sp := WorkflowKeyAvailability(workflowKey)
if len(ctx) == 0 {
rule.Debug("No context availability was found for workflow key %q", workflowKey)
}
c.SetContextAvailability(ctx)
c.SetSpecialFunctionAvailability(sp)
}
ty, errs := c.Check(expr)
for _, err := range errs {
rule.exprError(err, line, col)
}
return ty, len(errs) == 0
}
func (rule *RuleExpression) checkSemantics(src string, line, col int, checkUntrusted bool, workflowKey string) (ExprType, int, bool) {
l := NewExprLexer(src)
p := NewExprParser()
expr, err := p.Parse(l)
if err != nil {
rule.exprError(err, line, col)
return nil, l.Offset(), false
}
t, ok := rule.checkSemanticsOfExprNode(expr, line, col, checkUntrusted, workflowKey)
return t, l.Offset(), ok
}
func (rule *RuleExpression) calcNeedsType(job *Job) *ObjectType {
// https://docs.github.com/en/actions/learn-github-actions/contexts#needs-context
o := NewEmptyStrictObjectType()
rule.populateDependantNeedsTypes(o, job, job)
return o
}
func (rule *RuleExpression) populateDependantNeedsTypes(out *ObjectType, job *Job, root *Job) {
for _, id := range job.Needs {
i := strings.ToLower(id.Value) // ID is case insensitive
if i == root.ID.Value {
continue // When cyclic dependency exists. This does not happen normally.
}
if _, ok := out.Props[i]; ok {
continue // Already added
}
j, ok := rule.workflow.Jobs[i]
if !ok {
continue
}
var outputs *ObjectType
if j.WorkflowCall == nil {
outputs = NewEmptyStrictObjectType()
for name := range j.Outputs {
outputs.Props[name] = StringType{}
}
} else {
outputs = rule.getWorkflowCallOutputsType(j.WorkflowCall)
}
out.Props[i] = NewStrictObjectType(map[string]ExprType{
"outputs": outputs,
"result": StringType{},
})
// Do not collect outputs type from parent of parent recursively. (#151)
}
}
func (rule *RuleExpression) checkMatrixExpression(expr *String) *ObjectType {
ty := rule.checkObjectExpression(expr, "matrix", "jobs.<job_id>.strategy")
if ty == nil {
return NewEmptyObjectType()
}
matTy, ok := ty.(*ObjectType)
if !ok {
return NewEmptyObjectType()
}
// Consider properties in include section elements since 'include' section adds matrix values
incTy, ok := matTy.Props["include"]
if ok {
delete(matTy.Props, "include")
if a, ok := incTy.(*ArrayType); ok {
if o, ok := a.Elem.(*ObjectType); ok {
for n, p := range o.Props {
t, ok := matTy.Props[n]
if !ok {
matTy.Props[n] = p
continue
}
matTy.Props[n] = t.Merge(p)
}
}
}
}
delete(matTy.Props, "exclude")
return matTy
}
func (rule *RuleExpression) checkMatrix(m *Matrix) *ObjectType {
if m.Expression != nil {
return rule.checkMatrixExpression(m.Expression)
}
// Check types of "exclude" but they are not used to guess type of matrix
if m.Exclude != nil {
if m.Exclude.Expression != nil {
if ty, ok := rule.checkArrayExpression(m.Exclude.Expression, "exclude", "jobs.<job_id>.strategy").(*ArrayType); ok {
rule.checkObjectTy(ty.Elem, m.Exclude.Expression.Pos, "exclude")
}
} else {
for _, combi := range m.Exclude.Combinations {
if combi.Expression != nil {
rule.checkObjectExpression(combi.Expression, "exclude", "jobs.<job_id>.strategy")
continue
}
for _, a := range combi.Assigns {
rule.checkRawYAMLValue(a.Value)
}
}
}
}
o := NewEmptyStrictObjectType()
for n, r := range m.Rows {
o.Props[n] = rule.checkMatrixRow(r)
}
if m.Include == nil {
return o
}
if m.Include.Expression != nil {
if a, ok := rule.checkOneExpression(m.Include.Expression, "include", "jobs.<job_id>.strategy").(*ArrayType); ok {
if ret, ok := o.Merge(a.Elem).(*ObjectType); ok {
return ret
}
}
return NewEmptyObjectType()
}
for _, combi := range m.Include.Combinations {
if combi.Expression != nil {
ty := rule.checkOneExpression(m.Include.Expression, "matrix combination at element of include section", "jobs.<job_id>.strategy")
if ty == nil {
continue
}
if merged, ok := o.Merge(ty).(*ObjectType); ok {
o = merged
} else {
o.Loose()
}
continue
}
for n, assign := range combi.Assigns {
ty := rule.checkRawYAMLValue(assign.Value)
if t, ok := o.Props[n]; ok {
// When the combination exists in 'matrix' section, merge type with existing one
ty = t.Merge(ty)
}
o.Props[n] = ty
}
}
return o
}
func (rule *RuleExpression) checkMatrixRow(r *MatrixRow) ExprType {
if r.Expression != nil {
if a, ok := rule.checkArrayExpression(r.Expression, "matrix row", "jobs.<job_id>.strategy").(*ArrayType); ok {
return a.Elem
}
return AnyType{}
}
var ty ExprType
for _, v := range r.Values {
t := rule.checkRawYAMLValue(v)
if ty == nil {
ty = t
} else {
ty = ty.Merge(t)
}
}
if ty == nil {
return AnyType{} // No element
}
return ty
}
func (rule *RuleExpression) checkWorkflowCallOutputs(outputs map[string]*WorkflowCallEventOutput, jobs map[string]*Job) {
if len(outputs) == 0 || len(jobs) == 0 {
return
}
props := make(map[string]ExprType, len(jobs))
for n, j := range jobs {
var o *ObjectType
if j.WorkflowCall != nil {
// Outputs are not defined in jobs.<job_id> section when it is reusable workflow call.
o = NewEmptyObjectType()
} else {
p := make(map[string]ExprType, len(j.Outputs))
for n := range j.Outputs {
p[n] = StringType{}
}
o = NewStrictObjectType(p)
}
props[n] = NewStrictObjectType(map[string]ExprType{
"outputs": o,
})
}