修复 token 与 Cookie 绑定并完善认证恢复

This commit is contained in:
Christ committed 2026-07-15 09:03:20 +08:00
1 parent 16d63dc7c9
commit 3cc1d4094d
30 files changed
+990 -998

No files matched your search

+34 -192
View File
@@ -8,6 +8,7 @@ import (
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
@@ -19,7 +20,7 @@ type countingMtop struct {
func (c *countingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
atomic.AddInt32(&c.calls, 1)
return &mtop.RefreshResult{AccessToken: c.token}, nil
return &mtop.RefreshResult{AccessToken: c.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil
}
type statusMtop struct {
@@ -39,170 +40,12 @@ func (c *failingCountingMtop) RefreshTokenWithDeviceIDContext(_ context.Context,
return nil, c.err
}
func TestRiskSensitiveRefreshIntervals(t *testing.T) {
if CookieRefreshInterval != 180*time.Second {
t.Fatalf("在线 Cookie 检查间隔应与参考实现保持 180 秒,got %s", CookieRefreshInterval)
}
if CookieRefreshCheckInterval != time.Minute {
t.Fatalf("在线 Cookie 循环检查频率应与参考实现保持 60 秒,got %s", CookieRefreshCheckInterval)
}
if PasswordLoginMinGap != 60*time.Second {
t.Fatalf("自动密码登录冷却应与参考运行时保持 60 秒,got %s", PasswordLoginMinGap)
}
}
func TestRefreshOnlineCookie_CacheHitSkipsMtop(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
func saveBoundToken(t *testing.T, store *db.Store, acc *Account, token string, expireAt int64) {
t.Helper()
if err := store.Tokens.SaveBound(context.Background(), acc.CookieID, acc.deviceID, token, expireAt,
credentialCookieFingerprint(acc.currentCookieStr())); err != nil {
t.Fatal(err)
}
conn := &fakeWSConn{}
if !acc.refreshOnlineCookie(context.Background(), conn, true) {
t.Fatal("缓存命中时在线 Cookie 检查应成功")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("180 秒检查命中缓存时不应请求 mtop,got %d", calls)
}
acc.mu.Lock()
currentToken := acc.currentToken
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if currentToken != "cached-tok" || lastRefresh.IsZero() {
t.Fatalf("应采用缓存 token 并更新时间,token=%q last_refresh=%s", currentToken, lastRefresh)
}
}
func TestCookieRefreshLoopRunsInitialCacheCheckImmediately(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
acc.mu.Lock()
acc.lastCookieRefresh = time.Time{}
acc.lastMsgReceived = time.Now().Add(-MessageCooldown - time.Second)
acc.mu.Unlock()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
acc.cookieRefreshLoop(ctx, nil)
}()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
lastMessage := acc.lastMsgReceived
acc.mu.Unlock()
if !lastRefresh.IsZero() {
if !lastMessage.IsZero() {
t.Fatalf("刷新轮次结束后应清空消息冷却标识: %s", lastMessage)
}
break
}
time.Sleep(5 * time.Millisecond)
}
cancel()
<-done
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if lastRefresh.IsZero() {
t.Fatal("Cookie 刷新循环启动后应立即完成首次缓存检查")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("首次检查命中缓存时不应请求 mtop, got %d", calls)
}
}
func TestRefreshOnlineCookie_RiskRecoveryRestoresOnlineRuntimeState(t *testing.T) {
mtopClient := &riskCountingMTop{}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.handler = &tokenRecoveredHandler{}
conn := &fakeWSConn{}
acc.mu.Lock()
acc.conn = conn
acc.runtimeState = RuntimeOnline
acc.runtimeMessage = "消息服务连接正常"
acc.runtimeUpdatedAt = time.Now()
acc.mu.Unlock()
if !acc.refreshOnlineCookie(context.Background(), conn, true) {
t.Fatal("风控自动恢复成功后在线 Cookie 刷新应成功")
}
status := acc.RuntimeStatus()
if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
t.Fatalf("在线风控恢复后运行态未收敛: %+v", status)
}
conn.mu.Lock()
defer conn.mu.Unlock()
if len(conn.tokens) != 1 || conn.tokens[0] != "standard-token" {
t.Fatalf("恢复 token 未更新到现有连接: %+v", conn.tokens)
}
}
func TestApplyOnlineToken_PeriodicRefreshRestoresRuntimeWithoutChangingCookieSchedule(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "unused"})
defer cleanup()
conn := &fakeWSConn{}
acc.mu.Lock()
acc.conn = conn
acc.runtimeState = RuntimeConnecting
acc.runtimeMessage = tokenRiskRecoveryMessage
acc.lastCookieRefresh = time.Time{}
acc.mu.Unlock()
acc.applyOnlineToken(conn, "periodic-token", false)
status := acc.RuntimeStatus()
if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
t.Fatalf("定时 token 风控恢复后运行态未收敛: %+v", status)
}
acc.mu.Lock()
lastCookieRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if !lastCookieRefresh.IsZero() {
t.Fatalf("定时 token 刷新不应改变 180 秒 Cookie 检查时间: %s", lastCookieRefresh)
}
conn.mu.Lock()
defer conn.mu.Unlock()
if len(conn.tokens) != 1 || conn.tokens[0] != "periodic-token" {
t.Fatalf("定时刷新 token 未更新到现有连接: %+v", conn.tokens)
}
}
func TestRunOnlineCookieRefresh_RetriesOnceAndPacesFailure(t *testing.T) {
mtopClient := &failingCountingMtop{
fakeRunMtop: fakeRunMtop{token: "unused"},
err: errors.New("temporary token failure"),
}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
started := time.Now()
if !acc.runOnlineCookieRefresh(context.Background(), &fakeWSConn{}, 0) {
t.Fatal("未取消的刷新轮次不应要求退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("失败后应且只应重试一次,got %d calls", calls)
}
if elapsed := time.Since(started); elapsed >= time.Second {
t.Fatalf("参考实现没有额外一分钟防抖,零延迟测试不应阻塞,elapsed=%s", elapsed)
}
acc.mu.Lock()
lastRefresh := acc.lastCookieRefresh
acc.mu.Unlock()
if lastRefresh.Before(started) {
t.Fatalf("第二次失败后必须重新开始 180 秒计时,last_refresh=%s started=%s", lastRefresh, started)
}
}
func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing.T) {
@@ -212,10 +55,7 @@ func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
@@ -240,10 +80,7 @@ func TestRefreshTokenBusinessFailureClearsMemoryAndCache(t *testing.T) {
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
@@ -268,10 +105,7 @@ func TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt(t *testing.T) {
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "expired-tok",
time.Now().Add(-time.Minute).Unix()); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "expired-tok", time.Now().Add(-time.Minute).Unix())
if _, _, err := acc.acquireToken(context.Background()); err == nil {
t.Fatal("后续网络请求失败应返回错误")
}
@@ -290,13 +124,7 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=123; _m_h5_tk=db-new;"); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
token, cookies, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatalf("acquireToken: %v", err)
@@ -307,8 +135,28 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
}
if strings.Contains(cookies, "db-new") {
t.Fatalf("缓存命中时不应提前重载 DB Cookie: %q", cookies)
if !strings.Contains(cookies, "_m_h5_tk=tk_1") {
t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies)
}
}
func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
saveBoundToken(t, store, acc, "stale-token", time.Now().Add(time.Hour).Unix())
newCookie := "unb=123; _m_h5_tk=renewed_2; cookie2=new"
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
t.Fatal(err)
}
acc.replaceCookieStr(newCookie)
token, _, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatal(err)
}
if token != "fresh-token" || atomic.LoadInt32(&mtopClient.calls) != 1 {
t.Fatalf("token=%q calls=%d want fresh token", token, atomic.LoadInt32(&mtopClient.calls))
}
}
@@ -370,10 +218,7 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
res := acc.tryLoginStatusCheck(context.Background())
if !res.recovered || res.riskRequired {
t.Fatalf("登录态检查应恢复 Cookie,got %+v", res)
@@ -421,10 +266,7 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 预置旧 session 的 token 缓存。
if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok",
time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
// 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。
newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc"
if err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil {