Skip to content

Commit

Permalink
feat: support regex in allowed domains with prefix (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
medreza authored Jun 14, 2022
1 parent 5294249 commit 1ee57fd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/cors/cors_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package cors

import (
"errors"
"regexp"
"strconv"
"strings"

Expand All @@ -39,6 +41,10 @@ type CrossOriginResourceSharing struct {
Container *restful.Container
}

const (
AllowedDomainsRegexPrefix = "re:"
)

// Filter is a filter function that implements the CORS flow
func (c CrossOriginResourceSharing) Filter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
origin := req.Request.Header.Get(restful.HEADER_Origin)
Expand Down Expand Up @@ -135,6 +141,15 @@ func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool {
if domain == origin || domain == "*" {
return true
}
if strings.HasPrefix(domain, AllowedDomainsRegexPrefix) {
pattern, err := getPattern(domain)
if err != nil {
return false
}
if pattern.MatchString(origin) {
return true
}
}
}

return false
Expand All @@ -159,3 +174,11 @@ func (c CrossOriginResourceSharing) isValidAccessControlRequestHeader(header str
}
return false
}

func getPattern(str string) (*regexp.Regexp, error) {
split := strings.Split(str, AllowedDomainsRegexPrefix)
if len(split) < 2 {
return nil, errors.New("pattern not found")
}
return regexp.Compile(split[1])
}
11 changes: 11 additions & 0 deletions pkg/cors/cors_filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,17 @@ func TestIsOriginAllowed(t *testing.T) {
assert.True(t, corsWithWildcardAllowedDomain.isOriginAllowed("https://www.example.io.something"))
assert.True(t, corsWithWildcardAllowedDomain.isOriginAllowed("https://www.example.io.something.io"))

// TEST 5: Allowed domains with regex
corsWithRegex := CrossOriginResourceSharing{
AllowedDomains: []string{"re:https://([a-z0-9]+[.])*example.io$", "https://www.example.com"},
}
assert.True(t, corsWithRegex.isOriginAllowed("https://www.example.io"))
assert.True(t, corsWithRegex.isOriginAllowed("https://subdomain.example.io"))
assert.True(t, corsWithRegex.isOriginAllowed("https://www.example.com"))
assert.False(t, corsWithRegex.isOriginAllowed("https://subdomain.example.com"))
assert.False(t, corsWithRegex.isOriginAllowed("https://www.example.net"))
assert.False(t, corsWithRegex.isOriginAllowed("https://subdomain.example.io.something"))
assert.False(t, corsWithRegex.isOriginAllowed("https://www.example.io.something.io"))
}

func TestIsValidAccessControlRequestMethod(t *testing.T) {
Expand Down

0 comments on commit 1ee57fd

Please sign in to comment.