-
Notifications
You must be signed in to change notification settings - Fork 0
/
reconciler.go
399 lines (337 loc) · 12.7 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
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
package google_gar_reconciler
import (
"context"
"fmt"
"maps"
"net/http"
"time"
artifactregistry "cloud.google.com/go/artifactregistry/apiv1"
"cloud.google.com/go/artifactregistry/apiv1/artifactregistrypb"
"cloud.google.com/go/iam/apiv1/iampb"
"github.com/nais/api/pkg/apiclient"
"github.com/nais/api/pkg/protoapi"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/api/googleapi"
"google.golang.org/api/iam/v1"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"k8s.io/utils/ptr"
"github.com/nais/api-reconcilers/internal/gcp"
"github.com/nais/api-reconcilers/internal/google_token_source"
"github.com/nais/api-reconcilers/internal/reconcilers"
github_team_reconciler "github.com/nais/api-reconcilers/internal/reconcilers/github/team"
str "github.com/nais/api-reconcilers/internal/strings"
)
const (
reconcilerName = "google:gcp:gar"
managedByLabelName = "managed-by"
managedByLabelValue = "api-reconcilers"
auditActionDeleteGarRepository = "google:gar:delete"
)
type garReconciler struct {
googleManagementProjectID string
workloadIdentityPoolName string
artifactRegistry *artifactregistry.Client
iamService *iam.Service
}
type OptFunc func(*garReconciler)
func WithGarClient(client *artifactregistry.Client) OptFunc {
return func(r *garReconciler) {
r.artifactRegistry = client
}
}
func WithIAMService(service *iam.Service) OptFunc {
return func(r *garReconciler) {
r.iamService = service
}
}
func New(ctx context.Context, serviceAccountEmail, googleManagementProjectID, workloadIdentityPoolName string, opts ...OptFunc) (reconcilers.Reconciler, error) {
r := &garReconciler{
googleManagementProjectID: googleManagementProjectID,
workloadIdentityPoolName: workloadIdentityPoolName,
}
for _, opt := range opts {
opt(r)
}
if r.iamService == nil || r.artifactRegistry == nil {
ts, err := google_token_source.GcpTokenSource(ctx, serviceAccountEmail)
if err != nil {
return nil, fmt.Errorf("get delegated token source: %w", err)
}
if r.iamService == nil {
iamService, err := iam.NewService(ctx, option.WithTokenSource(ts))
if err != nil {
return nil, err
}
r.iamService = iamService
}
if r.artifactRegistry == nil {
artifactRegistry, err := artifactregistry.NewClient(ctx, option.WithTokenSource(ts), option.WithGRPCDialOption(grpc.WithStatsHandler(otelgrpc.NewClientHandler())))
if err != nil {
return nil, err
}
r.artifactRegistry = artifactRegistry
}
}
return r, nil
}
func (r *garReconciler) Configuration() *protoapi.NewReconciler {
return &protoapi.NewReconciler{
Name: r.Name(),
DisplayName: "Google Artifact Registry",
Description: "Provision artifact registry repositories for Console teams.",
MemberAware: false,
}
}
func (r *garReconciler) Name() string {
return reconcilerName
}
func (r *garReconciler) Reconcile(ctx context.Context, client *apiclient.APIClient, naisTeam *protoapi.Team, log logrus.FieldLogger) error {
serviceAccount, err := r.getOrCreateServiceAccount(ctx, naisTeam.Slug)
if err != nil {
return err
}
if err := r.setServiceAccountPolicy(ctx, serviceAccount, naisTeam.Slug, client); err != nil {
return err
}
garRepository, err := r.getOrCreateOrUpdateGarRepository(ctx, naisTeam.Slug, log)
if err != nil {
return err
}
if err := r.setGarRepositoryPolicy(ctx, garRepository, serviceAccount, naisTeam.GoogleGroupEmail); err != nil {
return err
}
client.Teams().SetTeamExternalReferences(ctx, &protoapi.SetTeamExternalReferencesRequest{
Slug: naisTeam.Slug,
GarRepository: &garRepository.Name,
})
return nil
}
func (r *garReconciler) Delete(ctx context.Context, client *apiclient.APIClient, naisTeam *protoapi.Team, log logrus.FieldLogger) error {
if naisTeam.GarRepository == nil {
log.Warnf("missing repository name in team, assume team has already been deleted")
return nil
}
serviceAccountName, _ := serviceAccountNameAndAccountID(naisTeam.Slug, r.googleManagementProjectID)
if _, err := r.iamService.Projects.ServiceAccounts.Delete(serviceAccountName).Context(ctx).Do(); err != nil {
googleError, ok := err.(*googleapi.Error)
if !ok || googleError.Code != http.StatusNotFound {
return fmt.Errorf("delete service account %q: %w", serviceAccountName, err)
}
log.WithError(err).Errorf("GAR service account %q does not exist, nothing to delete", serviceAccountName)
}
req := &artifactregistrypb.DeleteRepositoryRequest{
Name: *naisTeam.GarRepository,
}
operation, err := r.artifactRegistry.DeleteRepository(ctx, req)
if err != nil {
return fmt.Errorf("delete GAR repository for team %q: %w", naisTeam.Slug, err)
}
if err = operation.Wait(ctx); err != nil {
return fmt.Errorf("wait for GAR repository deletion for team %q: %w", naisTeam.Slug, err)
}
reconcilers.AuditLogForTeam(
ctx,
client,
r,
auditActionDeleteGarRepository,
naisTeam.Slug,
"Delete GAR repository %q", *naisTeam.GarRepository,
)
_, err = client.Teams().SetTeamExternalReferences(ctx, &protoapi.SetTeamExternalReferencesRequest{
Slug: naisTeam.Slug,
GarRepository: ptr.To(""),
})
return err
}
func (r *garReconciler) getOrCreateServiceAccount(ctx context.Context, teamSlug string) (*iam.ServiceAccount, error) {
serviceAccountName, accountID := serviceAccountNameAndAccountID(teamSlug, r.googleManagementProjectID)
existing, err := r.iamService.Projects.ServiceAccounts.Get(serviceAccountName).Context(ctx).Do()
if err == nil {
return existing, nil
}
return r.iamService.Projects.ServiceAccounts.Create("projects/"+r.googleManagementProjectID, &iam.CreateServiceAccountRequest{
AccountId: accountID,
ServiceAccount: &iam.ServiceAccount{
Description: "Service Account used to push images to Google Artifact Registry for " + teamSlug,
DisplayName: "Artifact Pusher for " + teamSlug,
},
}).Context(ctx).Do()
}
func (r *garReconciler) setServiceAccountPolicy(ctx context.Context, serviceAccount *iam.ServiceAccount, teamSlug string, client *apiclient.APIClient) error {
members, err := r.getServiceAccountPolicyMembers(ctx, teamSlug, client.Reconcilers())
if err != nil {
return err
}
req := iam.SetIamPolicyRequest{
Policy: &iam.Policy{
Bindings: []*iam.Binding{
{
Members: members,
Role: "roles/iam.workloadIdentityUser",
},
},
},
}
_, err = r.iamService.Projects.ServiceAccounts.SetIamPolicy(serviceAccount.Name, &req).Context(ctx).Do()
return err
}
func (r *garReconciler) getOrCreateOrUpdateGarRepository(ctx context.Context, teamSlug string, log logrus.FieldLogger) (*artifactregistrypb.Repository, error) {
parent := "projects/" + r.googleManagementProjectID + "/locations/europe-north1"
name := parent + "/repositories/" + teamSlug
description := fmt.Sprintf("Docker repository for team %q. Managed by github.com/nais/api-reconcilers.", teamSlug)
getRequest := &artifactregistrypb.GetRepositoryRequest{
Name: name,
}
existing, err := r.artifactRegistry.GetRepository(ctx, getRequest)
if err != nil && status.Code(err) != codes.NotFound {
return nil, err
}
if existing == nil {
template := &artifactregistrypb.Repository{
Format: artifactregistrypb.Repository_DOCKER,
Name: name,
Description: description,
Labels: map[string]string{
"team": teamSlug,
managedByLabelName: managedByLabelValue,
},
}
createRequest := &artifactregistrypb.CreateRepositoryRequest{
Parent: parent,
Repository: template,
RepositoryId: teamSlug,
}
createResponse, err := r.artifactRegistry.CreateRepository(ctx, createRequest)
if err != nil {
return nil, err
}
return createResponse.Wait(ctx)
}
if existing.Format != artifactregistrypb.Repository_DOCKER {
return nil, fmt.Errorf("existing repo has invalid format: %q %q", name, existing.Format)
}
return r.updateGarRepository(ctx, existing, teamSlug, description, log)
}
func (r *garReconciler) getServiceAccountPolicyMembers(ctx context.Context, teamSlug string, client protoapi.ReconcilersClient) ([]string, error) {
repos, err := github_team_reconciler.GetTeamRepositories(ctx, client, teamSlug)
if err != nil {
return nil, err
}
members := make([]string, 0)
for _, githubRepo := range repos {
if githubRepo.Archived {
continue
}
for _, perm := range githubRepo.Permissions {
if perm.Name == "push" && perm.Granted {
member := "principalSet://iam.googleapis.com/" + r.workloadIdentityPoolName + "/attribute.repository/" + githubRepo.Name
members = append(members, member)
break
}
}
}
return members, nil
}
func (r *garReconciler) updateGarRepository(ctx context.Context, repository *artifactregistrypb.Repository, teamSlug, description string, log logrus.FieldLogger) (*artifactregistrypb.Repository, error) {
var changes []string
if repository.Labels["team"] != teamSlug {
repository.Labels["team"] = teamSlug
changes = append(changes, "labels.team")
}
if repository.Labels[managedByLabelName] != managedByLabelValue {
repository.Labels[managedByLabelName] = managedByLabelValue
changes = append(changes, "labels.managed-by")
}
if repository.Description != description {
repository.Description = fmt.Sprintf("Docker repository for team %q. Managed by github.com/nais/api-reconcilers.", teamSlug)
changes = append(changes, "description")
}
targetPolicies := DefaultCleanupPolicies()
policyUpToDate := maps.EqualFunc(targetPolicies, repository.CleanupPolicies, func(a, b *artifactregistrypb.CleanupPolicy) bool {
return proto.Equal(a, b)
})
if !policyUpToDate || repository.CleanupPolicyDryRun {
repository.CleanupPolicyDryRun = false
repository.CleanupPolicies = targetPolicies
changes = append(changes, "cleanup_policies")
changes = append(changes, "cleanup_policy_dry_run")
}
if len(changes) > 0 {
updateRequest := &artifactregistrypb.UpdateRepositoryRequest{
Repository: repository,
UpdateMask: &fieldmaskpb.FieldMask{
Paths: changes,
},
}
return r.artifactRegistry.UpdateRepository(ctx, updateRequest)
}
log.Debugf("existing repository is up to date")
return repository, nil
}
func (r *garReconciler) setGarRepositoryPolicy(ctx context.Context, repository *artifactregistrypb.Repository, serviceAccount *iam.ServiceAccount, groupEmail *string) error {
bindings := []*iampb.Binding{
{
Role: "roles/artifactregistry.writer",
Members: []string{"serviceAccount:" + serviceAccount.Email},
},
}
if groupEmail != nil {
bindings = append(bindings, &iampb.Binding{
Role: "roles/artifactregistry.repoAdmin",
Members: []string{"group:" + *groupEmail},
})
}
_, err := r.artifactRegistry.SetIamPolicy(ctx, &iampb.SetIamPolicyRequest{
Resource: repository.Name,
Policy: &iampb.Policy{
Bindings: bindings,
},
})
return err
}
func serviceAccountNameAndAccountID(teamSlug, projectID string) (serviceAccountName, accountID string) {
accountID = str.SlugHashPrefixTruncate(teamSlug, "gar", gcp.GoogleServiceAccountMaxLength)
emailAddress := accountID + "@" + projectID + ".iam.gserviceaccount.com"
serviceAccountName = "projects/" + projectID + "/serviceAccounts/" + emailAddress
return
}
// Remove all images that are more than 90 days old, but keep the last 50 "versions" regardless of age.
// These numbers are also referenced in our own documentation at: https://doc.nais.io/how-to-guides/github-action/; try to keep them in sync.
//
// Each "build and push" includes artifacts such as signatures and attestations that seemingly count as "versions".
// Thus, an "image" actually consists of 5 artifacts at the worst (for images pushed through the nais/docker-build-push action)
//
// Documentation: https://cloud.google.com/artifact-registry/docs/repositories/cleanup-policy
func DefaultCleanupPolicies() map[string]*artifactregistrypb.CleanupPolicy {
var keepCount int32 = 50
keepUntilAge := time.Hour * 24 * 90
anyTagState := artifactregistrypb.CleanupPolicyCondition_ANY
return map[string]*artifactregistrypb.CleanupPolicy{
"delete_old_images": {
Id: "delete_old_images",
Action: artifactregistrypb.CleanupPolicy_DELETE,
ConditionType: &artifactregistrypb.CleanupPolicy_Condition{
Condition: &artifactregistrypb.CleanupPolicyCondition{
TagState: &anyTagState,
OlderThan: durationpb.New(keepUntilAge),
},
},
},
"keep_latest_versions": {
Id: "keep_latest_versions",
Action: artifactregistrypb.CleanupPolicy_KEEP,
ConditionType: &artifactregistrypb.CleanupPolicy_MostRecentVersions{
MostRecentVersions: &artifactregistrypb.CleanupPolicyMostRecentVersions{
KeepCount: &keepCount,
},
},
},
}
}