-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathapi.go
More file actions
1681 lines (1606 loc) · 43.4 KB
/
Copy pathapi.go
File metadata and controls
1681 lines (1606 loc) · 43.4 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
// Copyright the Open Container Initiative Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
specs "github.com/opencontainers/distribution-spec/specs-go/v1"
digest "github.com/opencontainers/go-digest"
image "github.com/opencontainers/image-spec/specs-go/v1"
)
var emptyDigest = digest.Canonical.FromBytes([]byte{})
type api struct {
client *http.Client
user, pass string
authCache map[string]string
}
type apiOpt func(*api)
func apiNew(client *http.Client, opts ...apiOpt) *api {
a := &api{
client: client,
}
for _, opt := range opts {
opt(a)
}
return a
}
func apiWithAuth(user, pass string, cacheAuth bool) apiOpt {
return func(a *api) {
a.user = user
a.pass = pass
if cacheAuth {
a.authCache = map[string]string{}
}
}
}
type apiDoOpt struct {
reqFn func(*http.Request) error
respFn func(*http.Response) error
out io.Writer
flags map[string]bool
}
func (a *api) Do(opts ...apiDoOpt) error {
errs := []error{}
reqFns := []func(*http.Request) error{}
respFns := []func(*http.Response) error{}
var out io.Writer
for _, opt := range opts {
if opt.reqFn != nil {
reqFns = append(reqFns, opt.reqFn)
}
if opt.respFn != nil {
respFns = append(respFns, opt.respFn)
}
if opt.out != nil {
out = opt.out
}
}
req, err := http.NewRequest(http.MethodGet, "", nil)
if err != nil {
return err
}
for _, reqFn := range reqFns {
err := reqFn(req)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) == 1 {
return errs[0]
} else if len(errs) > 1 {
return errors.Join(errs...)
}
// add cached auth header if available
if a.authCache != nil {
err = a.addCachedAuth(req)
if err != nil {
return err
}
}
if out != nil {
out = redactWriter{w: out}
}
wt := &wrapTransport{out: out, orig: a.client.Transport}
if a.client.Transport == nil {
wt.orig = http.DefaultTransport
}
c := *a.client
c.Transport = wt
resp, err := c.Do(req)
if err != nil {
return err
}
// on auth failures, generate the auth header and retry
if resp.StatusCode == http.StatusUnauthorized {
auth, err := a.getAuthHeader(c, resp)
if err != nil {
errs = append(errs, err)
}
if resp.Body != nil {
_ = resp.Body.Close()
}
if err == nil && auth != "" {
req.Header.Set("Authorization", auth)
if req.GetBody != nil {
req.Body, err = req.GetBody()
if err != nil {
return fmt.Errorf("failed to reset body after auth request: %w", err)
}
}
resp, err = c.Do(req)
if err != nil {
return err
}
}
}
for _, respFn := range respFns {
err := respFn(resp)
if err != nil {
errs = append(errs, err)
}
}
if resp.Body != nil {
_ = resp.Body.Close()
}
if len(errs) == 1 {
return errs[0]
} else if len(errs) > 1 {
return errors.Join(errs...)
}
return nil
}
func (a *api) GetFlags(opts ...apiDoOpt) map[string]bool {
ret := map[string]bool{}
for _, opt := range opts {
maps.Copy(ret, opt.flags)
}
return ret
}
func (a *api) VerifyDigest(resp *http.Response, dig digest.Digest, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
digHeader := resp.Header.Get("Docker-Content-Digest")
if digHeader == "" && flags["RequireDigestHeader"] {
return fmt.Errorf("registry did not return a Docker-Content-Digest header")
}
if digHeader != "" && dig.String() != "" && digHeader != dig.String() {
return fmt.Errorf("Docker-Content-Digest header value expected %q, received %q", dig.String(), digHeader)
}
return nil
}
func (a *api) BlobDelete(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/" + dig.String())
if err != nil {
return err
}
var status int
err = a.Do(
apiWithMethod("DELETE"),
apiWithURL(u),
apiExpectStatus(http.StatusAccepted, http.StatusNotFound, http.StatusMethodNotAllowed),
apiReturnStatus(&status),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob delete failed: %w", err)
}
if status == http.StatusMethodNotAllowed {
return fmt.Errorf("registry returned status %d%.0w", status, errRegUnsupported)
}
return nil
}
func (a *api) BlobGetReq(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/" + dig.String())
if err != nil {
return err
}
err = a.Do(
apiWithMethod("GET"),
apiWithURL(u),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob get failed: %w", err)
}
return nil
}
func (a *api) BlobGetExistsFull(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
resp := http.Response{Header: http.Header{}}
opts = append(opts,
apiExpectStatus(http.StatusOK),
apiReturnResponse(&resp),
)
if val, ok := td.blobs[dig]; ok && (len(val) > 0 || dig == emptyDigest) {
opts = append(opts, apiExpectBody(val), apiExpectHeader("Content-Length", fmt.Sprintf("%d", len(val))))
}
errs := []error{}
if err := a.BlobGetReq(registry, repo, dig, td, opts...); err != nil {
errs = append(errs, err)
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (a *api) BlobHeadReq(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/" + dig.String())
if err != nil {
return err
}
err = a.Do(
apiWithMethod("HEAD"),
apiWithURL(u),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob head failed: %w", err)
}
return nil
}
func (a *api) BlobHeadExists(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
resp := http.Response{Header: http.Header{}}
opts = append(opts,
apiExpectStatus(http.StatusOK),
apiExpectBody([]byte{}),
apiReturnResponse(&resp),
)
if val, ok := td.blobs[dig]; ok && (len(val) > 0 || dig == emptyDigest) {
opts = append(opts, apiExpectHeader("Content-Length", fmt.Sprintf("%d", len(val))))
}
errs := []error{}
if err := a.BlobHeadReq(registry, repo, dig, td, opts...); err != nil {
errs = append(errs, err)
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (a *api) BlobMount(registry, repo, source string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
bodyBytes, ok := td.blobs[dig]
if !ok {
return fmt.Errorf("BlobPostPut missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
qa := u.Query()
qa.Set("mount", dig.String())
if source != "" {
qa.Set("from", source)
}
u.RawQuery = qa.Encode()
// TODO: add digest algorithm if not sha256
errs := []error{}
loc := ""
status := 0
resp := http.Response{Header: http.Header{}}
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiExpectStatus(http.StatusCreated, http.StatusAccepted),
apiReturnHeader("Location", &loc),
apiReturnStatus(&status),
apiReturnResponse(&resp),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
if loc == "" {
return fmt.Errorf("blob post did not return a location")
}
if status == http.StatusAccepted {
// fallback to post+put
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob post could not parse location header %q: %w", loc, err)
}
qa = u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithContentLength(int64(len(bodyBytes))),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithBody(bodyBytes),
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob put failed: %w", err)
}
errs = append(errs, fmt.Errorf("registry returned status %d, fell back to blob POST+PUT%.0w", status, errRegUnsupported))
} else if status != http.StatusCreated {
return fmt.Errorf("blob mount returned status %d", status)
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
return err
}
if err := a.BlobVerifyLocation(u, loc, bodyBytes, opts...); err != nil {
return err
}
return errors.Join(errs...)
}
func (a *api) BlobPatchChunked(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
bodyBytes, ok := td.blobs[dig]
if !ok {
return fmt.Errorf("BlobPatchChunked missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
// TODO: add digest algorithm if not sha256
minStr := ""
loc := ""
resp := http.Response{Header: http.Header{}}
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiWithContentLength(0),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("OCI-Chunk-Min-Length", &minStr),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
// calc chunk size to make 3 chunks, adjust to min chunk size if specified
chunkSize := len(bodyBytes)/3 + 1
if minStr != "" {
min, err := strconv.Atoi(minStr)
if err != nil {
return fmt.Errorf("parsing OCI-Chunk-Min-Length size %q failed: %w", minStr, err)
}
if min > chunkSize {
chunkSize = min
}
}
if chunkSize < chunkMin {
chunkSize = chunkMin
}
if chunkSize > len(bodyBytes) {
chunkSize = len(bodyBytes)
}
lastByte := -1
// loop over the number of chunks
for lastByte < len(bodyBytes)-1 {
if flags["OutOfOrderChunks"] {
if loc == "" {
return fmt.Errorf("blob request did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob request could not parse location header: %w", err)
}
// send an out of order chunk, skipping ahead or back to the beginning
badStart := lastByte + 1 + chunkSize
if badStart >= len(bodyBytes) {
badStart = 0
}
badLastByte := min(badStart+chunkSize-1, len(bodyBytes)-1)
method := "PATCH"
if flags["PutLastChunk"] && badLastByte == len(bodyBytes)-1 {
method = "PUT"
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
}
err = a.Do(
apiWithMethod(method),
apiWithURL(u),
apiWithContentLength(int64(badLastByte-badStart+1)),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithHeaderAdd("Content-Range", fmt.Sprintf("%d-%d", badStart, badLastByte)),
apiWithBody(bodyBytes[badStart:badLastByte+1]),
apiExpectStatus(http.StatusRequestedRangeNotSatisfiable),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob out of order chunk: %w", err)
}
// recover with a GET request to find the new location/range
rangeHeader := ""
err = a.Do(
apiWithMethod("GET"),
apiWithURL(u),
apiExpectStatus(http.StatusNoContent),
apiReturnHeader("Location", &loc),
apiReturnHeader("Range", &rangeHeader),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob chunked upload get request: %w", err)
}
rangeHeader, found := strings.CutPrefix(rangeHeader, "0-")
if !found {
return fmt.Errorf("content-range header is missing the 0- prefix: %q", rangeHeader)
}
rangeLastByte, err := strconv.Atoi(rangeHeader)
if err != nil {
return fmt.Errorf("content-range header could not be parsed: %q", rangeHeader)
}
if lastByte >= 0 && rangeLastByte != lastByte {
return fmt.Errorf("content-range unexpected, received %q, expected \"0-%d\"", rangeHeader, lastByte)
}
}
if loc == "" {
return fmt.Errorf("blob request did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob request could not parse location header: %w", err)
}
start := lastByte + 1
lastByte = min(start+chunkSize-1, len(bodyBytes)-1)
var chunkOpts []apiDoOpt
if flags["PutLastChunk"] && lastByte == len(bodyBytes)-1 {
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
chunkOpts = append([]apiDoOpt{
apiWithMethod("PUT"),
}, opts...)
if flags["ExpectBadDigest"] {
chunkOpts = append(chunkOpts,
apiExpectStatus(http.StatusBadRequest),
)
} else {
chunkOpts = append(chunkOpts,
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
)
}
} else {
chunkOpts = append([]apiDoOpt{
apiWithMethod("PATCH"),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("Location", &loc),
}, opts...)
}
err = a.Do(
apiWithURL(u),
apiWithContentLength(int64(lastByte-start+1)),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithHeaderAdd("Content-Range", fmt.Sprintf("%d-%d", start, lastByte)),
apiWithBody(bodyBytes[start:lastByte+1]),
apiWithAnd(chunkOpts),
)
if err != nil {
return fmt.Errorf("blob patch failed: %w", err)
}
}
if !flags["PutLastChunk"] {
if loc == "" {
return fmt.Errorf("blob patch did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob patch could not parse location header: %w", err)
}
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
var putOpts []apiDoOpt
if flags["ExpectBadDigest"] {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusBadRequest),
}, opts...)
} else {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
}, opts...)
}
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithContentLength(0),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithAnd(putOpts),
)
if err != nil {
return fmt.Errorf("blob put failed: %w", err)
}
}
if flags["ExpectBadDigest"] {
return nil
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
return err
}
if err := a.BlobVerifyLocation(u, loc, bodyBytes, opts...); err != nil {
return err
}
return nil
}
func (a *api) BlobPatchStream(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
bodyBytes, ok := td.blobs[dig]
if !ok {
return fmt.Errorf("BlobPatchStream missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
// TODO: add digest algorithm if not sha256
loc := ""
resp := http.Response{Header: http.Header{}}
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiWithContentLength(0),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
if loc == "" {
return fmt.Errorf("blob post did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob post could not parse location header: %w", err)
}
err = a.Do(
apiWithMethod("PATCH"),
apiWithURL(u),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithBody(bodyBytes),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob patch failed: %w", err)
}
if loc == "" {
return fmt.Errorf("blob patch did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob patch could not parse location header: %w", err)
}
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
var putOpts []apiDoOpt
if flags["ExpectBadDigest"] {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusBadRequest),
}, opts...)
} else {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated),
apiExpectHeader("Location", ""),
}, opts...)
}
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithContentLength(0),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
apiWithAnd(putOpts),
)
if err != nil {
return fmt.Errorf("blob put failed: %w", err)
}
if flags["ExpectBadDigest"] {
return nil
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
return err
}
if err := a.BlobVerifyLocation(u, loc, bodyBytes, opts...); err != nil {
return err
}
return nil
}
func (a *api) BlobPostCancel(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
loc := ""
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
if loc == "" {
return fmt.Errorf("blob post did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob post could not parse location header: %w", err)
}
err = a.Do(
apiWithMethod("DELETE"),
apiWithURL(u),
apiWithContentLength(0),
apiExpectStatus(http.StatusNoContent),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob cancel failed: %w", err)
}
return nil
}
func (a *api) BlobPostOnly(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
bodyBytes, ok := td.blobs[dig]
if !ok {
return fmt.Errorf("BlobPostOnly missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
loc := ""
resp := http.Response{Header: http.Header{}}
var status int
var postOpts []apiDoOpt
if flags["ExpectBadDigest"] {
postOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusBadRequest, http.StatusAccepted),
}, opts...)
} else {
postOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated, http.StatusAccepted),
apiExpectHeader("Location", ""),
}, opts...)
}
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiWithContentLength(int64(len(bodyBytes))),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithBody(bodyBytes),
apiReturnStatus(&status),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
apiWithAnd(postOpts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
if status == http.StatusAccepted {
// fallback to a PUT request, but track the unsupported API
var putOpts []apiDoOpt
if flags["ExpectBadDigest"] {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusBadRequest),
}, opts...)
} else {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
}, opts...)
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob post could not parse location header: %w", err)
}
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithContentLength(int64(len(bodyBytes))),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithBody(bodyBytes),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
apiWithAnd(putOpts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
return fmt.Errorf("registry does not support content in the POST, fallback to PUT%.0w", errRegUnsupported)
}
if flags["ExpectBadDigest"] {
return nil
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
return err
}
if err := a.BlobVerifyLocation(u, loc, bodyBytes, opts...); err != nil {
return err
}
return nil
}
func (a *api) BlobPostPut(registry, repo string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
bodyBytes, ok := td.blobs[dig]
if !ok {
return fmt.Errorf("BlobPostPut missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/blobs/uploads/")
if err != nil {
return err
}
// TODO: add digest algorithm if not sha256
loc := ""
resp := http.Response{Header: http.Header{}}
err = a.Do(
apiWithMethod("POST"),
apiWithURL(u),
apiExpectStatus(http.StatusAccepted),
apiReturnHeader("Location", &loc),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("blob post failed: %w", err)
}
if loc == "" {
return fmt.Errorf("blob post did not return a location")
}
u, err = u.Parse(loc)
if err != nil {
return fmt.Errorf("blob post could not parse location header: %w", err)
}
qa := u.Query()
qa.Set("digest", dig.String())
u.RawQuery = qa.Encode()
var putOpts []apiDoOpt
if flags["ExpectBadDigest"] {
putOpts = append([]apiDoOpt{apiExpectStatus(http.StatusBadRequest)},
opts...)
} else {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
apiReturnResponse(&resp),
}, opts...)
}
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithContentLength(int64(len(bodyBytes))),
apiWithHeaderAdd("Content-Type", mtOctetStream),
apiWithBody(bodyBytes),
apiWithAnd(putOpts),
)
if err != nil {
return fmt.Errorf("blob put failed: %w", err)
}
if flags["ExpectBadDigest"] {
return nil
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
return err
}
if err := a.BlobVerifyLocation(u, loc, bodyBytes, opts...); err != nil {
return err
}
return nil
}
func (a *api) BlobVerifyLocation(u *url.URL, loc string, bodyBytes []byte, opts ...apiDoOpt) error {
if loc == "" {
return fmt.Errorf("location header missing")
}
u, err := u.Parse(loc)
if err != nil {
return fmt.Errorf("could not parse location header %q: %w", loc, err)
}
err = a.Do(
apiWithMethod("GET"),
apiWithURL(u),
apiExpectBody(bodyBytes),
apiExpectStatus(http.StatusOK),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("failed to verify returned location: %w", err)
}
return nil
}
func (a *api) ManifestDelete(registry, repo, ref string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/manifests/" + ref)
if err != nil {
return err
}
var status int
err = a.Do(
apiWithMethod("DELETE"),
apiWithURL(u),
apiExpectStatus(http.StatusAccepted, http.StatusNotFound, http.StatusBadRequest, http.StatusMethodNotAllowed),
apiReturnStatus(&status),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("manifest delete failed: %w", err)
}
if status == http.StatusBadRequest || status == http.StatusMethodNotAllowed {
return fmt.Errorf("registry returned status %d%.0w", status, errRegUnsupported)
}
return nil
}
func (a *api) ManifestGetReq(registry, repo, ref string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/manifests/" + ref)
if err != nil {
return err
}
err = a.Do(
apiWithMethod("GET"),
apiWithURL(u),
apiWithHeaderAdd("Accept", mtOCIIndex),
apiWithHeaderAdd("Accept", mtOCIImage),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("manifest get failed: %w", err)
}
return nil
}
func (a *api) ManifestGetExists(registry, repo, ref string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
opts = append(opts,
apiExpectStatus(http.StatusOK),
)
resp := http.Response{Header: http.Header{}}
if val, ok := td.manifests[dig]; ok && len(val) > 0 {
mediaType := detectMediaType(val)
opts = append(opts,
apiExpectBody(val),
apiExpectHeader("Content-Type", mediaType),
apiExpectHeader("Content-Length", fmt.Sprintf("%d", len(val))),
apiReturnResponse(&resp),
)
}
errs := []error{}
if err := a.ManifestGetReq(registry, repo, ref, dig, td, opts...); err != nil {
errs = append(errs, err)
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (a *api) ManifestHeadReq(registry, repo, ref string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
u, err := url.Parse(registry + "/v2/" + repo + "/manifests/" + ref)
if err != nil {
return err
}
err = a.Do(
apiWithMethod("HEAD"),
apiWithURL(u),
apiWithHeaderAdd("Accept", mtOCIIndex),
apiWithHeaderAdd("Accept", mtOCIImage),
apiWithAnd(opts),
)
if err != nil {
return fmt.Errorf("manifest head failed: %w", err)
}
return nil
}
func (a *api) ManifestHeadExists(registry, repo, ref string, dig digest.Digest, td *testData, opts ...apiDoOpt) error {
opts = append(opts,
apiExpectStatus(http.StatusOK),
apiExpectBody([]byte{}),
)
resp := http.Response{Header: http.Header{}}
if val, ok := td.manifests[dig]; ok && len(val) > 0 {
mediaType := detectMediaType(val)
opts = append(opts,
apiExpectHeader("Content-Type", mediaType),
apiExpectHeader("Content-Length", fmt.Sprintf("%d", len(val))),
apiReturnResponse(&resp),
)
}
errs := []error{}
if err := a.ManifestHeadReq(registry, repo, ref, dig, td, opts...); err != nil {
errs = append(errs, err)
}
if err := a.VerifyDigest(&resp, dig, opts...); err != nil {
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (a *api) ManifestPut(registry, repo, ref string, dig digest.Digest, td *testData, referrersEnabled bool, putOpts []apiDoOpt, opts ...apiDoOpt) error {
flags := a.GetFlags(opts...)
bodyBytes, ok := td.manifests[dig]
if !ok {
return fmt.Errorf("ManifestPut missing expected digest to send: %s%.0w", dig.String(), errAPITestError)
}
u, err := url.Parse(registry + "/v2/" + repo + "/manifests/" + ref)
if err != nil {
return err
}
mediaType := detectMediaType(bodyBytes)
resp := http.Response{Header: http.Header{}}
loc := ""
putOpts = append(putOpts, opts...)
if flags["ExpectBadDigest"] {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusBadRequest),
}, putOpts...)
} else {
putOpts = append([]apiDoOpt{
apiExpectStatus(http.StatusCreated),
apiReturnHeader("Location", &loc),
}, putOpts...)
}
if referrersEnabled {
// if the referrers API is being tested, verify OCI-Subject header is returned when appropriate
subj := detectSubject(td.manifests[dig])
if subj != nil {
putOpts = append(putOpts, apiExpectHeader("OCI-Subject", subj.Digest.String()))
}
}
errs := []error{}
err = a.Do(
apiWithMethod("PUT"),
apiWithURL(u),
apiWithBody(bodyBytes),
apiWithHeaderAdd("Content-Type", mediaType),
apiReturnResponse(&resp),
apiWithAnd(putOpts),
)
if err != nil {
errs = append(errs, fmt.Errorf("manifest put failed: %w", err))
}
// do not validate response if a failure was expected
if flags["ExpectBadDigest"] {
return errors.Join(errs...)
}