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