-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
281 lines (255 loc) · 7.01 KB
/
main_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
package proxy
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
func Test_AuthProxy(t *testing.T) {
const managementAPI = "http://management_api.example.com"
const tokenPath = "/auth/token" // #nosec G101 this is not a hardcoded credential
cookieName := "_test"
tokenSecret := []byte("secret")
authURLs := AuthSites{"site1": "site1.example.com", "site2": "site2.example.com"}
validTime := time.Now().AddDate(0, 0, 1)
expiredTime := time.Now().AddDate(0, 0, -1)
proxy := Proxy{
CookieName: cookieName,
Secret: tokenSecret,
Sites: authURLs,
DefaultSite: "default.example.com",
log: zap.L(),
ManagementAPI: managementAPI,
TokenPath: tokenPath,
TokenParam: "token",
}
token1 := makeTestJWT(tokenSecret, "site1", validTime)
token2 := makeTestJWT(tokenSecret, "site2", validTime.Add(time.Minute))
ptr := func(s string) *string { return &s }
tests := []struct {
name string
url string
cookie *http.Cookie
wantErr string
wantRedirectURL *string
wantUpstream *string
}{
{
name: "no token -- redirect to API",
url: "/",
cookie: nil,
wantRedirectURL: ptr(managementAPI + tokenPath + "?returnTo=%2F"),
},
{
name: "expired cookie -- redirect to API",
url: "/",
cookie: makeTestJWTCookie(cookieName, makeTestJWT(tokenSecret, "site1", expiredTime)),
wantRedirectURL: ptr(managementAPI + tokenPath + "?returnTo=%2F"),
},
{
name: "default site",
url: "/",
cookie: makeTestJWTCookie(cookieName, makeTestJWT(tokenSecret, "default", validTime)),
wantUpstream: ptr("default.example.com"),
},
{
name: "query valid -- redirect to set cookie",
url: "/?token=" + token1,
wantRedirectURL: ptr("/?cf=1&token=" + token1),
},
{
name: "query valid with flag but no cookie -- use query token",
url: "/?cf=1&token=" + token1,
wantUpstream: ptr(authURLs["site1"]),
},
{
name: "cookie valid",
url: "/",
cookie: makeTestJWTCookie(cookieName, token1),
wantUpstream: ptr(authURLs["site1"]),
},
{
name: "query and cookie valid and same -- redirect without query token",
url: "/?token=" + token1,
cookie: makeTestJWTCookie(cookieName, token1),
wantRedirectURL: ptr("/"),
},
{
name: "query and cookie valid but different -- redirect to set cookie",
url: "/?token=" + token1,
cookie: makeTestJWTCookie(cookieName, token2),
wantRedirectURL: ptr("/?cf=1&token=" + token1),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, tc.url, nil)
if tc.cookie != nil {
r.AddCookie(tc.cookie)
}
ctx := context.WithValue(r.Context(), caddy.CtxKey("vars"), map[string]any{})
r = r.WithContext(ctx)
var w httptest.ResponseRecorder
err := proxy.handleRequest(&w, r)
if tc.wantErr != "" {
assert.ErrorContains(t, err, tc.wantErr)
return
}
assert.Nil(t, err)
if tc.wantUpstream != nil {
assert.Equal(t, *tc.wantUpstream, caddyhttp.GetVar(r.Context(), CaddyVarUpstream))
}
if tc.wantRedirectURL != nil {
assert.Equal(t, *tc.wantRedirectURL, caddyhttp.GetVar(r.Context(), CaddyVarRedirectURL))
}
})
}
}
func Test_getTokenFromCookie(t *testing.T) {
const cookieName = "cookie"
secret := []byte("secret")
const tokenParam = "token"
proxy := Proxy{
CookieName: cookieName,
log: zap.L(),
Secret: secret,
TokenParam: tokenParam,
}
testJWT := makeTestJWT(secret, "good", time.Now().AddDate(0, 0, 1))
tests := []struct {
name string
cookie *http.Cookie
query string
want string
}{
{
name: "no token",
want: "",
},
{
name: "token in cookie",
cookie: makeTestJWTCookie(cookieName, testJWT),
want: testJWT,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
if tc.cookie != nil {
r.AddCookie(tc.cookie)
}
ctx := context.WithValue(r.Context(), caddy.CtxKey("vars"), map[string]any{})
r = r.WithContext(ctx)
r.URL.RawQuery = tc.query
token := proxy.getTokenFromCookie(r)
assert.Equal(t, tc.want, token, "wrong token in test %q", tc.name)
})
}
}
func Test_getTokenFromQueryString(t *testing.T) {
secret := []byte("secret")
const tokenParam = "token"
proxy := Proxy{
log: zap.L(),
Secret: secret,
TokenParam: tokenParam,
}
tests := []struct {
name string
query string
want string
}{
{
name: "no token",
want: "",
},
{
name: "token in URL param",
query: tokenParam + "=abc123",
want: "abc123",
},
{
name: "token and returnTo in URL params",
query: tokenParam + "=abc123&returnTo=https%3A%2F%2Fexample.com%2Fpath",
want: "abc123",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
ctx := context.WithValue(r.Context(), caddy.CtxKey("vars"), map[string]any{})
r = r.WithContext(ctx)
r.URL.RawQuery = tc.query
token := proxy.getTokenFromQueryString(r)
assert.Equal(t, tc.want, token)
})
}
}
func makeTestJWTCookie(name, token string) *http.Cookie {
return &http.Cookie{
Name: name,
Value: token,
}
}
func makeTestJWT(secret []byte, level string, expires time.Time) string {
claim := ProxyClaim{
Level: level,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expires),
IssuedAt: jwt.NewNumericDate(expires.AddDate(0, 0, -1)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenString, _ := token.SignedString(secret)
return tokenString
}
func TestProxy_isTrustedBot(t *testing.T) {
tests := []struct {
name string
trusted []string
userAgent string
want bool
}{
{
name: "empty user agent",
trusted: []string{"googlebot"},
userAgent: "",
want: false,
},
{
name: "empty trusted list",
trusted: nil,
userAgent: "Googlebot/2.1 (+http://www.googlebot.com/bot.html)",
want: false,
},
{
name: "not in trusted list",
trusted: []string{"googlebot"},
userAgent: "duckduckgo",
want: false,
},
{
name: "in trusted list",
trusted: []string{"duckduckgo", "googlebot"},
userAgent: "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
proxy := Proxy{
TrustedBots: tt.trusted,
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.Header.Set("User-Agent", tt.userAgent)
assert.Equalf(t, tt.want, proxy.isTrustedBot(r), "user agent '%s', trusted %+v",
r.Header.Get("User-Agent"), tt.trusted)
})
}
}