Skip to content

Commit

Permalink
fix: use k8syaml.YAMLToJSONStrict when marshalling resources
Browse files Browse the repository at this point in the history
Properly handles cases where the YAML is not valid JSON, such as
maps with integer keys (#3446).
  • Loading branch information
dwalters committed May 3, 2022
1 parent 9d5491c commit 1ae9dfb
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 14 deletions.
25 changes: 25 additions & 0 deletions api/krusty/configmaps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,31 @@ metadata:
`)
}

func TestIssue3446(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK(".", `
resources:
- cm.yaml
`)
th.WriteF("cm.yaml", `
apiVersion: v1
kind: ConfigMap
metadata:
name: cm
data:
123: abc
`)
m := th.Run(".", th.MakeDefaultOptions())
th.AssertActualEqualsExpected(m, `
apiVersion: v1
data:
"123": abc
kind: ConfigMap
metadata:
name: cm
`)
}

func TestGeneratorSimpleOverlay(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteK("base", `
Expand Down
5 changes: 3 additions & 2 deletions api/krusty/duplicatekeys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ spec:
`)
m := th.Run(".", th.MakeDefaultOptions())
_, err := m.AsYaml()
assert.Error(t, err)
assert.Contains(t, err.Error(), "mapping key \"env\" already defined")
if assert.Error(t, err) {
assert.Contains(t, err.Error(), "key \"env\" already set in map")
}
}
18 changes: 6 additions & 12 deletions kyaml/yaml/rnode.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"strconv"
"strings"

k8syaml "sigs.k8s.io/yaml"

"sigs.k8s.io/kustomize/kyaml/errors"
"sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/go-yaml/yaml"
"sigs.k8s.io/kustomize/kyaml/sliceutil"
Expand Down Expand Up @@ -879,19 +881,11 @@ func (rn *RNode) MarshalJSON() ([]byte, error) {
return nil, err
}

if rn.YNode().Kind == SequenceNode {
var a []interface{}
if err := Unmarshal([]byte(s), &a); err != nil {
return nil, err
}
return json.Marshal(a)
}

m := map[string]interface{}{}
if err := Unmarshal([]byte(s), &m); err != nil {
return nil, err
b, err := k8syaml.YAMLToJSONStrict([]byte(s))
if err != nil {
return nil, errors.Wrap(err)
}
return json.Marshal(m)
return b, nil
}

// UnmarshalJSON overwrites this RNode with data from []byte.
Expand Down

0 comments on commit 1ae9dfb

Please sign in to comment.