feat(backend): server hardening — timeouts, security headers, trusted-proxy client IP (closes #19)
check / check (push) Failing after 0s

Add ReadHeaderTimeout and IdleTimeout to the http.Server (named
constants beside the existing timeouts) to close the slowloris and
idle-keep-alive gaps.

Add a SecurityHeaders middleware setting HSTS, a JSON-API CSP
(default-src 'none'; frame-ancestors 'none'), X-Frame-Options: DENY,
X-Content-Type-Options: nosniff, Referrer-Policy, and Permissions-Policy.
It is registered before CORS so the headers ride on preflight responses.

Resolve the client IP from X-Forwarded-For / X-Real-IP only when the
direct peer is in a trusted-proxy allowlist, defaulting to loopback plus
RFC1918 and configurable via TRUSTED_PROXIES; an untrusted peer's
forwarded headers are ignored and the direct peer is logged. Uses
net/netip; no new dependency.

Model: opus-4-8
This commit is contained in:
2026-09-21 12:49:58 +00:00
parent f7c7f92e27
commit 911dfbb825
8 changed files with 347 additions and 16 deletions
+12 -8
View File
@@ -8,20 +8,24 @@ import (
)
const (
readTimeout = 10 * time.Second
writeTimeout = 10 * time.Second
maxHeaderBytes = 1 << 20 // 1 MiB
readTimeout = 10 * time.Second
readHeaderTimeout = 5 * time.Second
writeTimeout = 10 * time.Second
idleTimeout = 60 * time.Second
maxHeaderBytes = 1 << 20 // 1 MiB
)
func (s *Server) serveUntilShutdown() {
listenAddr := fmt.Sprintf(":%d", s.params.Config.Port)
s.httpServer = &http.Server{
Addr: listenAddr,
Handler: s,
MaxHeaderBytes: maxHeaderBytes,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
Addr: listenAddr,
Handler: s,
MaxHeaderBytes: maxHeaderBytes,
ReadTimeout: readTimeout,
ReadHeaderTimeout: readHeaderTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
}
s.SetupRoutes()