-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
iam.go
368 lines (303 loc) · 9.77 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
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
/*
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 model
import (
"fmt"
"strings"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/dns"
"k8s.io/kops/pkg/model/iam"
"k8s.io/kops/pkg/util/stringorslice"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awstasks"
)
// IAMModelBuilder configures IAM objects
type IAMModelBuilder struct {
*KopsModelContext
Lifecycle *fi.Lifecycle
}
var _ fi.ModelBuilder = &IAMModelBuilder{}
const NodeRolePolicyTemplate = `{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "{{ IAMServiceEC2 }}"},
"Action": "sts:AssumeRole"
}
]
}`
func (b *IAMModelBuilder) Build(c *fi.ModelBuilderContext) error {
// Collect managed Instance Group roles
managedRoles := make(map[kops.InstanceGroupRole]bool)
// Collect Instance Profile ARNs and their associated Instance Group roles
sharedProfileARNsToIGRole := make(map[string]kops.InstanceGroupRole)
for _, ig := range b.InstanceGroups {
if ig.Spec.IAM != nil && ig.Spec.IAM.Profile != nil {
specProfile := fi.StringValue(ig.Spec.IAM.Profile)
if matchingRole, ok := sharedProfileARNsToIGRole[specProfile]; ok {
if matchingRole != ig.Spec.Role {
return fmt.Errorf("found IAM instance profile assigned to multiple Instance Group roles %v and %v: %v",
ig.Spec.Role, sharedProfileARNsToIGRole[specProfile], specProfile)
}
} else {
sharedProfileARNsToIGRole[specProfile] = ig.Spec.Role
}
} else {
managedRoles[ig.Spec.Role] = true
}
}
// Generate IAM tasks for each shared role
for profileARN, igRole := range sharedProfileARNsToIGRole {
role, err := iam.BuildNodeRoleSubject(igRole)
if err != nil {
return err
}
iamName, err := findCustomAuthNameFromArn(profileARN)
if err != nil {
return fmt.Errorf("unable to parse instance profile name from arn %q: %v", profileARN, err)
}
err = b.buildIAMTasks(role, iamName, c, true)
if err != nil {
return err
}
}
// Generate IAM tasks for each managed role
for igRole := range managedRoles {
role, err := iam.BuildNodeRoleSubject(igRole)
if err != nil {
return err
}
iamName := b.IAMName(igRole)
if err := b.buildIAMTasks(role, iamName, c, false); err != nil {
return err
}
}
return nil
}
// BuildServiceAccountRoleTasks build tasks specifically for the ServiceAccount role.
func (b *IAMModelBuilder) BuildServiceAccountRoleTasks(role iam.Subject, c *fi.ModelBuilderContext) error {
iamName, err := b.IAMNameForServiceAccountRole(role)
if err != nil {
return err
}
iamRole, err := b.buildIAMRole(role, iamName, c)
if err != nil {
return err
}
if err := b.buildIAMRolePolicy(role, iamName, iamRole, c); err != nil {
return err
}
return nil
}
func (b *IAMModelBuilder) buildIAMRole(role iam.Subject, iamName string, c *fi.ModelBuilderContext) (*awstasks.IAMRole, error) {
roleKey, isServiceAccount := b.roleKey(role)
rolePolicy, err := b.buildAWSIAMRolePolicy(role)
if err != nil {
return nil, err
}
iamRole := &awstasks.IAMRole{
Name: s(iamName),
Lifecycle: b.Lifecycle,
RolePolicyDocument: fi.WrapResource(rolePolicy),
}
if isServiceAccount {
// e.g. kube-system-dns-controller
iamRole.ExportWithID = s(roleKey)
} else {
// e.g. nodes
iamRole.ExportWithID = s(roleKey + "s")
}
if b.Cluster.Spec.IAM != nil && b.Cluster.Spec.IAM.PermissionsBoundary != nil {
iamRole.PermissionsBoundary = b.Cluster.Spec.IAM.PermissionsBoundary
}
c.AddTask(iamRole)
return iamRole, nil
}
func (b *IAMModelBuilder) buildIAMRolePolicy(role iam.Subject, iamName string, iamRole *awstasks.IAMRole, c *fi.ModelBuilderContext) error {
iamPolicy := &iam.PolicyResource{
Builder: &iam.PolicyBuilder{
Cluster: b.Cluster,
Role: role,
Region: b.Region,
UseServiceAccountIAM: b.UseServiceAccountIAM(),
},
}
if !dns.IsGossipHostname(b.Cluster.ObjectMeta.Name) {
// This is slightly tricky; we need to know the hosted zone id,
// but we might be creating the hosted zone dynamically.
// We create a stub-reference which will be combined by the execution engine.
iamPolicy.DNSZone = &awstasks.DNSZone{
Name: fi.String(b.NameForDNSZone()),
}
}
t := &awstasks.IAMRolePolicy{
Name: s(iamName),
Lifecycle: b.Lifecycle,
Role: iamRole,
PolicyDocument: iamPolicy,
}
c.AddTask(t)
return nil
}
// roleKey builds a string to represent the role uniquely. It returns true if this is a service account role.
func (b *IAMModelBuilder) roleKey(role iam.Subject) (string, bool) {
serviceAccount, ok := role.ServiceAccount()
if ok {
return strings.ToLower(serviceAccount.Namespace + "-" + serviceAccount.Name), true
}
// This isn't great, but we have to be backwards compatible with the old names.
switch role.(type) {
case *iam.NodeRoleMaster:
return strings.ToLower(string(kops.InstanceGroupRoleMaster)), false
case *iam.NodeRoleNode:
return strings.ToLower(string(kops.InstanceGroupRoleNode)), false
case *iam.NodeRoleBastion:
return strings.ToLower(string(kops.InstanceGroupRoleBastion)), false
default:
klog.Fatalf("unknown node role type: %T", role)
return "", false
}
}
func (b *IAMModelBuilder) buildIAMTasks(role iam.Subject, iamName string, c *fi.ModelBuilderContext, shared bool) error {
roleKey, _ := b.roleKey(role)
iamRole, err := b.buildIAMRole(role, iamName, c)
if err != nil {
return err
}
if err := b.buildIAMRolePolicy(role, iamName, iamRole, c); err != nil {
return err
}
{
// To minimize diff for easier code review
var iamInstanceProfile *awstasks.IAMInstanceProfile
{
iamInstanceProfile = &awstasks.IAMInstanceProfile{
Name: s(iamName),
Lifecycle: b.Lifecycle,
Shared: fi.Bool(shared),
}
c.AddTask(iamInstanceProfile)
}
{
iamInstanceProfileRole := &awstasks.IAMInstanceProfileRole{
Name: s(iamName),
Lifecycle: b.Lifecycle,
InstanceProfile: iamInstanceProfile,
Role: iamRole,
}
c.AddTask(iamInstanceProfileRole)
}
// Create External Policy tasks
if !shared {
var externalPolicies []string
if b.Cluster.Spec.ExternalPolicies != nil {
p := *(b.Cluster.Spec.ExternalPolicies)
externalPolicies = append(externalPolicies, p[roleKey]...)
}
name := fmt.Sprintf("%s-policyoverride", roleKey)
t := &awstasks.IAMRolePolicy{
Name: s(name),
Lifecycle: b.Lifecycle,
Role: iamRole,
Managed: true,
ExternalPolicies: &externalPolicies,
}
c.AddTask(t)
}
// Generate additional policies if needed, and attach to existing role
if !shared {
additionalPolicy := ""
if b.Cluster.Spec.AdditionalPolicies != nil {
additionalPolicies := *(b.Cluster.Spec.AdditionalPolicies)
additionalPolicy = additionalPolicies[roleKey]
}
additionalPolicyName := "additional." + iamName
t := &awstasks.IAMRolePolicy{
Name: s(additionalPolicyName),
Lifecycle: b.Lifecycle,
Role: iamRole,
}
if additionalPolicy != "" {
p := &iam.Policy{
Version: iam.PolicyDefaultVersion,
}
statements, err := iam.ParseStatements(additionalPolicy)
if err != nil {
return fmt.Errorf("additionalPolicy %q is invalid: %v", roleKey, err)
}
p.Statement = append(p.Statement, statements...)
policy, err := p.AsJSON()
if err != nil {
return fmt.Errorf("error building IAM policy: %v", err)
}
t.PolicyDocument = fi.WrapResource(fi.NewStringResource(policy))
} else {
t.PolicyDocument = fi.WrapResource(fi.NewStringResource(""))
}
c.AddTask(t)
}
}
return nil
}
// IAMServiceEC2 returns the name of the IAM service for EC2 in the current region.
// It is ec2.amazonaws.com everywhere but in cn-north / cn-northwest, where it is ec2.amazonaws.com.cn
func IAMServiceEC2(region string) string {
switch region {
case "cn-north-1":
return "ec2.amazonaws.com.cn"
case "cn-northwest-1":
return "ec2.amazonaws.com.cn"
default:
return "ec2.amazonaws.com"
}
}
// buildAWSIAMRolePolicy produces the AWS IAM role policy for the given role.
func (b *IAMModelBuilder) buildAWSIAMRolePolicy(role iam.Subject) (fi.Resource, error) {
var policy string
serviceAccount, ok := role.ServiceAccount()
if ok {
serviceAccountIssuer, err := iam.ServiceAccountIssuer(b.ClusterName(), &b.Cluster.Spec)
if err != nil {
return nil, err
}
oidcProvider := strings.TrimPrefix(serviceAccountIssuer, "https://")
iamPolicy := &iam.Policy{
Version: iam.PolicyDefaultVersion,
Statement: []*iam.Statement{
{
Effect: "Allow",
Principal: iam.Principal{
Federated: "arn:aws:iam::" + b.AWSAccountID + ":oidc-provider/" + oidcProvider,
},
Action: stringorslice.String("sts:AssumeRoleWithWebIdentity"),
Condition: map[string]interface{}{
"StringEquals": map[string]interface{}{
oidcProvider + ":sub": "system:serviceaccount:" + serviceAccount.Namespace + ":" + serviceAccount.Name,
},
},
},
},
}
s, err := iamPolicy.AsJSON()
if err != nil {
return nil, err
}
policy = s
} else {
// We don't generate using json.Marshal here, it would create whitespace changes in the policy for existing clusters.
policy = strings.ReplaceAll(NodeRolePolicyTemplate, "{{ IAMServiceEC2 }}", IAMServiceEC2(b.Region))
}
return fi.NewStringResource(policy), nil
}