forked from wallix/awless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.go
406 lines (366 loc) · 12.5 KB
/
transform.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
/*
Copyright 2017 WALLIX
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 aws
import (
"errors"
"fmt"
"net"
"reflect"
"sync"
"time"
awssdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/wallix/awless/graph"
)
func initResource(source interface{}) (*graph.Resource, error) {
var res *graph.Resource
switch ss := source.(type) {
// EC2
case *ec2.Instance:
res = graph.InitResource(awssdk.StringValue(ss.InstanceId), graph.Instance)
case *ec2.Vpc:
res = graph.InitResource(awssdk.StringValue(ss.VpcId), graph.Vpc)
case *ec2.Subnet:
res = graph.InitResource(awssdk.StringValue(ss.SubnetId), graph.Subnet)
case *ec2.SecurityGroup:
res = graph.InitResource(awssdk.StringValue(ss.GroupId), graph.SecurityGroup)
case *ec2.KeyPairInfo:
res = graph.InitResource(awssdk.StringValue(ss.KeyName), graph.Keypair)
case *ec2.Volume:
res = graph.InitResource(awssdk.StringValue(ss.VolumeId), graph.Volume)
case *ec2.InternetGateway:
res = graph.InitResource(awssdk.StringValue(ss.InternetGatewayId), graph.InternetGateway)
case *ec2.RouteTable:
res = graph.InitResource(awssdk.StringValue(ss.RouteTableId), graph.RouteTable)
// IAM
case *iam.User:
res = graph.InitResource(awssdk.StringValue(ss.UserId), graph.User)
case *iam.UserDetail:
res = graph.InitResource(awssdk.StringValue(ss.UserId), graph.User)
case *iam.RoleDetail:
res = graph.InitResource(awssdk.StringValue(ss.RoleId), graph.Role)
case *iam.GroupDetail:
res = graph.InitResource(awssdk.StringValue(ss.GroupId), graph.Group)
case *iam.Policy:
res = graph.InitResource(awssdk.StringValue(ss.PolicyId), graph.Policy)
case *iam.ManagedPolicyDetail:
res = graph.InitResource(awssdk.StringValue(ss.PolicyId), graph.Policy)
// S3
case *s3.Bucket:
res = graph.InitResource(awssdk.StringValue(ss.Name), graph.Bucket)
case *s3.Object:
res = graph.InitResource(awssdk.StringValue(ss.Key), graph.Object)
default:
return nil, fmt.Errorf("Unknown type of resource %T", source)
}
return res, nil
}
func newResource(source interface{}) (*graph.Resource, error) {
res, err := initResource(source)
if err != nil {
return res, err
}
value := reflect.ValueOf(source)
if !value.IsValid() || value.Kind() != reflect.Ptr || value.IsNil() {
return nil, fmt.Errorf("can not fetch cloud resource. %v is not a valid pointer.", value)
}
nodeV := value.Elem()
resultc := make(chan graph.Property)
errc := make(chan error)
var wg sync.WaitGroup
for prop, trans := range awsResourcesDef[res.Type()] {
wg.Add(1)
go func(p string, t *propertyTransform) {
defer wg.Done()
if t.transform != nil {
sourceField := nodeV.FieldByName(t.name)
if sourceField.IsValid() && !sourceField.IsNil() {
val, err := t.transform(sourceField.Interface())
if err == ErrTagNotFound {
return
}
if err != nil {
errc <- err
}
p := graph.Property{Key: p, Value: val}
resultc <- p
}
}
if t.fetch != nil {
val, err := t.fetch(source)
if err != nil {
errc <- err
}
p := graph.Property{Key: p, Value: val}
resultc <- p
}
}(prop, trans)
}
go func() {
wg.Wait()
close(errc)
close(resultc)
}()
for {
select {
case e := <-errc:
if e != nil {
return res, e
}
case p, ok := <-resultc:
if !ok {
return res, nil
}
res.Properties[p.Key] = p.Value
}
}
}
var ErrTagNotFound = errors.New("aws tag key not found")
var ErrFieldNotFound = errors.New("aws struct field not found")
type propertyTransform struct {
name string
transform transformFn
fetch fetchFn
}
type transformFn func(i interface{}) (interface{}, error)
type fetchFn func(i interface{}) (interface{}, error)
var extractValueFn = func(i interface{}) (interface{}, error) {
iv := reflect.ValueOf(i)
if iv.Kind() == reflect.Ptr && !iv.IsNil() {
return iv.Elem().Interface(), nil
}
return nil, fmt.Errorf("aws type unknown: %T", i)
}
// Extract time forcing timezone to UTC (friendlier when running test in different timezones i.e. travis)
var extractTimeFn = func(i interface{}) (interface{}, error) {
t, ok := i.(*time.Time)
if !ok {
return nil, fmt.Errorf("expected time pointer, got: %T", i)
}
return t.UTC(), nil
}
var extractIpPermissionSliceFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ec2.IpPermission); !ok {
return nil, fmt.Errorf("aws type unknown: %T", i)
}
var rules []*graph.FirewallRule
for _, ipPerm := range i.([]*ec2.IpPermission) {
rule := &graph.FirewallRule{}
protocol := awssdk.StringValue(ipPerm.IpProtocol)
switch protocol {
case "-1":
rule.Protocol = "any"
rule.PortRange = graph.PortRange{Any: true}
case "tcp", "udp", "icmp", "58":
rule.Protocol = protocol
fromPort := awssdk.Int64Value(ipPerm.FromPort)
toPort := awssdk.Int64Value(ipPerm.ToPort)
if fromPort == -1 || toPort == -1 {
rule.PortRange = graph.PortRange{Any: true}
} else {
rule.PortRange = graph.PortRange{FromPort: fromPort, ToPort: toPort}
}
default:
rule.Protocol = protocol
rule.PortRange = graph.PortRange{Any: true}
}
for _, r := range ipPerm.IpRanges {
_, net, err := net.ParseCIDR(awssdk.StringValue(r.CidrIp))
if err != nil {
return rules, err
}
rule.IPRanges = append(rule.IPRanges, net)
}
for _, r := range ipPerm.Ipv6Ranges {
_, net, err := net.ParseCIDR(awssdk.StringValue(r.CidrIpv6))
if err != nil {
return rules, err
}
rule.IPRanges = append(rule.IPRanges, net)
}
rules = append(rules, rule)
}
return rules, nil
}
var extractFieldFn = func(field string) transformFn {
return func(i interface{}) (interface{}, error) {
value := reflect.ValueOf(i)
if value.Kind() != reflect.Ptr {
return nil, fmt.Errorf("aws type unknown: %T", i)
}
struc := value.Elem()
if struc.Kind() != reflect.Struct {
return nil, fmt.Errorf("aws type unknown: %T", i)
}
structField := struc.FieldByName(field)
if !structField.IsValid() {
return nil, ErrFieldNotFound
}
return extractValueFn(structField.Interface())
}
}
var extractTagFn = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
tags, ok := i.([]*ec2.Tag)
if !ok {
return nil, fmt.Errorf("aws model: unexpected type %T", i)
}
for _, t := range tags {
if key == awssdk.StringValue(t.Key) {
return awssdk.StringValue(t.Value), nil
}
}
return nil, ErrTagNotFound
}
}
var extractSliceValues = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
var res []interface{}
value := reflect.ValueOf(i)
if value.Kind() != reflect.Slice {
return nil, fmt.Errorf("aws type invalid: %T", i)
}
for i := 0; i < value.Len(); i++ {
e, err := extractFieldFn(key)(value.Index(i).Interface())
if err != nil {
return nil, err
}
res = append(res, e)
}
return res, nil
}
}
var extractRoutesSliceFn = func(i interface{}) (interface{}, error) {
if _, ok := i.([]*ec2.Route); !ok {
return nil, fmt.Errorf("aws type unknown: %T", i)
}
var routes []*graph.Route
for _, r := range i.([]*ec2.Route) {
route := &graph.Route{}
var err error
switch {
case awssdk.StringValue(r.DestinationCidrBlock) != "" && awssdk.StringValue(r.DestinationIpv6CidrBlock) != "":
return nil, fmt.Errorf("extract values: both IPv4 and IPv6 destination in route %v", r)
case awssdk.StringValue(r.DestinationCidrBlock) != "":
_, route.Destination, err = net.ParseCIDR(awssdk.StringValue(r.DestinationCidrBlock))
if err != nil {
return nil, err
}
case awssdk.StringValue(r.DestinationIpv6CidrBlock) != "":
_, route.Destination, err = net.ParseCIDR(awssdk.StringValue(r.DestinationIpv6CidrBlock))
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("extract values: no IPv4 nor IPv6 destination in route %v", r)
}
switch {
case notEmpty(r.EgressOnlyInternetGatewayId):
if notEmpty(r.GatewayId) || notEmpty(r.InstanceId) || notEmpty(r.NatGatewayId) || notEmpty(r.NetworkInterfaceId) || notEmpty(r.VpcPeeringConnectionId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.EgressOnlyInternetGatewayTarget
route.Target = awssdk.StringValue(r.EgressOnlyInternetGatewayId)
case notEmpty(r.GatewayId):
if notEmpty(r.EgressOnlyInternetGatewayId) || notEmpty(r.InstanceId) || notEmpty(r.NatGatewayId) || notEmpty(r.NetworkInterfaceId) || notEmpty(r.VpcPeeringConnectionId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.GatewayTarget
route.Target = awssdk.StringValue(r.GatewayId)
case notEmpty(r.InstanceId):
if notEmpty(r.EgressOnlyInternetGatewayId) || notEmpty(r.GatewayId) || notEmpty(r.NatGatewayId) || notEmpty(r.NetworkInterfaceId) || notEmpty(r.VpcPeeringConnectionId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.InstanceTarget
route.Target = awssdk.StringValue(r.InstanceId)
case notEmpty(r.NatGatewayId):
if notEmpty(r.EgressOnlyInternetGatewayId) || notEmpty(r.GatewayId) || notEmpty(r.InstanceId) || notEmpty(r.NetworkInterfaceId) || notEmpty(r.VpcPeeringConnectionId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.NatTarget
route.Target = awssdk.StringValue(r.NatGatewayId)
case notEmpty(r.NetworkInterfaceId):
if notEmpty(r.EgressOnlyInternetGatewayId) || notEmpty(r.GatewayId) || notEmpty(r.InstanceId) || notEmpty(r.NatGatewayId) || notEmpty(r.VpcPeeringConnectionId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.NetworkInterfaceTarget
route.Target = awssdk.StringValue(r.NetworkInterfaceId)
case notEmpty(r.VpcPeeringConnectionId):
if notEmpty(r.EgressOnlyInternetGatewayId) || notEmpty(r.GatewayId) || notEmpty(r.InstanceId) || notEmpty(r.NatGatewayId) || notEmpty(r.NetworkInterfaceId) {
return nil, fmt.Errorf("extract values: multiple non-empty target type in route %v", r)
}
route.TargetType = graph.VpcPeeringConnectionTarget
route.Target = awssdk.StringValue(r.VpcPeeringConnectionId)
default:
return nil, fmt.Errorf("extract values: no non-empty target type in route %v", r)
}
routes = append(routes, route)
}
return routes, nil
}
var extractHasATrueBoolInStructSliceFn = func(key string) transformFn {
return func(i interface{}) (interface{}, error) {
var res bool
value := reflect.ValueOf(i)
if value.Kind() != reflect.Slice {
return nil, fmt.Errorf("aws type invalid: %T", i)
}
for i := 0; i < value.Len(); i++ {
e, err := extractFieldFn(key)(value.Index(i).Interface())
if err != nil {
continue //Empty field, we do not need to throw the error
}
b, ok := e.(bool)
if !ok {
return nil, fmt.Errorf("this field is not a boolean, but has type: %T", e)
}
if b {
res = true
}
}
return res, nil
}
}
var fetchAndExtractGrantsFn = func(i interface{}) (interface{}, error) {
b, ok := i.(*s3.Bucket)
if !ok {
return nil, fmt.Errorf("aws type unknown: %T", i)
}
acls, err := StorageService.ProviderRunnableAPI().(s3iface.S3API).GetBucketAcl(&s3.GetBucketAclInput{Bucket: b.Name})
if err != nil {
return nil, err
}
var grants []*graph.Grant
for _, acl := range acls.Grants {
grant := &graph.Grant{
Permission: awssdk.StringValue(acl.Permission),
GranteeID: awssdk.StringValue(acl.Grantee.ID),
GranteeType: awssdk.StringValue(acl.Grantee.Type),
GranteeDisplayName: awssdk.StringValue(acl.Grantee.DisplayName),
}
if awssdk.StringValue(acl.Grantee.EmailAddress) != "" {
grant.GranteeDisplayName += "<" + awssdk.StringValue(acl.Grantee.EmailAddress) + ">"
}
if grant.GranteeType == "Group" {
grant.GranteeID += awssdk.StringValue(acl.Grantee.URI)
}
grants = append(grants, grant)
}
return grants, nil
}
func notEmpty(str *string) bool {
return awssdk.StringValue(str) != ""
}