This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
/
loader.go
1222 lines (1074 loc) · 36.6 KB
/
loader.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
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 teams
import (
"errors"
"fmt"
"sort"
"time"
"golang.org/x/net/context"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
)
// How long until the tail of a team sigchain is considered non-fresh
const freshnessLimit = time.Duration(1) * time.Hour
// Load a Team from the TeamLoader.
// Can be called from inside the teams package.
func Load(ctx context.Context, g *libkb.GlobalContext, lArg keybase1.LoadTeamArg) (*Team, error) {
teamData, err := g.GetTeamLoader().Load(ctx, lArg)
if err != nil {
return nil, err
}
ret := NewTeam(ctx, g, teamData)
if lArg.RefreshUIDMapper {
// If we just loaded the group, then inform the UIDMapper of any UID->EldestSeqno
// mappings, so that we're guaranteed they aren't stale.
ret.refreshUIDMapper(ctx, g)
}
return ret, nil
}
// Loader of keybase1.TeamData objects. Handles caching.
// Because there is one of this global object and it is attached to G,
// its Load interface must return a keybase1.TeamData not a teams.Team.
// To load a teams.Team use the package-level function Load.
// Threadsafe.
type TeamLoader struct {
libkb.Contextified
world LoaderContext
storage *Storage
// Single-flight locks per team ID.
// (Private and public loads of the same ID will block each other, should be fine)
locktab libkb.LockTable
// Cache lookups of team name -> ID for a few seconds, to absorb bursts of lookups
// from the frontend
nameLookupBurstCache *libkb.BurstCache
}
var _ libkb.TeamLoader = (*TeamLoader)(nil)
func NewTeamLoader(g *libkb.GlobalContext, world LoaderContext, storage *Storage) *TeamLoader {
return &TeamLoader{
Contextified: libkb.NewContextified(g),
world: world,
storage: storage,
nameLookupBurstCache: libkb.NewBurstCache(g, 100, 10*time.Second, "SubteamNameToID"),
}
}
// NewTeamLoaderAndInstall creates a new loader and installs it into G.
func NewTeamLoaderAndInstall(g *libkb.GlobalContext) *TeamLoader {
world := NewLoaderContextFromG(g)
st := NewStorage(g)
l := NewTeamLoader(g, world, st)
g.SetTeamLoader(l)
return l
}
func (l *TeamLoader) Load(ctx context.Context, lArg keybase1.LoadTeamArg) (res *keybase1.TeamData, err error) {
me, err := l.world.getMe(ctx)
if err != nil {
return nil, err
}
if me.IsNil() && !lArg.Public {
return nil, libkb.NewLoginRequiredError("login required to load a private team")
}
return l.load1(ctx, me, lArg)
}
func (l *TeamLoader) Delete(ctx context.Context, teamID keybase1.TeamID) (err error) {
defer l.G().CTraceTimed(ctx, fmt.Sprintf("TeamLoader#Delete(%v)", teamID), func() error { return err })()
// Single-flight lock by team ID.
lock := l.locktab.AcquireOnName(ctx, l.G(), teamID.String())
defer lock.Release(ctx)
return l.storage.Delete(ctx, teamID, teamID.IsPublic())
}
func (l *TeamLoader) HintLatestSeqno(ctx context.Context, teamID keybase1.TeamID, seqno keybase1.Seqno) error {
// Single-flight lock by team ID.
lock := l.locktab.AcquireOnName(ctx, l.G(), teamID.String())
defer lock.Release(ctx)
// Load from the cache
td := l.storage.Get(ctx, teamID, teamID.IsPublic())
if td == nil {
// Nothing to store the hint on.
return nil
}
if seqno < td.LatestSeqnoHint {
// The hint is behind the times, ignore.
return nil
}
td.LatestSeqnoHint = seqno
l.storage.Put(ctx, td)
return nil
}
type nameLookupBurstCacheKey struct {
teamName keybase1.TeamName
public bool
}
func (n nameLookupBurstCacheKey) String() string {
return fmt.Sprintf("%s:%v", n.teamName.String(), n.public)
}
// Resolve a team name to a team ID.
// Will always hit the server for subteams. The server can lie in this return value.
func (l *TeamLoader) ResolveNameToIDUntrusted(ctx context.Context, teamName keybase1.TeamName, public bool, allowCache bool) (id keybase1.TeamID, err error) {
defer l.G().CVTrace(ctx, libkb.VLog0, fmt.Sprintf("resolveNameToUIDUntrusted(%s,%v,%v)", teamName.String(), public, allowCache), func() error { return err })()
// For root team names, just hash.
if teamName.IsRootTeam() {
return teamName.ToTeamID(public), nil
}
if !allowCache {
return resolveNameToIDUntrustedAPICall(ctx, l.G(), teamName, public)
}
var idVoidPointer interface{}
key := nameLookupBurstCacheKey{teamName, public}
idVoidPointer, err = l.nameLookupBurstCache.Load(ctx, key, l.makeNameLookupBurstCacheLoader(ctx, l.G(), key))
if err != nil {
return keybase1.TeamID(""), err
}
if idPointer, ok := idVoidPointer.(*keybase1.TeamID); ok && idPointer != nil {
id = *idPointer
} else {
return keybase1.TeamID(""), errors.New("bad cast out of nameLookupBurstCache")
}
return id, nil
}
func resolveNameToIDUntrustedAPICall(ctx context.Context, g *libkb.GlobalContext, teamName keybase1.TeamName, public bool) (id keybase1.TeamID, err error) {
arg := libkb.NewAPIArgWithNetContext(ctx, "team/get")
arg.SessionType = libkb.APISessionTypeREQUIRED
arg.Args = libkb.HTTPArgs{
"name": libkb.S{Val: teamName.String()},
"lookup_only": libkb.B{Val: true},
"public": libkb.B{Val: public},
}
var rt rawTeam
if err := g.API.GetDecode(arg, &rt); err != nil {
return id, err
}
id = rt.ID
if !id.Exists() {
return id, fmt.Errorf("could not resolve team name: %v", teamName.String())
}
return id, nil
}
func (l *TeamLoader) makeNameLookupBurstCacheLoader(ctx context.Context, g *libkb.GlobalContext, key nameLookupBurstCacheKey) libkb.BurstCacheLoader {
return func() (obj interface{}, err error) {
id, err := resolveNameToIDUntrustedAPICall(ctx, g, key.teamName, key.public)
if err != nil {
return nil, err
}
return &id, nil
}
}
// Load1 unpacks the loadArg, calls load2, and does some final checks.
// The key difference between load1 and load2 is that load2 is recursive (for subteams).
func (l *TeamLoader) load1(ctx context.Context, me keybase1.UserVersion, lArg keybase1.LoadTeamArg) (*keybase1.TeamData, error) {
err := l.checkArg(ctx, lArg)
if err != nil {
return nil, err
}
var teamName *keybase1.TeamName
if len(lArg.Name) > 0 {
teamNameParsed, err := keybase1.TeamNameFromString(lArg.Name)
if err != nil {
return nil, fmt.Errorf("invalid team name: %v", err)
}
teamName = &teamNameParsed
}
teamID := lArg.ID
// Resolve the name to team ID. Will always hit the server for subteams.
// It is safe for the answer to be wrong because the name is checked on the way out,
// and the merkle tree check guarantees one sigchain per team id.
if !teamID.Exists() {
teamID, err = l.ResolveNameToIDUntrusted(ctx, *teamName, lArg.Public, lArg.AllowNameLookupBurstCache)
if err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader looking up team by name failed: %v -> %v", *teamName, err)
return nil, err
}
}
mungedForceRepoll := lArg.ForceRepoll
mungedWantMembers, err := l.mungeWantMembers(ctx, lArg.Refreshers.WantMembers)
if err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader munge failed: %v", err)
// drop the error and just force a repoll.
mungedForceRepoll = true
mungedWantMembers = nil
}
ret, err := l.load2(ctx, load2ArgT{
teamID: teamID,
needAdmin: lArg.NeedAdmin,
needKeyGeneration: lArg.Refreshers.NeedKeyGeneration,
needKBFSKeyGeneration: lArg.Refreshers.NeedKBFSKeyGeneration,
wantMembers: mungedWantMembers,
wantMembersRole: lArg.Refreshers.WantMembersRole,
forceFullReload: lArg.ForceFullReload,
forceRepoll: mungedForceRepoll,
staleOK: lArg.StaleOK,
public: lArg.Public,
needSeqnos: nil,
readSubteamID: nil,
me: me,
})
if err != nil {
return nil, err
}
if ret == nil {
return nil, fmt.Errorf("team loader fault: got nil from load2")
}
// Only public teams are allowed to be behind on secrets.
// This is allowed because you can load a public team you're not in.
if !l.hasSyncedSecrets(&ret.team) && !ret.team.Chain.Public {
// this should not happen
return nil, fmt.Errorf("missing secrets for team")
}
// Check team name on the way out
// The snapshot may have already been written to cache, but that should be ok,
// because the cache is keyed by ID.
if teamName != nil {
// (TODO: this won't work for renamed level 3 teams or above. There's work on this in miles/teamloader-names)
if !teamName.Eq(ret.team.Name) {
return nil, fmt.Errorf("team name mismatch: %v != %v", ret.team.Name, teamName.String())
}
}
return &ret.team, nil
}
func (l *TeamLoader) checkArg(ctx context.Context, lArg keybase1.LoadTeamArg) error {
hasID := lArg.ID.Exists()
hasName := len(lArg.Name) > 0
if hasID {
id, err := keybase1.TeamIDFromString(lArg.ID.String())
if err != nil {
return fmt.Errorf("team load arg has invalid ID: %v", lArg.ID)
}
if id.IsPublic() != lArg.Public {
return libkb.NewTeamVisibilityError(lArg.Public, id.IsPublic())
}
}
if !hasID && !hasName {
return fmt.Errorf("team load arg must have either ID or Name")
}
return nil
}
// Mostly the same as the public keybase.LoadTeamArg
// but only supports loading by ID, and has neededSeqnos.
type load2ArgT struct {
teamID keybase1.TeamID
reason string // optional tag for debugging why this load is happening
needAdmin bool
needKeyGeneration keybase1.PerTeamKeyGeneration
needKBFSKeyGeneration keybase1.TeamKBFSKeyRefresher
// wantMembers here is different from wantMembers on LoadTeamArg:
// The EldestSeqno's should not be 0.
wantMembers []keybase1.UserVersion
wantMembersRole keybase1.TeamRole
forceFullReload bool
forceRepoll bool
staleOK bool
public bool
needSeqnos []keybase1.Seqno
// Non-nil if we are loading an ancestor for the greater purpose of
// loading a subteam. This parameter helps the server figure out whether
// to give us a subteam-reader version of the team.
// If and only if this is set, load2 is allowed to return a secret-less TeamData.
// Load1 should never ever return a secret-less TeamData.
readSubteamID *keybase1.TeamID
// If the user is logged out, this will be a nil UserVersion, meaning
/// me.IsNil() will be true.
me keybase1.UserVersion
}
type load2ResT struct {
team keybase1.TeamData
didRepoll bool
}
// Load2 does the rest of the work loading a team.
// It is `playchain` described in the pseudocode in teamplayer.txt
func (l *TeamLoader) load2(ctx context.Context, arg load2ArgT) (ret *load2ResT, err error) {
ctx = libkb.WithLogTag(ctx, "LT") // Load Team
traceLabel := fmt.Sprintf("TeamLoader#load2(%v, public:%v)", arg.teamID, arg.public)
if len(arg.reason) > 0 {
traceLabel = traceLabel + " '" + arg.reason + "'"
}
defer l.G().CTraceTimed(ctx, traceLabel, func() error { return err })()
ret, err = l.load2Inner(ctx, arg)
return ret, err
}
func (l *TeamLoader) load2Inner(ctx context.Context, arg load2ArgT) (*load2ResT, error) {
// Single-flight lock by team ID.
lock := l.locktab.AcquireOnName(ctx, l.G(), arg.teamID.String())
defer lock.Release(ctx)
return l.load2InnerLocked(ctx, arg)
}
func (l *TeamLoader) load2InnerLocked(ctx context.Context, arg load2ArgT) (res *load2ResT, err error) {
const nRetries = 3
for i := 0; i < nRetries; i++ {
res, err = l.load2InnerLockedRetry(ctx, arg)
switch err.(type) {
case nil:
return res, nil
case ProofError:
if arg.forceRepoll {
return res, err
}
// Something went wrong, throw out the cache and try again.
l.G().Log.CDebugf(ctx, "Got proof error (%s); trying again with forceRepoll=true", err.Error())
arg.forceRepoll = true
arg.forceFullReload = true
origErr := err
res, err = l.load2InnerLockedRetry(ctx, arg)
if err == nil {
l.G().Log.CDebugf(ctx, "Found an unexpected TeamLoader case in which busting the cache saved the day (original error was: %s)", origErr.Error())
}
return res, err
case GreenLinkError:
// Try again
l.G().Log.CDebugf(ctx, "TeamLoader retrying after green link")
arg.forceRepoll = true
continue
}
return res, err
}
if err == nil {
// Should never happen
return res, fmt.Errorf("failed retryable team load")
}
// Return the last error
return res, err
}
func (l *TeamLoader) load2InnerLockedRetry(ctx context.Context, arg load2ArgT) (*load2ResT, error) {
ctx, tbs := l.G().CTimeBuckets(ctx)
tracer := l.G().CTimeTracer(ctx, "TeamLoader.load2ILR", false)
defer tracer.Finish()
var err error
var didRepoll bool
// Fetch from cache
tracer.Stage("cache load")
var ret *keybase1.TeamData
if !arg.forceFullReload {
// Load from cache
ret = l.storage.Get(ctx, arg.teamID, arg.public)
}
if ret != nil && !ret.Chain.Reader.Eq(arg.me) {
// Check that we are the same person as when this team was last loaded as a courtesy.
// This should never happen. We shouldn't be able to decrypt someone else's snapshot.
l.G().Log.CWarningf(ctx, "TeamLoader discarding snapshot for wrong user: (%v, %v) != (%v, %v)",
arg.me.Uid, arg.me.EldestSeqno, ret.Chain.Reader.Uid, ret.Chain.Reader.EldestSeqno)
ret = nil
}
var cachedName *keybase1.TeamName
if ret != nil && !ret.Name.IsNil() {
cachedName = &ret.Name
}
// Determine whether to repoll merkle.
tracer.Stage("merkle")
discardCache, repoll := l.load2DecideRepoll(ctx, arg, ret)
if discardCache {
ret = nil
repoll = true
}
if ret != nil {
l.G().Log.CDebugf(ctx, "TeamLoader found cached snapshot")
}
var lastSeqno keybase1.Seqno
var lastLinkID keybase1.LinkID
if (ret == nil) || repoll {
l.G().Log.CDebugf(ctx, "TeamLoader looking up merkle leaf (force:%v)", arg.forceRepoll)
// Reference the merkle tree to fetch the sigchain tail leaf for the team.
lastSeqno, lastLinkID, err = l.world.merkleLookup(ctx, arg.teamID, arg.public)
if err != nil {
return nil, err
}
didRepoll = true
} else {
lastSeqno = ret.Chain.LastSeqno
lastLinkID = ret.Chain.LastLinkID
}
// For child calls to load2, the subteam reader ID is carried up
// or if it doesn't exist, start at this team.
readSubteamID := arg.teamID
if arg.readSubteamID != nil {
readSubteamID = *arg.readSubteamID
}
proofSet := newProofSet(l.G())
var parentChildOperations []*parentChildOperation
// Backfill stubbed links that need to be filled now.
tracer.Stage("backfill")
if ret != nil && len(arg.needSeqnos) > 0 {
ret, proofSet, parentChildOperations, err = l.fillInStubbedLinks(
ctx, arg.me, arg.teamID, ret, arg.needSeqnos, readSubteamID, proofSet, parentChildOperations)
if err != nil {
return nil, err
}
}
tracer.Stage("pre-fetch")
var fetchLinksAndOrSecrets bool
if ret == nil {
l.G().Log.CDebugf(ctx, "TeamLoader fetching: no cache")
// We have no cache
fetchLinksAndOrSecrets = true
} else if ret.Chain.LastSeqno < lastSeqno {
l.G().Log.CDebugf(ctx, "TeamLoader fetching: chain update")
// The cache is definitely behind
fetchLinksAndOrSecrets = true
} else if !l.hasSyncedSecrets(ret) {
// The cached secrets are behind the cached chain.
// We may need to hit the server for secrets, even though there are no new links.
if arg.needAdmin {
l.G().Log.CDebugf(ctx, "TeamLoader fetching: NeedAdmin")
// Admins should always have up-to-date secrets
fetchLinksAndOrSecrets = true
}
if err := l.satisfiesNeedKeyGeneration(ctx, arg.needKeyGeneration, ret); err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader fetching: NeedKeyGeneration: %v", err)
fetchLinksAndOrSecrets = true
}
if err := l.satisfiesNeedsKBFSKeyGeneration(ctx, arg.needKBFSKeyGeneration, ret); err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader fetching: KBFSNeedKeyGeneration: %v", err)
fetchLinksAndOrSecrets = true
}
if arg.readSubteamID == nil {
// This is not a recursive load. We should have the keys.
// This may be an extra round trip for public teams you're not in.
l.G().Log.CDebugf(ctx, "TeamLoader fetching: primary load")
fetchLinksAndOrSecrets = true
}
}
// Pull new links from the server
tracer.Stage("fetch")
var teamUpdate *rawTeam
if fetchLinksAndOrSecrets {
lows := l.lows(ctx, ret)
l.G().Log.CDebugf(ctx, "TeamLoader getting links from server (%+v)", lows)
teamUpdate, err = l.world.getNewLinksFromServer(ctx, arg.teamID, arg.public, lows, arg.readSubteamID)
if err != nil {
return nil, err
}
l.G().Log.CDebugf(ctx, "TeamLoader got %v links", len(teamUpdate.Chain))
}
tracer.Stage("unpack")
links, err := l.unpackLinks(ctx, teamUpdate)
if err != nil {
return nil, err
}
var prev libkb.LinkID
if ret != nil {
prev, err = TeamSigChainState{ret.Chain}.GetLatestLibkbLinkID()
if err != nil {
return nil, err
}
}
tracer.Stage("linkloop (%v)", len(links))
for i, link := range links {
l.G().Log.CDebugf(ctx, "TeamLoader processing link seqno:%v", link.Seqno())
if link.Seqno() > lastSeqno {
// This link came from a point in the chain after when we checked the merkle leaf.
// Processing it would require re-checking merkle.
// It would be tricky to ignore it because off-chain data is asserted to be in sync with the chain.
// So, return an error that the caller will retry.
l.G().Log.CDebugf(ctx, "TeamLoader found green link seqno:%v", link.Seqno())
return nil, NewGreenLinkError(link.Seqno())
}
if err := l.checkStubbed(ctx, arg, link); err != nil {
return nil, err
}
if !link.Prev().Eq(prev) {
return nil, NewPrevError("team replay failed: prev chain broken at link %d (%v != %v)",
i, link.Prev(), prev)
}
var signer *signerX
signer, err = l.verifyLink(ctx, arg.teamID, ret, arg.me, link, readSubteamID, proofSet)
if err != nil {
return nil, err
}
if l.isParentChildOperation(ctx, link) {
pco, err := l.toParentChildOperation(ctx, link)
if err != nil {
return nil, err
}
parentChildOperations = append(parentChildOperations, pco)
}
ret, err = l.applyNewLink(ctx, ret, link, signer, arg.me)
if err != nil {
return nil, err
}
prev = link.LinkID()
}
tbs.Log(ctx, "CachedUPAKLoader.LoadKeyV2")
if ret == nil {
return nil, fmt.Errorf("team loader fault: got nil from load2")
}
if !ret.Chain.LastLinkID.Eq(lastLinkID) {
return nil, fmt.Errorf("wrong sigchain link ID: %v != %v",
ret.Chain.LastLinkID, lastLinkID)
}
tracer.Stage("pco")
err = l.checkParentChildOperations(ctx,
arg.me, arg.teamID, ret.Chain.ParentID, readSubteamID, parentChildOperations, proofSet)
if err != nil {
return nil, err
}
tracer.Stage("checkproofs")
err = l.checkProofs(ctx, ret, proofSet)
if err != nil {
return nil, err
}
tracer.Stage("secrets")
if teamUpdate != nil {
if teamUpdate.SubteamReader {
// Only allow subteam-reader results if we are in a recursive load.
if arg.readSubteamID == nil {
return nil, fmt.Errorf("unexpected subteam reader result")
}
} else {
// Add the secrets.
// If it's a public team, there might not be secrets. (If we're not in the team)
if !ret.Chain.Public || (teamUpdate.Box != nil) {
ret, err = l.addSecrets(ctx, ret, arg.me, teamUpdate.Box, teamUpdate.Prevs, teamUpdate.ReaderKeyMasks)
if err != nil {
return nil, fmt.Errorf("loading team secrets: %v", err)
}
if teamUpdate.LegacyTLFUpgrade != nil {
ret, err = l.addKBFSCryptKeys(ctx, ret, teamUpdate.LegacyTLFUpgrade)
if err != nil {
return nil, fmt.Errorf("loading KBFS crypt keys: %v", err)
}
}
}
}
}
// Make sure public works out
if ret.Chain.Public != arg.public {
return nil, fmt.Errorf("team public mismatch: chain:%v != arg:%v", ret.Chain.Public, arg.public)
}
if ret.Chain.Id.IsPublic() != ret.Chain.Public {
return nil, fmt.Errorf("team public mismatch: id:%v != chain:%v", ret.Chain.Id.IsPublic(), ret.Chain.Public)
}
// Sanity check the id
if !ret.Chain.Id.Eq(arg.teamID) {
return nil, fmt.Errorf("team id mismatch: %v != %v", ret.Chain.Id.String(), arg.teamID.String())
}
// Recalculate the team name.
// This must always run to pick up changes on chain and off-chain with ancestor renames.
// Also because without this a subteam could claim any parent in its name.
tracer.Stage("namecalc")
newName, err := l.calculateName(ctx, ret, arg.me, readSubteamID, arg.staleOK)
if err != nil {
return nil, fmt.Errorf("error recalculating name for %v: %v", ret.Name, err)
}
if !ret.Name.Eq(newName) {
// This deep copy is an absurd price to pay, but these mid-team renames should be quite rare.
copy := ret.DeepCopy()
ret = ©
ret.Name = newName
}
l.logIfUnsyncedSecrets(ctx, ret)
// Mutating this field is safe because only TeamLoader
// while holding the single-flight lock reads or writes this field.
ret.CachedAt = keybase1.ToTime(l.G().Clock().Now())
// Clear the untrusted seqno hint.
// Mutating this field is safe because only TeamLoader
// while holding the single-flight lock reads or writes this field.
ret.LatestSeqnoHint = 0
// Cache the validated result
tracer.Stage("put")
l.storage.Put(ctx, ret)
tracer.Stage("notify")
if cachedName != nil && !cachedName.Eq(newName) {
chain := TeamSigChainState{inner: ret.Chain}
// Send a notification if we used to have the name cached and it has changed at all.
changeSet := keybase1.TeamChangeSet{Renamed: true}
go l.G().NotifyRouter.HandleTeamChangedByID(context.Background(),
chain.GetID(), chain.GetLatestSeqno(), chain.IsImplicit(), changeSet)
go l.G().NotifyRouter.HandleTeamChangedByName(context.Background(),
cachedName.String(), chain.GetLatestSeqno(), chain.IsImplicit(), changeSet)
go l.G().NotifyRouter.HandleTeamChangedByName(context.Background(),
newName.String(), chain.GetLatestSeqno(), chain.IsImplicit(), changeSet)
}
// Check request constraints
tracer.Stage("postcheck")
err = l.load2CheckReturn(ctx, arg, ret)
if err != nil {
return nil, err
}
return &load2ResT{
team: *ret,
didRepoll: didRepoll,
}, nil
}
// Decide whether to repoll merkle based on load arg.
// Returns (discardCache, repoll)
// If discardCache is true, the caller should throw out their cached copy and repoll.
// Considers:
// - NeedAdmin
// - NeedKeyGeneration
// - WantMembers
// - ForceRepoll
// - Cache freshness / StaleOK
// - NeedSeqnos
func (l *TeamLoader) load2DecideRepoll(ctx context.Context, arg load2ArgT, fromCache *keybase1.TeamData) (bool, bool) {
// NeedAdmin is a special constraint where we start from scratch.
// Because of admin-only invite links.
if arg.needAdmin {
if !l.satisfiesNeedAdmin(ctx, arg.me, fromCache) {
// Start from scratch if we are newly admin
return true, true
}
}
// Whether to hit up merkle for the latest tail.
// This starts out false and then there are many reasons for turning it true.
repoll := false
if arg.forceRepoll {
repoll = true
}
// Repoll if the server has previously hinted that the team has new links.
if fromCache != nil && fromCache.Chain.LastSeqno < fromCache.LatestSeqnoHint {
repoll = true
}
// Repoll to get a new key generation
if arg.needKeyGeneration > 0 {
if l.satisfiesNeedKeyGeneration(ctx, arg.needKeyGeneration, fromCache) != nil {
repoll = true
}
}
if arg.needKBFSKeyGeneration.Generation > 0 {
if l.satisfiesNeedsKBFSKeyGeneration(ctx, arg.needKBFSKeyGeneration, fromCache) != nil {
repoll = true
}
}
// Repoll because it might help get the wanted members
if len(arg.wantMembers) > 0 {
if l.satisfiesWantMembers(ctx, arg.wantMembers, arg.wantMembersRole, fromCache) != nil {
repoll = true
}
}
// Repoll if we need a seqno not in the cache.
// Does not force a repoll if we just need to fill in previous links
if len(arg.needSeqnos) > 0 {
if fromCache == nil {
repoll = true
} else {
if fromCache.Chain.LastSeqno < l.seqnosMax(arg.needSeqnos) {
repoll = true
}
}
}
if fromCache == nil {
// We need a merkle leaf when starting from scratch.
repoll = true
}
cacheIsOld := (fromCache != nil) && !l.isFresh(ctx, fromCache.CachedAt)
if cacheIsOld && !arg.staleOK {
// We need a merkle leaf
repoll = true
}
return false, repoll
}
// Check whether the load produced a snapshot that can be returned to the caller.
// This should not check anything that is critical to the validity of the snapshot
// because the snapshot is put into the cache before this check.
// Considers:
// - NeedAdmin
// - NeedKeyGeneration
// - NeedSeqnos
func (l *TeamLoader) load2CheckReturn(ctx context.Context, arg load2ArgT, res *keybase1.TeamData) error {
if arg.needAdmin {
if !l.satisfiesNeedAdmin(ctx, arg.me, res) {
l.G().Log.CDebugf(ctx, "user %v is not an admin of team %v at seqno:%v",
arg.me, arg.teamID, res.Chain.LastSeqno)
return fmt.Errorf("user %v is not an admin of the team", arg.me)
}
}
// Repoll to get a new key generation
if arg.needKeyGeneration > 0 {
err := l.satisfiesNeedKeyGeneration(ctx, arg.needKeyGeneration, res)
if err != nil {
return err
}
}
if arg.needKBFSKeyGeneration.Generation > 0 {
err := l.satisfiesNeedsKBFSKeyGeneration(ctx, arg.needKBFSKeyGeneration, res)
if err != nil {
return err
}
}
if len(arg.needSeqnos) > 0 {
err := l.checkNeededSeqnos(ctx, res, arg.needSeqnos)
if err != nil {
return err
}
}
return nil
}
// Whether the user is an admin at the snapshot, and there are no stubbed links, and keys are up to date.
func (l *TeamLoader) satisfiesNeedAdmin(ctx context.Context, me keybase1.UserVersion, teamData *keybase1.TeamData) bool {
if teamData == nil {
return false
}
if (TeamSigChainState{inner: teamData.Chain}.HasAnyStubbedLinks()) {
return false
}
if !l.hasSyncedSecrets(teamData) {
return false
}
state := TeamSigChainState{inner: teamData.Chain}
role, err := state.GetUserRole(me)
if err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader error getting my role: %v", err)
return false
}
if !role.IsAdminOrAbove() {
if !state.IsSubteam() {
return false
}
yes, err := l.isImplicitAdminOf(ctx, state.GetID(), state.GetParentID(), me, me)
if err != nil {
l.G().Log.CDebugf(ctx, "TeamLoader error getting checking implicit admin: %s", err)
return false
}
if !yes {
return false
}
}
return true
}
// Check whether a user is an implicit admin of a team.
func (l *TeamLoader) isImplicitAdminOf(ctx context.Context, teamID keybase1.TeamID, ancestorID *keybase1.TeamID,
me keybase1.UserVersion, uv keybase1.UserVersion) (bool, error) {
// IDs of ancestors that were not freshly polled.
// Check them again with forceRepoll if the affirmative is not found cached.
checkAgain := make(map[keybase1.TeamID]bool)
check1 := func(chain *TeamSigChainState) bool {
role, err := chain.GetUserRole(uv)
if err != nil {
return false
}
return role.IsAdminOrAbove()
}
i := 0
for {
i++
if i >= 100 {
// Break in case there's a bug in this loop.
return false, fmt.Errorf("stuck in a loop while checking for implicit admin: %v", ancestorID)
}
// Use load2 so that we can use subteam-reader and get secretless teams.
ancestor, err := l.load2(ctx, load2ArgT{
teamID: *ancestorID,
reason: "isImplicitAdminOf-1",
me: me,
readSubteamID: &teamID,
})
if err != nil {
return false, err
}
// Be wary, `ancestor` could be, and is likely, a secretless team.
// Do not let it out of sight.
ancestorChain := TeamSigChainState{inner: ancestor.team.Chain}
if !ancestor.didRepoll {
checkAgain[ancestorChain.GetID()] = true
}
if check1(&ancestorChain) {
return true, nil
}
if !ancestorChain.IsSubteam() {
break
}
// Get the next level up.
ancestorID = ancestorChain.GetParentID()
}
// The answer was not found to be yes in the cache.
// Try again with the teams that were not polled as they might have unseen updates.
for ancestorID := range checkAgain {
ancestor, err := l.load2(ctx, load2ArgT{
teamID: ancestorID,
reason: "isImplicitAdminOf-again",
me: me,
forceRepoll: true, // Get the latest info.
readSubteamID: &teamID,
})
if err != nil {
return false, err
}
// Be wary, `ancestor` could be, and is likely, a secretless team.
// Do not let it out of sight.
ancestorChain := TeamSigChainState{inner: ancestor.team.Chain}
if check1(&ancestorChain) {
return true, nil
}
}
return false, nil
}
func (l *TeamLoader) satisfiesNeedsKBFSKeyGeneration(ctx context.Context,
kbfs keybase1.TeamKBFSKeyRefresher, state *keybase1.TeamData) error {
if kbfs.Generation == 0 {
return nil
}
if state == nil {
return fmt.Errorf("nil team does not contain KBFS key generation: %#v", kbfs)
}
gen, err := TeamSigChainState{inner: state.Chain}.GetLatestKBFSGeneration(kbfs.AppType)
if err != nil {
return err
}
if kbfs.Generation > gen {
return fmt.Errorf("KBFS key generation too low: %v < %v", gen, kbfs.Generation)
}
return nil
}
// Whether the snapshot has loaded at least up to the key generation and has the secret.
func (l *TeamLoader) satisfiesNeedKeyGeneration(ctx context.Context, needKeyGeneration keybase1.PerTeamKeyGeneration, state *keybase1.TeamData) error {
if needKeyGeneration == 0 {
return nil
}
if state == nil {
return fmt.Errorf("nil team does not contain key generation: %v", needKeyGeneration)
}
key, err := TeamSigChainState{inner: state.Chain}.GetLatestPerTeamKey()
if err != nil {
return err
}
if needKeyGeneration > key.Gen {
return fmt.Errorf("team key generation too low: %v < %v", key.Gen, needKeyGeneration)
}
_, ok := state.PerTeamKeySeeds[needKeyGeneration]
if !ok {
return fmt.Errorf("team key secret missing for generation: %v", needKeyGeneration)
}
return nil
}
// Whether the snapshot has each of `wantMembers` as a member.
func (l *TeamLoader) satisfiesWantMembers(ctx context.Context,
wantMembers []keybase1.UserVersion, wantMembersRole keybase1.TeamRole, state *keybase1.TeamData) error {
if wantMembersRole == keybase1.TeamRole_NONE {
// Default to writer.
wantMembersRole = keybase1.TeamRole_WRITER
}
if len(wantMembers) == 0 {
return nil
}
if state == nil {
return fmt.Errorf("nil team does not have wanted members")
}
for _, uv := range wantMembers {
role, err := TeamSigChainState{inner: state.Chain}.GetUserRole(uv)
if err != nil {
return fmt.Errorf("could not get wanted user role: %v", err)
}
if !role.IsOrAbove(wantMembersRole) {
return fmt.Errorf("wanted user %v is a %v which is not at least %v", uv, role, wantMembersRole)
}
}
return nil
}
func (l *TeamLoader) mungeWantMembers(ctx context.Context, wantMembers []keybase1.UserVersion) (res []keybase1.UserVersion, err error) {
for _, uv1 := range wantMembers {
uv2 := uv1
if uv2.EldestSeqno == 0 {
// Lookup the latest eldest seqno for that uid.
// This value may come from a cache.
uv2.EldestSeqno, err = l.world.lookupEldestSeqno(ctx, uv2.Uid)
if err != nil {
return res, err
}
l.G().Log.CDebugf(ctx, "TeamLoader resolved wantMember %v -> %v", uv2.Uid, uv2.EldestSeqno)
}
res = append(res, uv2)
}
return res, err
}
// Whether y is in xs.
func (l *TeamLoader) seqnosContains(xs []keybase1.Seqno, y keybase1.Seqno) bool {
for _, x := range xs {
if x.Eq(y) {
return true
}
}
return false
}
// Return the max in a list of positive seqnos. Returns 0 if the list is empty