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:
2026-05-31 11:13:32 +08:00
parent e1fb28e8fb
commit 55c408d86c
19 changed files with 504 additions and 94 deletions

View File

@ -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{

View File

@ -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
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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}
}

View File

@ -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: 本站 + inlinehighlight.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")