All checks were successful
check / check (push) Successful in 1m47s
## Summary This PR implements three security hardening measures: ### Security Headers Middleware (closes #34) Adds a `SecurityHeaders()` middleware applied globally to all routes. Every response now includes: - `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload` - `X-Content-Type-Options: nosniff` - `X-Frame-Options: DENY` - `Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'` - `Referrer-Policy: strict-origin-when-cross-origin` - `Permissions-Policy: camera=(), microphone=(), geolocation=()` ### Session Fixation Prevention (closes #38) Adds a `Regenerate()` method to the session manager that destroys the old session and creates a new one with a fresh ID, copying all session values. Called after successful login to prevent session fixation attacks. ### Request Body Size Limits (closes #39) Adds a `MaxBodySize()` middleware using `http.MaxBytesReader` to limit POST/PUT/PATCH request bodies to 1 MB. Applied to all form endpoints (`/pages`, `/sources`, `/source/*`). ## Files Changed - `internal/middleware/middleware.go` — Added `SecurityHeaders()` and `MaxBodySize()` middleware - `internal/session/session.go` — Added `Regenerate()` method for session fixation prevention - `internal/handlers/auth.go` — Updated login handler to regenerate session after authentication - `internal/server/routes.go` — Added SecurityHeaders globally, MaxBodySize to form route groups - `README.md` — Documented new middleware in stack, updated Security section, moved items to completed TODO closes #34, closes #38, closes #39 Co-authored-by: clawbot <clawbot@noreply.git.eeqj.de> Reviewed-on: #41 Co-authored-by: clawbot <clawbot@noreply.example.org> Co-committed-by: clawbot <clawbot@noreply.example.org>
206 lines
6.1 KiB
Go
206 lines
6.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"time"
|
|
|
|
basicauth "github.com/99designs/basicauth-go"
|
|
"github.com/go-chi/chi/middleware"
|
|
"github.com/go-chi/cors"
|
|
metrics "github.com/slok/go-http-metrics/metrics/prometheus"
|
|
ghmm "github.com/slok/go-http-metrics/middleware"
|
|
"github.com/slok/go-http-metrics/middleware/std"
|
|
"go.uber.org/fx"
|
|
"sneak.berlin/go/webhooker/internal/config"
|
|
"sneak.berlin/go/webhooker/internal/globals"
|
|
"sneak.berlin/go/webhooker/internal/logger"
|
|
"sneak.berlin/go/webhooker/internal/session"
|
|
)
|
|
|
|
// nolint:revive // MiddlewareParams is a standard fx naming convention
|
|
type MiddlewareParams struct {
|
|
fx.In
|
|
Logger *logger.Logger
|
|
Globals *globals.Globals
|
|
Config *config.Config
|
|
Session *session.Session
|
|
}
|
|
|
|
type Middleware struct {
|
|
log *slog.Logger
|
|
params *MiddlewareParams
|
|
session *session.Session
|
|
}
|
|
|
|
func New(lc fx.Lifecycle, params MiddlewareParams) (*Middleware, error) {
|
|
s := new(Middleware)
|
|
s.params = ¶ms
|
|
s.log = params.Logger.Get()
|
|
s.session = params.Session
|
|
return s, nil
|
|
}
|
|
|
|
// the following is from
|
|
// https://learning-cloud-native-go.github.io/docs/a6.adding_zerolog_logger/
|
|
|
|
func ipFromHostPort(hp string) string {
|
|
h, _, err := net.SplitHostPort(hp)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if len(h) > 0 && h[0] == '[' {
|
|
return h[1 : len(h)-1]
|
|
}
|
|
return h
|
|
}
|
|
|
|
type loggingResponseWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
// nolint:revive // unexported type is only used internally
|
|
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
|
|
return &loggingResponseWriter{w, http.StatusOK}
|
|
}
|
|
|
|
func (lrw *loggingResponseWriter) WriteHeader(code int) {
|
|
lrw.statusCode = code
|
|
lrw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// type Middleware func(http.Handler) http.Handler
|
|
// this returns a Middleware that is designed to do every request through the
|
|
// mux, note the signature:
|
|
func (s *Middleware) Logging() func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
lrw := NewLoggingResponseWriter(w)
|
|
ctx := r.Context()
|
|
defer func() {
|
|
latency := time.Since(start)
|
|
requestID := ""
|
|
if reqID := ctx.Value(middleware.RequestIDKey); reqID != nil {
|
|
if id, ok := reqID.(string); ok {
|
|
requestID = id
|
|
}
|
|
}
|
|
s.log.Info("http request",
|
|
"request_start", start,
|
|
"method", r.Method,
|
|
"url", r.URL.String(),
|
|
"useragent", r.UserAgent(),
|
|
"request_id", requestID,
|
|
"referer", r.Referer(),
|
|
"proto", r.Proto,
|
|
"remoteIP", ipFromHostPort(r.RemoteAddr),
|
|
"status", lrw.statusCode,
|
|
"latency_ms", latency.Milliseconds(),
|
|
)
|
|
}()
|
|
|
|
next.ServeHTTP(lrw, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func (s *Middleware) CORS() func(http.Handler) http.Handler {
|
|
if s.params.Config.IsDev() {
|
|
// In development, allow any origin for local testing.
|
|
return cors.Handler(cors.Options{
|
|
AllowedOrigins: []string{"*"},
|
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
|
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
|
ExposedHeaders: []string{"Link"},
|
|
AllowCredentials: false,
|
|
MaxAge: 300,
|
|
})
|
|
}
|
|
// In production, the web UI is server-rendered so cross-origin
|
|
// requests are not expected. Return a no-op middleware.
|
|
return func(next http.Handler) http.Handler {
|
|
return next
|
|
}
|
|
}
|
|
|
|
// RequireAuth returns middleware that checks for a valid session.
|
|
// Unauthenticated users are redirected to the login page.
|
|
func (s *Middleware) RequireAuth() func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
sess, err := s.session.Get(r)
|
|
if err != nil {
|
|
s.log.Debug("auth middleware: failed to get session", "error", err)
|
|
http.Redirect(w, r, "/pages/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
if !s.session.IsAuthenticated(sess) {
|
|
s.log.Debug("auth middleware: unauthenticated request",
|
|
"path", r.URL.Path,
|
|
"method", r.Method,
|
|
)
|
|
http.Redirect(w, r, "/pages/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func (s *Middleware) Metrics() func(http.Handler) http.Handler {
|
|
mdlw := ghmm.New(ghmm.Config{
|
|
Recorder: metrics.NewRecorder(metrics.Config{}),
|
|
})
|
|
return func(next http.Handler) http.Handler {
|
|
return std.Handler("", mdlw, next)
|
|
}
|
|
}
|
|
|
|
func (s *Middleware) MetricsAuth() func(http.Handler) http.Handler {
|
|
return basicauth.New(
|
|
"metrics",
|
|
map[string][]string{
|
|
s.params.Config.MetricsUsername: {
|
|
s.params.Config.MetricsPassword,
|
|
},
|
|
},
|
|
)
|
|
}
|
|
|
|
// 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)
|
|
})
|
|
}
|
|
}
|