Skip to content

Commit

Permalink
Strip BOM from input JSON when found
Browse files Browse the repository at this point in the history
Fixes #6988

Signed-off-by: Anders Eknert <[email protected]>
  • Loading branch information
anderseknert authored and ashutosh-narkar committed Sep 4, 2024
1 parent 3c2fc5d commit efef7d2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions util/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ func Reference(x interface{}) *interface{} {

// Unmarshal decodes a YAML, JSON or JSON extension value into the specified type.
func Unmarshal(bs []byte, v interface{}) error {
if len(bs) > 2 && bs[0] == 0xef && bs[1] == 0xbb && bs[2] == 0xbf {
bs = bs[3:] // Strip UTF-8 BOM, see https://www.rfc-editor.org/rfc/rfc8259#section-8.1
}

if json.Valid(bs) {
return unmarshalJSON(bs, v, false)
}
Expand Down
14 changes: 14 additions & 0 deletions util/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,17 @@ func TestInvalidYAMLValidJSON(t *testing.T) {
t.Fatal(err)
}
}

func TestUnmarshalJSONUTF8BOM(t *testing.T) {
bomFail := []byte{0xef, 0xbb, 0xbf, 0x22, 0x5c, 0x2f, 0x22, 0x0a} // "\/" preceded by UTF-8 BOM

if json.Valid(bomFail) {
t.Fatal("expected invalid JSON")
}

var x any
err := util.Unmarshal(bomFail, &x)
if err != nil {
t.Fatal("expected BOM to be stripped", err)
}
}

0 comments on commit efef7d2

Please sign in to comment.