From db759a1ad11d764f87645f42a0b314d8ccf40947 Mon Sep 17 00:00:00 2001 From: zuzuviewer <750938164@qq.com> Date: Fri, 21 Mar 2025 11:47:07 +0800 Subject: [PATCH] Fix s3 auth failed with X-Forwarded-Host and X-Forwarded-Port (#6650) --- weed/s3api/auth_signature_v4.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/weed/s3api/auth_signature_v4.go b/weed/s3api/auth_signature_v4.go index 33780a1cc..1e0453cc4 100644 --- a/weed/s3api/auth_signature_v4.go +++ b/weed/s3api/auth_signature_v4.go @@ -25,6 +25,7 @@ import ( "encoding/hex" "hash" "io" + "net" "net/http" "net/url" "regexp" @@ -720,16 +721,44 @@ func extractHostHeader(r *http.Request) string { // If X-Forwarded-Port is set, use that too to form the host. if forwardedHost != "" { extractedHost := forwardedHost - if forwardedPort != "" && forwardedPort != "80" && forwardedPort != "443" { - extractedHost = forwardedHost + ":" + forwardedPort + host, port, err := net.SplitHostPort(extractedHost) + if err == nil { + extractedHost = host + if forwardedPort == "" { + forwardedPort = port + } + } + if !isDefaultPort(r.URL.Scheme, forwardedPort) { + extractedHost = net.JoinHostPort(forwardedHost, forwardedPort) } return extractedHost } else { // Go http server removes "host" from Request.Header + host := r.Host + if host == "" { + host = r.URL.Host + } + h, port, err := net.SplitHostPort(host) + if err != nil { + return r.Host + } + if isDefaultPort(r.URL.Scheme, port) { + return h + } return r.Host } } +func isDefaultPort(scheme, port string) bool { + if port == "" { + return true + } + + lowerCaseScheme := strings.ToLower(scheme) + return (lowerCaseScheme == "http" && port == "80") || + (lowerCaseScheme == "https" && port == "443") +} + // getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names func getSignedHeaders(signedHeaders http.Header) string { var headers []string