-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Copy pathiamrolepolicy.go
404 lines (332 loc) · 11.2 KB
/
iamrolepolicy.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
/*
Copyright 2019 The Kubernetes Authors.
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 awstasks
import (
"encoding/json"
"fmt"
"hash/fnv"
"net/url"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/iam"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/diff"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
)
// +kops:fitask
type IAMRolePolicy struct {
ID *string
Lifecycle fi.Lifecycle
Name *string
Role *IAMRole
// The PolicyDocument to create as an inline policy.
// If the PolicyDocument is empty, the policy will be removed.
PolicyDocument fi.Resource
// External (non-kops managed) AWS policies to attach to the role
ExternalPolicies *[]string
// Managed tracks the use of ExternalPolicies
Managed bool
}
func (e *IAMRolePolicy) Find(c *fi.Context) (*IAMRolePolicy, error) {
var actual IAMRolePolicy
cloud := c.Cloud.(awsup.AWSCloud)
// Handle policy overrides
if e.ExternalPolicies != nil {
request := &iam.ListAttachedRolePoliciesInput{
RoleName: e.Role.Name,
}
response, err := cloud.IAM().ListAttachedRolePolicies(request)
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == iam.ErrCodeNoSuchEntityException {
return nil, nil
}
return nil, fmt.Errorf("error getting policies for role: %v", err)
}
var policies []string
if response != nil && len(response.AttachedPolicies) > 0 {
for _, policy := range response.AttachedPolicies {
policies = append(policies, aws.StringValue(policy.PolicyArn))
}
}
sort.Strings(policies)
actual.ID = e.ID
actual.Name = e.Name
actual.Lifecycle = e.Lifecycle
actual.Role = e.Role
actual.Managed = true
actual.ExternalPolicies = &policies
return &actual, nil
}
request := &iam.GetRolePolicyInput{
RoleName: e.Role.Name,
PolicyName: e.Name,
}
response, err := cloud.IAM().GetRolePolicy(request)
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == iam.ErrCodeNoSuchEntityException {
return nil, nil
}
}
if err != nil {
return nil, fmt.Errorf("error getting role: %v", err)
}
p := response
actual.Role = &IAMRole{Name: p.RoleName}
if aws.StringValue(e.Role.Name) == aws.StringValue(p.RoleName) {
actual.Role.ID = e.Role.ID
}
if p.PolicyDocument != nil {
// The PolicyDocument is URI encoded (?)
policy := *p.PolicyDocument
policy, err = url.QueryUnescape(policy)
if err != nil {
return nil, fmt.Errorf("error parsing PolicyDocument for IAMRolePolicy %q: %v", aws.StringValue(e.Name), err)
}
// Reformat the PolicyDocument by unmarshaling and re-marshaling to JSON.
// This will make it possible to compare it when using CloudFormation.
var jsonData interface{}
err = json.Unmarshal([]byte(policy), &jsonData)
if err != nil {
return nil, fmt.Errorf("error parsing cloudformation policy document from JSON: %v", err)
}
jsonBytes, err := json.MarshalIndent(jsonData, "", " ")
if err != nil {
return nil, fmt.Errorf("error converting cloudformation policy document to JSON: %v", err)
}
actual.PolicyDocument = fi.NewStringResource(string(jsonBytes))
}
actual.Name = p.PolicyName
e.ID = actual.ID
// Avoid spurious changes
actual.Lifecycle = e.Lifecycle
return &actual, nil
}
func (e *IAMRolePolicy) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (s *IAMRolePolicy) CheckChanges(a, e, changes *IAMRolePolicy) error {
if a != nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
}
return nil
}
func (_ *IAMRolePolicy) ShouldCreate(a, e, changes *IAMRolePolicy) (bool, error) {
ePolicy, err := e.policyDocumentString()
if err != nil {
return false, fmt.Errorf("error rendering PolicyDocument: %v", err)
}
if a == nil && ePolicy == "" && e.ExternalPolicies == nil {
return false, nil
}
return true, nil
}
func (_ *IAMRolePolicy) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *IAMRolePolicy) error {
policy, err := e.policyDocumentString()
if err != nil {
return fmt.Errorf("error rendering PolicyDocument: %v", err)
}
// Handles the full lifecycle of Policy Overrides
if e.Managed {
// Attach policies that are not already attached
AttachPolicies:
for _, policy := range *e.ExternalPolicies {
for _, cloudPolicy := range *a.ExternalPolicies {
if cloudPolicy == policy {
continue AttachPolicies
}
}
request := &iam.AttachRolePolicyInput{
RoleName: e.Role.Name,
PolicyArn: s(policy),
}
_, err = t.Cloud.IAM().AttachRolePolicy(request)
if err != nil {
return fmt.Errorf("error attaching IAMRolePolicy: %v", err)
}
}
// Clean up unused cloud policies
CheckPolicies:
for _, cloudPolicy := range *a.ExternalPolicies {
for _, policy := range *e.ExternalPolicies {
if policy == cloudPolicy {
continue CheckPolicies
}
}
klog.V(2).Infof("Detaching unused IAMRolePolicy %s/%s", aws.StringValue(e.Role.Name), cloudPolicy)
// Detach policy
request := &iam.DetachRolePolicyInput{
RoleName: e.Role.Name,
PolicyArn: s(cloudPolicy),
}
_, err := t.Cloud.IAM().DetachRolePolicy(request)
if err != nil {
klog.V(2).Infof("Unable to detach IAMRolePolicy %s/%s", aws.StringValue(e.Role.Name), cloudPolicy)
return err
}
}
return nil
}
if policy == "" {
// A deletion
request := &iam.DeleteRolePolicyInput{}
request.RoleName = e.Role.Name
request.PolicyName = e.Name
klog.V(2).Infof("Deleting role policy %s/%s", aws.StringValue(e.Role.Name), aws.StringValue(e.Name))
_, err = t.Cloud.IAM().DeleteRolePolicy(request)
if err != nil {
if awsup.AWSErrorCode(err) == iam.ErrCodeNoSuchEntityException {
// Already deleted
klog.V(2).Infof("Got NoSuchEntity deleting role policy %s/%s; assuming does not exist", aws.StringValue(e.Role.Name), aws.StringValue(e.Name))
return nil
}
return fmt.Errorf("error deleting IAMRolePolicy: %v", err)
}
return nil
}
doPut := false
if a == nil {
klog.V(2).Infof("Creating IAMRolePolicy")
doPut = true
} else if changes != nil {
if changes.PolicyDocument != nil {
klog.V(2).Infof("Applying changed role policy to %q:", *e.Name)
actualPolicy, err := a.policyDocumentString()
if err != nil {
return fmt.Errorf("error reading actual policy document: %v", err)
}
if actualPolicy == policy {
klog.Warning("Policies were actually the same")
} else {
d := diff.FormatDiff(actualPolicy, policy)
klog.V(2).Infof("diff: %s", d)
}
doPut = true
}
}
if doPut {
request := &iam.PutRolePolicyInput{}
request.PolicyDocument = aws.String(policy)
request.RoleName = e.Role.Name
request.PolicyName = e.Name
klog.V(8).Infof("PutRolePolicy RoleName=%s PolicyName=%s: %s", aws.StringValue(e.Role.Name), aws.StringValue(e.Name), policy)
_, err = t.Cloud.IAM().PutRolePolicy(request)
if err != nil {
klog.V(2).Infof("PutRolePolicy RoleName=%s PolicyName=%s: %s", aws.StringValue(e.Role.Name), aws.StringValue(e.Name), policy)
return fmt.Errorf("error creating/updating IAMRolePolicy: %v", err)
}
}
// TODO: Should we use path as our tag?
return nil // No tags in IAM
}
func (e *IAMRolePolicy) policyDocumentString() (string, error) {
if e.PolicyDocument == nil {
return "", nil
}
policy, err := fi.ResourceAsString(e.PolicyDocument)
if err != nil {
return "", err
}
policySize := len(policy)
if policySize > 10240 {
return "", fmt.Errorf("policy size was %d. Policy cannot exceed 10240 bytes.", policySize)
}
return policy, err
}
type terraformIAMRolePolicy struct {
Name *string `json:"name,omitempty" cty:"name"`
Role *terraformWriter.Literal `json:"role" cty:"role"`
PolicyDocument *terraformWriter.Literal `json:"policy,omitempty" cty:"policy"`
PolicyArn *string `json:"policy_arn,omitempty" cty:"policy_arn"`
}
func (_ *IAMRolePolicy) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *IAMRolePolicy) error {
if e.ExternalPolicies != nil && len(*e.ExternalPolicies) > 0 {
for _, policy := range *e.ExternalPolicies {
// create a hash of the arn
h := fnv.New32a()
h.Write([]byte(policy))
name := fmt.Sprintf("%s-%d", *e.Name, h.Sum32())
tf := &terraformIAMRolePolicy{
Role: e.Role.TerraformLink(),
PolicyArn: s(policy),
}
err := t.RenderResource("aws_iam_role_policy_attachment", name, tf)
if err != nil {
return fmt.Errorf("error rendering RolePolicyAttachment: %v", err)
}
}
}
policyString, err := e.policyDocumentString()
if err != nil {
return fmt.Errorf("error rendering PolicyDocument: %v", err)
}
if policyString == "" {
// A deletion; we simply don't render; terraform will observe the removal
return nil
}
policy, err := t.AddFileResource("aws_iam_role_policy", *e.Name, "policy", e.PolicyDocument, false)
if err != nil {
return fmt.Errorf("error rendering PolicyDocument: %v", err)
}
tf := &terraformIAMRolePolicy{
Name: e.Name,
Role: e.Role.TerraformLink(),
PolicyDocument: policy,
}
return t.RenderResource("aws_iam_role_policy", *e.Name, tf)
}
func (e *IAMRolePolicy) TerraformLink() *terraformWriter.Literal {
return terraformWriter.LiteralSelfLink("aws_iam_role_policy", *e.Name)
}
type cloudformationIAMRolePolicy struct {
PolicyName *string `json:"PolicyName"`
Roles []*cloudformation.Literal `json:"Roles"`
PolicyDocument map[string]interface{} `json:"PolicyDocument"`
}
func (_ *IAMRolePolicy) RenderCloudformation(t *cloudformation.CloudformationTarget, a, e, changes *IAMRolePolicy) error {
// Currently CloudFormation does not have a reciprocal function to Terraform that allows the modification of a role
// after the fact. In order to make this feature complete we would have to intercept the role task and modify it.
if e.ExternalPolicies != nil && len(*e.ExternalPolicies) > 0 {
return fmt.Errorf("CloudFormation not supported for use with ExternalPolicies.")
}
policyString, err := e.policyDocumentString()
if err != nil {
return fmt.Errorf("error rendering PolicyDocument: %v", err)
}
if policyString == "" {
// A deletion; we simply don't render; cloudformation will observe the removal
return nil
}
tf := &cloudformationIAMRolePolicy{
PolicyName: e.Name,
Roles: []*cloudformation.Literal{e.Role.CloudformationLink()},
}
{
data := make(map[string]interface{})
err = json.Unmarshal([]byte(policyString), &data)
if err != nil {
return fmt.Errorf("error parsing PolicyDocument: %v", err)
}
tf.PolicyDocument = data
}
return t.RenderResource("AWS::IAM::Policy", *e.Name, tf)
}
func (e *IAMRolePolicy) CloudformationLink() *cloudformation.Literal {
return cloudformation.Ref("AWS::IAM::Policy", *e.Name)
}