forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
1608 lines (1419 loc) · 48.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"
"strconv"
"strings"
"sync"
"golang.org/x/net/context"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
jsonw "github.com/keybase/go-jsonw"
)
// Create a new user/version pair.
func NewUserVersion(uid keybase1.UID, eldestSeqno keybase1.Seqno) keybase1.UserVersion {
return keybase1.UserVersion{
Uid: uid,
EldestSeqno: eldestSeqno,
}
}
func ParseUserVersion(s string) (res keybase1.UserVersion, err error) {
parts := strings.Split(s, "%")
if len(parts) == 1 {
// default to seqno 1
parts = append(parts, "1")
}
if len(parts) != 2 {
return res, fmt.Errorf("invalid user version: %s", s)
}
uid, err := libkb.UIDFromHex(parts[0])
if err != nil {
return res, err
}
eldestSeqno, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return res, fmt.Errorf("invalid eldest seqno: %s", err)
}
return keybase1.UserVersion{
Uid: uid,
EldestSeqno: keybase1.Seqno(eldestSeqno),
}, nil
}
const TeamSigChainPlayerSupportedLinkVersion = 2
// Accessor wrapper for keybase1.TeamSigChainState
type TeamSigChainState struct {
inner keybase1.TeamSigChainState
}
func (t TeamSigChainState) DeepCopy() TeamSigChainState {
return TeamSigChainState{
inner: t.inner.DeepCopy(),
}
}
func (t TeamSigChainState) GetID() keybase1.TeamID {
return t.inner.Id
}
func (t TeamSigChainState) IsSubteam() bool {
return t.inner.ParentID != nil
}
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) GetLatestLinkID() keybase1.LinkID {
return t.inner.LastLinkID
}
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 {
return keybase1.PerTeamKeyGeneration(len(t.inner.PerTeamKeys))
}
func (t TeamSigChainState) GetUserRole(user keybase1.UserVersion) (keybase1.TeamRole, error) {
return t.getUserRole(user), nil
}
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 {
points := t.inner.UserLog[user]
if len(points) == 0 {
return keybase1.TeamRole_NONE
}
role := points[len(points)-1].Role
return role
}
// 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 := findAdminDowngrade(points[(i + 1):])
if r != nil {
tmp := newProofTerm(t.GetID().AsUserOrTeam(), *r, linkMap)
ret.right = &tmp
}
return ret, nil
}
}
return ret, NewAdminPermissionError(t.GetID(), uv, "not found")
}
func findAdminDowngrade(points []keybase1.UserLogPoint) *keybase1.SignatureMetadata {
for _, p := range points {
if !p.Role.IsAdminOrAbove() {
return &p.SigMeta
}
}
return nil
}
func findReaderDowngrade(points []keybase1.UserLogPoint) *keybase1.SignatureMetadata {
for _, p := range points {
if !p.Role.IsReaderOrAbove() {
return &p.SigMeta
}
}
return nil
}
// AssertWasReaderAt asserts that user (uv) was a reader or above at the team at the given
// SigChainLocation (scl). Thus, we start at the point given, go backwards until we find a promotion,
// the go forwards to make sure there wasn't a demotion before the specified time. If there
// was, we return a PermissionError. If no adminship was found at all, we return a PermissionError.
// NOTE: This is a copy-pasta of AssertWasAdminAt, but I became sad about having to factor out
// the commonality, so decided copy-paste was easiest.
func (t TeamSigChainState) AssertWasReaderAt(uv keybase1.UserVersion, scl keybase1.SigChainLocation) (err error) {
points := t.inner.UserLog[uv]
for i := len(points) - 1; i >= 0; i-- {
point := points[i]
// OK great, we found an admin point in the log that's less than or equal to the
// given one
if point.SigMeta.SigChainLocation.LessThanOrEqualTo(scl) && point.Role.IsReaderOrAbove() {
// But now we reverse and go forward, and check that it wasn't revoked or downgraded.
// If so, that's a problem!
if right := findReaderDowngrade(points[(i + 1):]); right != nil && right.SigChainLocation.LessThanOrEqualTo(scl) {
return NewPermissionError(t.GetID(), uv, "permission was downgraded too soon!")
}
return nil
}
}
return NewPermissionError(t.GetID(), uv, "not found")
}
// AssertWasAdminAt asserts that user (uv) was an admin (or owner) at the team at the given
// SigChainLocation (scl). Thus, we start at the point given, go backwards until we find a promotion,
// the go forwards to make sure there wasn't a demotion before the specified time. If there
// was, we return an AdminPermissionError. If no adminship was found at all, we return a AdminPermissionError.
func (t TeamSigChainState) AssertWasAdminAt(uv keybase1.UserVersion, scl keybase1.SigChainLocation) (err error) {
points := t.inner.UserLog[uv]
for i := len(points) - 1; i >= 0; i-- {
point := points[i]
// OK great, we found an admin point in the log that's less than or equal to the
// given one
if point.SigMeta.SigChainLocation.LessThanOrEqualTo(scl) && point.Role.IsAdminOrAbove() {
// But now we reverse and go forward, and check that it wasn't revoked or downgraded.
// If so, that's a problem!
if right := findAdminDowngrade(points[(i + 1):]); right != nil && right.SigChainLocation.LessThanOrEqualTo(scl) {
return NewAdminPermissionError(t.GetID(), uv, "admin permission was downgraded too soon!")
}
return nil
}
}
return NewAdminPermissionError(t.GetID(), uv, "not found")
}
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) GetLatestPerTeamKey() (keybase1.PerTeamKey, error) {
res, ok := t.inner.PerTeamKeys[keybase1.PerTeamKeyGeneration(len(t.inner.PerTeamKeys))]
if !ok {
// if this happens it's a programming error
return res, errors.New("per-team-key not found")
}
return res, nil
}
func (t TeamSigChainState) GetPerTeamKeyAtGeneration(gen keybase1.PerTeamKeyGeneration) (keybase1.PerTeamKey, error) {
res, ok := t.inner.PerTeamKeys[gen]
if !ok {
return keybase1.PerTeamKey{}, libkb.NotFoundError{Msg: fmt.Sprintf("per-team-key not found for generation %d", gen)}
}
return res, nil
}
func (t TeamSigChainState) HasAnyStubbedLinks() bool {
for _, v := range t.inner.StubbedLinks {
if v {
return true
}
}
return false
}
func (t TeamSigChainState) IsLinkFullyPresent(seqno keybase1.Seqno) bool {
if seqno > t.inner.LastSeqno {
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 of a user's role.
// Mutates the UserLog.
// Must be called with seqno's and events in correct order.
// Idempotent if called correctly.
func (t *TeamSigChainState) inform(u keybase1.UserVersion, role keybase1.TeamRole, sigMeta keybase1.SignatureMetadata) {
currentRole := t.getUserRole(u)
if currentRole == role {
// no change in role, now new checkpoint needed
return
}
t.inner.UserLog[u] = append(t.inner.UserLog[u], keybase1.UserLogPoint{
Role: role,
SigMeta: sigMeta,
})
}
func (t *TeamSigChainState) informNewInvite(i keybase1.TeamInvite) {
t.inner.ActiveInvites[i.Id] = i
}
func (t *TeamSigChainState) informCanceledInvite(i keybase1.TeamInviteID) {
delete(t.inner.ActiveInvites, i)
}
func (t *TeamSigChainState) informCompletedInvite(i keybase1.TeamInviteID) {
delete(t.inner.ActiveInvites, i)
}
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
}
type TeamIDAndName struct {
ID keybase1.TeamID
Name keybase1.TeamName
}
// 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 []TeamIDAndName) {
type Entry struct {
ID keybase1.TeamID
Name keybase1.TeamName
// Seqno of the last cached rename of this team
Seqno keybase1.Seqno
}
// Use a map to deduplicate names. If there is a subteam name
// collision, take the one with the latest (parent) seqno
// modifying its name.
// A collision could occur if you were removed from a team
// and miss its renaming or deletion to to stubbing.
resMap := make(map[string] /*TeamName*/ Entry)
for subteamID, points := range t.inner.SubteamLog {
if len(points) == 0 {
// this should never happen
continue
}
lastPoint := points[len(points)-1]
entry := Entry{
ID: subteamID,
Name: lastPoint.Name,
Seqno: lastPoint.Seqno,
}
existing, ok := resMap[entry.Name.String()]
replace := !ok || (entry.Seqno >= existing.Seqno)
if replace {
resMap[entry.Name.String()] = entry
}
}
for _, entry := range resMap {
res = append(res, TeamIDAndName{
ID: entry.ID,
Name: entry.Name,
})
}
return res
}
// 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) HasActiveInvite(name, typ string) (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, typ string) (*keybase1.TeamInvite, error) {
for _, invite := range t.inner.ActiveInvites {
styp, err := invite.Type.String()
if err != nil {
return nil, err
}
if invite.Name == keybase1.TeamInviteName(name) && styp == typ {
return &invite, nil
}
}
return nil, libkb.NotFoundError{}
}
func (t *TeamSigChainState) FindActiveInviteByID(id keybase1.TeamInviteID) (keybase1.TeamInvite, bool) {
invite, found := t.inner.ActiveInvites[id]
return invite, found
}
// Threadsafe handle to a local model of a team sigchain.
type TeamSigChainPlayer struct {
libkb.Contextified
sync.Mutex
// information about the reading user
reader keybase1.UserVersion
storedState *TeamSigChainState
}
// Load a team chain from the perspective of uid.
func NewTeamSigChainPlayer(g *libkb.GlobalContext, reader keybase1.UserVersion) *TeamSigChainPlayer {
return &TeamSigChainPlayer{
Contextified: libkb.NewContextified(g),
reader: reader,
storedState: nil,
}
}
func NewTeamSigChainPlayerWithState(g *libkb.GlobalContext, reader keybase1.UserVersion, state TeamSigChainState) *TeamSigChainPlayer {
res := NewTeamSigChainPlayer(g, reader)
res.storedState = &state
return res
}
// Get the latest state.
// The caller may _not_ modify the returned state.
func (t *TeamSigChainPlayer) GetState() (res TeamSigChainState, err error) {
t.Lock()
defer t.Unlock()
if t.storedState != nil {
return *t.storedState, nil
}
return res, fmt.Errorf("no links loaded")
}
// Add a chain link to the end. It can be stubbed.
// It must have already been partially verified by TeamLoader.
// `signer` may be nil iff link is stubbed.
// If this returns an error, the TeamSigChainPlayer was not modified.
func (t *TeamSigChainPlayer) AppendChainLink(ctx context.Context, link *chainLinkUnpacked, signer *signerX) error {
t.Lock()
defer t.Unlock()
var prevState *TeamSigChainState
if t.storedState != nil {
prevState = t.storedState
}
newState, err := t.appendChainLinkHelper(ctx, prevState, link, signer)
if err != nil {
if prevState == nil {
return NewAppendLinkError(link, keybase1.Seqno(0), err)
}
return NewAppendLinkError(link, prevState.GetLatestSeqno(), err)
}
// Accept the new state
t.storedState = &newState
return nil
}
// Add a chain link to the end.
// `signer` may be nil iff link is stubbed.
// Does not modify self or any arguments.
// The `prevState` argument is nil if this is the first chain link. `prevState` must not be modified in this function.
func (t *TeamSigChainPlayer) appendChainLinkHelper(
ctx context.Context, prevState *TeamSigChainState, link *chainLinkUnpacked, signer *signerX) (
res TeamSigChainState, err error) {
err = t.checkOuterLink(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(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
}
return *newState, nil
}
type checkInnerLinkResult struct {
newState TeamSigChainState
}
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
}
// 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(
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")
}
// TODO: this may be superfluous.
err = link.AssertInnerOuterMatch()
if err != nil {
return res, err
}
// completely ignore these fields
_ = payload.Ctime
_ = 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 prevState != nil && !prevState.inner.Id.Equal(teamID) {
return res, fmt.Errorf("wrong team id: %s != %s", teamID.String(), prevState.inner.Id.String())
}
hasPrevState := func(has bool) error {
if has {
if prevState == nil {
return fmt.Errorf("link type '%s' unexpected at beginning", payload.Body.Type)
}
} else {
if prevState != nil {
return fmt.Errorf("link type '%s' unexpected at seqno:%v", payload.Body.Type, prevState.inner.LastSeqno+1)
}
}
return nil
}
hasGeneric := func(hasExpected bool, hasReal bool, attr string) error {
if hasExpected != hasReal {
if hasReal {
return fmt.Errorf("team section contains unexpected %s", attr)
}
return fmt.Errorf("missing %s", attr)
}
return nil
}
hasName := func(has bool) error {
return hasGeneric(has, team.Name != nil, "name")
}
hasMembers := func(has bool) error {
return hasGeneric(has, team.Members != nil, "members")
}
hasParent := func(has bool) error {
return hasGeneric(has, team.Parent != nil, "parent")
}
hasSubteam := func(has bool) error {
return hasGeneric(has, team.Subteam != nil, "subteam")
}
hasPerTeamKey := func(has bool) error {
return hasGeneric(has, team.PerTeamKey != nil, "per-team-key")
}
hasAdmin := func(has bool) error {
return hasGeneric(has, team.Admin != nil, "admin")
}
hasInvites := func(has bool) error {
return hasGeneric(has, team.Invites != nil, "invite")
}
hasCompletedInvites := func(has bool) error {
return hasGeneric(has, len(team.CompletedInvites) != 0, "completed_invites")
}
allowInflate := func(allow bool) error {
if isInflate && !allow {
return fmt.Errorf("inflating link type not supported: %v", payload.Body.Type)
}
return nil
}
switch libkb.LinkType(payload.Body.Type) {
case libkb.LinkTypeTeamRoot:
err = libkb.PickFirstError(
allowInflate(false),
hasPrevState(false),
hasName(true),
hasMembers(true),
hasParent(false),
hasSubteam(false),
hasPerTeamKey(true),
hasAdmin(false),
hasInvites(false),
hasCompletedInvites(false))
if err != nil {
return res, err
}
// Check the team name
teamName, err := keybase1.TeamNameFromString(string(*team.Name))
if err != nil {
return res, err
}
if !teamName.IsRootTeam() {
return res, fmt.Errorf("root team has subteam name: %s", teamName)
}
// Check the team ID
// assert that team_name = hash(team_id)
// this is only true for root teams
if !teamID.Equal(teamName.ToTeamID()) {
return res, fmt.Errorf("team id:%s does not match team name:%s", teamID, teamName)
}
if teamID.IsSubTeam() {
return res, fmt.Errorf("malformed root team id")
}
roleUpdates, err := t.sanityCheckMembers(*team.Members, sanityCheckMembersOptions{
requireOwners: true,
allowRemovals: false,
})
if err != nil {
return res, err
}
perTeamKey, err := t.checkPerTeamKey(*link.source, *team.PerTeamKey, 1)
if err != nil {
return res, err
}
perTeamKeys := make(map[keybase1.PerTeamKeyGeneration]keybase1.PerTeamKey)
perTeamKeys[keybase1.PerTeamKeyGeneration(1)] = perTeamKey
res.newState = TeamSigChainState{
inner: keybase1.TeamSigChainState{
Reader: t.reader,
Id: teamID,
RootAncestor: teamName.RootAncestorName(),
NameDepth: teamName.Depth(),
NameLog: []keybase1.TeamNameLogPoint{{
LastPart: teamName.LastPart(),
Seqno: 1,
}},
LastSeqno: 1,
LastLinkID: link.LinkID().Export(),
ParentID: nil,
UserLog: make(map[keybase1.UserVersion][]keybase1.UserLogPoint),
SubteamLog: make(map[keybase1.TeamID][]keybase1.SubteamLogPoint),
PerTeamKeys: perTeamKeys,
LinkIDs: make(map[keybase1.Seqno]keybase1.LinkID),
StubbedLinks: make(map[keybase1.Seqno]bool),
}}
t.updateMembership(&res.newState, roleUpdates, payload.SignatureMetadata())
// check that the signer is an owner
if res.newState.getUserRole(signer.signer) != keybase1.TeamRole_OWNER {
return res, fmt.Errorf("signer is not an owner: %v (%v)", signer, team.Members.Owners)
}
return res, nil
case libkb.LinkTypeChangeMembership:
err = libkb.PickFirstError(
allowInflate(false),
hasPrevState(true),
hasName(false),
hasMembers(true),
hasParent(false),
hasInvites(false),
hasSubteam(false),
hasInvites(false))
if err != nil {
return res, err
}
// Check that the signer is at least an ADMIN or is an IMPLICIT ADMIN to have permission to make this link.
var signerIsExplicitOwner bool
if !signer.implicitAdmin {
signerRole, err := prevState.GetUserRole(signer.signer)
if err != nil {
return res, err
}
if !signerRole.IsAdminOrAbove() {
return res, fmt.Errorf("link signer does not have permission to change membership: %v is a %v",
signer, signerRole)
}
if signerRole == keybase1.TeamRole_OWNER {
signerIsExplicitOwner = true
}
}
roleUpdates, err := t.sanityCheckMembers(*team.Members, sanityCheckMembersOptions{
disallowOwners: prevState.IsSubteam(),
allowRemovals: true,
})
if err != nil {
return res, err
}
// Only owners can add more owners.
if (len(roleUpdates[keybase1.TeamRole_OWNER]) > 0) && !signerIsExplicitOwner {
return res, fmt.Errorf("non-owner cannot add owners")
}
// Only owners can remove owners.
if t.roleUpdatesDemoteOwners(prevState, roleUpdates) && !signerIsExplicitOwner {
return res, fmt.Errorf("non-owner cannot demote owners")
}
res.newState = prevState.DeepCopy()
t.updateMembership(&res.newState, roleUpdates, payload.SignatureMetadata())
t.completeInvites(&res.newState, team.CompletedInvites)
// Note: If someone was removed, the per-team-key should be rotated. This is not checked though.
if team.PerTeamKey != nil {
lastKey, err := prevState.GetLatestPerTeamKey()
if err != nil {
return res, fmt.Errorf("getting previous per-team-key: %s", err)
}
newKey, err := t.checkPerTeamKey(*link.source, *team.PerTeamKey, lastKey.Gen+keybase1.PerTeamKeyGeneration(1))
if err != nil {
return res, err
}
res.newState.inner.PerTeamKeys[newKey.Gen] = newKey
}
return res, nil
case libkb.LinkTypeRotateKey:
err = libkb.PickFirstError(
allowInflate(false),
hasPrevState(true),
hasName(false),
hasMembers(false),
hasParent(false),
hasSubteam(false),
hasPerTeamKey(true),
hasInvites(false),
hasCompletedInvites(false))
if err != nil {
return res, err
}
// Check that the signer is at least a writer to have permission to make this link.
if !signer.implicitAdmin {
signerRole, err := prevState.GetUserRole(signer.signer)
if err != nil {
return res, err
}
switch signerRole {
case keybase1.TeamRole_WRITER, keybase1.TeamRole_ADMIN, keybase1.TeamRole_OWNER:
// ok
default:
return res, fmt.Errorf("link signer does not have permission to rotate key: %v is a %v", signer, signerRole)
}
}
lastKey, err := prevState.GetLatestPerTeamKey()
if err != nil {
return res, fmt.Errorf("getting previous per-team-key: %s", err)
}
newKey, err := t.checkPerTeamKey(*link.source, *team.PerTeamKey, lastKey.Gen+keybase1.PerTeamKeyGeneration(1))
if err != nil {
return res, err
}
res.newState = prevState.DeepCopy()
res.newState.inner.PerTeamKeys[newKey.Gen] = newKey
return res, nil
case libkb.LinkTypeLeave:
err = libkb.PickFirstError(
allowInflate(false),
hasPrevState(true),
hasName(false),
hasMembers(false),
hasParent(false),
hasSubteam(false),
hasPerTeamKey(false),
hasInvites(false),
hasAdmin(false),
hasInvites(false),
hasCompletedInvites(false))
if err != nil {
return res, err
}
// Check that the signer is at least a reader.
// Implicit admins cannot leave a subteam.
signerRole, err := prevState.GetUserRole(signer.signer)
if err != nil {
return res, err
}
switch signerRole {
case keybase1.TeamRole_READER, keybase1.TeamRole_WRITER, keybase1.TeamRole_ADMIN, keybase1.TeamRole_OWNER:
// ok
default:
return res, fmt.Errorf("link signer does not have permission to leave: %v is a %v", signer, signerRole)
}
// The last owner of a team should not leave.
// But that's really up to them and the server. We're just reading what has happened.
res.newState = prevState.DeepCopy()
res.newState.inform(signer.signer, keybase1.TeamRole_NONE, payload.SignatureMetadata())
return res, nil
case libkb.LinkTypeNewSubteam:
err = libkb.PickFirstError(
allowInflate(true),
hasPrevState(true),
hasName(false),
hasMembers(false),
hasParent(false),
hasSubteam(true),
hasPerTeamKey(false),
hasInvites(false),
hasCompletedInvites(false))
if err != nil {
return res, err
}
// Check the subteam ID
subteamID, err := t.assertIsSubteamID(string(team.Subteam.ID))
if err != nil {
return res, err
}
// Check the subteam name
subteamName, err := t.assertSubteamName(prevState, link.Seqno(), string(team.Subteam.Name))
if err != nil {
return res, err
}
res.newState = prevState.DeepCopy()
// informSubteam will take care of asserting that these links are inflated
// in order for each subteam.
err = res.newState.informSubteam(subteamID, subteamName, link.Seqno())
if err != nil {
return res, fmt.Errorf("adding new subteam: %v", err)
}
return res, nil
case libkb.LinkTypeSubteamHead:
err = libkb.PickFirstError(
allowInflate(false),
hasPrevState(false),
hasName(true),
hasMembers(true),
hasParent(true),
hasSubteam(false),
hasPerTeamKey(true),
hasInvites(false),
hasCompletedInvites(false))
if err != nil {
return res, err
}