Skip to content
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

fix: fix bug in query result marshaling for invalid utf8 characters #14585

Merged
merged 3 commits into from
Oct 28, 2024
Merged
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
16 changes: 16 additions & 0 deletions pkg/util/marshal/query.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package marshal

import (
"bytes"
"fmt"
"strconv"
"strings"
"unicode/utf8"
"unsafe"

jsoniter "github.com/json-iterator/go"
Expand All @@ -20,6 +23,16 @@ import (
"github.com/grafana/loki/v3/pkg/util/httpreq"
)

var (
// The rune error replacement is rejected by Prometheus hence replacing them with space.
removeInvalidUtf = func(r rune) rune {
if r == utf8.RuneError {
return 32 // rune value for space
}
return r
}
)

// NewResultValue constructs a ResultValue from a promql.Value
func NewResultValue(v parser.Value) (loghttp.ResultValue, error) {
var err error
Expand Down Expand Up @@ -77,6 +90,9 @@ func NewStreams(s logqlmodel.Streams) (loghttp.Streams, error) {
ret := make([]loghttp.Stream, len(s))

for i, stream := range s {
if strings.ContainsRune(stream.Labels, utf8.RuneError) {
stream.Labels = string(bytes.Map(removeInvalidUtf, []byte(stream.Labels)))
}
ret[i], err = NewStream(stream)

if err != nil {
Expand Down
19 changes: 19 additions & 0 deletions pkg/util/marshal/query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package marshal

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/grafana/loki/v3/pkg/logqlmodel"
)

func TestNewStreams(t *testing.T) {
s, err := NewStreams(logqlmodel.Streams{
{
Labels: "{asdf=\"�\"}",
},
})
require.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

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

it would be useful to assert the result as well

require.Equal(t, " ", s[0].Labels["asdf"], "expected only a space for label who only contained invalid UTF8 rune")
}
Loading