fix(middleware): Origin 同源校验增加 scheme 比对

http/https 不再视为同源;可信反代后采信 X-Forwarded-Proto(round2 P2-11),补测试。
This commit is contained in:
2026-09-08 17:32:57 +08:00
parent 1272d680a8
commit 3105b0415c
2 changed files with 60 additions and 3 deletions
+10 -3
View File
@@ -25,7 +25,8 @@ func OriginCheck(next http.Handler) http.Handler {
})
}
// sameOrigin 校验 Origin(或 Referer)的 host 与请求 Host 一致。
// sameOrigin 校验 Origin(或 Referer)与请求同源:host 一致且 scheme 与请求
// 实际 scheme 一致(TLS 直连为 https;可信反代后取 X-Forwarded-Proto,评审 round2 P2-11)。
func sameOrigin(r *http.Request) bool {
raw := r.Header.Get("Origin")
if raw == "" {
@@ -35,10 +36,16 @@ func sameOrigin(r *http.Request) bool {
return false
}
u, err := url.Parse(raw)
if err != nil || u.Host == "" {
if err != nil || u.Host == "" || u.Scheme == "" {
return false
}
return strings.EqualFold(u.Host, r.Host)
scheme := "http"
if r.TLS != nil {
scheme = "https"
} else if trueBehindProxy(r) && strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
scheme = "https"
}
return strings.EqualFold(u.Scheme, scheme) && strings.EqualFold(u.Host, r.Host)
}
func writeErr(w http.ResponseWriter, status int, code, msg string) {