Skip to content

Commit

Permalink
openapi3: support \uC4FE codepoint syntax in Schema.Pattern (#873)
Browse files Browse the repository at this point in the history
  • Loading branch information
fenollp committed Nov 26, 2023
1 parent 582e6d0 commit e7a726a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 16 deletions.
16 changes: 0 additions & 16 deletions openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -2011,22 +2011,6 @@ func (schema *Schema) expectedType(settings *schemaValidationSettings, value int
}
}

// NOTE: racey WRT [writes to schema.Pattern] vs [reads schema.Pattern then writes to compiledPatterns]
func (schema *Schema) compilePattern() (cp *regexp.Regexp, err error) {
pattern := schema.Pattern
if cp, err = regexp.Compile(pattern); err != nil {
err = &SchemaError{
Schema: schema,
SchemaField: "pattern",
Origin: err,
Reason: fmt.Sprintf("cannot compile pattern %q: %v", pattern, err),
}
return
}
var _ bool = compiledPatterns.CompareAndSwap(pattern, nil, cp)
return
}

// SchemaError is an error that occurs during schema validation.
type SchemaError struct {
// Value is the value that failed validation.
Expand Down
29 changes: 29 additions & 0 deletions openapi3/schema_pattern.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package openapi3

import (
"fmt"
"regexp"
)

var patRewriteCodepoints = regexp.MustCompile(`[\][u]([0-9A-F]{4})`)

// See https://pkg.go.dev/regexp/syntax
func intoGoRegexp(re string) string {
return patRewriteCodepoints.ReplaceAllString(re, `x{$1}`)
}

// NOTE: racey WRT [writes to schema.Pattern] vs [reads schema.Pattern then writes to compiledPatterns]
func (schema *Schema) compilePattern() (cp *regexp.Regexp, err error) {
pattern := schema.Pattern
if cp, err = regexp.Compile(intoGoRegexp(pattern)); err != nil {
err = &SchemaError{
Schema: schema,
SchemaField: "pattern",
Origin: err,
Reason: fmt.Sprintf("cannot compile pattern %q: %v", pattern, err),
}
return
}
var _ bool = compiledPatterns.CompareAndSwap(pattern, nil, cp)
return
}
18 changes: 18 additions & 0 deletions openapi3/schema_pattern_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package openapi3

import (
"regexp"
"testing"

"github.com/stretchr/testify/require"
)

func TestPattern(t *testing.T) {
_, err := regexp.Compile("^[a-zA-Z\\u0080-\\u024F\\s\\/\\-\\)\\(\\`\\.\\\"\\']+$")
require.EqualError(t, err, "error parsing regexp: invalid escape sequence: `\\u`")

_, err = regexp.Compile(`^[a-zA-Z\x{0080}-\x{024F}]+$`)
require.NoError(t, err)

require.Equal(t, `^[a-zA-Z\x{0080}-\x{024F}]+$`, intoGoRegexp(`^[a-zA-Z\u0080-\u024F]+$`))
}

0 comments on commit e7a726a

Please sign in to comment.