forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interfaces.go
2493 lines (2276 loc) · 108 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 (
"context"
"os"
"time"
"github.com/keybase/client/go/kbfs/data"
"github.com/keybase/client/go/kbfs/favorites"
"github.com/keybase/client/go/kbfs/idutil"
"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/libkey"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/kbfs/tlfhandle"
"github.com/keybase/client/go/libkb"
"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"
billy "gopkg.in/src-d/go-billy.v4"
)
type logMaker interface {
MakeLogger(module string) logger.Logger
MakeVLogger(logger.Logger) *libkb.VDebugLog
}
type blockCacher interface {
BlockCache() data.BlockCache
}
type keyGetterGetter interface {
keyGetter() blockKeyGetter
}
type codecGetter interface {
Codec() kbfscodec.Codec
}
type blockOpsGetter interface {
BlockOps() BlockOps
}
type blockServerGetter interface {
BlockServer() BlockServer
}
type cryptoPureGetter interface {
cryptoPure() cryptoPure
}
type cryptoGetter interface {
Crypto() Crypto
}
type chatGetter interface {
Chat() Chat
}
type currentSessionGetterGetter interface {
CurrentSessionGetter() idutil.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 reporterGetter interface {
Reporter() Reporter
}
type diskLimiterGetter interface {
DiskLimiter() DiskLimiter
}
type syncedTlfGetterSetter interface {
IsSyncedTlf(tlfID tlf.ID) bool
IsSyncedTlfPath(tlfPath string) bool
GetTlfSyncState(tlfID tlf.ID) FolderSyncConfig
SetTlfSyncState(
ctx context.Context, tlfID tlf.ID, config FolderSyncConfig) (
<-chan error, error)
GetAllSyncedTlfs() []tlf.ID
idutil.OfflineStatusGetter
}
type blockRetrieverGetter interface {
BlockRetriever() BlockRetriever
}
type settingsDBGetter interface {
GetSettingsDB() *SettingsDB
}
// 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() data.FolderBranch
// GetBasename returns the current basename of the node, or ""
// if the node has been unlinked.
GetBasename() data.PathPartString
// GetPathPlaintextSansTlf returns the cleaned path of the node in
// plaintext.
GetPathPlaintextSansTlf() (string, bool)
// 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 types `FakeDir` or `FakeFile`
// to indicate that the caller should pretend the entry exists,
// even if it really does not. In the case of fake files, a
// non-nil `fi` can be returned and used by the caller to
// construct the dir entry for the file. 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 data.PathPartString) (
shouldCreate bool, newCtx context.Context, et data.EntryType,
fi os.FileInfo, sympath data.PathPartString)
// 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 data.PathPartString) (
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() data.EntryType
// GetBlockID returns the block ID of the node.
GetBlockID() kbfsblock.ID
// FillCacheDuration sets `d` to the suggested cache time for this
// node, if desired.
FillCacheDuration(d *time.Duration)
// Obfuscator returns something that can obfuscate the child
// entries of this Node in the case of directories; for other
// types, it returns nil.
Obfuscator() data.Obfuscator
// ChildName returns an obfuscatable version of the given name of
// a child entry of this node.
ChildName(name string) data.PathPartString
}
// 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.
//
// Each directory and file name is specified with a
// `data.PathPartString`, to protect against accidentally logging
// plaintext filenames. These can be easily created from the parent
// node's `Node` object with the `ChildName` function.
type KBFSOps interface {
// GetFavorites returns the logged-in user's list of favorite
// top-level folders. This is a remote-access operation when the cache
// is empty or expired.
GetFavorites(ctx context.Context) ([]favorites.Folder, error)
// GetFavoritesAll returns the logged-in user's lists of favorite, ignored,
// and new top-level folders. This is a remote-access operation when the
// cache is empty or expired.
GetFavoritesAll(ctx context.Context) (keybase1.FavoritesResult, 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, mode FavoritesRefreshMode)
// 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 favorites.Folder, data favorites.Data) 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 favorites.Folder) error
// SetFavoritesHomeTLFInfo sets the home TLF TeamIDs to initialize the
// favorites cache on login.
SetFavoritesHomeTLFInfo(ctx context.Context, info homeTLFInfo)
// RefreshEditHistory asks the FBO for the given favorite to reload its
// edit history.
RefreshEditHistory(fav favorites.Folder)
// 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.Handle) (
keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error)
// GetTLFID gets the TLF ID for tlfHandle.
GetTLFID(ctx context.Context, tlfHandle *tlfhandle.Handle) (tlf.ID, error)
// GetTLFHandle returns the TLF handle for a given node.
GetTLFHandle(ctx context.Context, node Node) (*tlfhandle.Handle, 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.Handle, branch data.BranchName) (
node Node, ei data.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.Handle, branch data.BranchName) (
node Node, ei data.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[data.PathPartString]data.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 data.PathPartString) (
Node, data.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) (data.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 data.PathPartString) (
Node, data.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 data.PathPartString, isExec bool,
excl Excl) (Node, data.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. The
// symlink is represented as a single `data.PathPartString`
// (generally obfuscated by `dir`'s Obfuscator) to avoid
// accidental logging, even though it could point outside of the
// directory. The deobfuscate command will inspect symlinks when
// deobfuscating to make this easier to debug. This is a
// remote-sync operation.
CreateLink(
ctx context.Context, dir Node, fromName, toPath data.PathPartString) (
data.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 data.PathPartString) 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 data.PathPartString) 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 data.PathPartString,
newParent Node, newName data.PathPartString) 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 data.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 data.FolderBranch) (
FolderBranchStatus, <-chan StatusUpdate, error)
// FolderConflictStatus is a lightweight method to return the
// conflict status of a particular folder/branch. (The conflict
// status is also available in `FolderBranchStatus`.)
FolderConflictStatus(ctx context.Context, folderBranch data.FolderBranch) (
keybase1.FolderConflictType, 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 data.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 data.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 data.FolderBranch) (
history TLFUpdateHistory, err error)
// GetEditHistory returns the edit history of the TLF, clustered
// by writer.
GetEditHistory(ctx context.Context, folderBranch data.FolderBranch) (
tlfHistory keybase1.FSFolderEditHistory, err error)
// GetNodeMetadata gets metadata associated with a Node.
GetNodeMetadata(ctx context.Context, node Node) (NodeMetadata, error)
// GetRootNodeMetadata gets metadata associated with the root node
// of a FolderBranch, and for convenience the TLF handle as well.
GetRootNodeMetadata(ctx context.Context, folderBranch data.FolderBranch) (
NodeMetadata, *tlfhandle.Handle, 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.Handle,
convID chat1.ConversationID, channelName string)
// ClearConflictView moves the conflict view of the given TLF out of the
// way and resets the state of the TLF.
ClearConflictView(ctx context.Context, tlfID tlf.ID) error
// FinishResolvingConflict removes the local view of a
// previously-cleared conflict.
FinishResolvingConflict(ctx context.Context, fb data.FolderBranch) error
// ForceStuckConflictForTesting forces the local view of the given
// TLF into a stuck conflict view, in order to test the above
// `ClearConflictView` method and related state changes.
ForceStuckConflictForTesting(ctx context.Context, tlfID tlf.ID) error
// 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.Handle) 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)
// AddRootNodeWrapper adds a new root node wrapper for every
// existing TLF. Any Nodes that have already been returned by
// `KBFSOps` won't use these wrappers.
AddRootNodeWrapper(func(Node) Node)
}
type gitMetadataPutter interface {
PutGitMetadata(ctx context.Context, folder keybase1.FolderHandle,
repoID keybase1.RepoID, metadata keybase1.GitLocalMetadata) error
}
// KeybaseService is an interface for communicating with the keybase
// service.
type KeybaseService interface {
idutil.KeybaseService
gitMetadataPutter
SubscriptionNotifier
// FavoriteAdd adds the given folder to the list of favorites.
FavoriteAdd(ctx context.Context, folder keybase1.FolderHandle) error
// FavoriteAdd removes the given folder from the list of
// favorites.
FavoriteDelete(ctx context.Context, folder keybase1.FolderHandle) error
// FavoriteList returns the current list of favorites.
FavoriteList(ctx context.Context, sessionID int) (keybase1.FavoritesResult,
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)
// NotifyOnlineStatusChanged notifies about online/offline status
// changes.
NotifyOnlineStatusChanged(ctx context.Context, online bool) 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
// NotifyOverallSyncStatus sends an overall sync status
// notification.
NotifyOverallSyncStatus(
ctx context.Context, status keybase1.FolderSyncStatus) error
// NotifyFavoritesChanged sends a notification that favorites have
// changed.
NotifyFavoritesChanged(ctx context.Context) 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)
// ClearCaches flushes all user and team info from KBFS-side
// caches.
ClearCaches(ctx context.Context)
// 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)
}
// 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.
//
// If the caller knows that the writership needs to be checked
// while offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `IsTeamWriter` might block on a network
// call.
IsTeamWriter(
ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey,
offline keybase1.OfflineAvailability) (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.
//
// If the caller knows that the writership needs to be checked
// while offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `NoLongerTeamWriter` might block on a
// network call.
NoLongerTeamWriter(
ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey,
offline keybase1.OfflineAvailability) (keybase1.MerkleRootV2, error)
// IsTeamReader is a copy of
// kbfsmd.TeamMembershipChecker.IsTeamWriter.
//
// If the caller knows that the readership needs to be checked
// while offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `IsTeamReader` might block on a
// network call.
IsTeamReader(
ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
offline keybase1.OfflineAvailability) (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.
//
// If the caller knows that the keys need to be retrieved while
// offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `GetTeamTLFCryptKeys` might block on a
// network call.
GetTeamTLFCryptKeys(ctx context.Context, tid keybase1.TeamID,
desiredKeyGen kbfsmd.KeyGen, offline keybase1.OfflineAvailability) (
map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey, kbfsmd.KeyGen, error)
}
type teamRootIDGetter interface {
// GetTeamRootID returns the root team ID for the given (sub)team
// ID.
//
// If the caller knows that the root needs to be retrieved while
// offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `GetTeamRootID` might block on a network
// call.
GetTeamRootID(
ctx context.Context, tid keybase1.TeamID,
offline keybase1.OfflineAvailability) (keybase1.TeamID, error)
}
// KBPKI interacts with the Keybase daemon to fetch user info.
type KBPKI interface {
idutil.KBPKI
idutil.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.
//
// If the caller knows that the keys needs to be verified while
// offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `HasVerifyingKey` might block on a
// network call.
HasVerifyingKey(ctx context.Context, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey,
atServerTime time.Time, offline keybase1.OfflineAvailability) error
// GetCryptPublicKeys gets all of a user's crypt public keys (including
// paper keys).
//
// If the caller knows that the keys needs to be retrieved while
// offline, they should pass in
// `keybase1.OfflineAvailability_BEST_EFFORT` as the `offline`
// parameter. Otherwise `GetCryptPublicKeys` might block on a
// network call.
GetCryptPublicKeys(
ctx context.Context, uid keybase1.UID,
offline keybase1.OfflineAvailability) (
[]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.FolderHandle) error
// FavoriteDelete deletes folder from the list of the logged in user's
// favorite folders. It is idempotent.
FavoriteDelete(ctx context.Context, folder keybase1.FolderHandle) error
// FavoriteList returns the list of all favorite folders for
// the logged in user.
FavoriteList(ctx context.Context) (keybase1.FavoritesResult, 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
}
// KeyMetadataWithRootDirEntry is like KeyMetadata, but can also
// return the root dir entry for the associated MD update.
type KeyMetadataWithRootDirEntry interface {
libkey.KeyMetadata
// GetRootDirEntry returns the root directory entry for the
// associated MD.
GetRootDirEntry() data.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 libkey.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 libkey.KeyMetadata) (
kbfscrypto.TLFCryptKey, error)
// GetFirstTLFCryptKey gets the first valid crypt key for the
// TLF with the given metadata.
GetFirstTLFCryptKey(ctx context.Context, kmd libkey.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 libkey.KeyMetadata,
blockPtr data.BlockPointer) (kbfscrypto.TLFCryptKey, error)
}
type blockKeyGetter interface {
encryptionKeyGetter
blockDecryptionKeyGetter
}
// KeyManager fetches and constructs the keys needed for KBFS file
// operations.
type KeyManager interface {
blockKeyGetter
mdDecryptionKeyGetter
// GetTLFCryptKeyOfAllGenerations gets the crypt keys of all generations
// for current devices. keys contains crypt keys from all generations, in
// order, starting from FirstValidKeyGen.
GetTLFCryptKeyOfAllGenerations(ctx context.Context, kmd libkey.KeyMetadata) (
keys []kbfscrypto.TLFCryptKey, err error)
// Rekey checks the given MD object, if it is a private TLF,
// against the current set of device keys for all valid
// readers and writers. If there are any new devices, it
// updates all existing key generations to include the new
// devices. If there are devices that have been removed, it
// creates a new epoch of keys for the TLF. If there was an
// error, or the RootMetadata wasn't changed, it returns false.
// Otherwise, it returns true. If a new key generation is
// added the second return value points to this new key. This
// is to allow for caching of the TLF crypt key only after a
// successful merged write of the metadata. Otherwise we could
// prematurely pollute the key cache.
//
// If the given MD object is a public TLF, it simply updates
// the TLF's handle with any newly-resolved writers.
//
// If promptPaper is set, prompts for any unlocked paper keys.
// promptPaper shouldn't be set if md is for a public TLF.
Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
bool, *kbfscrypto.TLFCryptKey, error)
}
// Reporter exports events (asynchronously) to any number of sinks
type Reporter interface {
// ReportErr records that a given error happened.
ReportErr(ctx context.Context, tlfName tlf.CanonicalName, t tlf.Type,
mode ErrorModeType, err error)
// AllKnownErrors returns all errors known to this Reporter.
AllKnownErrors() []ReportedError
// NotifyOnlineStatusChanged sends the given notification to any sink.
OnlineStatusChanged(ctx context.Context, online bool)
// Notify sends the given notification to any sink.
Notify(ctx context.Context, notification *keybase1.FSNotification)
// NotifyPathUpdated sends the given notification to any sink.
NotifyPathUpdated(ctx context.Context, path string)
// NotifySyncStatus sends the given path sync status to any sink.
NotifySyncStatus(ctx context.Context, status *keybase1.FSPathSyncStatus)
// NotifyOverallSyncStatus sends the given path overall sync
// status to any sink.
NotifyOverallSyncStatus(
ctx context.Context, status keybase1.FolderSyncStatus)
// NotifyFavoritesChanged sends the a favorites invalidation to any sink.
NotifyFavoritesChanged(ctx context.Context)
// Shutdown frees any resources allocated by a Reporter.
Shutdown()
}
// MDCache gets and puts plaintext top-level metadata into the cache.
type MDCache interface {
// Get gets the metadata object associated with the given TLF ID,
// revision number, and branch ID (kbfsmd.NullBranchID for merged MD).
Get(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID) (ImmutableRootMetadata, error)
// Put stores the metadata object, only if an MD matching that TLF
// ID, revision number, and branch ID isn't already cached. If
// there is already a matching item in the cache, we require that
// caller manages the cache explicitly by deleting or replacing it
// explicitly. This should be used when putting existing MDs
// being fetched from the server.
Put(md ImmutableRootMetadata) error
// Delete removes the given metadata object from the cache if it exists.
Delete(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID)
// Replace replaces the entry matching the md under the old branch
// ID with the new one. If the old entry doesn't exist, this is
// equivalent to a Put, except that it overrides anything else
// that's already in the cache. This should be used when putting
// new MDs created locally.
Replace(newRmd ImmutableRootMetadata, oldBID kbfsmd.BranchID) error
// MarkPutToServer sets `PutToServer` to true for the specified
// MD, if it already exists in the cache.
MarkPutToServer(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID)
// GetIDForHandle retrieves a cached, trusted TLF ID for the given
// handle, if one exists.
GetIDForHandle(handle *tlfhandle.Handle) (tlf.ID, error)
// PutIDForHandle caches a trusted TLF ID for the given handle.
PutIDForHandle(handle *tlfhandle.Handle, id tlf.ID) error
// ChangeHandleForID moves an ID to be under a new handle, if the
// ID is cached already.
ChangeHandleForID(oldHandle *tlfhandle.Handle, newHandle *tlfhandle.Handle)
// GetNextMD returns a cached view of the next MD following the
// given global Merkle root.
GetNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno) (
nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
nextRootSeqno keybase1.Seqno, err error)
// PutNextMD caches a view of the next MD following the given
// global Merkle root.
PutNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno,
nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
nextRootSeqno keybase1.Seqno) error
}
// KeyCache handles caching for both TLFCryptKeys and BlockCryptKeys.
type KeyCache interface {
// GetTLFCryptKey gets the crypt key for the given TLF.
GetTLFCryptKey(tlf.ID, kbfsmd.KeyGen) (kbfscrypto.TLFCryptKey, error)
// PutTLFCryptKey stores the crypt key for the given TLF.
PutTLFCryptKey(tlf.ID, kbfsmd.KeyGen, kbfscrypto.TLFCryptKey) error
}
// DiskBlockCacheType specifies a type of an on-disk block cache.
type DiskBlockCacheType int
const (
// DiskBlockAnyCache indicates that any disk block cache is fine.
DiskBlockAnyCache DiskBlockCacheType = iota
// DiskBlockWorkingSetCache indicates that the working set cache
// should be used.
DiskBlockWorkingSetCache
// DiskBlockSyncCache indicates that the sync cache should be
// used.
DiskBlockSyncCache
)
func (dbct DiskBlockCacheType) String() string {
switch dbct {
case DiskBlockSyncCache:
return "DiskBlockSyncCache"
case DiskBlockWorkingSetCache:
return "DiskBlockWorkingSetCache"
case DiskBlockAnyCache:
return "DiskBlockAnyCache"
default:
return "unknown DiskBlockCacheType"
}
}
// DiskBlockCache caches blocks to the disk.