Skip to content

Commit

Permalink
test: add csp headers
Browse files Browse the repository at this point in the history
  • Loading branch information
tomanagle committed Apr 1, 2024
1 parent f394b54 commit 065fc3f
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func main() {
middleware.Logger,
m.TextHTMLMiddleware,
m.CSPMiddleware,
authMiddleware.ValidateUser,
authMiddleware.AddUserToContext,
)

r.NotFound(handlers.NewNotFoundHandler().ServeHTTP)
Expand Down
60 changes: 60 additions & 0 deletions internal/middleware/middleare_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
)

func TestCSPMiddleware(t *testing.T) {

testCases := []struct {
name string
}{
{
name: "success",
},
}

for _, tc := range testCases {

t.Run(tc.name, func(t *testing.T) {

assert := assert.New(t)

next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

nonces := GetNonces(ctx)
twNonce := GetTwNonce(ctx)
htmxNonce := GetHtmxNonce(ctx)
responseTargetsNonce := GetResponseTargetsNonce(ctx)

assert.Equal(nonces.Tw, twNonce)
assert.Len(twNonce, 32)

assert.Equal(nonces.Htmx, htmxNonce)
assert.Len(htmxNonce, 32)

assert.Equal(nonces.ResponseTargets, responseTargetsNonce)
assert.Len(responseTargetsNonce, 32)

})

middleware := CSPMiddleware(next)

recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/", nil)

middleware.ServeHTTP(recorder, request)

csp := recorder.Header().Get("Content-Security-Policy")

assert.NotEmpty(csp)

})
}

}
3 changes: 1 addition & 2 deletions internal/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ type Nonces struct {
}

func generateRandomString(length int) string {

bytes := make([]byte, length)
_, err := rand.Read(bytes)
if err != nil {
Expand Down Expand Up @@ -115,7 +114,7 @@ type UserContextKey string

var UserKey UserContextKey = "user"

func (m *AuthMiddleware) ValidateUser(next http.Handler) http.Handler {
func (m *AuthMiddleware) AddUserToContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

sessionCookie, err := r.Cookie(m.sessionCookieName)
Expand Down

0 comments on commit 065fc3f

Please sign in to comment.