-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyncer.go
More file actions
1562 lines (1317 loc) · 41.2 KB
/
Copy pathsyncer.go
File metadata and controls
1562 lines (1317 loc) · 41.2 KB
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sync
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"io"
"math"
"os"
"strconv"
"time"
"github.com/conductorone/baton-sdk/pkg/sync/expand"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
c1zpb "github.com/conductorone/baton-sdk/pb/c1/c1z/v1"
v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2"
reader_v2 "github.com/conductorone/baton-sdk/pb/c1/reader/v2"
"github.com/conductorone/baton-sdk/pkg/annotations"
"github.com/conductorone/baton-sdk/pkg/connectorstore"
"github.com/conductorone/baton-sdk/pkg/dotc1z/manager"
"github.com/conductorone/baton-sdk/pkg/types"
)
const maxDepth = 8
var dontFixCycles, _ = strconv.ParseBool(os.Getenv("BATON_DONT_FIX_CYCLES"))
var (
ErrSyncNotComplete = fmt.Errorf("sync exited without finishing")
)
type Syncer interface {
Sync(context.Context) error
Close(context.Context) error
}
// syncer orchestrates a connector sync and stores the results using the provided datasource.Writer.
type syncer struct {
c1zManager manager.Manager
c1zPath string
store connectorstore.Writer
connector types.ConnectorClient
state State
runDuration time.Duration
transitionHandler func(s Action)
progressHandler func(p *Progress)
tmpDir string
skipFullSync bool
skipEGForResourceType map[string]bool
}
// Checkpoint marshals the current state and stores it.
func (s *syncer) Checkpoint(ctx context.Context) error {
checkpoint, err := s.state.Marshal()
if err != nil {
return err
}
err = s.store.CheckpointSync(ctx, checkpoint)
if err != nil {
return err
}
return nil
}
func (s *syncer) handleInitialActionForStep(ctx context.Context, a Action) {
if s.transitionHandler != nil {
s.transitionHandler(a)
}
}
func (s *syncer) handleProgress(ctx context.Context, a *Action, c int) {
if s.progressHandler != nil {
//nolint:gosec // No risk of overflow because `c` is a slice length.
count := uint32(c)
s.progressHandler(NewProgress(a, count))
}
}
var attempts = 0
func shouldWaitAndRetry(ctx context.Context, err error) bool {
if err == nil {
attempts = 0
return true
}
if status.Code(err) != codes.Unavailable && status.Code(err) != codes.DeadlineExceeded {
return false
}
attempts++
l := ctxzap.Extract(ctx)
// use linear time by default
var wait time.Duration = time.Duration(attempts) * time.Second
// If error contains rate limit data, use that instead
if st, ok := status.FromError(err); ok {
details := st.Details()
for _, detail := range details {
if rlData, ok := detail.(*v2.RateLimitDescription); ok {
waitResetAt := time.Until(rlData.ResetAt.AsTime())
if waitResetAt <= 0 {
continue
}
duration := time.Duration(rlData.Limit)
if duration <= 0 {
continue
}
waitResetAt /= duration
// Round up to the nearest second to make sure we don't hit the rate limit again
waitResetAt = time.Duration(math.Ceil(waitResetAt.Seconds())) * time.Second
if waitResetAt > 0 {
wait = waitResetAt
break
}
}
}
}
l.Warn("retrying operation", zap.Error(err), zap.Duration("wait", wait))
for {
select {
case <-time.After(wait):
return true
case <-ctx.Done():
return false
}
}
}
// Sync starts the syncing process. The sync process is driven by the action stack that is part of the state object.
// For each page of data that is required to be fetched from the connector, a new action is pushed on to the stack. Once
// an action is completed, it is popped off of the queue. Before processing each action, we checkpoint the state object
// into the datasource. This allows for graceful resumes if a sync is interrupted.
func (s *syncer) Sync(ctx context.Context) error {
if s.skipFullSync {
return s.SkipSync(ctx)
}
l := ctxzap.Extract(ctx)
runCtx := ctx
var runCanc context.CancelFunc
if s.runDuration > 0 {
runCtx, runCanc = context.WithTimeout(ctx, s.runDuration)
}
if runCanc != nil {
defer runCanc()
}
err := s.loadStore(ctx)
if err != nil {
return err
}
_, err = s.connector.Validate(ctx, &v2.ConnectorServiceValidateRequest{})
if err != nil {
return err
}
syncID, newSync, err := s.store.StartSync(ctx)
if err != nil {
return err
}
if newSync {
l.Debug("beginning new sync", zap.String("sync_id", syncID))
} else {
l.Debug("resuming previous sync", zap.String("sync_id", syncID))
}
currentStep, err := s.store.CurrentSyncStep(ctx)
if err != nil {
return err
}
state := &state{}
err = state.Unmarshal(currentStep)
if err != nil {
return err
}
s.state = state
for s.state.Current() != nil {
err = s.Checkpoint(ctx)
if err != nil {
return err
}
select {
case <-runCtx.Done():
err = context.Cause(runCtx)
switch {
case errors.Is(err, context.DeadlineExceeded):
l.Debug("sync run duration has expired, exiting sync early", zap.String("sync_id", syncID))
return ErrSyncNotComplete
default:
l.Error("sync context cancelled", zap.String("sync_id", syncID), zap.Error(err))
return err
}
default:
}
stateAction := s.state.Current()
switch stateAction.Op {
case InitOp:
s.state.FinishAction(ctx)
// FIXME(jirwin): Disabling syncing assets for now
// s.state.PushAction(ctx, Action{Op: SyncAssetsOp})
s.state.PushAction(ctx, Action{Op: SyncGrantExpansionOp})
s.state.PushAction(ctx, Action{Op: SyncGrantsOp})
s.state.PushAction(ctx, Action{Op: SyncEntitlementsOp})
s.state.PushAction(ctx, Action{Op: SyncResourcesOp})
s.state.PushAction(ctx, Action{Op: SyncResourceTypesOp})
err = s.Checkpoint(ctx)
if err != nil {
return err
}
continue
case SyncResourceTypesOp:
err = s.SyncResourceTypes(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncResourcesOp:
err = s.SyncResources(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncEntitlementsOp:
err = s.SyncEntitlements(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncGrantsOp:
err = s.SyncGrants(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncAssetsOp:
err = s.SyncAssets(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
case SyncGrantExpansionOp:
if !s.state.NeedsExpansion() {
l.Debug("skipping grant expansion, no grants to expand")
s.state.FinishAction(ctx)
continue
}
err = s.SyncGrantExpansion(ctx)
if !shouldWaitAndRetry(ctx, err) {
return err
}
continue
default:
return fmt.Errorf("unexpected sync step")
}
}
err = s.store.EndSync(ctx)
if err != nil {
return err
}
l.Info("Sync complete.")
err = s.store.Cleanup(ctx)
if err != nil {
return err
}
return nil
}
func (s *syncer) SkipSync(ctx context.Context) error {
l := ctxzap.Extract(ctx)
l.Info("skipping sync")
var runCanc context.CancelFunc
if s.runDuration > 0 {
_, runCanc = context.WithTimeout(ctx, s.runDuration)
}
if runCanc != nil {
defer runCanc()
}
err := s.loadStore(ctx)
if err != nil {
return err
}
_, err = s.connector.Validate(ctx, &v2.ConnectorServiceValidateRequest{})
if err != nil {
return err
}
_, err = s.store.StartNewSync(ctx)
if err != nil {
return err
}
err = s.store.EndSync(ctx)
if err != nil {
return err
}
err = s.store.Cleanup(ctx)
if err != nil {
return err
}
return nil
}
// SyncResourceTypes calls the ListResourceType() connector endpoint and persists the results in to the datasource.
func (s *syncer) SyncResourceTypes(ctx context.Context) error {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing resource types...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
err := s.loadStore(ctx)
if err != nil {
return err
}
resp, err := s.connector.ListResourceTypes(ctx, &v2.ResourceTypesServiceListResourceTypesRequest{PageToken: pageToken})
if err != nil {
return err
}
err = s.store.PutResourceTypes(ctx, resp.List...)
if err != nil {
return err
}
s.handleProgress(ctx, s.state.Current(), len(resp.List))
if resp.NextPageToken == "" {
s.state.FinishAction(ctx)
return nil
}
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
return nil
}
// getSubResources fetches the sub resource types from a resources' annotations.
func (s *syncer) getSubResources(ctx context.Context, parent *v2.Resource) error {
for _, a := range parent.Annotations {
if a.MessageIs((*v2.ChildResourceType)(nil)) {
crt := &v2.ChildResourceType{}
err := a.UnmarshalTo(crt)
if err != nil {
return err
}
childAction := Action{
Op: SyncResourcesOp,
ResourceTypeID: crt.ResourceTypeId,
ParentResourceID: parent.Id.Resource,
ParentResourceTypeID: parent.Id.ResourceType,
}
s.state.PushAction(ctx, childAction)
}
}
return nil
}
// SyncResources handles fetching all of the resources from the connector given the provided resource types. For each
// resource, we gather any child resource types it may emit, and traverse the resource tree.
func (s *syncer) SyncResources(ctx context.Context) error {
if s.state.Current().ResourceTypeID == "" {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing resources...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListResourceTypes(ctx, &v2.ResourceTypesServiceListResourceTypesRequest{PageToken: pageToken})
if err != nil {
return err
}
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}
for _, rt := range resp.List {
s.state.PushAction(ctx, Action{Op: SyncResourcesOp, ResourceTypeID: rt.Id})
}
return nil
}
return s.syncResources(ctx)
}
// syncResources fetches a given resource from the connector, and returns a slice of new child resources to fetch.
func (s *syncer) syncResources(ctx context.Context) error {
req := &v2.ResourcesServiceListResourcesRequest{
ResourceTypeId: s.state.ResourceTypeID(ctx),
PageToken: s.state.PageToken(ctx),
}
if s.state.ParentResourceTypeID(ctx) != "" && s.state.ParentResourceID(ctx) != "" {
req.ParentResourceId = &v2.ResourceId{
ResourceType: s.state.ParentResourceTypeID(ctx),
Resource: s.state.ParentResourceID(ctx),
}
}
resp, err := s.connector.ListResources(ctx, req)
if err != nil {
return err
}
s.handleProgress(ctx, s.state.Current(), len(resp.List))
if resp.NextPageToken == "" {
s.state.FinishAction(ctx)
} else {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
}
bulkPutResoruces := []*v2.Resource{}
for _, r := range resp.List {
// Check if we've already synced this resource, skip it if we have
_, err = s.store.GetResource(ctx, &reader_v2.ResourcesReaderServiceGetResourceRequest{
ResourceId: &v2.ResourceId{ResourceType: r.Id.ResourceType, Resource: r.Id.Resource},
})
if err == nil {
continue
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
err = s.validateResourceTraits(ctx, r)
if err != nil {
return err
}
// Set the resource creation source
r.CreationSource = v2.Resource_CREATION_SOURCE_CONNECTOR_LIST_RESOURCES
bulkPutResoruces = append(bulkPutResoruces, r)
err = s.getSubResources(ctx, r)
if err != nil {
return err
}
}
if len(bulkPutResoruces) > 0 {
err = s.store.PutResources(ctx, bulkPutResoruces...)
if err != nil {
return err
}
}
return nil
}
func (s *syncer) validateResourceTraits(ctx context.Context, r *v2.Resource) error {
resourceTypeResponse, err := s.store.GetResourceType(ctx, &reader_v2.ResourceTypesReaderServiceGetResourceTypeRequest{
ResourceTypeId: r.Id.ResourceType,
})
if err != nil {
return err
}
for _, t := range resourceTypeResponse.ResourceType.Traits {
var trait proto.Message
switch t {
case v2.ResourceType_TRAIT_APP:
trait = &v2.AppTrait{}
case v2.ResourceType_TRAIT_GROUP:
trait = &v2.GroupTrait{}
case v2.ResourceType_TRAIT_USER:
trait = &v2.UserTrait{}
case v2.ResourceType_TRAIT_ROLE:
trait = &v2.RoleTrait{}
default:
}
if trait != nil {
annos := annotations.Annotations(r.Annotations)
if !annos.Contains(trait) {
ctxzap.Extract(ctx).Error(
"resource was missing expected trait",
zap.String("trait", string(trait.ProtoReflect().Descriptor().Name())),
zap.String("resource_type_id", r.Id.ResourceType),
zap.String("resource_id", r.Id.Resource),
)
return fmt.Errorf("resource was missing expected trait %s", trait.ProtoReflect().Descriptor().Name())
}
}
}
return nil
}
// shouldSkipEntitlementsAndGrants determines if we should sync entitlements for a given resource. We cache the
// result of this function for each resource type to avoid constant lookups in the database.
func (s *syncer) shouldSkipEntitlementsAndGrants(ctx context.Context, r *v2.Resource) (bool, error) {
// We've checked this resource type, so we can return what we have cached directly.
if skip, ok := s.skipEGForResourceType[r.Id.ResourceType]; ok {
return skip, nil
}
rt, err := s.store.GetResourceType(ctx, &reader_v2.ResourceTypesReaderServiceGetResourceTypeRequest{
ResourceTypeId: r.Id.ResourceType,
})
if err != nil {
return false, err
}
rtAnnos := annotations.Annotations(rt.ResourceType.Annotations)
skipEntitlements := rtAnnos.Contains(&v2.SkipEntitlementsAndGrants{})
s.skipEGForResourceType[r.Id.ResourceType] = skipEntitlements
return skipEntitlements, nil
}
// SyncEntitlements fetches the entitlements from the connector. It first lists each resource from the datastore,
// and pushes an action to fetch the entitlements for each resource.
func (s *syncer) SyncEntitlements(ctx context.Context) error {
if s.state.ResourceTypeID(ctx) == "" && s.state.ResourceID(ctx) == "" {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing entitlements...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListResources(ctx, &v2.ResourcesServiceListResourcesRequest{PageToken: pageToken})
if err != nil {
return err
}
// We want to take action on the next page before we push any new actions
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}
for _, r := range resp.List {
shouldSkipEntitlements, err := s.shouldSkipEntitlementsAndGrants(ctx, r)
if err != nil {
return err
}
if shouldSkipEntitlements {
continue
}
s.state.PushAction(ctx, Action{Op: SyncEntitlementsOp, ResourceID: r.Id.Resource, ResourceTypeID: r.Id.ResourceType})
}
return nil
}
err := s.syncEntitlementsForResource(ctx, &v2.ResourceId{
ResourceType: s.state.ResourceTypeID(ctx),
Resource: s.state.ResourceID(ctx),
})
if err != nil {
return err
}
return nil
}
// syncEntitlementsForResource fetches the entitlements for a specific resource from the connector.
func (s *syncer) syncEntitlementsForResource(ctx context.Context, resourceID *v2.ResourceId) error {
resourceResponse, err := s.store.GetResource(ctx, &reader_v2.ResourcesReaderServiceGetResourceRequest{
ResourceId: resourceID,
})
if err != nil {
return err
}
pageToken := s.state.PageToken(ctx)
resp, err := s.connector.ListEntitlements(ctx, &v2.EntitlementsServiceListEntitlementsRequest{
Resource: resourceResponse.Resource,
PageToken: pageToken,
})
if err != nil {
return err
}
err = s.store.PutEntitlements(ctx, resp.List...)
if err != nil {
return err
}
s.handleProgress(ctx, s.state.Current(), len(resp.List))
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}
return nil
}
// syncAssetsForResource looks up a resource given the input ID. From there it looks to see if there are any traits that
// include references to an asset. For each AssetRef, we then call GetAsset on the connector and stream the asset from the connector.
// Once we have the entire asset, we put it in the database.
func (s *syncer) syncAssetsForResource(ctx context.Context, resourceID *v2.ResourceId) error {
l := ctxzap.Extract(ctx)
resourceResponse, err := s.store.GetResource(ctx, &reader_v2.ResourcesReaderServiceGetResourceRequest{
ResourceId: resourceID,
})
if err != nil {
return err
}
var assetRefs []*v2.AssetRef
rAnnos := annotations.Annotations(resourceResponse.Resource.Annotations)
userTrait := &v2.UserTrait{}
ok, err := rAnnos.Pick(userTrait)
if err != nil {
return err
}
if ok {
assetRefs = append(assetRefs, userTrait.Icon)
}
grpTrait := &v2.GroupTrait{}
ok, err = rAnnos.Pick(grpTrait)
if err != nil {
return err
}
if ok {
assetRefs = append(assetRefs, grpTrait.Icon)
}
appTrait := &v2.AppTrait{}
ok, err = rAnnos.Pick(appTrait)
if err != nil {
return err
}
if ok {
assetRefs = append(assetRefs, appTrait.Icon, appTrait.Logo)
}
for _, assetRef := range assetRefs {
if assetRef == nil {
continue
}
l.Debug("fetching asset", zap.String("asset_ref_id", assetRef.Id))
resp, err := s.connector.GetAsset(ctx, &v2.AssetServiceGetAssetRequest{Asset: assetRef})
if err != nil {
return err
}
// FIXME(jirwin): if the return from the client is nil, skip this asset
// Temporary until we can implement assets on the platform side
if resp == nil {
continue
}
var metadata *v2.AssetServiceGetAssetResponse_Metadata
assetBytes := &bytes.Buffer{}
var recvErr error
var msg *v2.AssetServiceGetAssetResponse
for !errors.Is(recvErr, io.EOF) {
msg, recvErr = resp.Recv()
if recvErr != nil {
if errors.Is(recvErr, io.EOF) {
continue
}
l.Error("error fetching asset", zap.Error(recvErr))
return err
}
l.Debug("received asset message")
switch assetMsg := msg.Msg.(type) {
case *v2.AssetServiceGetAssetResponse_Metadata_:
metadata = assetMsg.Metadata
case *v2.AssetServiceGetAssetResponse_Data_:
l.Debug("Received data for asset")
_, err := io.Copy(assetBytes, bytes.NewReader(assetMsg.Data.Data))
if err != nil {
_ = resp.CloseSend()
return err
}
}
}
if metadata == nil {
return fmt.Errorf("no metadata received, unable to store asset")
}
err = s.store.PutAsset(ctx, assetRef, metadata.ContentType, assetBytes.Bytes())
if err != nil {
return err
}
}
s.state.FinishAction(ctx)
return nil
}
// SyncAssets iterates each resource in the data store, and adds an action to fetch all of the assets for that resource.
func (s *syncer) SyncAssets(ctx context.Context) error {
if s.state.ResourceTypeID(ctx) == "" && s.state.ResourceID(ctx) == "" {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing assets...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListResources(ctx, &v2.ResourcesServiceListResourcesRequest{PageToken: pageToken})
if err != nil {
return err
}
// We want to take action on the next page before we push any new actions
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}
for _, r := range resp.List {
s.state.PushAction(ctx, Action{Op: SyncAssetsOp, ResourceID: r.Id.Resource, ResourceTypeID: r.Id.ResourceType})
}
return nil
}
err := s.syncAssetsForResource(ctx, &v2.ResourceId{
ResourceType: s.state.ResourceTypeID(ctx),
Resource: s.state.ResourceID(ctx),
})
if err != nil {
ctxzap.Extract(ctx).Error("error syncing assets", zap.Error(err))
return err
}
return nil
}
// SyncGrantExpansion
// TODO(morgabra) Docs
func (s *syncer) SyncGrantExpansion(ctx context.Context) error {
l := ctxzap.Extract(ctx)
entitlementGraph := s.state.EntitlementGraph(ctx)
if !entitlementGraph.Loaded {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
l.Info("Expanding grants...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListGrants(ctx, &v2.GrantsServiceListGrantsRequest{PageToken: pageToken})
if err != nil {
return err
}
// We want to take action on the next page before we push any new actions
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
entitlementGraph.Loaded = true
}
for _, grant := range resp.List {
annos := annotations.Annotations(grant.Annotations)
expandable := &v2.GrantExpandable{}
_, err := annos.Pick(expandable)
if err != nil {
return err
}
if len(expandable.GetEntitlementIds()) == 0 {
continue
}
principalID := grant.GetPrincipal().GetId()
if principalID == nil {
return fmt.Errorf("principal id was nil")
}
// FIXME(morgabra) Log and skip some of the error paths here?
for _, srcEntitlementID := range expandable.EntitlementIds {
l.Debug(
"Expandable entitlement found",
zap.String("src_entitlement_id", srcEntitlementID),
zap.String("dst_entitlement_id", grant.GetEntitlement().GetId()),
)
srcEntitlement, err := s.store.GetEntitlement(ctx, &reader_v2.EntitlementsReaderServiceGetEntitlementRequest{
EntitlementId: srcEntitlementID,
})
if err != nil {
l.Error("error fetching source entitlement",
zap.String("src_entitlement_id", srcEntitlementID),
zap.String("dst_entitlement_id", grant.GetEntitlement().GetId()),
zap.Error(err),
)
continue
}
// The expand annotation points at entitlements by id. Those entitlements' resource should match
// the current grant's principal, so we don't allow expanding arbitrary entitlements.
sourceEntitlementResourceID := srcEntitlement.GetEntitlement().GetResource().GetId()
if sourceEntitlementResourceID == nil {
return fmt.Errorf("source entitlement resource id was nil")
}
if principalID.ResourceType != sourceEntitlementResourceID.ResourceType ||
principalID.Resource != sourceEntitlementResourceID.Resource {
l.Error(
"source entitlement resource id did not match grant principal id",
zap.String("grant_principal_id", principalID.String()),
zap.String("source_entitlement_resource_id", sourceEntitlementResourceID.String()))
return fmt.Errorf("source entitlement resource id did not match grant principal id")
}
entitlementGraph.AddEntitlement(grant.Entitlement)
entitlementGraph.AddEntitlement(srcEntitlement.GetEntitlement())
err = entitlementGraph.AddEdge(ctx,
srcEntitlement.GetEntitlement().GetId(),
grant.GetEntitlement().GetId(),
expandable.Shallow,
expandable.ResourceTypeIds,
)
if err != nil {
return fmt.Errorf("error adding edge to graph: %w", err)
}
}
}
return nil
}
if entitlementGraph.Loaded {
cycle := entitlementGraph.GetFirstCycle()
if cycle != nil {
l.Warn(
"cycle detected in entitlement graph",
zap.Any("cycle", cycle),
zap.Any("initial graph", entitlementGraph),
)
if dontFixCycles {
return fmt.Errorf("cycles detected in entitlement graph")
}
err := entitlementGraph.FixCycles()
if err != nil {
return err
}
}
}
err := s.expandGrantsForEntitlements(ctx)
if err != nil {
return err
}
return nil
}
// SyncGrants fetches the grants for each resource from the connector. It iterates each resource
// from the datastore, and pushes a new action to sync the grants for each individual resource.
func (s *syncer) SyncGrants(ctx context.Context) error {
if s.state.ResourceTypeID(ctx) == "" && s.state.ResourceID(ctx) == "" {
pageToken := s.state.PageToken(ctx)
if pageToken == "" {
ctxzap.Extract(ctx).Info("Syncing grants...")
s.handleInitialActionForStep(ctx, *s.state.Current())
}
resp, err := s.store.ListResources(ctx, &v2.ResourcesServiceListResourcesRequest{PageToken: pageToken})
if err != nil {
return err
}
// We want to take action on the next page before we push any new actions
if resp.NextPageToken != "" {
err = s.state.NextPage(ctx, resp.NextPageToken)
if err != nil {
return err
}
} else {
s.state.FinishAction(ctx)
}
for _, r := range resp.List {
shouldSkip, err := s.shouldSkipEntitlementsAndGrants(ctx, r)
if err != nil {
return err
}
if shouldSkip {
continue
}
s.state.PushAction(ctx, Action{Op: SyncGrantsOp, ResourceID: r.Id.Resource, ResourceTypeID: r.Id.ResourceType})
}
return nil
}
err := s.syncGrantsForResource(ctx, &v2.ResourceId{
ResourceType: s.state.ResourceTypeID(ctx),
Resource: s.state.ResourceID(ctx),
})
if err != nil {
return err
}
return nil
}
type latestSyncFetcher interface {
LatestFinishedSync(ctx context.Context) (string, error)
}
func (s *syncer) fetchResourceForPreviousSync(ctx context.Context, resourceID *v2.ResourceId) (string, *v2.ETag, error) {
l := ctxzap.Extract(ctx)
var previousSyncID string
var err error
if psf, ok := s.store.(latestSyncFetcher); ok {
previousSyncID, err = psf.LatestFinishedSync(ctx)
if err != nil {
return "", nil, err
}
}
if previousSyncID == "" {
return "", nil, nil
}