-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
session_test.go
829 lines (795 loc) · 23.4 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
package sessions
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"sync"
"testing"
"time"
)
const sessionID = "01234567890123456789----"
// Reset the global parameters.
func reset() {
Persistence = ExtendablePersistenceLayer{}
SessionExpiry = math.MaxInt64
SessionIDExpiry = time.Hour
SessionIDGracePeriod = 5 * time.Minute
AcceptRemoteIP = 1
SessionCookie = "sessionid"
NewSessionCookie = func() *http.Cookie {
return &http.Cookie{
Expires: time.Now().Add(10 * 365 * 24 * time.Hour),
MaxAge: 10 * 365 * 24 * 60 * 60,
HttpOnly: true,
}
}
sessions.sessions = make(map[string]*Session)
}
// Test the gob-part for sessions, including Base64 encoding, without logged-in
// user.
func TestSessionGob(t *testing.T) {
// Initialize session.
data := map[string]interface{}{
"field": "value",
"42": 13,
"true": false,
}
date, _ := time.Parse("2006-01-02", "2017-06-27")
session := &Session{
user: nil,
referenceID: "ABCD",
created: date,
lastAccess: date,
lastIP: "192.168.178.1:80",
data: data,
}
// Serialize to Base64.
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
if err := encoder.Encode(session); err != nil {
t.Error(err)
}
s := base64.StdEncoding.EncodeToString(buffer.Bytes())
t.Logf("Serialized session: %s (length: %d)", s, len(s))
// Deserialize.
d, err := base64.StdEncoding.DecodeString(s)
if err != nil {
t.Error(err)
}
r := bytes.NewReader(d)
decoder := gob.NewDecoder(r)
var recoveredSession Session
if err := decoder.Decode(&recoveredSession); err != nil {
t.Error(err)
}
// Compare sessions.
if !recoveredSession.created.Equal(session.created) {
t.Errorf("Recovered session has different creation time (%s) than expected (%s)", recoveredSession.created, session.created)
}
if !recoveredSession.lastAccess.Equal(session.lastAccess) {
t.Errorf("Recovered session has different last access time (%s) than expected (%s)", recoveredSession.lastAccess, session.lastAccess)
}
if recoveredSession.referenceID != session.referenceID {
t.Errorf("Recovered session has different reference ID (%s) than expected (%s)", recoveredSession.referenceID, session.referenceID)
}
if recoveredSession.User() != nil {
t.Errorf("Recovered session has a user (%v) instead of nil", recoveredSession.user)
}
if len(recoveredSession.data) != len(session.data) {
t.Errorf("Recovered session data has different size (%d) than expected (%d)", len(recoveredSession.data), len(session.data))
}
for field, value := range data {
recoveredValue, ok := recoveredSession.data[field]
if !ok {
t.Errorf("Field %s not in recovered session data", field)
continue
}
if recoveredValue != value {
t.Errorf("Value %s for field %s not as expected (%s)", recoveredValue, field, value)
}
}
}
// Test the JSON-part for sessions, without logged-in user.
func TestSessionJSON(t *testing.T) {
// Initialize session.
data := map[string]interface{}{
"field": "value",
"42": nil,
"true": false,
}
date, _ := time.Parse("2006-01-02", "2017-06-27")
session := &Session{
user: nil,
referenceID: "ABCD",
created: date,
lastAccess: date,
lastIP: "192.168.178.1:80",
lastUserAgentHash: 12345,
data: data,
}
// Serialize to JSON.
j, err := json.Marshal(session)
if err != nil {
t.Error(err)
}
t.Logf("JSON session: %s", j)
// Unserialize.
recoveredSession := &Session{}
if err := json.Unmarshal(j, recoveredSession); err != nil {
t.Error(err)
}
// Compare sessions.
if !recoveredSession.created.Equal(session.created) {
t.Errorf("Recovered session has different creation time (%s) than expected (%s)", recoveredSession.created, session.created)
}
if !recoveredSession.lastAccess.Equal(session.lastAccess) {
t.Errorf("Recovered session has different last access time (%s) than expected (%s)", recoveredSession.lastAccess, session.lastAccess)
}
if recoveredSession.referenceID != session.referenceID {
t.Errorf("Recovered session has different reference ID (%s) than expected (%s)", recoveredSession.referenceID, session.referenceID)
}
if recoveredSession.lastIP != session.lastIP {
t.Errorf("Recovered session has different IP (%s) than expected (%s)", recoveredSession.lastIP, session.lastIP)
}
if recoveredSession.lastUserAgentHash != session.lastUserAgentHash {
t.Errorf("Recovered session has different user agent hash (%d) than expected (%d)", recoveredSession.lastUserAgentHash, session.lastUserAgentHash)
}
if recoveredSession.User() != nil {
t.Errorf("Recovered session has a user (%v) instead of nil", recoveredSession.user)
}
if len(recoveredSession.data) != len(session.data) {
t.Errorf("Recovered session data has different size (%d) than expected (%d)", len(recoveredSession.data), len(session.data))
}
for field, value := range data {
recoveredValue, ok := recoveredSession.data[field]
if !ok {
t.Errorf("Field %s not in recovered session data", field)
continue
}
if recoveredValue != value {
t.Errorf("Value %s for field %s not as expected (%s)", recoveredValue, field, value)
}
}
}
// Test the gob-part for sessions, including Base64 encoding, with a logged-in
// user.
func TestSessionGobWithUser(t *testing.T) {
// Initialize session.
user := &TestUser{ID: "12345"}
data := map[string]interface{}{
"field": "value",
"42": 13,
"true": false,
}
date, _ := time.Parse("2006-01-02", "2017-06-27")
session := &Session{
user: user,
referenceID: "ABCD",
created: date,
lastAccess: date,
lastIP: "192.168.178.1:80",
data: data,
}
Persistence = ExtendablePersistenceLayer{
LoadUserFunc: func(id interface{}) (User, error) {
if id != "12345" {
return nil, fmt.Errorf("Requested invalid user ID: %s", id)
}
return user, nil
},
}
// Serialize to Base64.
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
if err := encoder.Encode(session); err != nil {
t.Error(err)
}
s := base64.StdEncoding.EncodeToString(buffer.Bytes())
t.Logf("Serialized session: %s (length: %d)", s, len(s))
// Deserialize.
d, err := base64.StdEncoding.DecodeString(s)
if err != nil {
t.Error(err)
}
r := bytes.NewReader(d)
decoder := gob.NewDecoder(r)
var recoveredSession Session
if err := decoder.Decode(&recoveredSession); err != nil {
t.Error(err)
}
// Compare sessions.
if !recoveredSession.created.Equal(session.created) {
t.Errorf("Recovered session has different creation time (%s) than expected (%s)", recoveredSession.created, session.created)
}
if !recoveredSession.lastAccess.Equal(session.lastAccess) {
t.Errorf("Recovered session has different last access time (%s) than expected (%s)", recoveredSession.lastAccess, session.lastAccess)
}
if recoveredSession.referenceID != session.referenceID {
t.Errorf("Recovered session has different reference ID (%s) than expected (%s)", recoveredSession.referenceID, session.referenceID)
}
if recoveredSession.lastIP != session.lastIP {
t.Errorf("Recovered session has different IP (%s) than expected (%s)", recoveredSession.lastIP, session.lastIP)
}
if recoveredSession.lastUserAgentHash != session.lastUserAgentHash {
t.Errorf("Recovered session has different user agent hash (%d) than expected (%d)", recoveredSession.lastUserAgentHash, session.lastUserAgentHash)
}
if recoveredSession.User() != session.User() {
t.Errorf("Recovered session has different user (%v) than expected (%v)", recoveredSession.user, session.user)
}
if len(recoveredSession.data) != len(session.data) {
t.Errorf("Recovered session data has different size (%d) than expected (%d)", len(recoveredSession.data), len(session.data))
}
for field, value := range data {
recoveredValue, ok := recoveredSession.data[field]
if !ok {
t.Errorf("Field %s not in recovered session data", field)
continue
}
if recoveredValue != value {
t.Errorf("Value %s for field %s not as expected (%s)", recoveredValue, field, value)
}
}
}
// Test the JSON-part for sessions, with a logged-in user.
func TestSessionJSONWithUser(t *testing.T) {
// Initialize session.
user := &TestUser{ID: "12345"}
data := map[string]interface{}{
"field": "value",
"42": nil,
"true": false,
}
date, _ := time.Parse("2006-01-02", "2017-06-27")
session := &Session{
user: user,
referenceID: "ABCD",
created: date,
lastAccess: date,
lastIP: "192.168.178.1:80",
data: data,
}
Persistence = ExtendablePersistenceLayer{
LoadUserFunc: func(id interface{}) (User, error) {
if id != "12345" {
return nil, fmt.Errorf("Requested invalid user ID: %s", id)
}
return user, nil
},
}
// Serialize to JSON.
j, err := json.Marshal(session)
if err != nil {
t.Error(err)
}
t.Logf("JSON session: %s", j)
// Unserialize.
recoveredSession := &Session{}
if err := json.Unmarshal(j, recoveredSession); err != nil {
t.Error(err)
}
// Compare sessions.
if !recoveredSession.created.Equal(session.created) {
t.Errorf("Recovered session has different creation time (%s) than expected (%s)", recoveredSession.created, session.created)
}
if !recoveredSession.lastAccess.Equal(session.lastAccess) {
t.Errorf("Recovered session has different last access time (%s) than expected (%s)", recoveredSession.lastAccess, session.lastAccess)
}
if recoveredSession.referenceID != session.referenceID {
t.Errorf("Recovered session has different reference ID (%s) than expected (%s)", recoveredSession.referenceID, session.referenceID)
}
if recoveredSession.User() != session.User() {
t.Errorf("Recovered session has different user (%v) than expected (%v)", recoveredSession.user, session.user)
}
if len(recoveredSession.data) != len(session.data) {
t.Errorf("Recovered session data has different size (%d) than expected (%d)", len(recoveredSession.data), len(session.data))
}
for field, value := range data {
recoveredValue, ok := recoveredSession.data[field]
if !ok {
t.Errorf("Field %s not in recovered session data", field)
continue
}
if recoveredValue != value {
t.Errorf("Value %s for field %s not as expected (%s)", recoveredValue, field, value)
}
}
}
// Session start returns no session.
func TestNoSession(t *testing.T) {
req := httptest.NewRequest("", "/", nil)
session, err := Start(nil, req, false)
if err != nil {
t.Error(err)
}
if session != nil {
t.Error("Expected nil session, received non-empty session")
}
}
// Session start returns no session because it doesn't exist.
func TestNonExistingSession(t *testing.T) {
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
}
if session != nil {
t.Error("Expected nil session, received non-empty session")
}
if !strings.Contains(res.Header().Get("Set-Cookie"), fmt.Sprintf("%s=deleted", SessionCookie)) {
t.Error("Cookie was not deleted")
}
}
// Session start returns anonymous session.
func TestAnonSession(t *testing.T) {
defer reset()
NewSessionCookie = func() *http.Cookie {
return &http.Cookie{
Expires: time.Now(),
MaxAge: 10,
HttpOnly: true,
}
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, true)
if err != nil {
t.Error(err)
}
if session == nil {
t.Error("Expected session, received nil")
return
}
if len(sessions.sessions) != 1 {
t.Error("Cache is not size 1")
}
cookie := regexp.MustCompile("^" + SessionCookie + "=[0-9a-zA-Z=+/]{24}")
t.Log(res.Header())
header := res.Header()
cookies := header["Set-Cookie"]
lastCookie := cookies[len(cookies)-1]
if !cookie.MatchString(lastCookie) {
t.Error("Cookie was not set")
}
}
// Session start returns an existing session.
func TestExistingSession(t *testing.T) {
defer reset()
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id != sessionID {
return nil, fmt.Errorf("Requested wrong session: %s", id)
}
return &Session{created: time.Now().Add(-time.Minute), lastAccess: time.Now().Add(-time.Minute), data: map[string]interface{}{"test": true}}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
}
if session == nil {
t.Error("Expected session, received nil")
return
}
if _, ok := session.data["test"]; !ok {
t.Error("Did not receive expected session")
}
}
// Session start returns an expired session.
func TestExpiredSession(t *testing.T) {
defer reset()
SessionExpiry = 0
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id != sessionID {
return nil, fmt.Errorf("Requested wrong session: %s", id)
}
return &Session{created: time.Now().Add(-time.Minute), lastAccess: time.Now()}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
}
if session != nil {
t.Error("Expected nil session, received non-empty session")
}
}
// Session start performs a session ID change.
func TestSessionIDChange(t *testing.T) {
defer reset()
SessionIDGracePeriod = 5 * time.Millisecond
var deleted, saved int
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id != sessionID {
return nil, fmt.Errorf("Requested wrong session: %s", id)
}
return &Session{
created: time.Now().Add(-2 * time.Hour),
lastAccess: time.Now().Add(-2 * time.Hour),
data: map[string]interface{}{"test": true},
}, nil
},
SaveSessionFunc: func(id string, session *Session) error {
saved++
return nil
},
DeleteSessionFunc: func(id string) error {
deleted++
if id != sessionID {
return fmt.Errorf("Deleting wrong session ID: %s", id)
}
return nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
}
if session == nil {
t.Error("Expected session, received nil")
return
}
if _, ok := session.data["test"]; !ok {
t.Error("Did not receive expected session")
}
cookie := regexp.MustCompile("^" + SessionCookie + "=[0-9a-zA-Z=+/]{24}")
if !cookie.MatchString(res.Header().Get("Set-Cookie")) {
t.Error("Cookie was not updated")
}
time.Sleep(10 * time.Millisecond)
if deleted != 1 {
t.Error("Old session was not deleted")
}
if saved != 2 {
t.Error("New session was not saved")
}
// Cover the expiry function.
if session.Expired() {
t.Error("Session has expired although it shouldn't have")
}
}
// Session start returns referenced session.
func TestReferencedSession(t *testing.T) {
defer reset()
SessionIDGracePeriod = 10 * time.Millisecond
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id == sessionID {
return &Session{
referenceID: "ABCDEFGHIJKLMNOPQRSTUVWX",
created: time.Now().Add(-5 * time.Millisecond),
lastAccess: time.Now().Add(-5 * time.Millisecond),
data: nil,
}, nil
}
return &Session{
created: time.Now(),
lastAccess: time.Now(),
data: map[string]interface{}{"test": true},
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
}
if session == nil {
t.Error("Expected session, received nil")
return
}
if _, ok := session.data["test"]; !ok {
t.Error("Did not receive expected session")
}
if !strings.Contains(res.Header().Get("Set-Cookie"), fmt.Sprintf("%s=ABCDEFGHIJKLMNOPQRSTUVWX", SessionCookie)) {
t.Error("Cookie was not updated")
}
}
// Session start detects that the reference session has expired.
func TestExpiredReferencedSession(t *testing.T) {
defer reset()
SessionIDGracePeriod = 10 * time.Millisecond
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id != sessionID {
return nil, errors.New("Wrong session ID")
}
return &Session{
referenceID: "ABCDEFGHIJKLMNOPQRSTUVWX",
created: time.Now().Add(-SessionIDExpiry - 2*SessionIDGracePeriod),
lastAccess: time.Now().Add(-SessionIDExpiry - 2*SessionIDGracePeriod),
data: nil,
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
_, err := Start(res, req, false)
if err == nil {
t.Error("Expected failure due to expired reference session, no failure however")
}
}
// Try requesting lots of session ID changes at once, hoping to get multiple new
// sessions.
func TestSessionIDChangeDoS(t *testing.T) {
defer reset()
SessionIDGracePeriod = 5 * time.Millisecond
var deleted, saved int
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
if id != sessionID {
return nil, fmt.Errorf("Requested wrong session: %s", id)
}
return &Session{
created: time.Now().Add(-time.Hour - 2*time.Millisecond),
lastAccess: time.Now().Add(-time.Hour - 2*time.Millisecond),
data: map[string]interface{}{"test": true},
}, nil
},
SaveSessionFunc: func(id string, session *Session) error {
saved++
return nil
},
DeleteSessionFunc: func(id string) error {
deleted++
if id != sessionID {
return fmt.Errorf("Deleting wrong session ID: %s", id)
}
return nil
},
}
var (
sessions []*Session
mutex sync.Mutex
wg sync.WaitGroup
)
for i := 0; i < 30; i++ {
wg.Add(1)
go func() {
defer wg.Done()
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
return
}
mutex.Lock()
sessions = append(sessions, session)
mutex.Unlock()
}()
}
wg.Wait()
// We should have received the same object.
for index, session := range sessions {
if index == 0 {
if session == nil {
t.Error("Expected session, received nil")
return
}
if _, ok := session.data["test"]; !ok {
t.Error("Did not receive expected session")
return
}
} else {
if session != sessions[0] {
t.Errorf("Received a different session: %d (%v)", index, session)
}
}
}
time.Sleep(10 * time.Millisecond)
if deleted != 1 {
t.Errorf("Old session was not deleted: %d", deleted)
}
if saved != 2 {
t.Error("New session was not saved")
}
}
// Test remote IP with a valid IP change.
func TestSessionValidRemoteIP(t *testing.T) {
defer reset()
AcceptRemoteIP = 3
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
return &Session{
created: time.Now(),
lastAccess: time.Now(),
lastIP: "192.168.178.1:80",
data: nil,
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
req.RemoteAddr = "192.168.100.50:8080"
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
return
}
if session == nil {
t.Error("Nil session returned, regular session expected")
}
}
// Test remote IP with an invalid IP change.
func TestSessionInvalidRemoteIP(t *testing.T) {
defer reset()
AcceptRemoteIP = 3
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
return &Session{
created: time.Now(),
lastAccess: time.Now(),
lastIP: "192.168.178.1:80",
data: nil,
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
req.RemoteAddr = "192.100.100.50:8080"
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
return
}
if session != nil {
t.Error("Session returned, nil session expected")
}
}
// Test remote user agent with a valid user agent change.
func TestSessionValidRemoteUserAgent(t *testing.T) {
defer reset()
AcceptRemoteIP = 3
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
return &Session{
created: time.Now(),
lastAccess: time.Now(),
lastIP: "192.168.178.1:80",
lastUserAgentHash: 2838198717544347415,
data: nil,
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
req.RemoteAddr = "192.168.178.1:80"
req.Header.Add("User-Agent", "My User Agent")
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
return
}
if session == nil {
t.Error("Nil session returned, regular session expected")
}
}
// Test remote user agent with an invalid user agent change.
func TestSessionInvalidRemoteUserAgent(t *testing.T) {
defer reset()
AcceptRemoteIP = 3
Persistence = ExtendablePersistenceLayer{
LoadSessionFunc: func(id string) (*Session, error) {
return &Session{
created: time.Now(),
lastAccess: time.Now(),
lastIP: "192.168.178.1:80",
lastUserAgentHash: 2838198717544347415,
data: nil,
}, nil
},
}
req := httptest.NewRequest("", "/", nil)
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: sessionID})
req.RemoteAddr = "192.168.178.1:80"
req.Header.Add("User-Agent", "Not my User Agent")
res := httptest.NewRecorder()
session, err := Start(res, req, false)
if err != nil {
t.Error(err)
return
}
if session != nil {
t.Error("Session returned, nil session expected")
}
}
// Test session data storage.
func TestSessionData(t *testing.T) {
defer reset()
req := httptest.NewRequest("", "/", nil)
res := httptest.NewRecorder()
session, err := Start(res, req, true)
if err != nil {
t.Error(err)
}
if session == nil {
t.Error("Expected session, received none")
return
}
if err := session.Set("key1", true); err != nil {
t.Error(err)
return
}
if err := session.Set("key1", false); err != nil {
t.Error(err)
return
}
if err := session.Set("key2", "value"); err != nil {
t.Error(err)
return
}
if err := session.Set("key3", nil); err != nil {
t.Error(err)
return
}
if err := session.Delete("key3"); err != nil {
t.Error(err)
return
}
val1 := session.Get("key1", nil)
if val1 == nil {
t.Error("key1 value was not found")
return
}
if b, ok := val1.(bool); !ok {
t.Error("key1 is not bool")
return
} else if b {
t.Error("key1 was not overwritten")
}
val2 := session.Get("key2", nil)
if val2 == nil {
t.Error("key2 value was not found")
return
}
if s, ok := val2.(string); !ok {
t.Error("key2 is not a string")
return
} else if s != "value" {
t.Errorf("key2 is %s, not 'value'", s)
}
val3 := session.Get("key3", "key").(string)
if val3 != "key" {
t.Error("key3 value is still stored")
return
}
val1a := session.GetAndDelete("key1", nil)
if val1a == nil {
t.Error("key1 value was not found")
return
}
val1b := session.GetAndDelete("key1", nil)
if val1b != nil {
t.Error("key1 is still stored")
return
}
}