Skip to content

fix(encoding): avoid nil panic when encoding unknown enum number - #3904

Open
amalsaidov wants to merge 1 commit into
go-kratos:mainfrom
amalsaidov:fix/form-encode-unknown-enum
Open

amalsaidov wants to merge 1 commit into
go-kratos:mainfrom
amalsaidov:fix/form-encode-unknown-enum

Conversation

@amalsaidov

Copy link
Copy Markdown

Description (what this PR does / why we need it):

EncodeField in encoding/form resolves an enum value by its number and immediately uses the returned descriptor's name:

desc := fieldDescriptor.Enum().Values().ByNumber(value.Enum())
return string(desc.Name()), nil

proto3 enums are open: a field can legally hold a number that has no declared value, for example a value written by a newer peer that defines more enum entries. When that happens ByNumber returns nil, and desc.Name() dereferences a nil pointer. Encoding such a message into form/query values (any HTTP request/response that goes through the form codec with an unknown enum number) panics and takes down the process.

This PR checks the lookup result and falls back to the numeric value when the descriptor is not found. That matches how protojson renders unknown enum numbers, and the form decoder already accepts an enum given as a number, so the value round-trips for known numbers.

Before the change the added test panics with:

panic: runtime error: invalid memory address or nil pointer dereference
	.../encoding/form/proto_encode.go:132 EncodeField

Which issue(s) this PR fixes (resolves / be part of):

None filed; found while reading the form codec.

Other special notes for the reviewers:

  • Added TestEncodeUnknownEnum, which sets a Sex field to a number with no declared name and asserts the encoded value is the number.
  • go build ./..., go test ./encoding/..., gofmt -l and go vet ./encoding/form/ are clean.

🤖 Generated with Claude Code

EncodeField looked up the enum value descriptor by number and used its
name without checking whether the lookup succeeded. proto3 enums are
open, so a field can legally hold a number that has no declared value,
for example one produced by a newer peer. In that case ByNumber returns
nil and string(desc.Name()) dereferences a nil pointer, crashing the
whole process when a response or request carrying such a value is
encoded into form/query values.

Fall back to the numeric value when the descriptor is not found, which
matches how protojson renders unknown enum numbers and what the form
decoder already accepts.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant