Skip to content

Commit 6d6ca8f

Browse files
committed
Refactor & clean up CheckAuth tests.
1 parent afd1023 commit 6d6ca8f

File tree

1 file changed

+43
-24
lines changed

1 file changed

+43
-24
lines changed

basic_test.go

Lines changed: 43 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,61 @@
11
package auth
22

33
import (
4-
"encoding/base64"
54
"fmt"
65
"net/http"
76
"testing"
87
)
98

10-
func TestAuthBasic(t *testing.T) {
9+
var basicSecrets = map[string]string{
10+
"test": "{SHA}qvTGHdzF6KLavt4PO0gs2a6pQ00=",
11+
"test2": "$apr1$a0j62R97$mYqFkloXH0/UOaUnAiV2b0",
12+
"test16": "$apr1$JI4wh3am$AmhephVqLTUyAVpFQeHZC0",
13+
"test3": "$2y$05$ih3C91zUBSTFcAh2mQnZYuob0UOZVEf16wl/ukgjDhjvj.xgM1WwS",
14+
}
15+
16+
func basicProvider(user, realm string) string {
17+
return basicSecrets[user]
18+
}
19+
20+
func TestBasicCheckAuthFailsOnBadHeaders(t *testing.T) {
1121
t.Parallel()
12-
secrets := HtpasswdFileProvider("test.htpasswd")
13-
a := &BasicAuth{Realm: "example.com", Secrets: secrets}
14-
r := &http.Request{}
15-
r.Method = "GET"
16-
if a.CheckAuth(r) != "" {
17-
t.Fatal("CheckAuth passed on empty headers")
18-
}
19-
r.Header = http.Header(make(map[string][]string))
20-
r.Header.Set("Authorization", "Digest blabla ololo")
21-
if a.CheckAuth(r) != "" {
22-
t.Fatal("CheckAuth passed on bad headers")
23-
}
24-
r.Header.Set("Authorization", "Basic !@#")
25-
if a.CheckAuth(r) != "" {
26-
t.Fatal("CheckAuth passed on bad base64 data")
22+
a := &BasicAuth{Realm: "example.com", Secrets: basicProvider}
23+
for _, auth := range []string{
24+
"",
25+
"Digest blabla ololo",
26+
"Basic !@#",
27+
} {
28+
r, err := http.NewRequest("GET", "http://example.com", nil)
29+
if err != nil {
30+
t.Fatal(err)
31+
}
32+
if auth != "" {
33+
r.Header.Set("Authorization", auth)
34+
}
35+
if a.CheckAuth(r) != "" {
36+
t.Errorf("CheckAuth returned a username for Authorization header %q", r.Header.Get("Authorization"))
37+
}
2738
}
39+
}
2840

29-
data := [][]string{
41+
func TestBasicCheckAuth(t *testing.T) {
42+
t.Parallel()
43+
a := &BasicAuth{Realm: "example.com", Secrets: basicProvider}
44+
for _, tt := range []struct {
45+
username, password string
46+
}{
3047
{"test", "hello"},
3148
{"test2", "hello2"},
3249
{"test3", "hello3"},
3350
{"test16", "topsecret"},
34-
}
35-
for _, tc := range data {
36-
auth := base64.StdEncoding.EncodeToString([]byte(tc[0] + ":" + tc[1]))
37-
r.Header.Set("Authorization", "Basic "+auth)
38-
if a.CheckAuth(r) != tc[0] {
39-
t.Fatalf("CheckAuth failed for user '%s'", tc[0])
51+
} {
52+
r, err := http.NewRequest("GET", "http://example.com", nil)
53+
if err != nil {
54+
t.Fatal(err)
55+
}
56+
r.SetBasicAuth(tt.username, tt.password)
57+
if a.CheckAuth(r) != tt.username {
58+
t.Fatalf("CheckAuth failed for user '%s'", tt.username)
4059
}
4160
}
4261
}

0 commit comments

Comments
 (0)