This repository has been archived on 2026-06-21. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MetaLab/internal/middleware/csrf.go
Victor_Jay 1cb7a832f1 fix: CSRF Token 日志脱敏
- 移除 CSF 中间件日志中敏感 token 值的打印(移除 %q)
- MISMATCH 日志仅保留路径和长度信息
- OK 日志移除,避免生产环境中泄露 CSRF token
2026-06-02 16:32:20 +08:00

61 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"crypto/subtle"
"log"
"net/http"
"metazone.cc/metalab/internal/config"
"github.com/gin-gonic/gin"
)
const (
csrfCookieName = "mlb_csrf"
csrfHeaderName = "X-CSRF-Token"
csrfMetaName = "csrf_token"
)
// CSRF 中间件Double Submit Cookie 模式
func CSRF(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodGet ||
c.Request.Method == http.MethodHead ||
c.Request.Method == http.MethodOptions {
c.Next()
return
}
cookieToken, err := c.Cookie(csrfCookieName)
if err != nil || cookieToken == "" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败",
})
return
}
headerToken := c.GetHeader(csrfHeaderName)
if headerToken == "" {
headerToken = c.PostForm(csrfMetaName)
}
if headerToken == "" {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败:缺少令牌",
})
return
}
if subtle.ConstantTimeCompare([]byte(cookieToken), []byte(headerToken)) != 1 {
log.Printf("[CSRF] MISMATCH | path=%s | cookie_len=%d | header_len=%d",
c.Request.URL.Path, len(cookieToken), len(headerToken))
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"success": false, "message": "CSRF 验证失败",
})
return
}
c.Set(csrfMetaName, cookieToken)
c.Next()
}
}