This repository has been archived by the owner on Jun 19, 2023. It is now read-only.
forked from geek-cookbook/traefik-forward-auth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain_test.go
320 lines (269 loc) · 9.4 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
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
package main
import (
"fmt"
"github.com/Klarrio/traefik-forward-auth/session"
"github.com/Klarrio/traefik-forward-auth/util"
oidc "github.com/Klarrio/traefik-forward-auth/wellknownopenidconfiguration"
"time"
// "reflect"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/dgrijalva/jwt-go"
)
/**
* Utilities
*/
func getJWT(t *testing.T, email string, roles string) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().Add(time.Duration(time.Second * 10)).Unix(),
"email": email,
"roles": roles,
})
tokenString, signError := token.SignedString([]byte("a-test-signing-key"))
if signError != nil {
t.Fatal("Could not sign the JWT token, reason:", signError)
}
return tokenString
}
type TokenValidUserServerHandler struct {
t *testing.T
}
func (t *TokenValidUserServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, fmt.Sprintf(`{"access_token":"%s"}`, getJWT(t.t, "[email protected]", "")))
}
type UserServerHandler struct{}
func (t *UserServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{
"id":"1",
"email":"[email protected]",
"verified_email":true,
"hd":"example.com"
}`)
}
func init() {
log = util.CreateLogger("panic", "")
}
func httpRequest(r *http.Request, c *http.Cookie) (*http.Response, string) {
w := httptest.NewRecorder()
// Set cookies on recorder
if c != nil {
http.SetCookie(w, c)
}
// Copy into request
for _, c := range w.HeaderMap["Set-Cookie"] {
r.Header.Add("Cookie", c)
}
handler(w, r)
res := w.Result()
body, _ := ioutil.ReadAll(res.Body)
return res, string(body)
}
func newHTTPRequest(uri string) *http.Request {
r := httptest.NewRequest("", "http://example.com", nil)
r.Header.Add("X-Forwarded-Uri", uri)
return r
}
/**
* Tests
*/
func TestHandler(t *testing.T) {
oidcApi = oidc.NewWellKnownOpenIDConfiguration(
log,
&oidc.OIDCClientCredentials{
ClientID: "idtest",
ClientSecret: "sectest",
},
"scopetest",
"prompttest")
oidcApi.AuthorizationEndpoint = "http://test.com/auth"
oidcApi.TokenEndpoint = "http://test.com/token"
oidcApi.UserInfoEndpoint = "http://test.com/user"
oidcApi.EndSessionEndpoint = "http://test.com/logout"
oidcApi.Resolve()
sessionInventory = session.NewInventory(oidcApi, false, log)
fw = &ForwardAuth{
Path: "_oauth",
CookieName: "cookie_test",
Lifetime: time.Second * time.Duration(10),
tokenMinValidity: time.Second * 2,
AccessTokenRolesField: "roles",
AccessTokenRolesDelimiter: " ",
}
// Should redirect vanilla request to login url
req := newHTTPRequest("foo")
res, _ := httpRequest(req, nil)
if res.StatusCode != 307 {
t.Error("Vanilla request should be redirected with 307, got:", res.StatusCode)
}
fwd, _ := res.Location()
if fwd.Scheme != "http" || fwd.Host != "test.com" || fwd.Path != "/auth" {
t.Error("Vanilla request should be redirected to login URL, got:", fwd)
}
// Should handle invalid cookie
req = newHTTPRequest("foo")
c := fw.MakeSessionAuthCookie(req, "non-existing-secret-key")
parts := strings.Split(c.Value, "|")
c.Value = fmt.Sprintf("bad|%s|%s", parts[1], parts[2])
res, _ = httpRequest(req, c)
if res.StatusCode != 401 {
t.Error("Request with invalid cookie should not be authorized, got:", res.StatusCode)
}
// Should handle non existing secret key
req = newHTTPRequest("foo")
c = fw.MakeSessionAuthCookie(req, "non-existing-secret-key")
res, _ = httpRequest(req, c)
if res.StatusCode != 307 {
t.Error("Request with non existing secret key should be redirected to auth, got:", res.StatusCode)
}
// Configure the token in the stateMap
secureKey, err := getSecureKey()
if err != nil {
t.Error("Expected the secret key to generate but got", err)
}
pseudoAccessToken := getJWT(t, "[email protected]", "account:read orders:read")
pseudoToken := &oidc.Token{
AccessToken: pseudoAccessToken,
TokenType: "access_token",
RefreshToken: "",
ExpiresIn: 10000,
IDToken: "",
}
sessionInventory.StoreSession(secureKey, pseudoToken, time.Now().Local().Add(time.Second*60))
// Should validate email
req = newHTTPRequest("foo")
c = fw.MakeSessionAuthCookie(req, secureKey)
fw.Domain = []string{"test.com"}
res, _ = httpRequest(req, c)
if res.StatusCode != 401 {
t.Error("Request with an email for unauthorized domain should shouldn't be authorised", res.StatusCode)
}
// Should deny requests where the OIDC access token does not contain one of the roles in
// the X-Forward-Auth-Accepted-Roles header
req = newHTTPRequest("foo")
req.Header.Add("X-Forward-Auth-Accepted-Roles", "account:write,orders:write")
c = fw.MakeSessionAuthCookie(req, secureKey)
fw.Domain = []string{}
res, _ = httpRequest(req, c)
if res.StatusCode != 401 {
t.Error("sessions with only read roles in the access token should not be allowed to endpoints which require write access. got: ", res.StatusCode)
}
// Should allow requests where the OIDC access token contains one or more of the roles in
// the X-Forward-Auth-Accepted-Roles header
req = newHTTPRequest("foo")
req.Header.Add("X-Forward-Auth-Accepted-Roles", "account:read,orders:write")
c = fw.MakeSessionAuthCookie(req, secureKey)
fw.Domain = []string{}
res, _ = httpRequest(req, c)
if res.StatusCode != 200 {
t.Error("sessions with one of the accepted roles in their access token should get access to the endpoint. got: ", res.StatusCode)
}
// Should allow valid request email
req = newHTTPRequest("foo")
c = fw.MakeSessionAuthCookie(req, secureKey)
fw.Domain = []string{}
res, _ = httpRequest(req, c)
if res.StatusCode != 200 {
t.Error("Valid request should be allowed, got:", res.StatusCode)
}
// Should pass through user
bearerTokens := res.Header["X-Forwarded-Access-Token"]
if len(bearerTokens) != 1 {
t.Error("Valid request missing X-Forwarded-Access-Token header")
} else if bearerTokens[0] != pseudoAccessToken {
t.Error("X-Forwarded-Access-Token should match test token, got:", bearerTokens[0])
}
// Validate that tokens expire
shortLivedSecureKey, err := getSecureKey()
if err != nil {
t.Error("Expected the secret key to generate but got", err)
}
sessionInventory.StoreSession(shortLivedSecureKey, pseudoToken, time.Now().Local().Add(time.Second))
req = newHTTPRequest("foo")
c = fw.MakeSessionAuthCookie(req, shortLivedSecureKey)
fw.Domain = []string{}
res, _ = httpRequest(req, c)
if res.StatusCode != 200 {
t.Error("Valid request should be allowed before key expiry, got:", res.StatusCode)
}
<-time.After(time.Duration(time.Second * 2))
req = newHTTPRequest("foo")
c = fw.MakeSessionAuthCookie(req, shortLivedSecureKey)
fw.Domain = []string{}
res, _ = httpRequest(req, c)
if res.StatusCode != 307 {
t.Error("Valid request should be disallowed and redirected to the authentication when key expired, got:", res.StatusCode)
}
// logout should redirect to login page
req = newHTTPRequest("logout")
res, _ = httpRequest(req, nil)
if res.StatusCode != 307 {
t.Error("Vanilla request should be redirected with 307, got:", res.StatusCode)
}
fwd, _ = res.Location()
if fwd.Scheme != "http" || fwd.Host != "test.com" || fwd.Path != "/auth" {
t.Error("Vanilla request should be redirected to login URL, got:", fwd)
}
}
func TestCallback(t *testing.T) {
oidcApi = oidc.NewWellKnownOpenIDConfiguration(
log,
&oidc.OIDCClientCredentials{
ClientID: "idtest",
ClientSecret: "sectest",
},
"scopetest",
"prompttest")
oidcApi.AuthorizationEndpoint = "http://test.com/auth"
oidcApi.TokenEndpoint = "http://test.com/token"
oidcApi.UserInfoEndpoint = "http://test.com/user"
oidcApi.Resolve()
sessionInventory = session.NewInventory(oidcApi, false, log)
fw = &ForwardAuth{
Path: "_oauth",
CSRFCookieName: "csrf_test",
}
// Setup valid user token server
tokenValidUserServerHandler := &TokenValidUserServerHandler{
t: t,
}
tokenValidUserServer := httptest.NewServer(tokenValidUserServerHandler)
defer tokenValidUserServer.Close()
tokenValidUserURL, _ := url.Parse(tokenValidUserServer.URL)
// Setup user server
userServerHandler := &UserServerHandler{}
userServer := httptest.NewServer(userServerHandler)
defer userServer.Close()
userURL, _ := url.Parse(userServer.URL)
oidcApi.UserInfoEndpoint = userURL.String()
oidcApi.Resolve()
// Should pass auth response request to callback
req := newHTTPRequest("_oauth")
res, _ := httpRequest(req, nil)
if res.StatusCode != 401 {
t.Error("Auth callback without cookie shouldn't be authorised, got:", res.StatusCode)
}
// Should catch invalid csrf cookie
req = newHTTPRequest("_oauth?state=12345678901234567890123456789012:http://redirect")
c := fw.MakeCSRFCookie(req, "nononononononononononononononono")
res, _ = httpRequest(req, c)
if res.StatusCode != 401 {
t.Error("Auth callback with invalid cookie shouldn't be authorised, got:", res.StatusCode)
}
// Should redirect valid request
oidcApi.TokenEndpoint = tokenValidUserURL.String()
oidcApi.Resolve()
req = newHTTPRequest("_oauth?state=12345678901234567890123456789012:http://redirect")
c = fw.MakeCSRFCookie(req, "12345678901234567890123456789012")
res, _ = httpRequest(req, c)
if res.StatusCode != 307 {
t.Error("Valid callback should be allowed, got:", res.StatusCode)
}
fwd, _ := res.Location()
if fwd.Scheme != "http" || fwd.Host != "redirect" || fwd.Path != "" {
t.Error("Valid request should be redirected to return url, got:", fwd)
}
}