Skip to content

api: Don't HTML escape application/json responses #26432

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
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
2 changes: 1 addition & 1 deletion pkg/api/handlers/utils/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func WriteJSON(w http.ResponseWriter, code int, value interface{}) {
w.WriteHeader(code)

coder := json.NewEncoder(w)
coder.SetEscapeHTML(true)
coder.SetEscapeHTML(false)
if err := coder.Encode(value); err != nil {
logrus.Errorf("Unable to write json: %q", err)
}
Expand Down
54 changes: 54 additions & 0 deletions pkg/api/handlers/utils/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
package utils

import (
"net/http/httptest"
"reflect"
"strings"
"testing"
)

Expand Down Expand Up @@ -53,3 +56,54 @@ func TestErrorEncoderFuncOmit(t *testing.T) {
t.Errorf("the `errs` field shouldn't have been omitted")
}
}

func TestWriteJSONNoHTMLEscape(t *testing.T) {
// Test that WriteJSON does not HTML-escape JSON content
// This test verifies the fix for issue #17769

recorder := httptest.NewRecorder()

// Test data with characters that would be HTML-escaped
testData := map[string]string{
"message": "Hello <world> & \"friends\"",
"script": "<script>alert('test')</script>",
"url": "https://example.com/path?param=value&other=<test>",
}

WriteJSON(recorder, 200, testData)

// Check response headers
if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json" {
t.Errorf("Expected Content-Type 'application/json', got '%s'", contentType)
}

// Check that response contains unescaped characters
body := recorder.Body.String()

// These characters should NOT be HTML-escaped in JSON responses
// (but quotes are still properly JSON-escaped)
expectedUnescaped := []string{
"<world>",
"&",
"\\\"friends\\\"", // JSON-escaped quotes, not HTML-escaped
"<script>",
"<test>",
}

for _, expected := range expectedUnescaped {
if !strings.Contains(body, expected) {
t.Errorf("Expected unescaped string '%s' in response body, got: %s", expected, body)
}
}

// Verify we can parse the JSON back
var parsed map[string]string
if err := json.Unmarshal([]byte(body), &parsed); err != nil {
t.Errorf("Failed to parse JSON response: %v", err)
}

// Verify the data matches what we sent
if !reflect.DeepEqual(parsed, testData) {
t.Errorf("Parsed message doesn't match original: got %v, want %v", parsed, testData)
}
}