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

fix(bindnode): more helpful error message for enum value footgun #430

Merged
merged 1 commit into from
May 25, 2022
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
38 changes: 38 additions & 0 deletions node/bindnode/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package bindnode_test

import (
"testing"

qt "github.com/frankban/quicktest"
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/node/bindnode"
)

func TestEnumError(t *testing.T) {
type Action string
const (
ActionPresent = Action("p")
ActionMissing = Action("m")
)
type S struct{ Action Action }

schema := `
type S struct {
Action Action
} representation tuple
type Action enum {
| Present ("p")
| Missing ("m")
} representation string
`

typeSystem, err := ipld.LoadSchemaBytes([]byte(schema))
qt.Assert(t, err, qt.IsNil)
schemaType := typeSystem.TypeByName("S")

node := bindnode.Wrap(&S{Action: ActionPresent}, schemaType).Representation()
_, err = ipld.Encode(node, dagcbor.Encode)
qt.Assert(t, err, qt.IsNotNil)
qt.Assert(t, err.Error(), qt.Equals, `AsString: "p" is not a valid member of enum Action (bindnode works at the type level; did you mean "Present"?)`)
}
6 changes: 6 additions & 0 deletions node/bindnode/repr.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,12 @@ func (w *_nodeRepr) AsString() (string, error) {
return s, nil
}
}
for k, v := range stg {
// a programming error? we may have the enum string value rather than the type
if v == s {
return "", fmt.Errorf("AsString: %q is not a valid member of enum %s (bindnode works at the type level; did you mean %q?)", s, w.schemaType.Name(), k)
}
}
return "", fmt.Errorf("AsString: %q is not a valid member of enum %s", s, w.schemaType.Name())
default:
return (*_node)(w).AsString()
Expand Down