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

The regex pattern is not validated prior to executing the MatchString function #326

Open
agmanchon opened this issue Nov 21, 2024 · 0 comments

Comments

@agmanchon
Copy link

agmanchon commented Nov 21, 2024

If the regex pattern specified for a field in the JSON schema is invalid, the MatchString function fails. To prevent this, the pattern should be validated in advance, and MatchString code should only be generated for valid patterns. For example, the pattern "^(?!\s*$)[a-zA-Z0-9\.]*$" causes MatchString to fail because the Go regexp package does not support lookaheads. Implementing a validation step to check for such unsupported patterns before code generation is a suggested improvement.Attached is a potential solution implemented in the code:

if len(v.pattern) != 0 {
      if v.isNillable {
	      out.Printlnf("if %s != nil {", value)
	      out.Indent(1)
      }
      if _, err := regexp.Compile(v.pattern); err != nil {
	      fmt.Println("WARNING: regex pattern not compatible with go regexp library, ignoring ...")
      } else {
	      out.Printlnf(
		      `if matched, _ := regexp.MatchString(`+"`%s`"+`, string(%s%s)); !matched {`,
		      v.pattern, pointerPrefix, value,
	      )
	      out.Indent(1)
	      out.Printlnf(
		      `return fmt.Errorf("field %%s pattern match: must match %%s", `+"`%s`"+`, "%s")`,
		      v.pattern, v.fieldName,
	      )
	      out.Indent(-1)
	      out.Printlnf("}")
      
	      if v.isNillable {
		      out.Indent(-1)
		      out.Printlnf("}")
	      }
      }
}
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

No branches or pull requests

1 participant