对 #4814 的审计跟进修复: - 域名尾随点绕过:user@gmail.com. 的域名不在 gmail 家族名单内,点号折叠与 googlemail 归一被整体跳过,别名刷号原样可复现。归一化入口统一去掉 FQDN 根点。 - 误拒合法用户:剥 "+后缀" 缺空串守卫,+alice@ 与 +bob@ 都折叠成 @domain, 该域后续 "+x@" 注册会永久 EMAIL_EXISTS 且无自助恢复。改为仅当 "+" 不在首位时剥离。 - 无界不可索引全表扫描:原实现按 LOWER(email) LIKE '%@domain' 把整域邮箱读进内存, 且挂在公开未鉴权的 send-verify-code 上。改为按去点邮箱 REPLACE(LOWER(TRIM(email)), '.', '') 做等值 + "local+%@domain" 前缀探针并带 LIMIT, 新增同表达式的部分索引(migrations/190)。TRIM 口径与既有精确匹配一致, 历史带首尾空白的行同样命中;LIKE 元字符转义,% 与 _ 不会扩大匹配面。 - 并发竞态:注册改走 CreateWithEmailAliasGuard,在邮箱唯一性锁上追加收件箱身份锁并在 锁内复查,避免同一收件箱的多个别名变体同时通过服务层前置查重。管理员建号仍走 Create,不受别名限制。 - 能力断言静默 fail-open:别名查重方法上提到 UserRepository 端口(编译期强制), 移除可选接口类型断言与静默降级分支。 - OAuth 邮箱注册的两条建号路径(同样发放注册赠额)纳入同一查重口径;邮箱换绑/绑定 不纳入,否则用户把邮箱改成自己收件箱的别名会被误拒。
254 lines
8.2 KiB
Go
254 lines
8.2 KiB
Go
//go:build unit
|
|
|
|
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/config"
|
|
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
|
"github.com/Wei-Shaw/sub2api/internal/service"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestAdminAuthJWTValidatesTokenVersion(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
cfg := &config.Config{JWT: config.JWTConfig{Secret: "test-secret", ExpireHour: 1}}
|
|
authService := service.NewAuthService(nil, nil, nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil, nil)
|
|
|
|
admin := &service.User{
|
|
ID: 1,
|
|
Email: "admin@example.com",
|
|
Role: service.RoleAdmin,
|
|
Status: service.StatusActive,
|
|
TokenVersion: 2,
|
|
Concurrency: 1,
|
|
}
|
|
|
|
userRepo := &stubUserRepo{
|
|
getByID: func(ctx context.Context, id int64) (*service.User, error) {
|
|
if id != admin.ID {
|
|
return nil, service.ErrUserNotFound
|
|
}
|
|
clone := *admin
|
|
return &clone, nil
|
|
},
|
|
}
|
|
userService := service.NewUserService(userRepo, nil, nil, nil)
|
|
|
|
router := gin.New()
|
|
router.Use(gin.HandlerFunc(NewAdminAuthMiddleware(authService, userService, nil, nil)))
|
|
router.GET("/t", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"ok": true})
|
|
})
|
|
|
|
t.Run("token_version_mismatch_rejected", func(t *testing.T) {
|
|
token, err := authService.GenerateToken(context.Background(), &service.User{
|
|
ID: admin.ID,
|
|
Email: admin.Email,
|
|
Role: admin.Role,
|
|
TokenVersion: admin.TokenVersion - 1,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/t", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
router.ServeHTTP(w, req)
|
|
|
|
require.Equal(t, http.StatusUnauthorized, w.Code)
|
|
require.Contains(t, w.Body.String(), "TOKEN_REVOKED")
|
|
})
|
|
|
|
t.Run("token_version_match_allows", func(t *testing.T) {
|
|
token, err := authService.GenerateToken(context.Background(), &service.User{
|
|
ID: admin.ID,
|
|
Email: admin.Email,
|
|
Role: admin.Role,
|
|
TokenVersion: admin.TokenVersion,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/t", nil)
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
router.ServeHTTP(w, req)
|
|
|
|
require.Equal(t, http.StatusOK, w.Code)
|
|
})
|
|
|
|
t.Run("websocket_token_version_mismatch_rejected", func(t *testing.T) {
|
|
token, err := authService.GenerateToken(context.Background(), &service.User{
|
|
ID: admin.ID,
|
|
Email: admin.Email,
|
|
Role: admin.Role,
|
|
TokenVersion: admin.TokenVersion - 1,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/t", nil)
|
|
req.Header.Set("Upgrade", "websocket")
|
|
req.Header.Set("Connection", "Upgrade")
|
|
req.Header.Set("Sec-WebSocket-Protocol", "sub2api-admin, jwt."+token)
|
|
router.ServeHTTP(w, req)
|
|
|
|
require.Equal(t, http.StatusUnauthorized, w.Code)
|
|
require.Contains(t, w.Body.String(), "TOKEN_REVOKED")
|
|
})
|
|
|
|
t.Run("websocket_token_version_match_allows", func(t *testing.T) {
|
|
token, err := authService.GenerateToken(context.Background(), &service.User{
|
|
ID: admin.ID,
|
|
Email: admin.Email,
|
|
Role: admin.Role,
|
|
TokenVersion: admin.TokenVersion,
|
|
})
|
|
require.NoError(t, err)
|
|
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/t", nil)
|
|
req.Header.Set("Upgrade", "websocket")
|
|
req.Header.Set("Connection", "Upgrade")
|
|
req.Header.Set("Sec-WebSocket-Protocol", "sub2api-admin, jwt."+token)
|
|
router.ServeHTTP(w, req)
|
|
|
|
require.Equal(t, http.StatusOK, w.Code)
|
|
})
|
|
}
|
|
|
|
type stubUserRepo struct {
|
|
getByID func(ctx context.Context, id int64) (*service.User, error)
|
|
}
|
|
|
|
func (s *stubUserRepo) Create(ctx context.Context, user *service.User) error {
|
|
panic("unexpected Create call")
|
|
}
|
|
|
|
func (s *stubUserRepo) CreateWithEmailAliasGuard(ctx context.Context, user *service.User) error {
|
|
panic("unexpected CreateWithEmailAliasGuard call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetByID(ctx context.Context, id int64) (*service.User, error) {
|
|
if s.getByID == nil {
|
|
panic("GetByID not stubbed")
|
|
}
|
|
return s.getByID(ctx, id)
|
|
}
|
|
|
|
func (s *stubUserRepo) GetByEmail(ctx context.Context, email string) (*service.User, error) {
|
|
panic("unexpected GetByEmail call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetFirstAdmin(ctx context.Context) (*service.User, error) {
|
|
panic("unexpected GetFirstAdmin call")
|
|
}
|
|
|
|
func (s *stubUserRepo) Update(ctx context.Context, user *service.User) error {
|
|
panic("unexpected Update call")
|
|
}
|
|
|
|
func (s *stubUserRepo) Delete(ctx context.Context, id int64) error {
|
|
panic("unexpected Delete call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetUserAvatar(ctx context.Context, userID int64) (*service.UserAvatar, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func (s *stubUserRepo) UpsertUserAvatar(ctx context.Context, userID int64, input service.UpsertUserAvatarInput) (*service.UserAvatar, error) {
|
|
panic("unexpected UpsertUserAvatar call")
|
|
}
|
|
|
|
func (s *stubUserRepo) DeleteUserAvatar(ctx context.Context, userID int64) error {
|
|
panic("unexpected DeleteUserAvatar call")
|
|
}
|
|
|
|
func (s *stubUserRepo) List(ctx context.Context, params pagination.PaginationParams) ([]service.User, *pagination.PaginationResult, error) {
|
|
panic("unexpected List call")
|
|
}
|
|
|
|
func (s *stubUserRepo) ListWithFilters(ctx context.Context, params pagination.PaginationParams, filters service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
|
|
panic("unexpected ListWithFilters call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetLatestUsedAtByUserIDs(ctx context.Context, userIDs []int64) (map[int64]*time.Time, error) {
|
|
panic("unexpected GetLatestUsedAtByUserIDs call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetLatestUsedAtByUserID(ctx context.Context, userID int64) (*time.Time, error) {
|
|
panic("unexpected GetLatestUsedAtByUserID call")
|
|
}
|
|
|
|
func (s *stubUserRepo) UpdateUserLastActiveAt(ctx context.Context, userID int64, activeAt time.Time) error {
|
|
panic("unexpected UpdateUserLastActiveAt call")
|
|
}
|
|
|
|
func (s *stubUserRepo) UpdateBalance(ctx context.Context, id int64, amount float64) error {
|
|
panic("unexpected UpdateBalance call")
|
|
}
|
|
|
|
func (s *stubUserRepo) DeductBalance(ctx context.Context, id int64, amount float64) error {
|
|
panic("unexpected DeductBalance call")
|
|
}
|
|
|
|
func (s *stubUserRepo) UpdateConcurrency(ctx context.Context, id int64, amount int) error {
|
|
panic("unexpected UpdateConcurrency call")
|
|
}
|
|
|
|
func (s *stubUserRepo) BatchSetConcurrency(context.Context, []int64, int) (int, error) { return 0, nil }
|
|
func (s *stubUserRepo) BatchAddConcurrency(context.Context, []int64, int) (int, error) { return 0, nil }
|
|
func (s *stubUserRepo) BatchUpdateLimits(context.Context, []int64, *int, *int) (int, error) {
|
|
return 0, nil
|
|
}
|
|
|
|
func (s *stubUserRepo) ExistsByEmail(ctx context.Context, email string) (bool, error) {
|
|
panic("unexpected ExistsByEmail call")
|
|
}
|
|
|
|
func (s *stubUserRepo) ExistsByEmailAlias(ctx context.Context, email string) (bool, error) {
|
|
panic("unexpected ExistsByEmailAlias call")
|
|
}
|
|
|
|
func (s *stubUserRepo) RemoveGroupFromAllowedGroups(ctx context.Context, groupID int64) (int64, error) {
|
|
panic("unexpected RemoveGroupFromAllowedGroups call")
|
|
}
|
|
|
|
func (s *stubUserRepo) RemoveGroupFromUserAllowedGroups(ctx context.Context, userID int64, groupID int64) error {
|
|
panic("unexpected RemoveGroupFromUserAllowedGroups call")
|
|
}
|
|
|
|
func (s *stubUserRepo) AddGroupToAllowedGroups(ctx context.Context, userID int64, groupID int64) error {
|
|
panic("unexpected AddGroupToAllowedGroups call")
|
|
}
|
|
|
|
func (s *stubUserRepo) ListUserAuthIdentities(ctx context.Context, userID int64) ([]service.UserAuthIdentityRecord, error) {
|
|
panic("unexpected ListUserAuthIdentities call")
|
|
}
|
|
|
|
func (s *stubUserRepo) UnbindUserAuthProvider(context.Context, int64, string) error {
|
|
panic("unexpected UnbindUserAuthProvider call")
|
|
}
|
|
|
|
func (s *stubUserRepo) UpdateTotpSecret(ctx context.Context, userID int64, encryptedSecret *string) error {
|
|
panic("unexpected UpdateTotpSecret call")
|
|
}
|
|
|
|
func (s *stubUserRepo) EnableTotp(ctx context.Context, userID int64) error {
|
|
panic("unexpected EnableTotp call")
|
|
}
|
|
|
|
func (s *stubUserRepo) DisableTotp(ctx context.Context, userID int64) error {
|
|
panic("unexpected DisableTotp call")
|
|
}
|
|
|
|
func (s *stubUserRepo) GetByIDIncludeDeleted(ctx context.Context, id int64) (*service.User, error) {
|
|
panic("unexpected GetByIDIncludeDeleted call")
|
|
}
|