fix(admin): 登录审计记录真实来源 IP(经本机反代时取 XFF 末跳)
管理后台经 caddy mTLS 网关(同机 loopback 反代 127.0.0.1:9444)对外后, LoginSubmit 里 hostOnly(r.RemoteAddr) 恒为 127.0.0.1,admin_login_ok/fail 的 ip 字段失去溯源价值。 新增 realIP():仅当 TCP 对端是 loopback(请求确实来自本机可信反代)才信 X-Forwarded-For,且取**最后一跳**(Caddy 把真实 TCP 对端追加在末位,更早的 段可被客户端伪造预置);直连、XFF 缺失或非法值一律回退 TCP 对端。 IPAllow 白名单中间件刻意不变——安全闸继续只看 RemoteAddr,不受任何代理头 影响(维持原注释声明的边界)。 测试:TestRealIP 七例(直连/伪造头/单跳/多跳/缺失/非法/IPv6); go test ./internal/admin 全绿。(internal/store 迁移彩排 3 例失败为 HEAD 既有——主仓干净树复现,与本次无关。) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01P9G7E3wmAYL9KeYCVZVsqu
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// realIP:仅当 TCP 对端为 loopback(本机可信反代,如 caddy mTLS 网关)时才信
|
||||
// X-Forwarded-For 的最后一跳;其余情况一律用 TCP 对端,防止伪造头污染审计。
|
||||
func TestRealIP(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
remoteAddr string
|
||||
xff string
|
||||
want string
|
||||
}{
|
||||
{"直连无代理", "203.0.113.7:52011", "", "203.0.113.7"},
|
||||
{"直连时伪造 XFF 不可信", "203.0.113.7:52011", "1.2.3.4", "203.0.113.7"},
|
||||
{"经本机反代取 XFF 最后一跳", "127.0.0.1:38200", "198.51.100.23", "198.51.100.23"},
|
||||
{"多跳取最后一跳(前段可伪造)", "127.0.0.1:38200", "6.6.6.6, 198.51.100.23", "198.51.100.23"},
|
||||
{"本机反代但无 XFF 回退 loopback", "127.0.0.1:38200", "", "127.0.0.1"},
|
||||
{"XFF 非法值回退", "127.0.0.1:38200", "not-an-ip", "127.0.0.1"},
|
||||
{"IPv6 loopback 反代", "[::1]:38200", "198.51.100.23", "198.51.100.23"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest("POST", "/login", nil)
|
||||
r.RemoteAddr = c.remoteAddr
|
||||
if c.xff != "" {
|
||||
r.Header.Set("X-Forwarded-For", c.xff)
|
||||
}
|
||||
if got := realIP(r); got != c.want {
|
||||
t.Errorf("realIP(remote=%s, xff=%q) = %q, want %q", c.remoteAddr, c.xff, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user