Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1707,6 +1707,7 @@ components:
- 20000
- 20100
- 20200
- 20201
- 20300
- 20400
- 20500
Expand All @@ -1715,6 +1716,7 @@ components:
- CodeSuccess
- CodeBadRequest
- CodeUnauthorized
- CodeRateLimited
- CodeNotFound
- CodeBusinessError
- CodeThirdPartyErr
Expand Down
2 changes: 1 addition & 1 deletion backend/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
7 changes: 5 additions & 2 deletions backend/cmd/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"tablewave/internal/service/datasource"
"tablewave/internal/service/queryrecord"
"tablewave/internal/service/sample"
"tablewave/internal/config"
)

// SetupRoutes configures all routes.
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 2 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
24 changes: 24 additions & 0 deletions backend/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ type Config struct {
ExtractDatasourceID int
// Alert 是指标预警(issue #155)的运行期配置:评估间隔 + SMTP 通知。
Alert AlertConfig
// Auth 是认证端点防护(issue #203)的运行期配置。
Auth AuthConfig
}

// AlertConfig 聚合预警模块的环境变量。SMTP 五项 + 收件人任何一项缺失都不拦启动:
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
26 changes: 24 additions & 2 deletions backend/internal/handler/auth.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package handler

import (
"errors"
"math"
"strconv"

"tablewave/internal/domain/entity"
"tablewave/internal/middleware"
"tablewave/internal/response"
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
90 changes: 90 additions & 0 deletions backend/internal/handler/auth_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions backend/internal/response/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const (
// 4xx 客户端错误
CodeBadRequest = 20100 // 请求参数错误
CodeUnauthorized = 20200 // 认证/授权错误
CodeRateLimited = 20201 // 认证端点限流/锁定(issue #203;HTTP 语义对应 429,信封码独立以便前端区分)
CodeNotFound = 20300 // 资源不存在
CodeBusinessError = 20400 // 业务逻辑错误
CodeThirdPartyErr = 20500 // 第三方服务错误
Expand Down
Loading
Loading