diff --git a/modules/caddyhttp/tracing/module_test.go b/modules/caddyhttp/tracing/module_test.go index 2a775fc18b2..b2d4c978463 100644 --- a/modules/caddyhttp/tracing/module_test.go +++ b/modules/caddyhttp/tracing/module_test.go @@ -3,6 +3,7 @@ package tracing import ( "context" "errors" + "fmt" "net/http" "net/http/httptest" "strings" @@ -121,6 +122,11 @@ func TestTracing_ServeHTTP_Propagation_Without_Initial_Headers(t *testing.T) { if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } + + responseTraceParent := w.Header().Get("Traceparent") + if responseTraceParent == "" { + t.Errorf("Missing traceparent in response headers") + } } func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) { @@ -128,13 +134,14 @@ func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) { SpanName: "mySpan", } + dummyTraceParentPrefix := "00-11111111111111111111111111111111" req := createRequestWithContext("GET", "https://example.com/foo") - req.Header.Set("traceparent", "00-11111111111111111111111111111111-1111111111111111-01") + req.Header.Set("traceparent", fmt.Sprintf("%s-1111111111111111-01", dummyTraceParentPrefix)) w := httptest.NewRecorder() var handler caddyhttp.HandlerFunc = func(writer http.ResponseWriter, request *http.Request) error { traceparent := request.Header.Get("Traceparent") - if !strings.HasPrefix(traceparent, "00-11111111111111111111111111111111") { + if !strings.HasPrefix(traceparent, dummyTraceParentPrefix) { t.Errorf("Invalid traceparent: %v", traceparent) } @@ -152,6 +159,17 @@ func TestTracing_ServeHTTP_Propagation_With_Initial_Headers(t *testing.T) { if err := ot.ServeHTTP(w, req, handler); err != nil { t.Errorf("ServeHTTP error: %v", err) } + + responseTraceParent := w.Header().Get("Traceparent") + if responseTraceParent == "" { + t.Error("Missing traceparent in response headers") + } else if !strings.HasPrefix(responseTraceParent, dummyTraceParentPrefix) { + t.Errorf( + "Traceparent prefix in response headers (%s) not same as initial (%s)", + responseTraceParent, + dummyTraceParentPrefix, + ) + } } func TestTracing_ServeHTTP_Next_Error(t *testing.T) { diff --git a/modules/caddyhttp/tracing/tracer.go b/modules/caddyhttp/tracing/tracer.go index 261952aa65e..3c0df1ea1e5 100644 --- a/modules/caddyhttp/tracing/tracer.go +++ b/modules/caddyhttp/tracing/tracer.go @@ -93,6 +93,8 @@ func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request caddyhttp.SetVar(ctx, "trace_id", traceID) // Add a span_id placeholder, accessible via `{http.vars.span_id}`. caddyhttp.SetVar(ctx, "span_id", spanID) + // Add traceId and spanId to response headers + w.Header().Set("traceparent", fmt.Sprintf("00-%s-%s-01", traceID, spanID)) // Add the traceID and spanID to the log fields for the request. if extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok { extra.Add(zap.String("traceID", traceID))