navid/veinsforge / 9105e567134e5c49bcfe0c981d5cfc06b419c388c6c73672413cc67f2f7f6c59 / internal/web/middleware.go
middleware.go
← internal/web · 7559 bytes · raw · download
package web
import (
"context"
"crypto/subtle"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"veinsforge/internal/auth"
"veinsforge/internal/data"
)
const (
sessionCookie = "veinsforge_session"
csrfCookie = "veinsforge_csrf"
)
func (s *Server) recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
s.logger.Printf("panic serving %s %s: %v", r.Method, r.URL.Path, rec)
s.renderError(w, r, http.StatusInternalServerError, "Internal server error.")
}
}()
next.ServeHTTP(w, r)
})
}
func (s *Server) security(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Permissions-Policy", "geolocation=(), camera=(), microphone=()")
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'")
if s.cfg.SecureCookies {
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
next.ServeHTTP(w, r)
})
}
func (s *Server) limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := s.clientIP(r)
r = r.WithContext(context.WithValue(r.Context(), ipKey, ip))
class := "general"
switch {
case r.Method != http.MethodGet && r.Method != http.MethodHead:
class = "write"
}
if r.URL.Path == "/login" || r.URL.Path == "/signup" {
class = "auth"
}
if !s.limiter.Allow(ip, class) {
w.Header().Set("Retry-After", "60")
s.renderError(w, r, http.StatusTooManyRequests, "Too many requests. Slow down.")
return
}
select {
case s.sem <- struct{}{}:
defer func() { <-s.sem }()
default:
w.Header().Set("Retry-After", "5")
s.renderError(w, r, http.StatusServiceUnavailable, "The forge is busy. Try again shortly.")
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodPost {
w.Header().Set("Allow", "GET, HEAD, POST")
s.renderError(w, r, http.StatusMethodNotAllowed, "Method not allowed.")
return
}
if len(r.URL.Path) > 2048 {
s.renderError(w, r, http.StatusRequestURITooLong, "Request path is too long.")
return
}
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes+(2<<20))
next.ServeHTTP(w, r)
})
}
func (s *Server) loadSession(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(sessionCookie)
if err == nil && cookie.Value != "" {
sess, err := s.data.GetSession(r.Context(), auth.HashToken(cookie.Value))
if err == nil {
r = r.WithContext(context.WithValue(r.Context(), userKey, sess.User))
r = r.WithContext(context.WithValue(r.Context(), sessionKey, &requestSession{ID: sess.ID, CSRF: sess.CSRF}))
if time.Since(sess.LastSeenAt) > time.Hour {
s.data.TouchSession(context.Background(), sess.ID)
}
} else {
s.clearSessionCookie(w)
}
}
next.ServeHTTP(w, r)
})
}
func (s *Server) withCSRF(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess := sessionFrom(r)
var expected string
if sess != nil {
expected = sess.CSRF
} else if c, err := r.Cookie(csrfCookie); err == nil {
expected = c.Value
}
if r.Method == http.MethodGet || r.Method == http.MethodHead {
if expected == "" {
token, err := auth.RandomToken(32)
if err == nil {
expected = token
http.SetCookie(w, &http.Cookie{
Name: csrfCookie,
Value: token,
Path: "/",
HttpOnly: true,
Secure: s.cfg.SecureCookies,
SameSite: http.SameSiteLaxMode,
MaxAge: 7 * 24 * 3600,
})
}
}
r = r.WithContext(context.WithValue(r.Context(), csrfKey, expected))
next.ServeHTTP(w, r)
return
}
if r.Method != http.MethodPost {
next.ServeHTTP(w, r)
return
}
if expected == "" {
s.renderError(w, r, http.StatusForbidden, "Missing CSRF token. Reload the page and try again.")
return
}
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data") {
if err := r.ParseMultipartForm(1 << 20); err != nil {
s.renderError(w, r, http.StatusBadRequest, "Upload is too large or malformed.")
return
}
if r.MultipartForm != nil {
defer r.MultipartForm.RemoveAll()
}
} else if err := r.ParseForm(); err != nil {
s.renderError(w, r, http.StatusBadRequest, "Malformed form body.")
return
}
got := r.FormValue("csrf")
if subtle.ConstantTimeCompare([]byte(got), []byte(expected)) != 1 {
s.renderError(w, r, http.StatusForbidden, "Invalid CSRF token. Reload the page and try again.")
return
}
r = r.WithContext(context.WithValue(r.Context(), csrfKey, expected))
next.ServeHTTP(w, r)
})
}
func (s *Server) clientIP(r *http.Request) string {
remote := r.RemoteAddr
if host, _, err := net.SplitHostPort(remote); err == nil {
remote = host
}
ip := net.ParseIP(remote)
if ip == nil {
return truncateString(remote, 64)
}
if !s.isTrusted(ip) {
return ip.String()
}
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
parts := strings.Split(xff, ",")
for i := len(parts) - 1; i >= 0; i-- {
candidate := strings.TrimSpace(parts[i])
parsed := net.ParseIP(candidate)
if parsed == nil {
continue
}
if s.isTrusted(parsed) {
continue
}
return parsed.String()
}
}
if real := strings.TrimSpace(r.Header.Get("X-Real-IP")); real != "" {
if parsed := net.ParseIP(real); parsed != nil {
return parsed.String()
}
}
return ip.String()
}
func (s *Server) isTrusted(ip net.IP) bool {
for _, block := range s.trusted {
if block.Contains(ip) {
return true
}
}
return false
}
func (s *Server) setSessionCookie(w http.ResponseWriter, token string) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
Value: token,
Path: "/",
HttpOnly: true,
Secure: s.cfg.SecureCookies,
SameSite: http.SameSiteLaxMode,
MaxAge: int(s.cfg.SessionTTL.Seconds()),
Expires: time.Now().Add(s.cfg.SessionTTL),
})
}
func (s *Server) clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookie,
Value: "",
Path: "/",
HttpOnly: true,
Secure: s.cfg.SecureCookies,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
Expires: time.Unix(1, 0),
})
}
func (s *Server) requireUser(w http.ResponseWriter, r *http.Request) *data.User {
u := userFrom(r)
if u == nil {
next := url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, "/login?next="+next, http.StatusSeeOther)
return nil
}
return u
}
func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) *data.User {
u := s.requireUser(w, r)
if u == nil {
return nil
}
if !u.IsAdmin {
s.renderError(w, r, http.StatusForbidden, "Administrator access required.")
return nil
}
return u
}
func truncateString(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}
func sameOriginReferer(r *http.Request) bool {
ref := r.Referer()
if ref == "" {
return true
}
u, err := url.Parse(ref)
if err != nil {
return false
}
return u.Host == "" || u.Host == r.Host
}
var _ = fmt.Sprintf