fix(user): withoutcancel audit, x-forwarded-for client ip

This commit is contained in:
2026-04-29 11:53:06 +08:00
parent 0f9c7fa657
commit 1e36f21ec4
2 changed files with 28 additions and 3 deletions
+20 -1
View File
@@ -97,7 +97,7 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
return
}
tok, u, err := h.svc.Login(r.Context(), req.Email, req.Password, r.RemoteAddr)
tok, u, err := h.svc.Login(r.Context(), req.Email, req.Password, clientIP(r))
if err != nil {
httpx.WriteError(w, rid, err)
return
@@ -142,3 +142,22 @@ func bearerFrom(r *http.Request) string {
}
return strings.TrimSpace(h[len(bearerPrefix):])
}
// clientIP 从请求头提取最接近真实客户端的 IP。优先级:X-Forwarded-For 首段
// > X-Real-IP > r.RemoteAddr。
//
// **安全提示**:当前未实现 trusted proxy 名单,X-Forwarded-For/X-Real-IP 可
// 被任意客户端伪造。生产部署必须在反向代理层 strip 客户端送来的这些头,仅
// 由代理本身写入;否则审计 IP 不可信。该问题在引入 ingress 配置时一并处理。
func clientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if comma := strings.IndexByte(xff, ','); comma > 0 {
return strings.TrimSpace(xff[:comma])
}
return strings.TrimSpace(xff)
}
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return strings.TrimSpace(xri)
}
return r.RemoteAddr
}