Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CSP nonce. Resolves: #69 #94

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

rafaelDev0ps
Copy link
Contributor

What was done

Added CSP nonce that:

  1. Generate a unique nonce for each request
  2. Add the CSP header to your responses with the nonce
  3. Pass the nonce through the render context

The changes ensure that

  • All dynamically generated scripts get the nonce attribute
  • The nonce is propagated through the rendering context
  • It's compatible with htmx's security settings

How to use it

Setup the CSP headers in the middleware

func WithCSP(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        nonce := generateNonce()
        csp := fmt.Sprintf("script-src 'self' 'nonce-%s'", nonce)
        w.Header().Set("Content-Security-Policy", csp)
        // Store nonce in context for use in render
        ctx := context.WithValue(r.Context(), "csp-nonce", nonce)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

Copy link

codecov bot commented Jan 15, 2025

Codecov Report

Attention: Patch coverage is 33.33333% with 4 lines in your changes missing coverage. Please review.

Project coverage is 72.48%. Comparing base (24b41a7) to head (3a23e7e).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
framework/h/render.go 0.00% 4 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           master      #94       +/-   ##
===========================================
+ Coverage   57.06%   72.48%   +15.41%     
===========================================
  Files           5       33       +28     
  Lines         778     2860     +2082     
===========================================
+ Hits          444     2073     +1629     
- Misses        307      746      +439     
- Partials       27       41       +14     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant