From 351f22e21633addb9ac0a85bc0d16729258de437 Mon Sep 17 00:00:00 2001 From: William Petit Date: Wed, 29 Mar 2023 17:29:16 +0200 Subject: [PATCH] feat(controller,app): automatically redirect requests to cookie domain --- internal/agent/controller/app/server.go | 38 ++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/agent/controller/app/server.go b/internal/agent/controller/app/server.go index b3bbfc7..2da9395 100644 --- a/internal/agent/controller/app/server.go +++ b/internal/agent/controller/app/server.go @@ -3,11 +3,13 @@ package app import ( "context" "net/http" + "strings" "sync" "time" "forge.cadoles.com/Cadoles/emissary/internal/agent/controller/app/spec" appSpec "forge.cadoles.com/Cadoles/emissary/internal/agent/controller/app/spec" + "forge.cadoles.com/Cadoles/emissary/internal/proxy/wildcard" edgeHTTP "forge.cadoles.com/arcad/edge/pkg/http" authHTTP "forge.cadoles.com/arcad/edge/pkg/module/auth/http" "gitlab.com/wpetit/goweb/logger" @@ -109,7 +111,7 @@ func (s *Server) Stop() error { }() if err := s.server.Close(); err != nil { - panic(errors.WithStack(err)) + return errors.WithStack(err) } return nil @@ -140,6 +142,10 @@ func (s *Server) configureAuth(router chi.Router, auth *spec.Auth) error { } } + if s.auth.Local.CookieDomain != "" { + router.Use(invalidCookieDomainRedirect(s.auth.Local.CookieDomain)) + } + router.Handle("/auth/*", authHTTP.NewLocalHandler( jwa.HS256, key, authHTTP.WithRoutePrefix("/auth"), @@ -158,3 +164,33 @@ func NewServer(bundle bundle.Bundle, auth *appSpec.Auth, handlerOptions ...edgeH handlerOptions: handlerOptions, } } + +func invalidCookieDomainRedirect(cookieDomain string) func(http.Handler) http.Handler { + domain := strings.TrimPrefix(cookieDomain, ".") + hostPattern := "*" + domain + + return func(h http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + hostParts := strings.SplitN(r.Host, ":", 2) + + if !wildcard.Match(hostParts[0], hostPattern) { + url := r.URL + + newHost := domain + if len(hostParts) > 1 { + newHost += ":" + hostParts[1] + } + + url.Host = newHost + + http.Redirect(w, r, url.String(), http.StatusTemporaryRedirect) + + return + } + + h.ServeHTTP(w, r) + } + + return http.HandlerFunc(fn) + } +}