Skip to content

Convert rebuilt map keys to the map's key type before MapIndex - #1652

Open
januththedev wants to merge 1 commit into
go-playground:masterfrom
januththedev:fix/named-map-key-index
Open

januththedev wants to merge 1 commit into
go-playground:masterfrom
januththedev:fix/named-map-key-index

Conversation

@januththedev

Copy link
Copy Markdown

AI attribution, as required by the "AI Agents" section of CONTRIBUTING.md: this bug was found, proved, and fixed with the assistance of an AI agent. The commit carries a Co-Authored-By: trailer identifying the model used, and I have reviewed the change line by line and run the tests myself. I am able to answer questions about any line in it.

A named map key type panics cross-field validation instead of returning "not found"

Description

util.go:237, inside getStructFieldOKInternal, case reflect.Map:. The function resolves a Field[key] namespace. It parses key out of the namespace, rebuilds it as a built-in value based on current.Type().Key().Kind(), and passes it straight to reflect.Value.MapIndex:

switch current.Type().Key().Kind() {
case reflect.Int:
    i, _ := strconv.Atoi(key)
    val = current.MapIndex(reflect.ValueOf(i))
...
default:
    val = current.MapIndex(reflect.ValueOf(key))   // plain `string`, line 237

A map key declared as a named type (type LangCode string) has the same reflect.Kind as its underlying type, so it lands in the matching branch — but reflect.ValueOf(key) yields a string, and string is not assignable to validator.LangCode. MapIndex panics rather than reporting "not found".

Why that's wrong

The function's own contract (util.go:244-247) is to "return found=false instead of panicking to handle cases like ValidateMap where cross-field validators (required_if, etc.) can't navigate non-struct parents."

A named key type is a perfectly ordinary, already-supported map shape — the repo's own test at validator_test.go:11928 uses exactly type LangCode string; type Label map[LangCode]string with dive,keys. Only the namespace-resolution path is missing the conversion. The result is that a Validate.Struct() call takes down the caller's process (an unrecovered panic, no error returned) purely because of a user-declared map key type.

Reachable from every cross-field validator — eqfield, nefield, required_if, excluded_if, and so on — and from GetStructFieldOK2() / GetStructFieldOKAdvanced2 in user-registered custom validators.

Reproduction

=== RUN   TestCrossFieldNamedMapKeyType
--- FAIL: TestCrossFieldNamedMapKeyType (0.00s)
panic: reflect.Value.MapIndex: value of type string is not assignable to type validator.LangCode [recovered, repanicked]
	.../reflect/map.go:156
validator.(*validate).getStructFieldOKInternal(...)
	E:/GITHUB/validator/util.go:237
validator.(*validate).GetStructFieldOK(...)
	E:/GITHUB/validator/field_level.go:98
validator.isEqField(...)
	E:/GITHUB/validator/baked_in.go:1376

The fix

A mapIndexOf helper that converts the rebuilt key to the map's real key type when they differ, and returns an invalid reflect.Value when the key cannot be represented at all — which the caller already funnels into found=false via ExtractType → kind == reflect.Invalid. All 14 current.MapIndex(...) call sites route through it.

For plain map[string]… / map[int]… the key.Type() != kt check is false, so behaviour is bit-for-bit unchanged and no conversion cost is added.

Tests

TestCrossFieldNamedMapKeyType in validator_test.go (63 lines), covering eqfield and nefield over a map with a named key type, asserting a clean validation error rather than a panic.

  • Before: the panic above. After: --- PASS.
  • Full suite go test ./...: 25/25 packages ok, exit 0. Main package 290 --- PASS, 0 --- FAIL, 1 pre-existing Windows-only skip. Baseline on unmodified HEAD was 25/25 packages ok with 289 passes and zero pre-existing failures, so the delta is exactly my one new test.
  • go vet ./ clean.
  • Benchmarks: allocation counts identical in every case (e.g. BenchmarkStructSimpleSuccess 24 B/op / 2 allocs/op both before and after). ns/op deltas are machine noise on this shared box, and none of those benchmarks exercise the map path anyway.

go test -race cannot run in my environment (gcc: fatal error: cannot execute 'cc1'), a missing C toolchain unrelated to this change.

Upstream status

I could not complete this check — gh issue list, gh pr list, gh api, and a direct fetch to api.github.com all failed with a TLS handshake timeout from my sandbox. What I can confirm locally: the clone is a single-commit checkout at 3487bab, so the defect is present at current upstream HEAD, and the panic is reachable purely from the public API with no unusual configuration. If you know of an existing report, point me at it and I will close this one.

Related defects found but deliberately left out of this change

  • util.go:137 — a negative index in a namespace (eqfield=B[-1]) panics with reflect: slice index out of range; arrIdx is never checked for < 0, since the guard above only checks the upper bound.
  • cache.go:225-234 — dive,keys,<tags> with no endkeys silently swallows every remaining tag into the keys sub-chain instead of panicking with keysTagNotDefined, so dive,keys,eq=endkeys,min=10 loses the min=10 (verified). The endkeys branch four lines below does panic, so the two are inconsistent.
  • util.go:172-241 — the map branch is 14 copy-pasted blocks; any new key kind (uintptr, complex, interface keys) silently falls into the default string branch and panics rather than degrading to found=false. My helper is the natural place to collapse that, but it is a larger refactor than this fix should be.

@januththedev
januththedev requested a review from a team as a code owner September 28, 2026 13:13
@januththedev
januththedev force-pushed the fix/named-map-key-index branch from 7d0d98b to 41014e7 Compare October 3, 2026 10:13
Developed with AI assistance, disclosed here per CONTRIBUTING.md.
@januththedev
januththedev force-pushed the fix/named-map-key-index branch from 41014e7 to 714b7e2 Compare October 3, 2026 11:22
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