-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplan.go
287 lines (249 loc) · 7.14 KB
/
plan.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
package preview
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/fs"
"reflect"
"slices"
"strings"
"github.com/aquasecurity/trivy/pkg/iac/scanners/terraformplan/tfjson/parser"
"github.com/aquasecurity/trivy/pkg/iac/terraform"
tfcontext "github.com/aquasecurity/trivy/pkg/iac/terraform/context"
tfjson "github.com/hashicorp/terraform-json"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
"github.com/coder/preview/hclext"
)
func PlanJSONHook(dfs fs.FS, input Input) (func(ctx *tfcontext.Context, blocks terraform.Blocks, inputVars map[string]cty.Value), error) {
var contents io.Reader = bytes.NewReader(input.PlanJSON)
// Also accept `{}` as an empty plan. If this is stored in postgres or another json
// type, then `{}` is the "empty" value.
if len(input.PlanJSON) == 0 || bytes.Compare(input.PlanJSON, []byte("{}")) == 0 {
if input.PlanJSONPath == "" {
return func(ctx *tfcontext.Context, blocks terraform.Blocks, inputVars map[string]cty.Value) {}, nil
}
var err error
contents, err = dfs.Open(input.PlanJSONPath)
if err != nil {
return nil, fmt.Errorf("unable to open plan JSON file: %w", err)
}
}
plan, err := ParsePlanJSON(contents)
if err != nil {
return nil, fmt.Errorf("unable to parse plan JSON: %w", err)
}
return func(ctx *tfcontext.Context, blocks terraform.Blocks, inputVars map[string]cty.Value) {
loaded := make(map[*tfjson.StateModule]bool)
// Do not recurse to child blocks.
// TODO: Only load into the single parent context for the module.
// And do not load context for a module more than once
for _, block := range blocks {
// TODO: Maybe switch to the 'configuration' block
planMod := priorPlanModule(plan, block)
if planMod == nil {
continue
}
if loaded[planMod] {
// No need to load this module into state again
continue
}
rootCtx := block.Context()
for {
if rootCtx.Parent() != nil {
rootCtx = rootCtx.Parent()
continue
}
break
}
// Load state into the context
err := loadResourcesToContext(rootCtx, planMod.Resources)
if err != nil {
// TODO: Somehow handle this error
panic(fmt.Sprintf("unable to load resources to context: %v", err))
}
loaded[planMod] = true
}
}, nil
}
// priorPlanModule returns the state data of the module a given block is in.
func priorPlanModule(plan *tfjson.Plan, block *terraform.Block) *tfjson.StateModule {
if !block.InModule() {
return plan.PriorState.Values.RootModule
}
var modPath []string
mod := block.ModuleBlock()
for {
modPath = append([]string{mod.LocalName()}, modPath...)
mod = mod.ModuleBlock()
if mod == nil {
break
}
}
current := plan.PriorState.Values.RootModule
for i := range modPath {
idx := slices.IndexFunc(current.ChildModules, func(m *tfjson.StateModule) bool {
return m.Address == strings.Join(modPath[:i+1], ".")
})
if idx == -1 {
// Maybe throw a diag here?
return nil
}
current = current.ChildModules[idx]
}
return current
}
func matchingBlock(block *terraform.Block, planMod *tfjson.StateModule) *tfjson.StateResource {
ref := block.Reference()
matchKey := keyMatcher(ref.RawKey())
for _, resource := range planMod.Resources {
if ref.BlockType().ShortName() == string(resource.Mode) &&
ref.TypeLabel() == resource.Type &&
ref.NameLabel() == resource.Name &&
matchKey(resource.Index) {
return resource
}
}
return nil
}
func loadResourcesToContext(ctx *tfcontext.Context, resources []*tfjson.StateResource) error {
for _, resource := range resources {
if resource.Mode != "data" {
continue
}
if strings.HasPrefix(resource.Type, "coder_") {
// Ignore coder blocks
continue
}
path := []string{string(resource.Mode), resource.Type, resource.Name}
// Always merge with any existing values
existing := ctx.Get(path...)
val, err := toCtyValue(resource.AttributeValues)
if err != nil {
return fmt.Errorf("unable to determine value of resource %q: %w", resource.Address, err)
}
var merged cty.Value
switch resource.Index.(type) {
case int, int32, int64, float32, float64:
asInt, ok := toInt(resource.Index)
if !ok {
return fmt.Errorf("unable to convert index '%v' to int", resource.Index)
}
if !existing.Type().IsTupleType() {
continue
}
merged = hclext.MergeWithTupleElement(existing, int(asInt), val)
case nil:
merged = hclext.MergeObjects(existing, val)
default:
return fmt.Errorf("unsupported index type %T", resource.Index)
}
ctx.Set(merged, string(resource.Mode), resource.Type, resource.Name)
}
return nil
}
func toCtyValue(a any) (cty.Value, error) {
if a == nil {
return cty.NilVal, nil
}
av := reflect.ValueOf(a)
switch av.Type().Kind() {
case reflect.Slice, reflect.Array:
sv := make([]cty.Value, 0, av.Len())
for i := 0; i < av.Len(); i++ {
v, err := toCtyValue(av.Index(i).Interface())
if err != nil {
return cty.NilVal, fmt.Errorf("slice value %d: %w", i, err)
}
sv = append(sv, v)
}
return cty.ListVal(sv), nil
case reflect.Map:
if av.Type().Key().Kind() != reflect.String {
return cty.NilVal, fmt.Errorf("map keys must be string, found %q", av.Type().Key().Kind())
}
mv := make(map[string]cty.Value)
var err error
for _, k := range av.MapKeys() {
v := av.MapIndex(k)
mv[k.String()], err = toCtyValue(v.Interface())
if err != nil {
return cty.NilVal, fmt.Errorf("map value %q: %w", k.String(), err)
}
}
return cty.ObjectVal(mv), nil
default:
ty, err := gocty.ImpliedType(a)
if err != nil {
return cty.NilVal, fmt.Errorf("implied type: %w", err)
}
cv, err := gocty.ToCtyValue(a, ty)
if err != nil {
return cty.NilVal, fmt.Errorf("implied value: %w", err)
}
return cv, nil
}
}
// ParsePlanJSON can parse the JSON output of a Terraform plan.
// terraform plan out.plan
// terraform show -json out.plan
func ParsePlanJSON(reader io.Reader) (*tfjson.Plan, error) {
plan := new(tfjson.Plan)
plan.FormatVersion = tfjson.PlanFormatVersionConstraints
return plan, json.NewDecoder(reader).Decode(plan)
}
// ParsePlanJSON can parse the JSON output of a Terraform plan.
// terraform plan out.plan
// terraform show -json out.plan
func TrivyParsePlanJSON(reader io.Reader) (*tfjson.Plan, error) {
p := parser.New()
plan, err := p.Parse(reader)
var _ = plan
plan.ToFS()
return nil, err
}
func keyMatcher(key cty.Value) func(to any) bool {
switch {
case key.Type().Equals(cty.Number):
idx, _ := key.AsBigFloat().Int64()
return func(to any) bool {
asInt, ok := toInt(to)
return ok && asInt == idx
}
case key.Type().Equals(cty.String):
// TODO: handle key strings
}
return func(to any) bool {
return true
}
}
func toInt(to any) (int64, bool) {
switch typed := to.(type) {
case uint:
return int64(typed), true
case uint8:
return int64(typed), true
case uint16:
return int64(typed), true
case uint32:
return int64(typed), true
case uint64:
return int64(typed), true
case int:
return int64(typed), true
case int8:
return int64(typed), true
case int16:
return int64(typed), true
case int32:
return int64(typed), true
case int64:
return typed, true
case float32:
return int64(typed), true
case float64:
return int64(typed), true
}
return 0, false
}