v3.3.0 b164fe9

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

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