-
Notifications
You must be signed in to change notification settings - Fork 289
/
Copy pathrepository_user.go
901 lines (850 loc) · 33.5 KB
/
repository_user.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
package iam
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/oplog"
"github.com/hashicorp/boundary/internal/types/scope"
"github.com/hashicorp/go-dbw"
)
// CreateUser will create a user in the repository and return the written user
func (r *Repository) CreateUser(ctx context.Context, user *User, opt ...Option) (*User, error) {
const op = "iam.(Repository).CreateUser"
if user == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user")
}
if user.PublicId != "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "public id is not empty")
}
u := user.Clone().(*User)
opts := getOpts(opt...)
if opts.withPublicId != "" {
if !strings.HasPrefix(opts.withPublicId, UserPrefix+"_") {
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("passed-in public ID %q has wrong prefix, should be %q", opts.withPublicId, UserPrefix))
}
u.PublicId = opts.withPublicId
} else {
id, err := newUserId()
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
u.PublicId = id
}
// There's no need to use r.lookupUser(...) here, because the new user cannot
// be associated with any accounts yet. Why would you typically want to
// call r.lookupUser(...) here vs returning the create resource? Well, the
// created resource doesn't include the user's primary account info (email,
// full name, etc), since you can't run DML against the view which does
// provide these output only attributes. But in this case, there's no way a
// newly created user could have any accounts, so we don't need to use
// r.lookupUser(...). I'm adding this comment so a future version of myself
// doesn't come along and decide to start using r.lookupUser(...) here which
// would just be an unnecessary database lookup. You're welcome future me.
resource, err := r.create(ctx, u)
if err != nil {
if errors.IsUniqueError(err) {
return nil, errors.New(ctx, errors.NotUnique, op, fmt.Sprintf("user %s already exists in org %s", user.Name, user.ScopeId))
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("for %s", u.PublicId)))
}
return resource.(*User), nil
}
// UpdateUser will update a user in the repository and return the written user
// plus its associated account ids. fieldMaskPaths provides field_mask.proto
// paths for fields that should be updated. Fields will be set to NULL if the
// field is a zero value and included in fieldMask. Name and Description are the
// only updatable fields, if no updatable fields are included in the
// fieldMaskPaths, then an error is returned.
func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, fieldMaskPaths []string, opt ...Option) (*User, []string, int, error) {
const op = "iam.(Repository).UpdateUser"
if user == nil {
return nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing user")
}
if user.PublicId == "" {
return nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
for _, f := range fieldMaskPaths {
switch {
case strings.EqualFold("name", f):
case strings.EqualFold("description", f):
default:
return nil, nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, fmt.Sprintf("invalid field mask: %s", f))
}
}
var dbMask, nullFields []string
dbMask, nullFields = dbw.BuildUpdatePaths(
map[string]any{
"name": user.Name,
"description": user.Description,
},
fieldMaskPaths,
nil,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, nil, db.NoRowsAffected, errors.E(ctx, errors.WithCode(errors.EmptyFieldMask), errors.WithOp(op))
}
u := user.Clone().(*User)
metadata, err := r.stdMetadata(ctx, u)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
metadata["op-type"] = []string{oplog.OpType_OP_TYPE_UPDATE.String()}
dbOpts := []db.Option{
db.WithVersion(&version),
}
opts := getOpts(opt...)
if opts.withSkipVetForWrite {
dbOpts = append(dbOpts, db.WithSkipVetForWrite(true))
}
scope, err := u.GetScope(ctx, r.reader)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get scope"))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, scope.GetPublicId(), kms.KeyPurposeOplog)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
dbOpts = append(dbOpts, db.WithOplog(oplogWrapper, metadata))
var rowsUpdated int
var returnedUser *User
var currentAccountIds []string
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
returnedUser = u.Clone().(*User)
rowsUpdated, err = w.Update(
ctx,
returnedUser,
dbMask,
nullFields,
dbOpts...,
)
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated > 1 {
// return err, which will result in a rollback of the update
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
txRepo := &Repository{
reader: reader,
writer: w,
kms: r.kms,
// intentionally not setting the defaultLimit
}
returnedUser, err = txRepo.lookupUser(ctx, user.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current user after update"))
}
currentAccountIds, err = txRepo.ListUserAccounts(ctx, user.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids after update"))
}
return nil
},
)
if err != nil {
if errors.IsUniqueError(err) {
return nil, nil, db.NoRowsAffected, errors.New(ctx, errors.NotUnique, op, fmt.Sprintf("user %s already exists in org %s", user.Name, user.ScopeId))
}
return nil, nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("for %s", user.PublicId)))
}
return returnedUser, currentAccountIds, rowsUpdated, nil
}
// LookupUser will look up a user and its associated account ids in the
// repository. If the user is not found, it will return nil, nil, nil.
func (r *Repository) LookupUser(ctx context.Context, userId string, _ ...Option) (*User, []string, error) {
const op = "iam.(Repository).LookupUser"
if userId == "" {
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
user, err := r.lookupUser(ctx, userId)
if err != nil {
return nil, nil, errors.Wrap(ctx, err, op)
}
currentAccountIds, err := r.ListUserAccounts(ctx, userId)
if err != nil {
return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids"))
}
return user, currentAccountIds, nil
}
// DeleteUser will delete a user from the repository
func (r *Repository) DeleteUser(ctx context.Context, withPublicId string, _ ...Option) (int, error) {
const op = "iam.(Repository).DeleteUser"
if withPublicId == "" {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
user := AllocUser()
user.PublicId = withPublicId
if err := r.reader.LookupByPublicId(ctx, &user); err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("for %s", withPublicId)))
}
rowsDeleted, err := r.delete(ctx, &user)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("for %s", withPublicId)))
}
return rowsDeleted, nil
}
// ListUsers lists users in the given scopes and supports the WithLimit option.
func (r *Repository) ListUsers(ctx context.Context, withScopeIds []string, opt ...Option) ([]*User, error) {
const op = "iam.(Repository).ListUsers"
if len(withScopeIds) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing scope id")
}
users, err := r.getUsers(ctx, "", withScopeIds, opt...)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return users, nil
}
// LookupUserWithLogin will attempt to lookup the user with a matching
// account id and return the user if found. If a user is not found and the
// account's scope is not the PrimaryAuthMethod, then an error is returned.
// If the account's scope is the PrimaryAuthMethod, then a new iam User will be
// created (autovivified) in the scope of the account, and associated with the
// account. If a new user is auto vivified, then the WithName and
// WithDescription options are supported as well.
func (r *Repository) LookupUserWithLogin(ctx context.Context, accountId string, opt ...Option) (*User, error) {
const op = "iam.(Repository).LookupUserWithLogin"
if accountId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing account id")
}
u, err := r.getUserWithAccount(ctx, accountId)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if u != nil {
return u, nil
}
acct := allocAccount()
acct.PublicId = accountId
err = r.reader.LookupByPublicId(context.Background(), &acct)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup account %s", accountId)))
}
allowed, err := r.allowUserAutoVivify(ctx, &acct)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if !allowed {
return nil, errors.New(ctx, errors.RecordNotFound, op, fmt.Sprintf("user not found for account %s and auth method is not primary for the scope so refusing to auto-create user", accountId))
}
metadata := oplog.Metadata{
"resource-public-id": []string{accountId},
"scope-id": []string{acct.ScopeId},
"scope-type": []string{scope.Org.String()},
"resource-type": []string{"auth-account"},
}
oplogWrapper, err := r.kms.GetWrapper(ctx, acct.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
// We will create a new user and associate the user with the account
// within one retryable transaction using writer.DoTx
var obtainedUser *User
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
ticket, err := w.GetTicket(ctx, &acct)
if err != nil {
return errors.Wrap(ctx, err, op)
}
obtainedUser, err = NewUser(acct.ScopeId, opt...)
if err != nil {
return errors.Wrap(ctx, err, op)
}
id, err := newUserId()
if err != nil {
return errors.Wrap(ctx, err, op)
}
var createMsg oplog.Message
obtainedUser.PublicId = id
err = w.Create(ctx, obtainedUser, db.NewOplogMsg(&createMsg))
if err != nil {
return errors.Wrap(ctx, err, op)
}
msgs = append(msgs, &createMsg)
var updateMsg oplog.Message
updateAcct := acct.Clone().(*authAccount)
updateAcct.IamUserId = id
updatedRows, err := w.Update(ctx, updateAcct, []string{"IamUserId"}, nil, db.NewOplogMsg(&updateMsg))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if updatedRows != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("account update affected %d rows", updatedRows))
}
msgs = append(msgs, &updateMsg)
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, ticket, metadata, msgs); err != nil {
return errors.Wrap(ctx, err, op)
}
txRepo := &Repository{
reader: reader,
writer: w,
kms: r.kms,
// intentionally not setting the defaultLimit
}
obtainedUser, err = txRepo.lookupUser(ctx, obtainedUser.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve user"))
}
return nil
},
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return obtainedUser, nil
}
// allowUserAutoVivify determines if a user can be autovivified based on the account's scope
func (r *Repository) allowUserAutoVivify(ctx context.Context, acct *authAccount) (bool, error) {
const op = "iam.(Repository).allowUserAutoVivify"
if acct == nil {
return false, errors.New(ctx, errors.InvalidParameter, op, "missing account")
}
acctScope := AllocScope()
acctScope.PublicId = acct.ScopeId
err := r.reader.LookupByPublicId(context.Background(), &acctScope)
if err != nil {
return false, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup account's scope %s", acct.ScopeId)))
}
return acct.AuthMethodId == acctScope.PrimaryAuthMethodId, nil
}
func (r *Repository) getUserWithAccount(ctx context.Context, withAccountId string, _ ...Option) (*User, error) {
const op = "iam.(Repository).getUserWithAccount"
if withAccountId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing account id")
}
rows, err := r.reader.Query(ctx, whereUserAccount, []any{withAccountId})
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to query account %s", withAccountId)))
}
defer rows.Close()
u := AllocUser()
if rows.Next() {
err = r.reader.ScanRows(ctx, rows, &u)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to scan rows for account %s", withAccountId)))
}
} else {
if err := rows.Err(); err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get next account"))
}
return nil, nil
}
return &u, nil
}
// ListUserAccounts returns the account ids for the userId and supports the
// WithLimit option. Returns nil, nil when no associated accounts are found.
func (r *Repository) ListUserAccounts(ctx context.Context, userId string, opt ...Option) ([]string, error) {
const op = "iam.(Repository).ListUserAccounts"
if userId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id")
}
var accounts []*authAccount
if err := r.list(ctx, &accounts, "iam_user_id = ?", []any{userId}, opt...); err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if len(accounts) == 0 {
return nil, nil
}
ids := make([]string, 0, len(accounts))
for _, aa := range accounts {
ids = append(ids, aa.PublicId)
}
return ids, nil
}
// AddUserAccounts will associate a user with existing accounts and
// return a list of all associated account ids for the user. The accounts must
// not already be associated with different users. No options are currently
// supported.
func (r *Repository) AddUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, _ ...Option) ([]string, error) {
const op = "iam.(Repository).AddUserAccounts"
if userId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id")
}
if userVersion == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user version")
}
if len(accountIds) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing account ids")
}
user, err := r.lookupUser(ctx, userId)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup user %s", userId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, user.ScopeId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentAccountIds []string
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
userTicket, err := w.GetTicket(ctx, user)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
updatedUser := AllocUser()
updatedUser.PublicId = userId
updatedUser.Version = userVersion + 1
var userOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedUser, []string{"Version"}, nil, db.NewOplogMsg(&userOplogMsg), db.WithVersion(&userVersion))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get user version"))
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated user and %d rows updated", rowsUpdated))
}
if err := associateUserWithAccounts(ctx, r.kms, reader, w, user.PublicId, accountIds); err != nil {
return errors.Wrap(ctx, err, op)
}
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
"scope-id": []string{user.ScopeId},
"scope-type": []string{scope.Org.String()},
"resource-public-id": []string{user.PublicId},
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, userTicket, metadata, []*oplog.Message{&userOplogMsg}); 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 account ids without a limit
}
currentAccountIds, err = txRepo.ListUserAccounts(ctx, user.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids after adds"))
}
return nil
},
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return currentAccountIds, nil
}
// DeleteUserAccounts will disassociate a user from existing accounts and
// return a list of all associated account ids for the user. The accounts must
// not be associated with different users. No options are currently
// supported.
func (r *Repository) DeleteUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, _ ...Option) ([]string, error) {
const op = "iam.(Repository).DeleteUserAccounts"
if userId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
if userVersion == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user version")
}
if len(accountIds) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing account ids")
}
user, err := r.lookupUser(ctx, userId)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup user %s", userId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, user.ScopeId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentAccountIds []string
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
userTicket, err := w.GetTicket(ctx, user)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
updatedUser := AllocUser()
updatedUser.PublicId = userId
updatedUser.Version = userVersion + 1
var userOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedUser, []string{"Version"}, nil, db.NewOplogMsg(&userOplogMsg), db.WithVersion(&userVersion))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to update user version"))
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated user and %d rows updated", rowsUpdated))
}
if err := dissociateUserFromAccounts(ctx, r.kms, reader, w, user.PublicId, accountIds); err != nil {
return errors.Wrap(ctx, err, op)
}
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
"scope-id": []string{user.ScopeId},
"scope-type": []string{scope.Org.String()},
"resource-public-id": []string{user.PublicId},
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, userTicket, metadata, []*oplog.Message{&userOplogMsg}); 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 account ids without a limit
}
currentAccountIds, err = txRepo.ListUserAccounts(ctx, user.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids after adds"))
}
return nil
},
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return currentAccountIds, nil
}
// SetUserAccounts will associate a user with existing accounts and
// return a list of all associated account ids for the user. The accounts must
// not already be associated with different users. No options are currently
// supported.
func (r *Repository) SetUserAccounts(ctx context.Context, userId string, userVersion uint32, accountIds []string, _ ...Option) ([]string, error) {
const op = "iam.(Repository).SetUserAccounts"
if userId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
if userVersion == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
user, err := r.lookupUser(ctx, userId)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup user %s", userId)))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, user.ScopeId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentAccountIds []string
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
associateIds, disassociateIds, err := associationChanges(ctx, reader, userId, accountIds)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to determine changes"))
}
// just in case we've got nothing to do...
if len(associateIds) == 0 && len(disassociateIds) == 0 {
// 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 account ids without a limit
}
currentAccountIds, err = txRepo.ListUserAccounts(ctx, userId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids after set"))
}
return nil
}
userTicket, err := w.GetTicket(ctx, user)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket"))
}
updatedUser := AllocUser()
updatedUser.PublicId = userId
updatedUser.Version = userVersion + 1
var userOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, &updatedUser, []string{"Version"}, nil, db.NewOplogMsg(&userOplogMsg), db.WithVersion(&userVersion))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to update user version"))
}
if rowsUpdated != 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated user and %d rows updated", rowsUpdated))
}
if len(associateIds) > 0 {
if err := associateUserWithAccounts(ctx, r.kms, reader, w, userId, associateIds); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to associate ids"))
}
}
if len(disassociateIds) > 0 {
if err := dissociateUserFromAccounts(ctx, r.kms, reader, w, userId, disassociateIds); err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to disassociate ids"))
}
}
metadata := oplog.Metadata{
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
"scope-id": []string{user.ScopeId},
"scope-type": []string{scope.Org.String()},
"resource-public-id": []string{userId},
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, userTicket, metadata, []*oplog.Message{&userOplogMsg}); 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 account ids without a limit
}
currentAccountIds, err = txRepo.ListUserAccounts(ctx, user.PublicId)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to retrieve current account ids after set"))
}
return nil
},
)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
return currentAccountIds, nil
}
// associateUserWithAccounts will associate the accounts (accountIds) with
// the user (userId) within the writer's database
func associateUserWithAccounts(ctx context.Context, repoKms *kms.Kms, reader db.Reader, writer db.Writer, userId string, accountIds []string, _ ...Option) error {
const op = "iam.associateUserWithAccounts"
if repoKms == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil kms")
}
if reader == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil reader")
}
if writer == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil writer")
}
if userId == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing user id")
}
if len(accountIds) == 0 {
return errors.New(ctx, errors.InvalidParameter, op, "missing account ids")
}
authAccounts := make([]*authAccount, 0, len(accountIds))
for _, accountId := range accountIds {
acct := allocAccount()
acct.PublicId = accountId
err := reader.LookupByPublicId(ctx, &acct)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup account %s", accountId)))
}
if acct.IamUserId != "" && acct.IamUserId != userId {
return errors.New(ctx, errors.AccountAlreadyAssociated, op, fmt.Sprintf("%s account is already associated with another user", accountId))
}
authAccounts = append(authAccounts, &acct)
}
for _, aa := range authAccounts {
// wrapper could be different for each authAccount depending on it's scope
oplogWrapper, err := repoKms.GetWrapper(ctx, aa.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
metadata := oplog.Metadata{
"resource-public-id": []string{aa.PublicId},
"scope-id": []string{aa.ScopeId},
"resource-type": []string{"auth-account"},
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
}
var updatedRows int
updatedAcct := aa.Clone().(*authAccount)
updatedAcct.IamUserId = userId
updatedRows, err = writer.Update(ctx, updatedAcct, []string{"IamUserId"}, nil, db.WithOplog(oplogWrapper, metadata), db.WithWhere("iam_user_id is NULL or iam_user_id = ?", userId))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed to associate %s account", aa.PublicId)))
}
if updatedRows == 0 {
return errors.New(ctx, errors.AccountAlreadyAssociated, op, fmt.Sprintf("failed to associate %s account: it is already associated with another user", aa.PublicId))
}
if updatedRows > 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("failed to associate %s account: would have updated too many accounts %d", aa.PublicId, updatedRows))
}
}
return nil
}
// dissociateUserFromAccounts will dissociate a user with its existing accounts
// (accountIds). An error is returned if account is associated with a different
// user. No options are currently supported.
func dissociateUserFromAccounts(ctx context.Context, repoKms *kms.Kms, reader db.Reader, writer db.Writer, userId string, accountIds []string, _ ...Option) error {
const op = "iam.dissociateUserFromAccounts"
if repoKms == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil kms")
}
if reader == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil reader")
}
if writer == nil {
return errors.New(ctx, errors.InvalidParameter, op, "nil writer")
}
if userId == "" {
return errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
if len(accountIds) == 0 {
return errors.New(ctx, errors.InvalidParameter, op, "missing account ids")
}
authAccounts := make([]*authAccount, 0, len(accountIds))
for _, accountId := range accountIds {
acct := allocAccount()
acct.PublicId = accountId
err := reader.LookupByPublicId(context.Background(), &acct)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to lookup account %s", accountId)))
}
if acct.IamUserId != userId {
return errors.New(ctx, errors.AccountAlreadyAssociated, op, fmt.Sprintf("%s account is not associated with user %s", accountId, userId))
}
authAccounts = append(authAccounts, &acct)
}
for _, aa := range authAccounts {
// wrapper could be different for each authAccount depending on it's scope
oplogWrapper, err := repoKms.GetWrapper(ctx, aa.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
metadata := oplog.Metadata{
"resource-public-id": []string{aa.PublicId},
"scope-id": []string{aa.ScopeId},
"resource-type": []string{"auth-account"},
"op-type": []string{oplog.OpType_OP_TYPE_UPDATE.String()},
}
var updatedRows int
updatedAcct := aa.Clone().(*authAccount)
updatedAcct.IamUserId = userId
// update IamUserId to null
updatedRows, err = writer.Update(ctx, updatedAcct, nil, []string{"IamUserId"}, db.WithOplog(oplogWrapper, metadata), db.WithWhere("iam_user_id is NULL or iam_user_id = ?", userId))
if err != nil {
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed to disassociate %s account", aa.PublicId)))
}
if updatedRows == 0 {
return errors.New(ctx, errors.AccountAlreadyAssociated, op, fmt.Sprintf("failed to disassociate %s account: it is already associated with another user", aa.PublicId))
}
if updatedRows > 1 {
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("failed to disassociate %s account: would have updated too many accounts %d", aa.PublicId, updatedRows))
}
}
return nil
}
// associationChanges returns two slices: accounts to associate and disassociate
func associationChanges(ctx context.Context, reader db.Reader, userId string, accountIds []string) ([]string, []string, error) {
const op = "iam.associationChanges"
var inClauseSpots []string
// starts at 2 because there is already a ? in the query
for i := 2; i < len(accountIds)+2; i++ {
// inClauseSpots = append(inClauseSpots, fmt.Sprintf("$%d", i))
inClauseSpots = append(inClauseSpots, "?")
}
inClause := strings.Join(inClauseSpots, ",")
if inClause == "" {
inClause = "''"
}
query := fmt.Sprintf(accountChangesQuery, inClause)
var params []any
for _, v := range accountIds {
params = append(params, v)
}
params = append(params, userId)
rows, err := reader.Query(ctx, query, params)
if err != nil {
return nil, nil, errors.Wrap(ctx, err, op)
}
defer rows.Close()
type change struct {
Action string
AccountId string
}
var changes []*change
for rows.Next() {
var chg change
if err := reader.ScanRows(ctx, rows, &chg); err != nil {
return nil, nil, errors.Wrap(ctx, err, op)
}
changes = append(changes, &chg)
}
var associateIds, disassociateIds []string
for _, c := range changes {
if c.AccountId == "" {
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing account id in change result")
}
switch c.Action {
case "associate":
associateIds = append(associateIds, c.AccountId)
case "disassociate":
disassociateIds = append(disassociateIds, c.AccountId)
default:
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unknown action %s for %s", c.Action, c.AccountId))
}
}
return associateIds, disassociateIds, nil
}
// lookupUser will lookup a single user and returns nil, nil when no user is found.
func (r *Repository) lookupUser(ctx context.Context, userId string, opt ...Option) (*User, error) {
const op = "iam.(Repository).lookupUser"
users, err := r.getUsers(ctx, userId, nil, opt...)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
switch {
case len(users) == 0:
return nil, nil // not an error to return no rows for a lookup
case len(users) > 1:
return nil, errors.New(ctx, errors.NotSpecificIntegrity, op, fmt.Sprintf("%s matched more than 1 ", userId))
default:
return users[0], nil
}
}
// getUsers allows the caller to specify to either lookup a specific User via
// its ID or search for a set of Users within a set of scopes. Passing both
// scopeIds and a userId is an error. The WithLimit option is supported and all
// other options are ignored.
//
// When no record is found then it returns nil, nil
func (r *Repository) getUsers(ctx context.Context, userId string, scopeIds []string, opt ...Option) ([]*User, error) {
const op = "iam.(Repository).getUsers"
if userId == "" && len(scopeIds) == 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing search criteria: both user id and scope ids are empty")
}
if userId != "" && len(scopeIds) > 0 {
return nil, errors.New(ctx, errors.InvalidParameter, op, "searching for both a specific user id and scope ids is not supported")
}
opts := getOpts(opt...)
dbArgs := []db.Option{}
limit := r.defaultLimit
if opts.withLimit != 0 {
// non-zero signals an override of the default limit for the repo.
limit = opts.withLimit
}
dbArgs = append(dbArgs, db.WithLimit(limit))
var args []any
var where []string
switch {
case userId != "":
where, args = append(where, "public_id = ?"), append(args, userId)
default:
where, args = append(where, "scope_id in(?)"), append(args, scopeIds)
}
var usersAcctInfo []*userAccountInfo
err := r.reader.SearchWhere(ctx, &usersAcctInfo, strings.Join(where, " and "), args, dbArgs...)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
if len(usersAcctInfo) == 0 { // we're done if nothing is found.
return nil, nil
}
users := make([]*User, 0, len(usersAcctInfo))
for _, u := range usersAcctInfo {
users = append(users, u.shallowConversion())
}
return users, nil
}