forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iam.go
156 lines (138 loc) · 5.14 KB
/
iam.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
package google
import (
"fmt"
"log"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/cloudresourcemanager/v1"
)
// The ResourceIamUpdater interface is implemented for each GCP resource supporting IAM policy.
//
// Implementations should keep track of the resource identifier.
type ResourceIamUpdater interface {
// Fetch the existing IAM policy attached to a resource.
GetResourceIamPolicy() (*cloudresourcemanager.Policy, error)
// Replaces the existing IAM Policy attached to a resource.
SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error
// A mutex guards against concurrent to call to the SetResourceIamPolicy method.
// The mutex key should be made of the resource type and resource id.
// For example: `iam-project-{id}`.
GetMutexKey() string
// Returns the unique resource identifier.
GetResourceId() string
// Textual description of this resource to be used in error message.
// The description should include the unique resource identifier.
DescribeResource() string
}
type newResourceIamUpdaterFunc func(d *schema.ResourceData, config *Config) (ResourceIamUpdater, error)
type iamPolicyModifyFunc func(p *cloudresourcemanager.Policy) error
// This method parses identifiers specific to the resource (d.GetId()) into the ResourceData
// object, so that it can be given to the resource's Read method. Externally, this is wrapped
// into schema.StateFunc functions - one each for a _member, a _binding, and a _policy. Any
// GCP resource supporting IAM policy might support one, two, or all of these. Any GCP resource
// for which an implementation of this interface exists could support any of the three.
type resourceIdParserFunc func(d *schema.ResourceData, config *Config) error
func iamPolicyReadModifyWrite(updater ResourceIamUpdater, modify iamPolicyModifyFunc) error {
mutexKey := updater.GetMutexKey()
mutexKV.Lock(mutexKey)
defer mutexKV.Unlock(mutexKey)
backoff := time.Second
for {
log.Printf("[DEBUG]: Retrieving policy for %s\n", updater.DescribeResource())
p, err := updater.GetResourceIamPolicy()
if isGoogleApiErrorWithCode(err, 429) {
time.Sleep(backoff)
continue
} else if err != nil {
return err
}
log.Printf("[DEBUG]: Retrieved policy for %s: %+v\n", updater.DescribeResource(), p)
err = modify(p)
if err != nil {
return err
}
log.Printf("[DEBUG]: Setting policy for %s to %+v\n", updater.DescribeResource(), p)
err = updater.SetResourceIamPolicy(p)
if err == nil {
fetchBackoff := 1 * time.Second
for successfulFetches := 0; successfulFetches < 3; {
time.Sleep(fetchBackoff)
new_p, err := updater.GetResourceIamPolicy()
if err != nil {
// Quota for Read is pretty limited, so watch out for running out of quota.
if isGoogleApiErrorWithCode(err, 429) {
fetchBackoff = fetchBackoff * 2
} else {
return err
}
}
modified_p := new_p
// This relies on the fact that `modify` is idempotent: since other changes might have
// happened between the call to set the policy and now, we just need to make sure that
// our change has been made. 'modify(p) == p' is our check for whether this has been
// correctly applied.
err = modify(modified_p)
if err != nil {
return err
}
if modified_p == new_p {
successfulFetches += 1
} else {
fetchBackoff = fetchBackoff * 2
if fetchBackoff > 30*time.Second {
return fmt.Errorf("Error applying IAM policy to %s: Waited too long for propagation.\n", updater.DescribeResource())
}
}
}
break
}
if isConflictError(err) {
log.Printf("[DEBUG]: Concurrent policy changes, restarting read-modify-write after %s\n", backoff)
time.Sleep(backoff)
backoff = backoff * 2
if backoff > 30*time.Second {
return fmt.Errorf("Error applying IAM policy to %s: too many concurrent policy changes.\n", updater.DescribeResource())
}
continue
}
return errwrap.Wrapf(fmt.Sprintf("Error applying IAM policy for %s: {{err}}", updater.DescribeResource()), err)
}
log.Printf("[DEBUG]: Set policy for %s", updater.DescribeResource())
return nil
}
// Merge multiple Bindings such that Bindings with the same Role result in
// a single Binding with combined Members
func mergeBindings(bindings []*cloudresourcemanager.Binding) []*cloudresourcemanager.Binding {
bm := rolesToMembersMap(bindings)
rb := make([]*cloudresourcemanager.Binding, 0)
for role, members := range bm {
var b cloudresourcemanager.Binding
b.Role = role
b.Members = make([]string, 0)
for m := range members {
b.Members = append(b.Members, m)
}
if len(b.Members) > 0 {
rb = append(rb, &b)
}
}
return rb
}
// Map a role to a map of members, allowing easy merging of multiple bindings.
func rolesToMembersMap(bindings []*cloudresourcemanager.Binding) map[string]map[string]bool {
bm := make(map[string]map[string]bool)
// Get each binding
for _, b := range bindings {
// Initialize members map
if _, ok := bm[b.Role]; !ok {
bm[b.Role] = make(map[string]bool)
}
// Get each member (user/principal) for the binding
for _, m := range b.Members {
// Add the member
bm[b.Role][m] = true
}
}
return bm
}