Skip to content

Commit fe1c642

Browse files
erraggyclaude
andauthored
fix(generator): escape discriminator JSON names instead of allowlist filtering (#340)
* fix(generator): escape discriminator JSON names instead of allowlist filtering The allowlist approach would silently break JSON deserialization for specs with non-alphanumeric discriminator property names. Escape only the two characters that break Go struct tag syntax (" and \) so the tag matches the actual JSON key. Also align unmarshal.go.tmpl to use | quote pipe consistently with oneof.go.tmpl. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(generator): remove pre-escaping, rely on template quote pipe The builder was escaping " and \ before the template applied strconv.Quote via | quote, causing double-escaping. Remove pre-escaping entirely — the | quote pipe in both templates handles all necessary escaping for Go struct tag string literals. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent d5a1bf1 commit fe1c642

2 files changed

Lines changed: 2 additions & 10 deletions

File tree

generator/template_builders.go

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -444,15 +444,7 @@ func (cg *oas3CodeGenerator) buildOneOfTypeDefinition(typeName, originalName str
444444
if schema.Discriminator != nil && schema.Discriminator.PropertyName != "" {
445445
oneOfData.Discriminator = schema.Discriminator.PropertyName
446446
oneOfData.DiscriminatorField = toFieldName(schema.Discriminator.PropertyName)
447-
// Sanitize the discriminator property name to prevent injection in generated code.
448-
// Only allow alphanumeric, underscore, hyphen, and dot — safe for JSON struct tags.
449-
jsonName := strings.Map(func(r rune) rune {
450-
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == '.' {
451-
return r
452-
}
453-
return -1 // drop unsafe characters
454-
}, schema.Discriminator.PropertyName)
455-
oneOfData.DiscriminatorJSONName = jsonName
447+
oneOfData.DiscriminatorJSONName = schema.Discriminator.PropertyName
456448
oneOfData.HasUnmarshal = true
457449

458450
// Build unmarshal cases from discriminator mapping

generator/templates/types/unmarshal.go.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// UnmarshalJSON implements json.Unmarshaler for {{.TypeName}}.
22
func (u *{{.TypeName}}) UnmarshalJSON(data []byte) error {
33
var disc struct {
4-
{{.DiscriminatorField}} string `json:"{{.DiscriminatorJSONName}}"`
4+
{{.DiscriminatorField}} string `json:{{.DiscriminatorJSONName | quote}}`
55
}
66
if err := json.Unmarshal(data, &disc); err != nil {
77
return err

0 commit comments

Comments
 (0)