forked from keybase/kbfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root_metadata_v3.go
1560 lines (1365 loc) · 46.2 KB
/
root_metadata_v3.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package kbfsmd
import (
"fmt"
"runtime"
goerrors "github.com/go-errors/errors"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/go-codec/codec"
"github.com/keybase/kbfs/kbfscodec"
"github.com/keybase/kbfs/kbfscrypto"
"github.com/keybase/kbfs/tlf"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// WriterMetadataV3 stores the metadata for a TLF that is
// only editable by users with writer permissions.
type WriterMetadataV3 struct {
// Serialized, possibly encrypted, version of the PrivateMetadata
SerializedPrivateMetadata []byte `codec:"data"`
// The last KB user with writer permissions to this TLF
// who modified this WriterMetadata
LastModifyingWriter keybase1.UID `codec:"lmw"`
// For public and single-team TLFs (since those don't have any
// keys at all).
Writers []keybase1.UserOrTeamID `codec:",omitempty"`
// Writers identified by unresolved social assertions.
UnresolvedWriters []keybase1.SocialAssertion `codec:"uw,omitempty"`
// Pointer to the writer key bundle for private TLFs.
WKeyBundleID TLFWriterKeyBundleID `codec:"wkid,omitempty"`
// Latest key generation.
LatestKeyGen KeyGen `codec:"lkg"`
// The directory ID, signed over to make verification easier
ID tlf.ID
// The branch ID, currently only set if this is in unmerged per-device history.
BID BranchID
// Flags
WFlags WriterFlags
// Estimated disk usage at this revision
DiskUsage uint64
// Estimated MD disk usage at this revision
MDDiskUsage uint64 `codec:",omitempty"`
// The total number of bytes in new data blocks
RefBytes uint64
// The total number of bytes in unreferenced blocks
UnrefBytes uint64
// The total number of bytes in new MD blocks
MDRefBytes uint64 `codec:",omitempty"`
codec.UnknownFieldSetHandler
}
// RootMetadataV3 is the MD that is signed by the reader or
// writer. Unlike RootMetadata, it contains exactly the serializable
// metadata.
type RootMetadataV3 struct {
// The metadata that is only editable by the writer.
WriterMetadata WriterMetadataV3 `codec:"wmd"`
// The last KB user who modified this RootMetadata
LastModifyingUser keybase1.UID
// Flags
Flags MetadataFlags
// The revision number
Revision Revision
// Pointer to the previous root block ID
PrevRoot ID
// For private TLFs. Any unresolved social assertions for readers.
UnresolvedReaders []keybase1.SocialAssertion `codec:"ur,omitempty"`
// Pointer to the reader key bundle for private TLFs.
RKeyBundleID TLFReaderKeyBundleID `codec:"rkid,omitempty"`
// ConflictInfo is set if there's a conflict for the given folder's
// handle after a social assertion resolution.
ConflictInfo *tlf.HandleExtension `codec:"ci,omitempty"`
// FinalizedInfo is set if there are no more valid writer keys capable
// of writing to the given folder.
FinalizedInfo *tlf.HandleExtension `codec:"fi,omitempty"`
// The root of the global Keybase Merkle tree at the time this
// update was created (from the writer's perspective). This field
// was added to V3 after it was live for a while, and older
// clients that don't know about this field yet might copy it into
// new updates via the unknown fields copier. Which means new MD
// updates might end up referring to older Merkle roots. That's
// ok since this is just a hint anyway, and shouldn't be fully
// trusted when checking MD updates against the Merkle tree.
// NOTE: this is a pointer in order to get the correct "omitempty"
// behavior, so that old MDs are still verifiable.
KBMerkleRoot *keybase1.MerkleRootV2 `codec:"mr,omitempty"`
codec.UnknownFieldSetHandler
}
// TODO: Use pkg/errors instead.
type missingKeyBundlesError struct {
stack []uintptr
}
func (e missingKeyBundlesError) Error() string {
s := "Missing key bundles: \n"
for _, pc := range e.stack {
f := goerrors.NewStackFrame(pc)
s += f.String()
}
return s
}
func makeMissingKeyBundlesError() missingKeyBundlesError {
stack := make([]uintptr, 20)
n := runtime.Callers(2, stack)
return missingKeyBundlesError{stack[:n]}
}
// ExtraMetadataV3 contains references to key bundles stored outside of metadata
// blocks. This only ever exists in memory and is never serialized itself.
type ExtraMetadataV3 struct {
wkb TLFWriterKeyBundleV3
rkb TLFReaderKeyBundleV3
// Set if wkb is new and should be sent to the server on an MD
// put.
wkbNew bool
// Set if rkb is new and should be sent to the server on an MD
// put.
rkbNew bool
}
// NewExtraMetadataV3 creates a new ExtraMetadataV3 given a pair of key bundles
func NewExtraMetadataV3(
wkb TLFWriterKeyBundleV3, rkb TLFReaderKeyBundleV3,
wkbNew, rkbNew bool) *ExtraMetadataV3 {
return &ExtraMetadataV3{wkb, rkb, wkbNew, rkbNew}
}
// MetadataVersion implements the ExtraMetadata interface for ExtraMetadataV3.
func (extra ExtraMetadataV3) MetadataVersion() MetadataVer {
return SegregatedKeyBundlesVer
}
func (extra *ExtraMetadataV3) updateNew(wkbNew, rkbNew bool) {
extra.wkbNew = extra.wkbNew || wkbNew
extra.rkbNew = extra.rkbNew || rkbNew
}
// DeepCopy implements the ExtraMetadata interface for ExtraMetadataV3.
func (extra ExtraMetadataV3) DeepCopy(codec kbfscodec.Codec) (
ExtraMetadata, error) {
wkb, err := extra.wkb.DeepCopy(codec)
if err != nil {
return nil, err
}
rkb, err := extra.rkb.DeepCopy(codec)
if err != nil {
return nil, err
}
return NewExtraMetadataV3(wkb, rkb, extra.wkbNew, extra.rkbNew), nil
}
// MakeSuccessorCopy implements the ExtraMetadata interface for ExtraMetadataV3.
func (extra ExtraMetadataV3) MakeSuccessorCopy(codec kbfscodec.Codec) (
ExtraMetadata, error) {
wkb, err := extra.wkb.DeepCopy(codec)
if err != nil {
return nil, err
}
rkb, err := extra.rkb.DeepCopy(codec)
if err != nil {
return nil, err
}
return NewExtraMetadataV3(wkb, rkb, false, false), nil
}
// GetWriterKeyBundle returns the contained writer key bundle.
func (extra ExtraMetadataV3) GetWriterKeyBundle() TLFWriterKeyBundleV3 {
return extra.wkb
}
// GetReaderKeyBundle returns the contained reader key bundle.
func (extra ExtraMetadataV3) GetReaderKeyBundle() TLFReaderKeyBundleV3 {
return extra.rkb
}
// IsWriterKeyBundleNew returns whether or not the writer key bundle
// is new and should be sent to the server on an MD put.
func (extra ExtraMetadataV3) IsWriterKeyBundleNew() bool {
return extra.wkbNew
}
// IsReaderKeyBundleNew returns whether or not the reader key bundle
// is new and should be sent to the server on an MD put.
func (extra ExtraMetadataV3) IsReaderKeyBundleNew() bool {
return extra.rkbNew
}
// MakeInitialRootMetadataV3 creates a new RootMetadataV3 object with
// revision RevisionInitial, and the given TLF ID and handle. Note
// that if the given ID/handle are private, rekeying must be done
// separately. Since they are data-compatible, this also creates V4
// MD objects.
func MakeInitialRootMetadataV3(tlfID tlf.ID, h tlf.Handle) (
*RootMetadataV3, error) {
switch {
case h.TypeForKeying() == tlf.TeamKeying &&
tlfID.Type() == tlf.SingleTeam && h.Type() != tlf.SingleTeam:
fallthrough
case h.TypeForKeying() != tlf.TeamKeying && tlfID.Type() != h.Type():
return nil, errors.New("TlfID and TlfHandle disagree on TLF type")
default:
}
var writers []keybase1.UserOrTeamID
if h.TypeForKeying() != tlf.PrivateKeying {
writers = make([]keybase1.UserOrTeamID, len(h.Writers))
copy(writers, h.Writers)
}
var unresolvedWriters, unresolvedReaders []keybase1.SocialAssertion
if len(h.UnresolvedWriters) > 0 {
unresolvedWriters = make(
[]keybase1.SocialAssertion, len(h.UnresolvedWriters))
copy(unresolvedWriters, h.UnresolvedWriters)
}
if len(h.UnresolvedReaders) > 0 {
unresolvedReaders = make(
[]keybase1.SocialAssertion, len(h.UnresolvedReaders))
copy(unresolvedReaders, h.UnresolvedReaders)
}
return &RootMetadataV3{
WriterMetadata: WriterMetadataV3{
Writers: writers,
ID: tlfID,
UnresolvedWriters: unresolvedWriters,
},
Revision: RevisionInitial,
UnresolvedReaders: unresolvedReaders,
// Normally an MD wouldn't start out with extensions, but this
// is useful for tests.
ConflictInfo: h.ConflictInfo,
FinalizedInfo: h.FinalizedInfo,
}, nil
}
// TlfID implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) TlfID() tlf.ID {
return md.WriterMetadata.ID
}
// KeyGenerationsToUpdate implements the RootMetadata interface
// for RootMetadataV3.
func (md *RootMetadataV3) KeyGenerationsToUpdate() (KeyGen, KeyGen) {
latest := md.LatestKeyGeneration()
if latest < FirstValidKeyGen {
return 0, 0
}
// We only keep track of the latest key generation in extra.
return latest, latest + 1
}
// LatestKeyGeneration implements the RootMetadata interface for
// RootMetadataV3.
func (md *RootMetadataV3) LatestKeyGeneration() KeyGen {
if md.TypeForKeying() == tlf.PublicKeying {
return PublicKeyGen
}
return md.WriterMetadata.LatestKeyGen
}
func (md *RootMetadataV3) haveOnlyUserRKeysChanged(
codec kbfscodec.Codec, prevMD *RootMetadataV3,
user keybase1.UID, prevRkb, rkb TLFReaderKeyBundleV3) (bool, error) {
if len(rkb.Keys) != len(prevRkb.Keys) {
return false, nil
}
for u, keys := range rkb.Keys {
if u != user {
prevKeys := prevRkb.Keys[u]
keysEqual, err := kbfscodec.Equal(codec, keys, prevKeys)
if err != nil {
return false, err
}
if !keysEqual {
return false, nil
}
}
}
return true, nil
}
// IsValidRekeyRequest implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsValidRekeyRequest(
codec kbfscodec.Codec, prevBareMd RootMetadata,
user keybase1.UID, prevExtra, extra ExtraMetadata) (
bool, error) {
if !md.IsWriterMetadataCopiedSet() {
// Not a copy.
return false, nil
}
prevMd, ok := prevBareMd.(*RootMetadataV3)
if !ok {
// Not the same type so not a copy.
return false, nil
}
prevExtraV3, ok := prevExtra.(*ExtraMetadataV3)
if !ok {
return false, errors.New("Invalid previous extra metadata")
}
extraV3, ok := extra.(*ExtraMetadataV3)
if !ok {
return false, errors.New("Invalid extra metadata")
}
writerEqual, err := kbfscodec.Equal(
codec, md.WriterMetadata, prevMd.WriterMetadata)
if err != nil {
return false, err
}
if !writerEqual {
// Copy mismatch.
return false, nil
}
onlyUserRKeysChanged, err := md.haveOnlyUserRKeysChanged(
codec, prevMd, user, prevExtraV3.rkb, extraV3.rkb)
if err != nil {
return false, err
}
if !onlyUserRKeysChanged {
// Keys outside of this user's reader key set have changed.
return false, nil
}
return true, nil
}
// MergedStatus implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) MergedStatus() MergeStatus {
if md.WriterMetadata.WFlags&MetadataFlagUnmerged != 0 {
return Unmerged
}
return Merged
}
// IsRekeySet implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsRekeySet() bool {
return md.Flags&MetadataFlagRekey != 0
}
// IsWriterMetadataCopiedSet implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsWriterMetadataCopiedSet() bool {
return md.Flags&MetadataFlagWriterMetadataCopied != 0
}
// IsFinal implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsFinal() bool {
return md.Flags&MetadataFlagFinal != 0
}
func (md *RootMetadataV3) checkNonPrivateExtra(extra ExtraMetadata) error {
if md.TypeForKeying() == tlf.PrivateKeying {
return errors.New("checkNonPrivateExtra called on private TLF")
}
if extra != nil {
return errors.Errorf("Expected nil, got %T", extra)
}
return nil
}
func (md *RootMetadataV3) getTLFKeyBundles(extra ExtraMetadata) (
*TLFWriterKeyBundleV3, *TLFReaderKeyBundleV3, error) {
if md.TypeForKeying() != tlf.PrivateKeying {
return nil, nil, InvalidNonPrivateTLFOperation{
md.TlfID(), "getTLFKeyBundles", md.Version(),
}
}
if extra == nil {
return nil, nil, makeMissingKeyBundlesError()
}
extraV3, ok := extra.(*ExtraMetadataV3)
if !ok {
return nil, nil, errors.Errorf(
"Expected *ExtraMetadataV3, got %T", extra)
}
return &extraV3.wkb, &extraV3.rkb, nil
}
// GetTLFKeyBundlesForTest returns the writer and reader key bundles
// from extra.
func (md *RootMetadataV3) GetTLFKeyBundlesForTest(extra ExtraMetadata) (
*TLFWriterKeyBundleV3, *TLFReaderKeyBundleV3, error) {
return md.getTLFKeyBundles(extra)
}
func (md *RootMetadataV3) isNonTeamWriter(
ctx context.Context, user keybase1.UID,
cryptKey kbfscrypto.CryptPublicKey, extra ExtraMetadata) (bool, error) {
switch md.TlfID().Type() {
case tlf.Public:
err := md.checkNonPrivateExtra(extra)
if err != nil {
return false, err
}
for _, w := range md.WriterMetadata.Writers {
if w == user.AsUserOrTeam() {
return true, nil
}
}
return false, nil
case tlf.Private:
wkb, _, err := md.getTLFKeyBundles(extra)
if err != nil {
return false, err
}
return wkb.IsWriter(user, cryptKey), nil
default:
return false, errors.Errorf("Unknown TLF type: %s", md.TlfID().Type())
}
}
// IsWriter implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsWriter(
ctx context.Context, user keybase1.UID,
cryptKey kbfscrypto.CryptPublicKey, verifyingKey kbfscrypto.VerifyingKey,
teamMemChecker TeamMembershipChecker, extra ExtraMetadata) (bool, error) {
switch md.TypeForKeying() {
case tlf.TeamKeying:
err := md.checkNonPrivateExtra(extra)
if err != nil {
return false, err
}
tid, err := md.WriterMetadata.Writers[0].AsTeam()
if err != nil {
return false, err
}
// TODO: Eventually this will have to use a Merkle sequence
// number to check historic versions.
isWriter, err := teamMemChecker.IsTeamWriter(
ctx, tid, user, verifyingKey)
if err != nil {
return false, err
}
return isWriter, nil
default:
return md.isNonTeamWriter(ctx, user, cryptKey, extra)
}
}
// IsReader implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsReader(
ctx context.Context, user keybase1.UID,
cryptKey kbfscrypto.CryptPublicKey, teamMemChecker TeamMembershipChecker,
extra ExtraMetadata) (bool, error) {
switch md.TypeForKeying() {
case tlf.PublicKeying:
err := md.checkNonPrivateExtra(extra)
if err != nil {
return false, err
}
return true, nil
case tlf.PrivateKeying:
// Writers are also readers.
isWriter, err := md.isNonTeamWriter(ctx, user, cryptKey, extra)
if err != nil {
return false, err
}
if isWriter {
return true, nil
}
_, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return false, err
}
return rkb.IsReader(user, cryptKey), nil
case tlf.TeamKeying:
err := md.checkNonPrivateExtra(extra)
if err != nil {
return false, err
}
tid, err := md.WriterMetadata.Writers[0].AsTeam()
if err != nil {
return false, err
}
if tid.IsPublic() {
return true, nil
}
// TODO: Eventually this will have to use a Merkle sequence
// number to check historic versions.
isReader, err := teamMemChecker.IsTeamReader(ctx, tid, user)
if err != nil {
return false, err
}
return isReader, nil
default:
panic(fmt.Sprintf("Unknown TLF keying type: %s", md.TypeForKeying()))
}
}
// DeepCopy implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) DeepCopy(
codec kbfscodec.Codec) (MutableRootMetadata, error) {
var newMd RootMetadataV3
if err := kbfscodec.Update(codec, &newMd, md); err != nil {
return nil, err
}
return &newMd, nil
}
// MakeSuccessorCopy implements the ImmutableRootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) MakeSuccessorCopy(
codec kbfscodec.Codec, extra ExtraMetadata, _ MetadataVer,
_ func() ([]kbfscrypto.TLFCryptKey, error), isReadableAndWriter bool) (
MutableRootMetadata, ExtraMetadata, error) {
var extraCopy ExtraMetadata
if extra != nil {
var err error
extraCopy, err = extra.MakeSuccessorCopy(codec)
if err != nil {
return nil, nil, err
}
}
mdCopy, err := md.DeepCopy(codec)
if err != nil {
return nil, nil, err
}
// TODO: If there is ever a RootMetadataV4 this will need to perform the conversion.
return mdCopy, extraCopy, nil
}
// CheckValidSuccessor implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) CheckValidSuccessor(
currID ID, nextMd RootMetadata) error {
// (1) Verify current metadata is non-final.
if md.IsFinal() {
return MetadataIsFinalError{}
}
// (2) Check TLF ID.
if nextMd.TlfID() != md.TlfID() {
return MDTlfIDMismatch{
CurrID: md.TlfID(),
NextID: nextMd.TlfID(),
}
}
// (3) Check revision.
if nextMd.RevisionNumber() != md.RevisionNumber()+1 {
return MDRevisionMismatch{
Rev: nextMd.RevisionNumber(),
Curr: md.RevisionNumber(),
}
}
// (4) Check PrevRoot pointer.
expectedPrevRoot := currID
if nextMd.IsFinal() {
expectedPrevRoot = md.GetPrevRoot()
}
if nextMd.GetPrevRoot() != expectedPrevRoot {
return MDPrevRootMismatch{
prevRoot: nextMd.GetPrevRoot(),
expectedPrevRoot: expectedPrevRoot,
}
}
// (5) Check branch ID.
if md.MergedStatus() == nextMd.MergedStatus() && md.BID() != nextMd.BID() {
return errors.Errorf("Unexpected branch ID on successor: %s vs. %s",
md.BID(), nextMd.BID())
} else if md.MergedStatus() == Unmerged && nextMd.MergedStatus() == Merged {
return errors.New("merged MD can't follow unmerged MD")
}
// (6) Check disk usage.
expectedUsage := md.DiskUsage()
if !nextMd.IsWriterMetadataCopiedSet() {
expectedUsage += nextMd.RefBytes() - nextMd.UnrefBytes()
}
if nextMd.DiskUsage() != expectedUsage {
return MDDiskUsageMismatch{
expectedDiskUsage: expectedUsage,
actualDiskUsage: nextMd.DiskUsage(),
}
}
expectedMDUsage := md.MDDiskUsage()
if !nextMd.IsWriterMetadataCopiedSet() {
expectedMDUsage += nextMd.MDRefBytes()
}
// Add an exception for the case where MDRefBytes is equal, since
// it probably indicates an older client just copied the previous
// MDRefBytes value as an unknown field.
if nextMd.MDDiskUsage() != expectedMDUsage &&
md.MDRefBytes() != nextMd.MDRefBytes() {
return MDDiskUsageMismatch{
expectedDiskUsage: expectedMDUsage,
actualDiskUsage: nextMd.MDDiskUsage(),
}
}
// TODO: Check that the successor (bare) TLF handle is the
// same or more resolved.
return nil
}
// CheckValidSuccessorForServer implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) CheckValidSuccessorForServer(
currID ID, nextMd RootMetadata) error {
err := md.CheckValidSuccessor(currID, nextMd)
switch err := err.(type) {
case nil:
break
case MDRevisionMismatch:
return ServerErrorConflictRevision{
Expected: err.Curr + 1,
Actual: err.Rev,
}
case MDPrevRootMismatch:
return ServerErrorConflictPrevRoot{
Expected: err.expectedPrevRoot,
Actual: err.prevRoot,
}
case MDDiskUsageMismatch:
return ServerErrorConflictDiskUsage{
Expected: err.expectedDiskUsage,
Actual: err.actualDiskUsage,
}
default:
return ServerError{Err: err}
}
return nil
}
// isBackedByTeam returns true if md is for a TLF backed by a team. It could be
// either a SingleTeam TLF or a private/public TLF backed by an implicit team.
func (md *RootMetadataV3) isBackedByTeam() bool {
if len(md.WriterMetadata.UnresolvedWriters) != 0 {
return false
}
if len(md.WriterMetadata.Writers) != 1 {
return false
}
if !md.WriterMetadata.Writers[0].IsTeamOrSubteam() {
return false
}
return true
}
// TypeForKeying implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) TypeForKeying() tlf.KeyingType {
if md.isBackedByTeam() {
return tlf.TeamKeying
}
return md.TlfID().Type().ToKeyingType()
}
// MakeBareTlfHandle implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) MakeBareTlfHandle(extra ExtraMetadata) (
tlf.Handle, error) {
var writers, readers []keybase1.UserOrTeamID
if md.TypeForKeying() == tlf.PrivateKeying {
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return tlf.Handle{}, err
}
writers = make([]keybase1.UserOrTeamID, 0, len(wkb.Keys))
readers = make([]keybase1.UserOrTeamID, 0, len(rkb.Keys))
for w := range wkb.Keys {
writers = append(writers, w.AsUserOrTeam())
}
for r := range rkb.Keys {
// TODO: Return an error instead if r is
// PublicUID. Maybe return an error if r is in
// WKeys also. Or do all this in
// MakeBareTlfHandle.
if _, ok := wkb.Keys[r]; !ok &&
r != keybase1.PublicUID {
readers = append(readers, r.AsUserOrTeam())
}
}
} else {
err := md.checkNonPrivateExtra(extra)
if err != nil {
return tlf.Handle{}, err
}
writers = md.WriterMetadata.Writers
if md.TypeForKeying() == tlf.PublicKeying {
readers = []keybase1.UserOrTeamID{keybase1.PublicUID.AsUserOrTeam()}
}
}
return tlf.MakeHandle(
writers, readers,
md.WriterMetadata.UnresolvedWriters, md.UnresolvedReaders,
md.TlfHandleExtensions())
}
// TlfHandleExtensions implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) TlfHandleExtensions() (
extensions []tlf.HandleExtension) {
if md.ConflictInfo != nil {
extensions = append(extensions, *md.ConflictInfo)
}
if md.FinalizedInfo != nil {
extensions = append(extensions, *md.FinalizedInfo)
}
return extensions
}
// PromoteReaders implements the RootMetadata interface for
// RootMetadataV3.
func (md *RootMetadataV3) PromoteReaders(
readersToPromote map[keybase1.UID]bool, extra ExtraMetadata) error {
if md.TypeForKeying() != tlf.PrivateKeying {
return InvalidNonPrivateTLFOperation{md.TlfID(), "PromoteReaders", md.Version()}
}
if len(readersToPromote) == 0 {
return nil
}
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return err
}
for reader := range readersToPromote {
dkim, ok := rkb.Keys[reader]
if !ok {
return errors.Errorf("Could not find %s in rkb", reader)
}
// TODO: This is incorrect, since dkim contains offsets info
// rkb.TLFEphemeralPublicKeys, which don't directly translate
// to offsets into wkb.TLFEphemeralPublicKeys.
//
// Also, doing this may leave some entries in
// rkb.TLFEphemeralPublicKeys unreferenced, so they should be
// removed.
//
// See KBFS-1719.
wkb.Keys[reader] = dkim
delete(rkb.Keys, reader)
}
return nil
}
// RevokeRemovedDevices implements the RootMetadata interface for
// RootMetadataV3.
func (md *RootMetadataV3) RevokeRemovedDevices(
updatedWriterKeys, updatedReaderKeys UserDevicePublicKeys,
extra ExtraMetadata) (ServerHalfRemovalInfo, error) {
if md.TypeForKeying() != tlf.PrivateKeying {
return nil, InvalidNonPrivateTLFOperation{
md.TlfID(), "RevokeRemovedDevices", md.Version()}
}
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return nil, err
}
wRemovalInfo := wkb.Keys.RemoveDevicesNotIn(updatedWriterKeys)
rRemovalInfo := rkb.Keys.RemoveDevicesNotIn(updatedReaderKeys)
return wRemovalInfo.MergeUsers(rRemovalInfo)
}
// GetUserDevicePublicKeys implements the RootMetadata interface
// for RootMetadataV3.
func (md *RootMetadataV3) GetUserDevicePublicKeys(extra ExtraMetadata) (
writerDeviceKeys, readerDeviceKeys UserDevicePublicKeys, err error) {
if md.TypeForKeying() != tlf.PrivateKeying {
return nil, nil, InvalidNonPrivateTLFOperation{
md.TlfID(), "GetUserDevicePublicKeys", md.Version()}
}
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return nil, nil, err
}
return wkb.Keys.ToPublicKeys(), rkb.Keys.ToPublicKeys(), nil
}
// GetTLFCryptKeyParams implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) GetTLFCryptKeyParams(
keyGen KeyGen, user keybase1.UID,
key kbfscrypto.CryptPublicKey, extra ExtraMetadata) (
kbfscrypto.TLFEphemeralPublicKey,
kbfscrypto.EncryptedTLFCryptKeyClientHalf,
kbfscrypto.TLFCryptKeyServerHalfID, bool, error) {
if keyGen != md.LatestKeyGeneration() {
return kbfscrypto.TLFEphemeralPublicKey{},
kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
kbfscrypto.TLFCryptKeyServerHalfID{}, false,
TLFCryptKeyNotPerDeviceEncrypted{md.TlfID(), keyGen}
}
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return kbfscrypto.TLFEphemeralPublicKey{},
kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
kbfscrypto.TLFCryptKeyServerHalfID{}, false, err
}
isWriter := true
dkim := wkb.Keys[user]
if dkim == nil {
dkim = rkb.Keys[user]
if dkim == nil {
return kbfscrypto.TLFEphemeralPublicKey{},
kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
}
isWriter = false
}
info, ok := dkim[key]
if !ok {
return kbfscrypto.TLFEphemeralPublicKey{},
kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
kbfscrypto.TLFCryptKeyServerHalfID{}, false, nil
}
var publicKeys kbfscrypto.TLFEphemeralPublicKeys
var keyType string
if isWriter {
publicKeys = wkb.TLFEphemeralPublicKeys
keyType = "writer"
} else {
publicKeys = rkb.TLFEphemeralPublicKeys
keyType = "reader"
}
keyCount := len(publicKeys)
index := info.EPubKeyIndex
if index >= keyCount {
return kbfscrypto.TLFEphemeralPublicKey{},
kbfscrypto.EncryptedTLFCryptKeyClientHalf{},
kbfscrypto.TLFCryptKeyServerHalfID{}, false,
errors.Errorf("Invalid %s key index %d >= %d",
keyType, index, keyCount)
}
return publicKeys[index], info.ClientHalf, info.ServerHalfID, true, nil
}
// CheckWKBID returns an error if the ID of the given writer key
// bundle doesn't match the given one.
func CheckWKBID(codec kbfscodec.Codec,
wkbID TLFWriterKeyBundleID, wkb TLFWriterKeyBundleV3) error {
computedWKBID, err := MakeTLFWriterKeyBundleID(codec, wkb)
if err != nil {
return err
}
if wkbID != computedWKBID {
return errors.Errorf("Expected WKB ID %s, got %s",
wkbID, computedWKBID)
}
return nil
}
// CheckRKBID returns an error if the ID of the given reader key
// bundle doesn't match the given one.
func CheckRKBID(codec kbfscodec.Codec,
rkbID TLFReaderKeyBundleID, rkb TLFReaderKeyBundleV3) error {
computedRKBID, err := MakeTLFReaderKeyBundleID(codec, rkb)
if err != nil {
return err
}
if rkbID != computedRKBID {
return errors.Errorf("Expected RKB ID %s, got %s",
rkbID, computedRKBID)
}
return nil
}
// IsValidAndSigned implements the RootMetadata interface for RootMetadataV3.
func (md *RootMetadataV3) IsValidAndSigned(
ctx context.Context, codec kbfscodec.Codec,
teamMemChecker TeamMembershipChecker, extra ExtraMetadata,
writerVerifyingKey kbfscrypto.VerifyingKey) error {
if md.TypeForKeying() == tlf.PrivateKeying {
wkb, rkb, err := md.getTLFKeyBundles(extra)
if err != nil {
return err
}
err = CheckWKBID(codec, md.GetTLFWriterKeyBundleID(), *wkb)
if err != nil {
return err
}
err = CheckRKBID(codec, md.GetTLFReaderKeyBundleID(), *rkb)
if err != nil {
return err
}
} else {
err := md.checkNonPrivateExtra(extra)
if err != nil {
return err
}
}
if md.IsFinal() {
if md.Revision < RevisionInitial+1 {
return errors.Errorf("Invalid final revision %d", md.Revision)
}
if md.Revision == (RevisionInitial + 1) {
if md.PrevRoot != (ID{}) {
return errors.Errorf("Invalid PrevRoot %s for initial final revision", md.PrevRoot)
}
} else {
if md.PrevRoot == (ID{}) {
return errors.New("No PrevRoot for non-initial final revision")
}
}
} else {
if md.Revision < RevisionInitial {
return errors.Errorf("Invalid revision %d", md.Revision)
}
if md.Revision == RevisionInitial {
if md.PrevRoot != (ID{}) {
return errors.Errorf("Invalid PrevRoot %s for initial revision", md.PrevRoot)
}
} else {
if md.PrevRoot == (ID{}) {
return errors.New("No PrevRoot for non-initial revision")
}
}
}
if len(md.WriterMetadata.SerializedPrivateMetadata) == 0 {
return errors.New("No private metadata")
}
if (md.MergedStatus() == Merged) != (md.BID() == NullBranchID) {
return errors.Errorf("Branch ID %s doesn't match merged status %s",
md.BID(), md.MergedStatus())
}
handle, err := md.MakeBareTlfHandle(extra)
if err != nil {
return err
}
writer := md.LastModifyingWriter()
user := md.LastModifyingUser
isWriter := false
isReader := false
if md.TypeForKeying() == tlf.TeamKeying {
tid, err := md.WriterMetadata.Writers[0].AsTeam()
if err != nil {
return err
}
// TODO: Eventually this will have to use a Merkle sequence
// number to check historic versions.
isWriter, err = teamMemChecker.IsTeamWriter(
ctx, tid, writer, writerVerifyingKey)
if err != nil {
return err
}
isReader, err = teamMemChecker.IsTeamReader(ctx, tid, user)
if err != nil {
return err
}
} else {
isWriter = handle.IsWriter(writer.AsUserOrTeam())
isReader = handle.IsReader(user.AsUserOrTeam())
}
// Make sure the last writer is valid.
if !isWriter {