fix(origin): fall back to ExternalSecure (#7228)

* fix(origin): fall back to ExternalSecure

* avoid middleware.Middleware

* avoid else

* lint
This commit is contained in:
Elio Bischof
2024-01-15 17:44:35 +01:00
committed by GitHub
parent fc34896092
commit 29b386005d
3 changed files with 59 additions and 21 deletions

View File

@@ -4,25 +4,28 @@ import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/muhlemmer/httpforwarded"
"github.com/zitadel/logging"
http_util "github.com/zitadel/zitadel/internal/api/http"
)
func OriginHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := composeOrigin(r)
if !http_util.IsOrigin(origin) {
logging.Debugf("extracted origin is not valid: %s", origin)
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r.WithContext(http_util.WithComposedOrigin(r.Context(), origin)))
})
func WithOrigin(fallBackToHttps bool) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := composeOrigin(r, fallBackToHttps)
if !http_util.IsOrigin(origin) {
logging.Debugf("extracted origin is not valid: %s", origin)
next.ServeHTTP(w, r)
return
}
next.ServeHTTP(w, r.WithContext(http_util.WithComposedOrigin(r.Context(), origin)))
})
}
}
func composeOrigin(r *http.Request) string {
func composeOrigin(r *http.Request, fallBackToHttps bool) string {
var proto, host string
fwd, fwdErr := httpforwarded.ParseFromRequest(r)
if fwdErr == nil {
@@ -36,9 +39,8 @@ func composeOrigin(r *http.Request) string {
host = r.Header.Get("X-Forwarded-Host")
}
if proto == "" {
if r.TLS == nil {
proto = "http"
} else {
proto = "http"
if fallBackToHttps {
proto = "https"
}
}