fix: 按可信入口转发的客户端 IP 限流邮箱验证码

This commit is contained in:
monster committed 2026-12-02 17:39:33 +08:00
1 parent 73c8650b70
commit 06de29e965
5 files changed
+115 -7

No files matched your search

+1 -7
View File
@@ -12,7 +12,6 @@ import (
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/web"
"log/slog"
"math/big"
"net"
"net/http"
"strings"
"time"
@@ -147,12 +146,7 @@ func (s *Service) sendCode(w http.ResponseWriter, r *http.Request) {
return
}
code := fmt.Sprintf("%06d", number.Int64())
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
slog.WarnContext(r.Context(), "操作失败", "module", "identity", "operation", "sendCode", "error", err)
ip = r.RemoteAddr
}
err = s.reserveCode(r.Context(), input, code, tokenHash(ip))
err = s.reserveCode(r.Context(), input, code, tokenHash(s.emailDeliveryIP(r)))
if errors.Is(err, errCodeLimited) {
w.Header().Set("Retry-After", "30")
writeError(r.Context(), w, 429, "rate_limited", "发送过于频繁,请稍后重试")
@@ -112,6 +112,32 @@ func TestEmailAutoRegistrationDefaultDisabled(t *testing.T) {
}
}
func TestEmailCodeLimitBehindIngress(t *testing.T) {
pool := emailDatabase(t)
s := newTestService(pool, authenticationStub{json.RawMessage(`{"email_code_enabled":true}`)}, "http://localhost").WithEmailSender(&mailStub{})
s.emailIngress = "192.0.2.10"
const client = "198.51.100.9"
if _, err := pool.Exec(t.Context(), `INSERT INTO email_code_deliveries (email, ip_hash)
SELECT 'prior' || n || '@example.com', $1 FROM generate_series(1,30) n`, tokenHash(client)); err != nil {
t.Fatal(err)
}
handler := s.AuthRouter()
send := func(ip string, want int) {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/email/code", strings.NewReader(`{"email":"next@example.com","purpose":"login"}`))
req.RemoteAddr = "192.0.2.10:443"
req.Header.Set("X-Real-IP", ip)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != want {
t.Fatalf("来源 %s: 状态码=%d,期望=%d", ip, rec.Code, want)
}
}
send(client, http.StatusTooManyRequests)
send("198.51.100.10", http.StatusOK)
send("198.51.100.11", http.StatusTooManyRequests) // 换来源也不能重复发送同一邮箱。
}
func TestEmailAuthentication(t *testing.T) {
pool := emailDatabase(t)
sender := &mailStub{}
@@ -0,0 +1,41 @@
package identity
import (
"context"
"net"
"net/http"
"net/netip"
"time"
)
func (s *Service) emailDeliveryIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
peer, err := netip.ParseAddr(host)
if err != nil {
return "unknown"
}
peer = peer.Unmap()
values := r.Header.Values("X-Real-IP")
if len(values) != 1 || s.emailIngress == "" {
return peer.String()
}
client, err := netip.ParseAddr(values[0])
if err != nil || client.Zone() != "" {
return peer.String()
}
// Nginx 会覆盖这个头。按入口服务名核对直连方,避免容器重建后信任旧 IP。
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
addresses, err := net.DefaultResolver.LookupNetIP(ctx, "ip", s.emailIngress)
if err == nil {
for _, address := range addresses {
if address.Unmap() == peer {
return client.Unmap().String()
}
}
}
return peer.String()
}
@@ -0,0 +1,45 @@
package identity
import (
"net/http/httptest"
"testing"
)
func TestEmailDeliveryIP(t *testing.T) {
if got := NewService(nil, nil, "").emailIngress; got != "nginx" {
t.Fatalf("默认入口 = %q,期望 nginx", got)
}
const proxy = "192.0.2.10"
const peer = "192.0.2.10:443"
const client = "198.51.100.9"
for _, tc := range []struct {
name, proxy, peer string
header []string
want string
}{
{"入口转发", proxy, peer, []string{client}, client},
{"同一入口另一客户端", proxy, peer, []string{"2001:db8::4"}, "2001:db8::4"},
{"入口服务名", "localhost", "127.0.0.1:8080", []string{client}, client},
{"映射地址使用同一额度", proxy, "[::ffff:192.0.2.10]:443", []string{"::ffff:198.51.100.9"}, client},
{"不同内网直连方", proxy, "172.18.0.3:443", []string{client}, "172.18.0.3"},
{"入口无法解析", "invalid host", peer, []string{client}, proxy},
{"没有真实地址", proxy, peer, nil, proxy},
{"重复地址头", proxy, peer, []string{client, client}, proxy},
{"无效地址", proxy, peer, []string{"not-an-ip"}, proxy},
{"地址列表", proxy, peer, []string{"198.51.100.1, 198.51.100.2"}, proxy},
{"带作用域地址", proxy, peer, []string{"fe80::1%zone"}, proxy},
} {
t.Run(tc.name, func(t *testing.T) {
s := &Service{emailIngress: tc.proxy}
r := httptest.NewRequest("POST", "/email/code", nil)
r.RemoteAddr = tc.peer
r.Header.Set("X-Forwarded-For", "203.0.113.100")
for _, value := range tc.header {
r.Header.Add("X-Real-IP", value)
}
if got := s.emailDeliveryIP(r); got != tc.want {
t.Fatalf("来源 IP = %q,期望 %q", got, tc.want)
}
})
}
}
@@ -142,6 +142,7 @@ type Service struct {
runtimeAccess RuntimeAccess
device *deviceAuthorization
email EmailSender
emailIngress string
accounts AccountPreserver
writer member.UserWriter
avatars ProfileStorage
@@ -167,6 +168,7 @@ type Service struct {
func NewService(db *pgxpool.Pool, settings SettingReader, publicURL string) *Service {
return &Service{
db: db,
emailIngress: "nginx",
settings: settings,
client: &http.Client{Timeout: 15 * time.Second},
publicURL: strings.TrimRight(publicURL, "/"),