Debian Codegraph @

internal/stream/stream_test.go

raw symbols SCIP
1 // Copyright 2019 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package stream_test
6
7 import (
8 "bytes"
9 "crypto/rand"
10 "errors"
11 "fmt"
12 "io"
13 "math"
14 "testing"
15 "testing/iotest"
16
17 "filippo.io/age/internal/stream"
18 "golang.org/x/crypto/chacha20poly1305"
19 )
20
21 const cs = stream.ChunkSize
22
23 // encrypt encrypts plaintext with key and returns the ciphertext.
24 func encrypt(t *testing.T, key, plaintext []byte) []byte {
25 t.Helper()
26 buf := &bytes.Buffer{}
27 w, err := stream.NewEncryptWriter(key, buf)
28 if err != nil {
29 t.Fatal(err)
30 }
31 if _, err := w.Write(plaintext); err != nil {
32 t.Fatal(err)
33 }
34 if err := w.Close(); err != nil {
35 t.Fatal(err)
36 }
37 return buf.Bytes()
38 }
39
40 func TestRoundTrip(t *testing.T) {
41 for _, length := range []int{0, 1000, cs - 1, cs, cs + 1, cs + 100, 2 * cs, 2*cs + 500} {
42 for _, stepSize := range []int{512, 600, 1000, cs - 1, cs, cs + 1} {
43 t.Run(fmt.Sprintf("len=%d,step=%d", length, stepSize), func(t *testing.T) {
44 testRoundTrip(t, stepSize, length)
45 })
46 }
47 }
48
49 length, stepSize := 2*cs+500, 1
50 t.Run(fmt.Sprintf("len=%d,step=%d", length, stepSize), func(t *testing.T) {
51 testRoundTrip(t, stepSize, length)
52 })
53 }
54
55 func testRoundTrip(t *testing.T, stepSize, length int) {
56 src := make([]byte, length)
57 rand.Read(src)
58 key := make([]byte, chacha20poly1305.KeySize)
59 rand.Read(key)
60 var ciphertext []byte
61
62 t.Run("EncryptWriter", func(t *testing.T) {
63 buf := &bytes.Buffer{}
64 w, err := stream.NewEncryptWriter(key, buf)
65 if err != nil {
66 t.Fatal(err)
67 }
68
69 var n int
70 for n < length {
71 b := min(length-n, stepSize)
72 nn, err := w.Write(src[n : n+b])
73 if err != nil {
74 t.Fatal(err)
75 }
76 if nn != b {
77 t.Errorf("Write returned %d, expected %d", nn, b)
78 }
79 n += nn
80
81 nn, err = w.Write(src[n:n])
82 if err != nil {
83 t.Fatal(err)
84 }
85 if nn != 0 {
86 t.Errorf("Write returned %d, expected 0", nn)
87 }
88 }
89 if err := w.Close(); err != nil {
90 t.Error("Close returned an error:", err)
91 }
92
93 ciphertext = buf.Bytes()
94 })
95
96 t.Run("DecryptReader", func(t *testing.T) {
97 r, err := stream.NewDecryptReader(key, bytes.NewReader(ciphertext))
98 if err != nil {
99 t.Fatal(err)
100 }
101
102 var n int
103 readBuf := make([]byte, stepSize)
104 for n < length {
105 nn, err := r.Read(readBuf)
106 if err != nil {
107 t.Fatalf("Read error at index %d: %v", n, err)
108 }
109
110 if !bytes.Equal(readBuf[:nn], src[n:n+nn]) {
111 t.Errorf("wrong data at indexes %d - %d", n, n+nn)
112 }
113
114 n += nn
115 }
116
117 t.Run("TestReader", func(t *testing.T) {
118 if length > 1000 && testing.Short() {
119 t.Skip("skipping slow iotest.TestReader on long input")
120 }
121 r, _ := stream.NewDecryptReader(key, bytes.NewReader(ciphertext))
122 if err := iotest.TestReader(r, src); err != nil {
123 t.Error("iotest.TestReader error on DecryptReader:", err)
124 }
125 })
126 })
127
128 t.Run("DecryptReaderAt", func(t *testing.T) {
129 rAt, err := stream.NewDecryptReaderAt(key, bytes.NewReader(ciphertext), int64(len(ciphertext)))
130 if err != nil {
131 t.Fatal(err)
132 }
133 rr := io.NewSectionReader(rAt, 0, int64(len(ciphertext)))
134
135 var n int
136 readBuf := make([]byte, stepSize)
137 for n < length {
138 nn, err := rr.Read(readBuf)
139 if n+nn == length && err == io.EOF {
140 err = nil
141 }
142 if err != nil {
143 t.Fatalf("ReadAt error at index %d: %v", n, err)
144 }
145
146 if !bytes.Equal(readBuf[:nn], src[n:n+nn]) {
147 t.Errorf("wrong data at indexes %d - %d", n, n+nn)
148 }
149
150 n += nn
151 }
152
153 t.Run("TestReader", func(t *testing.T) {
154 if length > 1000 && testing.Short() {
155 t.Skip("skipping slow iotest.TestReader on long input")
156 }
157 rr := io.NewSectionReader(rAt, 0, int64(len(src)))
158 if err := iotest.TestReader(rr, src); err != nil {
159 t.Error("iotest.TestReader error on DecryptReaderAt:", err)
160 }
161 })
162 })
163
164 t.Run("EncryptReader", func(t *testing.T) {
165 er, err := stream.NewEncryptReader(key, bytes.NewReader(src))
166 if err != nil {
167 t.Fatal(err)
168 }
169
170 var n int
171 readBuf := make([]byte, stepSize)
172 for {
173 nn, err := er.Read(readBuf)
174 if nn == 0 && err == io.EOF {
175 break
176 } else if err != nil {
177 t.Fatalf("EncryptReader Read error at index %d: %v", n, err)
178 }
179
180 if !bytes.Equal(readBuf[:nn], ciphertext[n:n+nn]) {
181 t.Errorf("EncryptReader wrong data at indexes %d - %d", n, n+nn)
182 }
183
184 n += nn
185 }
186 if n != len(ciphertext) {
187 t.Errorf("EncryptReader read %d bytes, expected %d", n, len(ciphertext))
188 }
189
190 t.Run("TestReader", func(t *testing.T) {
191 if length > 1000 && testing.Short() {
192 t.Skip("skipping slow iotest.TestReader on long input")
193 }
194 er, _ := stream.NewEncryptReader(key, bytes.NewReader(src))
195 if err := iotest.TestReader(er, ciphertext); err != nil {
196 t.Error("iotest.TestReader error on EncryptReader:", err)
197 }
198 })
199 })
200 }
201
202 // trackingReaderAt wraps an io.ReaderAt and tracks whether ReadAt was called.
203 type trackingReaderAt struct {
204 r io.ReaderAt
205 called bool
206 }
207
208 func (t *trackingReaderAt) ReadAt(p []byte, off int64) (int, error) {
209 t.called = true
210 return t.r.ReadAt(p, off)
211 }
212
213 func (t *trackingReaderAt) reset() {
214 t.called = false
215 }
216
217 func TestDecryptReaderAt(t *testing.T) {
218 key := make([]byte, chacha20poly1305.KeySize)
219 rand.Read(key)
220
221 // Create plaintext spanning exactly 3 chunks: 2 full chunks + partial third
222 // Chunk 0: [0, cs)
223 // Chunk 1: [cs, 2*cs)
224 // Chunk 2: [2*cs, 2*cs+500)
225 plaintextSize := 2*cs + 500
226 plaintext := make([]byte, plaintextSize)
227 rand.Read(plaintext)
228 ciphertext := encrypt(t, key, plaintext)
229
230 // Create tracking ReaderAt
231 tracker := &trackingReaderAt{r: bytes.NewReader(ciphertext)}
232
233 // Create DecryptReaderAt (this reads and caches the final chunk)
234 ra, err := stream.NewDecryptReaderAt(key, tracker, int64(len(ciphertext)))
235 if err != nil {
236 t.Fatal(err)
237 }
238 tracker.reset()
239
240 // Helper to check reads
241 checkRead := func(name string, off int64, size int, wantN int, wantEOF bool, wantSrcRead bool) {
242 t.Helper()
243 tracker.reset()
244 p := make([]byte, size)
245 n, err := ra.ReadAt(p, off)
246
247 if wantEOF {
248 if err != io.EOF {
249 t.Errorf("%s: got err=%v, want EOF", name, err)
250 }
251 } else {
252 if err != nil {
253 t.Errorf("%s: got err=%v, want nil", name, err)
254 }
255 }
256
257 if n != wantN {
258 t.Errorf("%s: got n=%d, want %d", name, n, wantN)
259 }
260
261 if tracker.called != wantSrcRead {
262 t.Errorf("%s: src.ReadAt called=%v, want %v", name, tracker.called, wantSrcRead)
263 }
264
265 // Verify data correctness
266 if n > 0 && off >= 0 && off < int64(plaintextSize) {
267 end := min(int(off)+n, plaintextSize)
268 if !bytes.Equal(p[:n], plaintext[off:end]) {
269 t.Errorf("%s: data mismatch", name)
270 }
271 }
272 }
273
274 // Test 1: Read from final chunk (cached by constructor)
275 checkRead("final chunk (cached)", int64(2*cs+100), 100, 100, false, false)
276
277 // Test 2: Read spanning second and third chunk
278 checkRead("span chunks 1-2", int64(cs+cs-50), 100, 100, false, true)
279
280 // Test 3: Read from final chunk again (cached from test 2)
281 // When reading across chunks 1-2 in test 2, the loop processes chunk 1 then chunk 2,
282 // so chunk 2 ends up in the cache.
283 checkRead("final chunk after span", int64(2*cs+200), 100, 100, false, false)
284
285 // Test 4: Read from final chunk again (now cached)
286 checkRead("final chunk (cached again)", int64(2*cs+50), 50, 50, false, false)
287
288 // Test 5: Read from first chunk (not cached)
289 checkRead("first chunk", 0, 100, 100, false, true)
290
291 // Test 6: Read from first chunk again (now cached)
292 checkRead("first chunk (cached)", 50, 100, 100, false, false)
293
294 // Test 7: Read spanning all chunks
295 tracker.reset()
296 p := make([]byte, plaintextSize)
297 n, err := ra.ReadAt(p, 0)
298 if err != io.EOF {
299 t.Errorf("span all: got err=%v, want EOF", err)
300 }
301 if n != plaintextSize {
302 t.Errorf("span all: got n=%d, want %d", n, plaintextSize)
303 }
304 if !bytes.Equal(p, plaintext) {
305 t.Errorf("span all: data mismatch")
306 }
307
308 // Test 8: Read beyond the end (offset > size)
309 tracker.reset()
310 p = make([]byte, 100)
311 n, err = ra.ReadAt(p, int64(plaintextSize+100))
312 if err == nil {
313 t.Error("beyond end: expected error, got nil")
314 }
315 if n != 0 {
316 t.Errorf("beyond end: got n=%d, want 0", n)
317 }
318
319 // Test 9: Read with off = size (should return 0, EOF)
320 tracker.reset()
321 p = make([]byte, 100)
322 n, err = ra.ReadAt(p, int64(plaintextSize))
323 if err != io.EOF {
324 t.Errorf("off=size: got err=%v, want EOF", err)
325 }
326 if n != 0 {
327 t.Errorf("off=size: got n=%d, want 0", n)
328 }
329
330 // Test 10: Read spanning last chunk and beyond
331 tracker.reset()
332 p = make([]byte, 1000) // request more than available
333 n, err = ra.ReadAt(p, int64(2*cs+400))
334 if err != io.EOF {
335 t.Errorf("span last+beyond: got err=%v, want EOF", err)
336 }
337 wantN := 500 - 400 // only 100 bytes available from offset 2*cs+400
338 if n != wantN {
339 t.Errorf("span last+beyond: got n=%d, want %d", n, wantN)
340 }
341 if !bytes.Equal(p[:n], plaintext[2*cs+400:]) {
342 t.Error("span last+beyond: data mismatch")
343 }
344
345 // Test 11: Read spanning second+last chunk and beyond
346 tracker.reset()
347 p = make([]byte, cs+1000) // request more than available
348 n, err = ra.ReadAt(p, int64(cs+100))
349 if err != io.EOF {
350 t.Errorf("span 1-2+beyond: got err=%v, want EOF", err)
351 }
352 wantN = plaintextSize - (cs + 100)
353 if n != wantN {
354 t.Errorf("span 1-2+beyond: got n=%d, want %d", n, wantN)
355 }
356 if !bytes.Equal(p[:n], plaintext[cs+100:]) {
357 t.Error("span 1-2+beyond: data mismatch")
358 }
359
360 // Test 12: Negative offset
361 tracker.reset()
362 p = make([]byte, 100)
363 n, err = ra.ReadAt(p, -1)
364 if err == nil {
365 t.Error("negative offset: expected error, got nil")
366 }
367 if n != 0 {
368 t.Errorf("negative offset: got n=%d, want 0", n)
369 }
370
371 // Test 13: Zero-length read in the middle
372 tracker.reset()
373 p = make([]byte, 0)
374 n, err = ra.ReadAt(p, 100)
375 if err != nil {
376 t.Errorf("zero-length middle: got err=%v, want nil", err)
377 }
378 if n != 0 {
379 t.Errorf("zero-length middle: got n=%d, want 0", n)
380 }
381
382 // Test 14: Zero-length read at end
383 tracker.reset()
384 p = make([]byte, 0)
385 n, err = ra.ReadAt(p, int64(plaintextSize))
386 if err != nil {
387 t.Errorf("zero-length end: got err=%v, want nil", err)
388 }
389 if n != 0 {
390 t.Errorf("zero-length end: got n=%d, want 0", n)
391 }
392
393 // Test 15: Read exactly one chunk at chunk boundary
394 checkRead("exact chunk at boundary", int64(cs), cs, cs, false, true)
395
396 // Test 16: Read one byte at each chunk boundary
397 checkRead("one byte at start", 0, 1, 1, false, true)
398 checkRead("one byte at cs-1", int64(cs-1), 1, 1, false, false) // cached from test 15
399 checkRead("one byte at cs", int64(cs), 1, 1, false, true)
400 checkRead("one byte at 2*cs-1", int64(2*cs-1), 1, 1, false, false) // same chunk
401 checkRead("one byte at 2*cs", int64(2*cs), 1, 1, false, true)
402 checkRead("last byte", int64(plaintextSize-1), 1, 1, true, false) // same chunk, EOF because we reach end
403
404 // Test 17: Read crossing exactly one chunk boundary
405 checkRead("cross boundary 0-1", int64(cs-50), 100, 100, false, true)
406 checkRead("cross boundary 1-2", int64(2*cs-50), 100, 100, false, true)
407 }
408
409 // eofReaderAt wraps a bytes.Reader and forces it to return io.EOF alongside a
410 // read that successfully reaches the exact end of the data.
411 type eofReaderAt struct {
412 r *bytes.Reader
413 }
414
415 func (e *eofReaderAt) ReadAt(p []byte, off int64) (int, error) {
416 n, err := e.r.ReadAt(p, off)
417 if err == nil && off+int64(n) == e.r.Size() {
418 err = io.EOF
419 }
420 return n, err
421 }
422
423 func TestDecryptReaderAtEOF(t *testing.T) {
424 key := make([]byte, chacha20poly1305.KeySize)
425 rand.Read(key)
426
427 // Multiple chunks, so that reads reach the final chunk both in the
428 // constructor and through ReadAt.
429 plaintext := make([]byte, 2*cs+100)
430 rand.Read(plaintext)
431 ciphertext := encrypt(t, key, plaintext)
432
433 // An io.ReaderAt is allowed to return io.EOF alongside a successful read
434 // that reaches the end of the source; both the constructor (which reads
435 // the final chunk eagerly) and ReadAt must tolerate it.
436 er := &eofReaderAt{r: bytes.NewReader(ciphertext)}
437
438 ra, err := stream.NewDecryptReaderAt(key, er, int64(len(ciphertext)))
439 if err != nil {
440 t.Fatalf("NewDecryptReaderAt failed on EOF: %v", err)
441 }
442
443 // Sequential small reads evict the final chunk from the cache, so it is
444 // read again through ReadAt, exercising its own EOF handling.
445 got, err := io.ReadAll(io.NewSectionReader(ra, 0, int64(len(plaintext))))
446 if err != nil {
447 t.Fatalf("ReadAll failed on EOF: %v", err)
448 }
449 if !bytes.Equal(got, plaintext) {
450 t.Error("plaintext mismatch")
451 }
452 }
453
454 // TestDecryptReaderTrailingData checks that data appended after a full-length
455 // final chunk is rejected, including when the source returns the trailing byte
456 // alongside io.EOF as permitted by io.Reader.
457 func TestDecryptReaderTrailingData(t *testing.T) {
458 key := make([]byte, chacha20poly1305.KeySize)
459 rand.Read(key)
460
461 // A plaintext of exactly one full chunk, so the trailing data can only be
462 // detected by reading past the final chunk.
463 plaintext := make([]byte, cs)
464 rand.Read(plaintext)
465 ciphertext := encrypt(t, key, plaintext)
466 trailing := append(bytes.Clone(ciphertext), 0x42)
467
468 wrappers := map[string]func(io.Reader) io.Reader{
469 "plain": func(r io.Reader) io.Reader { return r },
470 "dataErr": iotest.DataErrReader,
471 }
472 for name, wrap := range wrappers {
473 t.Run(name, func(t *testing.T) {
474 r, err := stream.NewDecryptReader(key, wrap(bytes.NewReader(trailing)))
475 if err != nil {
476 t.Fatal(err)
477 }
478 if _, err := io.ReadAll(r); err == nil {
479 t.Error("trailing data: expected error, got nil")
480 }
481
482 r, err = stream.NewDecryptReader(key, wrap(bytes.NewReader(ciphertext)))
483 if err != nil {
484 t.Fatal(err)
485 }
486 got, err := io.ReadAll(r)
487 if err != nil {
488 t.Errorf("valid file: got err=%v, want nil", err)
489 }
490 if !bytes.Equal(got, plaintext) {
491 t.Error("valid file: plaintext mismatch")
492 }
493 })
494 }
495 }
496
497 func TestDecryptReaderAtEmpty(t *testing.T) {
498 key := make([]byte, chacha20poly1305.KeySize)
499 rand.Read(key)
500
501 // Create empty encrypted file
502 ciphertext := encrypt(t, key, nil)
503
504 tracker := &trackingReaderAt{r: bytes.NewReader(ciphertext)}
505 ra, err := stream.NewDecryptReaderAt(key, tracker, int64(len(ciphertext)))
506 if err != nil {
507 t.Fatal(err)
508 }
509 tracker.reset()
510
511 // Test 1: Read from empty file at offset 0
512 p := make([]byte, 100)
513 n, err := ra.ReadAt(p, 0)
514 if err != io.EOF {
515 t.Errorf("empty read: got err=%v, want EOF", err)
516 }
517 if n != 0 {
518 t.Errorf("empty read: got n=%d, want 0", n)
519 }
520
521 // Test 2: Zero-length read from empty file
522 p = make([]byte, 0)
523 n, err = ra.ReadAt(p, 0)
524 if err != nil {
525 t.Errorf("empty zero-length: got err=%v, want nil", err)
526 }
527 if n != 0 {
528 t.Errorf("empty zero-length: got n=%d, want 0", n)
529 }
530
531 // Test 3: Read beyond empty file
532 p = make([]byte, 100)
533 n, err = ra.ReadAt(p, 1)
534 if err == nil {
535 t.Error("empty beyond: expected error, got nil")
536 }
537 if n != 0 {
538 t.Errorf("empty beyond: got n=%d, want 0", n)
539 }
540 }
541
542 func TestDecryptReaderAtSingleChunk(t *testing.T) {
543 key := make([]byte, chacha20poly1305.KeySize)
544 rand.Read(key)
545
546 // Single chunk, not full
547 plaintext := make([]byte, 1000)
548 rand.Read(plaintext)
549 ciphertext := encrypt(t, key, plaintext)
550
551 tracker := &trackingReaderAt{r: bytes.NewReader(ciphertext)}
552 ra, err := stream.NewDecryptReaderAt(key, tracker, int64(len(ciphertext)))
553 if err != nil {
554 t.Fatal(err)
555 }
556 tracker.reset()
557
558 // All reads should use cache (final chunk = only chunk)
559 p := make([]byte, 100)
560 n, err := ra.ReadAt(p, 0)
561 if err != nil {
562 t.Errorf("single chunk start: got err=%v, want nil", err)
563 }
564 if n != 100 {
565 t.Errorf("single chunk start: got n=%d, want 100", n)
566 }
567 if tracker.called {
568 t.Error("single chunk start: unexpected src.ReadAt call")
569 }
570 if !bytes.Equal(p[:n], plaintext[:100]) {
571 t.Error("single chunk start: data mismatch")
572 }
573
574 // Read at end
575 n, err = ra.ReadAt(p, 900)
576 if err != io.EOF {
577 t.Errorf("single chunk end: got err=%v, want EOF", err)
578 }
579 if n != 100 {
580 t.Errorf("single chunk end: got n=%d, want 100", n)
581 }
582 if tracker.called {
583 t.Error("single chunk end: unexpected src.ReadAt call")
584 }
585 if !bytes.Equal(p[:n], plaintext[900:]) {
586 t.Error("single chunk end: data mismatch")
587 }
588 }
589
590 func TestDecryptReaderAtFullChunks(t *testing.T) {
591 key := make([]byte, chacha20poly1305.KeySize)
592 rand.Read(key)
593
594 // Exactly 2 full chunks
595 plaintext := make([]byte, 2*cs)
596 rand.Read(plaintext)
597 ciphertext := encrypt(t, key, plaintext)
598
599 tracker := &trackingReaderAt{r: bytes.NewReader(ciphertext)}
600 ra, err := stream.NewDecryptReaderAt(key, tracker, int64(len(ciphertext)))
601 if err != nil {
602 t.Fatal(err)
603 }
604 tracker.reset()
605
606 // Read last byte of second chunk (cached)
607 p := make([]byte, 1)
608 n, err := ra.ReadAt(p, int64(2*cs-1))
609 if err != io.EOF {
610 t.Errorf("last byte: got err=%v, want EOF", err)
611 }
612 if n != 1 {
613 t.Errorf("last byte: got n=%d, want 1", n)
614 }
615 if tracker.called {
616 t.Error("last byte: unexpected src.ReadAt call (should be cached)")
617 }
618 if p[0] != plaintext[2*cs-1] {
619 t.Error("last byte: data mismatch")
620 }
621
622 // Read at exactly the boundary between chunks
623 p = make([]byte, 100)
624 n, err = ra.ReadAt(p, int64(cs-50))
625 if err != nil {
626 t.Errorf("boundary: got err=%v, want nil", err)
627 }
628 if n != 100 {
629 t.Errorf("boundary: got n=%d, want 100", n)
630 }
631 if !bytes.Equal(p, plaintext[cs-50:cs+50]) {
632 t.Error("boundary: data mismatch")
633 }
634 }
635
636 func TestDecryptReaderAtWrongKey(t *testing.T) {
637 key := make([]byte, chacha20poly1305.KeySize)
638 rand.Read(key)
639 plaintext := make([]byte, 1000)
640 rand.Read(plaintext)
641 ciphertext := encrypt(t, key, plaintext)
642
643 // Try to decrypt with wrong key
644 wrongKey := make([]byte, chacha20poly1305.KeySize)
645 rand.Read(wrongKey)
646 _, err := stream.NewDecryptReaderAt(wrongKey, bytes.NewReader(ciphertext), int64(len(ciphertext)))
647 if err == nil {
648 t.Error("wrong key: expected error, got nil")
649 }
650 }
651
652 func TestDecryptReaderAtInvalidSize(t *testing.T) {
653 key := make([]byte, chacha20poly1305.KeySize)
654 rand.Read(key)
655 plaintext := make([]byte, 1000)
656 rand.Read(plaintext)
657 ciphertext := encrypt(t, key, plaintext)
658
659 // Wrong size (too small)
660 _, err := stream.NewDecryptReaderAt(key, bytes.NewReader(ciphertext), int64(len(ciphertext)-1))
661 if err == nil {
662 t.Error("wrong size (small): expected error, got nil")
663 }
664
665 // Wrong size (too large)
666 _, err = stream.NewDecryptReaderAt(key, bytes.NewReader(ciphertext), int64(len(ciphertext)+1))
667 if err == nil {
668 t.Error("wrong size (large): expected error, got nil")
669 }
670
671 // Size that would imply empty final chunk (invalid)
672 // This would be: one full encrypted chunk + just overhead
673 invalidSize := int64(cs + chacha20poly1305.Overhead + chacha20poly1305.Overhead)
674 _, err = stream.NewDecryptReaderAt(key, bytes.NewReader(make([]byte, invalidSize)), invalidSize)
675 if err == nil {
676 t.Error("invalid size (empty final chunk): expected error, got nil")
677 }
678
679 // Negative sizes and sizes that would overflow the chunk count computation
680 // must be rejected with an error rather than a panic.
681 for _, size := range []int64{-1, -70000, math.MaxInt64, math.MaxInt64 - 200, math.MaxInt64 - 65550} {
682 if _, err := stream.EncryptedChunkCount(size); err == nil {
683 t.Errorf("EncryptedChunkCount(%d): expected error, got nil", size)
684 }
685 if _, err := stream.NewDecryptReaderAt(key, bytes.NewReader(ciphertext), size); err == nil {
686 t.Errorf("NewDecryptReaderAt(%d): expected error, got nil", size)
687 }
688 }
689 }
690
691 func TestDecryptReaderAtTruncated(t *testing.T) {
692 key := make([]byte, chacha20poly1305.KeySize)
693 rand.Read(key)
694 plaintext := make([]byte, 2*cs+500)
695 rand.Read(plaintext)
696 ciphertext := encrypt(t, key, plaintext)
697
698 // Truncate ciphertext but lie about size. The source ending before the
699 // expected end of the final chunk must be reported as an unexpected EOF,
700 // not as a decryption failure.
701 truncated := ciphertext[:len(ciphertext)-100]
702 _, err := stream.NewDecryptReaderAt(key, bytes.NewReader(truncated), int64(len(ciphertext)))
703 if !errors.Is(err, io.ErrUnexpectedEOF) {
704 t.Errorf("truncated: got err=%v, want io.ErrUnexpectedEOF", err)
705 }
706 }
707
708 func TestDecryptReaderAtTruncatedChunk(t *testing.T) {
709 key := make([]byte, chacha20poly1305.KeySize)
710 rand.Read(key)
711
712 // Create 4 chunks: 3 full + 1 partial
713 plaintext := make([]byte, 3*cs+500)
714 rand.Read(plaintext)
715 ciphertext := encrypt(t, key, plaintext)
716
717 // Truncate to 3 chunks (remove the actual final chunk)
718 // The third chunk was NOT encrypted with the last chunk flag,
719 // so decryption should fail when we try to use it as the final chunk.
720 encChunkSize := cs + 16 // ChunkSize + Overhead
721 truncatedSize := int64(3 * encChunkSize)
722 truncated := ciphertext[:truncatedSize]
723
724 _, err := stream.NewDecryptReaderAt(key, bytes.NewReader(truncated), truncatedSize)
725 if err == nil {
726 t.Error("truncated at chunk boundary: expected error, got nil")
727 }
728 }
729
730 func TestDecryptReaderAtConcurrent(t *testing.T) {
731 key := make([]byte, chacha20poly1305.KeySize)
732 rand.Read(key)
733
734 // Create plaintext spanning 3 chunks: 2 full + partial
735 plaintextSize := 2*cs + 500
736 plaintext := make([]byte, plaintextSize)
737 rand.Read(plaintext)
738 ciphertext := encrypt(t, key, plaintext)
739
740 ra, err := stream.NewDecryptReaderAt(key, bytes.NewReader(ciphertext), int64(len(ciphertext)))
741 if err != nil {
742 t.Fatal(err)
743 }
744
745 t.Run("same chunk", func(t *testing.T) {
746 t.Parallel()
747 const goroutines = 10
748 const iterations = 100
749 errc := make(chan error, goroutines)
750
751 for g := range goroutines {
752 go func(id int) {
753 for i := range iterations {
754 off := int64((id*iterations + i) % 500)
755 p := make([]byte, 100)
756 n, err := ra.ReadAt(p, off)
757 if err != nil {
758 errc <- fmt.Errorf("goroutine %d iter %d: %v", id, i, err)
759 return
760 }
761 if n != 100 {
762 errc <- fmt.Errorf("goroutine %d iter %d: n=%d, want 100", id, i, n)
763 return
764 }
765 if !bytes.Equal(p, plaintext[off:off+100]) {
766 errc <- fmt.Errorf("goroutine %d iter %d: data mismatch", id, i)
767 return
768 }
769 }
770 errc <- nil
771 }(g)
772 }
773
774 for range goroutines {
775 if err := <-errc; err != nil {
776 t.Error(err)
777 }
778 }
779 })
780
781 t.Run("different chunks", func(t *testing.T) {
782 t.Parallel()
783 const goroutines = 10
784 const iterations = 100
785 errc := make(chan error, goroutines)
786
787 for g := range goroutines {
788 go func(id int) {
789 for i := range iterations {
790 // Each goroutine reads from a different chunk based on id
791 chunkIdx := id % 3
792 off := int64(chunkIdx*cs + (i % 400))
793 size := 100
794 if off+int64(size) > int64(plaintextSize) {
795 size = plaintextSize - int(off)
796 }
797 p := make([]byte, size)
798 n, err := ra.ReadAt(p, off)
799 if n == size && err == io.EOF {
800 err = nil // EOF at end is acceptable
801 }
802 if err != nil {
803 errc <- fmt.Errorf("goroutine %d iter %d: off=%d: %v", id, i, off, err)
804 return
805 }
806 if n != size {
807 errc <- fmt.Errorf("goroutine %d iter %d: n=%d, want %d", id, i, n, size)
808 return
809 }
810 if !bytes.Equal(p[:n], plaintext[off:off+int64(n)]) {
811 errc <- fmt.Errorf("goroutine %d iter %d: data mismatch", id, i)
812 return
813 }
814 }
815 errc <- nil
816 }(g)
817 }
818
819 for range goroutines {
820 if err := <-errc; err != nil {
821 t.Error(err)
822 }
823 }
824 })
825
826 t.Run("across chunks", func(t *testing.T) {
827 t.Parallel()
828 const goroutines = 10
829 const iterations = 100
830 errc := make(chan error, goroutines)
831
832 for g := range goroutines {
833 go func(id int) {
834 for i := range iterations {
835 // Read across chunk boundaries
836 boundary := (id%2 + 1) * cs // either cs or 2*cs
837 off := int64(boundary - 50 + (i % 30))
838 size := 100
839 if off+int64(size) > int64(plaintextSize) {
840 size = plaintextSize - int(off)
841 }
842 if size <= 0 {
843 continue
844 }
845 p := make([]byte, size)
846 n, err := ra.ReadAt(p, off)
847 if n == size && err == io.EOF {
848 err = nil
849 }
850 if err != nil {
851 errc <- fmt.Errorf("goroutine %d iter %d: off=%d size=%d: %v", id, i, off, size, err)
852 return
853 }
854 if n != size {
855 errc <- fmt.Errorf("goroutine %d iter %d: n=%d, want %d", id, i, n, size)
856 return
857 }
858 if !bytes.Equal(p[:n], plaintext[off:off+int64(n)]) {
859 errc <- fmt.Errorf("goroutine %d iter %d: data mismatch", id, i)
860 return
861 }
862 }
863 errc <- nil
864 }(g)
865 }
866
867 for range goroutines {
868 if err := <-errc; err != nil {
869 t.Error(err)
870 }
871 }
872 })
873 }
874
875 func TestDecryptReaderAtCorrupted(t *testing.T) {
876 key := make([]byte, chacha20poly1305.KeySize)
877 rand.Read(key)
878 plaintext := make([]byte, 2*cs+500)
879 rand.Read(plaintext)
880 ciphertext := encrypt(t, key, plaintext)
881
882 // Corrupt final chunk - should fail in constructor
883 corruptedFinal := bytes.Clone(ciphertext)
884 corruptedFinal[len(corruptedFinal)-10] ^= 0xFF
885 _, err := stream.NewDecryptReaderAt(key, bytes.NewReader(corruptedFinal), int64(len(corruptedFinal)))
886 if err == nil {
887 t.Error("corrupted final: expected error, got nil")
888 }
889
890 // Corrupt first chunk - should fail on read
891 corruptedFirst := bytes.Clone(ciphertext)
892 corruptedFirst[10] ^= 0xFF
893 ra, err := stream.NewDecryptReaderAt(key, bytes.NewReader(corruptedFirst), int64(len(corruptedFirst)))
894 if err != nil {
895 t.Fatalf("corrupted first constructor: unexpected error: %v", err)
896 }
897 p := make([]byte, 100)
898 _, err = ra.ReadAt(p, 0)
899 if err == nil {
900 t.Error("corrupted first read: expected error, got nil")
901 }
902 }