All checks were successful
check / check (push) Successful in 6s
Adds a `NoCache()` middleware that sets `Cache-Control: no-store` and `Pragma: no-cache`, and wires it onto the dynamic app route groups (`/pages`, `/user/{username}`, `/sources`, `/source/{sourceID}`) adjacent to their existing `CSRF()` call. The static `/s` mount, `/metrics`, `/webhook/{uuid}`, and `/.well-known/healthcheck` are intentionally left untouched (static assets are safe to cache; the others are not authenticated pages).
A middleware unit test asserts both headers are set.
Closes #61
Co-authored-by: sneak <sneak@sneak.berlin>
Reviewed-on: #75
Co-authored-by: clawbot <clawbot@noreply.example.org>
Co-committed-by: clawbot <clawbot@noreply.example.org>
312 lines
7.6 KiB
Go
312 lines
7.6 KiB
Go
// Package middleware provides HTTP middleware for logging, auth,
|
|
// CORS, and metrics.
|
|
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"
|
|
)
|
|
|
|
const (
|
|
// corsMaxAge is the maximum time (in seconds) that a
|
|
// preflight response can be cached.
|
|
corsMaxAge = 300
|
|
)
|
|
|
|
//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
|
|
}
|
|
|
|
// Middleware provides HTTP middleware for logging, CORS, auth, and
|
|
// metrics.
|
|
type Middleware struct {
|
|
log *slog.Logger
|
|
params *MiddlewareParams
|
|
session *session.Session
|
|
}
|
|
|
|
// New creates a Middleware from the provided fx parameters.
|
|
//
|
|
//nolint:revive // lc parameter is required by fx even if unused.
|
|
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
|
|
}
|
|
|
|
// newLoggingResponseWriter wraps w and records status codes.
|
|
func newLoggingResponseWriter(
|
|
w http.ResponseWriter,
|
|
) *loggingResponseWriter {
|
|
return &loggingResponseWriter{w, http.StatusOK}
|
|
}
|
|
|
|
func (lrw *loggingResponseWriter) WriteHeader(code int) {
|
|
lrw.statusCode = code
|
|
lrw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// Logging returns middleware that logs each HTTP request with
|
|
// timing and metadata.
|
|
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)
|
|
})
|
|
}
|
|
}
|
|
|
|
// CORS returns middleware that sets CORS headers (permissive in
|
|
// dev, no-op in prod).
|
|
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: corsMaxAge,
|
|
})
|
|
}
|
|
|
|
// 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)
|
|
})
|
|
}
|
|
}
|
|
|
|
// Metrics returns middleware that records Prometheus HTTP metrics.
|
|
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)
|
|
}
|
|
}
|
|
|
|
// MetricsAuth returns middleware that protects metrics endpoints
|
|
// with basic auth.
|
|
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)
|
|
})
|
|
}
|
|
}
|
|
|
|
// NoCache returns middleware that instructs browsers and
|
|
// intermediary proxies not to cache the response. It sets
|
|
// Cache-Control: no-store and Pragma: no-cache (the latter for
|
|
// older HTTP/1.0 intermediaries). Apply it to authenticated pages
|
|
// so webhook configuration and captured event data are not stored
|
|
// by caches.
|
|
func (s *Middleware) NoCache() 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("Cache-Control", "no-store")
|
|
w.Header().Set("Pragma", "no-cache")
|
|
|
|
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)
|
|
})
|
|
}
|
|
}
|