fix: 审计问题全量修复 + RateLimiter 原子化重构 + CDN 本地化收紧
- 安全:移除 CSP 中 esm.sh/cdnjs.cloudflare.com,highlight.js 主题已本地化 73 个文件 - 安全:StatusBanned 分支补 dummy hash 防时序攻击 - 安全:手写 constantTimeEq 替换为 crypto/subtle.ConstantTimeCompare - Bug:锁定操作消息已删除→已锁定 - YAGNI:删除 12 个空预留模板目录 - KISS:删除 common.CheckPassword 薄封装,统一用 bcrypt 调用 - KISS:删除 tokenCtrl 别名字段,api.go 统一用 authCtrl - RateLimiter:check()+recordFail 闭包模式重构为 try() 原子操作,消除竞态 - RateLimiter:新增 ClearIP() 方法,注册成功时清除 IP 计数 - 文档:修正 audit_service.go 注释编号跳跃(3→5→4) - 文档:修正 deps_core.go 过清理→过期清理
This commit is contained in:
@ -12,9 +12,3 @@ func HashPassword(password string, cost int) (string, error) {
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
// CheckPassword 验证密码
|
||||
func CheckPassword(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@ -94,7 +94,7 @@ func (ac *AdminController) UpdateUserStatus(c *gin.Context) {
|
||||
if req.Status == model.StatusActive {
|
||||
action = "解封"
|
||||
} else if req.Status == model.StatusLocked {
|
||||
action = "已删除"
|
||||
action = "已锁定"
|
||||
}
|
||||
common.OkMessage(c, action+"成功")
|
||||
}
|
||||
|
||||
@ -31,15 +31,15 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
email := req.Email
|
||||
ip := clientIP(c)
|
||||
|
||||
// --- 限流:账户维度 ---
|
||||
acctResult, recordAccount := ac.rateLimiter.AllowAccount(email)
|
||||
// --- 限流:账户维度(原子检查+递增)---
|
||||
acctResult := ac.rateLimiter.AllowAccount(email)
|
||||
if acctResult.Blocked {
|
||||
common.Error(c, http.StatusTooManyRequests, acctResult.Message)
|
||||
return
|
||||
}
|
||||
|
||||
// --- 限流:IP 维度 ---
|
||||
ipResult, recordIP := ac.rateLimiter.AllowIP(ip)
|
||||
// --- 限流:IP 维度(原子检查+递增)---
|
||||
ipResult := ac.rateLimiter.AllowIP(ip)
|
||||
if ipResult.Blocked {
|
||||
common.Error(c, http.StatusTooManyRequests, ipResult.Message)
|
||||
return
|
||||
@ -47,14 +47,7 @@ func (ac *AuthController) Login(c *gin.Context) {
|
||||
|
||||
user, err := ac.authService.Login(req, ip)
|
||||
if err != nil {
|
||||
// 记录失败 → 两个维度各 +1
|
||||
if recordAccount != nil {
|
||||
recordAccount()
|
||||
}
|
||||
if recordIP != nil {
|
||||
recordIP()
|
||||
}
|
||||
|
||||
// 失败计数已在 AllowAccount/AllowIP 中原子递增,无需额外记录
|
||||
switch err {
|
||||
case common.ErrInvalidCred:
|
||||
common.Error(c, http.StatusUnauthorized, "邮箱或密码错误")
|
||||
|
||||
@ -34,8 +34,9 @@ func (ac *AuthController) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 注册 IP 限流:1 分钟 5 次
|
||||
regResult, recordReg := ac.rateLimiter.AllowIP(clientIP(c) + ":register")
|
||||
// 注册 IP 限流:1 分钟 5 次(原子检查+递增)
|
||||
regKey := clientIP(c) + ":register"
|
||||
regResult := ac.rateLimiter.AllowIP(regKey)
|
||||
if regResult.Blocked {
|
||||
common.Error(c, http.StatusTooManyRequests, "注册请求过于频繁,请稍后重试")
|
||||
return
|
||||
@ -43,9 +44,7 @@ func (ac *AuthController) Register(c *gin.Context) {
|
||||
|
||||
user, err := ac.authService.Register(req, clientIP(c))
|
||||
if err != nil {
|
||||
if recordReg != nil {
|
||||
recordReg()
|
||||
}
|
||||
// 失败计数已在 AllowIP 中原子递增,无需额外记录
|
||||
switch err {
|
||||
case common.ErrMaintenanceMode:
|
||||
common.Error(c, http.StatusForbidden, "社区正在维护中,暂不支持注册")
|
||||
@ -61,6 +60,9 @@ func (ac *AuthController) Register(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 注册成功 → 清除该 IP 的注册限流计数
|
||||
ac.rateLimiter.ClearIP(regKey)
|
||||
|
||||
sid, err := ac.sessionManager.Create(user, req.RememberMe, clientIP(c), c.GetHeader("User-Agent"))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "注册失败,请稍后重试")
|
||||
|
||||
@ -17,11 +17,12 @@ type authUseCase interface {
|
||||
IsRegistrationEnabled() bool
|
||||
}
|
||||
|
||||
// rateLimiter AuthController 对 RateLimiter 的最小依赖(ISP:3 个方法)
|
||||
// rateLimiter AuthController 对 RateLimiter 的最小依赖(ISP:4 个方法)
|
||||
type rateLimiter interface {
|
||||
AllowAccount(email string) (middleware.RateLimitResult, func())
|
||||
AllowIP(ip string) (middleware.RateLimitResult, func())
|
||||
AllowAccount(email string) middleware.RateLimitResult
|
||||
AllowIP(ip string) middleware.RateLimitResult
|
||||
Clear(email, ip string)
|
||||
ClearIP(ipKey string)
|
||||
}
|
||||
|
||||
// postUseCase PostController 对 PostService 的最小依赖(ISP:7 个方法)
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
@ -44,7 +45,7 @@ func CSRF(cfg *config.Config) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if !constantTimeEq(cookieToken, headerToken) {
|
||||
if subtle.ConstantTimeCompare([]byte(cookieToken), []byte(headerToken)) != 1 {
|
||||
log.Printf("[CSRF] MISMATCH | path=%s | cookie(len=%d)=%q | header(len=%d)=%q",
|
||||
c.Request.URL.Path, len(cookieToken), cookieToken, len(headerToken), headerToken)
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||
|
||||
@ -41,14 +41,4 @@ func generateCSRFToken() (string, error) {
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// constantTimeEq 恒定时间字符串比较(防时序攻击)
|
||||
func constantTimeEq(a, b string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
var result byte
|
||||
for i := 0; i < len(a); i++ {
|
||||
result |= a[i] ^ b[i]
|
||||
}
|
||||
return result == 0
|
||||
}
|
||||
|
||||
|
||||
@ -21,12 +21,14 @@ func NewRateLimiter() *RateLimiter {
|
||||
return rl
|
||||
}
|
||||
|
||||
// AllowAccount 检查账户维度是否允许登录尝试
|
||||
func (rl *RateLimiter) AllowAccount(email string) (RateLimitResult, func()) {
|
||||
return rl.check(rl.accountFailures, email, accountWindow, accountBlockDur, accountMaxFails, true)
|
||||
// AllowAccount 原子检查+递增帐户维度。未被封禁则递增失败计数并返回允许。
|
||||
// 调用方在操作成功(如登录成功)时应调用 Clear 清除计数。
|
||||
func (rl *RateLimiter) AllowAccount(email string) RateLimitResult {
|
||||
return rl.try(rl.accountFailures, email, accountWindow, accountBlockDur, accountMaxFails, true)
|
||||
}
|
||||
|
||||
// AllowIP 检查 IP 维度是否允许登录尝试
|
||||
func (rl *RateLimiter) AllowIP(ip string) (RateLimitResult, func()) {
|
||||
return rl.check(rl.ipFailures, ip, ipWindow, ipBlockDur, ipMaxFails, false)
|
||||
// AllowIP 原子检查+递增 IP 维度。未被封禁则递增失败计数并返回允许。
|
||||
// 调用方在操作成功时应调用 Clear 清除计数。
|
||||
func (rl *RateLimiter) AllowIP(ip string) RateLimitResult {
|
||||
return rl.try(rl.ipFailures, ip, ipWindow, ipBlockDur, ipMaxFails, false)
|
||||
}
|
||||
|
||||
@ -10,6 +10,13 @@ func (rl *RateLimiter) Clear(email, ip string) {
|
||||
delete(rl.ipFailures, ip)
|
||||
}
|
||||
|
||||
// ClearIP 按 IP key 清除失败计数(用于注册等仅 IP 维度的限流)
|
||||
func (rl *RateLimiter) ClearIP(ipKey string) {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
delete(rl.ipFailures, ipKey)
|
||||
}
|
||||
|
||||
// cleanupLoop 定期清理过期条目
|
||||
func (rl *RateLimiter) cleanupLoop() {
|
||||
ticker := time.NewTicker(cleanupInterval)
|
||||
|
||||
@ -30,8 +30,10 @@ type windowState struct {
|
||||
blockedUntil time.Time
|
||||
}
|
||||
|
||||
// check 核心检查逻辑
|
||||
func (rl *RateLimiter) check(m map[string]*windowState, key string, window, blockDur time.Duration, maxFails int, lowKey bool) (RateLimitResult, func()) {
|
||||
// try 原子检查+递增:在持锁状态下判断是否被限流,若允许则递增计数。
|
||||
// 检查与递增在同一临界区内完成,无竞态窗口。
|
||||
// 调用方需在操作成功后调用 Clear/或 ClearIP 清除计数。
|
||||
func (rl *RateLimiter) try(m map[string]*windowState, key string, window, blockDur time.Duration, maxFails int, lowKey bool) RateLimitResult {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
|
||||
@ -44,38 +46,28 @@ func (rl *RateLimiter) check(m map[string]*windowState, key string, window, bloc
|
||||
}
|
||||
}
|
||||
|
||||
// 已被封禁中
|
||||
if !state.blockedUntil.IsZero() && now.Before(state.blockedUntil) {
|
||||
retry := int(state.blockedUntil.Sub(now).Seconds()) + 1
|
||||
msg := "请求过于频繁,请稍后重试"
|
||||
if lowKey {
|
||||
msg = fmt.Sprintf("该账号登录尝试过于频繁,请 %d 秒后重试", retry)
|
||||
}
|
||||
return RateLimitResult{Blocked: true, RetryAfter: retry, Message: msg}, nil
|
||||
return RateLimitResult{Blocked: true, RetryAfter: retry, Message: msg}
|
||||
}
|
||||
|
||||
// 窗口过期 → 重置
|
||||
if now.Sub(state.windowStart) > window {
|
||||
state.count = 0
|
||||
state.windowStart = now
|
||||
state.blockedUntil = time.Time{}
|
||||
}
|
||||
|
||||
recordFail := func() {
|
||||
rl.mu.Lock()
|
||||
defer rl.mu.Unlock()
|
||||
s := m[key]
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if now.Sub(s.windowStart) > window {
|
||||
s.count = 1
|
||||
s.windowStart = now
|
||||
return
|
||||
}
|
||||
s.count++
|
||||
if s.count >= maxFails {
|
||||
s.blockedUntil = now.Add(blockDur)
|
||||
}
|
||||
// 原子递增计数(本次尝试已记录)
|
||||
state.count++
|
||||
if state.count >= maxFails {
|
||||
state.blockedUntil = now.Add(blockDur)
|
||||
}
|
||||
|
||||
return RateLimitResult{Blocked: false}, recordFail
|
||||
return RateLimitResult{Blocked: false}
|
||||
}
|
||||
|
||||
@ -9,16 +9,14 @@ import (
|
||||
func SecurityHeaders() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Content-Security-Policy
|
||||
// script-src: 本站 + esm.sh CDN (Tiptap ESM 模块) + cdnjs (highlight.js)
|
||||
// style-src: 本站 + esm.sh (Tiptap CSS) + cdnjs (highlight.js 主题)
|
||||
// connect-src: 本站 + esm.sh (source map 请求)
|
||||
// img-src: 本站 + data: URI (头像裁切) + blob: (粘贴图片)
|
||||
// script-src/style-src: 本站 + inline(highlight.js 主题已本地化在 static/vditor/ 下)
|
||||
// img-src: 本站 + data: URI(头像裁切)+ blob:(粘贴图片)
|
||||
c.Header("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline' https://esm.sh https://cdnjs.cloudflare.com; "+
|
||||
"style-src 'self' 'unsafe-inline' https://esm.sh https://cdnjs.cloudflare.com; "+
|
||||
"script-src 'self' 'unsafe-inline'; "+
|
||||
"style-src 'self' 'unsafe-inline'; "+
|
||||
"img-src 'self' data: blob:; "+
|
||||
"connect-src 'self' https://esm.sh")
|
||||
"connect-src 'self'")
|
||||
|
||||
// 禁止 MIME 类型嗅探
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
|
||||
@ -8,8 +8,8 @@ package model
|
||||
// 支持的 shortcode:
|
||||
// [zone:event:活动ID] → 官方活动卡片(标题、时间、封面、链接)
|
||||
// [zone:game:游戏slug] → 游戏信息卡片(名称、封面、类型)
|
||||
// [zone:poll:投票ID] → 投票组件(预留)
|
||||
// [zone:resource:资源ID] → 资源卡片(工具/素材推荐,预留)
|
||||
// [zone:poll:投票ID] → 投票卡片(※后端 API 开发中)
|
||||
// [zone:resource:资源ID] → 资源卡片(※后端 API 开发中)
|
||||
//
|
||||
// 扩展现有类型:在 ShortcodeRegistry 中注册新类型 + 实现 Renderer 即可。
|
||||
// =============================================================================
|
||||
@ -34,8 +34,8 @@ type ShortcodeType string
|
||||
const (
|
||||
ShortcodeEvent ShortcodeType = "event" // [zone:event:活动ID]
|
||||
ShortcodeGame ShortcodeType = "game" // [zone:game:游戏slug]
|
||||
ShortcodePoll ShortcodeType = "poll" // [zone:poll:投票ID] ※预留(后端API未实现)
|
||||
ShortcodeResource ShortcodeType = "resource" // [zone:resource:资源ID] ※预留(后端API未实现)
|
||||
ShortcodePoll ShortcodeType = "poll" // [zone:poll:投票ID] ※后端 API 开发中
|
||||
ShortcodeResource ShortcodeType = "resource" // [zone:resource:资源ID] ※后端 API 开发中
|
||||
)
|
||||
|
||||
// allTypes 所有已定义的 shortcode 类型,添加新类型时在这里追加
|
||||
|
||||
@ -40,12 +40,12 @@ func setupAPIRoutes(r *gin.Engine, cfg *config.Config, d *dependencies) {
|
||||
api := r.Group("/api")
|
||||
api.Use(middleware.CSRF(cfg))
|
||||
{
|
||||
api.POST("/auth/check-email", d.tokenCtrl.CheckEmail)
|
||||
api.POST("/auth/register", d.tokenCtrl.Register)
|
||||
api.POST("/auth/login", d.tokenCtrl.Login)
|
||||
api.POST("/auth/confirm-restore", d.tokenCtrl.ConfirmRestore)
|
||||
api.POST("/auth/logout", d.tokenCtrl.Logout)
|
||||
api.POST("/auth/refresh", d.tokenCtrl.RefreshToken)
|
||||
api.POST("/auth/check-email", d.authCtrl.CheckEmail)
|
||||
api.POST("/auth/register", d.authCtrl.Register)
|
||||
api.POST("/auth/login", d.authCtrl.Login)
|
||||
api.POST("/auth/confirm-restore", d.authCtrl.ConfirmRestore)
|
||||
api.POST("/auth/logout", d.authCtrl.Logout)
|
||||
api.POST("/auth/refresh", d.authCtrl.RefreshToken)
|
||||
|
||||
// 帖子公开 API(无需登录)
|
||||
api.GET("/posts", d.postCtrl.ListAPI)
|
||||
|
||||
@ -27,7 +27,6 @@ type dependencies struct {
|
||||
adminCtrl *adminCtrl.AdminController
|
||||
auditCtrl *adminCtrl.AuditController
|
||||
siteSettingCtrl *adminCtrl.SiteSettingController
|
||||
tokenCtrl *controller.AuthController
|
||||
}
|
||||
|
||||
func buildDepsCore(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSettings) (
|
||||
@ -42,7 +41,7 @@ func buildDepsCore(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSet
|
||||
time.Duration(cfg.Session.IdleTimeout)*time.Minute,
|
||||
time.Duration(cfg.Session.RememberTimeout)*time.Minute,
|
||||
)
|
||||
// 启动后台过清理 goroutine
|
||||
// 启动后台过期清理 goroutine
|
||||
sessionStore.StartCleanup(time.Duration(cfg.Session.CleanupInterval) * time.Second)
|
||||
|
||||
sessionMgr := session.NewManager(sessionStore, userRepo, cfg)
|
||||
|
||||
@ -51,6 +51,6 @@ func buildDeps(db *gorm.DB, cfg *config.Config, siteSettings *config.SiteSetting
|
||||
studioCtrl: studioCtrl,
|
||||
adminPostCtrl: adminPostCtrl,
|
||||
adminCtrl: adminController, auditCtrl: auditController,
|
||||
siteSettingCtrl: siteSettingController, tokenCtrl: authCtrl,
|
||||
siteSettingCtrl: siteSettingController,
|
||||
}
|
||||
}
|
||||
|
||||
@ -172,7 +172,7 @@ func (s *AuditService) review(reviewerID uint, submissionID uint, approved bool,
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
// 5. 标记审核结果
|
||||
// 4. 标记审核结果
|
||||
submission.ReviewedBy = &reviewerID
|
||||
submission.ReviewerName = &reviewer.Username
|
||||
if approved {
|
||||
|
||||
@ -135,7 +135,7 @@ func (s *AuthService) Login(req model.LoginRequest, loginIP string) (*model.User
|
||||
|
||||
// 已注销(deleted)→ 验证密码后要求二次确认
|
||||
if user.Status == model.StatusDeleted {
|
||||
if !common.CheckPassword(req.Password, user.PasswordHash) {
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)) != nil {
|
||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(req.Password))
|
||||
return nil, common.ErrInvalidCred
|
||||
}
|
||||
@ -150,10 +150,11 @@ func (s *AuthService) Login(req model.LoginRequest, loginIP string) (*model.User
|
||||
|
||||
// 封禁
|
||||
if user.Status == model.StatusBanned {
|
||||
_ = bcrypt.CompareHashAndPassword(dummyHash, []byte(req.Password))
|
||||
return nil, common.ErrUserBanned
|
||||
}
|
||||
|
||||
if !common.CheckPassword(req.Password, user.PasswordHash) {
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)) != nil {
|
||||
return nil, common.ErrInvalidCred
|
||||
}
|
||||
|
||||
@ -180,7 +181,7 @@ func (s *AuthService) ConfirmRestore(req model.LoginRequest, loginIP string) (*m
|
||||
return nil, common.ErrUserNotFound
|
||||
}
|
||||
|
||||
if !common.CheckPassword(req.Password, user.PasswordHash) {
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)) != nil {
|
||||
return nil, common.ErrInvalidCred
|
||||
}
|
||||
|
||||
@ -215,7 +216,7 @@ func (s *AuthService) ChangePassword(userID uint, currentPassword, newPassword s
|
||||
return common.ErrUserNotFound
|
||||
}
|
||||
|
||||
if !common.CheckPassword(currentPassword, user.PasswordHash) {
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(currentPassword)) != nil {
|
||||
return common.ErrIncorrectPassword
|
||||
}
|
||||
|
||||
@ -248,7 +249,7 @@ func (s *AuthService) DeleteAccount(userID uint, password, reason string) error
|
||||
return common.ErrOwnerCannotDelete
|
||||
}
|
||||
|
||||
if !common.CheckPassword(password, user.PasswordHash) {
|
||||
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)) != nil {
|
||||
return common.ErrIncorrectPassword
|
||||
}
|
||||
|
||||
|
||||
@ -124,14 +124,18 @@ func renderPlaceholder(sc model.Shortcode) string {
|
||||
)
|
||||
|
||||
case model.ShortcodePoll:
|
||||
// [zone:poll:投票ID] ※预留
|
||||
// [zone:poll:投票ID]
|
||||
// 前端根据投票ID获取标题、选项、截止时间等信息
|
||||
// ※后端 API 开发中
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="poll" data-zone-id="%s"><span class="zone-card-loading">投票组件加载中...</span></div>`,
|
||||
`<div class="zone-card" data-zone-type="poll" data-zone-id="%s"><span class="zone-card-loading">投票卡片加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
)
|
||||
|
||||
case model.ShortcodeResource:
|
||||
// [zone:resource:资源ID] ※预留
|
||||
// [zone:resource:资源ID]
|
||||
// 前端根据资源ID获取名称、描述、下载链接等信息
|
||||
// ※后端 API 开发中
|
||||
return fmt.Sprintf(
|
||||
`<div class="zone-card" data-zone-type="resource" data-zone-id="%s"><span class="zone-card-loading">资源卡片加载中...</span></div>`,
|
||||
html.EscapeString(sc.Params),
|
||||
|
||||
Reference in New Issue
Block a user