Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lang: Fix non-string key panics in map function #24277

Merged
merged 1 commit into from
Mar 4, 2020
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
8 changes: 5 additions & 3 deletions lang/funcs/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,12 +346,14 @@ var MapFunc = function.New(&function.Spec{

for i := 0; i < len(args); i += 2 {

key := args[i].AsString()

err := gocty.FromCtyValue(args[i], &key)
keyVal, err := convert.Convert(args[i], cty.String)
if err != nil {
return cty.NilVal, err
}
if keyVal.IsNull() {
return cty.NilVal, fmt.Errorf("argument %d is a null key", i+1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not super important here, but just wanted to point out that you can return the special error type ArgError from a function (e.g. using NewArgErrorf instead of Errorf here) to indicate that a specific argument is incorrect.

When using functions with HCL, HCL recognizes that error type and indicates the specific single argument as the problem, rather than the entire call.

}
key := keyVal.AsString()

val := args[i+1]

Expand Down
25 changes: 25 additions & 0 deletions lang/funcs/collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)

func TestLength(t *testing.T) {
Expand Down Expand Up @@ -730,6 +731,19 @@ func TestMap(t *testing.T) {
}),
false,
},
{ // convert number keys to strings
[]cty.Value{
cty.NumberIntVal(1),
cty.StringVal("hello"),
cty.NumberIntVal(2),
cty.StringVal("goodbye"),
},
cty.MapVal(map[string]cty.Value{
"1": cty.StringVal("hello"),
"2": cty.StringVal("goodbye"),
}),
false,
},
{ // map of lists is okay
[]cty.Value{
cty.StringVal("hello"),
Expand Down Expand Up @@ -785,6 +799,14 @@ func TestMap(t *testing.T) {
cty.NilVal,
true,
},
{ // null key returns an error
[]cty.Value{
cty.NullVal(cty.DynamicPseudoType),
cty.NumberIntVal(5),
},
cty.NilVal,
true,
},
}

for _, test := range tests {
Expand All @@ -794,6 +816,9 @@ func TestMap(t *testing.T) {
if err == nil {
t.Fatal("succeeded; want error")
}
if _, ok := err.(function.PanicError); ok {
t.Fatalf("unexpected panic: %s", err)
}
return
} else if err != nil {
t.Fatalf("unexpected error: %s", err)
Expand Down