Skip to content

Commit

Permalink
index.json: Properly escape json strings. (#258)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
bzed authored Feb 20, 2024
1 parent bbcace7 commit ac5e5a3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
10 changes: 6 additions & 4 deletions index/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -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{','}
Expand Down
5 changes: 3 additions & 2 deletions index/index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down

0 comments on commit ac5e5a3

Please sign in to comment.