middleware.go RawHistoryFolder
1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package httpserver
4
5import (
6 "net/http"
7 "net/url"
8 "path"
9 "strings"
10 "time"
11
12 "github.com/bnema/zerowrap"
13
14 "bnema.dev/ermite/internal/mediapolicy"
15)
16
17// contentSecurityPolicy allows scripts from the origin plus 'unsafe-eval'
18// for htmx attribute expressions; inline scripts stay forbidden. Forms post
19// to the origin only, <base> and plugins are off.
20const contentSecurityPolicy = "default-src 'self'; script-src 'self' 'unsafe-eval'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'"
21
22// hstsValue is one year. No includeSubDomains or preload: the server cannot
23// speak for the rest of the domain.
24const hstsValue = "max-age=31536000"
25
26// isHTTPS reports whether the public URL is an https:// URL.
27func isHTTPS(publicURL string) bool {
28 u, err := url.Parse(publicURL)
29 return err == nil && strings.EqualFold(u.Scheme, "https")
30}
31
32// withSecurityHeaders sets the security headers on every response, before
33// the handler runs, so that errors and 404s carry them too. With hsts, the
34// browser is told to stay on https.
35func withSecurityHeaders(next http.Handler, hsts bool, hosts []string) http.Handler {
36 csp := contentSecurityPolicy + "; media-src 'self' " + mediapolicy.Sources(hosts)
37 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38 h := w.Header()
39 h.Set("Content-Security-Policy", csp)
40 h.Set("X-Frame-Options", "DENY")
41 h.Set("X-Content-Type-Options", "nosniff")
42 h.Set("Referrer-Policy", "same-origin")
43 if hsts {
44 h.Set("Strict-Transport-Security", hstsValue)
45 }
46 next.ServeHTTP(w, r)
47 })
48}
49
50// statusRecorder remembers the status code of a response.
51type statusRecorder struct {
52 http.ResponseWriter
53 status int
54}
55
56func (s *statusRecorder) WriteHeader(code int) {
57 if s.status == 0 {
58 s.status = code
59 }
60 s.ResponseWriter.WriteHeader(code)
61}
62
63func (s *statusRecorder) Write(b []byte) (int, error) {
64 if s.status == 0 {
65 s.status = http.StatusOK
66 }
67 return s.ResponseWriter.Write(b)
68}
69
70// Flush lets streaming handlers (Connect server streams require an
71// http.Flusher) push their messages out as they are written.
72func (s *statusRecorder) Flush() {
73 if s.status == 0 {
74 s.status = http.StatusOK
75 }
76 if f, ok := s.ResponseWriter.(http.Flusher); ok {
77 f.Flush()
78 }
79}
80
81// Unwrap lets http.ResponseController reach Flush and friends.
82func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
83
84// loginPathPrefix is where the web serves one-time login links: the rest of
85// the path is a secret.
86const loginPathPrefix = "/-/login/"
87
88// loggedPath is the path of a request as the log may show it. The check is
89// wide on purpose: a path that only reaches the link after cleaning
90// ("/x/../-/login/…", "//-/login/…") or holds the prefix further in is cut too.
91func loggedPath(p string) string {
92 if strings.HasPrefix(path.Clean(p), loginPathPrefix) || strings.Contains(p, loginPathPrefix) {
93 return loginPathPrefix + "…"
94 }
95 return p
96}
97
98// withRequestLog logs method, path, status and duration at debug level. It
99// never logs the query string or any header: they can carry credentials. The
100// secret of a login link is cut from the path.
101func withRequestLog(next http.Handler) http.Handler {
102 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
103 start := time.Now()
104 rec := &statusRecorder{ResponseWriter: w}
105 next.ServeHTTP(rec, r)
106 status := rec.status
107 if status == 0 {
108 status = http.StatusOK
109 }
110 log := zerowrap.FromCtx(r.Context())
111 log.Debug().
112 Str("method", r.Method).
113 Str("path", loggedPath(r.URL.Path)).
114 Int("status", status).
115 Dur("duration", time.Since(start)).
116 Msg("request")
117 })
118}