-
Notifications
You must be signed in to change notification settings - Fork 0
/
nonce_test.go
110 lines (87 loc) · 2.3 KB
/
nonce_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
package nonce_test
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
nonce "go.eigsys.de/gin-nonce"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewNonceHandler(t *testing.T) {
t.Run("normal", func(t *testing.T) {
resp := httptest.NewRecorder()
ginContext, _ := gin.CreateTestContext(resp)
handler := nonce.New().WithRandRead(func(b []byte) (int, error) {
b[0] = 'b'
b[1] = 'a'
b[2] = 'r'
return 3, nil
})
handler.Middleware()(ginContext)
if handler.GetKey() != "go.eigsys.de/gin-nonce:nonce" {
t.Error("wrong key")
}
if value, ok := ginContext.Get("go.eigsys.de/gin-nonce:nonce"); !ok || value.(string) != "YmFyAAAAAAAAAAAAAAAAAA" {
t.Error("wrong nonce")
}
})
t.Run("rand-read-error", func(t *testing.T) {
resp := httptest.NewRecorder()
ginContext, _ := gin.CreateTestContext(resp)
handler := nonce.New().WithRandRead(func(b []byte) (n int, err error) {
return 0, errors.New("oops")
})
handler.Middleware()(ginContext)
if resp.Code != http.StatusInternalServerError {
t.Error("wrong status code")
}
})
}
func TestHandler_WithKey(t *testing.T) {
handler := nonce.New().WithKey("foo")
if handler.GetKey() != "foo" {
t.Error("wrong key")
}
}
func TestHandler_GetKey(t *testing.T) {
handler := nonce.New().WithKey("foo")
if handler.GetKey() != "foo" {
t.Error("wrong key")
}
}
func TestHandler_GetNonce(t *testing.T) {
t.Run("normal", func(t *testing.T) {
resp := httptest.NewRecorder()
ginContext, _ := gin.CreateTestContext(resp)
ginContext.Set("go.eigsys.de/gin-nonce:nonce", "bar")
handler := nonce.New()
value, ok := handler.GetNonce(ginContext)
if value != "bar" {
t.Error("wrong value")
}
if !ok {
t.Error("not ok")
}
})
t.Run("error", func(t *testing.T) {
resp := httptest.NewRecorder()
ginContext, _ := gin.CreateTestContext(resp)
handler := nonce.New()
_, ok := handler.GetNonce(ginContext)
if ok {
t.Error("unexpectedly ok")
}
})
}
func ExampleNew() {
router := gin.Default()
handler := nonce.New()
router.Use(handler.Middleware())
router.GET("/", func(ginCtx *gin.Context) {
currentNonce, _ := handler.GetNonce(ginCtx)
ginCtx.Header("Content-Security-Policy", fmt.Sprintf("style-src 'nonce-%s';", currentNonce))
ginCtx.String(http.StatusOK, "Hello, Gopher!")
})
_ = router.Run()
}