From ac5e5a3a12aeee5eed5ca704f1022d1f33144d54 Mon Sep 17 00:00:00 2001 From: Bernd Zeimetz Date: Tue, 20 Feb 2024 10:29:43 +0100 Subject: [PATCH] index.json: Properly escape json strings. (#258) * Properly escape json strings. Although most likely not officially supported, we might end up with some weird metric names in the DB. icinga2 is a good candidate for a source of broken metrics. --- index/index.go | 10 ++++++---- index/index_test.go | 5 +++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/index/index.go b/index/index.go index 2e6b5f286..281a187e6 100644 --- a/index/index.go +++ b/index/index.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "context" + "encoding/json" "fmt" "io" "net/http" @@ -81,12 +82,13 @@ func (i *Index) WriteJSON(w http.ResponseWriter) error { continue } - quote := []byte{'"'} + json_b, err := json.Marshal(string(b)) + if err != nil { + return err + } jsonParts := [][]byte{ nil, - quote, - b, - quote, + json_b, } if idx != 0 { jsonParts[0] = []byte{','} diff --git a/index/index_test.go b/index/index_test.go index 2f9dfea26..1e37380eb 100644 --- a/index/index_test.go +++ b/index/index_test.go @@ -34,15 +34,16 @@ func TestWriteJSONNonleafRows(t *testing.T) { "testing.leaf", "testing.nonleaf.", "testing.leaf.node", + "testing.\"broken\".node", } metrics, err := writeRows(rows) if err != nil { t.Fatalf("Error during transform or unmarshal: %s", err) } - if len(metrics) != 2 { + if len(metrics) != 3 { t.Fatalf("Wrong metrics slice length = %d: %s", len(metrics), metrics) } - if metrics[0] != "testing.leaf" || metrics[1] != "testing.leaf.node" { + if metrics[0] != "testing.leaf" || metrics[1] != "testing.leaf.node" || metrics[2] != "testing.\"broken\".node" { t.Fatalf("Wrong metrics contents: %s", metrics) } }