-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathrepository_principal_role.go
616 lines (591 loc) · 24.9 KB
/
repository_principal_role.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package iam
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/intglobals"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/oplog"
)
// AddPrincipalRoles provides the ability to add principals (userIds and
// groupIds) to a role (roleId). The role's current db version must match the
// roleVersion or an error will be returned. The list of current PrincipalRoles
// after the adds will be returned on success. Zero is not a valid value for
// the WithVersion option and will return an error.
func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, _ ...Option) ([]*PrincipalRole, error) {
const op = "iam.(Repository).AddPrincipalRoles"
if roleId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing role id")
}
if roleVersion == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
userIds, groupIds, managedGroupIds, err := splitPrincipals(ctx, principalIds)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if len(userIds) == 0 && len(groupIds) == 0 && len(managedGroupIds) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing any of users, groups, or managed groups to add")
}
newUserRoles := make([]any, 0, len(userIds))
for _, id := range userIds {
usrRole, err := NewUserRole(roleId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory user role"))
}
newUserRoles = append(newUserRoles, usrRole)
}
newGrpRoles := make([]any, 0, len(groupIds))
for _, id := range groupIds {
grpRole, err := NewGroupRole(roleId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory group role"))
}
newGrpRoles = append(newGrpRoles, grpRole)
}
newManagedGrpRoles := make([]any, 0, len(managedGroupIds))
for _, id := range managedGroupIds {
managedGrpRole, err := NewManagedGroupRole(roleId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory managed group role"))
}
newManagedGrpRoles = append(newManagedGrpRoles, managedGrpRole)
}
role := allocRole()
role.PublicId = roleId
scope, err := role.GetScope(ctx, r.reader)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to get role %s scope", roleId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, scope.GetPublicId(), kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentPrincipals []*PrincipalRole
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
roleTicket, err := w.GetTicket(ctx, &role)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
updatedRole := allocRole()
updatedRole.PublicId = roleId
updatedRole.Version = roleVersion + 1
var roleOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedRole, []string{"Version"}, nil, db.NewOplogMsg(&roleOplogMsg), db.WithVersion(&roleVersion))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to update role version"))
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated role and %d rows updated", rowsUpdated))
}
msgs = append(msgs, &roleOplogMsg)
if len(newUserRoles) > 0 {
userOplogMsgs := make([]*oplog.Message, 0, len(newUserRoles))
if err := w.CreateItems(ctx, newUserRoles, db.NewOplogMsgs(&userOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add users"))
}
msgs = append(msgs, userOplogMsgs...)
}
if len(newGrpRoles) > 0 {
grpOplogMsgs := make([]*oplog.Message, 0, len(newGrpRoles))
if err := w.CreateItems(ctx, newGrpRoles, db.NewOplogMsgs(&grpOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add groups"))
}
msgs = append(msgs, grpOplogMsgs...)
}
if len(newManagedGrpRoles) > 0 {
managedGrpOplogMsgs := make([]*oplog.Message, 0, len(newManagedGrpRoles))
if err := w.CreateItems(ctx, newManagedGrpRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add managed groups"))
}
msgs = append(msgs, managedGrpOplogMsgs...)
}
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_CREATE.String()},
"scope-id": []string{scope.PublicId},
"scope-type": []string{scope.Type},
"resource-public-id": []string{roleId},
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, roleTicket, metadata, msgs); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog"))
}
// we need a new repo, that's using the same reader/writer as this TxHandler
txRepo := &Repository{
reader: reader,
writer: w,
kms: r.kms,
// intentionally not setting the defaultLimit, so we'll get all
// the principal roles without a limit
}
currentPrincipals, err = txRepo.ListPrincipalRoles(ctx, roleId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current principal roles after adds"))
}
return nil
},
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return currentPrincipals, nil
}
// SetPrincipalRoles will set the role's principals. Set add and/or delete
// principals as need to reconcile the existing principals with the principals
// requested. If both userIds and groupIds are empty, the principal roles will
// be cleared. Zero is not a valid value for the WithVersion option and will
// return an error.
func (r *Repository) SetPrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, _ ...Option) ([]*PrincipalRole, int, error) {
const op = "iam.(Repository).SetPrincipalRoles"
if roleId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing role id")
}
if roleVersion == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
role := allocRole()
role.PublicId = roleId
// it's "safe" to do this lookup outside the DoTx transaction because we
// have a roleVersion so the principals can’t change without the version
// changing.
userIds, groupIds, managedGroupIds, err := splitPrincipals(ctx, principalIds)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
toSet, err := r.PrincipalsToSet(ctx, &role, userIds, groupIds, managedGroupIds)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
// handle no change to existing principal roles
if len(toSet.UnchangedPrincipalRoles) > 0 {
return toSet.UnchangedPrincipalRoles, db.NoRowsAffected, nil
}
scope, err := role.GetScope(ctx, r.reader)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to get role %s scope", roleId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, scope.GetPublicId(), kms.KeyPurposeOplog)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentPrincipals []*PrincipalRole
var totalRowsAffected int
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
// we need a roleTicket, which won't be redeemed until all the other
// writes are successful. We can't just use a single ticket because
// we need to write oplog entries for deletes and adds
roleTicket, err := w.GetTicket(ctx, &role)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket for role"))
}
updatedRole := allocRole()
updatedRole.PublicId = roleId
updatedRole.Version = roleVersion + 1
var roleOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedRole, []string{"Version"}, nil, db.NewOplogMsg(&roleOplogMsg), db.WithVersion(&roleVersion))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated role and %d rows updated", rowsUpdated))
}
msgs := make([]*oplog.Message, 0, 5)
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
"scope-id": []string{scope.PublicId},
"scope-type": []string{scope.Type},
"resource-public-id": []string{roleId},
}
msgs = append(msgs, &roleOplogMsg)
if len(toSet.DeleteUserRoles) > 0 ||
len(toSet.DeleteGroupRoles) > 0 ||
len(toSet.DeleteManagedGroupRoles) > 0 {
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_DELETE.String())
if len(toSet.DeleteUserRoles) > 0 {
userOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteUserRoles))
rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteUserRoles, db.NewOplogMsgs(&userOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete user roles"))
}
if rowsDeleted != len(toSet.DeleteUserRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("user roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteUserRoles)))
}
totalRowsAffected += rowsDeleted
msgs = append(msgs, userOplogMsgs...)
}
if len(toSet.DeleteGroupRoles) > 0 {
grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteGroupRoles))
rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteGroupRoles, db.NewOplogMsgs(&grpOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete groups"))
}
if rowsDeleted != len(toSet.DeleteGroupRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("group roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteGroupRoles)))
}
totalRowsAffected += rowsDeleted
msgs = append(msgs, grpOplogMsgs...)
}
if len(toSet.DeleteManagedGroupRoles) > 0 {
managedGrpOplogMsgs := make([]*oplog.Message, 0, len(toSet.DeleteManagedGroupRoles))
rowsDeleted, err := w.DeleteItems(ctx, toSet.DeleteManagedGroupRoles, db.NewOplogMsgs(&managedGrpOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete managed groups"))
}
if rowsDeleted != len(toSet.DeleteManagedGroupRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("managed group roles deleted %d did not match request for %d", rowsDeleted, len(toSet.DeleteManagedGroupRoles)))
}
totalRowsAffected += rowsDeleted
msgs = append(msgs, managedGrpOplogMsgs...)
}
}
if len(toSet.AddUserRoles) > 0 ||
len(toSet.AddGroupRoles) > 0 ||
len(toSet.AddManagedGroupRoles) > 0 {
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String())
if len(toSet.AddUserRoles) > 0 {
userOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddUserRoles))
if err := w.CreateItems(ctx, toSet.AddUserRoles, db.NewOplogMsgs(&userOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add users"))
}
totalRowsAffected += len(toSet.AddUserRoles)
msgs = append(msgs, userOplogMsgs...)
}
if len(toSet.AddGroupRoles) > 0 {
grpOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddGroupRoles))
if err := w.CreateItems(ctx, toSet.AddGroupRoles, db.NewOplogMsgs(&grpOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add groups"))
}
totalRowsAffected += len(toSet.AddGroupRoles)
msgs = append(msgs, grpOplogMsgs...)
}
if len(toSet.AddManagedGroupRoles) > 0 {
managedGrpOplogMsgs := make([]*oplog.Message, 0, len(toSet.AddManagedGroupRoles))
if err := w.CreateItems(ctx, toSet.AddManagedGroupRoles, db.NewOplogMsgs(&managedGrpOplogMsgs)); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add managed groups"))
}
totalRowsAffected += len(toSet.AddManagedGroupRoles)
msgs = append(msgs, managedGrpOplogMsgs...)
}
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, roleTicket, metadata, msgs); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog"))
}
// we need a new repo, that's using the same reader/writer as this TxHandler
txRepo := &Repository{
reader: reader,
writer: w,
kms: r.kms,
// intentionally not setting the defaultLimit, so we'll get all
// the principal roles without a limit
}
currentPrincipals, err = txRepo.ListPrincipalRoles(ctx, roleId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current principal roles after sets"))
}
return nil
})
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
return currentPrincipals, totalRowsAffected, nil
}
// DeletePrincipalRoles principals (userIds and/or groupIds) from a role
// (roleId). The role's current db version must match the roleVersion or an
// error will be returned. Zero is not a valid value for the WithVersion option
// and will return an error.
func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, roleVersion uint32, principalIds []string, _ ...Option) (int, error) {
const op = "iam.(Repository).DeletePrincipalRoles"
if roleId == "" {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing role id")
}
userIds, groupIds, managedGroupIds, err := splitPrincipals(ctx, principalIds)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
if len(userIds) == 0 && len(groupIds) == 0 && len(managedGroupIds) == 0 {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing any of users, groups, or managed groups to delete")
}
if roleVersion == 0 {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
role := allocRole()
role.PublicId = roleId
deleteUserRoles := make([]any, 0, len(userIds))
for _, id := range userIds {
usrRole, err := NewUserRole(roleId, id)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory user role"))
}
deleteUserRoles = append(deleteUserRoles, usrRole)
}
deleteGrpRoles := make([]any, 0, len(groupIds))
for _, id := range groupIds {
grpRole, err := NewGroupRole(roleId, id)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory group role"))
}
deleteGrpRoles = append(deleteGrpRoles, grpRole)
}
deleteManagedGrpRoles := make([]any, 0, len(managedGroupIds))
for _, id := range managedGroupIds {
managedGrpRole, err := NewManagedGroupRole(roleId, id)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory managed group role"))
}
deleteManagedGrpRoles = append(deleteManagedGrpRoles, managedGrpRole)
}
scope, err := role.GetScope(ctx, r.reader)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to get role %s scope to create metadata", roleId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, scope.GetPublicId(), kms.KeyPurposeOplog)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var totalRowsDeleted int
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
roleTicket, err := w.GetTicket(ctx, &role)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
updatedRole := allocRole()
updatedRole.PublicId = roleId
updatedRole.Version = roleVersion + 1
var roleOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedRole, []string{"Version"}, nil, db.NewOplogMsg(&roleOplogMsg), db.WithVersion(&roleVersion))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to update role version"))
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated role and %d rows updated", rowsUpdated))
}
msgs = append(msgs, &roleOplogMsg)
if len(deleteUserRoles) > 0 {
userOplogMsgs := make([]*oplog.Message, 0, len(deleteUserRoles))
rowsDeleted, err := w.DeleteItems(ctx, deleteUserRoles, db.NewOplogMsgs(&userOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete user roles"))
}
if rowsDeleted != len(deleteUserRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("user roles deleted %d did not match request for %d", rowsDeleted, len(deleteUserRoles)))
}
totalRowsDeleted += rowsDeleted
msgs = append(msgs, userOplogMsgs...)
}
if len(deleteGrpRoles) > 0 {
grpOplogMsgs := make([]*oplog.Message, 0, len(deleteGrpRoles))
rowsDeleted, err := w.DeleteItems(ctx, deleteGrpRoles, db.NewOplogMsgs(&grpOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete groups"))
}
if rowsDeleted != len(deleteGrpRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("group roles deleted %d did not match request for %d", rowsDeleted, len(deleteGrpRoles)))
}
totalRowsDeleted += rowsDeleted
msgs = append(msgs, grpOplogMsgs...)
}
if len(deleteManagedGrpRoles) > 0 {
managedGrpOplogMsgs := make([]*oplog.Message, 0, len(deleteManagedGrpRoles))
rowsDeleted, err := w.DeleteItems(ctx, deleteManagedGrpRoles, db.NewOplogMsgs(&managedGrpOplogMsgs))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete managed groups"))
}
if rowsDeleted != len(deleteManagedGrpRoles) {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("managed group roles deleted %d did not match request for %d", rowsDeleted, len(deleteManagedGrpRoles)))
}
totalRowsDeleted += rowsDeleted
msgs = append(msgs, managedGrpOplogMsgs...)
}
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_DELETE.String()},
"scope-id": []string{scope.PublicId},
"scope-type": []string{scope.Type},
"resource-public-id": []string{roleId},
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, roleTicket, metadata, msgs); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to write oplog"))
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
return totalRowsDeleted, nil
}
// ListPrincipalRoles returns the principal roles for the roleId and supports the WithLimit option.
func (r *Repository) ListPrincipalRoles(ctx context.Context, roleId string, opt ...Option) ([]*PrincipalRole, error) {
const op = "iam.(Repository).ListPrincipalRoles"
if roleId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing role id")
}
var roles []*PrincipalRole
if err := r.list(ctx, &roles, "role_id = ?", []any{roleId}, opt...); err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to lookup roles"))
}
principals := make([]*PrincipalRole, 0, len(roles))
principals = append(principals, roles...)
return principals, nil
}
type PrincipalSet struct {
AddUserRoles []any
AddGroupRoles []any
AddManagedGroupRoles []any
DeleteUserRoles []any
DeleteGroupRoles []any
DeleteManagedGroupRoles []any
// unchangedPrincipalRoles is set iff there are no changes, that is, the
// length of all other members is zero
UnchangedPrincipalRoles []*PrincipalRole
}
// TODO: Should this be moved inside the transaction, at this point?
// PrincipalsToSet sets principals on a role from the given lists.
func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, groupIds, managedGroupIds []string) (*PrincipalSet, error) {
const op = "iam.(Repository).PrincipalsToSet"
// TODO(mgaffney) 08/2020: Use SQL to calculate changes.
if role == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing role")
}
existing, err := r.ListPrincipalRoles(ctx, role.PublicId)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to list existing principal role %s", role.PublicId)))
}
existingUsers := map[string]*PrincipalRole{}
existingGroups := map[string]*PrincipalRole{}
existingManagedGroups := map[string]*PrincipalRole{}
for _, p := range existing {
switch p.GetType() {
case UserRoleType.String():
existingUsers[p.PrincipalId] = p
case GroupRoleType.String():
existingGroups[p.PrincipalId] = p
case ManagedGroupRoleType.String():
existingManagedGroups[p.PrincipalId] = p
default:
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is unknown principal type %s", p.PrincipalId, p.GetType()))
}
}
var newUserRoles []any
userIdsMap := map[string]struct{}{}
for _, id := range userIds {
userIdsMap[id] = struct{}{}
if _, ok := existingUsers[id]; !ok {
usrRole, err := NewUserRole(role.PublicId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory user role for add"))
}
newUserRoles = append(newUserRoles, usrRole)
}
}
var newGrpRoles []any
groupIdsMap := map[string]struct{}{}
for _, id := range groupIds {
groupIdsMap[id] = struct{}{}
if _, ok := existingGroups[id]; !ok {
grpRole, err := NewGroupRole(role.PublicId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory group role for add"))
}
newGrpRoles = append(newGrpRoles, grpRole)
}
}
var newManagedGrpRoles []any
managedGroupIdsMap := map[string]struct{}{}
for _, id := range managedGroupIds {
managedGroupIdsMap[id] = struct{}{}
if _, ok := existingManagedGroups[id]; !ok {
managedGrpRole, err := NewManagedGroupRole(role.PublicId, id)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory managed group role for add"))
}
newManagedGrpRoles = append(newManagedGrpRoles, managedGrpRole)
}
}
var deleteUserRoles []any
for _, p := range existingUsers {
if _, ok := userIdsMap[p.PrincipalId]; !ok {
usrRole, err := NewUserRole(p.GetRoleId(), p.GetPrincipalId())
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory user role for delete"))
}
deleteUserRoles = append(deleteUserRoles, usrRole)
}
}
var deleteGrpRoles []any
for _, p := range existingGroups {
if _, ok := groupIdsMap[p.PrincipalId]; !ok {
grpRole, err := NewGroupRole(p.GetRoleId(), p.GetPrincipalId())
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory group role for delete"))
}
deleteGrpRoles = append(deleteGrpRoles, grpRole)
}
}
var deleteManagedGrpRoles []any
for _, p := range existingManagedGroups {
if _, ok := managedGroupIdsMap[p.PrincipalId]; !ok {
managedGrpRole, err := NewManagedGroupRole(p.GetRoleId(), p.GetPrincipalId())
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory managed group role for delete"))
}
deleteManagedGrpRoles = append(deleteManagedGrpRoles, managedGrpRole)
}
}
toSet := &PrincipalSet{
AddUserRoles: newUserRoles,
AddGroupRoles: newGrpRoles,
AddManagedGroupRoles: newManagedGrpRoles,
DeleteUserRoles: deleteUserRoles,
DeleteGroupRoles: deleteGrpRoles,
DeleteManagedGroupRoles: deleteManagedGrpRoles,
}
if len(toSet.AddUserRoles) == 0 &&
len(toSet.AddGroupRoles) == 0 &&
len(toSet.AddManagedGroupRoles) == 0 &&
len(toSet.DeleteUserRoles) == 0 &&
len(toSet.DeleteGroupRoles) == 0 &&
len(toSet.DeleteManagedGroupRoles) == 0 {
toSet.UnchangedPrincipalRoles = existing
}
return toSet, nil
}
func splitPrincipals(ctx context.Context, principals []string) (users, groups, managedGroups []string, retErr error) {
const op = "iam.splitPrincipals"
for _, principal := range principals {
switch {
case strings.HasPrefix(principal, UserPrefix):
if users == nil {
users = make([]string, 0, len(principals))
}
users = append(users, principal)
case strings.HasPrefix(principal, GroupPrefix):
if groups == nil {
groups = make([]string, 0, len(principals))
}
groups = append(groups, principal)
case strings.HasPrefix(principal, intglobals.OidcManagedGroupPrefix):
if managedGroups == nil {
managedGroups = make([]string, 0, len(principals))
}
managedGroups = append(managedGroups, principal)
default:
return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("invalid principal ID %q", principal))
}
}
return
}