forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interfaces.go
2734 lines (2480 loc) · 117 KB
/
interfaces.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 libkbfs
import (
"time"
"github.com/keybase/client/go/kbfs/kbfsblock"
"github.com/keybase/client/go/kbfs/kbfscodec"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsedits"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/tlf"
kbname "github.com/keybase/client/go/kbun"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/keybase1"
metrics "github.com/rcrowley/go-metrics"
"golang.org/x/net/context"
billy "gopkg.in/src-d/go-billy.v4"
)
type dataVersioner interface {
// DataVersion returns the data version for this block
DataVersion() DataVer
}
type logMaker interface {
MakeLogger(module string) logger.Logger
}
type blockCacher interface {
BlockCache() BlockCache
}
type keyGetterGetter interface {
keyGetter() blockKeyGetter
}
type codecGetter interface {
Codec() kbfscodec.Codec
}
type blockServerGetter interface {
BlockServer() BlockServer
}
type cryptoPureGetter interface {
cryptoPure() cryptoPure
}
type cryptoGetter interface {
Crypto() Crypto
}
type chatGetter interface {
Chat() Chat
}
type currentSessionGetterGetter interface {
CurrentSessionGetter() CurrentSessionGetter
}
type signerGetter interface {
Signer() kbfscrypto.Signer
}
type diskBlockCacheGetter interface {
DiskBlockCache() DiskBlockCache
}
type diskBlockCacheSetter interface {
MakeDiskBlockCacheIfNotExists() error
}
type diskBlockCacheFractionSetter interface {
SetDiskBlockCacheFraction(float64)
}
type syncBlockCacheFractionSetter interface {
SetSyncBlockCacheFraction(float64)
}
type diskMDCacheGetter interface {
DiskMDCache() DiskMDCache
}
type diskMDCacheSetter interface {
MakeDiskMDCacheIfNotExists() error
}
type diskQuotaCacheGetter interface {
DiskQuotaCache() DiskQuotaCache
}
type diskQuotaCacheSetter interface {
MakeDiskQuotaCacheIfNotExists() error
}
type blockMetadataStoreGetSeter interface {
MakeBlockMetadataStoreIfNotExists() error
XattrStore() XattrStore
// Other metadata store types goes here.
}
type clockGetter interface {
Clock() Clock
}
type diskLimiterGetter interface {
DiskLimiter() DiskLimiter
}
type syncedTlfGetterSetter interface {
IsSyncedTlf(tlfID tlf.ID) bool
GetTlfSyncState(tlfID tlf.ID) FolderSyncConfig
SetTlfSyncState(tlfID tlf.ID, config FolderSyncConfig) (<-chan error, error)
GetAllSyncedTlfs() []tlf.ID
}
type blockRetrieverGetter interface {
BlockRetriever() BlockRetriever
}
// Offset is a generic representation of an offset to an indirect
// pointer within an indirect Block.
type Offset interface {
Equals(other Offset) bool
Less(other Offset) bool
}
// Block just needs to be (de)serialized using msgpack
type Block interface {
dataVersioner
// GetEncodedSize returns the encoded size of this block, but only
// if it has been previously set; otherwise it returns 0.
GetEncodedSize() uint32
// SetEncodedSize sets the encoded size of this block, locally
// caching it. The encoded size is not serialized.
SetEncodedSize(size uint32)
// NewEmpty returns a new block of the same type as this block
NewEmpty() Block
// NewEmptier returns a function that creates a new block of the
// same type as this block.
NewEmptier() func() Block
// Set sets this block to the same value as the passed-in block
Set(other Block)
// ToCommonBlock retrieves this block as a *CommonBlock.
ToCommonBlock() *CommonBlock
// IsIndirect indicates whether this block contains indirect pointers.
IsIndirect() bool
// IsTail returns true if this block doesn't point to any other
// blocks, either indirectly or in child directory entries.
IsTail() bool
// OffsetExceedsData returns true if `off` is greater than the
// data contained in a direct block, assuming it starts at
// `startOff`. Note that the offset of the next block isn't
// relevant; this function should only indicate whether the offset
// is greater than what currently could be stored in this block.
OffsetExceedsData(startOff, off Offset) bool
// BytesCanBeDirtied returns the number of bytes that should be
// marked as dirtied if this block is dirtied.
BytesCanBeDirtied() int64
}
// BlockWithPtrs defines methods needed for interacting with indirect
// pointers.
type BlockWithPtrs interface {
Block
// FirstOffset returns the offset of the indirect pointer that
// points to the first (left-most) block in a block tree.
FirstOffset() Offset
// NumIndirectPtrs returns the number of indirect pointers in this
// block. The behavior is undefined when called on a non-indirect
// block.
NumIndirectPtrs() int
// IndirectPtr returns the block info and offset for the indirect
// pointer at index `i`. The behavior is undefined when called on
// a non-indirect block.
IndirectPtr(i int) (BlockInfo, Offset)
// AppendNewIndirectPtr appends a new indirect pointer at the
// given offset.
AppendNewIndirectPtr(ptr BlockPointer, off Offset)
// ClearIndirectPtrSize clears the encoded size of the indirect
// pointer stored at index `i`.
ClearIndirectPtrSize(i int)
// SetIndirectPtrType set the type of the indirect pointer stored
// at index `i`.
SetIndirectPtrType(i int, dt BlockDirectType)
// SetIndirectPtrOff set the offset of the indirect pointer stored
// at index `i`.
SetIndirectPtrOff(i int, off Offset)
// SetIndirectPtrInfo sets the block info of the indirect pointer
// stored at index `i`.
SetIndirectPtrInfo(i int, info BlockInfo)
// SwapIndirectPtrs swaps the indirect ptr at `i` in this block
// with the one at `otherI` in `other`.
SwapIndirectPtrs(i int, other BlockWithPtrs, otherI int)
}
// NodeID is a unique but transient ID for a Node. That is, two Node
// objects in memory at the same time represent the same file or
// directory if and only if their NodeIDs are equal (by pointer).
type NodeID interface {
// ParentID returns the NodeID of the directory containing the
// pointed-to file or directory, or nil if none exists.
ParentID() NodeID
}
// Node represents a direct pointer to a file or directory in KBFS.
// It is somewhat like an inode in a regular file system. Users of
// KBFS can use Node as a handle when accessing files or directories
// they have previously looked up.
type Node interface {
// GetID returns the ID of this Node. This should be used as a
// map key instead of the Node itself.
GetID() NodeID
// GetFolderBranch returns the folder ID and branch for this Node.
GetFolderBranch() FolderBranch
// GetBasename returns the current basename of the node, or ""
// if the node has been unlinked.
GetBasename() string
// Readonly returns true if KBFS should outright reject any write
// attempts on data or directory structures of this node. Though
// note that even if it returns false, KBFS can reject writes to
// the node for other reasons, such as TLF permissions. An
// implementation that wraps another `Node` (`inner`) must return
// `inner.Readonly()` if it decides not to return `true` on its
// own.
Readonly(ctx context.Context) bool
// ShouldCreateMissedLookup is called for Nodes representing
// directories, whenever `name` is looked up but is not found in
// the directory. If the Node decides a new entry should be
// created matching this lookup, it should return `true` as well
// as a context to use for the creation, the type of the new entry
// and the symbolic link contents if the entry is a Sym; the
// caller should then create this entry. Otherwise it should
// return false. It may return the type `FakeDir` to indicate
// that the caller should pretend the entry exists, even if it
// really does not. An implementation that wraps another `Node`
// (`inner`) must return `inner.ShouldCreateMissedLookup()` if it
// decides not to return `true` on its own.
ShouldCreateMissedLookup(ctx context.Context, name string) (
shouldCreate bool, newCtx context.Context, et EntryType, sympath string)
// ShouldRetryOnDirRead is called for Nodes representing
// directories, whenever a `Lookup` or `GetDirChildren` is done on
// them. It should return true to instruct the caller that it
// should re-sync its view of the directory and retry the
// operation.
ShouldRetryOnDirRead(ctx context.Context) bool
// RemoveDir is called on a `Node` before going through the normal
// `RemoveDir` flow, to give the Node a chance to handle it in a
// custom way. If the `Node` handles it internally, it should
// return `true`.
RemoveDir(ctx context.Context, dirName string) (
removeHandled bool, err error)
// WrapChild returns a wrapped version of child, if desired, to
// add custom behavior to the child node. An implementation that
// wraps another `Node` (`inner`) must first call
// `inner.WrapChild(child)` before performing its own wrapping
// operation, to ensure that all wrapping is preserved and that it
// happens in the correct order.
WrapChild(child Node) Node
// Unwrap returns the initial, unwrapped Node that was used to
// create this Node.
Unwrap() Node
// GetFS returns a file system interface that, if non-nil, should
// be used to satisfy any directory-related calls on this Node,
// instead of the standard, block-based method of acessing data.
// The provided context will be used, if possible, for any
// subsequent calls on the file system.
GetFS(ctx context.Context) billy.Filesystem
// GetFile returns a file interface that, if non-nil, should be
// used to satisfy any file-related calls on this Node, instead of
// the standard, block-based method of accessing data. The
// provided context will be used, if possible, for any subsequent
// calls on the file.
GetFile(ctx context.Context) billy.File
// EntryType is the type of the entry represented by this node.
EntryType() EntryType
// GetBlockID returns the block ID of the node.
GetBlockID() kbfsblock.ID
}
// KBFSOps handles all file system operations. Expands all indirect
// pointers. Operations that modify the server data change all the
// block IDs along the path, and so must return a path with the new
// BlockIds so the caller can update their references.
//
// KBFSOps implementations must guarantee goroutine-safety of calls on
// a per-top-level-folder basis.
//
// There are two types of operations that could block:
// * remote-sync operations, that need to synchronously update the
// MD for the corresponding top-level folder. When these
// operations return successfully, they will have guaranteed to
// have successfully written the modification to the KBFS servers.
// * remote-access operations, that don't sync any modifications to KBFS
// servers, but may block on reading data from the servers.
//
// KBFSOps implementations are supposed to give git-like consistency
// semantics for modification operations; they will be visible to
// other clients immediately after the remote-sync operations succeed,
// if and only if there was no other intervening modification to the
// same folder. If not, the change will be sync'd to the server in a
// special per-device "unmerged" area before the operation succeeds.
// In this case, the modification will not be visible to other clients
// until the KBFS code on this device performs automatic conflict
// resolution in the background.
//
// All methods take a Context (see https://blog.golang.org/context),
// and if that context is cancelled during the operation, KBFSOps will
// abort any blocking calls and return ctx.Err(). Any notifications
// resulting from an operation will also include this ctx (or a
// Context derived from it), allowing the caller to determine whether
// the notification is a result of their own action or an external
// action.
type KBFSOps interface {
// GetFavorites returns the logged-in user's list of favorite
// top-level folders. This is a remote-access operation.
GetFavorites(ctx context.Context) ([]Favorite, error)
// RefreshCachedFavorites tells the instances to forget any cached
// favorites list and fetch a new list from the server. The
// effects are asychronous; if there's an error refreshing the
// favorites, the cached favorites will become empty.
RefreshCachedFavorites(ctx context.Context)
// ClearCachedFavorites tells the instances to forget any cached
// favorites list, e.g. when a user logs out.
ClearCachedFavorites(ctx context.Context)
// AddFavorite adds the favorite to both the server and
// the local cache.
AddFavorite(ctx context.Context, fav Favorite) error
// DeleteFavorite deletes the favorite from both the server and
// the local cache. Idempotent, so it succeeds even if the folder
// isn't favorited.
DeleteFavorite(ctx context.Context, fav Favorite) error
// RefreshEditHistory asks the FBO for the given favorite to reload its
// edit history.
RefreshEditHistory(fav Favorite)
// GetTLFCryptKeys gets crypt key of all generations as well as
// TLF ID for tlfHandle. The returned keys (the keys slice) are ordered by
// generation, starting with the key for FirstValidKeyGen.
GetTLFCryptKeys(ctx context.Context, tlfHandle *TlfHandle) (
keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error)
// GetTLFID gets the TLF ID for tlfHandle.
GetTLFID(ctx context.Context, tlfHandle *TlfHandle) (tlf.ID, error)
// GetTLFHandle returns the TLF handle for a given node.
GetTLFHandle(ctx context.Context, node Node) (*TlfHandle, error)
// GetOrCreateRootNode returns the root node and root entry
// info associated with the given TLF handle and branch, if
// the logged-in user has read permissions to the top-level
// folder. It creates the folder if one doesn't exist yet (and
// branch == MasterBranch), and the logged-in user has write
// permissions to the top-level folder. This is a
// remote-access operation.
GetOrCreateRootNode(
ctx context.Context, h *TlfHandle, branch BranchName) (
node Node, ei EntryInfo, err error)
// GetRootNode is like GetOrCreateRootNode but if the root node
// does not exist it will return a nil Node and not create it.
GetRootNode(
ctx context.Context, h *TlfHandle, branch BranchName) (
node Node, ei EntryInfo, err error)
// GetDirChildren returns a map of children in the directory,
// mapped to their EntryInfo, if the logged-in user has read
// permission for the top-level folder. This is a remote-access
// operation.
GetDirChildren(ctx context.Context, dir Node) (map[string]EntryInfo, error)
// Lookup returns the Node and entry info associated with a
// given name in a directory, if the logged-in user has read
// permissions to the top-level folder. The returned Node is nil
// if the name is a symlink. This is a remote-access operation.
Lookup(ctx context.Context, dir Node, name string) (Node, EntryInfo, error)
// Stat returns the entry info associated with a
// given Node, if the logged-in user has read permissions to the
// top-level folder. This is a remote-access operation.
Stat(ctx context.Context, node Node) (EntryInfo, error)
// CreateDir creates a new subdirectory under the given node, if
// the logged-in user has write permission to the top-level
// folder. Returns the new Node for the created subdirectory, and
// its new entry info. This is a remote-sync operation.
CreateDir(ctx context.Context, dir Node, name string) (
Node, EntryInfo, error)
// CreateFile creates a new file under the given node, if the
// logged-in user has write permission to the top-level folder.
// Returns the new Node for the created file, and its new
// entry info. excl (when implemented) specifies whether this is an exclusive
// create. Semantically setting excl to WithExcl is like O_CREAT|O_EXCL in a
// Unix open() call.
//
// This is a remote-sync operation.
CreateFile(ctx context.Context, dir Node, name string, isExec bool, excl Excl) (
Node, EntryInfo, error)
// CreateLink creates a new symlink under the given node, if the
// logged-in user has write permission to the top-level folder.
// Returns the new entry info for the created symlink. This
// is a remote-sync operation.
CreateLink(ctx context.Context, dir Node, fromName string, toPath string) (
EntryInfo, error)
// RemoveDir removes the subdirectory represented by the given
// node, if the logged-in user has write permission to the
// top-level folder. Will return an error if the subdirectory is
// not empty. This is a remote-sync operation.
RemoveDir(ctx context.Context, dir Node, dirName string) error
// RemoveEntry removes the directory entry represented by the
// given node, if the logged-in user has write permission to the
// top-level folder. This is a remote-sync operation.
RemoveEntry(ctx context.Context, dir Node, name string) error
// Rename performs an atomic rename operation with a given
// top-level folder if the logged-in user has write permission to
// that folder, and will return an error if nodes from different
// folders are passed in. Also returns an error if the new name
// already has an entry corresponding to an existing directory
// (only non-dir types may be renamed over). This is a
// remote-sync operation.
Rename(ctx context.Context, oldParent Node, oldName string, newParent Node,
newName string) error
// Read fills in the given buffer with data from the file at the
// given node starting at the given offset, if the logged-in user
// has read permission to the top-level folder. The read data
// reflects any outstanding writes and truncates to that file that
// have been written through this KBFSOps object, even if those
// writes have not yet been sync'd. There is no guarantee that
// Read returns all of the requested data; it will return the
// number of bytes that it wrote to the dest buffer. Reads on an
// unlinked file may or may not succeed, depending on whether or
// not the data has been cached locally. If (0, nil) is returned,
// that means EOF has been reached. This is a remote-access
// operation.
Read(ctx context.Context, file Node, dest []byte, off int64) (int64, error)
// Write modifies the file at the given node, by writing the given
// buffer at the given offset within the file, if the logged-in
// user has write permission to the top-level folder. It
// overwrites any data already there, and extends the file size as
// necessary to accomodate the new data. It guarantees to write
// the entire buffer in one operation. Writes on an unlinked file
// may or may not succeed as no-ops, depending on whether or not
// the necessary blocks have been locally cached. This is a
// remote-access operation.
Write(ctx context.Context, file Node, data []byte, off int64) error
// Truncate modifies the file at the given node, by either
// shrinking or extending its size to match the given size, if the
// logged-in user has write permission to the top-level folder.
// If extending the file, it pads the new data with 0s. Truncates
// on an unlinked file may or may not succeed as no-ops, depending
// on whether or not the necessary blocks have been locally
// cached. This is a remote-access operation.
Truncate(ctx context.Context, file Node, size uint64) error
// SetEx turns on or off the executable bit on the file
// represented by a given node, if the logged-in user has write
// permissions to the top-level folder. This is a remote-sync
// operation.
SetEx(ctx context.Context, file Node, ex bool) error
// SetMtime sets the modification time on the file represented by
// a given node, if the logged-in user has write permissions to
// the top-level folder. If mtime is nil, it is a noop. This is
// a remote-sync operation.
SetMtime(ctx context.Context, file Node, mtime *time.Time) error
// SyncAll flushes all outstanding writes and truncates for any
// dirty files to the KBFS servers within the given folder, if the
// logged-in user has write permissions to the top-level folder.
// If done through a file system interface, this may include
// modifications done via multiple file handles. This is a
// remote-sync operation.
SyncAll(ctx context.Context, folderBranch FolderBranch) error
// FolderStatus returns the status of a particular folder/branch, along
// with a channel that will be closed when the status has been
// updated (to eliminate the need for polling this method).
FolderStatus(ctx context.Context, folderBranch FolderBranch) (
FolderBranchStatus, <-chan StatusUpdate, error)
// Status returns the status of KBFS, along with a channel that will be
// closed when the status has been updated (to eliminate the need for
// polling this method). Note that this channel only applies to
// connection status changes.
//
// KBFSStatus can be non-empty even if there is an error.
Status(ctx context.Context) (
KBFSStatus, <-chan StatusUpdate, error)
// UnstageForTesting clears out this device's staged state, if
// any, and fast-forwards to the current head of this
// folder-branch.
UnstageForTesting(ctx context.Context, folderBranch FolderBranch) error
// RequestRekey requests to rekey this folder. Note that this asynchronously
// requests a rekey, so canceling ctx doesn't cancel the rekey.
RequestRekey(ctx context.Context, id tlf.ID)
// SyncFromServer blocks until the local client has contacted the
// server and guaranteed that all known updates for the given
// top-level folder have been applied locally (and notifications
// sent out to any observers). It returns an error if this
// folder-branch is currently unmerged or dirty locally. If
// lockBeforeGet is non-nil, it blocks on idempotently taking the
// lock from server at the time it gets any metadata.
SyncFromServer(ctx context.Context,
folderBranch FolderBranch, lockBeforeGet *keybase1.LockID) error
// GetUpdateHistory returns a complete history of all the merged
// updates of the given folder, in a data structure that's
// suitable for encoding directly into JSON. This is an expensive
// operation, and should only be used for ocassional debugging.
// Note that the history does not include any unmerged changes or
// outstanding writes from the local device.
GetUpdateHistory(ctx context.Context, folderBranch FolderBranch) (
history TLFUpdateHistory, err error)
// GetEditHistory returns the edit history of the TLF, clustered
// by writer.
GetEditHistory(ctx context.Context, folderBranch FolderBranch) (
tlfHistory keybase1.FSFolderEditHistory, err error)
// GetNodeMetadata gets metadata associated with a Node.
GetNodeMetadata(ctx context.Context, node Node) (NodeMetadata, error)
// Shutdown is called to clean up any resources associated with
// this KBFSOps instance.
Shutdown(ctx context.Context) error
// PushConnectionStatusChange updates the status of a service for
// human readable connection status tracking.
PushConnectionStatusChange(service string, newStatus error)
// PushStatusChange causes Status listeners to be notified via closing
// the status channel.
PushStatusChange()
// ClearPrivateFolderMD clears any cached private folder metadata,
// e.g. on a logout.
ClearPrivateFolderMD(ctx context.Context)
// ForceFastForward forwards the nodes of all folders that have
// been previously cleared with `ClearPrivateFolderMD` to their
// newest version. It works asynchronously, so no error is
// returned.
ForceFastForward(ctx context.Context)
// InvalidateNodeAndChildren sends invalidation messages for the
// given node and all of its children that are currently in the
// NodeCache. It's useful if the caller has outside knowledge of
// data changes to that node or its children that didn't come
// through the usual MD update channels (e.g., autogit nodes need
// invalidation when the corresponding git repo is updated).
InvalidateNodeAndChildren(ctx context.Context, node Node) error
// TeamNameChanged indicates that a team has changed its name, and
// we should clean up any outstanding handle info associated with
// the team ID.
TeamNameChanged(ctx context.Context, tid keybase1.TeamID)
// TeamAbandoned indicates that a team has been abandoned, and
// shouldn't be referred to by its previous name anymore.
TeamAbandoned(ctx context.Context, tid keybase1.TeamID)
// MigrateToImplicitTeam migrates the given folder from a private-
// or public-keyed folder, to a team-keyed folder. If it's
// already a private/public team-keyed folder, nil is returned.
MigrateToImplicitTeam(ctx context.Context, id tlf.ID) error
// KickoffAllOutstandingRekeys kicks off all outstanding rekeys. It does
// nothing to folders that have not scheduled a rekey. This should be
// called when we receive an event of "paper key cached" from service.
KickoffAllOutstandingRekeys() error
// NewNotificationChannel is called to notify any existing TLF
// matching `handle` that a new kbfs-edits channel is available.
NewNotificationChannel(
ctx context.Context, handle *TlfHandle, convID chat1.ConversationID,
channelName string)
// Reset completely resets the given folder. Should only be
// called after explicit user confirmation. After the call,
// `handle` has the new TLF ID.
Reset(ctx context.Context, handle *TlfHandle) error
// GetSyncConfig returns the sync state configuration for the
// given TLF.
GetSyncConfig(ctx context.Context, tlfID tlf.ID) (
keybase1.FolderSyncConfig, error)
// SetSyncConfig sets the sync state configuration for the given
// TLF to either fully enabled, fully disabled, or partially
// syncing selected paths. If syncing is disabled, it returns a
// channel that is closed when all of the TLF's blocks have been
// removed from the sync cache. For a partially-synced folder,
// the config must contain no absolute paths, no duplicate paths,
// and no relative paths that go out of the TLF.
SetSyncConfig(
ctx context.Context, tlfID tlf.ID, config keybase1.FolderSyncConfig) (
<-chan error, error)
}
type merkleRootGetter interface {
// GetCurrentMerkleRoot returns the current root of the global
// Keybase Merkle tree.
GetCurrentMerkleRoot(ctx context.Context) (
keybase1.MerkleRootV2, time.Time, error)
// VerifyMerkleRoot checks that the specified merkle root
// contains the given KBFS root; if not, it returns an error.
VerifyMerkleRoot(
ctx context.Context, root keybase1.MerkleRootV2,
kbfsRoot keybase1.KBFSRoot) error
}
type gitMetadataPutter interface {
PutGitMetadata(ctx context.Context, folder keybase1.Folder,
repoID keybase1.RepoID, metadata keybase1.GitLocalMetadata) error
}
// KeybaseService is an interface for communicating with the keybase
// service.
type KeybaseService interface {
merkleRootGetter
gitMetadataPutter
// Resolve, given an assertion, resolves it to a username/UID
// pair. The username <-> UID mapping is trusted and
// immutable, so it can be cached. If the assertion is just
// the username or a UID assertion, then the resolution can
// also be trusted. If the returned pair is equal to that of
// the current session, then it can also be
// trusted. Otherwise, Identify() needs to be called on the
// assertion before the assertion -> (username, UID) mapping
// can be trusted.
Resolve(ctx context.Context, assertion string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error)
// Identify, given an assertion, returns a UserInfo struct
// with the user that matches that assertion, or an error
// otherwise. The reason string is displayed on any tracker
// popups spawned.
Identify(ctx context.Context, assertion, reason string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error)
// NormalizeSocialAssertion creates a SocialAssertion from its input and
// normalizes it. The service name will be lowercased. If the service is
// case-insensitive, then the username will also be lowercased. Colon
// assertions (twitter:user) will be transformed to the user@twitter
// format. Only registered services are allowed.
NormalizeSocialAssertion(
ctx context.Context, assertion string) (keybase1.SocialAssertion, error)
// ResolveIdentifyImplicitTeam resolves, and optionally
// identifies, an implicit team. If the implicit team doesn't yet
// exist, and doIdentifies is true, one is created.
ResolveIdentifyImplicitTeam(
ctx context.Context, assertions, suffix string, tlfType tlf.Type,
doIdentifies bool, reason string) (ImplicitTeamInfo, error)
// ResolveImplicitTeamByID resolves an implicit team to a team
// name, given a team ID.
ResolveImplicitTeamByID(
ctx context.Context, teamID keybase1.TeamID) (string, error)
// CreateTeamTLF associates the given TLF ID with the team ID in
// the team's sigchain. If the team already has a TLF ID
// associated with it, this overwrites it.
CreateTeamTLF(
ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error
// GetTeamSettings returns the KBFS settings for the given team.
GetTeamSettings(ctx context.Context, teamID keybase1.TeamID) (
keybase1.KBFSTeamSettings, error)
// LoadUserPlusKeys returns a UserInfo struct for a
// user with the specified UID.
// If you have the UID for a user and don't require Identify to
// validate an assertion or the identity of a user, use this to
// get UserInfo structs as it is much cheaper than Identify.
//
// pollForKID, if non empty, causes `PollForKID` field to be populated, which
// causes the service to poll for the given KID. This is useful during
// provisioning where the provisioner needs to get the MD revision that the
// provisionee has set the rekey bit on.
LoadUserPlusKeys(ctx context.Context,
uid keybase1.UID, pollForKID keybase1.KID) (UserInfo, error)
// LoadTeamPlusKeys returns a TeamInfo struct for a team with the
// specified TeamID. The caller can specify `desiredKeyGen` to
// force a server check if that particular key gen isn't yet
// known; it may be set to UnspecifiedKeyGen if no server check is
// required. The caller can specify `desiredUID` and
// `desiredRole` to force a server check if that particular UID
// isn't a member of the team yet according to local caches; it
// may be set to "" if no server check is required.
LoadTeamPlusKeys(ctx context.Context, tid keybase1.TeamID,
tlfType tlf.Type, desiredKeyGen kbfsmd.KeyGen,
desiredUser keybase1.UserVersion, desiredKey kbfscrypto.VerifyingKey,
desiredRole keybase1.TeamRole) (TeamInfo, error)
// CurrentSession returns a SessionInfo struct with all the
// information for the current session, or an error otherwise.
CurrentSession(ctx context.Context, sessionID int) (SessionInfo, error)
// FavoriteAdd adds the given folder to the list of favorites.
FavoriteAdd(ctx context.Context, folder keybase1.Folder) error
// FavoriteAdd removes the given folder from the list of
// favorites.
FavoriteDelete(ctx context.Context, folder keybase1.Folder) error
// FavoriteList returns the current list of favorites.
FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error)
// EncryptFavorites encrypts cached favorites to store on disk.
EncryptFavorites(ctx context.Context, dataToEncrypt []byte) ([]byte, error)
// DecryptFavorites decrypts cached favorites stored on disk.
DecryptFavorites(ctx context.Context, dataToDecrypt []byte) ([]byte, error)
// Notify sends a filesystem notification.
Notify(ctx context.Context, notification *keybase1.FSNotification) error
// NotifyPathUpdated sends a path updated notification.
NotifyPathUpdated(ctx context.Context, path string) error
// NotifySyncStatus sends a sync status notification.
NotifySyncStatus(ctx context.Context,
status *keybase1.FSPathSyncStatus) error
// FlushUserFromLocalCache instructs this layer to clear any
// KBFS-side, locally-cached information about the given user.
// This does NOT involve communication with the daemon, this is
// just to force future calls loading this user to fall through to
// the daemon itself, rather than being served from the cache.
FlushUserFromLocalCache(ctx context.Context, uid keybase1.UID)
// TODO: Add CryptoClient methods, too.
// EstablishMountDir asks the service for the current mount path
// and sets it if not established.
EstablishMountDir(ctx context.Context) (string, error)
// Shutdown frees any resources associated with this
// instance. No other methods may be called after this is
// called.
Shutdown()
}
// KeybaseServiceCn defines methods needed to construct KeybaseService
// and Crypto implementations.
type KeybaseServiceCn interface {
NewKeybaseService(
config Config, params InitParams, ctx Context, log logger.Logger) (
KeybaseService, error)
NewCrypto(
config Config, params InitParams, ctx Context, log logger.Logger) (
Crypto, error)
NewChat(
config Config, params InitParams, ctx Context, log logger.Logger) (
Chat, error)
}
type resolver interface {
// Resolve, given an assertion, resolves it to a username/UID
// pair. The username <-> UID mapping is trusted and
// immutable, so it can be cached. If the assertion is just
// the username or a UID assertion, then the resolution can
// also be trusted. If the returned pair is equal to that of
// the current session, then it can also be
// trusted. Otherwise, Identify() needs to be called on the
// assertion before the assertion -> (username, UserOrTeamID) mapping
// can be trusted.
//
// TODO: some of the above assumptions on cacheability aren't
// right for subteams, which can change their name, so this may
// need updating.
Resolve(ctx context.Context, assertion string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error)
// ResolveImplicitTeam resolves the given implicit team.
ResolveImplicitTeam(
ctx context.Context, assertions, suffix string, tlfType tlf.Type) (
ImplicitTeamInfo, error)
// ResolveImplicitTeamByID resolves the given implicit team, given
// a team ID.
ResolveImplicitTeamByID(
ctx context.Context, teamID keybase1.TeamID, tlfType tlf.Type) (
ImplicitTeamInfo, error)
// ResolveTeamTLFID returns the TLF ID associated with a given
// team ID, or tlf.NullID if no ID is yet associated with that
// team.
ResolveTeamTLFID(ctx context.Context, teamID keybase1.TeamID) (
tlf.ID, error)
// NormalizeSocialAssertion creates a SocialAssertion from its input and
// normalizes it. The service name will be lowercased. If the service is
// case-insensitive, then the username will also be lowercased. Colon
// assertions (twitter:user) will be transformed to the user@twitter
// format. Only registered services are allowed.
NormalizeSocialAssertion(
ctx context.Context, assertion string) (keybase1.SocialAssertion, error)
}
type identifier interface {
// Identify resolves an assertion (which could also be a
// username) to a UserInfo struct, spawning tracker popups if
// necessary. The reason string is displayed on any tracker
// popups spawned.
Identify(ctx context.Context, assertion, reason string) (
kbname.NormalizedUsername, keybase1.UserOrTeamID, error)
// IdentifyImplicitTeam identifies (and creates if necessary) the
// given implicit team.
IdentifyImplicitTeam(
ctx context.Context, assertions, suffix string, tlfType tlf.Type,
reason string) (ImplicitTeamInfo, error)
}
type normalizedUsernameGetter interface {
// GetNormalizedUsername returns the normalized username
// corresponding to the given UID.
GetNormalizedUsername(ctx context.Context, id keybase1.UserOrTeamID) (
kbname.NormalizedUsername, error)
}
// CurrentSessionGetter is an interface for objects that can return
// session info.
type CurrentSessionGetter interface {
// GetCurrentSession gets the current session info.
GetCurrentSession(ctx context.Context) (SessionInfo, error)
}
// teamMembershipChecker is a copy of kbfsmd.TeamMembershipChecker for
// embedding in KBPKI. Unfortunately, this is necessary since mockgen
// can't handle embedded interfaces living in other packages.
type teamMembershipChecker interface {
// IsTeamWriter is a copy of
// kbfsmd.TeamMembershipChecker.IsTeamWriter.
IsTeamWriter(ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey) (bool, error)
// NoLongerTeamWriter returns the global Merkle root of the
// most-recent time the given user (with the given device key,
// which implies an eldest seqno) transitioned from being a writer
// to not being a writer on the given team. If the user was never
// a writer of the team, it returns an error.
NoLongerTeamWriter(
ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) (
keybase1.MerkleRootV2, error)
// IsTeamReader is a copy of
// kbfsmd.TeamMembershipChecker.IsTeamWriter.
IsTeamReader(ctx context.Context, tid keybase1.TeamID, uid keybase1.UID) (
bool, error)
}
type teamKeysGetter interface {
// GetTeamTLFCryptKeys gets all of a team's secret crypt keys, by
// generation, as well as the latest key generation number for the
// team. The caller can specify `desiredKeyGen` to force a server
// check if that particular key gen isn't yet known; it may be set
// to UnspecifiedKeyGen if no server check is required.
GetTeamTLFCryptKeys(ctx context.Context, tid keybase1.TeamID,
desiredKeyGen kbfsmd.KeyGen) (
map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey, kbfsmd.KeyGen, error)
}
type teamRootIDGetter interface {
// GetTeamRootID returns the root team ID for the given (sub)team
// ID.
GetTeamRootID(ctx context.Context, tid keybase1.TeamID) (
keybase1.TeamID, error)
}
// KBPKI interacts with the Keybase daemon to fetch user info.
type KBPKI interface {
CurrentSessionGetter
resolver
identifier
normalizedUsernameGetter
merkleRootGetter
teamMembershipChecker
teamKeysGetter
teamRootIDGetter
gitMetadataPutter
// HasVerifyingKey returns nil if the given user has the given
// VerifyingKey, and an error otherwise. If the revoked key was
// valid according to the untrusted server timestamps, a special
// error type `RevokedDeviceVerificationError` is returned, which
// includes information the caller can use to verify the key using
// the merkle tree.
HasVerifyingKey(ctx context.Context, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey,
atServerTime time.Time) error
// GetCryptPublicKeys gets all of a user's crypt public keys (including
// paper keys).
GetCryptPublicKeys(ctx context.Context, uid keybase1.UID) (
[]kbfscrypto.CryptPublicKey, error)
// TODO: Split the methods below off into a separate
// FavoriteOps interface.
// FavoriteAdd adds folder to the list of the logged in user's
// favorite folders. It is idempotent.
FavoriteAdd(ctx context.Context, folder keybase1.Folder) error
// FavoriteDelete deletes folder from the list of the logged in user's
// favorite folders. It is idempotent.
FavoriteDelete(ctx context.Context, folder keybase1.Folder) error
// FavoriteList returns the list of all favorite folders for
// the logged in user.
FavoriteList(ctx context.Context) ([]keybase1.Folder, error)
// CreateTeamTLF associates the given TLF ID with the team ID in
// the team's sigchain. If the team already has a TLF ID
// associated with it, this overwrites it.
CreateTeamTLF(
ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error
// Notify sends a filesystem notification.
Notify(ctx context.Context, notification *keybase1.FSNotification) error
// NotifyPathUpdated sends a path updated notification.
NotifyPathUpdated(ctx context.Context, path string) error
}
// KeyMetadata is an interface for something that holds key
// information. This is usually implemented by RootMetadata.
type KeyMetadata interface {
// TlfID returns the ID of the TLF for which this object holds
// key info.
TlfID() tlf.ID
// TypeForKeying returns the keying type for this MD.
TypeForKeying() tlf.KeyingType
// LatestKeyGeneration returns the most recent key generation
// with key data in this object, or PublicKeyGen if this TLF
// is public.
LatestKeyGeneration() kbfsmd.KeyGen
// GetTlfHandle returns the handle for the TLF. It must not
// return nil.
//
// TODO: Remove the need for this function in this interface,
// so that kbfsmd.RootMetadata can implement this interface
// fully.
GetTlfHandle() *TlfHandle
// IsWriter checks that the given user is a valid writer of the TLF
// right now.
IsWriter(
ctx context.Context, checker kbfsmd.TeamMembershipChecker,
uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) (
bool, error)
// HasKeyForUser returns whether or not the given user has
// keys for at least one device. Returns an error if the TLF
// is public.
HasKeyForUser(user keybase1.UID) (bool, error)
// GetTLFCryptKeyParams returns all the necessary info to
// construct the TLF crypt key for the given key generation,
// user, and device (identified by its crypt public key), or
// false if not found. This returns an error if the TLF is
// public.
GetTLFCryptKeyParams(
keyGen kbfsmd.KeyGen, user keybase1.UID,
key kbfscrypto.CryptPublicKey) (
kbfscrypto.TLFEphemeralPublicKey,
kbfscrypto.EncryptedTLFCryptKeyClientHalf,
kbfscrypto.TLFCryptKeyServerHalfID, bool, error)
// StoresHistoricTLFCryptKeys returns whether or not history keys are
// symmetrically encrypted; if not, they're encrypted per-device.
StoresHistoricTLFCryptKeys() bool
// GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given
// generation using the current generation's TLFCryptKey.
GetHistoricTLFCryptKey(codec kbfscodec.Codec, keyGen kbfsmd.KeyGen,
currentKey kbfscrypto.TLFCryptKey) (
kbfscrypto.TLFCryptKey, error)
}
// KeyMetadataWithRootDirEntry is like KeyMetadata, but can also
// return the root dir entry for the associated MD update.
type KeyMetadataWithRootDirEntry interface {
KeyMetadata
// GetRootDirEntry returns the root directory entry for the
// associated MD.
GetRootDirEntry() DirEntry
}
type encryptionKeyGetter interface {
// GetTLFCryptKeyForEncryption gets the crypt key to use for
// encryption (i.e., with the latest key generation) for the
// TLF with the given metadata.
GetTLFCryptKeyForEncryption(ctx context.Context, kmd KeyMetadata) (
kbfscrypto.TLFCryptKey, error)
}
type mdDecryptionKeyGetter interface {
// GetTLFCryptKeyForMDDecryption gets the crypt key to use for the
// TLF with the given metadata to decrypt the private portion of
// the metadata. It finds the appropriate key from mdWithKeys
// (which in most cases is the same as mdToDecrypt) if it's not
// already cached.
GetTLFCryptKeyForMDDecryption(ctx context.Context,
kmdToDecrypt, kmdWithKeys KeyMetadata) (
kbfscrypto.TLFCryptKey, error)
}
type blockDecryptionKeyGetter interface {
// GetTLFCryptKeyForBlockDecryption gets the crypt key to use
// for the TLF with the given metadata to decrypt the block
// pointed to by the given pointer.
GetTLFCryptKeyForBlockDecryption(ctx context.Context, kmd KeyMetadata,
blockPtr BlockPointer) (kbfscrypto.TLFCryptKey, error)
}