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

feat(router): allow users to have multiple wildcards cores allow_origins #1358

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 205 additions & 0 deletions router-tests/cors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
package integration
df-wg marked this conversation as resolved.
Show resolved Hide resolved

import (
"github.com/stretchr/testify/require"
"github.com/wundergraph/cosmo/router-tests/testenv"
"github.com/wundergraph/cosmo/router/core"
"github.com/wundergraph/cosmo/router/pkg/config"
"github.com/wundergraph/cosmo/router/pkg/cors"
"net/http"
"testing"
"time"
)

func TestCors(t *testing.T) {
t.Parallel()

t.Run("allow all origins allows requests", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
ModifyEngineExecutionConfiguration: func(cfg *config.EngineExecutionConfiguration) {
cfg.WebSocketReadTimeout = time.Millisecond * 10
},
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowAllOrigins: true,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://example.org",
})
require.NoError(t, err)
require.Equal(t, `{"data":{"initialPayload":{"extensions":{"token":"123"},"query":"{initialPayload}"}}}`, res.Body)
})
})

t.Run("disallowing origins blocks requests", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://example.com"},
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://not-example.com",
})
require.NoError(t, err)
require.Equal(t, "", res.Body)
require.Equal(t, http.StatusForbidden, res.Response.StatusCode)
})
})

t.Run("matching origins succeeds requests", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://example.com"},
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://example.com",
})
require.NoError(t, err)
require.Equal(t, `{"data":{"initialPayload":{"extensions":{"token":"123"},"query":"{initialPayload}"}}}`, res.Body)
})
})

t.Run("wildcard matching", func(t *testing.T) {
t.Run("matching wildcard with allow false fails", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://example.com/*"},
AllowWildcard: false,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://example.com/test",
})
require.NoError(t, err)
require.Equal(t, "", res.Body)
require.Equal(t, http.StatusForbidden, res.Response.StatusCode)
})
})

t.Run("matching single wildcard succeeds", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://example.com/*"},
AllowWildcard: true,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://example.com/test",
})
require.NoError(t, err)
require.Equal(t, `{"data":{"initialPayload":{"extensions":{"token":"123"},"query":"{initialPayload}"}}}`, res.Body)
})
})

t.Run("matching multiple wildcard succeeds", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://*example.com:*"},
AllowWildcard: true,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://matching.double.example.com:123/super-scary-extension",
})
require.NoError(t, err)
require.Equal(t, `{"data":{"initialPayload":{"extensions":{"token":"123"},"query":"{initialPayload}"}}}`, res.Body)
})
})

t.Run("matching multiple complex wildcards succeeds", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://*example.com:*"},
AllowWildcard: true,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://matching.double.example.com:123/super-scary-extension",
})
require.NoError(t, err)
require.Equal(t, `{"data":{"initialPayload":{"extensions":{"token":"123"},"query":"{initialPayload}"}}}`, res.Body)
})
})

t.Run("matching multiple wildcard fails", func(t *testing.T) {
t.Parallel()

testenv.Run(t, &testenv.Config{
RouterOptions: []core.Option{
core.WithCors(&cors.Config{
Enabled: true,
AllowOrigins: []string{"http://*example.com:*"},
AllowWildcard: true,
}),
},
}, func(t *testing.T, xEnv *testenv.Environment) {
res, err := xEnv.MakeGraphQLRequestWithHeaders(testenv.GraphQLRequest{
Query: `query { initialPayload }`,
Extensions: []byte(`{"token":"123"}`),
}, map[string]string{
"Origin": "http://not-matching.double.example.co:123/super-scary-extension",
})
require.NoError(t, err)
require.Equal(t, "", res.Body)
require.Equal(t, http.StatusForbidden, res.Response.StatusCode)
})
})
})
}
17 changes: 17 additions & 0 deletions router-tests/testenv/testenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,23 @@ func (e *Environment) MakeGraphQLRequestWithContext(ctx context.Context, request
return e.makeGraphQLRequest(req)
}

func (e *Environment) MakeGraphQLRequestWithHeaders(request GraphQLRequest, headers map[string]string) (*TestResponse, error) {
data, err := json.Marshal(request)
require.NoError(e.t, err)
req, err := http.NewRequestWithContext(e.Context, http.MethodPost, e.GraphQLRequestURL(), bytes.NewReader(data))
if err != nil {
return nil, err
}
if request.Header != nil {
req.Header = request.Header
}
req.Header.Set("Accept-Encoding", "identity")
for k, v := range headers {
req.Header.Set(k, v)
}
return e.makeGraphQLRequest(req)
}

func (e *Environment) MakeGraphQLRequestOverGET(request GraphQLRequest) (*TestResponse, error) {
req, err := e.newGraphQLRequestOverGET(e.GraphQLRequestURL(), request)
if err != nil {
Expand Down
71 changes: 54 additions & 17 deletions router/pkg/cors/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ type cors struct {
}

var (
DefaultSchemas = []string{
maxRecursionDepth = 10 // Safeguard against deep recursion
Aenimus marked this conversation as resolved.
Show resolved Hide resolved
DefaultSchemas = []string{
"http://",
"https://",
}
Expand Down Expand Up @@ -97,22 +98,6 @@ func (cors *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}

func (cors *cors) validateWildcardOrigin(origin string) bool {
for _, w := range cors.wildcardOrigins {
if w[0] == "*" && strings.HasSuffix(origin, w[1]) {
return true
}
if w[1] == "*" && strings.HasPrefix(origin, w[0]) {
return true
}
if strings.HasPrefix(origin, w[0]) && strings.HasSuffix(origin, w[1]) {
return true
}
}

return false
}

func (cors *cors) validateOrigin(origin string) bool {
if cors.allowAllOrigins {
return true
Expand All @@ -131,6 +116,58 @@ func (cors *cors) validateOrigin(origin string) bool {
return false
}

func (cors *cors) validateWildcardOrigin(origin string) bool {
for _, w := range cors.wildcardOrigins {
if matchOriginWithRule(origin, w, 0, map[string]bool{}) {
return true
}
}
return false
}

// Recursive helper function with depth limit and memoization
func matchOriginWithRule(origin string, rule []string, depth int, memo map[string]bool) bool {
if depth > maxRecursionDepth {
return false // Exceeded recursion depth
}

// Memoization key
key := origin + "|" + strings.Join(rule, "|")
if val, exists := memo[key]; exists {
return val
}

if len(rule) == 0 {
// Successfully matched if origin is also fully consumed
return origin == ""
}

part := rule[0]

if part == "*" {
// Try to match the remaining rule by advancing in origin
for i := 0; i <= len(origin); i++ {
if matchOriginWithRule(origin[i:], rule[1:], depth+1, memo) {
memo[key] = true
return true
}
}
memo[key] = false
return false
}

// Check if the origin starts with the current part
if strings.HasPrefix(origin, part) {
// Recursively check the rest of the origin and rule
result := matchOriginWithRule(origin[len(part):], rule[1:], depth+1, memo)
memo[key] = result
return result
}

memo[key] = false
return false
}

func (cors *cors) handlePreflight(w http.ResponseWriter) {
header := w.Header()
for key, value := range cors.preflightHeaders {
Expand Down
26 changes: 16 additions & 10 deletions router/pkg/cors/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,21 +123,27 @@ func (c *Config) parseWildcardRules() [][]string {
continue
}

if c := strings.Count(o, "*"); c > 1 {
df-wg marked this conversation as resolved.
Show resolved Hide resolved
panic(errors.New("only one * is allowed").Error())
}
// Split origin by wildcard (*)
parts := strings.Split(o, "*")

i := strings.Index(o, "*")
if i == 0 {
wRules = append(wRules, []string{"*", o[1:]})
// If there’s no wildcard, skip this origin
if len(parts) == 1 {
continue
}
if i == (len(o) - 1) {
wRules = append(wRules, []string{o[:i-1], "*"})
continue

// Generate rules for origins with multiple wildcard segments
var rule []string
for i, part := range parts {
if i > 0 {
rule = append(rule, "*") // Add wildcard indicator between segments
}
if part != "" {
rule = append(rule, part)
}
}

wRules = append(wRules, []string{o[:i], o[i+1:]})
// Add parsed rule to wRules
wRules = append(wRules, rule)
}

return wRules
Expand Down
Loading
Loading