2023-10-10 13:20:53 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"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 composeOrigin(r *http.Request) string {
|
2023-10-17 13:01:47 +00:00
|
|
|
var proto, host string
|
|
|
|
fwd, fwdErr := httpforwarded.ParseFromRequest(r)
|
|
|
|
if fwdErr == nil {
|
|
|
|
proto = oldestForwardedValue(fwd, "proto")
|
|
|
|
host = oldestForwardedValue(fwd, "host")
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
2023-10-17 13:01:47 +00:00
|
|
|
if proto == "" {
|
|
|
|
proto = r.Header.Get("X-Forwarded-Proto")
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
|
|
|
if host == "" {
|
2023-10-17 13:01:47 +00:00
|
|
|
host = r.Header.Get("X-Forwarded-Host")
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
2023-10-17 13:01:47 +00:00
|
|
|
if proto == "" {
|
|
|
|
if r.TLS == nil {
|
|
|
|
proto = "http"
|
|
|
|
} else {
|
|
|
|
proto = "https"
|
|
|
|
}
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
2023-10-17 13:01:47 +00:00
|
|
|
if host == "" {
|
|
|
|
host = r.Host
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
2023-10-17 13:01:47 +00:00
|
|
|
return fmt.Sprintf("%s://%s", proto, host)
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|
|
|
|
|
2023-10-17 13:01:47 +00:00
|
|
|
func oldestForwardedValue(forwarded map[string][]string, key string) string {
|
2023-10-10 13:20:53 +00:00
|
|
|
if forwarded == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
values := forwarded[key]
|
|
|
|
if len(values) == 0 {
|
|
|
|
return ""
|
|
|
|
}
|
2023-10-17 13:01:47 +00:00
|
|
|
return values[0]
|
2023-10-10 13:20:53 +00:00
|
|
|
}
|