v2.30.0 3ee801c

logging.go RawHistoryFolder

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// RequestLogger is a middleware that logs HTTP requests using zerowrap.
71// It also attaches the logger to the request context for downstream handlers.
72// The trustedNets parameter controls which proxy headers are trusted for IP extraction.
73// Pass nil to only use RemoteAddr (safest default when not behind a trusted proxy).
74func RequestLogger(log zerowrap.Logger, trustedNets ...[]*net.IPNet) func(http.Handler) http.Handler {
75	var nets []*net.IPNet
76	if len(trustedNets) > 0 {
77		nets = trustedNets[0]
78	}
79	return func(next http.Handler) http.Handler {
80		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
81			start := time.Now()
82
83			// Generate or reuse X-Request-ID for request tracing
84			requestID := r.Header.Get("X-Request-ID")
85			if requestID == "" {
86				requestID = generateRequestID()
87				// Set on the incoming request so downstream handlers can read it
88				r.Header.Set("X-Request-ID", requestID)
89			}
90			w.Header().Set("X-Request-ID", requestID)
91
92			// Wrap the response writer to capture status and bytes
93			rw := NewResponseWriter(w)
94
95			// SECURITY: Use trusted-proxy-aware IP extraction to prevent
96			// IP spoofing via X-Forwarded-For from untrusted sources.
97			clientIP := GetClientIP(r, nets)
98
99			// Attach the logger to the request context for downstream handlers.
100			// If an OTel span is active (from otelhttp middleware), inject
101			// trace_id and span_id into the logger for log↔trace correlation.
102			reqLog := log
103			spanCtx := trace.SpanFromContext(r.Context()).SpanContext()
104			if spanCtx.HasTraceID() {
105				reqLog = reqLog.WithFields(map[string]any{
106					"trace_id": spanCtx.TraceID().String(),
107					"span_id":  spanCtx.SpanID().String(),
108				})
109			}
110			ctx := zerowrap.WithCtx(r.Context(), reqLog)
111			r = r.WithContext(ctx)
112
113			// Call the next handler
114			next.ServeHTTP(rw, r)
115
116			// Calculate duration
117			duration := time.Since(start)
118
119			// Log the request (use reqLog to include trace_id/span_id)
120			reqLog.Info().
121				Str(zerowrap.FieldLayer, "adapter").
122				Str(zerowrap.FieldAdapter, "http").
123				Str("request_id", requestID).
124				Str(zerowrap.FieldMethod, r.Method).
125				Str(zerowrap.FieldPath, r.URL.Path).
126				Str("query", r.URL.RawQuery).
127				Str(zerowrap.FieldHost, r.Host).
128				Str("user_agent", r.UserAgent()).
129				Str("referer", r.Referer()).
130				Str(zerowrap.FieldClientIP, clientIP).
131				Int(zerowrap.FieldStatus, rw.StatusCode()).
132				Int("bytes", rw.BytesWritten()).
133				Dur(zerowrap.FieldDuration, duration).
134				Str("proto", r.Proto).
135				Msg("HTTP request")
136		})
137	}
138}
139
140// fallbackCounter ensures uniqueness when crypto/rand is unavailable.
141var fallbackCounter atomic.Uint64
142
143// generateRequestID creates a random 16-byte hex-encoded request ID.
144func generateRequestID() string {
145	b := make([]byte, 16)
146	if _, err := rand.Read(b); err != nil {
147		// Fallback to timestamp + monotonic counter if RNG is unavailable
148		return fmt.Sprintf("%x-%x", time.Now().UnixNano(), fallbackCounter.Add(1))
149	}
150	return hex.EncodeToString(b)
151}
152
153// PanicRecovery middleware recovers from panics and logs them.
154func PanicRecovery(log zerowrap.Logger) func(http.Handler) http.Handler {
155	return func(next http.Handler) http.Handler {
156		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
157			defer func() {
158				if err := recover(); err != nil {
159					log.Error().
160						Str(zerowrap.FieldLayer, "adapter").
161						Str(zerowrap.FieldAdapter, "http").
162						Interface("panic", err).
163						Str(zerowrap.FieldMethod, r.Method).
164						Str(zerowrap.FieldPath, r.URL.Path).
165						Str(zerowrap.FieldHost, r.Host).
166						Msg("panic recovered")
167
168					w.Header().Set("Content-Type", "application/json")
169					w.WriteHeader(http.StatusInternalServerError)
170					_ = json.NewEncoder(w).Encode(dto.ErrorResponse{Error: "Internal Server Error"})
171				}
172			}()
173
174			next.ServeHTTP(w, r)
175		})
176	}
177}
178
179// CORS middleware adds permissive CORS headers.
180// NOTE: This is intentionally NOT used on the proxy chain (backends control their own CORS).
181// Available for use on specific endpoints (e.g., registry API) where CORS is needed.
182func CORS(next http.Handler) http.Handler {
183	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
184		w.Header().Set("Access-Control-Allow-Origin", "*")
185		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
186		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
187
188		// Handle preflight OPTIONS request
189		if r.Method == "OPTIONS" {
190			w.WriteHeader(http.StatusOK)
191			return
192		}
193
194		next.ServeHTTP(w, r)
195	})
196}
197
198// Chain combines multiple middleware functions.
199func Chain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
200	return func(final http.Handler) http.Handler {
201		for i := len(middlewares) - 1; i >= 0; i-- {
202			final = middlewares[i](final)
203		}
204		return final
205	}
206}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 7

Tags 106

↑↓ moveenter openesc close