Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions contrib/INTEGRATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,12 @@ call `instr.OperationName` and do not add `buildOpName` builders to the integrat
span, ctx := tracer.StartSpanFromContext(ctx, "mylib.request", startOpts...)
```

### Truncating tag values

Tag values must be valid UTF-8. To cap a tag such as a query or a request body at a byte limit, use
`instrumentation.TruncateUTF8(s, limit)` rather than `s[:limit]`, which can split a multi-byte
character.

### Tag performance

#### Favor a cached `StartSpanConfig` and `WithTags` over per-operation `Tag` closures
Expand Down
5 changes: 3 additions & 2 deletions contrib/elastic/go-elasticsearch.v6/elastictrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,11 @@ func peek(rc io.ReadCloser, encoding string, max, n int) (string, io.ReadCloser,
gzr, err2 := gzip.NewReader(bytes.NewReader(snip))
if err2 != nil {
// snip wasn't gzip; return it as is
return string(snip), rc2, nil
return instrumentation.TruncateUTF8(string(snip), n), rc2, nil
}
defer gzr.Close()
snip, err = io.ReadAll(io.LimitReader(gzr, int64(cutoff)))
return instrumentation.TruncateUTF8(string(snip), cutoff), rc2, err
}
return string(snip), rc2, err
return instrumentation.TruncateUTF8(string(snip), n), rc2, err
}
187 changes: 187 additions & 0 deletions contrib/elastic/go-elasticsearch.v6/elastictrace_utf8_test.go
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)
}
})
}
}
7 changes: 4 additions & 3 deletions contrib/go.mongodb.org/mongo-driver.v2/mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,11 @@ func (m *monitor) Started(ctx context.Context, evt *event.CommandStartedEvent) {
}
if m.cfg.maxQuerySize != 0 {
b, _ := bson.MarshalExtJSON(evt.Command, false, false)
if m.cfg.maxQuerySize > 0 && len(b) > m.cfg.maxQuerySize {
b = b[:m.cfg.maxQuerySize]
query := string(b)
if m.cfg.maxQuerySize > 0 {
query = instrumentation.TruncateUTF8(query, m.cfg.maxQuerySize)
}
tags[m.cfg.spanName] = string(b)
tags[m.cfg.spanName] = query
}
span, _ := tracer.StartSpanFromContext(ctx, m.cfg.spanName,
tracer.WithTags(tags),
Expand Down
74 changes: 74 additions & 0 deletions contrib/go.mongodb.org/mongo-driver.v2/mongo/mongo_utf8_test.go
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)
})
}
}
4 changes: 3 additions & 1 deletion contrib/go.mongodb.org/mongo-driver.v2/mongo/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ func WithService(name string) OptionFn {
}

// WithMaxQuerySize sets the maximum query size (in bytes) before queries
// are truncated when attached as a span tag.
// are truncated when attached as a span tag. A truncated query is cut so
// that no multi-byte UTF-8 character is split, so it may be up to 3 bytes
// shorter than max.
//
// If negative (the default), query truncation is disabled and the query
// will always be attached in full.
Expand Down
7 changes: 4 additions & 3 deletions contrib/go.mongodb.org/mongo-driver/mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,11 @@ func (m *monitor) Started(ctx context.Context, evt *event.CommandStartedEvent) {
}
if m.cfg.maxQuerySize != 0 {
b, _ := bson.MarshalExtJSON(evt.Command, false, false)
if m.cfg.maxQuerySize > 0 && len(b) > m.cfg.maxQuerySize {
b = b[:m.cfg.maxQuerySize]
query := string(b)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Bound MongoDB bytes before allocating the query string

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
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

if m.cfg.maxQuerySize > 0 {
query = instrumentation.TruncateUTF8(query, m.cfg.maxQuerySize)
}
tags[m.cfg.spanName] = string(b)
tags[m.cfg.spanName] = query
}
span, _ := tracer.StartSpanFromContext(ctx, m.cfg.spanName,
tracer.WithTags(tags),
Expand Down
Loading
Loading