security: add headers middleware, session regeneration, and body size limits
Some checks failed
check / check (push) Has been cancelled

- Add SecurityHeaders middleware applied globally: HSTS, X-Content-Type-Options,
  X-Frame-Options, CSP, Referrer-Policy, and Permissions-Policy headers on every
  response.
- Add session regeneration (Regenerate method) after successful login to prevent
  session fixation attacks. Old session is destroyed and a new ID is issued.
- Add MaxBodySize middleware using http.MaxBytesReader to limit POST/PUT/PATCH
  request bodies to 1 MB on all form endpoints (/pages, /sources, /source/*).

Closes #34, closes #38, closes #39
This commit is contained in:
clawbot
2026-03-05 02:53:45 -08:00
parent a51e863017
commit 0489d9916f
4 changed files with 100 additions and 2 deletions

View File

@@ -171,3 +171,35 @@ func (s *Middleware) MetricsAuth() func(http.Handler) http.Handler {
},
)
}
// SecurityHeaders returns middleware that sets production security headers
// on every response: HSTS, X-Content-Type-Options, X-Frame-Options, CSP,
// Referrer-Policy, and Permissions-Policy.
func (s *Middleware) SecurityHeaders() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
next.ServeHTTP(w, r)
})
}
}
// MaxBodySize returns middleware that limits the request body size for POST
// requests. If the body exceeds the given limit in bytes, the server returns
// 413 Request Entity Too Large. This prevents clients from sending arbitrarily
// large form bodies.
func (s *Middleware) MaxBodySize(maxBytes int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodPatch {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
next.ServeHTTP(w, r)
})
}
}