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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
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)
|
|
}
|
|
})
|
|
}
|
|
}
|