Merge pull request #26432 from stefwalter/dont-html-escape-json

api: Don't HTML escape application/json responses
This commit is contained in:
openshift-merge-bot[bot]
2025-06-30 14:47:55 +00:00
committed by GitHub
2 changed files with 55 additions and 1 deletions

View File

@ -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)
}

View File

@ -3,6 +3,9 @@
package utils
import (
"net/http/httptest"
"reflect"
"strings"
"testing"
)
@ -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)
}
}