Skip to content
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
60 changes: 56 additions & 4 deletions enumify.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ func Generate(opts Options) (err error) {
typeID := etype.Id() // Enum
namesVar := etype.NamesVarId() // enumNames
namesVarSlice := etype.NamesVarSliceId() // enumNames or enumNames[0]
parserID := g.Id("Parse" + etype.Name) // ParseEnum

f.Comment("//============================================================================")
f.Comment("// " + etype.Name + " Enum Type: Generated Functions and Methods")
Expand Down Expand Up @@ -197,6 +198,57 @@ func Generate(opts Options) (err error) {
f.Line()
}

// Text Marshal and Unmarshal code
if !opts.NoText {
f.Commentf("Ensure %s implements text.Marshaler.", etype.Name)
method := methodSig.Clone().Id("MarshalText").Call().Params(g.Id("[]byte"), g.Error())
method.Block(
g.Return(g.Id("[]byte").Call(s.Clone().Dot("String").Call()), g.Nil()),
)
f.Add(method)
f.Line()

f.Commentf("Ensure %s implements text.Unmarshaler.", etype.Name)
method = methodPtrSig.Clone().Id("UnmarshalText").Call(g.Id("data").Id("[]byte")).Params(evar.Clone().Error())
method.Block(
ptrS.Clone().Op(",").Add(evar).Op("=").Add(parserID.Clone()).Call(g.String().Call(g.Id("data"))),
g.Return(evar),
)
f.Add(method)
f.Line()
}

// Binary Marshal and Unmarshal code
if !opts.NoBinary {
f.Commentf("Ensure %s implements binary.Marshaler.", etype.Name)
method := methodSig.Clone().Id("MarshalBinary").Call().Params(g.Id("[]byte"), g.Error())
method.Block(
g.Return(g.Id("[]byte").Values(g.Byte().Call(s)), g.Nil()),
)
f.Add(method)
f.Line()

f.Commentf("Ensure %s implements binary.Unmarshaler.", etype.Name)
method = methodPtrSig.Clone().Id("UnmarshalBinary").Call(g.Id("data").Id("[]byte")).Params(evar.Clone().Error())
method.Block(
g.Switch(g.Len(g.Id("data"))).Block(
g.Case(g.Lit(0)).Block(
ptrS.Clone().Op("=").Add(typeID.Clone().Call(g.Lit(0))),
g.Return(g.Nil()),
),
g.Case(g.Lit(1)).Block(
ptrS.Clone().Op("=").Add(typeID.Clone().Call(g.Id("data").Index(g.Lit(0)))),
g.Return(g.Nil()),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Generated UnmarshalBinary accepts out-of-range byte values

High Severity

The UnmarshalBinary method, when handling single-byte input, directly casts the byte to the enum type. This bypasses the validation logic used by other unmarshalers, allowing invalid byte values to create invalid enum instances.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9dccb90. Configure here.

),
g.Default().Block(
g.Return(g.Qual("fmt", "Errorf").Call(g.Lit("cannot unmarshal %d bytes into "+etype.Name), g.Len(g.Id("data")))),
),
),
)
f.Add(method)
f.Line()
}

// JSON Marshal and Unmarshal code
if !opts.NoJSON {
f.Commentf("Ensure %s implements json.Marshaler.", etype.Name)
Expand All @@ -220,7 +272,7 @@ func Generate(opts Options) (err error) {
),
g.Line(),
g.If(
ptrS.Clone().Op(",").Id("err").Op("=").Id("Parse"+etype.Name).Call(sv).Op(";").Id("err").Op("!=").Nil().
ptrS.Clone().Op(",").Id("err").Op("=").Add(parserID.Clone()).Call(sv).Op(";").Id("err").Op("!=").Nil().
Block(
g.Return(evar),
),
Expand Down Expand Up @@ -251,7 +303,7 @@ func Generate(opts Options) (err error) {
g.Return(evar),
),
g.Line(),
g.If(g.Add(ptrS.Clone()).Op(",").Id("err").Op("=").Id("Parse"+etype.Name).Call(sv).Op(";").Id("err").Op("!=").Nil().
g.If(g.Add(ptrS.Clone()).Op(",").Id("err").Op("=").Add(parserID.Clone()).Call(sv).Op(";").Id("err").Op("!=").Nil().
Block(
g.Return(evar),
),
Expand All @@ -271,11 +323,11 @@ func Generate(opts Options) (err error) {
g.Switch(val.Clone().Op(":=").Id("src").Assert(g.Type())).Block(
g.Case(g.Nil()).Block(g.Return(g.Nil())),
g.Case(g.String()).Block(
g.List(ptrS.Clone(), evar.Clone().Op("=").Id("Parse"+etype.Name).Call(val)),
g.List(ptrS.Clone(), evar.Clone().Op("=").Add(parserID.Clone()).Call(val)),
g.Return(evar),
),
g.Case(g.Id("[]byte")).Block(
g.List(ptrS.Clone(), evar.Clone().Op("=").Id("Parse"+etype.Name).Call(g.String().Call(val))),
g.List(ptrS.Clone(), evar.Clone().Op("=").Add(parserID.Clone()).Call(g.String().Call(val))),
g.Return(evar),
),
g.Default().Block(
Expand Down
15 changes: 15 additions & 0 deletions parse.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package enumify

import (
"errors"
"fmt"
"strings"
)
Expand Down Expand Up @@ -47,6 +48,11 @@ func ParseFactory[T ~uint8, Names []string | [][]string](names Names) Parser[T]
unknown := T(0)

return func(val any) (T, error) {
// Convert byte slices to strings.
if v, ok := val.([]byte); ok && len(v) > 1 {
val = string(v)
}

switch v := val.(type) {
case string:
v = normalize(v)
Expand All @@ -65,6 +71,15 @@ func ParseFactory[T ~uint8, Names []string | [][]string](names Names) Parser[T]

// If no match is found, return an error.
return unknown, fmt.Errorf("invalid %T value: %q", unknown, v)
case []byte:
switch len(v) {
case 0:
return unknown, nil
case 1:
return T(v[0]), nil
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Single-byte slice parsing skips range validation

High Severity

The case []byte handler for single-byte slices returns T(v[0]) without validating the value against the enum's defined range. This differs from other numeric type handlers, which correctly check bounds and return an error for out-of-range values.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9dccb90. Configure here.

default:
panic(errors.New("byte slices should be parsed as strings: this code should be unreachable"))
}
case T:
if v >= T(len(normalizedNames)) {
return unknown, fmt.Errorf("invalid %T value: %d", unknown, v)
Expand Down
16 changes: 16 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ func TestParseFactory(t *testing.T) {
{value: "REVIEW", expected: StatusReview},
{value: "PUBLISHED", expected: StatusPublished},
{value: "ARCHIVED", expected: StatusArchived},
{value: byte(0), expected: StatusUnknown},
{value: byte(1), expected: StatusDraft},
{value: byte(2), expected: StatusReview},
{value: byte(3), expected: StatusPublished},
{value: byte(4), expected: StatusArchived},
{value: []byte{0}, expected: StatusUnknown},
{value: []byte{1}, expected: StatusDraft},
{value: []byte{2}, expected: StatusReview},
{value: []byte{3}, expected: StatusPublished},
{value: []byte{4}, expected: StatusArchived},
{value: []byte(""), expected: StatusUnknown},
{value: []byte("unknown"), expected: StatusUnknown},
{value: []byte("draft"), expected: StatusDraft},
{value: []byte("review"), expected: StatusReview},
{value: []byte("published"), expected: StatusPublished},
{value: []byte("archived"), expected: StatusArchived},
{value: uint(0), expected: StatusUnknown},
{value: uint(1), expected: StatusDraft},
{value: uint(2), expected: StatusReview},
Expand Down
Loading