-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_test.go
118 lines (113 loc) · 2.56 KB
/
token_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
package main
import (
"encoding/json"
"net/http"
"strings"
"testing"
)
func TestTokenMarshalToJSON(t *testing.T) {
b, err := json.Marshal(Token{"x", "x", "x"})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
str := string(b)
for _, substr := range []string{`"timestamp"`, `"fingerprint"`, `"secret"`} {
if !strings.Contains(str, substr) {
t.Errorf("Failed to find in marshalled JSON: str %q, substr %q", str, substr)
}
}
}
func TestNewToken(t *testing.T) {
token := NewToken("mysecret")
if len(token.Fingerprint) == 0 {
t.Error(`Field "Fingerprint" must be set.`)
}
if len(token.Secret) == 0 {
t.Error(`Field "Secret" must be set.`)
}
if len(token.Timestamp) == 0 {
t.Error(`Field "Timestamp" must be set.`)
}
}
func TestExtractToken(t *testing.T) {
for _, tc := range []struct {
name string
headers http.Header
tokenHeaderNames []string
fallbackToken string
expectedSecret string
expectedError bool
}{{
name: "1_case_sensitive",
headers: http.Header{
"Baz": {"c"},
"Token": {"d"},
},
tokenHeaderNames: []string{"foo", "bar", "baz"},
fallbackToken: "",
expectedSecret: "",
expectedError: true,
}, {
name: "2_token_header_empty",
headers: http.Header{
"Baz": {"c"},
"token": {"d"},
"Token": {},
},
tokenHeaderNames: []string{"Token"},
fallbackToken: "",
expectedSecret: "",
expectedError: true,
}, {
name: "3_header_order",
headers: http.Header{
"A": {"a"},
"C": {"c"},
"B": {"b"},
},
tokenHeaderNames: []string{"X", "B", "C"},
fallbackToken: "",
expectedSecret: "b",
expectedError: false,
}, {
name: "4_fallback",
headers: http.Header{
"x": {"a"},
"y": {},
"z": {"c"},
},
tokenHeaderNames: []string{"X", "Y", "Z"},
fallbackToken: "Foobar",
expectedSecret: "Foobar",
expectedError: false,
}, {
name: "BearerToken",
headers: http.Header{
"x": {"a"},
"y": {},
"z": {"Bearer secret"},
},
tokenHeaderNames: []string{"z"},
fallbackToken: "",
expectedSecret: "secret",
expectedError: false,
}} {
t.Run(tc.name, func(t *testing.T) {
token, err := ExtractToken(
tc.headers, tc.tokenHeaderNames, tc.fallbackToken,
)
if tc.expectedError && err == nil {
t.Errorf("Unexpected success: got %q, want error", token)
}
if !tc.expectedError && err != nil {
t.Errorf("Unexpected error: %v", err)
}
if tc.expectedSecret != token.Secret {
t.Errorf(
"Wrong secret extracted: got %q, want %q",
token.Secret, tc.expectedSecret,
)
}
})
}
}