From f7f88ad6d8ce0867c1abbd2900fdfa3ed73311a1 Mon Sep 17 00:00:00 2001 From: huanghaosheng <386998068@qq.com> Date: Mon, 12 Oct 2026 23:06:51 +0800 Subject: [PATCH] =?UTF-8?q?fix(middleware):=20JWT=20=E5=AF=86=E9=92=A5?= =?UTF-8?q?=E6=9C=AA=E9=85=8D=E7=BD=AE=E6=97=B6=E8=BF=94=E5=9B=9E=20500=20?= =?UTF-8?q?=E8=80=8C=E9=9D=9E=20401?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 密钥未配置属服务端配置错误,此前与 token 过期一样返回 401,把排查方向引向前端与刷新逻辑,是 P0-1 难以定位的直接原因。 改为识别 ErrSecretNotConfigured 后返回 500 server auth misconfigured 并打 FATAL 日志;JWTAuth、SoftJWTAuth 与 SSE 鉴权三处同步。 --- backend/internal/middleware/jwt/jwt.go | 18 ++++++++++++++++++ backend/internal/worker/ssehub.go | 8 ++++++++ 2 files changed, 26 insertions(+) diff --git a/backend/internal/middleware/jwt/jwt.go b/backend/internal/middleware/jwt/jwt.go index 5640d47..83d58fc 100644 --- a/backend/internal/middleware/jwt/jwt.go +++ b/backend/internal/middleware/jwt/jwt.go @@ -34,6 +34,15 @@ func JWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Client) g claims, err := auth.ParseToken(tokenString) if err != nil { + // 服务端未正确配置密钥:这是 500 级故障,必须打 FATAL 日志, + // 绝不能伪装成 401,否则会出现静默误诊。 + if errors.Is(err, auth.ErrSecretNotConfigured) { + log.Printf("FATAL: JWT secret not configured; %s %s rejected", + c.Request.Method, c.Request.URL.Path) + c.AbortWithStatusJSON(http.StatusInternalServerError, + gin.H{"error": "server auth misconfigured"}) + return + } c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"}) return } @@ -59,6 +68,15 @@ func SoftJWTAuth(accountRepo *account.AccountRepository, cache *rediscache.Clien claims, err := auth.ParseToken(tokenString) if err != nil { + // 服务端未正确配置密钥:这是 500 级故障,必须打 FATAL 日志, + // 绝不能伪装成 401,否则会出现静默误诊。 + if errors.Is(err, auth.ErrSecretNotConfigured) { + log.Printf("FATAL: JWT secret not configured; %s %s rejected", + c.Request.Method, c.Request.URL.Path) + c.AbortWithStatusJSON(http.StatusInternalServerError, + gin.H{"error": "server auth misconfigured"}) + return + } c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid or expired token"}) return } diff --git a/backend/internal/worker/ssehub.go b/backend/internal/worker/ssehub.go index d5a8862..13dff55 100644 --- a/backend/internal/worker/ssehub.go +++ b/backend/internal/worker/ssehub.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "log" "net/http" "sync" "time" @@ -90,6 +91,13 @@ func (h *SSEHub) SSERequireAuth() gin.HandlerFunc { } claims, err := auth.ParseToken(token) if err != nil { + // 与 middleware/jwt 保持一致:密钥未配置属服务端故障(500),不是客户端凭证问题。 + if errors.Is(err, auth.ErrSecretNotConfigured) { + log.Printf("FATAL: JWT secret not configured; SSE %s rejected", c.Request.URL.Path) + c.AbortWithStatusJSON(http.StatusInternalServerError, + gin.H{"error": "server auth misconfigured"}) + return + } c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"}) return }