From c485d1a96f781c977ec451ca205de3a49afb1462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 00:20:57 +0100 Subject: [PATCH] feat(platform): tag requests, logs and api errors with a request id A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is generated. The ID is echoed in the response header, added to every log record written with the request context and returned in API error bodies. Closes #44 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/api/server.go | 17 ++++++--- internal/platform/log.go | 36 ++++++++++++++++-- internal/platform/log_test.go | 33 ++++++++++++++++ internal/platform/router.go | 8 ++-- internal/requestid/requestid.go | 53 ++++++++++++++++++++++++++ internal/requestid/requestid_test.go | 56 ++++++++++++++++++++++++++++ 6 files changed, 191 insertions(+), 12 deletions(-) create mode 100644 internal/platform/log_test.go create mode 100644 internal/requestid/requestid.go create mode 100644 internal/requestid/requestid_test.go diff --git a/internal/api/server.go b/internal/api/server.go index 56d6948..537a894 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -14,6 +14,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" @@ -130,17 +131,20 @@ func (s *Server) setLocale(c *gin.Context) { } type apiError struct { - Error string `json:"error"` - Message string `json:"message"` - Fields map[string]string `json:"fields,omitempty"` + Error string `json:"error"` + Message string `json:"message"` + Fields map[string]string `json:"fields,omitempty"` + RequestID string `json:"request_id,omitempty"` } // fail aborts with a machine-readable code and a message translated from // the catalog entry "error.". kv fills placeholders in that message. func fail(c *gin.Context, status int, code string, kv ...any) { + ctx := c.Request.Context() c.AbortWithStatusJSON(status, apiError{ - Error: code, - Message: i18n.T(c.Request.Context(), "error."+code, kv...), + Error: code, + Message: i18n.T(ctx, "error."+code, kv...), + RequestID: requestid.FromContext(ctx), }) } @@ -154,7 +158,8 @@ func bind(c *gin.Context, dst any) bool { if err == nil { return true } - e := apiError{Error: "invalid_input", Message: i18n.T(c.Request.Context(), "error.invalid_input")} + ctx := c.Request.Context() + e := apiError{Error: "invalid_input", Message: i18n.T(ctx, "error.invalid_input"), RequestID: requestid.FromContext(ctx)} var ve validator.ValidationErrors if errors.As(err, &ve) { e.Fields = map[string]string{} diff --git a/internal/platform/log.go b/internal/platform/log.go index 5592947..640fed1 100644 --- a/internal/platform/log.go +++ b/internal/platform/log.go @@ -1,19 +1,49 @@ package platform import ( + "context" + "io" "log/slog" "os" "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" ) // NewLogger returns a JSON logger tagged with component and the release // version, and the level variable controlling it. The level can be changed // once configuration is loaded; the logger is needed before that to report // configuration errors. +// +// Records logged with a request context carry its request_id, so handlers +// should prefer the *Context logging methods. func NewLogger(component string) (*slog.Logger, *slog.LevelVar) { + return newLogger(os.Stderr, component) +} + +func newLogger(w io.Writer, component string) (*slog.Logger, *slog.LevelVar) { level := new(slog.LevelVar) - l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})). - With("component", component, "app_version", buildinfo.Version) - return l, level + h := contextHandler{slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level})} + return slog.New(h).With("component", component, "app_version", buildinfo.Version), level +} + +// contextHandler adds attributes carried in the context to each record. +type contextHandler struct{ slog.Handler } + +// Handle implements slog.Handler. +func (h contextHandler) Handle(ctx context.Context, r slog.Record) error { + if id := requestid.FromContext(ctx); id != "" { + r.AddAttrs(slog.String("request_id", id)) + } + return h.Handler.Handle(ctx, r) +} + +// WithAttrs keeps the wrapper so derived loggers still add the request ID. +func (h contextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return contextHandler{h.Handler.WithAttrs(attrs)} +} + +// WithGroup keeps the wrapper so derived loggers still add the request ID. +func (h contextHandler) WithGroup(name string) slog.Handler { + return contextHandler{h.Handler.WithGroup(name)} } diff --git a/internal/platform/log_test.go b/internal/platform/log_test.go new file mode 100644 index 0000000..84e4ef1 --- /dev/null +++ b/internal/platform/log_test.go @@ -0,0 +1,33 @@ +package platform + +import ( + "bytes" + "context" + "encoding/json" + "testing" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" +) + +func TestLoggerAddsRequestID(t *testing.T) { + var buf bytes.Buffer + log, _ := newLogger(&buf, "test") + log = log.With("extra", 1) + + log.InfoContext(requestid.NewContext(context.Background(), "abc"), "with id") + log.InfoContext(context.Background(), "without id") + + dec := json.NewDecoder(&buf) + for _, want := range []any{"abc", nil} { + var rec map[string]any + if err := dec.Decode(&rec); err != nil { + t.Fatalf("decoding log line: %v", err) + } + if got := rec["request_id"]; got != want { + t.Errorf("%q: request_id = %v, want %v", rec["msg"], got, want) + } + if rec["extra"] != float64(1) || rec["component"] != "test" { + t.Errorf("%q: lost attributes from With: %v", rec["msg"], rec) + } + } +} diff --git a/internal/platform/router.go b/internal/platform/router.go index 2dd1219..d9fae7c 100644 --- a/internal/platform/router.go +++ b/internal/platform/router.go @@ -8,18 +8,20 @@ import ( "time" "github.com/gin-gonic/gin" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" ) var quietPaths = map[string]bool{"/healthz": true, "/readyz": true} -// NewRouter returns a gin engine that logs requests and panics through log -// as JSON and writes nothing to stdout itself. +// NewRouter returns a gin engine that assigns request IDs, logs requests and +// panics through log as JSON and writes nothing to stdout itself. func NewRouter(log *slog.Logger) *gin.Engine { gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = io.Discard gin.DefaultErrorWriter = io.Discard r := gin.New() - r.Use(accessLog(log), recovery(log)) + r.Use(requestid.Middleware(), accessLog(log), recovery(log)) return r } diff --git a/internal/requestid/requestid.go b/internal/requestid/requestid.go new file mode 100644 index 0000000..f288d62 --- /dev/null +++ b/internal/requestid/requestid.go @@ -0,0 +1,53 @@ +// Package requestid assigns every HTTP request an ID that ties together the +// response, all log lines written for it and error reports from users. +package requestid + +import ( + "context" + "regexp" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +// Header carries the ID in both directions. +const Header = "X-Request-ID" + +// Incoming IDs end up in logs and response headers, so anything beyond a +// conservative token alphabet is replaced rather than passed through. +var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +type ctxKey struct{} + +// NewContext returns ctx carrying id. +func NewContext(ctx context.Context, id string) context.Context { + return context.WithValue(ctx, ctxKey{}, id) +} + +// FromContext returns the request ID in ctx, or "" outside a request. +func FromContext(ctx context.Context) string { + id, _ := ctx.Value(ctxKey{}).(string) + return id +} + +// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us +// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival. +// It must run before any middleware that logs. +func Middleware() gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader(Header) + if !valid.MatchString(id) { + id = newID() + } + c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id)) + c.Header(Header, id) + c.Next() + } +} + +func newID() string { + if id, err := uuid.NewV7(); err == nil { + return id.String() + } + return uuid.NewString() +} diff --git a/internal/requestid/requestid_test.go b/internal/requestid/requestid_test.go new file mode 100644 index 0000000..1af7f61 --- /dev/null +++ b/internal/requestid/requestid_test.go @@ -0,0 +1,56 @@ +package requestid + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +func TestMiddleware(t *testing.T) { + tests := []struct { + name string + incoming string + keep bool + }{ + {name: "none", incoming: "", keep: false}, + {name: "uuid from proxy", incoming: "0b9a7c3e-6a43-4d2c-9a55-2f3b1c0d4e5f", keep: true}, + {name: "trace style", incoming: "Root=1-5759e988-bd862e3fe1be46a994272793", keep: false}, + {name: "opaque token", incoming: "edge:abc.123_X", keep: true}, + {name: "header injection", incoming: "abc\r\nSet-Cookie: x=y", keep: false}, + {name: "too long", incoming: strings.Repeat("a", 129), keep: false}, + } + gin.SetMode(gin.TestMode) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var seen string + r := gin.New() + r.Use(Middleware()) + r.GET("/", func(c *gin.Context) { seen = FromContext(c.Request.Context()) }) + + req := httptest.NewRequest(http.MethodGet, "/", nil) + if tt.incoming != "" { + req.Header.Set(Header, tt.incoming) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + + got := w.Header().Get(Header) + if got != seen { + t.Errorf("response header %q != context ID %q", got, seen) + } + if tt.keep { + if got != tt.incoming { + t.Errorf("ID = %q, want incoming %q", got, tt.incoming) + } + return + } + if u, err := uuid.Parse(got); err != nil || u.Version() != 7 { + t.Errorf("ID = %q, want generated UUIDv7", got) + } + }) + } +}