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

Allow routing to wildcard subdomains #45

Merged
merged 1 commit into from
Oct 6, 2024
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
24 changes: 18 additions & 6 deletions internal/server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ func (m HostServiceMap) CheckHostAvailability(name string, hosts []string) *Serv
return nil
}

func (m HostServiceMap) ServiceForHost(host string) *Service {
service, ok := m[host]
if ok {
return service
}

sep := strings.Index(host, ".")
if sep > 0 {
service, ok := m["*"+host[sep:]]
if ok {
return service
}
}

return m[""]
}

type Router struct {
statePath string
services ServiceMap
Expand Down Expand Up @@ -338,12 +355,7 @@ func (r *Router) serviceForHost(host string) *Service {
r.serviceLock.RLock()
defer r.serviceLock.RUnlock()

service, ok := r.hostServices[host]
if !ok {
service = r.hostServices[""]
}

return service
return r.hostServices.ServiceForHost(host)
}

func (r *Router) setActiveTarget(name string, hosts []string, target *Target, options ServiceOptions, drainTimeout time.Duration) error {
Expand Down
81 changes: 81 additions & 0 deletions internal/server/router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,37 @@ func TestRouter_TargetWithoutHostActsAsWildcard(t *testing.T) {
assert.Equal(t, "second", body)
}

func TestRouter_TargetsAllowWildcardSubdomains(t *testing.T) {
router := testRouter(t)
_, first := testBackend(t, "first", http.StatusOK)
_, second := testBackend(t, "second", http.StatusOK)
_, fallback := testBackend(t, "fallback", http.StatusOK)

require.NoError(t, router.SetServiceTarget("first", []string{"*.first.example.com"}, first, defaultServiceOptions, defaultTargetOptions, DefaultDeployTimeout, DefaultDrainTimeout))
require.NoError(t, router.SetServiceTarget("second", []string{"*.second.example.com"}, second, defaultServiceOptions, defaultTargetOptions, DefaultDeployTimeout, DefaultDrainTimeout))
require.NoError(t, router.SetServiceTarget("fallback", defaultEmptyHosts, fallback, defaultServiceOptions, defaultTargetOptions, DefaultDeployTimeout, DefaultDrainTimeout))

statusCode, body := sendGETRequest(router, "http://app.first.example.com/")
assert.Equal(t, http.StatusOK, statusCode)
assert.Equal(t, "first", body)

statusCode, body = sendGETRequest(router, "http://api.second.example.com/")
assert.Equal(t, http.StatusOK, statusCode)
assert.Equal(t, "second", body)

statusCode, body = sendGETRequest(router, "http://something-else.example.com/")
assert.Equal(t, http.StatusOK, statusCode)
assert.Equal(t, "fallback", body)
}

func TestRouter_WildcardDomainsCannotBeUsedWithAutomaticTLS(t *testing.T) {
router := testRouter(t)
_, first := testBackend(t, "first", http.StatusOK)

err := router.SetServiceTarget("first", []string{"first.example.com", "*.first.example.com"}, first, ServiceOptions{TLSEnabled: true}, defaultTargetOptions, DefaultDeployTimeout, DefaultDrainTimeout)
require.Equal(t, ErrorAutomaticTLSDoesNotSupportWildcards, err)
}

func TestRouter_ServiceFailingToBecomeHealthy(t *testing.T) {
router := testRouter(t)
_, target := testBackend(t, "", http.StatusInternalServerError)
Expand Down Expand Up @@ -379,6 +410,56 @@ func TestRouter_RestoreLastSavedState(t *testing.T) {
assert.Equal(t, http.StatusMovedPermanently, statusCode)
}

func TestHostServiceMap_ServiceForHost(t *testing.T) {
hsm := HostServiceMap{
"example.com": &Service{name: "1"},
"app.example.com": &Service{name: "2"},
"api.example.com": &Service{name: "3"},
"*.example.com": &Service{name: "4"},
"": &Service{name: "5"},
}

assert.Equal(t, "1", hsm.ServiceForHost("example.com").name)
assert.Equal(t, "2", hsm.ServiceForHost("app.example.com").name)
assert.Equal(t, "3", hsm.ServiceForHost("api.example.com").name)
assert.Equal(t, "4", hsm.ServiceForHost("anything.example.com").name)

assert.Equal(t, "5", hsm.ServiceForHost("extra.level.example.com").name)
assert.Equal(t, "5", hsm.ServiceForHost("other.com").name)

hsm = HostServiceMap{
"example.com": &Service{name: "1"},
}

assert.Nil(t, hsm.ServiceForHost("app.example.com"))
}

func BenchmarkHostServiceMap_WilcardRouting(b *testing.B) {
hsm := HostServiceMap{
"one.example.com": &Service{},
"*.two.example.com": &Service{},
"": &Service{},
}

b.Run("exact match", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = hsm.ServiceForHost("one.example.com")
}
})

b.Run("wildcard match", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = hsm.ServiceForHost("anything.two.example.com")
}
})

b.Run("default match", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = hsm.ServiceForHost("missing.example.com")
}
})
}

// Helpers

func testRouter(t *testing.T) *Router {
Expand Down
14 changes: 12 additions & 2 deletions internal/server/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"os"
"path"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -45,8 +46,9 @@ const (
)

var (
ErrorRolloutTargetNotSet = errors.New("rollout target not set")
ErrorUnableToLoadErrorPages = errors.New("unable to load error pages")
ErrorRolloutTargetNotSet = errors.New("rollout target not set")
ErrorUnableToLoadErrorPages = errors.New("unable to load error pages")
ErrorAutomaticTLSDoesNotSupportWildcards = errors.New("automatic TLS does not support wildcards")
)

type TargetSlot int
Expand Down Expand Up @@ -308,6 +310,14 @@ func (s *Service) createCertManager(hosts []string, options ServiceOptions) (Cer
return NewStaticCertManager(options.TLSCertificatePath, options.TLSPrivateKeyPath)
}

// Ensure we're not trying to use Let's Encrypt to fetch a wildcard domain,
// as that is not supported with the challenge types that we use.
for _, host := range hosts {
if strings.Contains(host, "*") {
return nil, ErrorAutomaticTLSDoesNotSupportWildcards
}
}

return &autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache(options.ScopedCachePath()),
Expand Down