8000 pkg/xml: escape reserved characters in element text by AruneshDwivedi · Pull Request #2034 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
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
12 changes: 11 additions & 1 deletion pkg/xml/xml.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,5 +254,15 @@ func (n *xmlNode) writeTag(w io.Writer, indent uint8, attributes string, openTag

// writeValue prints XML value into io.Writer
func (n *xmlNode) writeValue(w io.Writer, value string) {
util.Fprintf(w, "%s", value)
// Element text is injected verbatim by default, which produces invalid
// XML when a value contains the reserved characters &, < or > (e.g. a
// generated password). Escape those so the rendered document stays
// well-formed. , \n and \r are intentionally left untouched to keep
// existing multi-line values working.
escaped := strings.NewReplacer(
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
).Replace(value)
util.Fprintf(w, "%s", escaped)
}
50 changes: 50 additions & 0 deletions pkg/xml/xml_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package xml

import (
"strings"
"testing"
)

func TestWriteValueEscapesReservedCharacters(t *testing.T) {
cases := []struct {
name string
input string
expected string
}{
{
name: "ampersand is escaped",
input: "p%X&word",
expected: "p%X&amp;word",
},
{
name: "less-than is escaped",
input: "a<b",
expected: "a&lt;b",
},
{
name: "greater-than is escaped",
input: "a>b",
expected: "a&gt;b",
},
{
name: "generated password with mixed special chars",
input: "l%XubpKqz2y!QsKlsynEEE6#Thknj&fG",
expected: "l%XubpKqz2y!QsKlsynEEE6#Thknj&amp;fG",
},
{
name: "plain value is unchanged",
input: "plainpassword",
expected: "plainpassword",
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var sb strings.Builder
(&xmlNode{}).writeValue(&sb, tc.input)
if sb.String() != tc.expected {
t.Errorf("writeValue() = %q, expected %q", sb.String(), tc.expected)
}
})
}
}
0