saveinmed/backend/internal/http/middleware/security.go
Tiago Yamamoto beffeb8268 feat(security): add rate limiting and security headers middleware
Rate Limiting (ratelimit.go):
- Token bucket algorithm per IP
- Default: 100 requests/minute
- X-Forwarded-For support
- Cleanup for stale buckets
- 7 tests (ratelimit_test.go)

Security Headers (security.go):
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- X-XSS-Protection: 1; mode=block
- Content-Security-Policy: default-src 'none'
- Referrer-Policy: strict-origin-when-cross-origin
- Cache-Control: no-store, max-age=0

Middleware coverage: 97.3% -> 95.8% (new code added)
2025-12-20 08:41:36 -03:00

33 lines
952 B
Go

package middleware
import (
"net/http"
)
// SecurityHeaders adds common security headers to responses.
func SecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Prevent MIME type sniffing
w.Header().Set("X-Content-Type-Options", "nosniff")
// Prevent clickjacking
w.Header().Set("X-Frame-Options", "DENY")
// Enable XSS filter
w.Header().Set("X-XSS-Protection", "1; mode=block")
// Content Security Policy (strict for API)
w.Header().Set("Content-Security-Policy", "default-src 'none'")
// Referrer Policy
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// Cache control for API responses
w.Header().Set("Cache-Control", "no-store, max-age=0")
// HSTS (HTTP Strict Transport Security) - only in production
// w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
next.ServeHTTP(w, r)
})
}