forked from jen20/awspolicyequivalence
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaws_policy_equivalence.go
506 lines (429 loc) · 13.2 KB
/
aws_policy_equivalence.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
// Package awspolicy contains functions to compare structural equivalence
// of AWS IAM policies.
package awspolicy
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/mitchellh/mapstructure"
)
// PoliciesAreEquivalent tests for the structural equivalence of two
// AWS policies. It does not read into the semantics, other than treating
// single element string arrays as equivalent to a string without an
// array, as the AWS endpoints do.
//
// It will, however, detect reordering and ignore whitespace.
//
// Returns true if the policies are structurally equivalent, false
// otherwise. If either of the input strings are not valid JSON,
// false is returned along with an error.
func PoliciesAreEquivalent(policy1, policy2 string) (bool, error) {
// Although "policy" generally equates to JSON, AWS also has pseudo-JSON
// policies, such as assume-role policies that can be lists of JSONs. This
// only handles a one-length list of JSON:
policy1 = strings.TrimSpace(policy1)
if strings.HasPrefix(policy1, "[") && strings.HasSuffix(policy1, "]") {
policy1 = strings.TrimPrefix(strings.TrimSuffix(policy1, "]"), "[")
policy1 = strings.TrimSpace(policy1)
}
if policy1 == "" {
policy1 = "{}"
}
policy2 = strings.TrimSpace(policy2)
if strings.HasPrefix(policy2, "[") && strings.HasSuffix(policy2, "]") {
policy2 = strings.TrimPrefix(strings.TrimSuffix(policy2, "]"), "[")
policy2 = strings.TrimSpace(policy2)
}
if policy2 == "" {
policy2 = "{}"
}
policy1intermediate := &intermediatePolicyDocument{}
if err := json.Unmarshal([]byte(policy1), policy1intermediate); err != nil {
return false, fmt.Errorf("unmarshaling policy 1: %s", err)
}
policy2intermediate := &intermediatePolicyDocument{}
if err := json.Unmarshal([]byte(policy2), policy2intermediate); err != nil {
return false, fmt.Errorf("unmarshaling policy 2: %s", err)
}
if reflect.DeepEqual(policy1intermediate, policy2intermediate) {
return true, nil
}
policy1Doc, err := policy1intermediate.document()
if err != nil {
return false, fmt.Errorf("parsing policy 1: %s", err)
}
policy2Doc, err := policy2intermediate.document()
if err != nil {
return false, fmt.Errorf("parsing policy 2: %s", err)
}
return policy1Doc.equals(policy2Doc), nil
}
type intermediatePolicyDocument struct {
Version string `json:",omitempty"`
Id string `json:",omitempty"`
Statements interface{} `json:"Statement"`
}
func (intermediate *intermediatePolicyDocument) document() (*policyDocument, error) {
var statements []*policyStatement
// Decode only non-nil statements to prevent irreversible result when setting values
// in Terraform state.
// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/22944
if intermediate.Statements != nil {
switch s := intermediate.Statements.(type) {
case []interface{}:
if err := mapstructure.Decode(s, &statements); err != nil {
return nil, fmt.Errorf("parsing statement 1: %s", err)
}
case map[string]interface{}:
var singleStatement *policyStatement
if err := mapstructure.Decode(s, &singleStatement); err != nil {
return nil, fmt.Errorf("parsing statement 2: %s", err)
}
statements = append(statements, singleStatement)
default:
return nil, errors.New("unknown statement parsing problem")
}
}
document := &policyDocument{
Version: intermediate.Version,
Id: intermediate.Id,
Statements: statements,
}
return document, nil
}
type policyDocument struct {
Version string
Id string
Statements []*policyStatement
}
func (doc *policyDocument) equals(other *policyDocument) bool {
// Prevent panic
if doc == nil {
return other == nil
}
// Check the basic fields of the document
if doc.Version != other.Version {
return false
}
if doc.Id != other.Id {
return false
}
// If we have different number of statements we are very unlikely
// to have them be equivalent.
if len(doc.Statements) != len(other.Statements) {
return false
}
// If we have the same number of statements in the policy, does
// each statement in the intermediate have a corresponding statement in
// other which is equal? If no, policies are not equal, if yes,
// then they may be.
for _, ours := range doc.Statements {
found := false
for _, theirs := range other.Statements {
if ours.equals(theirs) {
found = true
}
}
if !found {
return false
}
}
// Now we need to repeat this process the other way around to
// ensure we don't have any matching errors.
for _, theirs := range other.Statements {
found := false
for _, ours := range doc.Statements {
if theirs.equals(ours) {
found = true
}
}
if !found {
return false
}
}
return true
}
type policyStatement struct {
Sid string `json:",omitempty" mapstructure:"Sid"`
Effect string `json:",omitempty" mapstructure:"Effect"`
Actions interface{} `json:"Action,omitempty" mapstructure:"Action"`
NotActions interface{} `json:"NotAction,omitempty" mapstructure:"NotAction"`
Resources interface{} `json:"Resource,omitempty" mapstructure:"Resource"`
NotResources interface{} `json:"NotResource,omitempty" mapstructure:"NotResource"`
Principals interface{} `json:"Principal,omitempty" mapstructure:"Principal"`
NotPrincipals interface{} `json:"NotPrincipal,omitempty" mapstructure:"NotPrincipal"`
Conditions map[string]map[string]interface{} `json:"Condition,omitempty" mapstructure:"Condition"`
}
func (statement *policyStatement) equals(other *policyStatement) bool {
if statement.Sid != other.Sid {
return false
}
if !strings.EqualFold(statement.Effect, other.Effect) {
return false
}
ourActions := newStringSet(statement.Actions)
theirActions := newStringSet(other.Actions)
if !stringSlicesEqualIgnoreOrder(ourActions, theirActions) {
return false
}
ourNotActions := newStringSet(statement.NotActions)
theirNotActions := newStringSet(other.NotActions)
if !stringSlicesEqualIgnoreOrder(ourNotActions, theirNotActions) {
return false
}
ourResources := newStringSet(statement.Resources)
theirResources := newStringSet(other.Resources)
//if !stringSlicesEqualIgnoreOrder(ourResources, theirResources) {
if !stringSlicesEqualIgnoreOrder(ourResources, theirResources) {
// fmt.Printf("%v\n%v\n", ourResources, theirResources)
return false
}
//if !ourResources.equals(theirResources) {
// return false
//}
ourNotResources := newStringSet(statement.NotResources)
theirNotResources := newStringSet(other.NotResources)
if !stringSlicesEqualIgnoreOrder(ourNotResources, theirNotResources) {
//if !ourNotResources.equals(theirNotResources) {
return false
}
ourConditionsBlock := conditionsBlock(statement.Conditions)
theirConditionsBlock := conditionsBlock(other.Conditions)
if !ourConditionsBlock.Equals(theirConditionsBlock) {
return false
}
if statement.Principals != nil || other.Principals != nil {
stringPrincipalsEqual := stringPrincipalsEqual(statement.Principals, other.Principals)
mapPrincipalsEqual := mapPrincipalsEqual(statement.Principals, other.Principals)
if !(stringPrincipalsEqual || mapPrincipalsEqual) {
return false
}
}
if statement.NotPrincipals != nil || other.NotPrincipals != nil {
stringNotPrincipalsEqual := stringPrincipalsEqual(statement.NotPrincipals, other.NotPrincipals)
mapNotPrincipalsEqual := mapPrincipalsEqual(statement.NotPrincipals, other.NotPrincipals)
if !(stringNotPrincipalsEqual || mapNotPrincipalsEqual) {
return false
}
}
return true
}
func mapPrincipalsEqual(ours, theirs interface{}) bool {
ourPrincipalMap, oursOk := ours.(map[string]interface{})
theirPrincipalMap, theirsOk := theirs.(map[string]interface{})
oursNormalized := make(map[string]principalStringSet)
if oursOk {
for key, val := range ourPrincipalMap {
var tmp = newPrincipalStringSet(val)
if len(tmp) > 0 {
oursNormalized[key] = tmp
}
}
}
theirsNormalized := make(map[string]principalStringSet)
if theirsOk {
for key, val := range theirPrincipalMap {
var tmp = newPrincipalStringSet(val)
if len(tmp) > 0 {
theirsNormalized[key] = newPrincipalStringSet(val)
}
}
}
for key, ours := range oursNormalized {
theirs, ok := theirsNormalized[key]
if !ok {
return false
}
if !ours.equals(theirs) {
return false
}
}
for key, theirs := range theirsNormalized {
ours, ok := oursNormalized[key]
if !ok {
return false
}
if !theirs.equals(ours) {
return false
}
}
return true
}
func stringPrincipalsEqual(ours, theirs interface{}) bool {
ourPrincipal, oursIsString := ours.(string)
theirPrincipal, theirsIsString := theirs.(string)
if !(oursIsString && theirsIsString) {
return false
}
if ourPrincipal == theirPrincipal {
return true
}
// Handle AWS converting account ID principal to root IAM user ARN
// ACCOUNTID == arn:PARTITION:iam::ACCOUNTID:root
accountIDRegex := regexp.MustCompile(`^[0-9]{12}$`)
if accountIDRegex.MatchString(ourPrincipal) {
if theirArn, err := arn.Parse(theirPrincipal); err == nil {
if theirArn.Service == "iam" && theirArn.Resource == "root" && theirArn.AccountID == ourPrincipal {
return true
}
}
}
if accountIDRegex.MatchString(theirPrincipal) {
if ourArn, err := arn.Parse(ourPrincipal); err == nil {
if ourArn.Service == "iam" && ourArn.Resource == "root" && ourArn.AccountID == theirPrincipal {
return true
}
}
}
return false
}
type conditionsBlock map[string]map[string]interface{}
func (conditions conditionsBlock) Equals(other conditionsBlock) bool {
if conditions == nil && other != nil || other == nil && conditions != nil {
return false
}
if len(conditions) != len(other) {
return false
}
oursNormalized := make(map[string]map[string]stringSet)
for key, condition := range conditions {
normalizedCondition := make(map[string]stringSet)
for innerKey, val := range condition {
normalizedCondition[innerKey] = newStringSet(val)
}
oursNormalized[key] = normalizedCondition
}
theirsNormalized := make(map[string]map[string]stringSet)
for key, condition := range other {
normalizedCondition := make(map[string]stringSet)
for innerKey, val := range condition {
normalizedCondition[innerKey] = newStringSet(val)
}
theirsNormalized[key] = normalizedCondition
}
for key, ours := range oursNormalized {
theirs, ok := theirsNormalized[key]
if !ok {
return false
}
for innerKey, oursInner := range ours {
theirsInner, ok := theirs[innerKey]
if !ok {
return false
}
if !oursInner.equals(theirsInner) {
return false
}
}
}
for key, theirs := range theirsNormalized {
ours, ok := oursNormalized[key]
if !ok {
return false
}
for innerKey, theirsInner := range theirs {
oursInner, ok := ours[innerKey]
if !ok {
return false
}
if !theirsInner.equals(oursInner) {
return false
}
}
}
return true
}
type stringSet []string
type principalStringSet stringSet
// newStringSet constructs an stringSet from an interface{} - which
// may be nil, a single string, or []interface{} (each of which is a string).
// This corresponds with how structures come off the JSON unmarshaler
// without any custom encoding rules.
func newStringSet(members interface{}) stringSet {
if members == nil {
return stringSet{}
}
switch v := members.(type) {
case string:
return stringSet{v}
case bool:
return stringSet{strconv.FormatBool(v)}
case float64:
return stringSet{strconv.FormatFloat(v, 'f', -1, 64)}
case []interface{}:
var actions []string
for _, action := range v {
switch action := action.(type) {
case string:
actions = append(actions, action)
case bool:
actions = append(actions, strconv.FormatBool(action))
case float64:
actions = append(actions, strconv.FormatFloat(action, 'f', -1, 64))
default:
return nil
}
}
if len(actions) == 0 {
return stringSet{}
}
return stringSet(actions)
default:
return nil
}
}
func newPrincipalStringSet(members interface{}) principalStringSet {
return principalStringSet(newStringSet(members))
}
func (ours stringSet) equals(theirs stringSet) bool {
if ours == nil || theirs == nil {
return false
}
if len(ours) != len(theirs) {
return false
}
ourMap := map[string]struct{}{}
theirMap := map[string]struct{}{}
for _, str := range ours {
ourMap[str] = struct{}{}
}
for _, str := range theirs {
theirMap[str] = struct{}{}
}
return reflect.DeepEqual(ourMap, theirMap)
}
func (ours principalStringSet) equals(theirs principalStringSet) bool {
if len(ours) != len(theirs) {
return false
}
for _, ourPrincipal := range ours {
matches := false
for _, theirPrincipal := range theirs {
if stringPrincipalsEqual(ourPrincipal, theirPrincipal) {
matches = true
break
}
}
if !matches {
return false
}
}
return true
}
func stringSlicesEqualIgnoreOrder(s1, s2 []string) bool {
if len(s1) != len(s2) {
return false
}
sort.Strings(s1)
sort.Strings(s2)
return reflect.DeepEqual(s1, s2)
}