-
Notifications
You must be signed in to change notification settings - Fork 149
/
securecookie_test.go
344 lines (311 loc) · 8.03 KB
/
securecookie_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
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package securecookie
import (
"crypto/aes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"reflect"
"strings"
"testing"
fuzz "github.com/google/gofuzz"
)
// Asserts that cookieError and MultiError are Error implementations.
var _ Error = cookieError{}
var _ Error = MultiError{}
var testCookies = []interface{}{
map[string]string{"foo": "bar"},
map[string]string{"baz": "ding"},
}
var testStrings = []string{"foo", "bar", "baz"}
func TestSecureCookie(t *testing.T) {
// TODO test too old / too new timestamps
s1 := New([]byte("12345"), []byte("1234567890123456"))
s2 := New([]byte("54321"), []byte("6543210987654321"))
value := map[string]interface{}{
"foo": "bar",
"baz": 128,
}
for i := 0; i < 50; i++ {
// Running this multiple times to check if any special character
// breaks encoding/decoding.
encoded, err1 := s1.Encode("sid", value)
if err1 != nil {
t.Error(err1)
continue
}
dst := make(map[string]interface{})
err2 := s1.Decode("sid", encoded, &dst)
if err2 != nil {
t.Fatalf("%v: %v", err2, encoded)
}
if !reflect.DeepEqual(dst, value) {
t.Fatalf("Expected %v, got %v.", value, dst)
}
dst2 := make(map[string]interface{})
err3 := s2.Decode("sid", encoded, &dst2)
if err3 == nil {
t.Fatalf("Expected failure decoding.")
}
err4, ok := err3.(Error)
if !ok {
t.Fatalf("Expected error to implement Error, got: %#v", err3)
}
if !err4.IsDecode() {
t.Fatalf("Expected DecodeError, got: %#v", err4)
}
// Test other error type flags.
if err4.IsUsage() {
t.Fatalf("Expected IsUsage() == false, got: %#v", err4)
}
if err4.IsInternal() {
t.Fatalf("Expected IsInternal() == false, got: %#v", err4)
}
}
}
func TestSecureCookieNilKey(t *testing.T) {
s1 := New(nil, nil)
value := map[string]interface{}{
"foo": "bar",
"baz": 128,
}
_, err := s1.Encode("sid", value)
if err != errHashKeyNotSet {
t.Fatal("Wrong error returned:", err)
}
}
func TestDecodeInvalid(t *testing.T) {
// List of invalid cookies, which must not be accepted, base64-decoded
// (they will be encoded before passing to Decode).
invalidCookies := []string{
"",
" ",
"\n",
"||",
"|||",
"cookie",
}
s := New([]byte("12345"), nil)
var dst string
for i, v := range invalidCookies {
for _, enc := range []*base64.Encoding{
base64.StdEncoding,
base64.URLEncoding,
} {
err := s.Decode("name", enc.EncodeToString([]byte(v)), &dst)
if err == nil {
t.Fatalf("%d: expected failure decoding", i)
}
err2, ok := err.(Error)
if !ok || !err2.IsDecode() {
t.Fatalf("%d: Expected IsDecode(), got: %#v", i, err)
}
}
}
}
func TestAuthentication(t *testing.T) {
hash := hmac.New(sha256.New, []byte("secret-key"))
for _, value := range testStrings {
hash.Reset()
signed := createMac(hash, []byte(value))
hash.Reset()
err := verifyMac(hash, []byte(value), signed)
if err != nil {
t.Error(err)
}
}
}
func TestEncryption(t *testing.T) {
block, err := aes.NewCipher([]byte("1234567890123456"))
if err != nil {
t.Fatalf("Block could not be created")
}
var encrypted, decrypted []byte
for _, value := range testStrings {
if encrypted, err = encrypt(block, []byte(value)); err != nil {
t.Error(err)
} else {
if decrypted, err = decrypt(block, encrypted); err != nil {
t.Error(err)
}
if string(decrypted) != value {
t.Errorf("Expected %v, got %v.", value, string(decrypted))
}
}
}
}
func TestGobSerialization(t *testing.T) {
var (
sz GobEncoder
serialized []byte
deserialized map[string]string
err error
)
for _, value := range testCookies {
if serialized, err = sz.Serialize(value); err != nil {
t.Error(err)
} else {
deserialized = make(map[string]string)
if err = sz.Deserialize(serialized, &deserialized); err != nil {
t.Error(err)
}
if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) {
t.Errorf("Expected %v, got %v.", value, deserialized)
}
}
}
}
func TestJSONSerialization(t *testing.T) {
var (
sz JSONEncoder
serialized []byte
deserialized map[string]string
err error
)
for _, value := range testCookies {
if serialized, err = sz.Serialize(value); err != nil {
t.Error(err)
} else {
deserialized = make(map[string]string)
if err = sz.Deserialize(serialized, &deserialized); err != nil {
t.Error(err)
}
if fmt.Sprintf("%v", deserialized) != fmt.Sprintf("%v", value) {
t.Errorf("Expected %v, got %v.", value, deserialized)
}
}
}
}
func TestNopSerialization(t *testing.T) {
cookieData := "fooobar123"
sz := NopEncoder{}
if _, err := sz.Serialize(cookieData); err != errValueNotByte {
t.Fatal("Expected error passing string")
}
dat, err := sz.Serialize([]byte(cookieData))
if err != nil {
t.Fatal(err)
}
if (string(dat)) != cookieData {
t.Fatal("Expected serialized data to be same as source")
}
var dst []byte
if err = sz.Deserialize(dat, dst); err != errValueNotBytePtr {
t.Fatal("Expect error unless you pass a *[]byte")
}
if err = sz.Deserialize(dat, &dst); err != nil {
t.Fatal(err)
}
if (string(dst)) != cookieData {
t.Fatal("Expected deserialized data to be same as source")
}
}
func TestEncoding(t *testing.T) {
for _, value := range testStrings {
encoded := encode([]byte(value))
decoded, err := decode(encoded)
if err != nil {
t.Error(err)
} else if string(decoded) != value {
t.Errorf("Expected %v, got %s.", value, string(decoded))
}
}
}
func TestMultiError(t *testing.T) {
s1, s2 := New(nil, nil), New(nil, nil)
_, err := EncodeMulti("sid", "value", s1, s2)
if len(err.(MultiError)) != 2 {
t.Errorf("Expected 2 errors, got %s.", err)
} else {
if !strings.Contains(err.Error(), "hash key is not set") {
t.Errorf("Expected missing hash key error, got %s.", err.Error())
}
ourErr, ok := err.(Error)
if !ok || !ourErr.IsUsage() {
t.Fatalf("Expected error to be a usage error; got %#v", err)
}
if ourErr.IsDecode() {
t.Errorf("Expected error NOT to be a decode error; got %#v", ourErr)
}
if ourErr.IsInternal() {
t.Errorf("Expected error NOT to be an internal error; got %#v", ourErr)
}
}
}
func TestMultiNoCodecs(t *testing.T) {
_, err := EncodeMulti("foo", "bar")
if err != errNoCodecs {
t.Errorf("EncodeMulti: bad value for error, got: %v", err)
}
var dst []byte
err = DecodeMulti("foo", "bar", &dst)
if err != errNoCodecs {
t.Errorf("DecodeMulti: bad value for error, got: %v", err)
}
}
func TestMissingKey(t *testing.T) {
emptyKeys := [][]byte{
nil,
[]byte(""),
}
for _, key := range emptyKeys {
s1 := New(key, nil)
var dst []byte
err := s1.Decode("sid", "value", &dst)
if err != errHashKeyNotSet {
t.Fatalf("Expected %#v, got %#v", errHashKeyNotSet, err)
}
if err2, ok := err.(Error); !ok || !err2.IsUsage() {
t.Errorf("Expected missing hash key to be IsUsage(); was %#v", err)
}
}
}
// ----------------------------------------------------------------------------
type FooBar struct {
Foo int
Bar string
}
func TestCustomType(t *testing.T) {
s1 := New([]byte("12345"), []byte("1234567890123456"))
// Type is not registered in gob. (!!!)
src := &FooBar{42, "bar"}
encoded, _ := s1.Encode("sid", src)
dst := &FooBar{}
_ = s1.Decode("sid", encoded, dst)
if dst.Foo != 42 || dst.Bar != "bar" {
t.Fatalf("Expected %#v, got %#v", src, dst)
}
}
type Cookie struct {
B bool
I int
S string
}
func FuzzEncodeDecode(f *testing.F) {
fuzzer := fuzz.New()
s1 := New([]byte("12345"), []byte("1234567890123456"))
s1.maxLength = 0
for i := 0; i < 100000; i++ {
var c Cookie
fuzzer.Fuzz(&c)
f.Add(c.B, c.I, c.S)
}
f.Fuzz(func(t *testing.T, b bool, i int, s string) {
c := Cookie{b, i, s}
encoded, err := s1.Encode("sid", c)
if err != nil {
t.Errorf("Encode failed: %v", err)
}
dc := Cookie{}
err = s1.Decode("sid", encoded, &dc)
if err != nil {
t.Errorf("Decode failed: %v", err)
}
if dc != c {
t.Fatalf("Expected %v, got %v.", s, dc)
}
})
}