Skip to content

Commit

Permalink
Add an optional boolean to not escape html during json encoding
Browse files Browse the repository at this point in the history
Signed-off-by: Steeve Chailloux <[email protected]>
  • Loading branch information
WnP committed Jan 30, 2024
1 parent b4d0ff0 commit b5de38f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
6 changes: 6 additions & 0 deletions pkg/yamltemplate/filetests/ytt-library/json.tpltest
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ encode:
indent:
test1: #@ json.encode({"a": [1,2,3,{"c":456}], "b": "str"}, indent=4)
test2: #@ json.encode({"a": [1,2,3,{"c":456}], "b": "str"}, indent=0)
no_escape_html:
test1: #@ json.encode({"a": "<123>"})
test2: #@ json.encode({"a": "<123>"}, no_escape_html=True)
decode:
test1: #@ json.decode("{}")
test2: #@ json.decode('{"a":[1,2,3,{"c":456}],"b":"str"}')
Expand All @@ -40,6 +43,9 @@ encode:
"b": "str"
}
test2: '{"a":[1,2,3,{"c":456}],"b":"str"}'
no_escape_html:
test1: '{"a":"\u003c123\u003e"}'
test2: '{"a":"<123>"}'
decode:
test1: {}
test2:
Expand Down
21 changes: 15 additions & 6 deletions pkg/yttlibrary/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package yttlibrary

import (
"bytes"
"encoding/json"
"fmt"
"strings"
Expand Down Expand Up @@ -37,6 +38,7 @@ func (b jsonModule) Encode(thread *starlark.Thread, f *starlark.Builtin, args st
}
allowedKWArgs := map[string]struct{}{
"indent": {},
"no_escape_html": {},
}
if err := core.CheckArgNames(kwargs, allowedKWArgs); err != nil {
return starlark.None, err
Expand All @@ -49,26 +51,33 @@ func (b jsonModule) Encode(thread *starlark.Thread, f *starlark.Builtin, args st
val = orderedmap.Conversion{yamlmeta.NewGoFromAST(val)}.AsUnorderedStringMaps()

var valBs []byte
buffer := bytes.NewBuffer(valBs)
indent, err := core.Int64Arg(kwargs, "indent")
if err != nil {
return starlark.None, err
}

if indent < 0 || indent > 8 {
// mitigate https://cwe.mitre.org/data/definitions/409.html
return starlark.None, fmt.Errorf("indent value must be between 0 and 8")
}

noEscapeHTML, err := core.BoolArg(kwargs, "no_escape_html")
if err != nil {
return starlark.None, err
}

encoder := json.NewEncoder(buffer)
if indent > 0 {
valBs, err = json.MarshalIndent(val, "", strings.Repeat(" ", int(indent)))
} else {
valBs, err = json.Marshal(val)
encoder.SetIndent("", strings.Repeat(" ", int(indent)))
}
if err != nil {
encoder.SetEscapeHTML(!noEscapeHTML)

if err := encoder.Encode(val); err != nil {
return starlark.None, err
}

return starlark.String(string(valBs)), nil
res := strings.TrimSuffix(buffer.String(), "\n")
return starlark.String(res), nil
}

// Decode is a core.StarlarkFunc that parses the provided input from JSON format into dicts, lists, and scalars
Expand Down

0 comments on commit b5de38f

Please sign in to comment.