-
Notifications
You must be signed in to change notification settings - Fork 4
/
store_test.go
99 lines (76 loc) · 2.21 KB
/
store_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
package csrf
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"goji.io"
"goji.io/pat"
"github.com/gorilla/securecookie"
)
// Check Store implementations
var _ store = &cookieStore{}
// brokenSaveStore is a CSRF store that cannot, well, save.
type brokenSaveStore struct {
store
}
func (bs *brokenSaveStore) Get(*http.Request) ([]byte, error) {
// Generate an invalid token so we can progress to our Save method
return generateRandomBytes(24)
}
func (bs *brokenSaveStore) Save(realToken []byte, w http.ResponseWriter) error {
return errors.New("test error")
}
// Tests for failure if the middleware can't save to the Store.
func TestStoreCannotSave(t *testing.T) {
m := goji.NewMux()
bs := &brokenSaveStore{}
m.UseC(Protect(testKey, setStore(bs)))
m.HandleFuncC(pat.Get("/"), testHandler)
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
m.ServeHTTP(rr, r)
if rr.Code != http.StatusForbidden {
t.Fatalf("broken store did not set an error status: got %v want %v",
rr.Code, http.StatusForbidden)
}
if c := rr.Header().Get("Set-Cookie"); c != "" {
t.Fatalf("broken store incorrectly set a cookie: got %v want %v",
c, "")
}
}
// TestCookieDecode tests that an invalid cookie store returns a decoding error.
func TestCookieDecode(t *testing.T) {
r, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
var age = 3600
// Test with a nil hash key
sc := securecookie.New(nil, nil)
sc.MaxAge(age)
st := &cookieStore{cookieName, age, true, true, "", "", sc}
// Set a fake cookie value so r.Cookie passes.
r.Header.Set("Cookie", fmt.Sprintf("%s=%s", cookieName, "notacookie"))
_, err = st.Get(r)
if err == nil {
t.Fatal("cookiestore did not report an invalid hashkey on decode")
}
}
// TestCookieEncode tests that an invalid cookie store returns an encoding error.
func TestCookieEncode(t *testing.T) {
var age = 3600
// Test with a nil hash key
sc := securecookie.New(nil, nil)
sc.MaxAge(age)
st := &cookieStore{cookieName, age, true, true, "", "", sc}
rr := httptest.NewRecorder()
err := st.Save(nil, rr)
if err == nil {
t.Fatal("cookiestore did not report an invalid hashkey on encode")
}
}