Repository navigation
fix(contrib): keep truncated span tags valid UTF-8 in Elasticsearch, OpenSearch and MongoDB #5991
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ajgajg1134
wants to merge
2
commits into
main
Choose a base branch
from
andrew.glaude/elasticsearch-utf8-truncation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
187 changes: 187 additions & 0 deletions
187
contrib/elastic/go-elasticsearch.v6/elastictrace_utf8_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2016 Datadog, Inc. | ||
|
|
||
| package elastic | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "io" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strconv" | ||
| "strings" | ||
| "testing" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/DataDog/dd-trace-go/v2/ddtrace/ext" | ||
| "github.com/DataDog/dd-trace-go/v2/ddtrace/mocktracer" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // multiByteRunes holds one rune of each multi-byte UTF-8 encoding width. | ||
| var multiByteRunes = []string{ | ||
| "é", // U+00E9, 2 bytes | ||
| "€", // U+20AC, 3 bytes | ||
| "😀", // U+1F600, 4 bytes | ||
| } | ||
|
|
||
| // TestPeekUTF8 is a regression test: cutting a valid UTF-8 body at a fixed byte limit must | ||
| // never leave a partial rune at the end of the snippet. | ||
| func TestPeekUTF8(t *testing.T) { | ||
| const prefix = "ab" | ||
| for _, r := range multiByteRunes { | ||
| require.Equal(t, len(r), utf8.RuneLen([]rune(r)[0])) | ||
| // k is the number of bytes of r that fit under the limit. | ||
| for k := 0; k <= len(r); k++ { | ||
| want := prefix | ||
| if k == len(r) { | ||
| want += r | ||
| } | ||
| limit := len(prefix) + k | ||
| body := prefix + r + "cd" | ||
|
|
||
| t.Run("raw/"+strconv.Itoa(len(r))+"-byte/"+strconv.Itoa(k), func(t *testing.T) { | ||
| snip, rc, err := peek(io.NopCloser(strings.NewReader(body)), "", -1, limit) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, want, snip) | ||
| assert.True(t, utf8.ValidString(snip)) | ||
| assert.LessOrEqual(t, len(snip), limit) | ||
| all, err := io.ReadAll(rc) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, body, string(all), "the forwarded body must be unchanged") | ||
| }) | ||
|
|
||
| t.Run("content-length/"+strconv.Itoa(len(r))+"-byte/"+strconv.Itoa(k), func(t *testing.T) { | ||
| // A Content-Length shorter than the cutoff lowers the limit instead. | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader(body)), "", limit, limit+100) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, want, snip) | ||
| }) | ||
|
|
||
| t.Run("gzip/"+strconv.Itoa(len(r))+"-byte/"+strconv.Itoa(k), func(t *testing.T) { | ||
| // The decompressed snippet is cut at the cutoff, not at the compressed length. | ||
| const cutoff = 1024 | ||
| pad := strings.Repeat("a", cutoff-k) | ||
| gz := gzipped(t, []byte(pad+r+strings.Repeat("b", cutoff))) | ||
| require.Less(t, len(gz), cutoff) | ||
|
|
||
| snip, _, err := peek(io.NopCloser(bytes.NewReader(gz)), "gzip", len(gz), cutoff) | ||
| require.NoError(t, err) | ||
| gzWant := pad | ||
| if k == len(r) { | ||
| gzWant += r | ||
| } | ||
| assert.Equal(t, gzWant, snip) | ||
| assert.True(t, utf8.ValidString(snip)) | ||
| }) | ||
| } | ||
|
|
||
| t.Run("not-gzip/"+strconv.Itoa(len(r))+"-byte", func(t *testing.T) { | ||
| // A body labeled gzip that isn't is returned raw, and is cut the same way. | ||
| body := prefix + r + "cd" | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader(body)), "gzip", -1, len(prefix)+1) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, prefix, snip) | ||
| }) | ||
| } | ||
|
|
||
| t.Run("ascii", func(t *testing.T) { | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader("ABCDEFG")), "", -1, 4) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, "ABCD", snip) | ||
| }) | ||
|
|
||
| t.Run("exact boundary", func(t *testing.T) { | ||
| for _, r := range multiByteRunes { | ||
| body := "ab" + r | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader(body)), "", -1, len(body)) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, body, snip) | ||
|
|
||
| snip, _, err = peek(io.NopCloser(strings.NewReader(body)), "", len(body), len(body)) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, body, snip) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("shorter than limit", func(t *testing.T) { | ||
| body := "ab😀" | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader(body)), "", -1, 100) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, body, snip) | ||
| }) | ||
|
|
||
| t.Run("invalid input is not rewritten", func(t *testing.T) { | ||
| // Only a rune cut by the limit is dropped; malformed bytes are left as they were. | ||
| body := "ab\xff\xfe\xfd\xfccd" | ||
| snip, _, err := peek(io.NopCloser(strings.NewReader(body)), "", -1, 6) | ||
| require.NoError(t, err) | ||
| assert.Equal(t, body[:6], snip) | ||
| }) | ||
| } | ||
|
|
||
| // TestRoundTripperUTF8BodyCutoff checks that the elasticsearch.body and error.message tags stay | ||
| // valid UTF-8 when a multi-byte rune straddles bodyCutoff. | ||
| func TestRoundTripperUTF8BodyCutoff(t *testing.T) { | ||
| for _, r := range multiByteRunes { | ||
| for k := 0; k <= len(r); k++ { | ||
| t.Run(strconv.Itoa(len(r))+"-byte/"+strconv.Itoa(k), func(t *testing.T) { | ||
| mt := mocktracer.Start() | ||
| defer mt.Stop() | ||
|
|
||
| body := strings.Repeat("a", bodyCutoff-k) + r + strings.Repeat("b", 64) | ||
| want := bodyCutoff - k | ||
| if k == len(r) { | ||
| want = bodyCutoff | ||
| } | ||
|
|
||
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { | ||
| got, _ := io.ReadAll(req.Body) | ||
| assert.Equal(t, body, string(got), "the forwarded request body must be unchanged") | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| _, _ = io.WriteString(w, body) | ||
| })) | ||
| defer srv.Close() | ||
|
|
||
| req, err := http.NewRequest(http.MethodPost, srv.URL+"/twitter/_search", strings.NewReader(body)) | ||
| require.NoError(t, err) | ||
| res, err := (&http.Client{Transport: NewRoundTripper()}).Do(req) | ||
| require.NoError(t, err) | ||
| got, err := io.ReadAll(res.Body) | ||
| require.NoError(t, err) | ||
| res.Body.Close() | ||
| assert.Equal(t, body, string(got), "the response body must be unchanged") | ||
|
|
||
| spans := mt.FinishedSpans() | ||
| require.Len(t, spans, 1) | ||
| for _, key := range []string{"elasticsearch.body", ext.ErrorMsg} { | ||
| tag := spans[0].Tag(key).(string) | ||
| assert.True(t, utf8.ValidString(tag), "%s ends in %q", key, tag[max(0, len(tag)-4):]) | ||
| assert.Len(t, tag, want, key) | ||
| assert.True(t, strings.HasPrefix(body, tag), key) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func BenchmarkPeek(b *testing.B) { | ||
| for _, bc := range []struct { | ||
| name string | ||
| body string | ||
| }{ | ||
| {"ascii", strings.Repeat("a", 2*bodyCutoff)}, | ||
| {"multibyte", strings.Repeat("€", bodyCutoff)}, | ||
| } { | ||
| b.Run(bc.name, func(b *testing.B) { | ||
| b.ReportAllocs() | ||
| for b.Loop() { | ||
| _, _, _ = peek(io.NopCloser(strings.NewReader(bc.body)), "", -1, bodyCutoff) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
74 changes: 74 additions & 0 deletions
74
contrib/go.mongodb.org/mongo-driver.v2/mongo/mongo_utf8_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| // Unless explicitly stated otherwise all files in this repository are licensed | ||
| // under the Apache License Version 2.0. | ||
| // This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
| // Copyright 2026-present Datadog, Inc. | ||
|
|
||
| package mongo | ||
|
|
||
| import ( | ||
| "context" | ||
| "strconv" | ||
| "strings" | ||
| "testing" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "go.mongodb.org/mongo-driver/v2/bson" | ||
| "go.mongodb.org/mongo-driver/v2/event" | ||
|
|
||
| "github.com/DataDog/dd-trace-go/v2/ddtrace/mocktracer" | ||
| ) | ||
|
|
||
| // TestMaxQuerySizeUTF8 is a regression test: a query cut by WithMaxQuerySize must stay valid | ||
| // UTF-8, dropping a multi-byte character the limit would split. | ||
| func TestMaxQuerySizeUTF8(t *testing.T) { | ||
| cmd, err := bson.Marshal(bson.D{{Key: "find", Value: "café€😀"}}) | ||
| require.NoError(t, err) | ||
| query := `{"find":"café€😀"}` | ||
|
|
||
| // queryTag runs one command through a monitor built with opts and returns the query tag. | ||
| queryTag := func(t *testing.T, opts ...Option) (string, bool) { | ||
| mt := mocktracer.Start() | ||
| defer mt.Stop() | ||
| mon := NewMonitor(opts...) | ||
| mon.Started(context.Background(), &event.CommandStartedEvent{ | ||
| Command: bson.Raw(cmd), CommandName: "find", DatabaseName: "db", ConnectionID: "c", RequestID: 1, | ||
| }) | ||
| mon.Succeeded(context.Background(), &event.CommandSucceededEvent{ | ||
| CommandFinishedEvent: event.CommandFinishedEvent{CommandName: "find", ConnectionID: "c", RequestID: 1}, | ||
| }) | ||
| spans := mt.FinishedSpans() | ||
| require.Len(t, spans, 1) | ||
| v, ok := spans[0].Tag("mongodb.query").(string) | ||
| return v, ok | ||
| } | ||
|
|
||
| t.Run("not truncated by default", func(t *testing.T) { | ||
| got, ok := queryTag(t) | ||
| require.True(t, ok) | ||
| assert.Equal(t, query, got) | ||
| }) | ||
|
|
||
| t.Run("zero omits the tag", func(t *testing.T) { | ||
| _, ok := queryTag(t, WithMaxQuerySize(0)) | ||
| assert.False(t, ok) | ||
| }) | ||
|
|
||
| t.Run("cut inside a rune", func(t *testing.T) { | ||
| // Two bytes into the 4-byte emoji. | ||
| got, _ := queryTag(t, WithMaxQuerySize(strings.Index(query, "😀")+2)) | ||
| assert.Equal(t, `{"find":"café€`, got) | ||
| }) | ||
|
|
||
| for limit := 1; limit <= len(query)+1; limit++ { | ||
| t.Run("limit "+strconv.Itoa(limit), func(t *testing.T) { | ||
| got, ok := queryTag(t, WithMaxQuerySize(limit)) | ||
| require.True(t, ok) | ||
| assert.True(t, utf8.ValidString(got), "%q", got) | ||
| assert.True(t, strings.HasPrefix(query, got), "%q", got) | ||
| assert.LessOrEqual(t, len(got), limit) | ||
| assert.Greater(t, len(got), min(limit, len(query))-utf8.UTFMax) | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
With a positive WithMaxQuerySize and a command larger than that limit, string(b) now allocates the entire serialized query before truncation. TruncateUTF8 returns a substring, and the span stores that string without copying it, retaining the full allocation. A multi-megabyte query capped at 1 KiB therefore retains megabytes instead of approximately 1 KiB. Bound the byte slice before converting it to a string, then trim any incomplete rune. Apply the same fix in the mongo-driver.v2 integration.
React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it
What each reaction means
🤖 Bits Code Review · Open Bits AI session