middleware.go RawHistoryFolder
1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package httpserver
4
5import (
6 "net/http"
7 "time"
8
9 "github.com/bnema/zerowrap"
10)
11
12// contentSecurityPolicy allows scripts from the origin plus 'unsafe-eval'
13// for htmx attribute expressions; inline scripts stay forbidden.
14const contentSecurityPolicy = "default-src 'self'; script-src 'self' 'unsafe-eval'; frame-ancestors 'none'"
15
16// withSecurityHeaders sets the security headers on every response, before
17// the handler runs, so that errors and 404s carry them too.
18func withSecurityHeaders(next http.Handler) http.Handler {
19 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
20 h := w.Header()
21 h.Set("Content-Security-Policy", contentSecurityPolicy)
22 h.Set("X-Frame-Options", "DENY")
23 h.Set("X-Content-Type-Options", "nosniff")
24 h.Set("Referrer-Policy", "same-origin")
25 next.ServeHTTP(w, r)
26 })
27}
28
29// statusRecorder remembers the status code of a response.
30type statusRecorder struct {
31 http.ResponseWriter
32 status int
33}
34
35func (s *statusRecorder) WriteHeader(code int) {
36 if s.status == 0 {
37 s.status = code
38 }
39 s.ResponseWriter.WriteHeader(code)
40}
41
42func (s *statusRecorder) Write(b []byte) (int, error) {
43 if s.status == 0 {
44 s.status = http.StatusOK
45 }
46 return s.ResponseWriter.Write(b)
47}
48
49// Flush lets streaming handlers (Connect server streams require an
50// http.Flusher) push their messages out as they are written.
51func (s *statusRecorder) Flush() {
52 if s.status == 0 {
53 s.status = http.StatusOK
54 }
55 if f, ok := s.ResponseWriter.(http.Flusher); ok {
56 f.Flush()
57 }
58}
59
60// Unwrap lets http.ResponseController reach Flush and friends.
61func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
62
63// withRequestLog logs method, path, status and duration at debug level. It
64// never logs the query string or any header: they can carry credentials.
65func withRequestLog(next http.Handler) http.Handler {
66 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
67 start := time.Now()
68 rec := &statusRecorder{ResponseWriter: w}
69 next.ServeHTTP(rec, r)
70 status := rec.status
71 if status == 0 {
72 status = http.StatusOK
73 }
74 log := zerowrap.FromCtx(r.Context())
75 log.Debug().
76 Str("method", r.Method).
77 Str("path", r.URL.Path).
78 Int("status", status).
79 Dur("duration", time.Since(start)).
80 Msg("request")
81 })
82}