Repository Public
1// Package httpx holds HTTP plumbing shared by the services: structured2// errors, correlation ids, client address resolution, security headers.3package httpx45import (6 "context"7 "encoding/json"8 "errors"9 "log/slog"10 "net"11 "net/http"12 "net/netip"13 "strings"14 "time"1516 "github.com/google/uuid"17)1819type ctxKey int2021const (22 keyCorrelation ctxKey = iota23 keyClientIP24)2526// Error is the structured API error. Code is stable and machine-readable.27type Error struct {28 Status int `json:"-"`29 Code string `json:"code"`30 Message string `json:"message"`31 Details map[string]any `json:"details,omitempty"`32 // RetryAfter, when > 0, is sent as a Retry-After header (seconds).33 RetryAfter int `json:"-"`34}3536func (e *Error) Error() string { return e.Code + ": " + e.Message }3738func Err(status int, code, message string) *Error {39 return &Error{Status: status, Code: code, Message: message}40}4142func (e *Error) With(k string, v any) *Error {43 c := *e44 c.Details = map[string]any{}45 for dk, dv := range e.Details {46 c.Details[dk] = dv47 }48 c.Details[k] = v49 return &c50}5152var (53 ErrUnauthenticated = Err(http.StatusUnauthorized, "unauthenticated", "Authentication is required.")54 ErrForbidden = Err(http.StatusForbidden, "forbidden", "You do not have permission to do this.")55 ErrStepUp = Err(http.StatusForbidden, "step_up_required", "A recent passkey verification is required.")56 ErrCSRF = Err(http.StatusForbidden, "csrf_failed", "Cross-site request check failed.")57 ErrNotFound = Err(http.StatusNotFound, "not_found", "The resource does not exist.")58 ErrRateLimited = Err(http.StatusTooManyRequests, "rate_limited", "Too many requests.")59 ErrNotImplemented = Err(http.StatusNotImplemented, "not_implemented", "This operation is not available.")60 ErrUnavailable = Err(http.StatusServiceUnavailable, "unavailable", "The service is temporarily unavailable.")61)6263func Validation(message string) *Error {64 return Err(http.StatusBadRequest, "validation_failed", message)65}6667func Conflict(code, message string) *Error { return Err(http.StatusConflict, code, message) }6869type errorBody struct {70 Error struct {71 Code string `json:"code"`72 Message string `json:"message"`73 Details map[string]any `json:"details,omitempty"`74 CorrelationID string `json:"correlation_id"`75 } `json:"error"`76}7778// WriteError renders any error. Unknown errors become an opaque 500: internal79// messages are logged with the correlation id, never returned to the client.80func WriteError(w http.ResponseWriter, r *http.Request, err error) {81 var e *Error82 if !errors.As(err, &e) {83 slog.ErrorContext(r.Context(), "internal error", "err", err, "correlation_id", Correlation(r.Context()),84 "method", r.Method, "path", r.URL.Path)85 e = Err(http.StatusInternalServerError, "internal", "An internal error occurred.")86 }87 var body errorBody88 body.Error.Code, body.Error.Message, body.Error.Details = e.Code, e.Message, e.Details89 body.Error.CorrelationID = Correlation(r.Context()).String()90 if e.RetryAfter > 0 {91 w.Header().Set("Retry-After", itoa(e.RetryAfter))92 }93 WriteJSON(w, e.Status, body)94}9596func WriteJSON(w http.ResponseWriter, status int, v any) {97 w.Header().Set("Content-Type", "application/json; charset=utf-8")98 w.Header().Set("Cache-Control", "no-store")99 w.WriteHeader(status)100 json.NewEncoder(w).Encode(v)101}102103// DecodeJSON reads a bounded JSON body and rejects unknown fields and trailing data.104func DecodeJSON(w http.ResponseWriter, r *http.Request, max int64, dst any) error {105 if ct := r.Header.Get("Content-Type"); ct != "" && !strings.HasPrefix(ct, "application/json") {106 return Err(http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json.")107 }108 dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, max))109 dec.DisallowUnknownFields()110 if err := dec.Decode(dst); err != nil {111 return Validation("Malformed JSON body.")112 }113 if dec.More() {114 return Validation("Unexpected data after JSON body.")115 }116 return nil117}118119// Correlation returns the request's correlation id (uuid.Nil outside a request).120func Correlation(ctx context.Context) uuid.UUID {121 id, _ := ctx.Value(keyCorrelation).(uuid.UUID)122 return id123}124125// ClientIP returns the resolved client address, if any.126func ClientIP(ctx context.Context) (netip.Addr, bool) {127 ip, ok := ctx.Value(keyClientIP).(netip.Addr)128 return ip, ok129}130131// WithRequestContext assigns a correlation id (always server-generated: a132// client-supplied id is never trusted as the audit key) and resolves the133// client IP, honouring X-Forwarded-For only when the peer is a trusted proxy.134func WithRequestContext(trustedProxies []string, next http.Handler) http.Handler {135 trusted := parsePrefixes(trustedProxies)136 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {137 id := uuid.New()138 ctx := context.WithValue(r.Context(), keyCorrelation, id)139 if ip, ok := resolveIP(r, trusted); ok {140 ctx = context.WithValue(ctx, keyClientIP, ip)141 }142 w.Header().Set("X-Correlation-Id", id.String())143 next.ServeHTTP(w, r.WithContext(ctx))144 })145}146147func parsePrefixes(in []string) []netip.Prefix {148 var out []netip.Prefix149 for _, s := range in {150 if p, err := netip.ParsePrefix(s); err == nil {151 out = append(out, p)152 } else if a, err := netip.ParseAddr(s); err == nil {153 out = append(out, netip.PrefixFrom(a, a.BitLen()))154 }155 }156 return out157}158159func resolveIP(r *http.Request, trusted []netip.Prefix) (netip.Addr, bool) {160 host, _, err := net.SplitHostPort(r.RemoteAddr)161 if err != nil {162 host = r.RemoteAddr163 }164 peer, err := netip.ParseAddr(host)165 if err != nil {166 return netip.Addr{}, false167 }168 peer = peer.Unmap()169 if !contains(trusted, peer) {170 return peer, true171 }172 // Walk X-Forwarded-For right to left; the first untrusted hop is the client.173 parts := strings.Split(r.Header.Get("X-Forwarded-For"), ",")174 for i := len(parts) - 1; i >= 0; i-- {175 a, err := netip.ParseAddr(strings.TrimSpace(parts[i]))176 if err != nil {177 break178 }179 a = a.Unmap()180 if !contains(trusted, a) {181 return a, true182 }183 }184 return peer, true185}186187func contains(ps []netip.Prefix, a netip.Addr) bool {188 for _, p := range ps {189 if p.Contains(a) {190 return true191 }192 }193 return false194}195196// SecurityHeaders sets headers appropriate for JSON API responses. The web197// app sets its own nonce-based CSP for HTML.198func SecurityHeaders(secure bool, next http.Handler) http.Handler {199 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {200 h := w.Header()201 h.Set("X-Content-Type-Options", "nosniff")202 h.Set("Referrer-Policy", "no-referrer")203 h.Set("X-Frame-Options", "DENY")204 h.Set("Cross-Origin-Opener-Policy", "same-origin")205 h.Set("Cross-Origin-Resource-Policy", "same-origin")206 h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")207 if secure {208 h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")209 }210 next.ServeHTTP(w, r)211 })212}213214// Recover turns a handler panic into a logged 500 instead of a dropped connection.215func Recover(next http.Handler) http.Handler {216 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {217 defer func() {218 if v := recover(); v != nil {219 if v == http.ErrAbortHandler {220 panic(v)221 }222 slog.ErrorContext(r.Context(), "panic", "value", v, "correlation_id", Correlation(r.Context()), "path", r.URL.Path)223 WriteError(w, r, errors.New("panic"))224 }225 }()226 next.ServeHTTP(w, r)227 })228}229230// AccessLog writes one structured line per request. Query strings are not231// logged (they may carry cursors or filters, never secrets, but stay out by policy).232func AccessLog(next http.Handler) http.Handler {233 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {234 start := time.Now()235 sw := &statusWriter{ResponseWriter: w, status: 200}236 next.ServeHTTP(sw, r)237 ip, _ := ClientIP(r.Context())238 slog.InfoContext(r.Context(), "http", "method", r.Method, "path", r.URL.Path, "status", sw.status,239 "ms", time.Since(start).Milliseconds(), "ip", ip.String(), "correlation_id", Correlation(r.Context()))240 })241}242243type statusWriter struct {244 http.ResponseWriter245 status int246}247248func (s *statusWriter) WriteHeader(c int) { s.status = c; s.ResponseWriter.WriteHeader(c) }249func (s *statusWriter) Flush() {250 if f, ok := s.ResponseWriter.(http.Flusher); ok {251 f.Flush()252 }253}254func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }255256func itoa(n int) string {257 if n == 0 {258 return "0"259 }260 var b [12]byte261 i := len(b)262 for n > 0 {263 i--264 b[i] = byte('0' + n%10)265 n /= 10266 }267 return string(b[i:])268}269