Debian Codegraph @

fs/remote/resolver_test.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 /*
18 Copyright 2019 The Go Authors. All rights reserved.
19 Use of this source code is governed by a BSD-style
20 license that can be found in the NOTICE.md file.
21 */
22
23 package remote
24
25 import (
26 "bytes"
27 "context"
28 "fmt"
29 "io"
30 "net/http"
31 "net/url"
32 "regexp"
33 "strings"
34 "testing"
35
36 "github.com/containerd/containerd/reference"
37 "github.com/containerd/containerd/remotes/docker"
38 "github.com/containerd/stargz-snapshotter/fs/source"
39 rhttp "github.com/hashicorp/go-retryablehttp"
40 digest "github.com/opencontainers/go-digest"
41 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
42 )
43
44 func TestMirror(t *testing.T) {
45 ref := "dummyexample.com/library/test"
46 refspec, err := reference.Parse(ref)
47 if err != nil {
48 t.Fatalf("failed to prepare dummy reference: %v", err)
49 }
50 var (
51 blobDigest = digest.FromString("dummy")
52 blobPath = fmt.Sprintf("/v2/%s/blobs/%s",
53 strings.TrimPrefix(refspec.Locator, refspec.Hostname()+"/"), blobDigest.String())
54 refHost = refspec.Hostname()
55 )
56
57 tests := []struct {
58 name string
59 hosts func(t *testing.T) source.RegistryHosts
60 wantHost string
61 error bool
62 }{
63 {
64 name: "no-mirror",
65 hosts: hostsConfig(
66 &sampleRoundTripper{okURLs: []string{refHost}},
67 ),
68 wantHost: refHost,
69 },
70 {
71 name: "valid-mirror",
72 hosts: hostsConfig(
73 &sampleRoundTripper{okURLs: []string{"mirrorexample.com"}},
74 hostSimple("mirrorexample.com"),
75 ),
76 wantHost: "mirrorexample.com",
77 },
78 {
79 name: "invalid-mirror",
80 hosts: hostsConfig(
81 &sampleRoundTripper{
82 withCode: map[string]int{
83 "mirrorexample1.com": http.StatusInternalServerError,
84 "mirrorexample2.com": http.StatusUnauthorized,
85 "mirrorexample3.com": http.StatusNotFound,
86 },
87 okURLs: []string{"mirrorexample4.com", refHost},
88 },
89 hostSimple("mirrorexample1.com"),
90 hostSimple("mirrorexample2.com"),
91 hostSimple("mirrorexample3.com"),
92 hostSimple("mirrorexample4.com"),
93 ),
94 wantHost: "mirrorexample4.com",
95 },
96 {
97 name: "invalid-all-mirror",
98 hosts: hostsConfig(
99 &sampleRoundTripper{
100 withCode: map[string]int{
101 "mirrorexample1.com": http.StatusInternalServerError,
102 "mirrorexample2.com": http.StatusUnauthorized,
103 "mirrorexample3.com": http.StatusNotFound,
104 },
105 okURLs: []string{refHost},
106 },
107 hostSimple("mirrorexample1.com"),
108 hostSimple("mirrorexample2.com"),
109 hostSimple("mirrorexample3.com"),
110 ),
111 wantHost: refHost,
112 },
113 {
114 name: "invalid-hostname-of-mirror",
115 hosts: hostsConfig(
116 &sampleRoundTripper{
117 okURLs: []string{`.*`},
118 },
119 hostSimple("mirrorexample.com/somepath/"),
120 ),
121 wantHost: refHost,
122 },
123 {
124 name: "redirected-mirror",
125 hosts: hostsConfig(
126 &sampleRoundTripper{
127 redirectURL: map[string]string{
128 regexp.QuoteMeta(fmt.Sprintf("mirrorexample.com%s", blobPath)): "https://backendexample.com/blobs/" + blobDigest.String(),
129 },
130 okURLs: []string{`.*`},
131 },
132 hostSimple("mirrorexample.com"),
133 ),
134 wantHost: "backendexample.com",
135 },
136 {
137 name: "invalid-redirected-mirror",
138 hosts: hostsConfig(
139 &sampleRoundTripper{
140 withCode: map[string]int{
141 "backendexample.com": http.StatusInternalServerError,
142 },
143 redirectURL: map[string]string{
144 regexp.QuoteMeta(fmt.Sprintf("mirrorexample.com%s", blobPath)): "https://backendexample.com/blobs/" + blobDigest.String(),
145 },
146 okURLs: []string{`.*`},
147 },
148 hostSimple("mirrorexample.com"),
149 ),
150 wantHost: refHost,
151 },
152 {
153 name: "fail-all",
154 hosts: hostsConfig(
155 &sampleRoundTripper{},
156 hostSimple("mirrorexample.com"),
157 ),
158 wantHost: "",
159 error: true,
160 },
161 {
162 name: "headers",
163 hosts: hostsConfig(
164 &sampleRoundTripper{
165 okURLs: []string{`.*`},
166 wantHeaders: map[string]http.Header{
167 "mirrorexample.com": http.Header(map[string][]string{
168 "test-a-key": {"a-value-1", "a-value-2"},
169 "test-b-key": {"b-value-1"},
170 }),
171 },
172 },
173 hostWithHeaders("mirrorexample.com", map[string][]string{
174 "test-a-key": {"a-value-1", "a-value-2"},
175 "test-b-key": {"b-value-1"},
176 }),
177 ),
178 wantHost: "mirrorexample.com",
179 },
180 {
181 name: "headers-with-mirrors",
182 hosts: hostsConfig(
183 &sampleRoundTripper{
184 withCode: map[string]int{
185 "mirrorexample1.com": http.StatusInternalServerError,
186 "mirrorexample2.com": http.StatusInternalServerError,
187 },
188 okURLs: []string{"mirrorexample3.com", refHost},
189 wantHeaders: map[string]http.Header{
190 "mirrorexample1.com": http.Header(map[string][]string{
191 "test-a-key": {"a-value"},
192 }),
193 "mirrorexample2.com": http.Header(map[string][]string{
194 "test-b-key": {"b-value"},
195 "test-b-key-2": {"b-value-2", "b-value-3"},
196 }),
197 "mirrorexample3.com": http.Header(map[string][]string{
198 "test-c-key": {"c-value"},
199 }),
200 },
201 },
202 hostWithHeaders("mirrorexample1.com", map[string][]string{
203 "test-a-key": {"a-value"},
204 }),
205 hostWithHeaders("mirrorexample2.com", map[string][]string{
206 "test-b-key": {"b-value"},
207 "test-b-key-2": {"b-value-2", "b-value-3"},
208 }),
209 hostWithHeaders("mirrorexample3.com", map[string][]string{
210 "test-c-key": {"c-value"},
211 }),
212 ),
213 wantHost: "mirrorexample3.com",
214 },
215 {
216 name: "headers-with-mirrors-invalid-all",
217 hosts: hostsConfig(
218 &sampleRoundTripper{
219 withCode: map[string]int{
220 "mirrorexample1.com": http.StatusInternalServerError,
221 "mirrorexample2.com": http.StatusInternalServerError,
222 },
223 okURLs: []string{"mirrorexample3.com", refHost},
224 wantHeaders: map[string]http.Header{
225 "mirrorexample1.com": http.Header(map[string][]string{
226 "test-a-key": {"a-value"},
227 }),
228 "mirrorexample2.com": http.Header(map[string][]string{
229 "test-b-key": {"b-value"},
230 "test-b-key-2": {"b-value-2", "b-value-3"},
231 }),
232 },
233 },
234 hostWithHeaders("mirrorexample1.com", map[string][]string{
235 "test-a-key": {"a-value"},
236 }),
237 hostWithHeaders("mirrorexample2.com", map[string][]string{
238 "test-b-key": {"b-value"},
239 "test-b-key-2": {"b-value-2", "b-value-3"},
240 }),
241 ),
242 wantHost: refHost,
243 },
244 {
245 name: "headers-with-redirected-mirror",
246 hosts: hostsConfig(
247 &sampleRoundTripper{
248 redirectURL: map[string]string{
249 regexp.QuoteMeta(fmt.Sprintf("mirrorexample.com%s", blobPath)): "https://backendexample.com/blobs/" + blobDigest.String(),
250 },
251 okURLs: []string{`.*`},
252 wantHeaders: map[string]http.Header{
253 "mirrorexample.com": http.Header(map[string][]string{
254 "test-a-key": {"a-value"},
255 "test-b-key-2": {"b-value-2", "b-value-3"},
256 }),
257 },
258 },
259 hostWithHeaders("mirrorexample.com", map[string][]string{
260 "test-a-key": {"a-value"},
261 "test-b-key-2": {"b-value-2", "b-value-3"},
262 }),
263 ),
264 wantHost: "backendexample.com",
265 },
266 }
267
268 for _, tt := range tests {
269 t.Run(tt.name, func(t *testing.T) {
270 fetcher, _, err := newHTTPFetcher(context.Background(), &fetcherConfig{
271 hosts: tt.hosts(t),
272 refspec: refspec,
273 desc: ocispec.Descriptor{Digest: blobDigest},
274 })
275 if err != nil {
276 if tt.error {
277 return
278 }
279 t.Fatalf("failed to resolve reference: %v", err)
280 }
281 checkFetcherURL(t, fetcher, tt.wantHost)
282
283 // Test check()
284 if err := fetcher.check(); err != nil {
285 t.Fatalf("failed to check fetcher: %v", err)
286 }
287
288 // Test refreshURL()
289 if err := fetcher.refreshURL(context.TODO()); err != nil {
290 t.Fatalf("failed to refresh URL: %v", err)
291 }
292 checkFetcherURL(t, fetcher, tt.wantHost)
293 })
294 }
295 }
296
297 func checkFetcherURL(t *testing.T, f *httpFetcher, wantHost string) {
298 nurl, err := url.Parse(f.url)
299 if err != nil {
300 t.Fatalf("failed to parse url %q: %v", f.url, err)
301 }
302 if nurl.Hostname() != wantHost {
303 t.Errorf("invalid hostname %q(%q); want %q", nurl.Hostname(), nurl.String(), wantHost)
304 }
305 }
306
307 type sampleRoundTripper struct {
308 t *testing.T
309 withCode map[string]int
310 redirectURL map[string]string
311 okURLs []string
312 wantHeaders map[string]http.Header
313 }
314
315 func getTestHeaders(headers map[string][]string) map[string][]string {
316 res := make(map[string][]string)
317 for k, v := range headers {
318 if strings.HasPrefix(k, "test-") {
319 res[k] = v
320 }
321 }
322 return res
323 }
324
325 func (tr *sampleRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
326 reqHeader := getTestHeaders(req.Header)
327 for host, wHeaders := range tr.wantHeaders {
328 wantHeader := getTestHeaders(wHeaders)
329 if ok, _ := regexp.Match(host, []byte(req.URL.String())); ok {
330 if len(wantHeader) != len(reqHeader) {
331 tr.t.Fatalf("unexpected num of headers; got %d, wanted %d", len(wantHeader), len(reqHeader))
332 }
333 for k, v := range wantHeader {
334 gotV, ok := reqHeader[k]
335 if !ok {
336 tr.t.Fatalf("required header %q not found; got %+v", k, reqHeader)
337 }
338 wantVM := make(map[string]struct{})
339 for _, e := range v {
340 wantVM[e] = struct{}{}
341 }
342 if len(gotV) != len(v) {
343 tr.t.Fatalf("unexpected num of header values of %q; got %d, wanted %d", k, len(gotV), len(v))
344 }
345 for _, gotE := range gotV {
346 delete(wantVM, gotE)
347 }
348 if len(wantVM) != 0 {
349 tr.t.Fatalf("header %q must have elements %+v", k, wantVM)
350 }
351 delete(reqHeader, k)
352 }
353 }
354 }
355 if len(reqHeader) != 0 {
356 tr.t.Fatalf("unexpected headers %+v", reqHeader)
357 }
358
359 for host, code := range tr.withCode {
360 if ok, _ := regexp.Match(host, []byte(req.URL.String())); ok {
361 return &http.Response{
362 StatusCode: code,
363 Header: make(http.Header),
364 Body: io.NopCloser(bytes.NewReader([]byte{})),
365 Request: req,
366 }, nil
367 }
368 }
369 for host, rurl := range tr.redirectURL {
370 if ok, _ := regexp.Match(host, []byte(req.URL.String())); ok {
371 header := make(http.Header)
372 header.Add("Location", rurl)
373 return &http.Response{
374 StatusCode: http.StatusMovedPermanently,
375 Header: header,
376 Body: io.NopCloser(bytes.NewReader([]byte{})),
377 Request: req,
378 }, nil
379 }
380 }
381 for _, host := range tr.okURLs {
382 if ok, _ := regexp.Match(host, []byte(req.URL.String())); ok {
383 header := make(http.Header)
384 header.Add("Content-Length", "1")
385 return &http.Response{
386 StatusCode: http.StatusOK,
387 Header: header,
388 Body: io.NopCloser(bytes.NewReader([]byte{0})),
389 Request: req,
390 }, nil
391 }
392 }
393 return &http.Response{
394 StatusCode: http.StatusNotFound,
395 Header: make(http.Header),
396 Body: io.NopCloser(bytes.NewReader([]byte{})),
397 Request: req,
398 }, nil
399 }
400
401 func TestCheck(t *testing.T) {
402 tr := &breakRoundTripper{}
403 f := &httpFetcher{
404 url: "test",
405 tr: tr,
406 }
407 tr.success = true
408 if err := f.check(); err != nil {
409 t.Errorf("connection failed; wanted to succeed")
410 }
411
412 tr.success = false
413 if err := f.check(); err == nil {
414 t.Errorf("connection succeeded; wanted to fail")
415 }
416 }
417
418 type breakRoundTripper struct {
419 success bool
420 }
421
422 func (b *breakRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
423 if b.success {
424 res = &http.Response{
425 StatusCode: http.StatusPartialContent,
426 Header: make(http.Header),
427 Body: io.NopCloser(bytes.NewReader([]byte("test"))),
428 }
429 } else {
430 res = &http.Response{
431 StatusCode: http.StatusInternalServerError,
432 Header: make(http.Header),
433 Body: io.NopCloser(bytes.NewReader([]byte{})),
434 }
435 }
436 return
437 }
438
439 func TestRetry(t *testing.T) {
440 tr := &retryRoundTripper{}
441 rclient := rhttp.NewClient()
442 rclient.HTTPClient.Transport = tr
443 rclient.Backoff = backoffStrategy
444 f := &httpFetcher{
445 url: "test",
446 tr: &rhttp.RoundTripper{Client: rclient},
447 }
448
449 regions := []region{{b: 0, e: 1}}
450
451 _, err := f.fetch(context.Background(), regions, true)
452
453 if err != nil {
454 t.Fatalf("unexpected error = %v", err)
455 }
456
457 if tr.retryCount != 4 {
458 t.Fatalf("unxpected retryCount; expected=4 got=%d", tr.retryCount)
459 }
460 }
461
462 type retryRoundTripper struct {
463 retryCount int
464 }
465
466 func (r *retryRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
467 defer func() {
468 r.retryCount++
469 }()
470
471 switch r.retryCount {
472 case 0:
473 err = fmt.Errorf("dummy error")
474 case 1:
475 res = &http.Response{
476 StatusCode: http.StatusTooManyRequests,
477 Header: make(http.Header),
478 Body: io.NopCloser(bytes.NewReader([]byte{})),
479 }
480 case 2:
481 res = &http.Response{
482 StatusCode: http.StatusServiceUnavailable,
483 Header: make(http.Header),
484 Body: io.NopCloser(bytes.NewReader([]byte{})),
485 }
486 default:
487 header := make(http.Header)
488 header.Add("Content-Length", "4")
489 res = &http.Response{
490 StatusCode: http.StatusOK,
491 Header: header,
492 Body: io.NopCloser(bytes.NewReader([]byte("test"))),
493 }
494 }
495 return
496 }
497
498 type hostFactory func(tr http.RoundTripper) docker.RegistryHost
499
500 func hostSimple(host string) hostFactory {
501 return func(tr http.RoundTripper) docker.RegistryHost {
502 return docker.RegistryHost{
503 Client: &http.Client{Transport: tr},
504 Host: host,
505 Scheme: "https",
506 Path: "/v2",
507 Capabilities: docker.HostCapabilityPull,
508 }
509 }
510 }
511
512 func hostWithHeaders(host string, headers http.Header) hostFactory {
513 return func(tr http.RoundTripper) docker.RegistryHost {
514 return docker.RegistryHost{
515 Client: &http.Client{Transport: tr},
516 Host: host,
517 Scheme: "https",
518 Path: "/v2",
519 Capabilities: docker.HostCapabilityPull,
520 Header: headers,
521 }
522 }
523 }
524
525 func hostsConfig(tr *sampleRoundTripper, mirrors ...hostFactory) func(t *testing.T) source.RegistryHosts {
526 return func(t *testing.T) source.RegistryHosts {
527 tr.t = t
528 return func(refspec reference.Spec) (reghosts []docker.RegistryHost, _ error) {
529 host := refspec.Hostname()
530 for _, m := range mirrors {
531 reghosts = append(reghosts, m(tr))
532 }
533 reghosts = append(reghosts, hostSimple(host)(tr))
534 return
535 }
536 }
537 }