-
Notifications
You must be signed in to change notification settings - Fork 0
/
session_test.go
307 lines (274 loc) · 8.25 KB
/
session_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
package pasetosession_test
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/lpar/blammo/log"
"github.com/o1egl/paseto"
flag "github.com/spf13/pflag"
"github.com/lpar/pasetosession"
)
const testIssuer = "testIssuer"
const testAudience = "testAudience"
const testSubject = "[email protected]"
const testEmail = "[email protected]"
const testName = "John Q. Smith Esq."
const testCookieName = "TestSessionCookie"
const testLifespan = time.Minute
var debug = flag.Bool("debug", false, "turn on debug logging")
var sessMgr = pasetosession.NewSessionManager("chunkybacon", testLifespan)
func TestMain(m *testing.M) {
sessMgr.Issuer = testIssuer
sessMgr.Audience = testAudience
sessMgr.CookieName = testCookieName
ds := os.Getenv("DEBUG")
if ds == "true" || ds == "1" || *debug {
log.SetDebug(true)
}
os.Exit(m.Run())
}
func TestToken(t *testing.T) {
s, strtok, err := makeTestData(t)
if err != nil {
t.Fatalf("failed to create test data")
}
ntok, err := s.DecodeToken(strtok, false)
verifyOutcome(ntok, err, t)
_, err = s.DecodeToken(strtok, false)
if err == nil {
t.Errorf("duplicate token decode allowed")
} else {
log.Debug().Err(err).Msg("duplicate decode attempted")
}
}
func TestTokenReuse(t *testing.T) {
s, strtok, err := makeTestData(t)
if err != nil {
t.Fatalf("failed to create test data")
}
ntok, err := s.DecodeToken(strtok, true)
verifyOutcome(ntok, err, t)
_, err = s.DecodeToken(strtok, false)
if err != nil {
t.Errorf("token reuse was not allowed")
}
verifyOutcome(ntok, err, t)
}
func makeTestData(t *testing.T) (*pasetosession.SessionManager, string, error) {
s := pasetosession.NewSessionManager("chunky bacon", 1*time.Minute)
s.Audience = testAudience
s.Issuer = testIssuer
tok := &paseto.JSONToken{}
tok.Set("name", testName)
tok.Set("email", testEmail)
strtok, err := s.EncodeToken(testSubject, tok)
if err != nil {
t.Errorf("failed to encode token: %v", err)
}
if strtok == "" {
t.Errorf("failed to encode token, empty string returned: %v", err)
}
if tok.Audience != "" || tok.Subject != "" || tok.Issuer != "" {
t.Errorf("call to EncodeToken mutated token argument")
}
log.Debug().Str("token", strtok).Msg("encoded token")
return s, strtok, err
}
func verifyOutcome(ntok *paseto.JSONToken, err error, t *testing.T) {
log.Debug().Str("audience", ntok.Audience).Str("issuer", ntok.Issuer).Str("subject", ntok.Subject).Msg("decoded token")
if err != nil {
t.Errorf("failed to decode token: %v", err)
}
if ntok.Audience != testAudience {
t.Errorf("audience corrupted, expected %s got %s", testAudience, ntok.Audience)
}
if ntok.Issuer != testIssuer {
t.Errorf("issuer corrupted, expected %s got %s", testIssuer, ntok.Issuer)
}
if ntok.Subject != testSubject {
t.Errorf("subject corrupted, expected %s got %s", testSubject, ntok.Subject)
}
if ntok.Get("name") != testName {
t.Errorf("name corrupted, expected %s got %s", testName, ntok.Get("name"))
}
if ntok.Get("email") != testEmail {
t.Errorf("email corrupted, expected %s got %s", testEmail, ntok.Get("email"))
}
}
func TestSessionKeys(t *testing.T) {
s1 := pasetosession.NewSessionManager("passphrase #1", 1*time.Minute)
s2 := pasetosession.NewSessionManager("passphrase #2", 1*time.Minute)
tok1, err := s1.EncodeToken("[email protected]")
if err != nil {
t.Errorf("failed to encode subject-only token")
}
tok2, err := s2.DecodeToken(tok1, false)
if err == nil {
t.Errorf("tokens were passed between session managers with different secret keys")
}
if tok2 != nil && tok2.Subject != "" {
t.Errorf("unexpected token subject output from erroneous decode: %s", tok2.Subject)
}
}
func TestSessionTimeout(t *testing.T) {
s := pasetosession.NewSessionManager("passphrase #1", 1*time.Second)
tok1, err := s.EncodeToken("[email protected]")
if err != nil {
t.Errorf("failed to encode subject-only token")
}
tok2, err := s.EncodeToken("[email protected]")
if err != nil {
t.Errorf("failed to encode subject-only token")
}
toko, err := s.DecodeToken(tok1, false)
if err != nil {
t.Fatalf("failed to decode subject-only token inside expiry limit")
}
if toko.Subject != "[email protected]" {
t.Errorf("token timeout test decode fail")
}
time.Sleep(2 * time.Second)
toko, err = s.DecodeToken(tok2, false)
if err == nil {
t.Errorf("managed to decode subject-only token outside expiry limit")
}
}
// Get a test cookie, then run it through refresh
func TestCookieIssueAndRefresh(t *testing.T) {
c := getTestCookie(t)
req, err := http.NewRequest("GET", "/baz", nil)
if err != nil {
t.Fatal(err)
}
req.AddCookie(c)
w := httptest.NewRecorder()
hndl := sessMgr.Refresh(okHandler(t, true))
hndl.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected http response using cookie: %d", resp.StatusCode)
}
ctok, err := getCookie(resp, testCookieName)
if err != nil {
t.Fatalf("no refreshed cookie issued")
}
if ctok.Value == c.Value {
t.Error("same cookie issued on refresh")
}
verifyTestCookie(t, ctok)
}
func TestAuthSuccess(t *testing.T) {
c := getTestCookie(t)
req, err := http.NewRequest("GET", "/protected", nil)
if err != nil {
t.Fatal(err)
}
req.AddCookie(c)
w := httptest.NewRecorder()
hndl := sessMgr.Authenticate(okHandler(t, true))
hndl.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected auth rejection using valid cookie: %d", resp.StatusCode)
}
}
func TestAuthFail(t *testing.T) {
req, err := http.NewRequest("GET", "/protected", nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
hndl := sessMgr.Authenticate(okHandler(t, false))
hndl.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode == http.StatusOK {
t.Fatalf("unexpected auth success using no cookie: %d", resp.StatusCode)
}
}
func TestLogout(t *testing.T) {
c := getTestCookie(t)
req, err := http.NewRequest("GET", "/protected", nil)
if err != nil {
t.Fatal(err)
}
req.AddCookie(c)
w := httptest.NewRecorder()
// Context should be found while we're processing the logout, it just kills the cookie afterwards
hndl := sessMgr.Logout(okHandler(t, false))
hndl.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected auth rejection using valid cookie: %d", resp.StatusCode)
}
ctok, err := getCookie(resp, testCookieName)
if err != nil {
t.Fatalf("failed to get cookie: %v", err)
}
if ctok.Value != "" {
t.Error("logout failed, cookie survived")
}
}
// Run a test request through the test cookie issuing handler,
// return a debug cookie.
func getTestCookie(t *testing.T) *http.Cookie {
req, err := http.NewRequest("GET", "/foo/bar", nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
hndl := http.HandlerFunc(testCookieIssuer)
hndl.ServeHTTP(w, req)
resp := w.Result()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected http response issuing cookie: %d", resp.StatusCode)
}
ctok, err := getCookie(resp, testCookieName)
if err != nil {
t.Error("no cookie issued")
}
verifyTestCookie(t, ctok)
return ctok
}
func getCookie(r *http.Response, name string) (*http.Cookie, error) {
cookies := r.Cookies()
for _, c := range cookies {
if c.Name == name {
return c, nil
}
}
return nil, fmt.Errorf("no cookie %s found", name)
}
func testCookieIssuer(w http.ResponseWriter, r *http.Request) {
sessMgr.TokenToCookie(w, testSubject)
fmt.Fprintln(w, "OK")
}
func okHandler(t *testing.T, requirecontext bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Debug().Msgf("checking for context on request %+v", r)
tok, ok := pasetosession.GetToken(r)
if requirecontext != ok {
t.Errorf("context presence mismatch, expected=%v, found=%v", requirecontext, ok)
} else {
log.Debug().Msgf("context = %+v", tok)
}
fmt.Fprintln(w, "OK")
}
}
func verifyTestCookie(t *testing.T, ctok *http.Cookie) {
if ctok.Path != "/" {
t.Errorf("Wrong cookie path, expected / got %s", ctok.Path)
}
exp := ctok.Expires
expexp := time.Now().Add(testLifespan)
durd := expexp.Sub(exp)
if durd > time.Second {
t.Errorf("Cookie lifetime incorrect, expected %v got %v", expexp.UTC(), exp.UTC())
}
if !ctok.HttpOnly {
t.Error("Cookie not marked as HttpOnly (XSS vulnerability)")
}
log.Debug().Msg("cookie verified")
}