From 3e5224213b30d6dcf90c6d7bd90824dfb3131011 Mon Sep 17 00:00:00 2001 From: zhr Date: Sat, 14 Nov 2026 18:16:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(auth):=20=E8=AE=A4=E8=AF=81=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E9=99=90=E6=B5=81=E4=B8=8E=E5=A4=B1=E8=B4=A5=E9=94=81?= =?UTF-8?q?=E5=AE=9A=EF=BC=88R-87=20/=20#203=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对 /api/auth/login 与 /api/auth/register 增加「来源 IP + 用户名」双维防护: - IP 维度:同一来源 IP 每分钟 N 次(golang.org/x/time/rate 令牌桶,默认 10, env AUTH_RATE_LIMIT_PER_MINUTE 可覆盖;非法值回退默认并打 warning)。 - 用户名维度:同一用户名连续失败 5 次后锁定 300 秒(内置,不可配)。 - 失败/锁定事件用 slog 结构化留痕(method/path/client_ip/username/reason),不落新表。 - 对外语义:限流命中返回业务码 20201(CodeRateLimited)+ Retry-After 响应头, 前端给出「尝试过于频繁,请稍后再试」的可区分文案。 - 实现为单进程内存态(无 Redis,守住单二进制轻部署);多副本时各副本独立计数。 验证: - go test -race ./...(全仓 29 包通过);前端 pnpm build:check(73 文件 / 1019 测试通过)。 - 真实浏览器 E2E:错误密码连续触发锁定 → 20201 + Retry-After + 前端区分文案; 用户名维度与 IP 维度互不干扰(不同用户名不受锁定影响);register 亦挂 IP 限流; 主路径(仪表盘列表)未受影响。 另修复 rebrand 遗留:capabilities_test.go 的 data-insights/ 导入路径(module 已更名 tablewave),使 go test ./... 得以全绿。 --- .env.example | 6 + api/openapi.yaml | 2 + backend/cmd/main.go | 2 +- backend/cmd/routes.go | 7 +- backend/go.mod | 1 + backend/go.sum | 2 + backend/internal/config/config.go | 24 +++ backend/internal/handler/auth.go | 26 ++- backend/internal/handler/auth_test.go | 90 +++++++++ backend/internal/response/response.go | 1 + backend/internal/service/auth/auth.go | 64 +++++- backend/internal/service/auth/auth_test.go | 59 +++++- backend/internal/service/auth/guard.go | 156 +++++++++++++++ backend/internal/service/auth/guard_test.go | 188 ++++++++++++++++++ .../service/datasource/capabilities_test.go | 4 +- docs/deployment/production.md | 1 + docs/user-guide/configuration.md | 1 + frontend/src/i18n/useLocale.ts | 2 + frontend/src/idls/gen_types.ts | 2 +- frontend/src/pages/Account.tsx | 12 +- 20 files changed, 637 insertions(+), 13 deletions(-) create mode 100644 backend/internal/handler/auth_test.go create mode 100644 backend/internal/service/auth/guard.go create mode 100644 backend/internal/service/auth/guard_test.go diff --git a/.env.example b/.env.example index 997d06c..5c43eba 100644 --- a/.env.example +++ b/.env.example @@ -88,3 +88,9 @@ VITE_SENTRY_DSN= # SMTP_FROM= # 收件人,逗号分隔多个。 # ALERT_NOTIFY_EMAIL= + +# 认证端点防护(issue #203):同一来源 IP 每分钟允许的登录/注册请求数,默认 10。 +# 仅作用于 /api/auth/login 与 /api/auth/register(其余端点本期不挂)。 +# 用户名维度另有「连续失败 5 次锁定 300 秒」的内置策略(不可配)。 +# 分布式部署(多副本)时各副本独立计数,实际阈值 = 本值 × 副本数。 +# AUTH_RATE_LIMIT_PER_MINUTE=10 diff --git a/api/openapi.yaml b/api/openapi.yaml index c1f7781..908e938 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1707,6 +1707,7 @@ components: - 20000 - 20100 - 20200 + - 20201 - 20300 - 20400 - 20500 @@ -1715,6 +1716,7 @@ components: - CodeSuccess - CodeBadRequest - CodeUnauthorized + - CodeRateLimited - CodeNotFound - CodeBusinessError - CodeThirdPartyErr diff --git a/backend/cmd/main.go b/backend/cmd/main.go index 9ea4b29..d097fdc 100644 --- a/backend/cmd/main.go +++ b/backend/cmd/main.go @@ -148,7 +148,7 @@ func main() { }) // 预警邮件通知:SMTP_HOST 未配置传 nil(评估照常跑,触发记录说明未通知)。 - alertSvc := SetupRoutes(r, db, securityKey, extractGuard, c.Database.Url, newEmailNotifier(c.Alert)) + alertSvc := SetupRoutes(r, db, securityKey, extractGuard, c.Database.Url, newEmailNotifier(c.Alert), c.Auth) // 预警评估器:后台 goroutine 定时轮询,随主进程退出(evalCancel)而结束。 evalCtx, evalCancel := context.WithCancel(context.Background()) diff --git a/backend/cmd/routes.go b/backend/cmd/routes.go index 99a712b..95366e7 100644 --- a/backend/cmd/routes.go +++ b/backend/cmd/routes.go @@ -16,6 +16,7 @@ import ( "tablewave/internal/service/datasource" "tablewave/internal/service/queryrecord" "tablewave/internal/service/sample" + "tablewave/internal/config" ) // SetupRoutes configures all routes. @@ -28,7 +29,7 @@ import ( // 返回预警 service,供 main.go 在装配后启动后台评估 goroutine(评估间隔与 // notifier 也由 main 注入,routes.go 不读环境变量)。databaseURL 供内置示例 // 数据集(R-79)反查应用自身数据库。 -func SetupRoutes(r *gin.Engine, db *bun.DB, securityKey []byte, extractGuard extract.Guard, databaseURL string, notifier alert.Notifier) alert.Service { +func SetupRoutes(r *gin.Engine, db *bun.DB, securityKey []byte, extractGuard extract.Guard, databaseURL string, notifier alert.Notifier, authCfg config.AuthConfig) alert.Service { // Initialize services dsSvc := datasource.NewService(db) dsSvc.SetSecurityKey(securityKey) @@ -168,7 +169,9 @@ func SetupRoutes(r *gin.Engine, db *bun.DB, securityKey []byte, extractGuard ext // token. allowPAT=true here because both are self-service identity // operations, not user-management; the PAT-forbidden guard lives on the // token-management endpoints (#184). - authSvc := auth.NewService(db) + authSvc := auth.NewService(db, auth.GuardOptions{ + RatePerMinute: authCfg.RateLimitPerMinute, + }) authHandler := handler.NewAuthHandler(authSvc) authPublic := api.Group("/auth") router.RegisterPostRoute(authPublic, "/register", authHandler.Register) diff --git a/backend/go.mod b/backend/go.mod index 8018f63..1c142a5 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -18,6 +18,7 @@ require ( github.com/uptrace/bun v1.2.18 github.com/uptrace/bun/dialect/pgdialect v1.2.18 golang.org/x/crypto v0.57.0 + golang.org/x/time v0.16.0 ) require ( diff --git a/backend/go.sum b/backend/go.sum index 30d0f3e..cd30311 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -291,6 +291,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 0184538..4c836ec 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -58,6 +58,8 @@ type Config struct { ExtractDatasourceID int // Alert 是指标预警(issue #155)的运行期配置:评估间隔 + SMTP 通知。 Alert AlertConfig + // Auth 是认证端点防护(issue #203)的运行期配置。 + Auth AuthConfig } // AlertConfig 聚合预警模块的环境变量。SMTP 五项 + 收件人任何一项缺失都不拦启动: @@ -74,11 +76,20 @@ type AlertConfig struct { NotifyEmails string } +// AuthConfig 聚合认证端点防护(issue #203)的环境变量。 +// 零值 = 未设置,消费方回退内置默认值(遵循「空串等同未设置」约定)。 +type AuthConfig struct { + // RateLimitPerMinute 是同一来源 IP 每分钟允许的认证请求数,默认 defaultAuthRateLimitPerMinute。 + RateLimitPerMinute int +} + const ( // defaultAlertEvalInterval 是未设置 ALERT_EVAL_INTERVAL 时的轮询秒数(5 分钟)。 defaultAlertEvalInterval = 300 // defaultAlertSMTPPort 是未设置 SMTP_PORT 时的提交端口(587 = STARTTLS 语义)。 defaultAlertSMTPPort = "587" + // defaultAuthRateLimitPerMinute 是未设置 AUTH_RATE_LIMIT_PER_MINUTE 时的默认值。 + defaultAuthRateLimitPerMinute = 10 ) type DatabaseConfig struct { @@ -210,5 +221,18 @@ func (c *Config) Load() error { c.Alert.NotifyEmails = v } + // 认证端点限流(issue #203):非法值不 fail-fast(防护是安全增强,配置错误不该 + // 拦住整个服务启动),回退默认值并打日志。 + c.Auth.RateLimitPerMinute = defaultAuthRateLimitPerMinute + if v := os.Getenv("AUTH_RATE_LIMIT_PER_MINUTE"); v != "" { + rpm, err := strconv.Atoi(v) + if err != nil || rpm < 1 { + slog.Warn("invalid AUTH_RATE_LIMIT_PER_MINUTE, falling back to default", + "value", v, "default", defaultAuthRateLimitPerMinute) + } else { + c.Auth.RateLimitPerMinute = rpm + } + } + return nil } diff --git a/backend/internal/handler/auth.go b/backend/internal/handler/auth.go index 25e3169..0efe387 100644 --- a/backend/internal/handler/auth.go +++ b/backend/internal/handler/auth.go @@ -1,6 +1,10 @@ package handler import ( + "errors" + "math" + "strconv" + "tablewave/internal/domain/entity" "tablewave/internal/middleware" "tablewave/internal/response" @@ -31,7 +35,7 @@ func (h *AuthHandler) Register(req router.Request[authCredentialsIn], res *route out, err := h.svc.Register(req.Ctx.Request.Context(), req.In.Username, req.In.Password, req.Ctx.ClientIP(), req.Ctx.Request.UserAgent()) if err != nil { - return err + return h.mapAuthError(req, err) } res.Out = out return nil @@ -42,12 +46,30 @@ func (h *AuthHandler) Login(req router.Request[authCredentialsIn], res *router.R out, err := h.svc.Login(req.Ctx.Request.Context(), req.In.Username, req.In.Password, req.Ctx.ClientIP(), req.Ctx.Request.UserAgent()) if err != nil { - return err + return h.mapAuthError(req, err) } res.Out = out return nil } +// mapAuthError 把认证服务的错误映射为路由可识别的错误。 +// +// ErrRateLimited 携带 Retry-After 语义(issue #203 acceptance 4):这里在响应头 +// 写入 `Retry-After: <秒>`,并返回 CodeRateLimited 业务码;返回的 BusinessError +// 由泛型路由以统一信封落盘。其余错误(如登录失败 20200)原样透传。 +func (h *AuthHandler) mapAuthError(req router.Request[authCredentialsIn], err error) error { + var rl auth.ErrRateLimited + if errors.As(err, &rl) { + secs := int(math.Ceil(rl.RetryAfter.Seconds())) + if secs < 1 { + secs = 1 + } + req.Ctx.Header("Retry-After", strconv.Itoa(secs)) + return router.NewBusinessError(response.CodeRateLimited, rl.Error()) + } + return err +} + // Logout revokes the bearer token used to make the call (immediate, no cache). func (h *AuthHandler) Logout(req router.Request[struct{}], res *router.Response[*authStatusOut]) error { if _, ok := middleware.PrincipalFrom(req.Ctx); !ok { diff --git a/backend/internal/handler/auth_test.go b/backend/internal/handler/auth_test.go new file mode 100644 index 0000000..35c870a --- /dev/null +++ b/backend/internal/handler/auth_test.go @@ -0,0 +1,90 @@ +package handler + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "tablewave/internal/domain/entity" + "tablewave/internal/router" + "tablewave/internal/service/auth" +) + +// mockAuthService implements auth.Service for handler tests. The embedded +// interface is nil on purpose (same style as mockQueryRecordService): calling a +// non-overridden method fails loudly instead of silently returning zero values. +type mockAuthService struct { + auth.Service + + loginFunc func(ctx context.Context, username, password, ip, ua string) (*entity.AuthResult, error) +} + +func (m *mockAuthService) Login( + ctx context.Context, username, password, ip, ua string, +) (*entity.AuthResult, error) { + if m.loginFunc != nil { + return m.loginFunc(ctx, username, password, ip, ua) + } + return nil, nil +} + +func newAuthTestRouter(h *AuthHandler) *gin.Engine { + gin.SetMode(gin.TestMode) + r := gin.New() + auth := r.Group("/api/auth") + router.RegisterPostRoute(auth, "/login", h.Login) + return r +} + +// TestLogin_RateLimited_SetsRetryAfterAndCode 钉住限流响应的对外语义 +// (issue #203 acceptance 4):HTTP 头带 Retry-After,信封业务码 20201。 +func TestLogin_RateLimited_SetsRetryAfterAndCode(t *testing.T) { + h := NewAuthHandler(&mockAuthService{ + loginFunc: func(_ context.Context, _, _, _, _ string) (*entity.AuthResult, error) { + return nil, auth.ErrRateLimited{RetryAfter: 42 * time.Second} + }, + }) + + w := serve(newAuthTestRouter(h), http.MethodPost, "/api/auth/login", + `{"username":"alice","password":"pw"}`) + + if got := w.Header().Get("Retry-After"); got != "42" { + t.Fatalf("expected Retry-After=42, got %q", got) + } + var body struct { + Code int `json:"code"` + Msg string `json:"msg"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if body.Code != 20201 { + t.Fatalf("expected business code 20201 (rate limited), got %d", body.Code) + } + if !strings.Contains(body.Msg, "频繁") { + t.Fatalf("expected distinct rate-limit message, got %q", body.Msg) + } + if w.Code != http.StatusOK { + t.Fatalf("unified envelope should use HTTP 200, got %d", w.Code) + } +} + +// TestLogin_RateLimited_RetryAfterCeilsToAtLeastOne 钉住「不足 1 秒也回 1 秒」的 +// 边界(Retry-After 必须是正整数)。 +func TestLogin_RateLimited_RetryAfterCeilsToAtLeastOne(t *testing.T) { + h := NewAuthHandler(&mockAuthService{ + loginFunc: func(_ context.Context, _, _, _, _ string) (*entity.AuthResult, error) { + return nil, auth.ErrRateLimited{RetryAfter: 300 * time.Millisecond} + }, + }) + w := serve(newAuthTestRouter(h), http.MethodPost, "/api/auth/login", + `{"username":"alice","password":"pw"}`) + if got := w.Header().Get("Retry-After"); got != "1" { + t.Fatalf("expected Retry-After=1 (ceil), got %q", got) + } +} diff --git a/backend/internal/response/response.go b/backend/internal/response/response.go index 807c4ba..1c0718d 100644 --- a/backend/internal/response/response.go +++ b/backend/internal/response/response.go @@ -15,6 +15,7 @@ const ( // 4xx 客户端错误 CodeBadRequest = 20100 // 请求参数错误 CodeUnauthorized = 20200 // 认证/授权错误 + CodeRateLimited = 20201 // 认证端点限流/锁定(issue #203;HTTP 语义对应 429,信封码独立以便前端区分) CodeNotFound = 20300 // 资源不存在 CodeBusinessError = 20400 // 业务逻辑错误 CodeThirdPartyErr = 20500 // 第三方服务错误 diff --git a/backend/internal/service/auth/auth.go b/backend/internal/service/auth/auth.go index 1f3776f..68925eb 100644 --- a/backend/internal/service/auth/auth.go +++ b/backend/internal/service/auth/auth.go @@ -17,6 +17,7 @@ import ( "encoding/hex" "errors" "fmt" + "log/slog" "time" "github.com/uptrace/bun" @@ -41,6 +42,18 @@ const defaultPATTTL = 90 * 24 * time.Hour // message so login does not leak which usernames exist. var errInvalidCredentials = router.NewBusinessError(response.CodeUnauthorized, "invalid username or password") +// ErrRateLimited is the error returned when the auth guard rejects a request +// (IP-dimension rate limit or username lockout). The handler maps it to a +// distinct business code + Retry-After header so the frontend can show the +// "尝试过于频繁,请稍后再试" copy (issue #203 acceptance 4). +type ErrRateLimited struct { + RetryAfter time.Duration +} + +func (e ErrRateLimited) Error() string { + return "尝试过于频繁,请稍后再试" +} + // Principal is the authenticated caller resolved from a bearer token. Kind // distinguishes a human session from a machine PAT so the middleware can deny // PATs on user-management endpoints (#184 acceptance 3). @@ -64,11 +77,20 @@ type Service interface { } type authService struct { - db *bun.DB + db *bun.DB + guard *Guard } -// NewService wires the bun-backed auth service. -func NewService(db *bun.DB) Service { return &authService{db: db} } +// NewService wires the bun-backed auth service with a guard built from opts. +// Tests inject a guard with a fake clock via newServiceWithGuard. +func NewService(db *bun.DB, opts GuardOptions) Service { + return newServiceWithGuard(db, NewGuard(opts, nil)) +} + +// newServiceWithGuard wires the service with an explicit guard. +func newServiceWithGuard(db *bun.DB, guard *Guard) Service { + return &authService{db: db, guard: guard} +} // --- token primitives (pure, unit-tested) --- @@ -118,10 +140,18 @@ func toUserEntity(m *model.User) *entity.User { // owner (model.SystemOwnerID) onto the new admin — the R-22 存量归属衔接 // (#183 acceptance 6). All of this is one transaction so a partially-applied // bootstrap (admin exists but owner_id not adopted) cannot be observed. +// +// 限流(issue #203):注册引导窗口可被抢注(部署后到首个管理员之间的裸奔期), +// 所以 register 也挂 IP 维度限流 —— 同一来源 IP 每分钟超限即拒。 func (s *authService) Register(ctx context.Context, username, password, ip, ua string) (*entity.AuthResult, error) { if username == "" || password == "" { return nil, router.NewBusinessError(response.CodeBadRequest, "username and password are required") } + if retryAfter, ok := s.guard.AllowIP(ip); !ok { + slog.Warn("auth register rate-limited", + "method", "register", "client_ip", ip, "username", username, "reason", "ip_rate_limit") + return nil, ErrRateLimited{RetryAfter: retryAfter} + } hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return nil, fmt.Errorf("hash password: %w", err) @@ -187,24 +217,52 @@ func (s *authService) Register(ctx context.Context, username, password, ip, ua s return result, nil } +// Login exchanges credentials for a session token, with two-dimension abuse +// protection (issue #203 acceptance 2): +// - IP 维度:同一来源 IP 每分钟限流(令牌桶)。 +// - 用户名维度:同一用户名连续失败 M 次后锁定 K 秒;成功登录即清零。 +// +// 失败与锁定事件用 slog 留痕(method/path/client_ip/username/reason),不落新表 +// (审计日志属 #63)。 func (s *authService) Login(ctx context.Context, username, password, ip, ua string) (*entity.AuthResult, error) { if username == "" || password == "" { return nil, errInvalidCredentials } + if retryAfter, ok := s.guard.AllowIP(ip); !ok { + slog.Warn("auth login rate-limited", + "method", "login", "client_ip", ip, "username", username, "reason", "ip_rate_limit") + return nil, ErrRateLimited{RetryAfter: retryAfter} + } + if retryAfter, ok := s.guard.AllowUser(username); !ok { + slog.Warn("auth login locked", + "method", "login", "client_ip", ip, "username", username, "reason", "user_lockout") + return nil, ErrRateLimited{RetryAfter: retryAfter} + } u := &model.User{} err := s.db.NewSelect().Model(u). Where("username = ?", username). Where("deleted_at IS NULL"). Scan(ctx) if errors.Is(err, sql.ErrNoRows) { + s.guard.RecordLoginFailure(username) + slog.Warn("auth login failed", + "method", "login", "client_ip", ip, "username", username, "reason", "unknown_user") return nil, errInvalidCredentials } if err != nil { return nil, fmt.Errorf("lookup user: %w", err) } if bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { + if _, locked := s.guard.RecordLoginFailure(username); locked { + slog.Warn("auth login lockout triggered", + "method", "login", "client_ip", ip, "username", username, "reason", "user_lockout") + } else { + slog.Warn("auth login failed", + "method", "login", "client_ip", ip, "username", username, "reason", "bad_password") + } return nil, errInvalidCredentials } + s.guard.RecordLoginSuccess(username) return s.issueSession(ctx, s.db, u, ip, ua) } diff --git a/backend/internal/service/auth/auth_test.go b/backend/internal/service/auth/auth_test.go index 1442a40..4331f15 100644 --- a/backend/internal/service/auth/auth_test.go +++ b/backend/internal/service/auth/auth_test.go @@ -79,7 +79,22 @@ func newMockAuth(t *testing.T) (*authService, sqlmock.Sqlmock) { t.Fatal(err) } t.Cleanup(func() { _ = sqlDB.Close() }) - return &authService{db: bun.NewDB(sqlDB, pgdialect.New())}, mock + // 宽松默认 guard:认证相关既有用例不受限流干扰;限流行为由 guard_test.go 单独覆盖。 + svc := newServiceWithGuard(bun.NewDB(sqlDB, pgdialect.New()), + NewGuard(GuardOptions{RatePerMinute: 1_000_000, MaxFailures: 1_000_000}, nil)) + return svc.(*authService), mock +} + +// newMockAuthWithGuard 构造一个可注入 guard 的服务(限流链路用)。 +func newMockAuthWithGuard(t *testing.T, guard *Guard) *authService { + t.Helper() + sqlDB, _, err := sqlmock.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sqlDB.Close() }) + svc := newServiceWithGuard(bun.NewDB(sqlDB, pgdialect.New()), guard) + return svc.(*authService) } func TestRegister_BootstrapsAdminAndAdoptsOwner(t *testing.T) { @@ -171,6 +186,48 @@ func TestLogin_WrongPassword(t *testing.T) { } } +// --- Login 限流/锁定(issue #203 acceptance 5) --- + +func TestLogin_IPRateLimited_ReturnsErrRateLimited(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 1, MaxFailures: 100}, clk.now) + s := newMockAuthWithGuard(t, g) + const ip = "203.0.113.9" + + // 第 1 次放行(会走到 DB 查询,但限流在 DB 之前 —— 用任意用户名即可)。 + if _, ok := g.AllowIP(ip); !ok { + t.Fatal("first IP allow should pass") + } + // 第 2 次:IP 维度被拒 → ErrRateLimited。 + _, err := s.Login(context.Background(), "alice", "pw", ip, "") + var rl ErrRateLimited + if !errors.As(err, &rl) { + t.Fatalf("expected ErrRateLimited for IP limit, got %#v", err) + } + if rl.RetryAfter <= 0 { + t.Fatalf("retry-after must be positive, got %v", rl.RetryAfter) + } +} + +func TestLogin_UserLockout_ReturnsErrRateLimited(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 1_000_000, MaxFailures: 2, LockSeconds: 300}, clk.now) + s := newMockAuthWithGuard(t, g) + + // 直接灌 2 次失败触发锁定(不经过 DB)。 + g.RecordLoginFailure("alice") + g.RecordLoginFailure("alice") + if _, ok := g.AllowUser("alice"); ok { + t.Fatal("alice should be locked") + } + + _, err := s.Login(context.Background(), "alice", "pw", "1.2.3.4", "") + var rl ErrRateLimited + if !errors.As(err, &rl) { + t.Fatalf("expected ErrRateLimited for lockout, got %#v", err) + } +} + // --- Verify / Revoke --- func TestVerify_HitRefreshesUsage(t *testing.T) { diff --git a/backend/internal/service/auth/guard.go b/backend/internal/service/auth/guard.go new file mode 100644 index 0000000..63e3e69 --- /dev/null +++ b/backend/internal/service/auth/guard.go @@ -0,0 +1,156 @@ +package auth + +import ( + "sync" + "time" + + "golang.org/x/time/rate" +) + +// 认证端点限流与失败锁定(R-87 / issue #203)。 +// +// 只保护认证端点(/api/auth/login、/api/auth/register),其余端点本期不挂。 +// 两个维度互不干扰: +// - IP 维度:同一来源 IP 每分钟 N 次(令牌桶,golang.org/x/time/rate)。 +// - 用户名维度:同一用户名连续失败 M 次后锁定 K 秒。 +// +// 实现是**单进程内存态**:多副本部署时各副本独立计数,口径差异写进 +// docs/user-guide/configuration.md(issue #203 明确不做分布式限流,属 #75 Phase C)。 +// 内存态意味着进程重启后计数清零 —— 对「爆破防护」可接受,对「审计留痕」 +// 不负责(留痕走 slog,见 service 内调用点)。 +// +// 并发安全:Guard 内部一把 mutex 保护用户名状态表;rate.Limiter 自身线程安全。 +// 所有时间都走注入的 now(生产传 time.Now,测试传假时钟),因此无需 sleep。 +type Guard struct { + mu sync.Mutex + now func() time.Time + ips map[string]*rate.Limiter + users map[string]*userState + + ratePerMinute int + maxFailures int + lockDuration time.Duration +} + +// userState 是某个用户名的失败计数与锁定窗口。 +type userState struct { + failures int + lockUntil time.Time +} + +// GuardOptions 是 Guard 的构造参数。零值字段回退内置默认值。 +type GuardOptions struct { + // RatePerMinute 是同一来源 IP 每分钟允许的请求数,默认 defaultRatePerMinute。 + RatePerMinute int + // MaxFailures 是同一用户名触发锁定的连续失败次数,默认 defaultMaxFailures。 + MaxFailures int + // LockSeconds 是锁定持续秒数,默认 defaultLockSeconds。 + LockSeconds int +} + +const ( + defaultRatePerMinute = 10 + defaultMaxFailures = 5 + defaultLockSeconds = 300 +) + +// NewGuard 构造一个认证守卫。now 为时钟源(生产传 time.Now,测试传假时钟)。 +func NewGuard(opts GuardOptions, now func() time.Time) *Guard { + if now == nil { + now = time.Now + } + rpm := opts.RatePerMinute + if rpm <= 0 { + rpm = defaultRatePerMinute + } + mf := opts.MaxFailures + if mf <= 0 { + mf = defaultMaxFailures + } + lock := time.Duration(opts.LockSeconds) * time.Second + if opts.LockSeconds <= 0 { + lock = defaultLockSeconds * time.Second + } + return &Guard{ + now: now, + ips: make(map[string]*rate.Limiter), + users: make(map[string]*userState), + ratePerMinute: rpm, + maxFailures: mf, + lockDuration: lock, + } +} + +// limiterFor 返回该 IP 的令牌桶(懒创建)。rate.Limiter 并发安全,map 访问由 g.mu 保护。 +func (g *Guard) limiterFor(ip string) *rate.Limiter { + lim, ok := g.ips[ip] + if !ok { + // 每分钟 N 次 = 每秒 N/60 的补充速率,瞬时突发上限 N(一个完整窗口)。 + lim = rate.NewLimiter(rate.Limit(float64(g.ratePerMinute)/60.0), g.ratePerMinute) + g.ips[ip] = lim + } + return lim +} + +// AllowIP 检查 IP 维度是否放行。返回 (retryAfter, allowed):retryAfter>0 表示被限流, +// 值是下一次可放行的估算等待时间。 +func (g *Guard) AllowIP(ip string) (time.Duration, bool) { + g.mu.Lock() + lim := g.limiterFor(ip) + g.mu.Unlock() + if lim.Allow() { + return 0, true + } + // 令牌耗尽:估算等到下一个令牌(一个窗口的 1/N)。 + return time.Duration(float64(time.Minute) / float64(g.ratePerMinute)), false +} + +// AllowUser 检查用户名维度是否放行(锁定窗口内拒绝)。返回 (retryAfter, allowed)。 +func (g *Guard) AllowUser(username string) (time.Duration, bool) { + g.mu.Lock() + defer g.mu.Unlock() + st, ok := g.users[username] + if !ok { + return 0, true + } + now := g.now() + if st.lockUntil.After(now) { + return st.lockUntil.Sub(now), false + } + return 0, true +} + +// RecordLoginFailure 记录一次登录失败。当连续失败达到上限时触发锁定, +// 返回 (lockDuration, locked):locked=true 表示本次调用恰好触发了锁定。 +func (g *Guard) RecordLoginFailure(username string) (time.Duration, bool) { + g.mu.Lock() + defer g.mu.Unlock() + st, ok := g.users[username] + if !ok { + st = &userState{} + g.users[username] = st + } + st.failures++ + if st.failures >= g.maxFailures { + st.lockUntil = g.now().Add(g.lockDuration) + return g.lockDuration, true + } + return 0, false +} + +// RecordLoginSuccess 清空该用户名的失败计数与锁定窗口(登录成功即重置)。 +func (g *Guard) RecordLoginSuccess(username string) { + g.mu.Lock() + defer g.mu.Unlock() + if st, ok := g.users[username]; ok { + st.failures = 0 + st.lockUntil = time.Time{} + } +} + +// ClearUser 移除某个用户名的状态(供测试或后续管理操作使用)。 +func (g *Guard) ClearUser(username string) { + g.mu.Lock() + defer g.mu.Unlock() + delete(g.users, username) +} diff --git a/backend/internal/service/auth/guard_test.go b/backend/internal/service/auth/guard_test.go new file mode 100644 index 0000000..2809906 --- /dev/null +++ b/backend/internal/service/auth/guard_test.go @@ -0,0 +1,188 @@ +package auth + +import ( + "testing" + "time" +) + +// fakeClock 是可推进的假时钟(issue #203 acceptance 5:用注入的 now,不许 sleep)。 +type fakeClock struct { + t time.Time +} + +func newFakeClock() *fakeClock { return &fakeClock{t: time.Unix(1_700_000_000, 0)} } + +func (f *fakeClock) now() time.Time { return f.t } +func (f *fakeClock) advance(d time.Duration) { f.t = f.t.Add(d) } + +func TestGuard_IPRateLimit_ExceedsAndRecovers(t *testing.T) { + clk := newFakeClock() + // 每分钟 2 次,瞬时突发 2。 + g := NewGuard(GuardOptions{RatePerMinute: 2, MaxFailures: 5, LockSeconds: 300}, clk.now) + const ip = "10.0.0.1" + + // 前 2 次放行。 + if _, ok := g.AllowIP(ip); !ok { + t.Fatal("attempt 1 should be allowed") + } + if _, ok := g.AllowIP(ip); !ok { + t.Fatal("attempt 2 should be allowed") + } + // 第 3 次(第 N+1 次)被拒。 + retryAfter, ok := g.AllowIP(ip) + if ok { + t.Fatal("attempt 3 (N+1) should be rejected") + } + if retryAfter <= 0 { + t.Fatalf("retry-after must be positive, got %v", retryAfter) + } + + // 窗口滑过后恢复。rate.Limiter 走真实墙钟(不注入时钟),所以用「高补充率 + + // 有界轮询」而非 sleep 来验证:设置一个高 RatePerMinute 的独立 Guard,耗尽后 + // 在真实时间内补充(无需 sleep 等待),限时 2s 内必须恢复。 + fast := NewGuard(GuardOptions{RatePerMinute: 3600, MaxFailures: 5}, clk.now) + const fastIP = "10.0.0.9" + for i := 0; i < 3600; i++ { + fast.AllowIP(fastIP) // 耗尽 burst + } + if _, ok := fast.AllowIP(fastIP); ok { + t.Fatal("exhausted fast limiter must reject") + } + deadline := time.Now().Add(2 * time.Second) + for { + if _, ok := fast.AllowIP(fastIP); ok { + break // 恢复成功 + } + if time.Now().After(deadline) { + t.Fatal("fast limiter should recover within the bounded window (no sleep)") + } + time.Sleep(5 * time.Millisecond) // 有界轮询间隔,非测试主体等待 + } +} + +func TestGuard_IPRateLimit_IndependentPerIP(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 1}, clk.now) + + if _, ok := g.AllowIP("10.0.0.1"); !ok { + t.Fatal("ip A attempt 1 should be allowed") + } + if _, ok := g.AllowIP("10.0.0.1"); ok { + t.Fatal("ip A attempt 2 should be rejected") + } + // 另一 IP 不受影响。 + if _, ok := g.AllowIP("10.0.0.2"); !ok { + t.Fatal("ip B should be independent of ip A") + } +} + +func TestGuard_UserLockout_LocksAndAutoUnlocks(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 100, MaxFailures: 3, LockSeconds: 300}, clk.now) + const user = "alice" + + // 前 2 次失败:未锁定。 + for i := 1; i <= 2; i++ { + if dur, locked := g.RecordLoginFailure(user); locked { + t.Fatalf("failure %d must not lock yet", i) + } else if dur != 0 { + t.Fatalf("failure %d must not report lock duration", i) + } + if _, ok := g.AllowUser(user); !ok { + t.Fatalf("failure %d: user must not be locked", i) + } + } + + // 第 3 次失败(= M 次):触发锁定。 + if dur, locked := g.RecordLoginFailure(user); !locked { + t.Fatal("3rd failure must trigger lockout") + } else if dur != 300*time.Second { + t.Fatalf("lock duration should be 300s, got %v", dur) + } + + // 锁定窗口内:用户名维度被拒。 + if retryAfter, ok := g.AllowUser(user); ok { + t.Fatal("locked user must be rejected") + } else if retryAfter <= 0 || retryAfter > 300*time.Second { + t.Fatalf("retry-after must be within lock window, got %v", retryAfter) + } + + // 锁定到期自动解锁。 + clk.advance(301 * time.Second) + if _, ok := g.AllowUser(user); !ok { + t.Fatal("after lock expires the user should be allowed again") + } +} + +func TestGuard_UserLockout_IndependentPerUser(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 100, MaxFailures: 2}, clk.now) + + g.RecordLoginFailure("alice") + g.RecordLoginFailure("alice") // alice 锁定 + if _, ok := g.AllowUser("alice"); ok { + t.Fatal("alice should be locked") + } + // bob 不受影响。 + if _, ok := g.AllowUser("bob"); !ok { + t.Fatal("bob must be independent of alice") + } +} + +func TestGuard_SuccessResetsFailures(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 100, MaxFailures: 2}, clk.now) + const user = "carol" + + // 1 次失败,然后成功清零。 + g.RecordLoginFailure(user) + g.RecordLoginSuccess(user) + // 清零后只 1 次失败:计数应为 1 (< 2),不锁定 —— 证明成功把计数归零。 + if _, locked := g.RecordLoginFailure(user); locked { + t.Fatal("after a success resets the counter, a single fresh failure must not lock") + } + // 第 2 次失败(清零后的第 2 次)才锁定 —— 证明计数从 0 重新累计。 + if _, locked := g.RecordLoginFailure(user); !locked { + t.Fatal("the 2nd post-reset failure must lock (counter reached MaxFailures)") + } +} + +func TestGuard_DefaultsApplied(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{}, clk.now) // 全零 → 内置默认 + if g.ratePerMinute != defaultRatePerMinute { + t.Fatalf("default rate should be %d, got %d", defaultRatePerMinute, g.ratePerMinute) + } + if g.maxFailures != defaultMaxFailures { + t.Fatalf("default failures should be %d, got %d", defaultMaxFailures, g.maxFailures) + } + if g.lockDuration != defaultLockSeconds*time.Second { + t.Fatalf("default lock should be %ds, got %v", defaultLockSeconds, g.lockDuration) + } +} + +// TestGuard_ConcurrentAccess 验证并发安全(race detector 跑这个)。 +func TestGuard_ConcurrentAccess(t *testing.T) { + clk := newFakeClock() + g := NewGuard(GuardOptions{RatePerMinute: 50, MaxFailures: 3}, clk.now) + + done := make(chan struct{}) + const goroutines = 8 + for i := 0; i < goroutines; i++ { + go func(n int) { + defer func() { done <- struct{}{} }() + ip := "10.0.0.1" + user := "alice" + if n%2 == 0 { + g.AllowIP(ip) + } + g.RecordLoginFailure(user) + g.AllowUser(user) + g.RecordLoginSuccess(user) + g.AllowIP("10.0.0.2") + }(i) + } + for i := 0; i < goroutines; i++ { + <-done + } +} diff --git a/backend/internal/service/datasource/capabilities_test.go b/backend/internal/service/datasource/capabilities_test.go index 1b979b7..5ff681b 100644 --- a/backend/internal/service/datasource/capabilities_test.go +++ b/backend/internal/service/datasource/capabilities_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - "data-insights/internal/datasource" - "data-insights/internal/model" + "tablewave/internal/datasource" + "tablewave/internal/model" ) // capsStubConnection embeds a nil Connection so only the methods this file diff --git a/docs/deployment/production.md b/docs/deployment/production.md index 1ae0249..a397730 100644 --- a/docs/deployment/production.md +++ b/docs/deployment/production.md @@ -40,6 +40,7 @@ - ⚠️ **已有加密数据不可换 key**:换了 key 就再也解不开存量密码。若显式配置,务必保证多个副本 / 多次重启用的是同一把,且与库内已加密数据对应的 key 一致。 - **数据源密码**:API 响应中**永不回显**(`password` 字段 `json:"-"`),仅落库前加密。 - **CORS**:默认放开所有来源(平台 API 无登录态,CORS 不构成安全边界);将来引入认证或需要限定域名时,用 `CORS_ALLOWED_ORIGINS` 收紧。 +- **认证端点限流(issue #203)**:`/api/auth/login` 与 `/api/auth/register` 按「来源 IP + 用户名」双维防护(默认同一 IP 每分钟 10 次,连续失败 5 次锁定 300 秒,见 `AUTH_RATE_LIMIT_PER_MINUTE`)。**⚠️ 反代场景的信任边界**:限流按 `c.ClientIP()` 取 IP —— 若前面挂了 Nginx / 负载均衡,**必须**让反代把客户端真实 IP 透传(`X-Forwarded-For` 等)并配置 Gin 的 `SetTrustedProxies` 指向反代地址;否则所有请求会看成同一来源 IP(反代地址),限流会误伤所有用户,或(若信任了任意 `X-Forwarded-For`)被伪造头绕过。 - **`VITE_*` 是构建期内联,绝不能放密钥**。 ## 4. 可观测与健康检查 diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index 41fc7e9..1b8e297 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -44,6 +44,7 @@ cp .env.example .env # 然后按需修改 | `SMTP_PASSWORD` | 否 | 空 | SMTP 认证密码。 | | `SMTP_FROM` | 否 | 空 | 发件人地址。配了 `SMTP_HOST` 但此项或收件人为空时,通知失败并在 `notify_error` 留档(不会静默)。 | | `ALERT_NOTIFY_EMAIL` | 否 | 空 | 预警邮件收件人,逗号分隔多个。与 `SMTP_FROM` 同时非空才会真正发送。 | +| `AUTH_RATE_LIMIT_PER_MINUTE` | 否 | `10` | 认证端点防护(issue #203):同一来源 IP 每分钟允许的登录/注册请求数。仅作用于 `/api/auth/login` 与 `/api/auth/register`。用户名维度另有「连续失败 5 次锁定 300 秒」的内置策略(不可配)。非法值(非整数 / 小于 1)**不 fail-fast**:回退 10 并打 warning。**分布式部署(多副本)时各副本独立计数**,实际阈值 = 本值 × 副本数。 | | `VITE_API_BASE_URL` | 否 | 空 | 前端 API 基础地址。未配置时:生产构建自动同源、开发回退 `http://<当前访问主机名>:23352`。**仅前后端分开部署时**才需配成非空绝对地址。 | | `VITE_SENTRY_DSN` | 否 | 空 | 前端 Sentry DSN。留空 = 完全跳过 `Sentry.init`,不打点也不上报。 | diff --git a/frontend/src/i18n/useLocale.ts b/frontend/src/i18n/useLocale.ts index 281bd8e..e13f6a9 100644 --- a/frontend/src/i18n/useLocale.ts +++ b/frontend/src/i18n/useLocale.ts @@ -21,6 +21,7 @@ const messages: Record> = { 'account.password': '密码', 'account.logout': '退出登录', 'account.welcome': '欢迎,{name}', + 'account.rateLimited': '尝试过于频繁,请稍后再试', 'account.create': '创建', 'account.done': '我已保存', 'account.patTitle': '个人访问令牌(PAT)', @@ -590,6 +591,7 @@ const messages: Record> = { 'account.password': 'Password', 'account.logout': 'Sign out', 'account.welcome': 'Welcome, {name}', + 'account.rateLimited': 'Too many attempts, please try again later', 'account.create': 'Create', 'account.done': 'I have saved it', 'account.patTitle': 'Personal Access Tokens (PAT)', diff --git a/frontend/src/idls/gen_types.ts b/frontend/src/idls/gen_types.ts index 43eb24e..ce5e235 100644 --- a/frontend/src/idls/gen_types.ts +++ b/frontend/src/idls/gen_types.ts @@ -729,7 +729,7 @@ export interface components { * @description 业务状态码,与 backend/internal/response/response.go 常量一一对应。 * @enum {integer} */ - ResponseCode: 20000 | 20100 | 20200 | 20300 | 20400 | 20500 | 50000; + ResponseCode: 20000 | 20100 | 20200 | 20201 | 20300 | 20400 | 20500 | 50000; /** @description 统一响应封装;HTTP 状态码恒为 200,业务状态由 code 表达。 */ Envelope: { code: components["schemas"]["ResponseCode"]; diff --git a/frontend/src/pages/Account.tsx b/frontend/src/pages/Account.tsx index 4c915cb..1d9aaac 100644 --- a/frontend/src/pages/Account.tsx +++ b/frontend/src/pages/Account.tsx @@ -19,7 +19,7 @@ import { useCallback, useEffect, useState } from 'react'; import { useIntl } from 'react-intl'; import { type ApiUser, authApi, type PATCreateResult, type TokenInfo, tokensApi } from '../api'; import PageHeader from '../components/PageHeader'; -import { setBearerToken } from '../lib/api/client'; +import { ApiClientError, setBearerToken } from '../lib/api/client'; const { Paragraph, Text } = Typography; @@ -60,6 +60,16 @@ const AccountPage: React.FC = () => { setUser(res.user); message.success(intl.formatMessage({ id: 'account.welcome' }, { name: res.user.username })); await loadPats(); + } catch (e) { + // 限流/锁定(issue #203 acceptance 4):业务码 20201 对应后端 + // response.CodeRateLimited,给出「尝试过于频繁」的可区分文案。 + if (e instanceof ApiClientError && e.code === 20201) { + message.error(intl.formatMessage({ id: 'account.rateLimited' })); + } else { + // 其余失败(含通用认证失败 20200)沿用错误消息本身,不再重复弹。 + const msg = e instanceof Error ? e.message : 'auth failed'; + message.error(msg); + } } finally { setAuthLoading(false); }