-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstreaming_service.go
486 lines (418 loc) · 12.8 KB
/
streaming_service.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
package hoard
import (
"fmt"
"io"
"github.com/monax/hoard/v8/encryption"
"github.com/monax/hoard/v8/protodet"
"github.com/monax/hoard/v8/versions"
"github.com/monax/hoard/v8/api"
"github.com/monax/hoard/v8/grant"
"github.com/monax/hoard/v8/reference"
"github.com/monax/hoard/v8/stores"
)
// StreamingService provides the API implementation for Service without relying directly on the
// GRPC generated streaming types
type StreamingService struct {
grantService GrantService
chunkSize int64
}
// Create a streaming service that will re-buffer any plaintext data in blocks of chunkSize. linker is a
// predicate used to decide whether PutSeal should store a LINK ref in a grant rather than an array of refs. It is
// passed the refs so it may decide to dynamically use LINK refs based on the number and size of references
func NewStreamingService(grantService GrantService, chunkSize int64) *StreamingService {
return &StreamingService{
grantService: grantService,
chunkSize: chunkSize,
}
}
func (service *StreamingService) PutSeal(sendAndClose func(*grant.Grant) error, recv func() (*api.PlaintextAndGrantSpec, error)) error {
first, err := recv()
if err != nil {
if err == io.EOF {
return fmt.Errorf("no messages sent before EOF")
}
return err
}
spec := first.GetGrantSpec()
if spec == nil {
return fmt.Errorf("grant spec expected in first message")
}
head := first.GetPlaintext().GetHead()
var refs []*reference.Ref
err = encrypt(first.GetPlaintext(), service.put,
func(ref *reference.Ref, encryptedData []byte) error {
refs = append(refs, ref)
return nil
},
func() (*api.Plaintext, error) {
ptgs, err := recv()
if err != nil {
return nil, err
}
return ptgs.GetPlaintext(), nil
}, service.chunkSize)
// TODO: it would be useful to be able to send Header.Data (i.e. metadata) as a trailer, this could then be
// normalised to the front of the refs array in the object pointed to by a LINK ref. This would allow things like
// file size, detected mime type, etc to be provided at the end of (or during) a stream. If a salt/chunksize is used
// we do need that at the beginning of the stream though. The decision to explicitly only support first-message headers
// was to avoid unintended behaviour from multiple headers appearing in the stream. Another option is to provide another call
// that take a grant without a header and adds a header by creating a copy of the link ref with a header added.
// Convert base refs into link ref(s) (usually a single unique link ref to allow for safe deletion of links)
refs, err = link(refs, head.GetSalt(), spec.LinkNonce, service.grantService.Put)
if err != nil {
return fmt.Errorf("could not link refs: %w", err)
}
// Now send the grant
grt, err := service.grantService.Seal(refs, spec)
if err != nil {
return err
}
return sendAndClose(grt)
}
// UnsealGet decrypts and gets plaintext associated with a grant
func (service *StreamingService) UnsealGet(grt *grant.Grant, send func(*api.Plaintext) error) error {
refs, err := service.grantService.Unseal(grt)
if err != nil {
return err
}
for _, ref := range refs {
data, err := service.grantService.Get(ref)
if err != nil {
return err
}
err = decode(data, ref.GetType(), service.grantService.Get, send, versions.LatestGrantVersion)
if err != nil {
return err
}
}
return nil
}
// UnsealDelete gets the references stored in a grant and deletes them
func (service *StreamingService) UnsealDelete(grt *grant.Grant, send func(address *api.Address) error) error {
refs, err := service.grantService.Unseal(grt)
if err != nil {
return err
}
for _, ref := range refs {
err := service.grantService.Store().Delete(ref.Address)
if err != nil {
return err
}
if err = send(&api.Address{Address: ref.Address}); err != nil {
return err
}
}
return nil
}
// Put encrypted data in the store
func (service *StreamingService) Put(send func(*reference.Ref) error, recv func() (*api.Plaintext, error)) error {
first, err := recv()
if err != nil {
if err == io.EOF {
return fmt.Errorf("no messages sent before EOF")
}
return err
}
err = encrypt(first, service.put, func(ref *reference.Ref, _ []byte) error { return send(ref) },
recv, service.chunkSize)
if err != nil {
return fmt.Errorf("Put: could not put plaintexts: %w", err)
}
return nil
}
// Get decrypted data from the store
func (service *StreamingService) Get(send func(*api.Plaintext) error, recv func() (*reference.Ref, error)) error {
for {
ref, err := recv()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
data, err := service.grantService.Get(ref)
if err != nil {
return err
}
err = decode(data, ref.GetType(), service.grantService.Get, send, versions.LatestGrantVersion)
if err != nil {
return err
}
}
}
// Encrypt data and return ciphertext
func (service *StreamingService) Encrypt(send func(*api.ReferenceAndCiphertext) error, recv func() (*api.Plaintext, error)) error {
first, err := recv()
if err != nil {
if err == io.EOF {
return fmt.Errorf("no messages sent before EOF")
}
return err
}
err = encrypt(first, service.grantService.Encrypt, func(ref *reference.Ref, encryptedData []byte) error {
return send(&api.ReferenceAndCiphertext{
Reference: ref,
Ciphertext: &api.Ciphertext{
EncryptedData: encryptedData,
},
})
}, recv, service.chunkSize)
if err != nil {
return fmt.Errorf("Could not encrypt data: %w", err)
}
return nil
}
// Decrypt ciphertext and return plaintext
func (service *StreamingService) Decrypt(send func(*api.Plaintext) error, recv func() (*api.ReferenceAndCiphertext, error)) error {
for {
refAndCiphertext, err := recv()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
data, err := service.grantService.Decrypt(refAndCiphertext.Reference, refAndCiphertext.Ciphertext.EncryptedData)
if err != nil {
return err
}
err = decode(data, refAndCiphertext.Reference.GetType(), service.grantService.Get, send, versions.LatestGrantVersion)
if err != nil {
return err
}
}
}
// StorageServer
// Push ciphertext directly to store
func (service *StreamingService) Push(send func(*api.Address) error, recv func() (*api.Ciphertext, error)) error {
for {
ciphertext, err := recv()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
addr, err := service.grantService.Store().Put(ciphertext.EncryptedData)
if err != nil {
return err
}
if err = send(&api.Address{Address: addr}); err != nil {
return err
}
}
}
// Pull gets ciphertext directly from the store
func (service *StreamingService) Pull(send func(*api.Ciphertext) error, recv func() (*api.Address, error)) error {
for {
addr, err := recv()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
data, err := service.grantService.Store().Get(addr.Address)
if err != nil {
return err
}
if err = send(&api.Ciphertext{EncryptedData: data}); err != nil {
return err
}
}
}
// GrantServer
// Seal puts refs in a shareable grant
func (service *StreamingService) Seal(sendAndClose func(*grant.Grant) error, recv func() (*api.ReferenceAndGrantSpec, error)) error {
var refs []*reference.Ref
first, err := recv()
if err != nil {
if err == io.EOF {
return fmt.Errorf("no messages sent before EOF")
}
return err
}
spec := first.GetGrantSpec()
if spec == nil {
return fmt.Errorf("grant spec expected in first message")
}
for {
if first.GetReference() != nil {
ref := first.GetReference()
first = nil
refs = append(refs, ref)
}
refAndSpec, err := recv()
if err != nil {
if err == io.EOF {
break
}
return err
}
if s := refAndSpec.GrantSpec; s != nil {
return fmt.Errorf("received multiple grant specs but there can be at most one")
}
refs = append(refs, refAndSpec.Reference)
}
grt, err := service.grantService.Seal(refs, spec)
if err != nil {
return err
}
return sendAndClose(grt)
}
// Unseal gets the refs stored in a grant
func (service *StreamingService) Unseal(grt *grant.Grant, send func(*reference.Ref) error) error {
refs, err := service.grantService.Unseal(grt)
if err != nil {
return err
}
for _, ref := range refs {
if err = send(ref); err != nil {
return err
}
}
return nil
}
// Reseal changes how the references in a grant are stored
func (service *StreamingService) Reseal(arg *api.GrantAndGrantSpec) (*grant.Grant, error) {
refs, err := service.grantService.Unseal(arg.Grant)
if err != nil {
return nil, err
}
// TODO: could provide a way to add Header metadata after the fact by re-linking some refs with header appended
// something like: refs ,err = link(append([]*reference.Ref{headerRef}, delink(refs)...), salt, linkNonce, service.grantService.Put)
return service.grantService.Seal(refs, arg.GrantSpec)
}
func (service *StreamingService) Stat(address *api.Address) (*stores.StatInfo, error) {
statInfo, err := service.grantService.Store().Stat(address.Address)
if err != nil {
return nil, err
}
// provide the address and the canonical location
statInfo.Address = address.Address
statInfo.Location = service.grantService.Store().Location(address.Address)
return statInfo, nil
}
func (service *StreamingService) Delete(address []byte) error {
return service.grantService.Store().Delete(address)
}
// Put wrapped with dummy 'encrypt' signature to help with reuse
func (service *StreamingService) put(data, salt []byte) (*reference.Ref, []byte, error) {
ref, err := service.grantService.Put(data, salt)
return ref, nil, err
}
// Abstracts the handling of incoming plaintexts that is common between Encrypt, Put, and PutSeal
func encrypt(first *api.Plaintext,
encrypt func(data []byte, salt []byte) (ref *reference.Ref, encryptedData []byte, err error),
send func(ref *reference.Ref, encryptedData []byte) error,
recv func() (*api.Plaintext, error),
chunkSize int64) error {
// Expect header to always be in first message if provided
head := first.GetHead()
if head != nil {
// Use chunkSize if supplied
if head.GetChunkSize() > 0 {
chunkSize = head.ChunkSize
}
data, err := protodet.Marshal(head)
if err != nil {
return err
}
ref, encryptedData, err := encrypt(data, head.GetSalt())
if err != nil {
return err
}
ref.Type = reference.Ref_HEADER
err = send(ref, encryptedData)
if err != nil {
return err
}
}
// Truncate to max chunkSize
if chunkSize > MaxChunkSize {
chunkSize = MaxChunkSize
}
return CopyChunked(
func(chunk []byte) error {
ref, encryptedData, err := encrypt(chunk, head.GetSalt())
if err != nil {
return err
}
return send(ref, encryptedData)
},
func() ([]byte, error) {
// Consume any body that may have been in the first message
if first.GetBody() != nil {
body := first.GetBody()
first = nil
return body, nil
}
plaintext, err := recv()
if err != nil {
return nil, err
}
return plaintext.Body, nil
},
chunkSize)
}
// Converts raw plaintext data to the wrapper type
// In the case of a HEADER ref type the plaintext is deserialised using the header type
// In the case of a LINK ref type the supplied get function is used to fetch additional plaintext data which are themselves each decoded
// Otherwise the data is returned as MustPlaintextFromRefs.Body
// The decoded plaintext(s) are then streamed as output via the supplied send function
func decode(data []byte, refType reference.Ref_RefType,
get func(*reference.Ref) ([]byte, error),
send func(*api.Plaintext) error, version int32) error {
switch refType {
case reference.Ref_HEADER:
head := new(api.Header)
err := protodet.Unmarshal(data, head)
if err != nil {
return err
}
return send(&api.Plaintext{Head: head})
case reference.Ref_LINK:
refs, err := reference.RefsFromPlaintext(data, version)
if err != nil {
return err
}
for _, ref := range refs {
data, err := get(ref)
if err != nil {
return err
}
err = decode(data, ref.Type, get, send, version)
if err != nil {
return err
}
}
return nil
default:
return send(&api.Plaintext{
Body: data,
})
}
}
func link(refs []*reference.Ref, salt []byte, linkNonce []byte,
put func(data, salt []byte) (*reference.Ref, error)) ([]*reference.Ref, error) {
var err error
// By default link refs use a unique nonce to allow them to be deletable unless the grant specifies otherwise
if len(linkNonce) == 0 {
linkNonce, err = encryption.NewNonce(encryption.NonceSize)
if err != nil {
return nil, fmt.Errorf("could not create nonce for LINK ref: %w", err)
}
}
// Store refs as a plaintext document
plaintext, err := reference.PlaintextFromRefs(refs, linkNonce)
if err != nil {
return nil, err
}
ref, err := put(plaintext, salt)
if err != nil {
return nil, err
}
// Mark this ref as a LINK so it will be followed during dereferencing
ref.Type = reference.Ref_LINK
return []*reference.Ref{ref}, nil
}