This repository has been archived by the owner on Jun 19, 2022. It is now read-only.
/
reconciler.go
250 lines (224 loc) · 10.5 KB
/
reconciler.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
/*
Copyright 2020 Google LLC
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 identity
import (
"context"
"fmt"
"strings"
"time"
"go.uber.org/zap"
"google.golang.org/api/iam/v1"
corev1 "k8s.io/api/core/v1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/retry"
kubeclient "knative.dev/pkg/client/injection/kube/client"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
duck "github.com/google/knative-gcp/pkg/duck/v1alpha1"
"github.com/google/knative-gcp/pkg/reconciler/identity/resources"
"github.com/google/knative-gcp/pkg/utils"
)
const (
Add = "add"
Remove = "remove"
Role = "roles/iam.workloadIdentityUser"
deleteWorkloadIdentityFailed = "WorkloadIdentityDeleteFailed"
workloadIdentityFailed = "WorkloadIdentityReconcileFailed"
concurrencyError = "googleapi: Error 409: There were concurrent policy changes."
)
// defaultRetry represents that there will be 3 iterations.
// The duration starts from 100ms and is multiplied by factor 2.0 for each iteration.
var defaultRetry = wait.Backoff{
Steps: 5,
Duration: 100 * time.Millisecond,
Factor: 2.0,
// The sleep at each iteration is the duration plus an additional
// amount chosen uniformly at random from the interval between 0 and jitter*duration.
Jitter: 1.0,
}
func NewIdentity(ctx context.Context) *Identity {
return &Identity{
KubeClient: kubeclient.Get(ctx),
}
}
type Identity struct {
KubeClient kubernetes.Interface
}
// ReconcileWorkloadIdentity will create a k8s service account, add ownerReference to it,
// and add iam policy binding between this k8s service account and its corresponding GCP service account.
func (i *Identity) ReconcileWorkloadIdentity(ctx context.Context, projectID string, identifiable duck.Identifiable) (*corev1.ServiceAccount, error) {
status := identifiable.IdentityStatus()
// Create corresponding k8s ServiceAccount if it doesn't exist.
namespace := identifiable.GetObjectMeta().GetNamespace()
kServiceAccount, err := i.createServiceAccount(ctx, namespace, identifiable.IdentitySpec().GoogleServiceAccount)
if err != nil {
status.MarkWorkloadIdentityFailed(identifiable.ConditionSet(), workloadIdentityFailed, err.Error())
return nil, fmt.Errorf("failed to get k8s ServiceAccount: %w", err)
}
// Add ownerReference to K8s ServiceAccount.
expectOwnerReference := *kmeta.NewControllerRef(identifiable)
expectOwnerReference.Controller = ptr.Bool(false)
if !ownerReferenceExists(kServiceAccount, expectOwnerReference) {
kServiceAccount.OwnerReferences = append(kServiceAccount.OwnerReferences, expectOwnerReference)
if _, err := i.KubeClient.CoreV1().ServiceAccounts(kServiceAccount.Namespace).Update(kServiceAccount); err != nil {
logging.FromContext(ctx).Desugar().Error("Failed to update OwnerReferences", zap.Error(err))
status.MarkWorkloadIdentityFailed(identifiable.ConditionSet(), workloadIdentityFailed, err.Error())
return nil, fmt.Errorf("failed to update OwnerReferences: %w", err)
}
}
// Add iam policy binding to GCP ServiceAccount.
if err := addIamPolicyBinding(ctx, projectID, identifiable.IdentitySpec().GoogleServiceAccount, kServiceAccount); err != nil {
status.MarkWorkloadIdentityFailed(identifiable.ConditionSet(), workloadIdentityFailed, err.Error())
return kServiceAccount, fmt.Errorf("adding iam policy binding failed with: %s", err)
}
status.ServiceAccountName = kServiceAccount.Name
status.MarkWorkloadIdentityConfigured(identifiable.ConditionSet())
return kServiceAccount, nil
}
// DeleteWorkloadIdentity will remove iam policy binding between k8s service account and its corresponding GCP service account,
// if this k8s service account only has one ownerReference.
func (i *Identity) DeleteWorkloadIdentity(ctx context.Context, projectID string, identifiable duck.Identifiable) error {
status := identifiable.IdentityStatus()
// If the ServiceAccountName wasn't set in the status, it means there are errors when reconciling workload identity.
// If ReconcileWorkloadIdentity error is for k8s service account, it will be handled by k8s ownerReferences Garbage collection.
// If ReconcileWorkloadIdentity error is for add iam policy binding, then no need to remove it.
// Thus, for this case, we simply return.
if status.ServiceAccountName == "" {
return nil
}
namespace := identifiable.GetObjectMeta().GetNamespace()
kServiceAccountName := resources.GenerateServiceAccountName(identifiable.IdentitySpec().GoogleServiceAccount)
kServiceAccount, err := i.KubeClient.CoreV1().ServiceAccounts(namespace).Get(kServiceAccountName, metav1.GetOptions{})
if err != nil {
status.MarkWorkloadIdentityFailed(identifiable.ConditionSet(), deleteWorkloadIdentityFailed, err.Error())
// k8s ServiceAccount should be there.
return fmt.Errorf("getting k8s service account failed with: %w", err)
}
if kServiceAccount != nil && len(kServiceAccount.OwnerReferences) == 1 {
logging.FromContext(ctx).Desugar().Debug("Removing iam policy binding.")
if err := removeIamPolicyBinding(ctx, projectID, identifiable.IdentitySpec().GoogleServiceAccount, kServiceAccount); err != nil {
status.MarkWorkloadIdentityFailed(identifiable.ConditionSet(), deleteWorkloadIdentityFailed, err.Error())
return fmt.Errorf("removing iam policy binding failed with: %w", err)
}
}
return nil
}
func (i *Identity) createServiceAccount(ctx context.Context, namespace, gServiceAccount string) (*corev1.ServiceAccount, error) {
kServiceAccountName := resources.GenerateServiceAccountName(gServiceAccount)
kServiceAccount, err := i.KubeClient.CoreV1().ServiceAccounts(namespace).Get(kServiceAccountName, metav1.GetOptions{})
if err != nil {
if apierrs.IsNotFound(err) {
expect := resources.MakeServiceAccount(namespace, gServiceAccount)
logging.FromContext(ctx).Desugar().Debug("Creating k8s service account", zap.Any("ksa", expect))
kServiceAccount, err := i.KubeClient.CoreV1().ServiceAccounts(expect.Namespace).Create(expect)
if err != nil {
logging.FromContext(ctx).Desugar().Error("Failed to create k8s service account", zap.Error(err))
return nil, fmt.Errorf("failed to create k8s service account: %w", err)
}
return kServiceAccount, nil
}
logging.FromContext(ctx).Desugar().Error("Failed to get k8s service account", zap.Error(err))
return nil, fmt.Errorf("getting k8s service account failed with: %w", err)
}
return kServiceAccount, nil
}
// TODO he iam policy binding should be mocked so that we can unit test it. issue https://github.com/google/knative-gcp/issues/657
// addIamPolicyBinding will add iam policy binding, which is related to a provided k8s ServiceAccount, to a GCP ServiceAccount.
func addIamPolicyBinding(ctx context.Context, projectID, gServiceAccount string, kServiceAccount *corev1.ServiceAccount) error {
if err := setIamPolicy(ctx, Add, projectID, gServiceAccount, kServiceAccount); err != nil {
return err
}
return nil
}
// removeIamPolicyBinding will remove iam policy binding, which is related to a provided k8s ServiceAccount, from a GCP ServiceAccount.
func removeIamPolicyBinding(ctx context.Context, projectID, gServiceAccount string, kServiceAccount *corev1.ServiceAccount) error {
if err := setIamPolicy(ctx, Remove, projectID, gServiceAccount, kServiceAccount); err != nil {
return err
}
return nil
}
func setIamPolicy(ctx context.Context, action, projectID string, gServiceAccount string, kServiceAccount *corev1.ServiceAccount) error {
iamService, err := iam.NewService(ctx)
if err != nil {
return fmt.Errorf("failed to set google iam service: %w", err)
}
projectId, err := utils.ProjectID(projectID)
if err != nil {
return fmt.Errorf("failed to get project id: %w", err)
}
// Extract gServiceAccount's project name. The format of gServiceAccountName is service-account-name@project-id.iam.gserviceaccount.com.
gsaProject := strings.Split(strings.Split(gServiceAccount, "@")[1], ".")[0]
resource := fmt.Sprintf("projects/%s/serviceAccounts/%s", gsaProject, gServiceAccount)
resp, err := iamService.Projects.ServiceAccounts.GetIamPolicy(resource).Context(ctx).Do()
if err != nil {
return fmt.Errorf("failed to get iam policy: %w", err)
}
// currentMember will end up as "serviceAccount:projectId.svc.id.goog[k8s-namespace/ksa-name]".
currentMember := fmt.Sprintf("serviceAccount:%s.svc.id.goog[%s/%s]", projectId, kServiceAccount.Namespace, kServiceAccount.Name)
rb := makeSetIamPolicyRequest(resp.Bindings, action, currentMember)
// Repeat setting iam policy binding with exponential backoff when there is concurrency issue.
return retry.OnError(defaultRetry, isConflict, func() error {
if _, err = iamService.Projects.ServiceAccounts.SetIamPolicy(resource, rb).Context(ctx).Do(); err != nil {
return fmt.Errorf("failed to set iam policy: %w", err)
}
return nil
})
}
func makeSetIamPolicyRequest(bindings []*iam.Binding, action, currentMember string) *iam.SetIamPolicyRequest {
switch action {
case Add:
return &iam.SetIamPolicyRequest{
Policy: &iam.Policy{
Bindings: append(bindings, &iam.Binding{
Members: []string{currentMember},
Role: Role}),
},
}
case Remove:
for _, binding := range bindings {
if binding.Role == Role {
newMembers := []string{}
for _, member := range binding.Members {
if member != currentMember {
newMembers = append(newMembers, member)
}
}
binding.Members = newMembers
}
}
return &iam.SetIamPolicyRequest{
Policy: &iam.Policy{
Bindings: bindings,
},
}
}
return nil
}
// isConflict determines if the err is an error which indicates concurrency issue.
func isConflict(err error) bool {
return strings.Contains(err.Error(), concurrencyError)
}
// ownerReferenceExists checks if a K8s ServiceAccount contains specific ownerReference
func ownerReferenceExists(kServiceAccount *corev1.ServiceAccount, expect metav1.OwnerReference) bool {
references := kServiceAccount.OwnerReferences
for _, reference := range references {
if reference.Name == expect.Name {
return true
}
}
return false
}