fix: preserve loopback access for host configuration

- Keep internal loopback HTTP APIs reachable when the server is bound to a
specific non-loopback host by adding a dedicated 127.0.0.1 listener.

- Move listener address helpers into utils and normalize HTTPS redirect hosts so
IPv6 request hosts are not double-bracketed.
This commit is contained in:
wenjie
2026-04-24 10:29:16 +08:00
parent 1893912ba7
commit 2d67720022
3 changed files with 73 additions and 24 deletions

View File

@@ -34,22 +34,29 @@ func ListenAndServeLoopbackHTTPRedirect(
return
}
host := req.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if strings.Contains(host, ":") {
host = "[" + host + "]"
}
if httpsPort != "443" {
host += ":" + httpsPort
}
http.Redirect(w, req, "https://"+host+req.URL.RequestURI(), http.StatusTemporaryRedirect)
http.Redirect(w, req, "https://"+redirectHost(req.Host, httpsPort)+req.URL.RequestURI(), http.StatusTemporaryRedirect)
}))
}
func redirectHost(requestHost string, httpsPort string) string {
host := requestHost
if h, _, err := net.SplitHostPort(requestHost); err == nil {
host = h
} else if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = strings.TrimPrefix(strings.TrimSuffix(host, "]"), "[")
}
if httpsPort != "443" {
return net.JoinHostPort(host, httpsPort)
}
if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") && !strings.HasSuffix(host, "]") {
return "[" + host + "]"
}
return host
}
func allowByLoopbackInternalToken(req *http.Request) bool {
return req != nil && isLoopbackRemote(req.RemoteAddr) && hasValidLoopbackHTTPToken(req)
}