-
Notifications
You must be signed in to change notification settings - Fork 10
/
tf.go
156 lines (134 loc) · 4.41 KB
/
tf.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
// Copyright 2022-2023 Snyk Ltd
// Copyright 2021 Fugue, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package input
import (
"fmt"
"path/filepath"
"strings"
"github.com/snyk/policy-engine/pkg/hcl_interpreter"
"github.com/snyk/policy-engine/pkg/models"
)
// This is the loader that supports reading files and directories of HCL (.tf)
// files. The implementation is in the `./pkg/hcl_interpreter/` package in this
// repository: this file just wraps that. That directory also contains a
// README explaining how everything fits together.
type TfDetector struct{}
func (t *TfDetector) DetectFile(i *File, opts DetectOptions) (IACConfiguration, error) {
if !opts.IgnoreExt && !hasTerraformExt(i.Path) {
return nil, fmt.Errorf("%w: %v", UnrecognizedFileExtension, i.Ext())
}
dir := filepath.Dir(i.Path)
moduleTree, err := hcl_interpreter.ParseFiles(nil, i.Fs, false, dir, []string{i.Path}, opts.VarFiles)
if err != nil {
return nil, fmt.Errorf("%w: %v", FailedToParseInput, err)
}
return newHclConfiguration(moduleTree)
}
func (t *TfDetector) DetectDirectory(i *Directory, opts DetectOptions) (IACConfiguration, error) {
// First check that a `.tf` file exists in the directory.
tfExists := false
children, err := i.Children()
if err != nil {
return nil, err
}
for _, child := range children {
if c, ok := child.(*File); ok && hasTerraformExt(c.Path) {
tfExists = true
}
}
if !tfExists {
return nil, nil
}
moduleRegister := hcl_interpreter.NewTerraformRegister(i.Fs, i.Path)
moduleTree, err := hcl_interpreter.ParseDirectory(moduleRegister, i.Fs, i.Path, opts.VarFiles)
if err != nil {
return nil, fmt.Errorf("%w: %v", FailedToParseInput, err)
}
return newHclConfiguration(moduleTree)
}
type HclConfiguration struct {
moduleTree *hcl_interpreter.ModuleTree
evaluation *hcl_interpreter.Evaluation
resources map[string]map[string]models.ResourceState
}
func newHclConfiguration(moduleTree *hcl_interpreter.ModuleTree) (*HclConfiguration, error) {
analysis := hcl_interpreter.AnalyzeModuleTree(moduleTree)
evaluation, err := hcl_interpreter.EvaluateAnalysis(analysis)
if err != nil {
return nil, fmt.Errorf("%w: %v", FailedToParseInput, err)
}
evaluationResources := evaluation.Resources()
resources := make([]models.ResourceState, len(evaluationResources))
for i := range evaluationResources {
resources[i] = evaluationResources[i].Model
}
namespace := moduleTree.FilePath()
for i := range resources {
resources[i].Namespace = namespace
}
return &HclConfiguration{
moduleTree: moduleTree,
evaluation: evaluation,
resources: groupResourcesByType(resources),
}, nil
}
func (c *HclConfiguration) LoadedFiles() []string {
return c.moduleTree.LoadedFiles()
}
func (c *HclConfiguration) Location(path []interface{}) (LocationStack, error) {
// Format is {resourceNamespace, resourceType, resourceId, attributePath...}
if len(path) < 3 {
return nil, nil
}
resourceId, ok := path[2].(string)
if !ok {
return nil, fmt.Errorf("Expected string resource ID in path")
}
ranges := c.evaluation.Location(resourceId, path[3:])
locs := LocationStack{}
for _, r := range ranges {
locs = append(locs, Location{
Path: r.Filename,
Line: r.Start.Line,
Col: r.Start.Column,
})
}
return locs, nil
}
func (c *HclConfiguration) ToState() models.State {
return models.State{
InputType: TerraformHCL.Name,
EnvironmentProvider: "iac",
Meta: map[string]interface{}{
"filepath": c.moduleTree.FilePath(),
},
Resources: c.resources,
Scope: map[string]interface{}{
"filepath": c.moduleTree.FilePath(),
},
}
}
func (c *HclConfiguration) Errors() []error {
errors := []error{}
errors = append(errors, c.moduleTree.Errors()...)
errors = append(errors, c.evaluation.Errors()...)
return errors
}
func (l *HclConfiguration) Type() *Type {
return TerraformHCL
}
func hasTerraformExt(path string) bool {
return strings.HasSuffix(path, ".tf") || strings.HasSuffix(path, ".tf.json")
}