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