Skip to content

Commit

Permalink
test(middleware/cors): Add subdomain matching tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sixcolors committed Mar 17, 2024
1 parent de3f4ab commit b5b6c9f
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions middleware/cors/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package cors

import (
"testing"

"github.com/gofiber/fiber/v2/utils"
)

// go test -run -v Test_normalizeOrigin
Expand All @@ -16,6 +18,9 @@ func Test_normalizeOrigin(t *testing.T) {
{"http://example.com:3000", true, "http://example.com:3000"}, // Port should be preserved.
{"http://example.com:3000/", true, "http://example.com:3000"}, // Trailing slash should be removed.
{"http://", false, ""}, // Invalid origin should not be accepted.
{"file:///etc/passwd", false, ""}, // File scheme should not be accepted.
{"https://*example.com", false, ""}, // Wildcard domain should not be accepted.
{"http://*.example.com", false, ""}, // Wildcard subdomain should not be accepted.
{"http://example.com/path", false, ""}, // Path should not be accepted.
{"http://example.com?query=123", false, ""}, // Query should not be accepted.
{"http://example.com#fragment", false, ""}, // Fragment should not be accepted.
Expand Down Expand Up @@ -105,3 +110,50 @@ func Test_normalizeDomain(t *testing.T) {
}
}
}

func TestSubdomainMatch(t *testing.T) {
tests := []struct {
name string
sub subdomain
origin string
expected bool
}{
{
name: "match with valid subdomain",
sub: subdomain{prefix: "https://api.", suffix: ".example.com"},
origin: "https://api.service.example.com",
expected: true,
},
{
name: "no match with invalid prefix",
sub: subdomain{prefix: "https://api.", suffix: ".example.com"},
origin: "https://service.example.com",
expected: false,
},
{
name: "no match with invalid suffix",
sub: subdomain{prefix: "https://api.", suffix: ".example.com"},
origin: "https://api.example.org",
expected: false,
},
{
name: "no match with empty origin",
sub: subdomain{prefix: "https://api.", suffix: ".example.com"},
origin: "",
expected: false,
},
{
name: "partial match not considered a match",
sub: subdomain{prefix: "https://api.", suffix: ".example.com"},
origin: "https://api.example.com",
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.sub.match(tt.origin)
utils.AssertEqual(t, tt.expected, got, "subdomain.match()")
})
}
}

0 comments on commit b5b6c9f

Please sign in to comment.