main
1package cookie
2
3import (
4 "crypto/hmac"
5 "crypto/sha256"
6 "encoding/base64"
7 "fmt"
8 "net/http"
9 "testing"
10 "time"
11
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "github.com/xlgmokha/x/pkg/crypt"
15 "github.com/xlgmokha/x/pkg/pls"
16 "github.com/xlgmokha/x/pkg/x"
17)
18
19func TestOption(t *testing.T) {
20 t.Run("WithPath", func(t *testing.T) {
21 assert.Equal(t, "/blah", New("name", WithPath("/blah")).Path)
22 })
23
24 t.Run("WithHttpOnly", func(t *testing.T) {
25 assert.False(t, New("x", WithHttpOnly(false)).HttpOnly)
26 assert.True(t, New("x", WithHttpOnly(true)).HttpOnly)
27 })
28
29 t.Run("WithSecure", func(t *testing.T) {
30 assert.False(t, New("x", WithSecure(false)).Secure)
31 assert.True(t, New("x", WithSecure(true)).Secure)
32 })
33
34 t.Run("WithDomain", func(t *testing.T) {
35 assert.Equal(t, "example.com", New("x", WithDomain("example.com")).Domain)
36 })
37
38 t.Run("WithSameSite", func(t *testing.T) {
39 assert.Equal(t, http.SameSiteLaxMode, New("x", WithSameSite(http.SameSiteLaxMode)).SameSite)
40 assert.Equal(t, http.SameSiteStrictMode, New("x", WithSameSite(http.SameSiteStrictMode)).SameSite)
41 assert.Equal(t, http.SameSiteNoneMode, New("x", WithSameSite(http.SameSiteNoneMode)).SameSite)
42 })
43
44 t.Run("WithExpiration", func(t *testing.T) {
45 now := time.Now()
46
47 t.Run("with future time", func(t *testing.T) {
48 expires := now.Add(1 * time.Second)
49 cookie := New("x", WithExpiration(expires))
50 assert.Equal(t, expires, cookie.Expires)
51 assert.Equal(t, 1, cookie.MaxAge)
52 })
53
54 t.Run("with past time", func(t *testing.T) {
55 expires := now.Add(-1 * time.Second)
56 cookie := New("x", WithExpiration(expires))
57 assert.Equal(t, expires, cookie.Expires)
58 assert.Equal(t, -1, cookie.MaxAge)
59 })
60 })
61
62 t.Run("WithSignedValue", func(t *testing.T) {
63 value := "1"
64 secret := "secret"
65 signer := x.New[*crypt.HMACSigner](
66 crypt.WithKey([]byte(secret)),
67 crypt.WithAlgorithm(sha256.New),
68 )
69 cookie := New("session", WithSignedValue(value, signer))
70
71 require.NotNil(t, cookie)
72 assert.NotEqual(t, "1", cookie.Value)
73 assert.NotEmpty(t, cookie.Value)
74
75 mac := hmac.New(sha256.New, []byte(secret))
76 mac.Write([]byte(value))
77 signature := mac.Sum(nil)
78
79 expected := fmt.Sprintf("%v--%v", value, base64.URLEncoding.EncodeToString(signature))
80
81 assert.Equal(t, expected, cookie.Value)
82 assert.True(t, hmac.Equal([]byte(expected), []byte(cookie.Value)))
83 })
84
85 t.Run("WithBase64EncodedValue", func(t *testing.T) {
86 value := x.Must(pls.GenerateRandomBytes(32))
87 cookie := New("session", WithBase64Value(value))
88
89 require.NotNil(t, cookie)
90 expected := base64.URLEncoding.EncodeToString(value)
91 assert.Equal(t, expected, cookie.Value)
92 })
93}