From a402c4bd324432301623c09e9415494f19e49b46 Mon Sep 17 00:00:00 2001 From: Andrew Wilkins Date: Wed, 21 Jun 2023 14:50:07 +0800 Subject: [PATCH] Fix data race accessing Request.URL (#1472) If an HTTP client is instrumented with apmhttp, then the http.Request.URL is recorded for including in span context. The caller of the HTTP client request may mutate the URL after the response is ready, so we must clone the URL while recording it to prevent data races. --- spancontext.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/spancontext.go b/spancontext.go index 38ced9261..90390d004 100644 --- a/spancontext.go +++ b/spancontext.go @@ -196,7 +196,15 @@ func (c *SpanContext) SetHTTPRequest(req *http.Request) { if req.URL == nil { return } - c.http.URL = req.URL + + // Clone the URL, since callers of http.RoundTrip may mutate the + // Request after the response body is closed. + clonedURL := *req.URL + if req.URL.User != nil { + clonedURLUser := *req.URL.User + clonedURL.User = &clonedURLUser + } + c.http.URL = &clonedURL c.model.HTTP = &c.http addr, port := apmhttputil.DestinationAddr(req)