Skip to content

Commit

Permalink
fix: Disable HTML escaping when JSON encoding values (#288)
Browse files Browse the repository at this point in the history
## Which problem is this PR solving?

Husky JSON encodes attribute values in certain circumstances (eg deeply
nested attributes). However, by default the JSON encoder escapes HTML
characters which makes using the values more difficult later.

This change updates the JSON encoder to not escape HTML characters.

## Short description of the changes
- Disable HTML escaping in the JSON encoder by calling
`SetEscapeHTML(false)`
- Add unit test to verify an attribute that contains HTML is not escaped
  • Loading branch information
MikeGoldsmith authored Dec 11, 2024
1 parent 7bc98b7 commit 7fd68ed
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
8 changes: 6 additions & 2 deletions otlp/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,12 +460,16 @@ func addAttributeToMap(ctx context.Context, result map[string]interface{}, key s
// addAttributeToMapAsJson adds an attribute to a map as a JSON string.
// Uses limitedWriter to ensure that the string can't be bigger than the maximum field size and
// helps reduce allocation and copying.
// Note that an Encoder emits JSON with a trailing newline because it's intended for use
// Notes:
// - The Encoder emits JSON with a trailing newline because it's intended for use
// in streaming. This is correct but sometimes surprising and the tests need to expect it.
// - The encoder has HTML escaping disabled.
func addAttributeToMapAsJson(attrs map[string]interface{}, key string, value *common.AnyValue) int {
val := getMarshallableValue(value)
w := newLimitedWriter(fieldSizeMax)
if err := json.NewEncoder(w).Encode(val); err != nil {
e := json.NewEncoder(w)
e.SetEscapeHTML(false)
if err := e.Encode(val); err != nil {
// TODO: log error or report error when we have a way to do so
return 0
}
Expand Down
8 changes: 8 additions & 0 deletions otlp/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -862,3 +862,11 @@ func TestGetSampleRateConversions(t *testing.T) {
assert.Equal(t, 0, len(attrs))
}
}

func TestAddAttributesToMapAreNotHTMLEncoded(t *testing.T) {
key := "my-html"
val := "<html><body><h1>hello</h1></body></html>"
attrs := map[string]interface{}{}
addAttributeToMapAsJson(attrs, key, &common.AnyValue{Value: &common.AnyValue_StringValue{StringValue: val}})
assert.Equal(t, "\"<html><body><h1>hello</h1></body></html>\"\n", attrs[key])
}

0 comments on commit 7fd68ed

Please sign in to comment.