-
Notifications
You must be signed in to change notification settings - Fork 48
fix: support for path validation for odata-formatted openapi specs #127
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
Merged
daveshanley
merged 6 commits into
pb33f:main
from
Rishabh-Daga:support-for-odata-formatted-openapi-specs
Apr 14, 2025
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ec3867b
support for path validation for odata-formatted openapi specs
SAPRD2 0d56fe0
implemented path parameter matching
SAPRD2 a842844
gofumpt-ed files
SAPRD2 e8f21d4
remove printf error
SAPRD2 37f17c8
increased coverage
SAPRD2 11e8664
added godoc documentation
SAPRD2 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| package helpers | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "fmt" | ||
| "regexp" | ||
| "strings" | ||
| ) | ||
|
|
||
| // GetRegexForPath returns a compiled regular expression for the given path template. | ||
| // | ||
| // This function takes a path template string `tpl` and generates a regular expression | ||
| // that matches the structure of the template. The template can include placeholders | ||
| // enclosed in braces `{}` with optional custom patterns. | ||
| // | ||
| // Placeholders in the template can be defined as: | ||
| // - `{name}`: Matches any sequence of characters except '/' | ||
| // - `{name:pattern}`: Matches the specified custom pattern | ||
| // | ||
| // The function ensures that the template is well-formed, with balanced and properly | ||
| // nested braces. If the template is invalid, an error is returned. | ||
| // | ||
| // Parameters: | ||
| // - tpl: The path template string to convert into a regular expression. | ||
| // | ||
| // Returns: | ||
| // - *regexp.Regexp: A compiled regular expression that matches the template. | ||
| // - error: An error if the template is invalid or the regular expression cannot be compiled. | ||
| // | ||
| // Example: | ||
| // | ||
| // regex, err := GetRegexForPath("/orders/{id:[0-9]+}/items/{itemId}") | ||
| // // regex: ^/orders/([0-9]+)/items/([^/]+)$ | ||
| // // err: nil | ||
| func GetRegexForPath(tpl string) (*regexp.Regexp, error) { | ||
| // Check if it is well-formed. | ||
| idxs, errBraces := BraceIndices(tpl) | ||
| if errBraces != nil { | ||
| return nil, errBraces | ||
| } | ||
|
|
||
| // Backup the original. | ||
| template := tpl | ||
|
|
||
| // Now let's parse it. | ||
| defaultPattern := "[^/]*" | ||
|
|
||
| pattern := bytes.NewBufferString("^") | ||
| var end int | ||
|
|
||
| for i := 0; i < len(idxs); i += 2 { | ||
|
|
||
| // Set all values we are interested in. | ||
| raw := tpl[end:idxs[i]] | ||
| end = idxs[i+1] | ||
| parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) | ||
| name := parts[0] | ||
| patt := defaultPattern | ||
| if len(parts) == 2 { | ||
| patt = parts[1] | ||
| } | ||
|
|
||
| // Name or pattern can't be empty. | ||
| if name == "" || patt == "" { | ||
| return nil, fmt.Errorf("missing name or pattern in %q", tpl[idxs[i]:end]) | ||
| } | ||
|
|
||
| // Build the regexp pattern. | ||
| _, err := fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| } | ||
|
|
||
| // Add the remaining. | ||
| raw := tpl[end:] | ||
| pattern.WriteString(regexp.QuoteMeta(raw)) | ||
|
|
||
| pattern.WriteByte('$') | ||
|
|
||
| // Compile full regexp. | ||
| reg, errCompile := regexp.Compile(pattern.String()) | ||
| if errCompile != nil { | ||
| return nil, errCompile | ||
| } | ||
|
|
||
| // Check for capturing groups which used to work in older versions | ||
| if reg.NumSubexp() != len(idxs)/2 { | ||
| return nil, fmt.Errorf("route %s contains capture groups in its regexp. Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)", template) | ||
| } | ||
|
|
||
| // Done! | ||
| return reg, nil | ||
| } | ||
|
|
||
| // BraceIndices returns the indices of the opening and closing braces in a string. | ||
| // | ||
| // It scans the input string `s` and identifies the positions of matching pairs | ||
| // of braces ('{' and '}'). The function ensures that the braces are balanced | ||
| // and properly nested. | ||
| // | ||
| // If the braces are unbalanced or improperly nested, an error is returned. | ||
| // | ||
| // Parameters: | ||
| // - s: The input string to scan for braces. | ||
| // | ||
| // Returns: | ||
| // - []int: A slice of integers where each pair of indices represents the | ||
| // start and end positions of a matching pair of braces. | ||
| // - error: An error if the braces are unbalanced or improperly nested. | ||
| // | ||
| // Example: | ||
| // | ||
| // indices, err := BraceIndices("/orders/{id}/items/{itemId}") | ||
| // // indices: [8, 12, 19, 26] | ||
| // // err: nil | ||
| func BraceIndices(s string) ([]int, error) { | ||
|
Rishabh-Daga marked this conversation as resolved.
|
||
| var level, idx int | ||
| var idxs []int | ||
| for i := 0; i < len(s); i++ { | ||
| switch s[i] { | ||
| case '{': | ||
| if level++; level == 1 { | ||
| idx = i | ||
| } | ||
| case '}': | ||
| if level--; level == 0 { | ||
| idxs = append(idxs, idx, i+1) | ||
| } else if level < 0 { | ||
| return nil, fmt.Errorf("unbalanced braces in %q", s) | ||
| } | ||
| } | ||
| } | ||
| if level != 0 { | ||
| return nil, fmt.Errorf("unbalanced braces in %q", s) | ||
| } | ||
| return idxs, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| package helpers | ||
|
|
||
| import ( | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestGetRegexForPath(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| tpl string | ||
| wantErr bool | ||
| wantExpr string | ||
| }{ | ||
| { | ||
| name: "well-formed template with default pattern", | ||
| tpl: "/orders/{id}", | ||
| wantErr: false, | ||
| wantExpr: "^/orders/([^/]*)$", | ||
| }, | ||
| { | ||
| name: "well-formed template with custom pattern", | ||
| tpl: "/orders/{id:[0-9]+}", | ||
| wantErr: false, | ||
| wantExpr: "^/orders/([0-9]+)$", | ||
| }, | ||
| { | ||
| name: "missing name in template", | ||
| tpl: "/orders/{:pattern}", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "missing pattern in template", | ||
| tpl: "/orders/{name:}", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "unbalanced braces in template", | ||
| tpl: "/orders/{id", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "unbalanced braces in template", | ||
| tpl: "/orders/id}", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "template with multiple variables", | ||
| tpl: "/orders/{id:[0-9]+}/items/{itemId}", | ||
| wantErr: false, | ||
| wantExpr: "^/orders/([0-9]+)/items/([^/]*)$", | ||
| }, | ||
| { | ||
| name: "OData formatted URL with single quotes", | ||
| tpl: "/entities('{id}')", | ||
| wantErr: false, | ||
| wantExpr: "^/entities\\('([^/]*)'\\)$", | ||
| }, | ||
| { | ||
| name: "OData formatted URL with custom pattern", | ||
| tpl: "/entities('{id:[0-9]+}')", | ||
| wantErr: false, | ||
| wantExpr: "^/entities\\('([0-9]+)'\\)$", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got, err := GetRegexForPath(tt.tpl) | ||
| if (err != nil) != tt.wantErr { | ||
| t.Errorf("GetRegexForPath() error = %v, wantErr %v", err, tt.wantErr) | ||
| return | ||
| } | ||
| if !tt.wantErr && got.String() != tt.wantExpr { | ||
| t.Errorf("GetRegexForPath() = %v, want %v", got.String(), tt.wantExpr) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestBraceIndices(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| s string | ||
| want []int | ||
| wantErr bool | ||
| }{ | ||
| { | ||
| name: "well-formed braces", | ||
| s: "/orders/{id}/items/{itemId}", | ||
| want: []int{8, 12, 19, 27}, | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "unbalanced braces", | ||
| s: "/orders/{id/items/{itemId}", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "unbalanced braces", | ||
| s: "/orders/{id}/items/{itemId", | ||
| wantErr: true, | ||
| }, | ||
| { | ||
| name: "no braces", | ||
| s: "/orders/id/items/itemId", | ||
| want: []int{}, | ||
| wantErr: false, | ||
| }, | ||
| { | ||
| name: "OData formatted URL with single quotes", | ||
| s: "/entities('{id}')", | ||
| want: []int{11, 15}, | ||
| wantErr: false, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| got, err := BraceIndices(tt.s) | ||
| if (err != nil) != tt.wantErr { | ||
| t.Errorf("BraceIndices() error = %v, wantErr %v", err, tt.wantErr) | ||
| return | ||
| } | ||
| if !tt.wantErr && !equal(got, tt.want) { | ||
| t.Errorf("BraceIndices() = %v, want %v", got, tt.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func equal(a, b []int) bool { | ||
| if len(a) != len(b) { | ||
| return false | ||
| } | ||
| for i := range a { | ||
| if a[i] != b[i] { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.