Debian Codegraph @

lfsapi/auth_test.go

raw symbols SCIP
1 package lfsapi
2
3 import (
4 "encoding/base64"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "sync/atomic"
11 "testing"
12
13 "github.com/git-lfs/git-lfs/v3/creds"
14 "github.com/git-lfs/git-lfs/v3/errors"
15 "github.com/git-lfs/git-lfs/v3/git"
16 "github.com/git-lfs/git-lfs/v3/lfshttp"
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19 )
20
21 type authRequest struct {
22 Test string
23 }
24
25 func TestAuthenticateHeaderAccess(t *testing.T) {
26 tests := map[string]creds.AccessMode{
27 "": creds.BasicAccess,
28 "basic 123": creds.BasicAccess,
29 "basic": creds.BasicAccess,
30 "unknown": creds.BasicAccess,
31 "NEGOTIATE": creds.NegotiateAccess,
32 "negotiate": creds.NegotiateAccess,
33 "NEGOTIATE 1 2 3": creds.NegotiateAccess,
34 "negotiate 1 2 3": creds.NegotiateAccess,
35 }
36
37 for _, key := range authenticateHeaders {
38 for value, expected := range tests {
39 res := &http.Response{Header: make(http.Header)}
40 res.Header.Set(key, value)
41 t.Logf("%s: %s", key, value)
42 result, _, _ := getAuthAccess(res, creds.NoneAccess, creds.AllAccessModes(), false)
43 assert.Equal(t, expected, result)
44 }
45 }
46 }
47
48 func TestDualAccessModes(t *testing.T) {
49 res := &http.Response{Header: make(http.Header)}
50 res.Header["Www-Authenticate"] = []string{"Negotiate 123", "Basic 456"}
51 access, next, _ := getAuthAccess(res, creds.NoneAccess, creds.AllAccessModes(), false)
52 assert.Equal(t, creds.NegotiateAccess, access)
53 access, next, _ = getAuthAccess(res, access, next, false)
54 assert.Equal(t, creds.BasicAccess, access)
55 access, _, _ = getAuthAccess(res, access, next, false)
56 assert.Equal(t, creds.BasicAccess, access)
57 }
58
59 func TestDoWithAuthApprove(t *testing.T) {
60 var called uint32
61
62 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
63 atomic.AddUint32(&called, 1)
64 assert.Equal(t, "POST", req.Method)
65
66 body := &authRequest{}
67 err := json.NewDecoder(req.Body).Decode(body)
68 assert.Nil(t, err)
69 assert.Equal(t, "Approve", body.Test)
70
71 w.Header().Set("Lfs-Authenticate", "Basic")
72 actual := req.Header.Get("Authorization")
73 if len(actual) == 0 {
74 w.WriteHeader(http.StatusUnauthorized)
75 return
76 }
77
78 expected := "Basic " + strings.TrimSpace(
79 base64.StdEncoding.EncodeToString([]byte("user:pass")),
80 )
81 assert.Equal(t, expected, actual)
82 }))
83 defer srv.Close()
84
85 cred := newMockCredentialHelper()
86 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
87 nil, map[string]string{
88 "lfs.url": srv.URL + "/repo/lfs",
89 },
90 ))
91 c.Credentials = cred
92
93 access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
94 assert.Equal(t, creds.NoneAccess, access.Mode())
95
96 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
97 require.Nil(t, err)
98
99 err = MarshalToRequest(req, &authRequest{Test: "Approve"})
100 require.Nil(t, err)
101
102 res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
103 require.Nil(t, err)
104
105 assert.Equal(t, http.StatusOK, res.StatusCode)
106 assert.True(t, cred.IsApproved(creds.Creds(map[string][]string{
107 "username": []string{"user"},
108 "password": []string{"pass"},
109 "protocol": []string{"http"},
110 "host": []string{srv.Listener.Addr().String()},
111 })))
112 access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
113 assert.Equal(t, creds.BasicAccess, access.Mode())
114 assert.EqualValues(t, 2, called)
115 }
116
117 func TestDoWithAuthReject(t *testing.T) {
118 var called uint32
119
120 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
121 atomic.AddUint32(&called, 1)
122 assert.Equal(t, "POST", req.Method)
123
124 body := &authRequest{}
125 err := json.NewDecoder(req.Body).Decode(body)
126 assert.Nil(t, err)
127 assert.Equal(t, "Reject", body.Test)
128
129 actual := req.Header.Get("Authorization")
130 expected := "Basic " + strings.TrimSpace(
131 base64.StdEncoding.EncodeToString([]byte("user:pass")),
132 )
133
134 w.Header().Set("Lfs-Authenticate", "Basic")
135 if actual != expected {
136 // Write http.StatusUnauthorized to force the credential
137 // helper to reject the credentials
138 w.WriteHeader(http.StatusUnauthorized)
139 } else {
140 w.WriteHeader(http.StatusOK)
141 }
142 }))
143 defer srv.Close()
144
145 invalidCreds := creds.Creds(map[string][]string{
146 "username": []string{"user"},
147 "password": []string{"wrong_pass"},
148 "path": []string{""},
149 "protocol": []string{"http"},
150 "host": []string{srv.Listener.Addr().String()},
151 })
152
153 cred := newMockCredentialHelper()
154 cred.Approve(invalidCreds)
155 assert.True(t, cred.IsApproved(invalidCreds))
156
157 c := NewClient(nil)
158 c.Credentials = cred
159 c.Endpoints = NewEndpointFinder(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
160 nil, map[string]string{
161 "lfs.url": srv.URL,
162 },
163 ))
164
165 req, err := http.NewRequest("POST", srv.URL, nil)
166 require.Nil(t, err)
167
168 err = MarshalToRequest(req, &authRequest{Test: "Reject"})
169 require.Nil(t, err)
170
171 res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL), req)
172 require.Nil(t, err)
173
174 assert.Equal(t, http.StatusOK, res.StatusCode)
175 assert.False(t, cred.IsApproved(invalidCreds))
176 assert.True(t, cred.IsApproved(creds.Creds(map[string][]string{
177 "username": []string{"user"},
178 "password": []string{"pass"},
179 "path": []string{""},
180 "protocol": []string{"http"},
181 "host": []string{srv.Listener.Addr().String()},
182 })))
183 assert.EqualValues(t, 3, called)
184 }
185
186 func TestDoWithAuthNoRetry(t *testing.T) {
187 var called uint32
188
189 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
190 atomic.AddUint32(&called, 1)
191 assert.Equal(t, "POST", req.Method)
192
193 body := &authRequest{}
194 err := json.NewDecoder(req.Body).Decode(body)
195 assert.Nil(t, err)
196 assert.Equal(t, "Approve", body.Test)
197
198 w.Header().Set("Lfs-Authenticate", "Basic")
199 actual := req.Header.Get("Authorization")
200 if len(actual) == 0 {
201 w.WriteHeader(http.StatusUnauthorized)
202 return
203 }
204
205 expected := "Basic " + strings.TrimSpace(
206 base64.StdEncoding.EncodeToString([]byte("user:pass")),
207 )
208 assert.Equal(t, expected, actual)
209 }))
210 defer srv.Close()
211
212 cred := newMockCredentialHelper()
213 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
214 nil, map[string]string{
215 "lfs.url": srv.URL + "/repo/lfs",
216 },
217 ))
218 c.Credentials = cred
219
220 access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
221 assert.Equal(t, creds.NoneAccess, access.Mode())
222
223 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
224 require.Nil(t, err)
225
226 err = MarshalToRequest(req, &authRequest{Test: "Approve"})
227 require.Nil(t, err)
228
229 res, err := c.DoWithAuthNoRetry("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
230 access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
231 assert.True(t, errors.IsAuthError(err))
232 assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
233 assert.Equal(t, creds.BasicAccess, access.Mode())
234 assert.EqualValues(t, 1, called)
235 }
236
237 func TestDoWithAuthRetryLimitExceeded(t *testing.T) {
238 var called uint32
239
240 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
241 atomic.AddUint32(&called, 1)
242 assert.Equal(t, "POST", req.Method)
243
244 body := &authRequest{}
245 err := json.NewDecoder(req.Body).Decode(body)
246 assert.Nil(t, err)
247 assert.Equal(t, "Reject", body.Test)
248
249 w.Header().Set("Lfs-Authenticate", "Basic")
250 w.WriteHeader(http.StatusUnauthorized)
251 }))
252 defer srv.Close()
253
254 cred := newMockCredentialHelper()
255 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
256 nil, map[string]string{
257 "lfs.url": srv.URL + "/repo/lfs",
258 },
259 ))
260 c.Credentials = cred
261
262 access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
263 assert.Equal(t, creds.NoneAccess, access.Mode())
264
265 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
266 require.Nil(t, err)
267
268 err = MarshalToRequest(req, &authRequest{Test: "Reject"})
269 require.Nil(t, err)
270
271 res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
272 require.Error(t, err)
273 assert.EqualError(t, err, "too many authentication attempts")
274 require.Nil(t, res)
275
276 access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
277 assert.Equal(t, creds.BasicAccess, access.Mode())
278 assert.EqualValues(t, defaultMaxAuthAttempts+1, called)
279 }
280
281 func TestDoWithAuthNoRetryOn401WhenAuthHeaderPresent(t *testing.T) {
282 var called uint32
283
284 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
285 atomic.AddUint32(&called, 1)
286 w.WriteHeader(http.StatusUnauthorized)
287 }))
288 defer srv.Close()
289
290 cred := newMockCredentialHelper()
291 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
292 nil, map[string]string{
293 "lfs.url": srv.URL + "/repo/lfs",
294 },
295 ))
296 c.Credentials = cred
297
298 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
299 require.Nil(t, err)
300
301 // We set the Authorization header explicitly so as to exercise the
302 // check for an extant Authorization header in DoWithAuth().
303 //
304 // Otherwise an Authorization header will be added automatically for
305 // each request attempt subsequent to the first, since the server
306 // always returns 401, but the header will then be removed by
307 // doWithAuth() when it receives another 401, so DoWithAuth() will
308 // never find an extant Authorization header in any requests.
309 req.Header.Set("Authorization", basicAuth("user", "pass"))
310 err = MarshalToRequest(req, &authRequest{Test: "Reject"})
311 require.Nil(t, err)
312
313 res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
314 require.Error(t, err)
315 assert.True(t, errors.IsAuthError(err))
316 assert.NotNil(t, res)
317 assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
318 assert.EqualValues(t, 1, called)
319 }
320
321 func TestDoWithAuthMultistageRetryLimitExceeded(t *testing.T) {
322 var called uint32
323
324 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
325 atomic.AddUint32(&called, 1)
326 w.Header().Set("Www-Authenticate", "Multistage type=foo")
327 w.WriteHeader(http.StatusUnauthorized)
328 }))
329 defer srv.Close()
330
331 cred := newNonAdvancingMultistageHelper()
332 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
333 nil, map[string]string{
334 "lfs.url": srv.URL + "/repo/lfs",
335 },
336 ))
337 c.Credentials = cred
338
339 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
340 require.Nil(t, err)
341
342 err = MarshalToRequest(req, &authRequest{Test: "Reject"})
343 require.Nil(t, err)
344
345 res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
346 require.Error(t, err)
347 assert.EqualError(t, err, "too many authentication attempts")
348 assert.Nil(t, res)
349
350 access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
351 assert.Equal(t, creds.BasicAccess, access.Mode())
352 assert.EqualValues(t, defaultMaxAuthAttempts+1, called)
353 }
354
355 type nonAdvancingMultistageHelper struct{}
356
357 func newNonAdvancingMultistageHelper() *nonAdvancingMultistageHelper {
358 return &nonAdvancingMultistageHelper{}
359 }
360
361 func (nonAdvancingMultistageHelper) Fill(input creds.Creds) (creds.Creds, error) {
362 out := make(creds.Creds)
363 for k, v := range input {
364 out[k] = v
365 }
366 out["authtype"] = []string{"Multistage"}
367 out["credential"] = []string{"cred1"}
368 out["state[]"] = []string{"lfstest:state1"}
369 return out, nil
370 }
371 func (nonAdvancingMultistageHelper) Approve(creds.Creds) error { return nil }
372 func (nonAdvancingMultistageHelper) Reject(creds.Creds) error { return nil }
373
374 func TestDoAPIRequestWithAuth(t *testing.T) {
375 var called uint32
376
377 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
378 atomic.AddUint32(&called, 1)
379 assert.Equal(t, "POST", req.Method)
380
381 body := &authRequest{}
382 err := json.NewDecoder(req.Body).Decode(body)
383 assert.Nil(t, err)
384 assert.Equal(t, "Approve", body.Test)
385
386 w.Header().Set("Lfs-Authenticate", "Basic")
387 actual := req.Header.Get("Authorization")
388 if len(actual) == 0 {
389 w.WriteHeader(http.StatusUnauthorized)
390 return
391 }
392
393 expected := "Basic " + strings.TrimSpace(
394 base64.StdEncoding.EncodeToString([]byte("user:pass")),
395 )
396 assert.Equal(t, expected, actual)
397 }))
398 defer srv.Close()
399
400 cred := newMockCredentialHelper()
401 c := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
402 nil, map[string]string{
403 "lfs.url": srv.URL + "/repo/lfs",
404 },
405 ))
406 c.Credentials = cred
407
408 access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
409 assert.Equal(t, creds.NoneAccess, access.Mode())
410
411 req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
412 require.Nil(t, err)
413
414 err = MarshalToRequest(req, &authRequest{Test: "Approve"})
415 require.Nil(t, err)
416
417 res, err := c.DoAPIRequestWithAuth("", req)
418 require.Nil(t, err)
419
420 assert.Equal(t, http.StatusOK, res.StatusCode)
421 assert.True(t, cred.IsApproved(creds.Creds(map[string][]string{
422 "username": []string{"user"},
423 "password": []string{"pass"},
424 "protocol": []string{"http"},
425 "host": []string{srv.Listener.Addr().String()},
426 })))
427 access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
428 assert.Equal(t, creds.BasicAccess, access.Mode())
429 assert.EqualValues(t, 2, called)
430 }
431
432 type mockCredentialHelper struct {
433 Approved map[string]creds.Creds
434 }
435
436 func newMockCredentialHelper() *mockCredentialHelper {
437 return &mockCredentialHelper{
438 Approved: make(map[string]creds.Creds),
439 }
440 }
441
442 func (m *mockCredentialHelper) Fill(input creds.Creds) (creds.Creds, error) {
443 if found, ok := m.Approved[credsToKey(input)]; ok {
444 return found, nil
445 }
446
447 output := make(creds.Creds)
448 for key, value := range input {
449 output[key] = value
450 }
451 if _, ok := output["username"]; !ok {
452 output["username"] = []string{"user"}
453 }
454 output["password"] = []string{"pass"}
455 return output, nil
456 }
457
458 func (m *mockCredentialHelper) Approve(creds creds.Creds) error {
459 m.Approved[credsToKey(creds)] = creds
460 return nil
461 }
462
463 func (m *mockCredentialHelper) Reject(creds creds.Creds) error {
464 delete(m.Approved, credsToKey(creds))
465 return nil
466 }
467
468 func (m *mockCredentialHelper) IsApproved(creds creds.Creds) bool {
469 if found, ok := m.Approved[credsToKey(creds)]; ok {
470 if len(found["password"]) == 1 && len(creds["password"]) == 1 {
471 return found["password"][0] == creds["password"][0]
472 } else {
473 return len(found["password"]) == 0 && len(creds["password"]) == 0
474 }
475 }
476 return false
477 }
478
479 func credsToKey(creds creds.Creds) string {
480 var kvs []string
481 for _, k := range []string{"protocol", "host", "path"} {
482 value := ""
483 if v, ok := creds[k]; ok && len(v) == 1 {
484 value = v[0]
485 }
486 kvs = append(kvs, fmt.Sprintf("%s:%s", k, value))
487 }
488
489 return strings.Join(kvs, " ")
490 }
491
492 func basicAuth(user, pass string) string {
493 value := fmt.Sprintf("%s:%s", user, pass)
494 return fmt.Sprintf("Basic %s", strings.TrimSpace(base64.StdEncoding.EncodeToString([]byte(value))))
495 }
496
497 type getCredsExpected struct {
498 Access creds.AccessMode
499 Creds creds.Creds
500 CredsURL string
501 Authorization string
502 }
503
504 type getCredsTest struct {
505 Remote string
506 Method string
507 Href string
508 Endpoint string
509 Header map[string]string
510 Config map[string]string
511 Expected getCredsExpected
512 }
513
514 func TestGetCreds(t *testing.T) {
515 tests := map[string]getCredsTest{
516 "no access": getCredsTest{
517 Remote: "origin",
518 Method: "GET",
519 Href: "https://git-server.com/repo/lfs/locks",
520 Endpoint: "https://git-server.com/repo/lfs",
521 Config: map[string]string{
522 "lfs.url": "https://git-server.com/repo/lfs",
523 },
524 Expected: getCredsExpected{
525 Access: creds.NoneAccess,
526 },
527 },
528 "basic access": getCredsTest{
529 Remote: "origin",
530 Method: "GET",
531 Href: "https://git-server.com/repo/lfs/locks",
532 Endpoint: "https://git-server.com/repo/lfs",
533 Config: map[string]string{
534 "lfs.url": "https://git-server.com/repo/lfs",
535 "lfs.https://git-server.com/repo/lfs.access": "basic",
536 },
537 Expected: getCredsExpected{
538 Access: creds.BasicAccess,
539 Authorization: basicAuth("git-server.com", "monkey"),
540 CredsURL: "https://git-server.com/repo/lfs",
541 Creds: map[string][]string{
542 "protocol": []string{"https"},
543 "host": []string{"git-server.com"},
544 "username": []string{"git-server.com"},
545 "password": []string{"monkey"},
546 },
547 },
548 },
549 "basic access with usehttppath": getCredsTest{
550 Remote: "origin",
551 Method: "GET",
552 Href: "https://git-server.com/repo/lfs/locks",
553 Endpoint: "https://git-server.com/repo/lfs",
554 Config: map[string]string{
555 "lfs.url": "https://git-server.com/repo/lfs",
556 "lfs.https://git-server.com/repo/lfs.access": "basic",
557 "credential.usehttppath": "true",
558 },
559 Expected: getCredsExpected{
560 Access: creds.BasicAccess,
561 Authorization: basicAuth("git-server.com", "monkey"),
562 CredsURL: "https://git-server.com/repo/lfs",
563 Creds: map[string][]string{
564 "protocol": []string{"https"},
565 "host": []string{"git-server.com"},
566 "username": []string{"git-server.com"},
567 "password": []string{"monkey"},
568 "path": []string{"repo/lfs"},
569 },
570 },
571 },
572 "basic access with url-specific usehttppath": getCredsTest{
573 Remote: "origin",
574 Method: "GET",
575 Href: "https://git-server.com/repo/lfs/locks",
576 Endpoint: "https://git-server.com/repo/lfs",
577 Config: map[string]string{
578 "lfs.url": "https://git-server.com/repo/lfs",
579 "lfs.https://git-server.com/repo/lfs.access": "basic",
580 "credential.https://git-server.com.usehttppath": "true",
581 },
582 Expected: getCredsExpected{
583 Access: creds.BasicAccess,
584 Authorization: basicAuth("git-server.com", "monkey"),
585 CredsURL: "https://git-server.com/repo/lfs",
586 Creds: map[string][]string{
587 "protocol": []string{"https"},
588 "host": []string{"git-server.com"},
589 "username": []string{"git-server.com"},
590 "password": []string{"monkey"},
591 "path": []string{"repo/lfs"},
592 },
593 },
594 },
595 "custom auth": getCredsTest{
596 Remote: "origin",
597 Method: "GET",
598 Href: "https://git-server.com/repo/lfs/locks",
599 Endpoint: "https://git-server.com/repo/lfs",
600 Header: map[string]string{
601 "Authorization": "custom",
602 },
603 Config: map[string]string{
604 "lfs.url": "https://git-server.com/repo/lfs",
605 "lfs.https://git-server.com/repo/lfs.access": "basic",
606 },
607 Expected: getCredsExpected{
608 Access: creds.BasicAccess,
609 Authorization: "custom",
610 },
611 },
612 "username in url": getCredsTest{
613 Remote: "origin",
614 Method: "GET",
615 Href: "https://git-server.com/repo/lfs/locks",
616 Endpoint: "https://git-server.com/repo/lfs",
617 Config: map[string]string{
618 "lfs.url": "https://[email protected]/repo/lfs",
619 "lfs.https://git-server.com/repo/lfs.access": "basic",
620 },
621 Expected: getCredsExpected{
622 Access: creds.BasicAccess,
623 Authorization: basicAuth("user", "monkey"),
624 CredsURL: "https://[email protected]/repo/lfs",
625 Creds: map[string][]string{
626 "protocol": []string{"https"},
627 "host": []string{"git-server.com"},
628 "username": []string{"user"},
629 "password": []string{"monkey"},
630 },
631 },
632 },
633 "different remote url, basic access": getCredsTest{
634 Remote: "origin",
635 Method: "GET",
636 Href: "https://git-server.com/repo/lfs/locks",
637 Endpoint: "https://git-server.com/repo/lfs",
638 Config: map[string]string{
639 "lfs.url": "https://git-server.com/repo/lfs",
640 "lfs.https://git-server.com/repo/lfs.access": "basic",
641 "remote.origin.url": "https://git-server.com/repo",
642 },
643 Expected: getCredsExpected{
644 Access: creds.BasicAccess,
645 Authorization: basicAuth("git-server.com", "monkey"),
646 CredsURL: "https://git-server.com/repo",
647 Creds: map[string][]string{
648 "protocol": []string{"https"},
649 "host": []string{"git-server.com"},
650 "username": []string{"git-server.com"},
651 "password": []string{"monkey"},
652 },
653 },
654 },
655 "api url auth": getCredsTest{
656 Remote: "origin",
657 Method: "GET",
658 Href: "https://git-server.com/repo/locks",
659 Endpoint: "https://git-server.com/repo",
660 Config: map[string]string{
661 "lfs.url": "https://user:[email protected]/repo",
662 "lfs.https://git-server.com/repo.access": "basic",
663 },
664 Expected: getCredsExpected{
665 Access: creds.BasicAccess,
666 Authorization: basicAuth("user", "pass"),
667 },
668 },
669 "git url auth": getCredsTest{
670 Remote: "origin",
671 Method: "GET",
672 Href: "https://git-server.com/repo/locks",
673 Endpoint: "https://git-server.com/repo",
674 Config: map[string]string{
675 "lfs.url": "https://git-server.com/repo",
676 "lfs.https://git-server.com/repo.access": "basic",
677 "remote.origin.url": "https://user:[email protected]/repo",
678 },
679 Expected: getCredsExpected{
680 Access: creds.BasicAccess,
681 Authorization: basicAuth("user", "pass"),
682 },
683 },
684 "scheme mismatch": getCredsTest{
685 Remote: "origin",
686 Method: "GET",
687 Href: "http://git-server.com/repo/lfs/locks",
688 Endpoint: "https://git-server.com/repo/lfs",
689 Config: map[string]string{
690 "lfs.url": "https://git-server.com/repo/lfs",
691 "lfs.https://git-server.com/repo/lfs.access": "basic",
692 },
693 Expected: getCredsExpected{
694 Access: creds.BasicAccess,
695 Authorization: basicAuth("git-server.com", "monkey"),
696 CredsURL: "http://git-server.com/repo/lfs/locks",
697 Creds: map[string][]string{
698 "protocol": []string{"http"},
699 "host": []string{"git-server.com"},
700 "username": []string{"git-server.com"},
701 "password": []string{"monkey"},
702 },
703 },
704 },
705 "host mismatch": getCredsTest{
706 Remote: "origin",
707 Method: "GET",
708 Href: "https://lfs-server.com/repo/lfs/locks",
709 Endpoint: "https://git-server.com/repo/lfs",
710 Config: map[string]string{
711 "lfs.url": "https://git-server.com/repo/lfs",
712 "lfs.https://git-server.com/repo/lfs.access": "basic",
713 },
714 Expected: getCredsExpected{
715 Access: creds.BasicAccess,
716 Authorization: basicAuth("lfs-server.com", "monkey"),
717 CredsURL: "https://lfs-server.com/repo/lfs/locks",
718 Creds: map[string][]string{
719 "protocol": []string{"https"},
720 "host": []string{"lfs-server.com"},
721 "username": []string{"lfs-server.com"},
722 "password": []string{"monkey"},
723 },
724 },
725 },
726 "port mismatch": getCredsTest{
727 Remote: "origin",
728 Method: "GET",
729 Href: "https://git-server.com:8080/repo/lfs/locks",
730 Endpoint: "https://git-server.com/repo/lfs",
731 Config: map[string]string{
732 "lfs.url": "https://git-server.com/repo/lfs",
733 "lfs.https://git-server.com/repo/lfs.access": "basic",
734 },
735 Expected: getCredsExpected{
736 Access: creds.BasicAccess,
737 Authorization: basicAuth("git-server.com:8080", "monkey"),
738 CredsURL: "https://git-server.com:8080/repo/lfs/locks",
739 Creds: map[string][]string{
740 "protocol": []string{"https"},
741 "host": []string{"git-server.com:8080"},
742 "username": []string{"git-server.com:8080"},
743 "password": []string{"monkey"},
744 },
745 },
746 },
747 "bare ssh URI": getCredsTest{
748 Remote: "origin",
749 Method: "POST",
750 Href: "https://git-server.com/repo/lfs/objects/batch",
751 Endpoint: "https://git-server.com/repo/lfs",
752 Config: map[string]string{
753 "lfs.url": "https://git-server.com/repo/lfs",
754 "lfs.https://git-server.com/repo/lfs.access": "basic",
755
756 "remote.origin.url": "[email protected]:repo.git",
757 },
758 Expected: getCredsExpected{
759 Access: creds.BasicAccess,
760 Authorization: basicAuth("git-server.com", "monkey"),
761 CredsURL: "https://git-server.com/repo/lfs",
762 Creds: map[string][]string{
763 "host": []string{"git-server.com"},
764 "password": []string{"monkey"},
765 "protocol": []string{"https"},
766 "username": []string{"git-server.com"},
767 },
768 },
769 },
770 }
771
772 for desc, test := range tests {
773 t.Log(desc)
774 req, err := http.NewRequest(test.Method, test.Href, nil)
775 if err != nil {
776 t.Errorf("[%s] %s", desc, err)
777 continue
778 }
779
780 for key, value := range test.Header {
781 req.Header.Set(key, value)
782 }
783
784 ctx := lfshttp.NewContext(git.NewReadOnlyConfig("", ""), nil, test.Config)
785 client := NewClient(ctx)
786 client.Credentials = &fakeCredentialFiller{}
787 client.Endpoints = NewEndpointFinder(ctx)
788 credWrapper, err := client.getCreds(test.Remote, client.Endpoints.AccessFor(test.Endpoint), req)
789 if !assert.Nil(t, err) {
790 continue
791 }
792
793 assert.Equal(t, test.Expected.Authorization, req.Header.Get("Authorization"), "authorization")
794
795 if test.Expected.Creds != nil {
796 assert.EqualValues(t, test.Expected.Creds, credWrapper.Creds)
797 } else {
798 assert.Nil(t, credWrapper.Creds, "creds")
799 }
800
801 if len(test.Expected.CredsURL) > 0 {
802 if assert.NotNil(t, credWrapper.Url, "credURL") {
803 assert.Equal(t, test.Expected.CredsURL, credWrapper.Url.String(), "credURL")
804 }
805 } else {
806 assert.Nil(t, credWrapper.Url)
807 }
808 }
809 }
810
811 type fakeCredentialFiller struct{}
812
813 func (f *fakeCredentialFiller) Fill(input creds.Creds) (creds.Creds, error) {
814 output := make(creds.Creds)
815 for key, value := range input {
816 output[key] = value
817 }
818 if _, ok := output["username"]; !ok {
819 output["username"] = input["host"]
820 }
821 output["password"] = []string{"monkey"}
822 return output, nil
823 }
824
825 func (f *fakeCredentialFiller) Approve(creds creds.Creds) error {
826 return errors.New("Not implemented")
827 }
828
829 func (f *fakeCredentialFiller) Reject(creds creds.Creds) error {
830 return errors.New("Not implemented")
831 }
832
833 func TestClientRedirectReauthenticate(t *testing.T) {
834 var srv1, srv2 *httptest.Server
835 var called1, called2 uint32
836 var creds1, creds2 creds.Creds
837
838 srv1 = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
839 atomic.AddUint32(&called1, 1)
840
841 if hdr := r.Header.Get("Authorization"); len(hdr) > 0 {
842 parts := strings.SplitN(hdr, " ", 2)
843 typ, b64 := parts[0], parts[1]
844
845 auth, err := base64.URLEncoding.DecodeString(b64)
846 assert.Nil(t, err)
847 assert.Equal(t, "Basic", typ)
848 assert.Equal(t, "user1:pass1", string(auth))
849
850 http.Redirect(w, r, srv2.URL+r.URL.Path, http.StatusMovedPermanently)
851 return
852 }
853 w.WriteHeader(http.StatusUnauthorized)
854 }))
855
856 srv2 = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
857 atomic.AddUint32(&called2, 1)
858
859 parts := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
860 typ, b64 := parts[0], parts[1]
861
862 auth, err := base64.URLEncoding.DecodeString(b64)
863 assert.Nil(t, err)
864 assert.Equal(t, "Basic", typ)
865 assert.Equal(t, "user2:pass2", string(auth))
866 }))
867
868 // Change the URL of srv2 to make it appears as if it is a different
869 // host.
870 srv2.URL = strings.Replace(srv2.URL, "127.0.0.1", "0.0.0.0", 1)
871
872 creds1 = creds.Creds(map[string][]string{
873 "protocol": []string{"http"},
874 "host": []string{strings.TrimPrefix(srv1.URL, "http://")},
875
876 "username": []string{"user1"},
877 "password": []string{"pass1"},
878 })
879 creds2 = creds.Creds(map[string][]string{
880 "protocol": []string{"http"},
881 "host": []string{strings.TrimPrefix(srv2.URL, "http://")},
882
883 "username": []string{"user2"},
884 "password": []string{"pass2"},
885 })
886
887 defer srv1.Close()
888 defer srv2.Close()
889
890 c := NewClient(lfshttp.NewContext(nil, nil, nil))
891 cred := creds.NewCredentialCacher()
892 cred.Approve(creds1)
893 cred.Approve(creds2)
894 c.Credentials = cred
895
896 req, err := http.NewRequest("GET", srv1.URL, nil)
897 require.Nil(t, err)
898
899 _, err = c.DoAPIRequestWithAuth("", req)
900 assert.Nil(t, err)
901
902 // called1 is 2 since LFS tries an unauthenticated request first
903 assert.EqualValues(t, 2, called1)
904 assert.EqualValues(t, 1, called2)
905 }