1// Package middleware provides HTTP middleware for the adapters layer.
2package middleware
3
4import (
5 "crypto/rand"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "net"
10 "net/http"
11 "sync/atomic"
12 "time"
13
14 "github.com/bnema/zerowrap"
15 "go.opentelemetry.io/otel/trace"
16
17 "github.com/bnema/gordon/internal/adapters/dto"
18)
19
20// ResponseWriter wraps http.ResponseWriter to capture status code and bytes written.
21type ResponseWriter struct {
22 http.ResponseWriter
23 statusCode int
24 bytes int
25}
26
27// NewResponseWriter creates a new wrapped response writer.
28func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
29 return &ResponseWriter{
30 ResponseWriter: w,
31 statusCode: http.StatusOK, // Default status code
32 }
33}
34
35// WriteHeader captures the status code.
36func (rw *ResponseWriter) WriteHeader(code int) {
37 rw.statusCode = code
38 rw.ResponseWriter.WriteHeader(code)
39}
40
41// Write captures bytes written.
42func (rw *ResponseWriter) Write(b []byte) (int, error) {
43 n, err := rw.ResponseWriter.Write(b)
44 rw.bytes += n
45 return n, err
46}
47
48// StatusCode returns the captured status code.
49func (rw *ResponseWriter) StatusCode() int {
50 return rw.statusCode
51}
52
53// BytesWritten returns the number of bytes written.
54func (rw *ResponseWriter) BytesWritten() int {
55 return rw.bytes
56}
57
58// Flush implements http.Flusher by delegating to the underlying ResponseWriter.
59func (rw *ResponseWriter) Flush() {
60 if f, ok := rw.ResponseWriter.(http.Flusher); ok {
61 f.Flush()
62 }
63}
64
65// Unwrap returns the underlying ResponseWriter.
66func (rw *ResponseWriter) Unwrap() http.ResponseWriter {
67 return rw.ResponseWriter
68}
69
70// ensureRequestID returns the X-Request-ID from the request if present, or generates
71// a new one. It sets X-Request-ID on both the request and response headers and returns
72// the ID along with the (potentially updated) request.
73func ensureRequestID(w http.ResponseWriter, r *http.Request) (string, *http.Request) {
74 requestID := r.Header.Get("X-Request-ID")
75 if requestID == "" {
76 requestID = generateRequestID()
77 r.Header.Set("X-Request-ID", requestID)
78 }
79 w.Header().Set("X-Request-ID", requestID)
80 return requestID, r
81}
82
83// RequestLogger is a middleware that logs HTTP requests using zerowrap.
84// It also attaches the logger to the request context for downstream handlers.
85// The trustedNets parameter controls which proxy headers are trusted for IP extraction.
86// Pass nil to only use RemoteAddr (safest default when not behind a trusted proxy).
87func RequestLogger(log zerowrap.Logger, trustedNets ...[]*net.IPNet) func(http.Handler) http.Handler {
88 var nets []*net.IPNet
89 if len(trustedNets) > 0 {
90 nets = trustedNets[0]
91 }
92 return func(next http.Handler) http.Handler {
93 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
94 start := time.Now()
95
96 // Generate or reuse X-Request-ID for request tracing
97 requestID, r := ensureRequestID(w, r)
98
99 // Wrap the response writer to capture status and bytes
100 rw := NewResponseWriter(w)
101
102 // SECURITY: Use trusted-proxy-aware IP extraction to prevent
103 // IP spoofing via X-Forwarded-For from untrusted sources.
104 clientIP := GetClientIP(r, nets)
105
106 // Attach the logger to the request context for downstream handlers.
107 // If an OTel span is active (from otelhttp middleware), inject
108 // trace_id and span_id into the logger for log↔trace correlation.
109 reqLog := log
110 spanCtx := trace.SpanFromContext(r.Context()).SpanContext()
111 if spanCtx.HasTraceID() {
112 reqLog = reqLog.WithFields(map[string]any{
113 "trace_id": spanCtx.TraceID().String(),
114 "span_id": spanCtx.SpanID().String(),
115 })
116 }
117 ctx := zerowrap.WithCtx(r.Context(), reqLog)
118 r = r.WithContext(ctx)
119
120 // Call the next handler
121 next.ServeHTTP(rw, r)
122
123 // Calculate duration
124 duration := time.Since(start)
125
126 // Log the request (use reqLog to include trace_id/span_id)
127 reqLog.Info().
128 Str(zerowrap.FieldLayer, "adapter").
129 Str(zerowrap.FieldAdapter, "http").
130 Str("request_id", requestID).
131 Str(zerowrap.FieldMethod, r.Method).
132 Str(zerowrap.FieldPath, r.URL.Path).
133 Str("query", sanitizeLoggedQuery(r.URL.RawQuery)).
134 Str(zerowrap.FieldHost, r.Host).
135 Str("user_agent", r.UserAgent()).
136 Str("referer", r.Referer()).
137 Str(zerowrap.FieldClientIP, clientIP).
138 Int(zerowrap.FieldStatus, rw.StatusCode()).
139 Int("bytes", rw.BytesWritten()).
140 Dur(zerowrap.FieldDuration, duration).
141 Str("proto", r.Proto).
142 Msg("HTTP request")
143 })
144 }
145}
146
147// fallbackCounter ensures uniqueness when crypto/rand is unavailable.
148var fallbackCounter atomic.Uint64
149
150// generateRequestID creates a random 16-byte hex-encoded request ID.
151func generateRequestID() string {
152 b := make([]byte, 16)
153 if _, err := rand.Read(b); err != nil {
154 // Fallback to timestamp + monotonic counter if RNG is unavailable
155 return fmt.Sprintf("%x-%x", time.Now().UnixNano(), fallbackCounter.Add(1))
156 }
157 return hex.EncodeToString(b)
158}
159
160// PanicRecovery middleware recovers from panics and logs them.
161func PanicRecovery(log zerowrap.Logger) func(http.Handler) http.Handler {
162 return func(next http.Handler) http.Handler {
163 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
164 defer func() {
165 if err := recover(); err != nil {
166 log.Error().
167 Str(zerowrap.FieldLayer, "adapter").
168 Str(zerowrap.FieldAdapter, "http").
169 Interface("panic", err).
170 Str(zerowrap.FieldMethod, r.Method).
171 Str(zerowrap.FieldPath, r.URL.Path).
172 Str(zerowrap.FieldHost, r.Host).
173 Msg("panic recovered")
174
175 w.Header().Set("Content-Type", "application/json")
176 w.WriteHeader(http.StatusInternalServerError)
177 _ = json.NewEncoder(w).Encode(dto.ErrorResponse{Error: "Internal Server Error"})
178 }
179 }()
180
181 next.ServeHTTP(w, r)
182 })
183 }
184}
185
186// CORS middleware adds permissive CORS headers.
187// NOTE: This is intentionally NOT used on the proxy chain (backends control their own CORS).
188// Available for use on specific endpoints (e.g., registry API) where CORS is needed.
189func CORS(next http.Handler) http.Handler {
190 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
191 w.Header().Set("Access-Control-Allow-Origin", "*")
192 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
193 w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
194
195 // Handle preflight OPTIONS request
196 if r.Method == "OPTIONS" {
197 w.WriteHeader(http.StatusOK)
198 return
199 }
200
201 next.ServeHTTP(w, r)
202 })
203}
204
205// Chain combines multiple middleware functions.
206func Chain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
207 return func(final http.Handler) http.Handler {
208 for i := len(middlewares) - 1; i >= 0; i-- {
209 final = middlewares[i](final)
210 }
211 return final
212 }
213}