{{ message }}
Repository navigation
Expand file tree
/
Copy pathblob_test.go
More file actions
1060 lines (1007 loc) · 37.6 KB
/
Copy pathblob_test.go
File metadata and controls
1060 lines (1007 loc) · 37.6 KB
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
package server
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/lifecycle"
"github.com/minio/minio-go/v7/pkg/replication"
)
// Prove the configured non-local service account can perform every operation
// required by the simulator's content-addressed evidence publisher.
func TestLiveBlobStoreContentAddressedCanary(t *testing.T) {
if os.Getenv("SIM_TESTNET_LIVE_BLOB") != "1" {
t.Skip("set SIM_TESTNET_LIVE_BLOB=1 with WARP_ENV to probe the configured server/blob store")
}
store, ok := LoadBlobStore()
if !ok {
t.Fatal("configured MinIO blob store is unavailable")
}
if store.Authority() == "local" {
t.Fatalf("configured blob store is local: %q", store.Authority())
}
content := []byte("urnetwork sim-testnet MinIO canary v1\n")
hash := sha256.Sum256(content)
key := path.Join(store.Prefix(), "sim-testnet", "preflight", "sha256", fmt.Sprintf("%x", hash[:]))
localPath := filepath.Join(t.TempDir(), "canary")
if err := os.WriteFile(localPath, content, 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := store.PutIfAbsent(ctx, key, localPath, "application/octet-stream"); err != nil {
t.Fatal(err)
}
reader, err := store.Get(ctx, key)
if err != nil {
t.Fatal(err)
}
actual, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil || !bytes.Equal(actual, content) {
t.Fatalf("MinIO canary read=%q read_error=%v close_error=%v", actual, readErr, closeErr)
}
objects, err := store.List(ctx, key)
if err != nil {
t.Fatal(err)
}
if len(objects) != 1 || objects[0].Key != key || objects[0].Size != int64(len(content)) {
t.Fatalf("MinIO canary listing=%+v", objects)
}
}
// Prove the configured competition archive has every immutable-retention
// property required by the production readiness gate. This is intentionally
// opt-in because it interrogates the live MinIO bucket policy.
func TestLiveBlobStoreRetentionProtection(t *testing.T) {
if os.Getenv("SIM_TESTNET_LIVE_BLOB") != "1" {
t.Skip("set SIM_TESTNET_LIVE_BLOB=1 with WARP_ENV to probe the configured server/blob store")
}
store, ok := LoadBlobStore()
if !ok {
t.Fatal("configured MinIO blob store is unavailable")
}
if bucket := strings.TrimSpace(os.Getenv("SIM_TESTNET_LIVE_BLOB_BUCKET")); bucket != "" {
config, present := LoadBlobStoreConfig()
if !present || config.Local {
t.Fatal("configured MinIO blob store cannot be overridden")
}
config.Bucket = bucket
overrideStore, err := NewBlobStore(config)
if err != nil {
t.Fatal(err)
}
store = overrideStore
}
protected, ok := store.(ProtectedBlobStore)
if !ok {
t.Fatalf("configured blob store %q cannot prove immutable retention", store.Authority())
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
proof, err := protected.CheckProtection(ctx)
if err != nil {
t.Fatal(err)
}
if proof.ObjectLock != "COMPLIANCE" || !proof.Versioning || len(proof.ReplicationTargets) == 0 {
t.Fatalf("incomplete MinIO retention proof: %+v", proof)
}
retained, ok := store.(RetainedBlobStore)
if !ok {
t.Fatalf("configured blob store %q cannot write retained objects", store.Authority())
}
content := []byte("urnetwork competition retained canary v1\n")
digest := sha256.Sum256(content)
localPath := filepath.Join(t.TempDir(), "retained-canary")
if err := os.WriteFile(localPath, content, 0o600); err != nil {
t.Fatal(err)
}
key := path.Join(store.Prefix(), "competition", "preflight", fmt.Sprintf("%x", digest[:]), strconv.FormatInt(NowUtc().UnixNano(), 10))
retention, err := retained.PutRetained(ctx, key, localPath, "application/octet-stream", NowUtc().Add(24*time.Hour))
if err != nil {
t.Fatal(err)
}
reader, err := retained.GetVersion(ctx, retention.Key, retention.VersionId)
if err != nil {
t.Fatal(err)
}
actual, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil || !bytes.Equal(actual, content) {
t.Fatalf("retained MinIO canary read=%q read_error=%v close_error=%v", actual, readErr, closeErr)
}
}
func TestLocalBlobStoreRoundTrip(t *testing.T) {
root := t.TempDir()
store := NewLocalBlobStore(root, "stats")
ctx := context.Background()
if store.Prefix() != "stats" {
t.Fatalf("prefix = %q, want stats", store.Prefix())
}
if store.Bucket() != "local" {
t.Fatalf("bucket = %q, want local", store.Bucket())
}
srcPath := filepath.Join(t.TempDir(), "seg.pb.zst")
content := []byte("hello blob content")
if err := os.WriteFile(srcPath, content, 0o644); err != nil {
t.Fatal(err)
}
key := "stats/local/findproviders2/2026-07-19/inst/1234-0.pb.zst"
if err := store.Put(ctx, key, srcPath, "application/zstd"); err != nil {
t.Fatalf("put: %s", err)
}
objects, err := store.List(ctx, "stats/local/")
if err != nil {
t.Fatalf("list: %s", err)
}
if len(objects) != 1 || objects[0].Key != key || objects[0].Size != int64(len(content)) {
t.Fatalf("list = %+v, want one object key=%s size=%d", objects, key, len(content))
}
reader, err := store.Get(ctx, key)
if err != nil {
t.Fatalf("get: %s", err)
}
got, _ := io.ReadAll(reader)
reader.Close()
if !bytes.Equal(got, content) {
t.Fatalf("get content = %q, want %q", got, content)
}
// a non-matching prefix returns empty (not everything)
if none, err := store.List(ctx, "stats/other/"); err != nil || len(none) != 0 {
t.Fatalf("non-matching prefix: got %v err=%v, want empty", none, err)
}
// a partial (in-progress) write is never listed
if err := os.WriteFile(store.(*localBlobStore).pathFor(key)+blobPartialSuffix, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if objs, _ := store.List(ctx, "stats/local/"); len(objs) != 1 {
t.Fatalf("partial write leaked into list: %+v", objs)
}
// a non-existent root is empty, not an error
if objs, err := NewLocalBlobStore(filepath.Join(root, "nope"), "").List(ctx, ""); err != nil || len(objs) != 0 {
t.Fatalf("non-existent root: got %v err=%v, want empty", objs, err)
}
}
func TestLocalBlobStoreListPageBoundsAndContinues(t *testing.T) {
root := t.TempDir()
store := NewLocalBlobStore(root, "blob")
pagedStore := store.(PagedBlobStore)
source := filepath.Join(t.TempDir(), "source")
if err := os.WriteFile(source, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
ctx := context.Background()
keys := []string{
"blob/history/run-a/01.json",
"blob/history/run-a/02.json",
"blob/history/run-a/03.json",
"blob/history/run-b/01.json",
}
for _, key := range keys {
if err := store.Put(ctx, key, source, "application/json"); err != nil {
t.Fatal(err)
}
}
prefix := "blob/history/run-a/"
first, more, err := pagedStore.ListPage(ctx, prefix, "", 2)
if err != nil || !more || len(first) != 2 || first[0].Key != keys[0] || first[1].Key != keys[1] {
t.Fatalf("first page = %+v more=%v err=%v", first, more, err)
}
second, more, err := pagedStore.ListPage(ctx, prefix, first[len(first)-1].Key, 2)
if err != nil || more || len(second) != 1 || second[0].Key != keys[2] {
t.Fatalf("second page = %+v more=%v err=%v", second, more, err)
}
if _, _, err := pagedStore.ListPage(ctx, prefix, "", 0); err == nil {
t.Fatal("zero page limit accepted")
}
if _, _, err := pagedStore.ListPage(ctx, prefix, "", MaximumBlobListPageObjects+1); err == nil {
t.Fatal("oversized page limit accepted")
}
}
func TestLocalBlobStoreListPageHonorsCancellation(t *testing.T) {
store := NewLocalBlobStore(t.TempDir(), "blob").(PagedBlobStore)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, _, err := store.ListPage(ctx, "blob/", "", 1); !errors.Is(err, context.Canceled) {
t.Fatalf("canceled page error = %v, want context canceled", err)
}
}
func TestLocalBlobStoreListPageBoundsFilesystemScan(t *testing.T) {
store := NewLocalBlobStore(t.TempDir(), "blob").(*localBlobStore)
source := filepath.Join(t.TempDir(), "source")
if err := os.WriteFile(source, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
for _, key := range []string{"blob/history/01.json", "blob/history/02.json", "blob/history/03.json"} {
if err := store.Put(context.Background(), key, source, "application/json"); err != nil {
t.Fatal(err)
}
}
if _, _, err := store.listPage(context.Background(), "blob/history/", "", 1, 2); !errors.Is(err, errLocalBlobListScanLimitExceeded) {
t.Fatalf("bounded filesystem scan error = %v, want %v", err, errLocalBlobListScanLimitExceeded)
}
}
func TestLocalBlobStoreListPageCancelsDuringFilesystemScan(t *testing.T) {
store := NewLocalBlobStore(t.TempDir(), "blob").(*localBlobStore)
source := filepath.Join(t.TempDir(), "source")
if err := os.WriteFile(source, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
if err := store.Put(context.Background(), "blob/history/01.json", source, "application/json"); err != nil {
t.Fatal(err)
}
entered := make(chan struct{})
release := make(chan struct{})
var enteredOnce sync.Once
store.afterListScanEntryForTest = func() {
enteredOnce.Do(func() { close(entered) })
<-release
}
ctx, cancel := context.WithCancel(context.Background())
result := make(chan error, 1)
go func() {
_, _, err := store.ListPage(ctx, "blob/history/", "", 1)
result <- err
}()
select {
case <-entered:
case <-time.After(time.Second):
close(release)
t.Fatal("filesystem scan did not reach cancellation barrier")
}
cancel()
close(release)
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("in-flight cancellation error = %v, want context canceled", err)
}
case <-time.After(time.Second):
t.Fatal("filesystem scan did not stop after cancellation")
}
}
func TestLocalBlobStoreListPageUsesGlobalLexicalOrder(t *testing.T) {
store := NewLocalBlobStore(t.TempDir(), "blob")
pagedStore := store.(PagedBlobStore)
source := filepath.Join(t.TempDir(), "source")
if err := os.WriteFile(source, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
keys := []string{
"blob/history/a-z/aa.json",
"blob/history/a/zz.json",
}
for _, key := range keys {
if err := store.Put(context.Background(), key, source, "application/json"); err != nil {
t.Fatal(err)
}
}
first, more, err := pagedStore.ListPage(context.Background(), "blob/history/", "", 1)
if err != nil || !more || len(first) != 1 || first[0].Key != keys[0] {
t.Fatalf("first lexical page = %+v more=%v err=%v", first, more, err)
}
second, more, err := pagedStore.ListPage(context.Background(), "blob/history/", first[0].Key, 1)
if err != nil || more || len(second) != 1 || second[0].Key != keys[1] {
t.Fatalf("second lexical page = %+v more=%v err=%v", second, more, err)
}
}
func TestLocalBlobStorePutIfAbsentIsAtomicAcrossInstances(t *testing.T) {
root := t.TempDir()
stores := []*localBlobStore{
NewLocalBlobStore(root, "blob").(*localBlobStore),
NewLocalBlobStore(root, "blob").(*localBlobStore),
}
contents := [][]byte{[]byte("first immutable value"), []byte("second immutable value")}
sourcePaths := make([]string, len(contents))
for i, content := range contents {
sourcePaths[i] = filepath.Join(t.TempDir(), fmt.Sprintf("source-%d", i))
if err := os.WriteFile(sourcePaths[i], content, 0o600); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
entered := make(chan int, len(stores))
release := make(chan struct{})
for i, store := range stores {
writerIndex := i
store.beforeCapacityLockForTest = func() {
entered <- writerIndex
select {
case <-release:
case <-ctx.Done():
}
}
}
type putResult struct {
writerIndex int
created bool
err error
}
results := make(chan putResult, len(stores))
for i, store := range stores {
writerIndex := i
go func() {
created, err := store.PutIfAbsent(ctx, "blob/evidence.json", sourcePaths[writerIndex], "application/json")
results <- putResult{writerIndex: writerIndex, created: created, err: err}
}()
}
for range stores {
select {
case <-entered:
case <-ctx.Done():
close(release)
t.Fatalf("writers did not reach the commit barrier: %v", ctx.Err())
}
}
close(release)
createdIndex := -1
for range stores {
select {
case result := <-results:
if result.err != nil {
t.Fatalf("writer %d: %v", result.writerIndex, result.err)
}
if result.created {
if createdIndex != -1 {
t.Fatalf("writers %d and %d both created the key", createdIndex, result.writerIndex)
}
createdIndex = result.writerIndex
}
case <-ctx.Done():
t.Fatalf("writers did not leave the commit barrier: %v", ctx.Err())
}
}
if createdIndex == -1 {
t.Fatal("neither writer created the key")
}
reader, err := stores[0].Get(ctx, "blob/evidence.json")
if err != nil {
t.Fatal(err)
}
winner, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil || !bytes.Equal(winner, contents[createdIndex]) {
t.Fatalf("winner = %q, read error = %v, close error = %v", winner, readErr, closeErr)
}
var partialPaths []string
if err := filepath.Walk(root, func(filePath string, info os.FileInfo, walkErr error) error {
if walkErr != nil {
return walkErr
}
if !info.IsDir() && strings.HasSuffix(filePath, blobPartialSuffix) && filePath != filepath.Join(root, localBlobCapacityLockName) {
partialPaths = append(partialPaths, filePath)
}
return nil
}); err != nil {
t.Fatal(err)
}
if len(partialPaths) != 0 {
t.Fatalf("partial files remain after the race: %v", partialPaths)
}
}
func TestLocalBlobStorePutIfAbsentPreservesCapacity(t *testing.T) {
store := NewLocalBlobStoreWithMaxBytes(t.TempDir(), "blob", 5)
first := filepath.Join(t.TempDir(), "first")
second := filepath.Join(t.TempDir(), "second")
if err := os.WriteFile(first, []byte("1234"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(second, []byte("56"), 0o600); err != nil {
t.Fatal(err)
}
ctx := context.Background()
created, err := store.PutIfAbsent(ctx, "blob/first", first, "application/octet-stream")
if err != nil || !created {
t.Fatalf("first create = %t, %v", created, err)
}
if created, err := store.PutIfAbsent(ctx, "blob/second", second, "application/octet-stream"); err == nil || created {
t.Fatalf("over-capacity create = %t, %v", created, err)
}
if created, err := store.PutIfAbsent(ctx, "blob/first", second, "application/octet-stream"); err != nil || created {
t.Fatalf("existing key create = %t, %v", created, err)
}
reader, err := store.Get(ctx, "blob/first")
if err != nil {
t.Fatal(err)
}
content, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil || string(content) != "1234" {
t.Fatalf("stored content = %q, read error = %v, close error = %v", content, readErr, closeErr)
}
}
// Decodes the application-level framing emitted by SigV4 streaming uploads.
// Every chunk and the terminal chunk must be complete and carry a hex signature.
func decodeAWSSignedChunkedBody(encoded []byte) ([]byte, error) {
const signaturePrefix = ";chunk-signature="
decoded := make([]byte, 0, len(encoded))
remaining := encoded
for {
headerEnd := bytes.Index(remaining, []byte("\r\n"))
if headerEnd < 0 {
return nil, errors.New("aws signed chunk header is truncated")
}
header := string(remaining[:headerEnd])
remaining = remaining[headerEnd+2:]
sizeHex, signature, ok := strings.Cut(header, signaturePrefix)
if !ok || sizeHex == "" {
return nil, fmt.Errorf("invalid aws signed chunk header %q", header)
}
for i := range sizeHex {
sizeByte := sizeHex[i]
if ('0' <= sizeByte && sizeByte <= '9') ||
('a' <= sizeByte && sizeByte <= 'f') ||
('A' <= sizeByte && sizeByte <= 'F') {
continue
}
return nil, fmt.Errorf("invalid aws signed chunk size %q", sizeHex)
}
chunkSize, err := strconv.ParseUint(sizeHex, 16, 64)
if err != nil {
return nil, fmt.Errorf("invalid aws signed chunk size %q: %w", sizeHex, err)
}
if len(signature) != sha256.Size*2 {
return nil, fmt.Errorf("invalid aws signed chunk signature length %d", len(signature))
}
if _, err := hex.DecodeString(signature); err != nil {
return nil, fmt.Errorf("invalid aws signed chunk signature: %w", err)
}
if uint64(len(remaining)) < chunkSize {
return nil, fmt.Errorf("aws signed chunk data is truncated: have %d bytes, want %d", len(remaining), chunkSize)
}
chunkSizeInt := int(chunkSize)
decoded = append(decoded, remaining[:chunkSizeInt]...)
remaining = remaining[chunkSizeInt:]
if len(remaining) < 2 || remaining[0] != '\r' || remaining[1] != '\n' {
return nil, errors.New("aws signed chunk data delimiter is missing")
}
remaining = remaining[2:]
if chunkSize == 0 {
if len(remaining) != 0 {
return nil, fmt.Errorf("aws signed chunk body has %d trailing bytes", len(remaining))
}
return decoded, nil
}
}
}
// Malformed framing must not pass merely because it contains the expected
// object bytes before the damaged terminal chunk or trailing data.
func TestDecodeAWSSignedChunkedBodyRejectsMalformedFraming(t *testing.T) {
payload := `{"evidence":true}`
signature := strings.Repeat("a", sha256.Size*2)
chunk := func(size string, data string) string {
return size + ";chunk-signature=" + signature + "\r\n" + data + "\r\n"
}
terminal := chunk("0", "")
tests := []struct {
name string
encoded string
want string
wantErr bool
}{
{name: "multiple complete chunks", encoded: chunk("c", `{"evidence":`) + chunk("5", `true}`) + terminal, want: payload},
{name: "missing terminal chunk", encoded: chunk("11", payload), wantErr: true},
{name: "truncated terminal header", encoded: chunk("11", payload) + "0;chunk-signature=" + signature[:len(signature)-1], wantErr: true},
{name: "truncated data", encoded: "11;chunk-signature=" + signature + "\r\n" + payload[:len(payload)-1], wantErr: true},
{name: "missing data delimiter", encoded: "11;chunk-signature=" + signature + "\r\n" + payload + "\n" + terminal, wantErr: true},
{name: "invalid signature", encoded: "11;chunk-signature=" + signature[:len(signature)-1] + "g\r\n" + payload + "\r\n" + terminal, wantErr: true},
{name: "invalid size", encoded: "11x;chunk-signature=" + signature + "\r\n" + payload + "\r\n" + terminal, wantErr: true},
{name: "signed size", encoded: "+11;chunk-signature=" + signature + "\r\n" + payload + "\r\n" + terminal, wantErr: true},
{name: "unsigned chunks", encoded: "11\r\n" + payload + "\r\n0\r\n\r\n", wantErr: true},
{name: "trailing data", encoded: chunk("11", payload) + terminal + "ignored", wantErr: true},
}
for _, test := range tests {
decoded, err := decodeAWSSignedChunkedBody([]byte(test.encoded))
if test.wantErr {
if err == nil {
t.Errorf("%s framing passed with body %q", test.name, decoded)
}
continue
}
if err != nil {
t.Errorf("%s framing failed: %v", test.name, err)
continue
}
if string(decoded) != test.want {
t.Errorf("%s body = %q, want %q", test.name, decoded, test.want)
}
}
}
func TestMinIOBlobStorePutIfAbsentUsesConditionalRequest(t *testing.T) {
type requestRecord struct {
method string
path string
ifNoneMatch string
contentType string
contentSHA256 string
decodedContentLength string
body []byte
bodyErr error
}
responseStatuses := []int{
http.StatusOK,
http.StatusPreconditionFailed,
http.StatusForbidden,
http.StatusConflict,
}
responseCodes := []string{"", minio.PreconditionFailed, minio.AccessDenied, "ConditionalRequestConflict"}
var requestStateLock sync.Mutex
var requests []requestRecord
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, bodyErr := io.ReadAll(r.Body)
requestStateLock.Lock()
requests = append(requests, requestRecord{
method: r.Method,
path: r.URL.Path,
ifNoneMatch: r.Header.Get("If-None-Match"),
contentType: r.Header.Get("Content-Type"),
contentSHA256: r.Header.Get("X-Amz-Content-Sha256"),
decodedContentLength: r.Header.Get("X-Amz-Decoded-Content-Length"),
body: body,
bodyErr: bodyErr,
})
responseIndex := len(requests) - 1
requestStateLock.Unlock()
if len(responseStatuses) <= responseIndex {
http.Error(w, "unexpected request", http.StatusInternalServerError)
return
}
status := responseStatuses[responseIndex]
if status == http.StatusOK {
w.Header().Set("ETag", `"created"`)
w.WriteHeader(status)
return
}
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(status)
_, _ = fmt.Fprintf(w, "<Error><Code>%s</Code><Message>rejected</Message></Error>", responseCodes[responseIndex])
}))
defer server.Close()
endpoint, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
client, err := minio.New(endpoint.Host, &minio.Options{
Creds: credentials.NewStaticV4("access", "secret", ""),
Secure: false,
Region: "us-east-1",
BucketLookup: minio.BucketLookupPath,
MaxRetries: 1,
})
if err != nil {
t.Fatal(err)
}
store := &minioBlobStore{client: client, bucket: "evidence", prefix: "blob", authority: endpoint.Host}
source := filepath.Join(t.TempDir(), "evidence.json")
if err := os.WriteFile(source, []byte(`{"evidence":true}`), 0o600); err != nil {
t.Fatal(err)
}
created, err := store.PutIfAbsent(context.Background(), "blob/evidence.json", source, "application/json")
if err != nil || !created {
t.Fatalf("successful conditional create = %t, %v", created, err)
}
created, err = store.PutIfAbsent(context.Background(), "blob/evidence.json", source, "application/json")
if err != nil || created {
t.Fatalf("precondition conflict = %t, %v", created, err)
}
if created, err = store.PutIfAbsent(context.Background(), "blob/evidence.json", source, "application/json"); err == nil || created {
t.Fatalf("access denial = %t, %v", created, err)
}
if created, err = store.PutIfAbsent(context.Background(), "blob/evidence.json", source, "application/json"); err == nil || created {
t.Fatalf("non-precondition conflict = %t, %v", created, err)
}
requestStateLock.Lock()
defer requestStateLock.Unlock()
if len(requests) != len(responseStatuses) {
t.Fatalf("request count = %d, want %d", len(requests), len(responseStatuses))
}
expectedBody := []byte(`{"evidence":true}`)
for i, request := range requests {
if request.method != http.MethodPut || request.path != "/evidence/blob/evidence.json" ||
request.ifNoneMatch != "*" || request.contentType != "application/json" ||
request.contentSHA256 != "STREAMING-AWS4-HMAC-SHA256-PAYLOAD" ||
request.decodedContentLength != strconv.Itoa(len(expectedBody)) {
t.Errorf("request %d = %+v", i, request)
}
if request.bodyErr != nil {
t.Errorf("request %d body read: %v", i, request.bodyErr)
continue
}
decodedBody, err := decodeAWSSignedChunkedBody(request.body)
if err != nil {
t.Errorf("request %d signed body: %v", i, err)
continue
}
if !bytes.Equal(decodedBody, expectedBody) {
t.Errorf("request %d decoded body = %q, want %q", i, decodedBody, expectedBody)
}
}
}
func TestMinIOBlobStoreListPageBoundsBackendRequest(t *testing.T) {
type requestRecord struct {
prefix string
startAfter string
maxKeys string
listType string
continuationToken string
}
var stateLock sync.Mutex
requests := []requestRecord{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
stateLock.Lock()
requests = append(requests, requestRecord{
prefix: r.URL.Query().Get("prefix"),
startAfter: r.URL.Query().Get("start-after"),
maxKeys: r.URL.Query().Get("max-keys"),
listType: r.URL.Query().Get("list-type"),
continuationToken: r.URL.Query().Get("continuation-token"),
})
stateLock.Unlock()
w.Header().Set("Content-Type", "application/xml")
_, _ = io.WriteString(w, `<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>evidence</Name><Prefix>history/run/</Prefix><KeyCount>3</KeyCount><MaxKeys>3</MaxKeys><IsTruncated>true</IsTruncated><NextContinuationToken>next-page</NextContinuationToken>
<Contents><Key>history/run/01.json</Key><Size>1</Size></Contents>
<Contents><Key>history/run/02.json</Key><Size>2</Size></Contents>
<Contents><Key>history/run/03.json</Key><Size>3</Size></Contents>
</ListBucketResult>`)
}))
defer server.Close()
endpoint, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
client, err := minio.New(endpoint.Host, &minio.Options{
Creds: credentials.NewStaticV4("access", "secret", ""),
Secure: false,
Region: "us-east-1",
BucketLookup: minio.BucketLookupPath,
MaxRetries: 1,
})
if err != nil {
t.Fatal(err)
}
store := &minioBlobStore{client: client, bucket: "evidence", prefix: "blob", authority: endpoint.Host}
objects, more, err := store.ListPage(context.Background(), "history/run/", "history/run/00.json", 2)
if err != nil || !more || len(objects) != 2 || objects[0].Key != "history/run/01.json" || objects[1].Key != "history/run/02.json" {
t.Fatalf("page = %+v more=%v err=%v", objects, more, err)
}
stateLock.Lock()
actualRequests := append([]requestRecord(nil), requests...)
stateLock.Unlock()
if len(actualRequests) != 1 {
t.Fatalf("MinIO made %d requests after page was proven: %+v", len(actualRequests), actualRequests)
}
request := actualRequests[0]
if request.prefix != "history/run/" || request.startAfter != "history/run/00.json" || request.maxKeys != "3" || request.listType != "2" || request.continuationToken != "" {
t.Fatalf("list request = %+v", request)
}
}
func TestMinIOPreconditionConflictClassificationIsExact(t *testing.T) {
tests := []struct {
err error
want bool
}{
{err: minio.ErrorResponse{Code: minio.PreconditionFailed, StatusCode: http.StatusPreconditionFailed}, want: true},
{err: minio.ErrorResponse{Code: minio.PreconditionFailed, StatusCode: http.StatusConflict}, want: false},
{err: minio.ErrorResponse{Code: minio.AccessDenied, StatusCode: http.StatusPreconditionFailed}, want: false},
{err: errors.New("transport failed"), want: false},
}
for _, test := range tests {
if got := isMinioPreconditionConflict(test.err); got != test.want {
t.Errorf("isMinioPreconditionConflict(%v) = %t, want %t", test.err, got, test.want)
}
}
}
func TestLocalBlobStoreRetainedCapability(t *testing.T) {
store := NewLocalBlobStore(t.TempDir(), "competition").(RetainedBlobStore)
source := filepath.Join(t.TempDir(), "artifact.json")
content := []byte("{\"schema\":1}\n")
if err := os.WriteFile(source, content, 0o600); err != nil {
t.Fatal(err)
}
retainUntil := NowUtc().Add(24 * time.Hour).Truncate(time.Second)
proof, err := store.PutRetained(
context.Background(), "competition/round/artifact.json", source,
"application/json", retainUntil,
)
if err != nil {
t.Fatal(err)
}
if proof.Mode != "LOCAL" || proof.Size != int64(len(content)) ||
proof.Key != "competition/round/artifact.json" || proof.RetainUntil != retainUntil {
t.Fatalf("retention proof = %+v", proof)
}
reader, err := store.GetVersion(context.Background(), proof.Key, proof.VersionId)
if err != nil {
t.Fatal(err)
}
got, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil || closeErr != nil || !bytes.Equal(got, content) {
t.Fatalf("retained read = %q, %v, %v", got, readErr, closeErr)
}
if err := store.CheckRetention(context.Background()); err != nil {
t.Fatal(err)
}
if _, err := store.PutRetained(
context.Background(), "competition/round/expired", source,
"application/json", NowUtc().Add(-time.Second),
); err == nil {
t.Fatal("expired retention deadline accepted")
}
}
func TestLocalBlobStoreReaper(t *testing.T) {
root := t.TempDir()
store := NewLocalBlobStore(root, "stats").(*localBlobStore)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
src := filepath.Join(t.TempDir(), "seg.pb.zst")
if err := os.WriteFile(src, []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
expiredKey := "stats/local/findproviders2/2026-07-10/inst/1-0.pb.zst" // aged, has a rule -> reaped
freshKey := "stats/local/findproviders2/2026-07-19/inst/2-0.pb.zst" // recent, has a rule -> kept
noRuleKey := "stats/local/otherstream/2026-07-10/inst/1-0.pb.zst" // aged, no rule -> kept
for _, k := range []string{expiredKey, freshKey, noRuleKey} {
if err := store.Put(ctx, k, src, "application/zstd"); err != nil {
t.Fatal(err)
}
}
// age the two "old" objects to 48h ago (by mtime, which the reaper uses)
old := time.Now().Add(-48 * time.Hour)
for _, k := range []string{expiredKey, noRuleKey} {
if err := os.Chtimes(store.pathFor(k), old, old); err != nil {
t.Fatal(err)
}
}
// findproviders2 keeps 24h; otherstream has no rule
if err := store.SetLifecycle(ctx, []BlobLifecycleRule{
{KeyPrefix: "stats/local/findproviders2/", TTL: 24 * time.Hour},
}); err != nil {
t.Fatal(err)
}
if err := store.reapPass(t.Context()); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(store.pathFor(expiredKey)); !os.IsNotExist(err) {
t.Fatalf("expired findproviders2 object should be deleted (err=%v)", err)
}
if _, err := os.Stat(store.pathFor(freshKey)); err != nil {
t.Fatalf("fresh findproviders2 object should be kept: %s", err)
}
if _, err := os.Stat(store.pathFor(noRuleKey)); err != nil {
t.Fatalf("object of a stream with no rule should be kept: %s", err)
}
}
func TestLocalBlobStoreCapacity(t *testing.T) {
root := t.TempDir()
store := NewLocalBlobStoreWithMaxBytes(root, "stats", 5)
ctx := context.Background()
first := filepath.Join(t.TempDir(), "first")
second := filepath.Join(t.TempDir(), "second")
replacement := filepath.Join(t.TempDir(), "replacement")
if err := os.WriteFile(first, []byte("1234"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(second, []byte("56"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(replacement, []byte("1"), 0o644); err != nil {
t.Fatal(err)
}
if err := store.Put(ctx, "stats/a", first, "application/octet-stream"); err != nil {
t.Fatalf("first put: %v", err)
}
if err := store.Put(ctx, "stats/b", second, "application/octet-stream"); err == nil {
t.Fatal("put exceeding aggregate cap succeeded")
}
if err := store.Put(ctx, "stats/a", replacement, "application/octet-stream"); err != nil {
t.Fatalf("smaller replacement: %v", err)
}
if err := store.Put(ctx, "stats/b", second, "application/octet-stream"); err != nil {
t.Fatalf("put after freeing capacity: %v", err)
}
}
func TestMeasureBlobUsageAuthenticatesAllocatedPrefix(t *testing.T) {
store := NewLocalBlobStoreWithMaxBytes(t.TempDir(), "competition", 20)
sourceDirectory := t.TempDir()
firstPath := filepath.Join(sourceDirectory, "first")
secondPath := filepath.Join(sourceDirectory, "second")
if err := os.WriteFile(firstPath, []byte("1234"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(secondPath, []byte("56"), 0600); err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := store.Put(ctx, "competition/one", firstPath, "application/octet-stream"); err != nil {
t.Fatal(err)
}
if err := store.Put(ctx, "competition/two", secondPath, "application/octet-stream"); err != nil {
t.Fatal(err)
}
if err := store.Put(ctx, "other/not-counted", secondPath, "application/octet-stream"); err != nil {
t.Fatal(err)
}
usage, err := MeasureBlobUsage(ctx, store, 10)
if err != nil {
t.Fatal(err)
}
if usage.ObjectCount != 2 || usage.UsedBytes != 6 || usage.FreeBytes != 4 || usage.UsedPercent != 60 {
t.Fatalf("blob usage = %+v", usage)
}
if _, err := MeasureBlobUsage(ctx, store, 0); err == nil {
t.Fatal("zero capacity allocation passed")
}
}
func TestEnabledReplicationTargetsRequireARealEnabledDestination(t *testing.T) {
config := replication.Config{Rules: []replication.Rule{
{Status: replication.Disabled, Destination: replication.Destination{Bucket: "arn:disabled"}},
{Status: replication.Enabled, Destination: replication.Destination{Bucket: "arn:replica-b"}},
{Status: replication.Enabled, Destination: replication.Destination{Bucket: "arn:replica-a"}},
{Status: replication.Enabled, Destination: replication.Destination{Bucket: "arn:replica-b"}},
}}
targets, err := enabledReplicationTargets(config)
if err != nil {
t.Fatal(err)
}
if len(targets) != 2 || targets[0] != "arn:replica-a" || targets[1] != "arn:replica-b" {
t.Fatalf("replication targets = %v", targets)
}
if _, err := enabledReplicationTargets(replication.Config{}); err == nil {
t.Fatal("replication config without an enabled target passed")
}
if _, err := enabledReplicationTargets(replication.Config{Rules: []replication.Rule{
{Status: replication.Enabled},
}}); err == nil {
t.Fatal("enabled replication rule without a destination passed")
}
}
func TestLoadBlobStoreConfigBackendSelection(t *testing.T) {
// explicit local backend
cleanup := Vault.PushSimpleResource("minio.yml", []byte("authority: local\npath: /tmp/sim-blob\nprefix: stats\n"))
config, present := LoadBlobStoreConfig()
if !present {
cleanup()
t.Fatal("expected present")
}
if !config.Local || config.LocalPath != "/tmp/sim-blob" {
cleanup()
t.Fatalf("authority 'local' should select local backend at /tmp/sim-blob, got %+v", config)
}
if config.LocalMaxBytes != DefaultLocalBlobMaxBytes {
t.Fatalf("local max bytes = %d, want %d", config.LocalMaxBytes, DefaultLocalBlobMaxBytes)
}
store, ok := LoadBlobStore()
if ok || store != nil {
cleanup()
t.Fatalf("configured local store without a physical declaration was admitted: ok=%t", ok)
}
cleanup()
// a real authority selects MinIO (not local)
cleanup = Vault.PushSimpleResource("minio.yml", []byte("authority: minio.example.com:9000\nbucket: stats\naccess_key: k\nsecret_key: s\n"))
defer cleanup()
config, present = LoadBlobStoreConfig()
if !present {
t.Fatal("expected present")
}
if config.Local {
t.Fatal("a real authority should not select the local backend")
}
if config.Bucket != "stats" {
t.Fatalf("bucket = %q, want stats", config.Bucket)
}
}
// SetLifecycle must replace only code-owned rules (blobLifecycleRuleIdPrefix)
// and preserve every foreign rule on the bucket — ops-set ILM and other envs'
// rules survive a retention apply.
func TestMergeOwnedLifecycleRules(t *testing.T) {
opsRule := lifecycle.Rule{
ID: "ops-backup-expiry",
Status: "Enabled",
RuleFilter: lifecycle.Filter{Prefix: "backups/"},
Expiration: lifecycle.Expiration{Days: 30},
}
otherEnvRule := lifecycle.Rule{
ID: blobLifecycleRuleIdPrefix + "stats-other-findproviders2",
Status: "Enabled",
RuleFilter: lifecycle.Filter{Prefix: "stats/other/findproviders2/"},
Expiration: lifecycle.Expiration{Days: 7},
}
staleOwnedRule := lifecycle.Rule{
ID: blobLifecycleRuleIdPrefix + "stats-main-findproviders2",
Status: "Enabled",
RuleFilter: lifecycle.Filter{Prefix: "stats/main/findproviders2/"},
Expiration: lifecycle.Expiration{Days: 14},
}
existing := lifecycle.NewConfiguration()
existing.Rules = []lifecycle.Rule{opsRule, otherEnvRule, staleOwnedRule}
owned := []lifecycle.Rule{
{
ID: blobLifecycleRuleIdPrefix + "stats-main-findproviders2",
Status: "Enabled",
RuleFilter: lifecycle.Filter{Prefix: "stats/main/findproviders2/"},
Expiration: lifecycle.Expiration{Days: 7},
},
}
merged := mergeOwnedLifecycleRules(existing, owned)
// replacement is by exact ID: the ops rule and another env's code-owned
// rule (different deterministic ID) both survive; only the rule being
// rewritten is replaced
ids := map[string]lifecycle.Rule{}
for _, rule := range merged {
ids[rule.ID] = rule
}
if len(merged) != 3 {
t.Fatalf("expected 3 merged rules, got %d", len(merged))
}
You can’t perform that action at this time.
