forked from google/go-containerregistry
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bearer_test.go
561 lines (503 loc) · 15.2 KB
/
bearer_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
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
// Copyright 2018 Google LLC All Rights Reserved.
//
// 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 transport
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
)
func TestBearerRefresh(t *testing.T) {
expectedToken := "Sup3rDup3rS3cr3tz"
expectedScope := "this-is-your-scope"
expectedService := "my-service.io"
cases := []struct {
tokenKey string
wantErr bool
}{{
tokenKey: "token",
wantErr: false,
}, {
tokenKey: "access_token",
wantErr: false,
}, {
tokenKey: "tolkien",
wantErr: true,
}}
for _, tc := range cases {
t.Run(tc.tokenKey, func(t *testing.T) {
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hdr := r.Header.Get("Authorization")
if !strings.HasPrefix(hdr, "Basic ") {
t.Errorf("Header.Get(Authorization); got %v, want Basic prefix", hdr)
}
if got, want := r.FormValue("scope"), expectedScope; got != want {
t.Errorf("FormValue(scope); got %v, want %v", got, want)
}
if got, want := r.FormValue("service"), expectedService; got != want {
t.Errorf("FormValue(service); got %v, want %v", got, want)
}
w.Write([]byte(fmt.Sprintf(`{%q: %q}`, tc.tokenKey, expectedToken)))
}))
defer server.Close()
basic := &authn.Basic{Username: "foo", Password: "bar"}
registry, err := name.NewRegistry(expectedService, name.WeakValidation)
if err != nil {
t.Errorf("Unexpected error during NewRegistry: %v", err)
}
bt := &bearerTransport{
inner: http.DefaultTransport,
basic: basic,
registry: registry,
realm: server.URL,
scopes: []string{expectedScope},
service: expectedService,
scheme: "http",
}
if err := bt.refresh(context.Background()); (err != nil) != tc.wantErr {
t.Errorf("refresh() = %v", err)
}
})
}
}
func TestBearerTransport(t *testing.T) {
expectedToken := "sdkjhfskjdhfkjshdf"
blobServer := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// We don't expect the blobServer to receive bearer tokens.
if got := r.Header.Get("Authorization"); got != "" {
t.Errorf("Header.Get(Authorization); got %v, want empty string", got)
}
w.WriteHeader(http.StatusOK)
}))
defer blobServer.Close()
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got, want := r.Header.Get("Authorization"), "Bearer "+expectedToken; got != want {
t.Errorf("Header.Get(Authorization); got %v, want %v", got, want)
}
if r.URL.Path == "/v2/auth" {
http.Redirect(w, r, "/redirect", http.StatusMovedPermanently)
return
}
if strings.Contains(r.URL.Path, "blobs") {
http.Redirect(w, r, blobServer.URL, http.StatusFound)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Errorf("Unexpected error during url.Parse: %v", err)
}
registry, err := name.NewRegistry(u.Host, name.WeakValidation)
if err != nil {
t.Errorf("Unexpected error during NewRegistry: %v", err)
}
client := http.Client{Transport: &bearerTransport{
inner: &http.Transport{},
bearer: authn.AuthConfig{RegistryToken: expectedToken},
registry: registry,
scheme: "http",
}}
_, err = client.Get(fmt.Sprintf("http://%s/v2/auth", u.Host))
if err != nil {
t.Errorf("Unexpected error during Get: %v", err)
}
_, err = client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Errorf("Unexpected error during Get: %v", err)
}
}
func TestBearerTransportTokenRefresh(t *testing.T) {
initialToken := "foo"
refreshedToken := "bar"
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hdr := r.Header.Get("Authorization")
if hdr == "Bearer "+refreshedToken {
w.WriteHeader(http.StatusOK)
return
}
if strings.HasPrefix(hdr, "Basic ") {
w.Write([]byte(fmt.Sprintf(`{"token": %q}`, refreshedToken)))
}
w.Header().Set("WWW-Authenticate", "scope=foo")
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
registry, err := name.NewRegistry(u.Host, name.WeakValidation)
if err != nil {
t.Fatalf("Unexpected error during NewRegistry: %v", err)
}
// Pass Username/Password
transport := &bearerTransport{
inner: http.DefaultTransport,
bearer: authn.AuthConfig{RegistryToken: initialToken},
basic: &authn.Basic{Username: "foo", Password: "bar"},
registry: registry,
realm: server.URL,
scheme: "http",
}
client := http.Client{Transport: transport}
res, err := client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Errorf("Unexpected error during client.Get: %v", err)
return
}
if res.StatusCode != http.StatusOK {
t.Errorf("client.Get final StatusCode got %v, want: %v", res.StatusCode, http.StatusOK)
}
if got, want := transport.bearer.RegistryToken, refreshedToken; got != want {
t.Errorf("Expected Bearer token to be refreshed, got %v, want %v", got, want)
}
// Pass RegistryToken directly
transport.bearer = authn.AuthConfig{RegistryToken: initialToken}
transport.basic = &authn.Bearer{Token: refreshedToken}
client = http.Client{Transport: transport}
res, err = client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Errorf("Unexpected error during client.Get: %v", err)
return
}
if res.StatusCode != http.StatusOK {
t.Errorf("client.Get final StatusCode got %v, want: %v", res.StatusCode, http.StatusOK)
}
if got, want := transport.bearer.RegistryToken, refreshedToken; got != want {
t.Errorf("Expected Bearer token to be refreshed, got %v, want %v", got, want)
}
}
func TestBearerTransportOauthRefresh(t *testing.T) {
initialToken := "foo"
accessToken := "bar"
refreshToken := "baz"
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
if err := r.ParseForm(); err != nil {
t.Fatal(err)
}
if it := r.FormValue("refresh_token"); it != initialToken {
t.Errorf("want %s got %s", initialToken, it)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`{"access_token": %q, "refresh_token": %q}`, accessToken, refreshToken)))
return
}
hdr := r.Header.Get("Authorization")
if hdr == "Bearer "+accessToken {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("WWW-Authenticate", "scope=foo")
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
registry, err := name.NewRegistry(u.Host, name.WeakValidation)
if err != nil {
t.Errorf("Unexpected error during NewRegistry: %v", err)
}
transport := &bearerTransport{
inner: http.DefaultTransport,
basic: authn.FromConfig(authn.AuthConfig{IdentityToken: initialToken}),
registry: registry,
realm: server.URL,
scheme: "http",
scopes: []string{"myscope"},
service: u.Host,
}
client := http.Client{Transport: transport}
res, err := client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Fatalf("Unexpected error during client.Get: %v", err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("client.Get final StatusCode got %v, want: %v", res.StatusCode, http.StatusOK)
}
if want, got := transport.bearer.RegistryToken, accessToken; want != got {
t.Errorf("Expected Bearer token to be refreshed, got %v, want %v", got, want)
}
basicAuthConfig, err := transport.basic.Authorization()
if err != nil {
t.Fatal(err)
}
if got, want := basicAuthConfig.IdentityToken, refreshToken; got != want {
t.Errorf("Expected Basic IdentityToken to be refreshed, got %v, want %v", got, want)
}
}
func TestBearerTransportOauth404Fallback(t *testing.T) {
basicAuth := "basic_auth"
identityToken := "identity_token"
accessToken := "access_token"
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusNotFound)
}
hdr := r.Header.Get("Authorization")
if hdr == "Basic "+basicAuth {
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf(`{"access_token": %q}`, accessToken)))
}
if hdr == "Bearer "+accessToken {
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("WWW-Authenticate", "scope=foo")
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
u, err := url.Parse(server.URL)
if err != nil {
t.Fatal(err)
}
registry, err := name.NewRegistry(u.Host, name.WeakValidation)
if err != nil {
t.Errorf("Unexpected error during NewRegistry: %v", err)
}
transport := &bearerTransport{
inner: http.DefaultTransport,
basic: authn.FromConfig(authn.AuthConfig{
IdentityToken: identityToken,
Auth: basicAuth,
}),
registry: registry,
realm: server.URL,
scheme: "http",
scopes: []string{"myscope"},
service: u.Host,
}
client := http.Client{Transport: transport}
res, err := client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Fatalf("Unexpected error during client.Get: %v", err)
}
if res.StatusCode != http.StatusOK {
t.Errorf("client.Get final StatusCode got %v, want: %v", res.StatusCode, http.StatusOK)
}
if got, want := transport.bearer.RegistryToken, accessToken; got != want {
t.Errorf("Expected Bearer token to be refreshed, got %v, want %v", got, want)
}
}
type recorder struct {
reqs []*http.Request
resp *http.Response
err error
}
func newRecorder(resp *http.Response, err error) *recorder {
return &recorder{
reqs: []*http.Request{},
resp: resp,
err: err,
}
}
func (r *recorder) RoundTrip(in *http.Request) (*http.Response, error) {
r.reqs = append(r.reqs, in)
return r.resp, r.err
}
func TestSchemeOverride(t *testing.T) {
// Record the requests we get in the inner transport.
cannedResponse := http.Response{
Status: http.StatusText(http.StatusOK),
StatusCode: http.StatusOK,
}
rec := newRecorder(&cannedResponse, nil)
registry, err := name.NewRegistry("example.com")
if err != nil {
t.Fatalf("Unexpected error during NewRegistry: %v", err)
}
st := &schemeTransport{
inner: rec,
registry: registry,
scheme: "http",
}
// We should see the scheme be overridden to "http" for the registry, but the
// scheme for the token server should be unchanged.
tests := []struct {
url string
wantScheme string
}{{
url: "https://example.com",
wantScheme: "http",
}, {
url: "https://token.example.com",
wantScheme: "https",
}}
for i, tt := range tests {
req, err := http.NewRequest("GET", tt.url, nil)
if err != nil {
t.Fatalf("Unexpected error during NewRequest: %v", err)
}
if _, err := st.RoundTrip(req); err != nil {
t.Fatalf("Unexpected error during RoundTrip: %v", err)
}
if got, want := rec.reqs[i].URL.Scheme, tt.wantScheme; got != want {
t.Errorf("Wrong scheme: wanted %v, got %v", want, got)
}
}
}
func TestCanonicalAddressResolution(t *testing.T) {
registry, err := name.NewRegistry("does-not-matter", name.WeakValidation)
if err != nil {
t.Errorf("Unexpected error during NewRegistry: %v", err)
}
tests := []struct {
registry name.Registry
scheme string
address string
want string
}{{
registry: registry,
scheme: "http",
address: "registry.example.com",
want: "registry.example.com:80",
}, {
registry: registry,
scheme: "http",
address: "registry.example.com:12345",
want: "registry.example.com:12345",
}, {
registry: registry,
scheme: "https",
address: "registry.example.com",
want: "registry.example.com:443",
}, {
registry: registry,
scheme: "https",
address: "registry.example.com:12345",
want: "registry.example.com:12345",
}, {
registry: registry,
scheme: "http",
address: "registry.example.com:",
want: "registry.example.com:80",
}, {
registry: registry,
scheme: "https",
address: "registry.example.com:",
want: "registry.example.com:443",
}, {
registry: registry,
scheme: "http",
address: "2001:db8::1",
want: "[2001:db8::1]:80",
}, {
registry: registry,
scheme: "https",
address: "2001:db8::1",
want: "[2001:db8::1]:443",
}, {
registry: registry,
scheme: "http",
address: "[2001:db8::1]:12345",
want: "[2001:db8::1]:12345",
}, {
registry: registry,
scheme: "https",
address: "[2001:db8::1]:12345",
want: "[2001:db8::1]:12345",
}, {
registry: registry,
scheme: "http",
address: "[2001:db8::1]:",
want: "[2001:db8::1]:80",
}, {
registry: registry,
scheme: "https",
address: "[2001:db8::1]:",
want: "[2001:db8::1]:443",
}, {
registry: registry,
scheme: "https",
address: "something:is::wrong]:",
want: "something:is::wrong]:",
}}
for _, tt := range tests {
got := canonicalAddress(tt.address, tt.scheme)
if got != tt.want {
t.Errorf("Wrong canonical host: wanted %v got %v", tt.want, got)
}
}
}
func TestInsufficientScope(t *testing.T) {
wrong := "the-wrong-scope"
right := "the-right-scope"
realm := ""
expectedService := "my-service.io"
passed := false
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
scopes := query["scope"]
switch {
case len(scopes) == 0:
if !passed {
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer realm=%q,scope=%q", realm, right))
w.WriteHeader(http.StatusUnauthorized)
}
case len(scopes) == 1:
w.Write([]byte(`{"token": "arbitrary-token"}`))
default:
passed = true
w.Write([]byte(`{"token": "arbitrary-token-2"}`))
}
}))
defer server.Close()
basic := &authn.Basic{Username: "foo", Password: "bar"}
u, err := url.Parse(server.URL)
if err != nil {
t.Error("Unexpected error during url.Parse: ", err)
}
realm = u.Host
registry, err := name.NewRegistry(expectedService, name.WeakValidation)
if err != nil {
t.Error("Unexpected error during NewRegistry: ", err)
}
bt := &bearerTransport{
inner: http.DefaultTransport,
basic: basic,
registry: registry,
realm: server.URL,
scopes: []string{wrong},
service: expectedService,
scheme: "http",
}
client := http.Client{Transport: bt}
res, err := client.Get(fmt.Sprintf("http://%s/v2/foo/bar/blobs/blah", u.Host))
if err != nil {
t.Error("Unexpected error during client.Get: ", err)
return
}
if res.StatusCode != http.StatusOK {
t.Errorf("client.Get final StatusCode got %v, want: %v", res.StatusCode, http.StatusOK)
}
if !passed {
t.Error("didn't refresh insufficient scope")
}
}