-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsession_test.go
118 lines (103 loc) · 2.49 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
package mid
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
type testSession struct {
id int
csrfKey [sha256.Size]byte
}
func (s testSession) CSRFKey() [sha256.Size]byte { return s.csrfKey }
func (testSession) Active() bool { return true }
func (testSession) Exp() time.Time { return time.Now().Add(24 * time.Hour) }
func TestCSRF(t *testing.T) {
var s1, s2 testSession
s2.csrfKey[0] = 'x'
tok, err := CSRFToken(s1)
if err != nil {
t.Fatal(err)
}
err = CSRFCheck(s1, tok)
if err != nil {
t.Errorf("got error %s, want nil", err)
}
err = CSRFCheck(s2, tok)
if !errors.Is(err, ErrCSRF) {
t.Errorf("got error %v, want %s", err, ErrCSRF)
}
err = CSRFCheck(s1, tok[1:])
if !errors.Is(err, ErrCSRF) {
t.Errorf("got error %v, want %s", err, ErrCSRF)
}
err = CSRFCheck(s1, "foo")
if !errors.Is(err, ErrCSRF) {
t.Errorf("got error %v, want %s", err, ErrCSRF)
}
}
func TestSessionHandler(t *testing.T) {
var (
store testSessionStore
got int
)
server := httptest.NewServer(SessionHandler(store, "cookie", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
sess := ContextSession(req.Context())
if sess == nil {
got = 0
} else {
got = sess.(testSession).id
}
})))
defer server.Close()
cases := []struct {
val string
want, wantStatus int
}{{
val: "foo",
wantStatus: http.StatusNoContent,
want: 1,
}, {
val: "bar",
wantStatus: http.StatusForbidden,
}, {
wantStatus: http.StatusForbidden,
}}
var client http.Client
for i, tc := range cases {
t.Run(fmt.Sprintf("case_%02d", i+1), func(t *testing.T) {
req, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Fatal(err)
}
if tc.val != "" {
req.AddCookie(&http.Cookie{Name: "cookie", Value: tc.val})
}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != tc.wantStatus {
t.Errorf("got status %d, want %d", resp.StatusCode, tc.wantStatus)
}
if resp.StatusCode == http.StatusNoContent && got != tc.want {
t.Errorf("got %d, want %d", got, tc.want)
}
})
}
}
type testSessionStore struct{}
func (s testSessionStore) Get(_ context.Context, key string) (Session, error) {
if key == "foo" {
return testSession{id: 1}, nil
}
return nil, ErrNoSession
}
func (testSessionStore) Cancel(context.Context, string) error {
return fmt.Errorf("unimplemented")
}