Skip to content

Commit f411a07

Browse files
authored
fix: fix bug in query result marshaling for invalid utf8 characters (#14585)
Signed-off-by: Callum Styan <callumstyan@gmail.com>
1 parent 99c423a commit f411a07

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

‎pkg/util/marshal/query.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package marshal
22

33
import (
4+
"bytes"
45
"fmt"
56
"strconv"
7+
"strings"
8+
"unicode/utf8"
69
"unsafe"
710

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

26+
var (
27+
// The rune error replacement is rejected by Prometheus hence replacing them with space.
28+
removeInvalidUtf = func(r rune) rune {
29+
if r == utf8.RuneError {
30+
return 32 // rune value for space
31+
}
32+
return r
33+
}
34+
)
35+
2336
// NewResultValue constructs a ResultValue from a promql.Value
2437
func NewResultValue(v parser.Value) (loghttp.ResultValue, error) {
2538
var err error
@@ -77,6 +90,9 @@ func NewStreams(s logqlmodel.Streams) (loghttp.Streams, error) {
7790
ret := make([]loghttp.Stream, len(s))
7891

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

8298
if err != nil {

‎pkg/util/marshal/query_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package marshal
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/require"
7+
8+
"github.com/grafana/loki/v3/pkg/logqlmodel"
9+
)
10+
11+
func TestNewStreams(t *testing.T) {
12+
s, err := NewStreams(logqlmodel.Streams{
13+
{
14+
Labels: "{asdf=\"\"}",
15+
},
16+
})
17+
require.NoError(t, err)
18+
require.Equal(t, " ", s[0].Labels["asdf"], "expected only a space for label who only contained invalid UTF8 rune")
19+
}

0 commit comments

Comments
 (0)