feat(auth): implement session-based token management with revocation support
All checks were successful
Build Backend / build (push) Successful in 2m19s
Build Backend / build-docker (push) Successful in 46s

Add Session model, SessionService, and SessionRepository to track user login
sessions and enable token revocation on auth-critical events.

- Introduce explicit TokenType (access/refresh) in JWT claims to prevent
  refresh token misuse via access token endpoints
- Add SessionID field to JWT claims, enabling stateless JWT validation
  against revoked sessions
- Replace legacy Auth middleware with RequireAuth/OptionalAuth pipeline
  that validates token type, account status, and session validity
- Implement session revocation on password change, reset, user ban/inactive,
  and explicit logout
- Add Principal cache with active invalidation for banned/role-changed users
- Fix IDOR vulnerability: GetMessagesByCursor now validates currentUserID
  is conversation participant via GetParticipantStrict
- Add group member visibility checks: announcements, group info, member list
  now require group membership
- Simplify Casbin policy: remove g grouping, use r.sub == p.sub matcher
  with globMatch; user_roles table is single source of truth for roles
- Add migration logic to clean legacy casbin g rules and migrate old p rules
  from path-style to admin/<domain> resource naming
This commit is contained in:
lafay
2026-07-05 18:28:08 +08:00
parent d240485d0e
commit eb931bf1c6
41 changed files with 2544 additions and 360 deletions

View File

@@ -0,0 +1,35 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"with_you/internal/pkg/auth"
"with_you/internal/pkg/response"
)
// RequireActive 要求账户状态为 active。
//
// 业务策略:
// - active放行。
// - pending_deletion在 /users/me/* 路由允许(用户可取消注销),但在 /admin/* 与敏感操作拒绝。
// - banned/inactive已由 RequireAuth 在认证管道拦截,不会到达此处。
//
// 应挂在需要严格 active 状态的路由组上(如 /admin
func RequireActive() gin.HandlerFunc {
return func(c *gin.Context) {
p, ok := auth.GetPrincipal(c)
if !ok || p == nil {
response.ErrorWithStringCode(c, http.StatusUnauthorized, "UNAUTHORIZED", "未授权")
c.Abort()
return
}
if !p.IsActive() {
response.ErrorWithStringCode(c, http.StatusForbidden, "ACCOUNT_INACTIVE", "账号未激活")
c.Abort()
return
}
c.Next()
}
}

View File

@@ -1,76 +1,6 @@
package middleware
import (
"strings"
"github.com/gin-gonic/gin"
"with_you/internal/pkg/response"
"with_you/internal/service"
)
// Auth 认证中间件
func Auth(jwtService service.JWTService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
response.Unauthorized(c, "authorization header is required")
c.Abort()
return
}
// 提取Token
prefix, token, found := strings.Cut(authHeader, " ")
if !found || prefix != "Bearer" {
response.Unauthorized(c, "invalid authorization header format")
c.Abort()
return
}
// 验证Token
claims, err := jwtService.ParseToken(token)
if err != nil {
response.Unauthorized(c, "invalid token")
c.Abort()
return
}
// 将用户信息存入上下文
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Next()
}
}
// OptionalAuth 可选认证中间件
func OptionalAuth(jwtService service.JWTService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.Next()
return
}
// 提取Token
prefix, token, found := strings.Cut(authHeader, " ")
if !found || prefix != "Bearer" {
c.Next()
return
}
// 验证Token
claims, err := jwtService.ParseToken(token)
if err != nil {
c.Next()
return
}
// 将用户信息存入上下文
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
c.Next()
}
}
// Package middleware 提供路由层中间件。
//
// 注意:旧的 Auth/OptionalAuth 函数已被 auth_pipeline.go 中的
// RequireAuth / OptionalAuth 替代,新版本内置令牌类型校验、账户状态校验与会话校验。
// 路由层应使用 RequireAuth(jwt, idp, cache) 与 OptionalAuth(jwt, idp, cache)。
package middleware

View File

@@ -0,0 +1,287 @@
package middleware
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"gorm.io/gorm"
"with_you/internal/cache"
apperrors "with_you/internal/errors"
"with_you/internal/model"
"with_you/internal/pkg/auth"
"with_you/internal/pkg/jwt"
"with_you/internal/pkg/response"
"with_you/internal/service"
)
// 认证管道相关常量。
const (
// principalCacheTTL Principal 缓存 TTL账户状态/角色变更后最多延迟生效时间。
// 30s 内可容忍多一次 DB 查询,平衡安全即时性与登录热点流量。
principalCacheTTL = 30 * time.Second
// sessionCacheTTL 会话撤销状态缓存 TTL登出/封禁后旧 token 在此时长内可能仍被放行。
// 由于 session 表由服务端控制30s 内的撤销延迟可接受;后续可调整为 0不缓存
sessionCacheTTL = 30 * time.Second
)
// IdentityProvider 认证管道依赖的身份与角色查询接口。
//
// 由 service 层实现并注入,避免中间件直接依赖具体 service
// 同时便于测试以 fake 注入。
type IdentityProvider interface {
// GetUserByID 加载用户实体含状态、verification_status
GetUserByID(ctx context.Context, userID string) (*model.User, error)
// GetRolesForUser 返回用户的角色集合。
GetRolesForUser(ctx context.Context, userID string) ([]string, error)
// GetSessionByID 返回会话实体(用于校验是否撤销/过期)。
// 当 sessionID 为空(旧 access token 兼容窗口)应返回 nil,nil。
GetSessionByID(ctx context.Context, sessionID string) (*model.Session, error)
}
// principalCacheValue 缓存 Principal 的载体,便于区分 hit/miss 与缓存空角色。
type principalCacheValue struct {
Principal *auth.Principal
}
// RequireAuth 强制认证中间件。
//
// 流程:
// 1. 提取 Bearer token缺失 → 401。
// 2. ParseAccessToken拒绝 refresh token
// 3. 从 cache/DB 加载用户与角色,组装 Principal。
// 4. 校验账户状态active 允许pending_deletion 允许访问(业务策略:允许取消注销);
// banned/inactive/其他 → 403。
// 5. 校验 sessionIDsid 非空时):撤销/过期 → 401。
// 6. Principal 写入 context。
func RequireAuth(jwtService service.JWTService, idp IdentityProvider, cache cache.Cache) gin.HandlerFunc {
return func(c *gin.Context) {
claims, ok := extractAccessToken(c, jwtService)
if !ok {
authDeny(c, http.StatusUnauthorized, apperrors.ErrInvalidToken, "")
return
}
principal, err := buildPrincipal(c.Request.Context(), idp, cache, claims)
if err != nil {
// 用户不存在或加载失败:以 401 处理(令牌虽有效但身份已失效)。
authDeny(c, http.StatusUnauthorized, apperrors.ErrInvalidToken, claims.UserID)
return
}
if err := checkAccountStatus(principal); err != nil {
authDeny(c, http.StatusForbidden, err, principal.UserID)
return
}
if err := validateSession(c.Request.Context(), idp, cache, principal); err != nil {
authDeny(c, http.StatusUnauthorized, err, principal.UserID)
return
}
auth.WithContext(c, principal)
c.Next()
}
}
// OptionalAuth 可选认证中间件。
//
// 行为:
// - 缺失 Authorization 头 → 当游客Principal 不写入 contextc.Next()。
// - 携带了 token 但解析/状态/会话失败 → 401语义更清晰避免静默降级到游客
func OptionalAuth(jwtService service.JWTService, idp IdentityProvider, cache cache.Cache) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.Next()
return
}
// 格式明显错误(非 Bearer→ 当游客,保持现有游客可见接口语义。
prefix, token, found := strings.Cut(authHeader, " ")
if !found || prefix != "Bearer" || token == "" {
c.Next()
return
}
claims, err := jwtService.ParseAccessToken(token)
if err != nil {
authDeny(c, http.StatusUnauthorized, apperrors.ErrInvalidToken, "")
return
}
principal, err := buildPrincipal(c.Request.Context(), idp, cache, claims)
if err != nil {
authDeny(c, http.StatusUnauthorized, apperrors.ErrInvalidToken, claims.UserID)
return
}
if err := checkAccountStatus(principal); err != nil {
authDeny(c, http.StatusForbidden, err, principal.UserID)
return
}
if err := validateSession(c.Request.Context(), idp, cache, principal); err != nil {
authDeny(c, http.StatusUnauthorized, err, principal.UserID)
return
}
auth.WithContext(c, principal)
c.Next()
}
}
// extractAccessToken 从请求中提取并解析 access token。
//
// 第二返回值 ok=false 表示应当拒绝已写响应true 表示已拿到 claims。
func extractAccessToken(c *gin.Context, jwtService service.JWTService) (*jwt.Claims, bool) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
return nil, false
}
prefix, token, found := strings.Cut(authHeader, " ")
if !found || prefix != "Bearer" || token == "" {
return nil, false
}
claims, err := jwtService.ParseAccessToken(token)
if err != nil {
return nil, false
}
return claims, true
}
// buildPrincipal 从缓存或 IDP 加载用户/角色,组装 Principal。
func buildPrincipal(ctx context.Context, idp IdentityProvider, cch cache.Cache, claims *jwt.Claims) (*auth.Principal, error) {
cacheKey := ""
if cch != nil {
cacheKey = auth.PrincipalCacheKey(claims.UserID)
if cached, ok := cch.Get(cacheKey); ok {
if v, ok := cached.(*principalCacheValue); ok && v != nil {
return v.Principal, nil
}
}
}
user, err := idp.GetUserByID(ctx, claims.UserID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, apperrors.ErrUserNotFound
}
return nil, err
}
roles, err := idp.GetRolesForUser(ctx, claims.UserID)
if err != nil {
return nil, err
}
if roles == nil {
roles = []string{}
}
p := &auth.Principal{
UserID: user.ID,
Username: user.Username,
SessionID: claims.SessionID,
Status: user.Status,
VerificationStatus: user.VerificationStatus,
Roles: roles,
TokenID: claims.ID,
IsLegacyToken: claims.TokenType == "",
}
if cacheKey != "" {
cch.Set(cacheKey, &principalCacheValue{Principal: p}, principalCacheTTL)
}
return p, nil
}
// checkAccountStatus 校验账户状态。
//
// 策略active 允许pending_deletion 允许(用户可访问取消注销接口);
// banned/inactive/其他拒绝。pending_deletion 在管理后台路由由 RequireActive 单独再加一道。
func checkAccountStatus(p *auth.Principal) error {
switch p.Status {
case model.UserStatusActive, model.UserStatusPendingDeletion:
return nil
case model.UserStatusBanned:
return apperrors.ErrUserBanned
case model.UserStatusInactive:
return apperrors.ErrAccountInactive
default:
return apperrors.ErrAccountInactive
}
}
// validateSession 校验会话有效性。
//
// 旧 access token无 sid在兼容窗口内跳过会话校验由 access TTL 自然过期收口。
func validateSession(ctx context.Context, idp IdentityProvider, cch cache.Cache, p *auth.Principal) error {
if p.SessionID == "" {
// 旧 token 兼容窗口。
return nil
}
if cch != nil {
key := auth.SessionCacheKey(p.SessionID)
if cached, ok := cch.Get(key); ok {
if valid, ok := cached.(bool); ok && !valid {
return apperrors.ErrSessionRevoked
}
}
}
session, err := idp.GetSessionByID(ctx, p.SessionID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return apperrors.ErrSessionRevoked
}
return err
}
if session == nil || !session.IsValid(time.Now()) {
if cch != nil {
cch.Set(auth.SessionCacheKey(p.SessionID), false, sessionCacheTTL)
}
return apperrors.ErrSessionRevoked
}
if cch != nil {
cch.Set(auth.SessionCacheKey(p.SessionID), true, sessionCacheTTL)
}
return nil
}
// InvalidatePrincipalCache 与 InvalidateSessionCache 已迁移至 internal/pkg/auth 包,
// 以避免 service → middleware 的包循环service 层修改用户状态后需要失效缓存,
// 但 middleware 又依赖 service 接口)。
//
// 保留本文件中的 InvalidatePrincipalCache/InvalidateSessionCache 仅作为转发会引入
// 循环,故直接删除;调用方请使用 auth.InvalidatePrincipalCache / auth.InvalidateSessionCache。
// authDeny 拒绝访问的统一响应:记日志 + 返回结构化错误。
func authDeny(c *gin.Context, statusCode int, appErr error, userID string) {
zap.L().Warn("auth denied",
zap.Int("status", statusCode),
zap.String("user_id", userID),
zap.String("ip", c.ClientIP()),
zap.String("user_agent", c.GetHeader("User-Agent")),
zap.String("path", c.Request.URL.Path),
zap.Any("err", appErr),
)
code := apperrors.ErrInvalidToken.Code
msg := apperrors.ErrInvalidToken.Message
var target *apperrors.AppError
if errors.As(appErr, &target) {
code = target.Code
msg = target.Message
}
response.ErrorWithStringCode(c, statusCode, code, msg)
c.Abort()
}

View File

@@ -0,0 +1,225 @@
package middleware
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"with_you/internal/model"
"with_you/internal/pkg/jwt"
"with_you/internal/service"
)
// fakeIDP 实现 IdentityProvider 接口,用于测试。
type fakeIDP struct {
user *model.User
userErr error
roles []string
roleErr error
session *model.Session
sessErr error
}
func (f *fakeIDP) GetUserByID(ctx context.Context, id string) (*model.User, error) {
if f.userErr != nil {
return nil, f.userErr
}
return f.user, nil
}
func (f *fakeIDP) GetRolesForUser(ctx context.Context, id string) ([]string, error) {
if f.roleErr != nil {
return nil, f.roleErr
}
if f.roles == nil {
return []string{}, nil
}
return f.roles, nil
}
func (f *fakeIDP) GetSessionByID(ctx context.Context, id string) (*model.Session, error) {
if f.sessErr != nil {
return nil, f.sessErr
}
return f.session, nil
}
// newTestJWT 构造测试用 JWT 服务。
func newTestJWT() service.JWTService {
return service.NewJWTService("test-secret", 3600, 86400)
}
// runRequireAuth 挂载 RequireAuth 并发起请求,返回 (status, principal)。
//
// Authorization 头直接设在 req 上;旧实现里 r.Use 内重复 Set 对 NewRecorder 无效,已移除。
func runRequireAuth(t *testing.T, jwtSvc service.JWTService, idp IdentityProvider, token string) (int, *testPrincipal) {
t.Helper()
gin.SetMode(gin.TestMode)
nextCalled := false
r := gin.New()
r.GET("/test", RequireAuth(jwtSvc, idp, nil), func(c *gin.Context) {
nextCalled = true
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
r.ServeHTTP(w, req)
return w.Code, &testPrincipal{called: nextCalled}
}
type testPrincipal struct {
called bool
}
// TestRequireAuth_MissingHeader 缺失 Authorization → 401。
func TestRequireAuth_MissingHeader(t *testing.T) {
jwtSvc := newTestJWT()
idp := &fakeIDP{user: &model.User{ID: "u1", Status: model.UserStatusActive}}
code, _ := runRequireAuth(t, jwtSvc, idp, "")
if code != http.StatusUnauthorized {
t.Errorf("status = %d, want %d", code, http.StatusUnauthorized)
}
}
// TestRequireAuth_RefreshTokenRejected refresh token 走 RequireAuth → 401。
func TestRequireAuth_RefreshTokenRejected(t *testing.T) {
jwtSvc := newTestJWT()
// 用 SessionService.Issue 签发带 sid 的 refresh token 比较繁琐,这里直接用 JWT 层签发。
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
refreshTok, _ := jwtLib.GenerateRefreshToken("u1", "alice", "s1")
idp := &fakeIDP{user: &model.User{ID: "u1", Status: model.UserStatusActive}, session: &model.Session{ID: "s1", ExpiresAt: time.Now().Add(time.Hour)}}
code, _ := runRequireAuth(t, jwtSvc, idp, refreshTok)
if code != http.StatusUnauthorized {
t.Errorf("refresh token should be rejected, status = %d, want %d", code, http.StatusUnauthorized)
}
}
// TestRequireAuth_BannedUser banned 用户 → 403。
func TestRequireAuth_BannedUser(t *testing.T) {
jwtSvc := newTestJWT()
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
accessTok, _ := jwtLib.GenerateAccessToken("u1", "alice", "s1")
idp := &fakeIDP{
user: &model.User{ID: "u1", Status: model.UserStatusBanned},
roles: []string{},
session: &model.Session{ID: "s1", ExpiresAt: time.Now().Add(time.Hour)},
}
code, _ := runRequireAuth(t, jwtSvc, idp, accessTok)
if code != http.StatusForbidden {
t.Errorf("banned user should be 403, status = %d, want %d", code, http.StatusForbidden)
}
}
// TestRequireAuth_RevokedSession 会话已撤销 → 401。
func TestRequireAuth_RevokedSession(t *testing.T) {
jwtSvc := newTestJWT()
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
accessTok, _ := jwtLib.GenerateAccessToken("u1", "alice", "s1")
revokedAt := time.Now().Add(-time.Minute)
idp := &fakeIDP{
user: &model.User{ID: "u1", Status: model.UserStatusActive},
roles: []string{},
session: &model.Session{ID: "s1", ExpiresAt: time.Now().Add(time.Hour), RevokedAt: &revokedAt},
}
code, _ := runRequireAuth(t, jwtSvc, idp, accessTok)
if code != http.StatusUnauthorized {
t.Errorf("revoked session should be 401, status = %d, want %d", code, http.StatusUnauthorized)
}
}
// TestRequireAuth_UserNotFound 用户不存在 → 401。
func TestRequireAuth_UserNotFound(t *testing.T) {
jwtSvc := newTestJWT()
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
accessTok, _ := jwtLib.GenerateAccessToken("u1", "alice", "s1")
idp := &fakeIDP{
userErr: gorm.ErrRecordNotFound,
}
code, _ := runRequireAuth(t, jwtSvc, idp, accessTok)
if code != http.StatusUnauthorized {
t.Errorf("user not found should be 401, status = %d, want %d", code, http.StatusUnauthorized)
}
}
// TestRequireAuth_ValidAccess 正常 access token → 200 且 next 被调用。
func TestRequireAuth_ValidAccess(t *testing.T) {
jwtSvc := newTestJWT()
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
accessTok, _ := jwtLib.GenerateAccessToken("u1", "alice", "s1")
idp := &fakeIDP{
user: &model.User{ID: "u1", Status: model.UserStatusActive},
roles: []string{model.RoleUser},
session: &model.Session{ID: "s1", ExpiresAt: time.Now().Add(time.Hour)},
}
// 这里需要校验 next 被调用,所以用更完整的测试。
gin.SetMode(gin.TestMode)
nextCalled := false
r := gin.New()
r.GET("/test", RequireAuth(jwtSvc, idp, nil), func(c *gin.Context) {
nextCalled = true
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer "+accessTok)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("valid access token should be 200, status = %d, want %d", w.Code, http.StatusOK)
}
if !nextCalled {
t.Error("next handler should be called")
}
}
// TestRequireAuth_LegacyToken 旧 access token无 sid宽容通过。
func TestRequireAuth_LegacyToken(t *testing.T) {
jwtSvc := newTestJWT()
jwtLib := jwt.New("test-secret", time.Hour, time.Hour)
// 签发不带 sid 的 access token模拟旧客户端
accessTok, _ := jwtLib.GenerateAccessToken("u1", "alice", "")
idp := &fakeIDP{
user: &model.User{ID: "u1", Status: model.UserStatusActive},
roles: []string{},
// 旧 token 无 sidGetSessionByID 不应被调用。
}
gin.SetMode(gin.TestMode)
nextCalled := false
r := gin.New()
r.GET("/test", RequireAuth(jwtSvc, idp, nil), func(c *gin.Context) {
nextCalled = true
c.JSON(http.StatusOK, gin.H{"ok": true})
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer "+accessTok)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("legacy access token should be 200 (compat window), status = %d", w.Code)
}
if !nextCalled {
t.Error("next handler should be called for legacy token")
}
}
// fakeIDP 的 session 路径校验:确保不传 session 时也不影响。
var _ = errors.New

View File

@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
apperrors "with_you/internal/errors"
"with_you/internal/pkg/auth"
"with_you/internal/pkg/response"
"with_you/internal/service"
)
// Authorize 基于 Casbin 资源/动作策略的路由级授权中间件。
//
// 用法:挂在 RequireAuth 之后,按路由标注 (resource, action)。
// admin.POST("/users/:id/roles", middleware.Authorize(casbin, "admin/users/roles", "write"), h.AssignRole)
//
// 校验流程:
// 1. 从 context 取出 Principal由 RequireAuth 写入)。
// 2. 调 CasbinService.EnforceForUser(userID, resource, action)。
// - 内部先查 user_roles 表得到角色集合,再对每个角色调 Enforce(role, resource, action)。
// - super_admin 通过 admin/** 通配策略获得所有 admin 能力。
// 3. 不匹配 → 403 PERMISSION_DENIED。
//
// 纵深防御service 层对最敏感操作(如分配 super_admin应再次校验 operator 角色,
// 即使路由 Authorize 漏配Service 仍能拦截。
func Authorize(casbinService service.CasbinService, resource, action string) gin.HandlerFunc {
return func(c *gin.Context) {
p, ok := auth.GetPrincipal(c)
if !ok || p == nil {
response.ErrorWithStringCode(c, http.StatusUnauthorized, "UNAUTHORIZED", "未授权")
c.Abort()
return
}
allowed, err := casbinService.EnforceForUser(c.Request.Context(), p.UserID, resource, action)
if err != nil {
response.ErrorWithStringCode(c, http.StatusInternalServerError, "CASBIN_INTERNAL_ERROR", "权限系统内部错误")
c.Abort()
return
}
if !allowed {
response.ErrorWithStringCode(c, http.StatusForbidden, apperrors.ErrPermissionDenied.Code, apperrors.ErrPermissionDenied.Message)
c.Abort()
return
}
c.Next()
}
}