TomDoesTech / GOTTH

https://www.youtube.com/watch?v=k00jVJeZxrs
534 stars 86 forks source link

CSPMiddleware creating new context instead of using the one from request #6

Closed raymclee closed 8 months ago

raymclee commented 8 months ago

https://github.com/TomDoesTech/GOTTH/blob/455727f15d1adbc6988bbe6fee75f015e4205754/internal/middleware/middleware.go#L27

should change to this, otherwrise it cannot parse the dynamic url

func CSPMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        htmxNonce := generateRandomString(16)
        responseTargetsNonse := generateRandomString(16)
        twNonce := generateRandomString(16)

        // set then in context
        ctx := context.WithValue(r.Context(), "htmxNonce", htmxNonce)
        ctx = context.WithValue(ctx, "twNonce", twNonce)
        ctx = context.WithValue(ctx, "responseTargetsNonse", responseTargetsNonse)

        // the hash of the CSS that HTMX injects
        htmxCSSHash := "sha256-pgn1TCGZX6O77zDvy0oTODMOxemn0oj0LeCnQTRj7Kg="

        cspHeader := fmt.Sprintf("default-src 'self'; script-src 'nonce-%s' 'nonce-%s'; style-src 'nonce-%s' '%s';", htmxNonce, responseTargetsNonse, twNonce, htmxCSSHash)
        w.Header().Set("Content-Security-Policy", cspHeader)

        next.ServeHTTP(w, r.WithContext(ctx))
    })
}
tomanagle commented 8 months ago

Do you want to submit a PR?

raymclee commented 8 months ago

sure here you go

tomanagle commented 8 months ago

Merged, thank you