-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
chain.go
2557 lines (2285 loc) · 81.1 KB
/
chain.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"
"golang.org/x/net/context"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/teams/hidden"
jsonw "github.com/keybase/go-jsonw"
)
// Create a new user/version pair.
func NewUserVersion(uid keybase1.UID, eldestSeqno keybase1.Seqno) keybase1.UserVersion {
return keybase1.NewUserVersion(uid, eldestSeqno)
}
const TeamSigChainPlayerSupportedLinkVersion = 2
// Accessor wrapper for keybase1.TeamSigChainState
type TeamSigChainState struct {
inner keybase1.TeamSigChainState
hidden *keybase1.HiddenTeamChain
}
func newTeamSigChainState(t Teamer) TeamSigChainState {
ret := TeamSigChainState{hidden: t.HiddenChain()}
if t.MainChain() != nil {
ret.inner = t.MainChain().Chain
}
return ret
}
func (t TeamSigChainState) DeepCopy() TeamSigChainState {
ret := TeamSigChainState{
inner: t.inner.DeepCopy(),
}
if t.hidden != nil {
tmp := t.hidden.DeepCopy()
ret.hidden = &tmp
}
return ret
}
func (t TeamSigChainState) DeepCopyToPtr() *TeamSigChainState {
t2 := t.DeepCopy()
return &t2
}
func (t TeamSigChainState) GetID() keybase1.TeamID {
return t.inner.Id
}
func (t TeamSigChainState) IsSubteam() bool {
return t.inner.ParentID != nil
}
func (t TeamSigChainState) IsImplicit() bool {
return t.inner.Implicit
}
func (t TeamSigChainState) IsPublic() bool {
return t.inner.Public
}
func (t TeamSigChainState) IsOpen() bool {
return t.inner.Open
}
func (t TeamSigChainState) LatestLastNamePart() keybase1.TeamNamePart {
return t.inner.NameLog[len(t.inner.NameLog)-1].LastPart
}
// Only non-nil if this is a subteam.
func (t TeamSigChainState) GetParentID() *keybase1.TeamID {
return t.inner.ParentID
}
func (t TeamSigChainState) GetLatestSeqno() keybase1.Seqno {
return t.inner.LastSeqno
}
func (t TeamSigChainState) GetLatestHiddenSeqno() keybase1.Seqno {
if t.hidden == nil {
return keybase1.Seqno(0)
}
return t.hidden.Last
}
func (t TeamSigChainState) GetLatestLinkID() keybase1.LinkID {
return t.inner.LastLinkID
}
func (t TeamSigChainState) GetLatestHighSeqno() keybase1.Seqno {
return t.inner.LastHighSeqno
}
func (t TeamSigChainState) GetLatestHighLinkID() keybase1.LinkID {
return t.inner.LastHighLinkID
}
func (t TeamSigChainState) GetLatestLibkbLinkID() (libkb.LinkID, error) {
return libkb.ImportLinkID(t.GetLatestLinkID())
}
func (t TeamSigChainState) GetLinkIDBySeqno(seqno keybase1.Seqno) (keybase1.LinkID, error) {
l1, ok := t.inner.LinkIDs[seqno]
if !ok {
return l1, fmt.Errorf("seqno %v not in chain", seqno)
}
return l1, nil
}
func (t TeamSigChainState) GetLibkbLinkIDBySeqno(seqno keybase1.Seqno) (l2 libkb.LinkID, err error) {
l1, err := t.GetLinkIDBySeqno(seqno)
if err != nil {
return l2, err
}
return libkb.ImportLinkID(l1)
}
func (t TeamSigChainState) GetLatestGeneration() keybase1.PerTeamKeyGeneration {
ret := t.inner.MaxPerTeamKeyGeneration
if h := t.hidden.MaxReaderPerTeamKeyGeneration(); h > ret {
ret = h
}
return ret
}
func (t TeamSigChainState) GetLatestKBFSGeneration(appType keybase1.TeamApplication) (int, error) {
info, ok := t.inner.TlfLegacyUpgrade[appType]
if !ok {
return 0, errors.New("no KBFS keys available")
}
return info.LegacyGeneration, nil
}
func (t TeamSigChainState) makeHiddenRatchet(mctx libkb.MetaContext) (ret *hidden.Ratchet, err error) {
return hidden.MakeRatchet(mctx, t.hidden)
}
func (t TeamSigChainState) GetUserRole(user keybase1.UserVersion) (keybase1.TeamRole, error) {
return t.getUserRole(user), nil
}
// Get the user's role right after link at seqno was processed.
func (t TeamSigChainState) GetUserRoleAtSeqno(user keybase1.UserVersion, seqno keybase1.Seqno) (keybase1.TeamRole, error) {
role := keybase1.TeamRole_NONE
if seqno <= 0 {
return role, fmt.Errorf("seqno %v is less than 1", seqno)
}
for _, point := range t.inner.UserLog[user] {
if point.SigMeta.SigChainLocation.Seqno > seqno {
return role, nil
}
role = point.Role
}
return role, nil
}
func (t TeamSigChainState) MemberCtime(user keybase1.UserVersion) *keybase1.Time {
points := t.inner.UserLog[user]
if len(points) == 0 {
return nil
}
// see if the user ever left the team so we return their most recent join
// time.
for i := len(points) - 1; i > 0; i-- {
// if we left the team at some point, return our later join time
if points[i].Role == keybase1.TeamRole_NONE {
if i < len(points)-1 && points[i+1].Role != keybase1.TeamRole_NONE {
return &points[i+1].SigMeta.Time
}
}
}
// we never left the team, give our original join time.
return &points[0].SigMeta.Time
}
func (t TeamSigChainState) GetUserLogPoint(user keybase1.UserVersion) *keybase1.UserLogPoint {
points := t.inner.UserLog[user]
if len(points) == 0 {
return nil
}
tmp := points[len(points)-1].DeepCopy()
return &tmp
}
func (t TeamSigChainState) GetAdminUserLogPoint(user keybase1.UserVersion) *keybase1.UserLogPoint {
ret := t.GetUserLogPoint(user)
if ret == nil {
return nil
}
if ret.Role != keybase1.TeamRole_ADMIN && ret.Role != keybase1.TeamRole_OWNER {
return nil
}
return ret
}
func (t TeamSigChainState) getUserRole(user keybase1.UserVersion) keybase1.TeamRole {
return t.inner.UserRole(user)
}
func (t TeamSigChainState) GetUserLastJoinTime(user keybase1.UserVersion) (time keybase1.Time, err error) {
return t.inner.GetUserLastJoinTime(user)
}
// GetUserLastRoleChangeTime returns the time of the last role change for user
// in team. If the user left the team as a last change, the time of such leave
// event is returned. If the user was never in the team, then this function
// returns time=0 and wasMember=false.
func (t TeamSigChainState) GetUserLastRoleChangeTime(user keybase1.UserVersion) (time keybase1.Time, wasMember bool) {
return t.inner.GetUserLastRoleChangeTime(user)
}
// NewStyle invites are completed in the `used_invites` field in the change
// membership link, can optionally specify an expiration time, and a maximum
// number of uses (potentially infinite).
func IsNewStyleInvite(invite keybase1.TeamInvite) (bool, error) {
return invite.MaxUses != nil, nil
}
// assertBecameAdminAt asserts that the user (uv) became admin at the SigChainLocation given.
// Figure out when this admin permission was revoked, if at all. If the promotion event
// wasn't found as specified, then return an AdminPermissionError. In addition, we return
// a bookend object, in the success case, to convey when the adminship was downgraded, if at all.
func (t TeamSigChainState) assertBecameAdminAt(uv keybase1.UserVersion, scl keybase1.SigChainLocation) (ret proofTermBookends, err error) {
points := t.inner.UserLog[uv]
linkMap := t.inner.LinkIDs
for i := len(points) - 1; i >= 0; i-- {
point := points[i]
if point.SigMeta.SigChainLocation.Eq(scl) {
if !point.Role.IsAdminOrAbove() {
return ret, NewAdminPermissionError(t.GetID(), uv, "not admin permission")
}
ret.left = newProofTerm(t.GetID().AsUserOrTeam(), point.SigMeta, linkMap)
r := findRoleDowngrade(points[(i+1):], keybase1.TeamRole_ADMIN)
if r != nil {
tmp := newProofTerm(t.GetID().AsUserOrTeam(), *r, linkMap)
ret.right = &tmp
}
return ret, nil
}
}
return ret, NewAdminPermissionError(t.GetID(), uv, "not found")
}
// Find a point where the role is taken away.
func findRoleDowngrade(points []keybase1.UserLogPoint, role keybase1.TeamRole) *keybase1.SignatureMetadata {
for _, p := range points {
if !p.Role.IsOrAbove(role) {
return &p.SigMeta
}
}
return nil
}
// AssertWasRoleOrAboveAt asserts that user `uv` had `role` or above on the
// team just after the given SigChainLocation `scl`.
// We start at the point given, go backwards until we find a promotion,
// then go forwards to make sure there wasn't a demotion before the specified time.
// If there was, return a PermissionError. If no adminship was found at all, return a PermissionError.
func (t TeamSigChainState) AssertWasRoleOrAboveAt(uv keybase1.UserVersion,
role keybase1.TeamRole, scl keybase1.SigChainLocation) (err error) {
mkErr := func(format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
if role.IsOrAbove(keybase1.TeamRole_ADMIN) {
return NewAdminPermissionError(t.GetID(), uv, msg)
}
return NewPermissionError(t.GetID(), uv, msg)
}
if scl.Seqno < keybase1.Seqno(0) {
return mkErr("negative seqno: %v", scl.Seqno)
}
points := t.inner.UserLog[uv]
for i := len(points) - 1; i >= 0; i-- {
point := points[i]
if err := point.SigMeta.SigChainLocation.Comparable(scl); err != nil {
return mkErr(err.Error())
}
if point.SigMeta.SigChainLocation.LessThanOrEqualTo(scl) && point.Role.IsOrAbove(role) {
// OK great, we found a point with the role in the log that's less than or equal to the given one.
// But now we reverse and go forward, and check that it wasn't revoked or downgraded.
// If so, that's a problem!
if right := findRoleDowngrade(points[(i+1):], role); right != nil && right.SigChainLocation.LessThanOrEqualTo(scl) {
return mkErr("%v permission was downgraded too soon!", role)
}
return nil
}
}
return mkErr("%v role point not found", role)
}
func (t TeamSigChainState) AssertWasWriterAt(uv keybase1.UserVersion, scl keybase1.SigChainLocation) (err error) {
return t.AssertWasRoleOrAboveAt(uv, keybase1.TeamRole_WRITER, scl)
}
func (t TeamSigChainState) AssertWasAdminAt(uv keybase1.UserVersion, scl keybase1.SigChainLocation) (err error) {
return t.AssertWasRoleOrAboveAt(uv, keybase1.TeamRole_ADMIN, scl)
}
func (t TeamSigChainState) GetUsersWithRole(role keybase1.TeamRole) (res []keybase1.UserVersion, err error) {
if role == keybase1.TeamRole_NONE {
return nil, errors.New("cannot get users with NONE role")
}
for uv := range t.inner.UserLog {
if t.getUserRole(uv) == role {
res = append(res, uv)
}
}
return res, nil
}
func (t TeamSigChainState) GetUsersWithRoleOrAbove(role keybase1.TeamRole) (res []keybase1.UserVersion, err error) {
if role == keybase1.TeamRole_NONE {
return nil, errors.New("cannot get users with NONE role")
}
for uv := range t.inner.UserLog {
if t.getUserRole(uv).IsOrAbove(role) {
res = append(res, uv)
}
}
return res, nil
}
func (t TeamSigChainState) GetLatestUVWithUID(uid keybase1.UID) (res keybase1.UserVersion, err error) {
found := false
for uv := range t.inner.UserLog {
if uv.Uid == uid && t.getUserRole(uv) != keybase1.TeamRole_NONE && (!found || res.EldestSeqno < uv.EldestSeqno) {
res = uv
found = true
}
}
if !found {
return res, errors.New("did not find user with given uid")
}
return res.DeepCopy(), nil
}
func (t TeamSigChainState) GetAllUVsWithUID(uid keybase1.UID) (res []keybase1.UserVersion) {
for uv := range t.inner.UserLog {
if uv.Uid == uid && t.getUserRole(uv) != keybase1.TeamRole_NONE {
res = append(res, uv)
}
}
return res
}
func (t TeamSigChainState) GetAllUVs() (res []keybase1.UserVersion) {
return t.inner.GetAllUVs()
}
func (t TeamSigChainState) GetLatestPerTeamKey(mctx libkb.MetaContext) (res keybase1.PerTeamKey, err error) {
res, _, err = t.getLatestPerTeamKeyWithMerkleSeqno(mctx)
return res, err
}
func (t TeamSigChainState) getLatestPerTeamKeyWithMerkleSeqno(mctx libkb.MetaContext) (res keybase1.PerTeamKey, mr keybase1.MerkleRootV2, err error) {
var hk *keybase1.PerTeamKey
if t.hidden != nil {
hk = t.hidden.MaxReaderPerTeamKey()
}
var ok bool
res, ok = t.inner.PerTeamKeys[t.inner.MaxPerTeamKeyGeneration]
if hk == nil && ok {
return res, t.inner.MerkleRoots[res.Seqno], nil
}
if !ok && hk != nil {
return *hk, t.hidden.MerkleRoots[hk.Seqno], nil
}
if !ok && hk == nil {
// if this happens it's a programming error
mctx.Debug("PTK not found error debug dump: inner %+v", t.inner)
if t.hidden != nil {
mctx.Debug("PTK not found error debug dump: hidden: %+v", *t.hidden)
}
return res, mr, fmt.Errorf("per-team-key not found for latest generation %d", t.inner.MaxPerTeamKeyGeneration)
}
if hk.Gen > res.Gen {
return *hk, t.hidden.MerkleRoots[hk.Seqno], nil
}
return res, t.inner.MerkleRoots[res.Seqno], nil
}
// checkNewPTK takes an existing state (t) and checks that a new PTK found (ptk) doesn't clash
// against any PTKs already in the state.
func (t *TeamSigChainState) checkNewPTK(ptk SCPerTeamKey) error {
// If there was no prior state, then the new PTK is OK
if t == nil {
return nil
}
gen := ptk.Generation
chk := func(existing keybase1.PerTeamKey, found bool) error {
if !found {
return nil
}
if !existing.SigKID.Equal(ptk.SigKID) || !existing.EncKID.Equal(ptk.EncKID) {
return fmt.Errorf("PTK clash at generation %d", gen)
}
return nil
}
if t.hidden != nil {
tmp, found := t.hidden.GetReaderPerTeamKeyAtGeneration(gen)
if err := chk(tmp, found); err != nil {
return err
}
}
tmp, found := t.inner.PerTeamKeys[gen]
if err := chk(tmp, found); err != nil {
return err
}
return nil
}
func (t *TeamSigChainState) GetLatestPerTeamKeyCTime() keybase1.UnixTime {
return t.inner.PerTeamKeyCTime
}
func (t TeamSigChainState) GetPerTeamKeyAtGeneration(gen keybase1.PerTeamKeyGeneration) (keybase1.PerTeamKey, error) {
res, ok := t.inner.PerTeamKeys[gen]
if ok {
return res, nil
}
res, ok = t.hidden.GetReaderPerTeamKeyAtGeneration(gen)
if ok {
return res, nil
}
return keybase1.PerTeamKey{}, libkb.NotFoundError{Msg: fmt.Sprintf("per-team-key not found for generation %d", gen)}
}
func (t TeamSigChainState) HasAnyStubbedLinks() bool {
for _, v := range t.inner.StubbedLinks {
if v {
return true
}
}
return false
}
// Whether the link has been processed and is not stubbed.
func (t TeamSigChainState) IsLinkFilled(seqno keybase1.Seqno) bool {
if seqno > t.inner.LastSeqno {
return false
}
if seqno < 0 {
return false
}
return !t.inner.StubbedLinks[seqno]
}
func (t TeamSigChainState) HasStubbedSeqno(seqno keybase1.Seqno) bool {
return t.inner.StubbedLinks[seqno]
}
func (t TeamSigChainState) GetSubteamName(id keybase1.TeamID) (*keybase1.TeamName, error) {
lastPoint := t.getLastSubteamPoint(id)
if lastPoint != nil {
return &lastPoint.Name, nil
}
return nil, fmt.Errorf("subteam not found: %v", id.String())
}
// Inform the UserLog and Bots of a user's role.
// Mutates the UserLog and Bots.
// Must be called with seqno's and events in correct order.
func (t *TeamSigChainState) inform(u keybase1.UserVersion, role keybase1.TeamRole, sigMeta keybase1.SignatureMetadata) {
t.inner.UserLog[u] = append(t.inner.UserLog[u], keybase1.UserLogPoint{
Role: role,
SigMeta: sigMeta,
})
// Clear an entry in Bots if any
if !role.IsRestrictedBot() {
delete(t.inner.Bots, u)
}
}
func (t *TeamSigChainState) informNewInvite(i keybase1.TeamInvite, teamSigMeta keybase1.TeamSignatureMetadata) {
t.inner.InviteMetadatas[i.Id] = keybase1.NewTeamInviteMetadata(i, teamSigMeta)
}
func (t *TeamSigChainState) informCanceledInvite(i keybase1.TeamInviteID,
cancelTeamSigMeta keybase1.TeamSignatureMetadata) {
inviteMD, ok := t.inner.InviteMetadatas[i]
if !ok {
return
}
inviteMD.Status = keybase1.NewTeamInviteMetadataStatusWithCancelled(keybase1.TeamInviteMetadataCancel{
TeamSigMeta: cancelTeamSigMeta,
})
t.inner.InviteMetadatas[i] = inviteMD
}
func (t *TeamSigChainState) informCompletedInvite(i keybase1.TeamInviteID,
completeTeamSigMeta keybase1.TeamSignatureMetadata) {
inviteMD, ok := t.inner.InviteMetadatas[i]
if !ok {
return
}
inviteMD.Status = keybase1.NewTeamInviteMetadataStatusWithCompleted(keybase1.TeamInviteMetadataCompleted{
TeamSigMeta: completeTeamSigMeta,
})
t.inner.InviteMetadatas[i] = inviteMD
}
func (t *TeamSigChainState) getLastSubteamPoint(id keybase1.TeamID) *keybase1.SubteamLogPoint {
if len(t.inner.SubteamLog[id]) > 0 {
return &t.inner.SubteamLog[id][len(t.inner.SubteamLog[id])-1]
}
return nil
}
// Inform the SubteamLog of a subteam name change.
// Links must be added in order by seqno for each subteam (asserted here).
// Links for different subteams can interleave.
// Mutates the SubteamLog.
// Name collisions are allowed here. They are allowed because you might
// be removed a subteam and then its future name changes and deletion would be stubbed.
// See ListSubteams for details.
func (t *TeamSigChainState) informSubteam(id keybase1.TeamID, name keybase1.TeamName, seqno keybase1.Seqno) error {
lastPoint := t.getLastSubteamPoint(id)
if lastPoint != nil && lastPoint.Seqno.Eq(seqno) {
return fmt.Errorf("re-entry into subteam log for seqno: %v", seqno)
}
if lastPoint != nil && seqno < lastPoint.Seqno {
return fmt.Errorf("cannot add to subteam log out of order: %v < %v", seqno, lastPoint.Seqno)
}
if lastPoint != nil && lastPoint.Name.IsNil() {
return fmt.Errorf("cannot process subteam rename because %v was deleted at seqno %v", id, lastPoint.Seqno)
}
t.inner.SubteamLog[id] = append(t.inner.SubteamLog[id], keybase1.SubteamLogPoint{
Name: name,
Seqno: seqno,
})
return nil
}
// Inform the SubteamLog of a subteam deletion.
// Links must be added in order by seqno for each subteam (asserted here).
// Links for different subteams can interleave.
// Mutates the SubteamLog.
func (t *TeamSigChainState) informSubteamDelete(id keybase1.TeamID, seqno keybase1.Seqno) error {
lastPoint := t.getLastSubteamPoint(id)
if lastPoint != nil && lastPoint.Seqno.Eq(seqno) {
return fmt.Errorf("re-entry into subteam log for seqno: %v", seqno)
}
if lastPoint != nil && seqno < lastPoint.Seqno {
return fmt.Errorf("cannot add to subteam log out of order: %v < %v", seqno, lastPoint.Seqno)
}
// Don't check for deleting the same team twice. Just allow it.
t.inner.SubteamLog[id] = append(t.inner.SubteamLog[id], keybase1.SubteamLogPoint{
Seqno: seqno,
})
return nil
}
// Only call this on a Team that has been loaded with NeedAdmin.
// Otherwise, you might get incoherent answers due to links that
// were stubbed over the life of the cached object.
//
// For subteams that you were removed from, this list may
// still include them because your removal was stubbed.
// The list will not contain duplicate names.
// Since this should only be called when you are an admin,
// none of that should really come up, but it's here just to be less fragile.
func (t *TeamSigChainState) ListSubteams() (res []keybase1.TeamIDAndName) {
return t.inner.ListSubteams()
}
// Check that a subteam rename occurred just so.
// That the subteam `subteamID` got a new name `newName` at exactly `seqno` in this,
// the parent, chain.
// Note this only checks against the last part of `newName` because mid-team renames are such a pain.
// This is currently linear in the number of times that subteam has been renamed.
// It should be easy to add an index if need be.
func (t *TeamSigChainState) SubteamRenameOccurred(
subteamID keybase1.TeamID, newName keybase1.TeamName, seqno keybase1.Seqno) error {
points := t.inner.SubteamLog[subteamID]
if len(points) == 0 {
return fmt.Errorf("subteam %v has no name log", subteamID)
}
for _, point := range points {
if point.Seqno == seqno {
if point.Name.LastPart().Eq(newName.LastPart()) {
// found it!
return nil
}
}
if point.Seqno > seqno {
break
}
}
return fmt.Errorf("subteam %v did not have rename entry in log: %v %v",
subteamID, newName, seqno)
}
func (t *TeamSigChainState) ActiveInvites() (ret []keybase1.TeamInviteMetadata) {
for _, md := range t.inner.InviteMetadatas {
if code, err := md.Status.Code(); err == nil &&
code == keybase1.TeamInviteMetadataStatusCode_ACTIVE {
ret = append(ret, md)
}
}
return ret
}
func (t *TeamSigChainState) NumActiveInvites() int {
return len(t.ActiveInvites())
}
func (t *TeamSigChainState) HasActiveInvite(name keybase1.TeamInviteName, typ keybase1.TeamInviteType) (bool, error) {
i, err := t.FindActiveInvite(name, typ)
if err != nil {
if _, ok := err.(libkb.NotFoundError); ok {
return false, nil
}
return false, err
}
if i != nil {
return true, nil
}
return false, nil
}
func (t *TeamSigChainState) FindActiveInvite(name keybase1.TeamInviteName, typ keybase1.TeamInviteType) (*keybase1.TeamInvite, error) {
for _, inviteMD := range t.ActiveInvites() {
if inviteMD.Invite.Name == name && inviteMD.Invite.Type.Eq(typ) {
return &inviteMD.Invite, nil
}
}
return nil, libkb.NotFoundError{}
}
func (t *TeamSigChainState) FindActiveInviteString(mctx libkb.MetaContext, name string, typ string) (ret keybase1.TeamInvite, err error) {
itype, err := TeamInviteTypeFromString(mctx, typ)
if err != nil {
return ret, err
}
invPtr, err := t.FindActiveInvite(keybase1.TeamInviteName(name), itype)
switch {
case err != nil:
return ret, err
case invPtr == nil:
return ret, libkb.NotFoundError{}
}
return *invPtr, nil
}
// FindActiveInviteMDByID returns potentially expired invites that have not been
// explicitly cancelled, since the sigchain player is agnostic to the concept
// of time. We treat invite expiration times as advisory for admin clients
// completing invites, but do not check them in the sigchain player.
func (t *TeamSigChainState) FindActiveInviteMDByID(
id keybase1.TeamInviteID) (inviteMD keybase1.TeamInviteMetadata, found bool) {
res, found := t.inner.InviteMetadatas[id]
if !found {
return inviteMD, false
}
code, err := res.Status.Code()
if err != nil {
return inviteMD, false
}
if code != keybase1.TeamInviteMetadataStatusCode_ACTIVE {
return inviteMD, false
}
return res, true
}
func (t *TeamSigChainState) IsInviteObsolete(id keybase1.TeamInviteID) bool {
inviteMD, found := t.inner.InviteMetadatas[id]
if !found {
return false
}
code, err := inviteMD.Status.Code()
if err != nil {
return false
}
return code == keybase1.TeamInviteMetadataStatusCode_OBSOLETE
}
// FindActiveKeybaseInvite finds and returns a Keybase-type
// invite for given UID. Ordering here is not guaranteed, caller
// shouldn't assume that returned invite will be the oldest/newest one
// for the UID.
func (t *TeamSigChainState) FindActiveKeybaseInvite(uid keybase1.UID) (keybase1.TeamInvite, keybase1.UserVersion, bool) {
for _, inviteMD := range t.ActiveInvites() {
if inviteUv, err := inviteMD.Invite.KeybaseUserVersion(); err == nil {
if inviteUv.Uid.Equal(uid) {
return inviteMD.Invite, inviteUv, true
}
}
}
return keybase1.TeamInvite{}, keybase1.UserVersion{}, false
}
func (t *TeamSigChainState) GetMerkleRoots() map[keybase1.Seqno]keybase1.MerkleRootV2 {
return t.inner.MerkleRoots
}
func (t TeamSigChainState) TeamBotSettings() map[keybase1.UserVersion]keybase1.TeamBotSettings {
return t.inner.Bots
}
// --------------------------------------------------
// AppendChainLink process a chain link.
// It must have already been partially verified by TeamLoader.
// `reader` is the user who is processing the chain.
// `state` is moved into this function. There must exist no live references into it from now on.
// If `state` is nil this is the first link of the chain.
// `signer` may be nil iff link is stubbed.
func AppendChainLink(ctx context.Context, g *libkb.GlobalContext, reader keybase1.UserVersion, state *TeamSigChainState,
link *ChainLinkUnpacked, signer *SignerX) (res TeamSigChainState, err error) {
t := &teamSigchainPlayer{
Contextified: libkb.NewContextified(g),
reader: reader,
}
var latestSeqno keybase1.Seqno
if state != nil {
latestSeqno = state.GetLatestSeqno()
}
res, err = t.appendChainLinkHelper(libkb.NewMetaContext(ctx, g), state, link, signer)
if err != nil {
return TeamSigChainState{}, NewAppendLinkError(link, latestSeqno, err)
}
return res, err
}
// InflateLink adds the full inner link for a link that has already been added in stubbed form.
// `state` is moved into this function. There must exist no live references into it from now on.
func InflateLink(ctx context.Context, g *libkb.GlobalContext, reader keybase1.UserVersion, state TeamSigChainState,
link *ChainLinkUnpacked, signer SignerX) (res TeamSigChainState, err error) {
if link.isStubbed() {
return TeamSigChainState{}, NewStubbedError(link)
}
if link.Seqno() > state.GetLatestSeqno() {
return TeamSigChainState{}, NewInflateErrorWithNote(link,
fmt.Sprintf("seqno off the chain %v > %v", link.Seqno(), state.GetLatestSeqno()))
}
// Check the that the link id matches our stubbed record.
seenLinkID, err := state.GetLibkbLinkIDBySeqno(link.Seqno())
if err != nil {
return TeamSigChainState{}, err
}
if !seenLinkID.Eq(link.LinkID()) {
return TeamSigChainState{}, NewInflateErrorWithNote(link,
fmt.Sprintf("link id mismatch: %v != %v", link.LinkID().String(), seenLinkID.String()))
}
// Check that the link has not already been inflated.
if _, ok := state.inner.StubbedLinks[link.Seqno()]; !ok {
return TeamSigChainState{}, NewInflateErrorWithNote(link, "already inflated")
}
t := &teamSigchainPlayer{
Contextified: libkb.NewContextified(g),
reader: reader,
}
iRes, err := t.addInnerLink(libkb.NewMetaContext(ctx, g), &state, link, signer, true)
if err != nil {
return TeamSigChainState{}, err
}
delete(iRes.newState.inner.StubbedLinks, link.Seqno())
return iRes.newState, nil
}
// Helper struct for playing sigchains.
type teamSigchainPlayer struct {
libkb.Contextified
reader keybase1.UserVersion // the user processing the chain
}
// Add a chain link to the end.
// `prevState` is moved into this function. There must exist no live references into it from now on.
// `signer` may be nil iff link is stubbed.
// If `prevState` is nil this is the first chain link.
func (t *teamSigchainPlayer) appendChainLinkHelper(
mctx libkb.MetaContext, prevState *TeamSigChainState, link *ChainLinkUnpacked, signer *SignerX) (
res TeamSigChainState, err error) {
err = t.checkOuterLink(mctx.Ctx(), prevState, link)
if err != nil {
return res, fmt.Errorf("team sigchain outer link: %s", err)
}
var newState *TeamSigChainState
if link.isStubbed() {
if prevState == nil {
return res, NewStubbedErrorWithNote(link, "first link cannot be stubbed")
}
newState2 := prevState.DeepCopy()
newState = &newState2
} else {
if signer == nil || !signer.signer.Uid.Exists() {
return res, NewInvalidLink(link, "signing user not provided for team link")
}
iRes, err := t.addInnerLink(mctx, prevState, link, *signer, false)
if err != nil {
return res, err
}
newState = &iRes.newState
}
newState.inner.LastSeqno = link.Seqno()
newState.inner.LastLinkID = link.LinkID().Export()
newState.inner.LinkIDs[link.Seqno()] = link.LinkID().Export()
if link.isStubbed() {
newState.inner.StubbedLinks[link.Seqno()] = true
}
// Store the head merkle sequence to the DB, for use in the audit mechanism.
// For the purposes of testing, we disable this feature, so we can check
// the lazy-repopulation scheme for old stored teams (without a full cache bust).
if link.Seqno() == keybase1.Seqno(1) && !link.isStubbed() && !t.G().Env.Test.TeamNoHeadMerkleStore {
tmp := link.inner.Body.MerkleRoot.ToMerkleRootV2()
newState.inner.HeadMerkle = &tmp
}
if !link.isStubbed() && newState.inner.MerkleRoots != nil {
newState.inner.MerkleRoots[link.Seqno()] = link.inner.Body.MerkleRoot.ToMerkleRootV2()
}
return *newState, nil
}
func (t *teamSigchainPlayer) checkOuterLink(ctx context.Context, prevState *TeamSigChainState, link *ChainLinkUnpacked) (err error) {
if prevState == nil {
if link.Seqno() != 1 {
return NewUnexpectedSeqnoError(keybase1.Seqno(1), link.Seqno())
}
} else {
if link.Seqno() != prevState.inner.LastSeqno+1 {
return NewUnexpectedSeqnoError(prevState.inner.LastSeqno+1, link.Seqno())
}
}
if prevState == nil {
if len(link.Prev()) != 0 {
return fmt.Errorf("expected outer nil prev but got:%s", link.Prev())
}
} else {
prevStateLastLinkID, err := libkb.ImportLinkID(prevState.inner.LastLinkID)
if err != nil {
return fmt.Errorf("invalid prev last link id: %v", err)
}
if !link.Prev().Eq(prevStateLastLinkID) {
return fmt.Errorf("wrong outer prev: %s != %s", link.Prev(), prevState.inner.LastLinkID)
}
}
return nil
}
type checkInnerLinkResult struct {
newState TeamSigChainState
}
// Check and add the inner link.
// `isInflate` is false if this is a new link and true if it is a link which has already been added as stubbed.
// Does not modify `prevState` but returns a new state.
func (t *teamSigchainPlayer) addInnerLink(mctx libkb.MetaContext,
prevState *TeamSigChainState, link *ChainLinkUnpacked, signer SignerX,
isInflate bool) (res checkInnerLinkResult, err error) {
if link.inner == nil {
return res, NewStubbedError(link)
}
payload := *link.inner
if !signer.signer.Uid.Exists() {
return res, NewInvalidLink(link, "empty link signer")
}
// This may be superfluous.
err = link.AssertInnerOuterMatch()
if err != nil {
return res, err
}
// completely ignore these fields
_ = payload.ExpireIn
_ = payload.SeqType
if payload.Tag != "signature" {
return res, NewInvalidLink(link, "unrecognized tag: '%s'", payload.Tag)
}
if payload.Body.Team == nil {
return res, NewInvalidLink(link, "missing team section")
}
team := payload.Body.Team
if len(team.ID) == 0 {
return res, NewInvalidLink(link, "missing team id")
}
teamID, err := keybase1.TeamIDFromString(string(team.ID))
if err != nil {
return res, err
}
if teamID.IsPublic() != team.Public {
return res, fmt.Errorf("link specified public:%v but ID is public:%v",
team.Public, teamID.IsPublic())
}
if prevState != nil && !prevState.inner.Id.Equal(teamID) {
return res, fmt.Errorf("wrong team id: %s != %s", teamID.String(), prevState.inner.Id.String())
}
if prevState != nil && prevState.IsImplicit() != team.Implicit {
return res, fmt.Errorf("link specified implicit:%v but team was already implicit:%v",
team.Implicit, prevState.IsImplicit())
}
if prevState != nil && prevState.IsPublic() != team.Public {
return res, fmt.Errorf("link specified public:%v but team was already public:%v",
team.Implicit, prevState.IsImplicit())
}
if team.Public && (!team.Implicit || (prevState != nil && !prevState.IsImplicit())) {
return res, fmt.Errorf("public non-implicit teams are not supported")
}
err = t.checkSeqnoToAdd(prevState, link.Seqno(), isInflate)
if err != nil {
return res, err
}
// When isInflate then it is likely prevSeqno != prevState.GetLatestSeqno()
prevSeqno := link.Seqno() - 1
allowInflate := func(allow bool) error {
if isInflate && !allow {
return fmt.Errorf("inflating link type not supported: %v", payload.Body.Type)
}
return nil
}
allowInImplicitTeam := func(allow bool) error {
if team.Implicit && !allow {
return NewImplicitTeamOperationError(payload.Body.Type)
}
return nil
}
enforceFirstInChain := func(firstInChain bool) error {
if firstInChain {
if prevState != nil {
return fmt.Errorf("link type '%s' unexpected at seqno:%v", payload.Body.Type, prevState.inner.LastSeqno+1)
}
} else {
if prevState == nil {
return fmt.Errorf("link type '%s' unexpected at beginning", payload.Body.Type)
}
}
return nil
}
enforceGeneric := func(name string, rule Tristate, hasReal bool) error {
switch rule {
case TristateDisallow:
if hasReal {
return fmt.Errorf("sigchain link contains unexpected '%s'", name)
}
case TristateRequire:
if !hasReal {
return fmt.Errorf("sigchain link missing %s", name)
}
case TristateOptional:
default:
return fmt.Errorf("unsupported tristate (fault): %v", rule)
}
return nil
}
enforce := func(rules LinkRules) error {
return libkb.PickFirstError(
enforceGeneric("name", rules.Name, team.Name != nil),
enforceGeneric("members", rules.Members, team.Members != nil),
enforceGeneric("parent", rules.Parent, team.Parent != nil),
enforceGeneric("subteam", rules.Subteam, team.Subteam != nil),
enforceGeneric("per-team-key", rules.PerTeamKey, team.PerTeamKey != nil),
enforceGeneric("admin", rules.Admin, team.Admin != nil),
enforceGeneric("invites", rules.Invites, team.Invites != nil),
enforceGeneric("completed-invites", rules.CompletedInvites, team.CompletedInvites != nil),
enforceGeneric("settings", rules.Settings, team.Settings != nil),
enforceGeneric("kbfs", rules.KBFS, team.KBFS != nil),
enforceGeneric("box-summary-hash", rules.BoxSummaryHash, team.BoxSummaryHash != nil),
enforceGeneric("bot_settings", rules.BotSettings, team.BotSettings != nil),
allowInImplicitTeam(rules.AllowInImplicitTeam),
allowInflate(rules.AllowInflate),
enforceFirstInChain(rules.FirstInChain),
)
}
checkAdmin := func(op string) (signerIsExplicitOwner bool, err error) {