forked from hyperledger-archives/aries-framework-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestprovider.go
1233 lines (993 loc) · 38.2 KB
/
restprovider.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 SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package edv
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"sync"
spi "github.com/hyperledger/aries-framework-go/spi/storage"
)
const (
expressionTagNameOnlyLength = 1
expressionTagNameAndValueLength = 2
invalidTagName = `"%s" is an invalid tag name since it contains one or more ':' characters`
invalidTagValue = `"%s" is an invalid tag value since it contains one or more ':' characters`
)
var (
errEmptyKey = errors.New("key cannot be empty")
errInvalidQueryExpressionFormat = errors.New("invalid expression format. " +
"it must be in the following format: TagName:TagValue")
)
// RESTProviderOption allows for configuration of a RESTProvider.
type RESTProviderOption func(opts *RESTProvider)
// WithTLSConfig is an option that allows for the definition of a secured HTTP transport using a tls.Config instance.
func WithTLSConfig(tlsConfig *tls.Config) RESTProviderOption {
return func(opts *RESTProvider) {
opts.restClient.httpClient.Transport = &http.Transport{TLSClientConfig: tlsConfig}
}
}
// WithHeaders option is for setting additional http request headers (since it's a function, it can call a remote
// authorization server to fetch the necessary info needed in these headers).
func WithHeaders(addHeadersFunc addHeaders) RESTProviderOption {
return func(opts *RESTProvider) {
opts.restClient.headersFunc = addHeadersFunc
}
}
// WithFullDocumentsReturnedFromQueries option is a performance optimization that speeds up queries by getting
// full documents from the EDV server instead of only document locations - each of which would require a separate REST
// call to retrieve. The EDV server that this RESTProvider connects to must support the TrustBloc EDV server extension
// as defined here: https://github.com/trustbloc/edv/blob/main/docs/extensions.md#return-full-documents-on-query.
func WithFullDocumentsReturnedFromQueries() RESTProviderOption {
return func(restProvider *RESTProvider) {
restProvider.returnFullDocumentsOnQuery = true
}
}
// WithBatchEndpointExtension option is a performance optimization that allows for restStore.Batch to only require one
// REST call. The EDV server that this RESTProvider connects to must support the TrustBloc EDV server extension
// as defined here: https://github.com/trustbloc/edv/blob/main/docs/extensions.md#batch-endpoint.
func WithBatchEndpointExtension() RESTProviderOption {
return func(opts *RESTProvider) {
opts.batchEndpointExtensionEnabled = true
}
}
// RESTProvider is a spi.Provider that can be used to store data in a server supporting the
// data vault HTTP API as defined in https://identity.foundation/confidential-storage/#http-api.
type RESTProvider struct {
vaultID string
formatter *EncryptedFormatter
restClient *restClient
openStores map[string]*restStore
lock sync.RWMutex
returnFullDocumentsOnQuery bool
batchEndpointExtensionEnabled bool
}
// NewRESTProvider returns a new RESTProvider. edvServerURL is the base URL for the EDV server.
// vaultID is the ID of the vault where this provider will store data. The vault must be created in advance, and since
// the EDV REST API does not provide a method to check if a vault with a given ID exists, any errors due to a
// non-existent vault will be deferred until calls are actually made to it in the store.
func NewRESTProvider(edvServerURL, vaultID string, formatter *EncryptedFormatter,
options ...RESTProviderOption) *RESTProvider {
client := restClient{
edvServerURL: edvServerURL,
httpClient: &http.Client{},
}
restProvider := RESTProvider{
vaultID: vaultID,
formatter: formatter,
restClient: &client,
openStores: make(map[string]*restStore),
}
for _, opt := range options {
opt(&restProvider)
}
return &restProvider
}
type closer func(storeName string)
// OpenStore opens a new RESTStore, using name as the namespace.
func (r *RESTProvider) OpenStore(name string) (spi.Store, error) {
if name == "" {
return nil, fmt.Errorf("store name cannot be empty")
}
storeName := strings.ToLower(name)
r.lock.Lock()
defer r.lock.Unlock()
openStore := r.openStores[storeName]
if openStore == nil {
newStore := &restStore{
vaultID: r.vaultID,
name: storeName,
formatter: r.formatter,
restClient: r.restClient,
returnFullDocumentsOnQuery: r.returnFullDocumentsOnQuery,
batchEndpointExtensionEnabled: r.batchEndpointExtensionEnabled,
close: r.removeStore,
}
r.openStores[storeName] = newStore
return newStore, nil
}
return &restStore{
vaultID: r.vaultID,
name: name,
formatter: r.formatter,
restClient: r.restClient,
returnFullDocumentsOnQuery: r.returnFullDocumentsOnQuery,
}, nil
}
// SetStoreConfig isn't needed for EDV storage, since indexes are managed by the server automatically based on the
// tags used in values. This method simply stores the configuration in memory so that it can be retrieved later
// via the GetStoreConfig method, which allows it to be more consistent with how other store implementations work.
// TODO (#2492) Store store config in persistent EDV storage for true consistency with other store implementations.
func (r *RESTProvider) SetStoreConfig(name string, config spi.StoreConfiguration) error {
for _, tagName := range config.TagNames {
if strings.Contains(tagName, ":") {
return fmt.Errorf(invalidTagName, tagName)
}
}
openStore, ok := r.openStores[name]
if !ok {
return spi.ErrStoreNotFound
}
openStore.config = config
return nil
}
// GetStoreConfig returns the store configuration currently stored in memory.
func (r *RESTProvider) GetStoreConfig(name string) (spi.StoreConfiguration, error) {
openStore, ok := r.openStores[name]
if !ok {
return spi.StoreConfiguration{}, spi.ErrStoreNotFound
}
return openStore.config, nil
}
// GetOpenStores returns all currently open stores.
func (r *RESTProvider) GetOpenStores() []spi.Store {
r.lock.RLock()
defer r.lock.RUnlock()
openStores := make([]spi.Store, len(r.openStores))
var counter int
for _, db := range r.openStores {
openStores[counter] = db
counter++
}
return openStores
}
// Close always returns a nil error since there's nothing to close for a RESTProvider.
func (r *RESTProvider) Close() error {
return nil
}
func (r *RESTProvider) removeStore(name string) {
r.lock.Lock()
defer r.lock.Unlock()
_, ok := r.openStores[name]
if ok {
delete(r.openStores, name)
}
}
// restStore is a store for storing EDV documents via the REST API.
type restStore struct {
vaultID string
name string
formatter *EncryptedFormatter
restClient *restClient
config spi.StoreConfiguration
returnFullDocumentsOnQuery bool
batchEndpointExtensionEnabled bool
close closer
lock sync.RWMutex
}
// Put stores data into an EDV server.
func (r *restStore) Put(key string, value []byte, tags ...spi.Tag) error {
errInputValidation := validatePutInput(key, value, tags)
if errInputValidation != nil {
return errInputValidation
}
if r.formatter.UsesDeterministicKeyFormatting() {
err := r.putUsingDeterministicDocumentID(key, value, tags)
if err != nil {
return fmt.Errorf("failed to store data using a deterministic document ID: %w", err)
}
} else {
err := r.appendKeyTagThenLockAndPutUsingRandomDocumentID(key, value, tags)
if err != nil {
return fmt.Errorf("failed to store data using a random document ID: %w", err)
}
}
return nil
}
func (r *restStore) Get(key string) ([]byte, error) {
if key == "" {
return nil, errEmptyKey
}
var encryptedDocumentBytes []byte
var err error
if r.formatter.UsesDeterministicKeyFormatting() {
encryptedDocumentBytes, err = r.getEncryptedDocumentStoredUnderDeterministicID(key)
if err != nil {
return nil,
fmt.Errorf("failed to get encrypted document stored under a deterministic document ID: %w", err)
}
} else {
encryptedDocumentBytes, err = r.getEncryptedDocumentStoredUnderRandomID(key)
if err != nil {
return nil,
fmt.Errorf("failed to get encrypted document stored under a randomly-generated ID: %w", err)
}
}
_, value, _, err := r.formatter.Deformat("", encryptedDocumentBytes)
if err != nil {
return nil, fmt.Errorf("failed to decrypt encrypted document: %w", err)
}
return value, nil
}
func (r *restStore) GetTags(key string) ([]spi.Tag, error) {
if key == "" {
return nil, errEmptyKey
}
var encryptedDocumentBytes []byte
var err error
if r.formatter.UsesDeterministicKeyFormatting() {
encryptedDocumentBytes, err = r.getEncryptedDocumentStoredUnderDeterministicID(key)
if err != nil {
return nil,
fmt.Errorf("failed to get encrypted document stored under a deterministic document ID: %w", err)
}
} else {
encryptedDocumentBytes, err = r.getEncryptedDocumentStoredUnderRandomID(key)
if err != nil {
return nil,
fmt.Errorf("failed to get encrypted document stored under a randomly-generated ID: %w", err)
}
}
_, _, tags, err := r.formatter.Deformat("", encryptedDocumentBytes)
if err != nil {
return nil, fmt.Errorf("failed to decrypt encrypted document: %w", err)
}
if !r.formatter.UsesDeterministicKeyFormatting() {
tags = filterOutKeyTag(tags, key)
}
return tags, nil
}
// EDV doesn't support getting documents in bulk, so the best we can do is emulate it by doing a Get on each
// key. A more efficient way to get documents in bulk is to use tags and querying with the "return full documents
// on query" extension enabled, which is non-standard (as of writing).
func (r *restStore) GetBulk(keys ...string) ([][]byte, error) {
if len(keys) == 0 {
return nil, errors.New("keys slice must contain at least one key")
}
values := make([][]byte, len(keys))
r.lock.Lock()
defer r.lock.Unlock()
for i, key := range keys {
var err error
values[i], err = r.Get(key)
if err != nil && !errors.Is(err, spi.ErrDataNotFound) {
return nil, fmt.Errorf(`unexpected failure while getting value for key "%s": %w`, key, err)
}
}
return values, nil
}
// EDV doesn't support any of the current query options.
// spi.WithPageSize will simply be ignored since it only relates to performance and not the actual end result.
// spi.WithInitialPageNum and spi.WithSortOrder will result in an error being returned since those options do
// affect the results that the Iterator returns.
func (r *restStore) Query(expression string, options ...spi.QueryOption) (spi.Iterator, error) {
err := checkForUnsupportedQueryOptions(options)
if err != nil {
return nil, err
}
expressionTagName, expressionTagValue, err := parseQueryExpression(expression)
if err != nil {
return nil, fmt.Errorf("failed to parse query expression: %w", err)
}
tag, err := r.formatter.formatTag(r.name,
spi.Tag{Name: expressionTagName, Value: expressionTagValue})
if err != nil {
return nil, fmt.Errorf("failed to format tag for querying: %w", err)
}
return r.query(tag)
}
func (r *restStore) Delete(key string) error {
if key == "" {
return errEmptyKey
}
if r.formatter.UsesDeterministicKeyFormatting() {
err := r.deleteDocumentUsingDeterministicID(key)
if err != nil {
return fmt.Errorf("failed to delete document using deterministic ID: %w", err)
}
} else {
err := r.lockAndDeleteDocumentStoredUnderRandomID(key)
if err != nil {
return fmt.Errorf("failed to delete document using random ID: %w", err)
}
}
return nil
}
// TODO (#2494): Return a spi.MultiError from here in the case of a failure.
func (r *restStore) Batch(operations []spi.Operation) error {
for _, operation := range operations {
if operation.Key == "" {
return errEmptyKey
}
}
if r.batchEndpointExtensionEnabled {
err := r.fastBatchUsingBatchExtension(operations)
if err != nil {
return fmt.Errorf("failed to batch using batch extension: %w", err)
}
} else {
// If the batch extension hasn't been enabled, we will have to emulate the behaviour using the
// standard endpoints, which will be slower.
err := r.slowBatchUsingStandardEndpoints(operations)
if err != nil {
return fmt.Errorf("failed to batch using standard endpoints: %w", err)
}
}
return nil
}
func (r *restStore) Close() error {
r.close(r.name)
return nil
}
// restStore doesn't queue values, so there's never anything to flush.
func (r *restStore) Flush() error {
return nil
}
func (r *restStore) putUsingDeterministicDocumentID(key string, value []byte, tags []spi.Tag) error {
// If the batch endpoint extension is enabled, we can avoid the need to read the document first since the
// batch endpoint does upserts instead of explicit creates and updates.
if r.batchEndpointExtensionEnabled {
err := r.storeUsingDeterministicDocumentIDAndBatchEndpoint(key, value, tags)
if err != nil {
return fmt.Errorf("failed to store document using "+
"deterministic ID and batch endpoint: %w", err)
}
} else {
err := r.storeUsingDeterministicDocumentIDAndStandardEndpoints(key, value, tags)
if err != nil {
return fmt.Errorf("failed to store document using random document ID and "+
"standard endpoints: %w", err)
}
}
return nil
}
func (r *restStore) appendKeyTagThenLockAndPutUsingRandomDocumentID(key string, value []byte, tags []spi.Tag) error {
tags = append(tags, spi.Tag{Value: key})
r.lock.Lock()
defer r.lock.Unlock()
return r.putUsingRandomDocumentID(key, value, tags)
}
func (r *restStore) storeUsingDeterministicDocumentIDAndBatchEndpoint(key string, value []byte, tags []spi.Tag) error {
encryptedDocumentID, encryptedDocumentBytes, _, err :=
r.formatter.format(r.name, key, value, tags...)
if err != nil {
return fmt.Errorf("failed to generate the encrypted document ID and "+
"encrypted document bytes: %w", err)
}
err = r.restClient.batch(r.vaultID, []vaultOperation{{
Operation: upsertDocumentVaultOperation,
DocumentID: encryptedDocumentID,
EncryptedDocument: encryptedDocumentBytes,
}})
if err != nil {
return fmt.Errorf("failed to put data in EDV server via the batch endpoint "+
"(is it enabled in the EDV server?): %w", err)
}
return nil
}
func (r *restStore) storeUsingDeterministicDocumentIDAndStandardEndpoints(
key string, value []byte, tags []spi.Tag) error {
documentID, err := r.formatter.generateDeterministicDocumentID(r.name, key)
if err != nil {
return fmt.Errorf("failed to generate the encrypted document ID: %w", err)
}
err = r.createOrUpdateDocumentBasedOnDeterministicDocumentID(key, documentID, value, tags)
if err != nil {
return fmt.Errorf("failed to create or update document based on document ID: %w", err)
}
return nil
}
func (r *restStore) createOrUpdateDocumentBasedOnDeterministicDocumentID(
key, documentID string, value []byte, tags []spi.Tag) error {
_, err := r.restClient.readDocument(r.vaultID, documentID)
if err != nil {
if errors.Is(err, spi.ErrDataNotFound) {
err = r.formatTagsThenCreateDocument(key, documentID, value, tags)
if err != nil {
return fmt.Errorf("failed to format tags then create document: %w", err)
}
} else {
return fmt.Errorf(`failed to determine if an EDV document for key "%s" in store "%s" already exists: %w`,
key, r.name, err)
}
}
err = r.updateDocument(key, documentID, value, tags)
if err != nil {
return fmt.Errorf("failed to update document: %w", err)
}
return nil
}
func (r *restStore) updateDocument(key, documentID string, value []byte, tags []spi.Tag) error {
formattedTags, err := r.formatter.formatTags(r.name, tags)
if err != nil {
return fmt.Errorf("failed to format tags: %w", err)
}
encryptedDocumentBytes, err := r.formatter.formatValue(key, documentID, value, tags, formattedTags)
if err != nil {
return fmt.Errorf("failed to format value: %w", err)
}
err = r.restClient.updateDocument(r.vaultID, documentID, encryptedDocumentBytes)
if err != nil {
return fmt.Errorf("failed to update existing document in EDV server: %w", err)
}
return nil
}
func (r *restStore) getEncryptedDocumentStoredUnderDeterministicID(key string) ([]byte, error) {
encryptedDocumentID, _, _, err := r.formatter.format(r.name, key, nil)
if err != nil {
return nil, fmt.Errorf("failed to generate the encrypted document ID: %w", err)
}
encryptedDocumentBytes, err := r.restClient.readDocument(r.vaultID, encryptedDocumentID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve document from EDV server: %w", err)
}
return encryptedDocumentBytes, nil
}
func (r *restStore) getEncryptedDocumentStoredUnderRandomID(key string) ([]byte, error) {
if r.returnFullDocumentsOnQuery {
encryptedDocumentBytes, err := r.getFullDocumentViaKeyTagQuery(key)
if err != nil {
return nil, fmt.Errorf("failed to get full document via query: %w", err)
}
return encryptedDocumentBytes, nil
}
documentID, err := r.getDocumentIDViaKeyTagQuery(key)
if err != nil {
return nil, fmt.Errorf("failed to get document ID via key tag query: %w", err)
}
encryptedDocumentBytes, err := r.restClient.readDocument(r.vaultID, documentID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve document from EDV server: %w", err)
}
return encryptedDocumentBytes, nil
}
func (r *restStore) deleteDocumentUsingDeterministicID(key string) error {
edvDocumentID, err := r.formatter.generateDeterministicDocumentID(r.name, key)
if err != nil {
return fmt.Errorf("failed to generate the encrypted document ID: %w", err)
}
err = r.restClient.deleteDocument(r.vaultID, edvDocumentID)
if err != nil && !errors.Is(err, spi.ErrDataNotFound) {
return fmt.Errorf("unexpected failure while deleting document in EDV server: %w", err)
}
return nil
}
func (r *restStore) lockAndDeleteDocumentStoredUnderRandomID(key string) error {
r.lock.Lock()
defer r.lock.Unlock()
return r.deleteDocumentStoredUnderRandomID(key)
}
func (r *restStore) getFullDocumentViaKeyTagQuery(key string) ([]byte, error) {
formattedKeyTag, err := r.formatter.formatTag(r.name, spi.Tag{Value: key})
if err != nil {
return nil, fmt.Errorf("failed to format key tag: %w", err)
}
matchingDocuments, err := r.restClient.queryVaultForFullDocuments(r.vaultID,
formattedKeyTag.Name, formattedKeyTag.Value)
if err != nil {
return nil, fmt.Errorf("failure while querying vault: %w", err)
}
if len(matchingDocuments) == 0 {
return nil, fmt.Errorf("no document matching the query was found: %w", spi.ErrDataNotFound)
} else if len(matchingDocuments) > 1 {
return nil, errors.New("multiple documents matching the query were found, " +
"but only one was expected")
}
encryptedDocumentBytes, err := json.Marshal(matchingDocuments[0])
if err != nil {
return nil, fmt.Errorf("failed to marshal encrypted document into bytes: %w", err)
}
return encryptedDocumentBytes, nil
}
func (r *restStore) query(encryptedIndexTag spi.Tag) (spi.Iterator, error) {
if r.returnFullDocumentsOnQuery {
documents, err :=
r.restClient.queryVaultForFullDocuments(r.vaultID, encryptedIndexTag.Name, encryptedIndexTag.Value)
if err != nil {
return nil, fmt.Errorf("failure while querying vault: %w", err)
}
allDocumentsBytes := make([][]byte, len(documents))
for i, document := range documents {
documentBytes, err := json.Marshal(document)
if err != nil {
return nil, fmt.Errorf("failed to marshal document into bytes: %w", err)
}
allDocumentsBytes[i] = documentBytes
}
return &restIterator{
vaultID: r.vaultID, restClient: r.restClient, formatter: r.formatter,
documents: allDocumentsBytes,
}, nil
}
documentURLs, err := r.restClient.queryVault(r.vaultID, encryptedIndexTag.Name, encryptedIndexTag.Value)
if err != nil {
return nil, fmt.Errorf("failure while querying EDV server: %w", err)
}
documentIDs := make([]string, len(documentURLs))
for i, documentURL := range documentURLs {
documentIDs[i] = getDocIDFromURL(documentURL)
}
return &restIterator{
vaultID: r.vaultID, restClient: r.restClient, formatter: r.formatter,
documentIDs: documentIDs,
}, nil
}
func (r *restStore) fastBatchUsingBatchExtension(operations []spi.Operation) error {
var vaultOperations []vaultOperation
var err error
if r.formatter.UsesDeterministicKeyFormatting() {
vaultOperations, err = r.generateVaultOperationsUsingDeterministicIDs(operations)
if err != nil {
return fmt.Errorf("failed to generate vault operations using deterministic IDs: %w", err)
}
} else {
r.lock.Lock()
defer r.lock.Unlock()
vaultOperations, err = r.createVaultOperationsUsingNonDeterministicIDs(operations)
if err != nil {
return fmt.Errorf("failed to create vault operations using random document IDs: %w", err)
}
}
err = r.restClient.batch(r.vaultID, vaultOperations)
if err != nil {
return fmt.Errorf("failure while executing batch operation in EDV server: %w", err)
}
return nil
}
func (r *restStore) slowBatchUsingStandardEndpoints(operations []spi.Operation) error {
r.lock.Lock()
defer r.lock.Unlock()
for _, operation := range operations {
err := r.executeOperationUsingStandardEndpoints(operation)
if err != nil {
return fmt.Errorf("failed to execute operation using standard endpoints: %w", err)
}
}
return nil
}
func (r *restStore) executeOperationUsingStandardEndpoints(operation spi.Operation) error {
if operation.Value == nil {
err := r.executeDeleteOperationUsingStandardEndpoints(operation)
if err != nil {
return fmt.Errorf("failed to execute delete operation using standard endpoints: %w", err)
}
} else {
err := r.executePutOperationUsingStandardEndpoints(operation)
if err != nil {
return fmt.Errorf("failed to execute put operation using standard endpoints: %w", err)
}
}
return nil
}
func (r *restStore) executeDeleteOperationUsingStandardEndpoints(operation spi.Operation) error {
if r.formatter.UsesDeterministicKeyFormatting() {
err := r.deleteDocumentUsingDeterministicID(operation.Key)
if err != nil {
return fmt.Errorf("failed to delete document using deterministic ID: %w", err)
}
} else {
err := r.deleteDocumentStoredUnderRandomID(operation.Key)
if err != nil {
return fmt.Errorf("failed to delete document using random ID: %w", err)
}
}
return nil
}
func (r *restStore) executePutOperationUsingStandardEndpoints(operation spi.Operation) error {
if r.formatter.UsesDeterministicKeyFormatting() {
err := r.putUsingDeterministicDocumentID(operation.Key, operation.Value, operation.Tags)
if err != nil {
return fmt.Errorf("failed to store data using a deterministic document ID: %w", err)
}
} else {
err := r.appendKeyTagAndPutUsingRandomDocumentID(operation.Key, operation.Value, operation.Tags)
if err != nil {
return fmt.Errorf("failed to store data using a random document ID: %w", err)
}
}
return nil
}
func (r *restStore) appendKeyTagAndPutUsingRandomDocumentID(key string, value []byte, tags []spi.Tag) error {
tags = append(tags, spi.Tag{Value: key})
return r.putUsingRandomDocumentID(key, value, tags)
}
func (r *restStore) putUsingRandomDocumentID(key string, value []byte, tags []spi.Tag) error {
var existingDocumentID string
existingDocumentBytes, err := r.getEncryptedDocumentStoredUnderRandomID(key)
if err == nil {
var existingDocument encryptedDocument
err = json.Unmarshal(existingDocumentBytes, &existingDocument)
if err != nil {
return fmt.Errorf("failed to unmarshal existing document bytes: %w", err)
}
existingDocumentID = existingDocument.ID
} else if !errors.Is(err, spi.ErrDataNotFound) {
return fmt.Errorf(`failed to determine if an EDV document for key "%s" in store "%s" already exists: %w`,
key, r.name, err)
}
// With random IDs, there's no benefit to using the batch endpoint extension for a single Put,
// so we might as well use the standard endpoints.
if existingDocumentID == "" {
documentID, err := generateRandomDocumentID()
if err != nil {
return fmt.Errorf("failed to generate a random document ID: %w", err)
}
err = r.formatTagsThenCreateDocument(key, documentID, value, tags)
if err != nil {
return fmt.Errorf("failed to format tags then create document: %w", err)
}
} else {
err := r.updateDocument(key, existingDocumentID, value, tags)
if err != nil {
return fmt.Errorf("failed to update document: %w", err)
}
}
return nil
}
func (r *restStore) formatTagsThenCreateDocument(key, documentID string, value []byte, tags []spi.Tag) error {
formattedTags, err := r.formatter.formatTags(r.name, tags)
if err != nil {
return fmt.Errorf("failed to format tags: %w", err)
}
err = r.createDocument(key, documentID, value, tags, formattedTags)
if err != nil {
return fmt.Errorf("failed to create document: %w", err)
}
return nil
}
func (r *restStore) createDocument(key, documentID string, value []byte, tags, formattedTags []spi.Tag) error {
encryptedDocumentBytes, err :=
r.formatter.formatValue(key, documentID, value, tags, formattedTags)
if err != nil {
return fmt.Errorf("failed to generate the encrypted document: %w", err)
}
_, err = r.restClient.createDocument(r.vaultID, encryptedDocumentBytes)
if err != nil {
return fmt.Errorf("failed to create document in EDV server: %w", err)
}
return nil
}
func (r *restStore) deleteDocumentStoredUnderRandomID(key string) error {
encryptedDocumentID, err := r.determineRandomDocumentIDViaVaultQuery(key)
if err != nil {
// It's not considered an error to attempt deleting a value that doesn't exist.
if errors.Is(err, spi.ErrDataNotFound) {
return nil
}
return fmt.Errorf("failed to determine previously generated random document ID: %w", err)
}
err = r.restClient.deleteDocument(r.vaultID, encryptedDocumentID)
if err != nil {
return fmt.Errorf("unexpected failure while deleting document in EDV server: %w", err)
}
return nil
}
func (r *restStore) generateVaultOperationsUsingDeterministicIDs(operations []spi.Operation) ([]vaultOperation, error) {
vaultOperations := make([]vaultOperation, len(operations))
for i, operation := range operations {
var edvOperation string
if operation.Value == nil {
edvOperation = deleteDocumentVaultOperation
} else {
edvOperation = upsertDocumentVaultOperation
}
encryptedDocumentID, encryptedDocumentBytes, _, err :=
r.formatter.format(r.name, operation.Key, operation.Value, operation.Tags...)
if err != nil {
return nil, fmt.Errorf("failed to generate the encrypted document ID and "+
"encrypted document bytes: %w", err)
}
vaultOperations[i] = vaultOperation{
Operation: edvOperation,
DocumentID: encryptedDocumentID,
EncryptedDocument: encryptedDocumentBytes,
}
}
return vaultOperations, nil
}
func (r *restStore) createVaultOperationsUsingNonDeterministicIDs(
operations []spi.Operation) ([]vaultOperation, error) {
var vaultOperations []vaultOperation
resolvedIDs := make(map[string]string, len(operations))
for _, operation := range operations {
if operation.Value == nil {
deleteOperation, err := r.createVaultDeleteOperation(resolvedIDs, operation)
if err != nil {
return nil, fmt.Errorf("failed to create vault delete operation: %w", err)
}
// An empty ID in the returned operation means that it's not needed or is redundant with another delete operation.
if deleteOperation.DocumentID != "" {
vaultOperations = append(vaultOperations, deleteOperation)
}
} else {
putOperation, err := r.createVaultUpsertOperation(resolvedIDs, operation)
if err != nil {
return nil, fmt.Errorf("failed to create vault upsert operation: %w", err)
}
vaultOperations = append(vaultOperations, putOperation)
}
}
return vaultOperations, nil
}
func (r *restStore) createVaultDeleteOperation(resolvedIDs map[string]string,
operation spi.Operation) (vaultOperation, error) {
documentID, err := r.determineDocumentIDToUseForOperation(resolvedIDs, operation.Key)
if err != nil {
return vaultOperation{}, fmt.Errorf("unexpected failure while determining document ID to use: %w", err)
}
// If the ID wasn't found, or is already being deleted (is blank either way),
// then there's nothing to delete, and so this operation is not needed.
if documentID != "" {
// In the event that a user does a Put, Delete, Put within the same batch, all with the same key, then we
// should make sure that second Put uses a fresh random document ID.
// This is in order to be consistent with what would normally happen when doing a Put after a Delete in a
// non-batch call. The key is mapped to a blank string below, which is used to indicate that
// a new random document ID should be generated in any subsequent Put operations for the same key within this batch.
resolvedIDs[operation.Key] = ""
return vaultOperation{Operation: deleteDocumentVaultOperation, DocumentID: documentID}, nil
}
// This empty operation will be dropped in the parent method.
return vaultOperation{}, nil
}
func (r *restStore) createVaultUpsertOperation(resolvedIDs map[string]string,
operation spi.Operation) (vaultOperation, error) {
documentID, err := r.determineDocumentIDToUseForOperation(resolvedIDs, operation.Key)
if err != nil {
return vaultOperation{}, fmt.Errorf("unexpected failure while determining document ID to use: %w", err)
}
tagsToFormat := appendKeyTag(operation)
var upsertOperation vaultOperation
if documentID == "" {
upsertOperation, err = r.createVaultUpsertOperationUsingNewDocumentID(resolvedIDs, operation, tagsToFormat)
if err != nil {
return vaultOperation{}, fmt.Errorf("failed to create vault upsert operation using a "+
"new document ID: %w", err)
}
} else {
upsertOperation, err =
r.createVaultUpsertOperationUsingExistingDocumentID(resolvedIDs, documentID, operation, tagsToFormat)
if err != nil {
return vaultOperation{}, fmt.Errorf("failed to create vault upsert operation using an "+
"existing document ID: %w", err)
}
}
return upsertOperation, nil
}
func (r *restStore) createVaultUpsertOperationUsingNewDocumentID(resolvedIDs map[string]string,
operation spi.Operation, tagsToFormat []spi.Tag) (vaultOperation, error) {
documentID, encryptedDocumentBytes, _, err :=
r.formatter.format(r.name, "", operation.Value, tagsToFormat...)
if err != nil {
return vaultOperation{}, fmt.Errorf("failed to generate the encrypted document: %w", err)
}
resolvedIDs[operation.Key] = documentID
return vaultOperation{Operation: upsertDocumentVaultOperation, EncryptedDocument: encryptedDocumentBytes}, nil
}
func (r *restStore) createVaultUpsertOperationUsingExistingDocumentID(resolvedIDs map[string]string, documentID string,
operation spi.Operation, tagsToFormat []spi.Tag) (vaultOperation, error) {
formattedTags, err := r.formatter.formatTags(r.name, tagsToFormat)
if err != nil {
return vaultOperation{}, fmt.Errorf("failed to format tags: %w", err)
}
encryptedDocumentBytes, err :=
r.formatter.formatValue(operation.Key, documentID, operation.Value, tagsToFormat, formattedTags)
if err != nil {
return vaultOperation{}, fmt.Errorf("failed to format value: %w", err)
}
resolvedIDs[operation.Key] = documentID
return vaultOperation{Operation: upsertDocumentVaultOperation, EncryptedDocument: encryptedDocumentBytes}, nil
}
func (r *restStore) determineDocumentIDToUseForOperation(resolvedIDs map[string]string,
currentOperationKey string) (string, error) {
// There are several cases to consider:
// 1. First, check the resolvedIDs slice. It contains the document IDs used in previous put operations within
// this batch. If the key is found then we must use the associated document ID in order to ensure we don't create
// duplicates in the database. If a document ID is found in the map but it's set to a blank string,
// then we know from the createVaultDeleteOperation method that this document ID has been effectively
// marked for deletion and should not be reused.
// 2. If the resolvedIDs slice doesn't have the document ID and the key wasn't previously marked for deletion,
// then we have to query the store. If the key is found, then that means that we must use that existing
// document ID for whichever operation is calling this method.
// 3. If the document ID was marked for deletion, then we should not query the store. In the case of a Put,
// we want to make sure that a fresh random ID gets generated instead of reusing the
// old one in order to be consistent with the equivalent non-batched operations.
// In the case of a Delete, the query is simply unnecessary.
documentIDToUse, isMarkedForDeletion :=
getDocumentIDFromPreviouslyResolvedDocumentIDs(resolvedIDs, currentOperationKey)
// If we haven't determined the document ID yet, then we must query the vault. If the document ID still
// can't be found, then it must not exist.
if documentIDToUse == "" && !isMarkedForDeletion {
var err error