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
  • Loading branch information
WnP committed Jan 29, 2024
1 parent b4d0ff0 commit 95154b9
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 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 @@ -49,22 +50,28 @@ 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
}

Expand Down

0 comments on commit 95154b9

Please sign in to comment.