fix: 对齐闲鱼消息连接与登录续期流程
对齐官方 WebSocket 竞速、连接级凭证、注册解码、控制状态与心跳时序。 持久化完整 Cookie Jar,修正请求作用域、删除、分区、加密、并发写回与错误路径。 统一启动续期、长登录开关和业务 MTOP 的原子更新,并补充回归与竞态测试。
This commit is contained in:
1 parent
d77c317452
commit
de9c12196f
59 files changed
+6170
-1247
No files matched your search
+447
-229
File diff suppressed because it is too large.
Load diff
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
@@ -241,7 +242,7 @@ type stubCookieRenewer struct {
|
||||
got string
|
||||
}
|
||||
|
||||
func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string) (*xrenew.Result, error) {
|
||||
func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string, _ ...[]cookierefresh.BrowserCookie) (*xrenew.Result, error) {
|
||||
s.calls++
|
||||
s.got = cookiesStr
|
||||
return s.result, s.err
|
||||
@@ -292,6 +293,7 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
|
||||
RenewMethod: "none",
|
||||
NewCookies: "unb=123; _m_h5_tk=partial;",
|
||||
UpdatedCookieNames: []string{"_m_h5_tk"},
|
||||
SetCookies: []string{"_m_h5_tk=partial; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
|
||||
Message: "setLoginSettings 未返回 Set-Cookie",
|
||||
}}
|
||||
acc.renewer = renewer
|
||||
@@ -309,6 +311,52 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
|
||||
t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
|
||||
t.Fatal("接口扁平 Cookie 更新不得伪造成完整浏览器 Jar")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryAPIRenewPersistsExplicitFlatCookieDeletionOnError(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", time.Now().Add(time.Hour).Unix()); err != nil {
|
||||
t.Fatalf("save token: %v", err)
|
||||
}
|
||||
acc.renewer = &stubCookieRenewer{
|
||||
result: &xrenew.Result{
|
||||
NewCookies: "",
|
||||
SetCookies: []string{
|
||||
"unb=; Domain=.goofish.com; Path=/; Max-Age=0",
|
||||
"_m_h5_tk=; Domain=.goofish.com; Path=/; Max-Age=0",
|
||||
},
|
||||
},
|
||||
err: errors.New("续期响应正文损坏"),
|
||||
}
|
||||
|
||||
if acc.tryAPIRenew(ctx) {
|
||||
t.Fatal("失败响应即使带 Cookie 删除也不应视为续期成功")
|
||||
}
|
||||
if got := acc.currentCookieStr(); got != "" {
|
||||
t.Fatalf("运行时应采用服务端明确删除后的空 Cookie,got %q", got)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Value != "" {
|
||||
t.Fatalf("数据库应保存明确删除后的空 Cookie,got %q", detail.Value)
|
||||
}
|
||||
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
|
||||
t.Fatal("扁平删除结果不得伪造成完整浏览器 Jar")
|
||||
}
|
||||
if token, err := store.Tokens.Get(ctx, "cid"); err != nil || token.AccessToken != "" {
|
||||
t.Fatalf("Cookie 删除后应清理旧 token: token=%+v err=%v", token, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
|
||||
@@ -694,7 +742,7 @@ func TestReplaceCookieStr_NoUnbNoChange(t *testing.T) {
|
||||
|
||||
// TestUpdateCookie_IgnoresEmpty 纯空白/空字符串被忽略,不覆盖现有 cookie。
|
||||
func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
orig := acc.currentCookieStr()
|
||||
|
||||
@@ -706,22 +754,187 @@ func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
|
||||
t.Errorf("空白 cookie 不应更新: got %q want %q", got, orig)
|
||||
}
|
||||
|
||||
// 非空(即使含首尾空白)应原样存储——UpdateCookie 只做空值检查,不做 trim。
|
||||
acc.UpdateCookie("unb=123; _m_h5_tk=tk_new;")
|
||||
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_new;" {
|
||||
acc.mu.Lock()
|
||||
originalDevice := acc.deviceID
|
||||
healthyConn := &fakeWSConn{}
|
||||
acc.conn = healthyConn
|
||||
acc.mu.Unlock()
|
||||
|
||||
// 非空(即使含首尾空白)应原样存储,但不能模拟页面 reload 去打断健康 WS。
|
||||
updated := "unb=123; _m_h5_tk=tk_new;"
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acc.UpdateCookie(updated)
|
||||
if got := acc.currentCookieStr(); got != updated {
|
||||
t.Errorf("非空 cookie 应更新: got %q", got)
|
||||
}
|
||||
acc.mu.Lock()
|
||||
currentDevice := acc.deviceID
|
||||
acc.mu.Unlock()
|
||||
healthyConn.mu.Lock()
|
||||
closed := healthyConn.closed
|
||||
healthyConn.mu.Unlock()
|
||||
if currentDevice != originalDevice || closed {
|
||||
t.Fatalf("普通 Cookie 更新不应轮换 device ID 或关闭健康连接: device=%q/%q closed=%v", currentDevice, originalDevice, closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCookie_AcceptsAuthoritativeEmptySnapshot(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
metadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
|
||||
if err := store.Cookies.UpdateRenewalCookie(context.Background(), acc.CookieID, "", metadata, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acc.UpdateCookie("")
|
||||
if got := acc.currentCookieStr(); got != "" {
|
||||
t.Fatalf("权威空 Jar 应清空运行时 Cookie,got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadCookieFromDBDetectsMetadataOnlyCredentialRotation(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
flat := acc.currentCookieStr()
|
||||
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/im"},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !acc.reloadCookieFromDB(ctx) {
|
||||
t.Fatal("首次权威 Jar 应同步到运行时")
|
||||
}
|
||||
acc.mu.Lock()
|
||||
boundFP := acc.credentialFP
|
||||
acc.currentToken = "old-token"
|
||||
acc.tokenCredentialFP = boundFP
|
||||
acc.mu.Unlock()
|
||||
if err := store.Tokens.SaveBound(ctx, acc.CookieID, acc.deviceID, "old-token", time.Now().Add(time.Hour).Unix(), boundFP); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/im"},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !acc.reloadCookieFromDB(ctx) {
|
||||
t.Fatal("扁平 Cookie 未变但权威 Jar 已变化时必须重新加载")
|
||||
}
|
||||
acc.mu.Lock()
|
||||
currentToken := acc.currentToken
|
||||
currentFP := acc.credentialFP
|
||||
acc.mu.Unlock()
|
||||
if currentToken != "" {
|
||||
t.Fatalf("Jar 变化后应清内存 token,got %q", currentToken)
|
||||
}
|
||||
if currentFP != credentialStateFingerprint(flat, metadataB) {
|
||||
t.Fatal("运行时未绑定到最新完整凭证状态")
|
||||
}
|
||||
if cached, err := store.Tokens.Get(ctx, acc.CookieID); err != nil || cached.AccessToken != "" {
|
||||
t.Fatalf("Jar 变化后应清数据库 token: cached=%+v err=%v", cached, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCookieSnapshotMatchesDBUsesCompleteCredentialState(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
flat := acc.currentCookieStr()
|
||||
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "sgcookie", Value: "a", Domain: ".goofish.com", Path: "/"},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := credentialStateFingerprint(flat, metadataA)
|
||||
if !acc.cookieSnapshotMatchesDB(ctx, expected) {
|
||||
t.Fatal("相同扁平 Cookie 与权威 Jar 应允许 /reg")
|
||||
}
|
||||
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "sgcookie", Value: "b", Domain: ".goofish.com", Path: "/"},
|
||||
})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if acc.cookieSnapshotMatchesDB(ctx, expected) {
|
||||
t.Fatal("token 获取后 Jar 变化时必须拒绝 /reg")
|
||||
}
|
||||
emptyMetadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, "", emptyMetadata, time.Now().Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !acc.cookieSnapshotMatchesDB(ctx, credentialStateFingerprint("", emptyMetadata)) {
|
||||
t.Fatal("完整空 Jar 是权威状态,不应因扁平值为空而被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdoptIncompleteTokenCookiesDoesNotInventCompleteSnapshot(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
updated := "unb=123; _m_h5_tk=flat-only; cookie2=next"
|
||||
got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
|
||||
UpdatedCookies: updated,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != updated {
|
||||
t.Fatalf("adopted Cookie=%q want %q", got, updated)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
|
||||
t.Fatal("仅有扁平 token 响应时不得伪造成完整浏览器 Jar")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdoptTokenResponseCookiesPersistsExplicitDeletionToEmpty(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
|
||||
UpdatedCookies: "",
|
||||
CookieStateChanged: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "" || acc.currentCookieStr() != "" {
|
||||
t.Fatalf("明确删除后的 Cookie 未同步: got=%q runtime=%q", got, acc.currentCookieStr())
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Value != "" {
|
||||
t.Fatalf("数据库 Cookie=%q want empty", detail.Value)
|
||||
}
|
||||
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
|
||||
t.Fatal("扁平 token 删除不得伪造成完整浏览器 Jar")
|
||||
}
|
||||
}
|
||||
|
||||
// TestCurrentCookieStr 线程安全返回当前 CookieStr。
|
||||
func TestCurrentCookieStr(t *testing.T) {
|
||||
acc, _, _, cleanup := newAccountForTest(t)
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_1;" {
|
||||
t.Errorf("currentCookieStr=%q", got)
|
||||
}
|
||||
acc.UpdateCookie("unb=1; x=2;")
|
||||
if got := acc.currentCookieStr(); got != "unb=1; x=2;" {
|
||||
updated := "unb=1; x=2;"
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acc.UpdateCookie(updated)
|
||||
if got := acc.currentCookieStr(); got != updated {
|
||||
t.Errorf("更新后 currentCookieStr=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
|
||||
if err != nil || saved != newCookie {
|
||||
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
|
||||
}
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
|
||||
t.Fatalf("Cookie 更新后应清 token 并为页面重载轮换 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
|
||||
t.Fatalf("Cookie 更新后应清 token 并保持页面 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
|
||||
if got := acc.CurrentCookieStr(); got != newCookie {
|
||||
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
|
||||
}
|
||||
// 新 cookie 对应官网页面重载:旧 token 清除,运行时 device ID 轮换。
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
|
||||
t.Fatalf("cookie 变更后应清 token 并轮换运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
// 普通 Cookie Jar 更新不等于页面 reload:旧 token 清除,device ID 保持。
|
||||
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
|
||||
t.Fatalf("cookie 变更后应清 token 并保持运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+79
-56
@@ -274,33 +274,27 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_DialFailureIncrementsFailures 拨号失败时 connFailures 递增,
|
||||
// ctx 在重试 sleep 期间取消 → Run 返回 ctx.Err。
|
||||
func TestRun_DialFailureIncrementsFailures(t *testing.T) {
|
||||
// TestRun_DialFailureRequiresRelogin mirrors the web page: native
|
||||
// CONNECT_FAILED enters CONN_ERROR and does not auto-reconnect.
|
||||
func TestRun_DialFailureRequiresRelogin(t *testing.T) {
|
||||
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
defer cleanup()
|
||||
|
||||
// 拨号始终失败。
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{err: errFakeDial}}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
runDone := make(chan error, 1)
|
||||
go func() { runDone <- acc.Run(ctx) }()
|
||||
|
||||
// 等待首次拨号失败 + 进入重试 sleep。
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
cancel()
|
||||
go func() { runDone <- acc.Run(context.Background()) }()
|
||||
select {
|
||||
case <-runDone:
|
||||
// Run 应已退出。
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("拨号失败 + ctx 取消后 Run 未退出")
|
||||
case err := <-runDone:
|
||||
if !errors.Is(err, errFakeDial) {
|
||||
t.Fatalf("Run error=%v,期望拨号错误", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("拨号失败后 Run 未退出")
|
||||
}
|
||||
acc.mu.Lock()
|
||||
failures := acc.connFailures
|
||||
acc.mu.Unlock()
|
||||
if failures < 1 {
|
||||
t.Fatalf("拨号失败应使 connFailures>=1,got %d", failures)
|
||||
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
|
||||
t.Fatalf("runtime state=%q,期望 %q", status.State, RuntimeAuthExpired)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,9 +346,11 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
|
||||
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
|
||||
acc, _, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
first := &fakeWSConn{recvBlock: false}
|
||||
second := &fakeWSConn{recvBlock: true}
|
||||
dialer := &fakeDialer{results: []dialResult{
|
||||
{conn: &fakeWSConn{recvBlock: false}},
|
||||
{conn: &fakeWSConn{recvBlock: true}},
|
||||
{conn: first},
|
||||
{conn: second},
|
||||
}}
|
||||
acc.wsDialer = dialer
|
||||
|
||||
@@ -362,6 +358,7 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
waitForDialCalls(t, dialer, 2)
|
||||
waitForRegisteredToken(t, second, "fresh-2")
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
@@ -388,39 +385,33 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
|
||||
func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
|
||||
acc, _, store, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
conn := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
|
||||
first := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
|
||||
second := &fakeWSConn{recvBlock: true}
|
||||
dialer := &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
|
||||
acc.wsDialer = dialer
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
acc.mu.Lock()
|
||||
failures := acc.networkFailures
|
||||
acc.mu.Unlock()
|
||||
if failures == 1 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
waitForDialCalls(t, dialer, 2)
|
||||
waitForRegisteredToken(t, second, "tok-1")
|
||||
acc.mu.Lock()
|
||||
currentToken := acc.currentToken
|
||||
networkFailures := acc.networkFailures
|
||||
acc.mu.Unlock()
|
||||
if networkFailures != 1 || currentToken != "" {
|
||||
if networkFailures != 0 || currentToken != "tok-1" {
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatalf("网络断线应结束当前 token 生命周期: failures=%d token=%q", networkFailures, currentToken)
|
||||
t.Fatalf("网络断线后应立即用新凭证恢复连接: failures=%d token=%q", networkFailures, currentToken)
|
||||
}
|
||||
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "" {
|
||||
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
|
||||
cancel()
|
||||
<-done
|
||||
t.Fatalf("网络断线应清除 token 缓存: cached=%+v err=%v", cached, err)
|
||||
t.Fatalf("重连成功后应缓存新连接凭证: cached=%+v err=%v", cached, err)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
@@ -428,30 +419,39 @@ func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("取消后 Run 未退出")
|
||||
}
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("网络断线前只应获取一次 token: calls=%d", calls)
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
|
||||
t.Fatalf("官网重连会重新获取连接凭证: calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
|
||||
func TestRun_InvalidRegTokenRequiresRelogin(t *testing.T) {
|
||||
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
|
||||
acc, _, _, cleanup := newRunAccount(t, mtopClient)
|
||||
defer cleanup()
|
||||
dialer := &fakeDialer{results: []dialResult{
|
||||
{conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}},
|
||||
{conn: &fakeWSConn{recvBlock: true}},
|
||||
}}
|
||||
acc.wsDialer = dialer
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
waitForDialCalls(t, dialer, 2)
|
||||
cancel()
|
||||
<-done
|
||||
go func() { done <- acc.Run(context.Background()) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !ws.IsInvalidTokenError(err) {
|
||||
t.Fatalf("Run error=%v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("invalid /reg 后 Run 未退出")
|
||||
}
|
||||
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
|
||||
t.Fatalf("invalid /reg should fetch exactly one fresh token immediately, calls=%d", calls)
|
||||
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
|
||||
t.Fatalf("invalid /reg 不应在页面要求重新登录时静默重试: calls=%d", calls)
|
||||
}
|
||||
if dialer.calls != 1 {
|
||||
t.Fatalf("invalid /reg dial calls=%d want 1", dialer.calls)
|
||||
}
|
||||
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
|
||||
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,6 +507,24 @@ func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) {
|
||||
t.Fatalf("dial calls=%d want>=%d", calls, want)
|
||||
}
|
||||
|
||||
func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
conn.mu.Lock()
|
||||
token := conn.registeredTok
|
||||
conn.mu.Unlock()
|
||||
if token == want {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
conn.mu.Lock()
|
||||
token := conn.registeredTok
|
||||
conn.mu.Unlock()
|
||||
t.Fatalf("registered token=%q want=%q", token, want)
|
||||
}
|
||||
|
||||
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。
|
||||
func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
|
||||
@@ -528,7 +546,7 @@ func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
|
||||
func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
|
||||
defer cleanup()
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
|
||||
@@ -542,17 +560,22 @@ func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
|
||||
go func() { done <- acc.Run(context.Background()) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("threshold disable should exit nil, got %v", err)
|
||||
if !errors.Is(err, errFakeDial) {
|
||||
t.Fatalf("token callback reject should enter CONN_ERROR, got %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("token failure threshold should disable without retry sleep")
|
||||
t.Fatal("Run did not stop after token callback reject")
|
||||
}
|
||||
if store.Cookies.GetStatus(context.Background(), "cid") {
|
||||
t.Fatal("token failure threshold should disable account")
|
||||
if !store.Cookies.GetStatus(context.Background(), "cid") {
|
||||
t.Fatal("token failure threshold must not disable account")
|
||||
}
|
||||
if len(h.events) == 0 || h.events[len(h.events)-1] != EventAccountDisabled {
|
||||
t.Fatalf("disable event not emitted: events=%+v alerts=%+v", h.events, h.alerts)
|
||||
for _, event := range h.events {
|
||||
if event == EventAccountDisabled {
|
||||
t.Fatalf("unexpected disable event: events=%+v alerts=%+v", h.events, h.alerts)
|
||||
}
|
||||
}
|
||||
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
|
||||
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@ package engine
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"sort"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
const tokenExpirySafetyMargin = time.Minute
|
||||
@@ -25,19 +25,39 @@ func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
|
||||
}
|
||||
|
||||
func credentialCookieFingerprint(cookieStr string) string {
|
||||
cookies := protocol.TransCookies(cookieStr)
|
||||
keys := make([]string, 0, len(cookies))
|
||||
for key := range cookies {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var canonical strings.Builder
|
||||
for _, key := range keys {
|
||||
for _, part := range strings.Split(cookieStr, ";") {
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
key = strings.TrimSpace(key)
|
||||
if !ok || key == "" {
|
||||
continue
|
||||
}
|
||||
canonical.WriteString(key)
|
||||
canonical.WriteByte(0)
|
||||
canonical.WriteString(cookies[key])
|
||||
canonical.WriteString(strings.TrimSpace(value))
|
||||
canonical.WriteByte(0)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(canonical.String()))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// credentialStateFingerprint binds a connection token to both the exact flat
|
||||
// Cookie header and the authoritative browser Jar that produced it. The flat
|
||||
// fingerprint deliberately retains duplicate names and their order because
|
||||
// lib-mtop reads the first path-ordered _m_h5_tk entry. A present empty Jar is
|
||||
// distinct from legacy metadata that has no complete snapshot.
|
||||
func credentialStateFingerprint(cookieStr, metadataJSON string) string {
|
||||
var canonical strings.Builder
|
||||
canonical.WriteString("flat\x00")
|
||||
canonical.WriteString(credentialCookieFingerprint(cookieStr))
|
||||
canonical.WriteString("\x00snapshot\x00")
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
canonical.WriteByte('1')
|
||||
raw, _ := json.Marshal(cookierefresh.NormalizeSnapshot(snapshot))
|
||||
canonical.Write(raw)
|
||||
} else {
|
||||
canonical.WriteByte('0')
|
||||
}
|
||||
sum := sha256.Sum256([]byte(canonical.String()))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package engine
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
func TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin(t *testing.T) {
|
||||
@@ -23,13 +25,38 @@ func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialCookieFingerprintIsOrderIndependent(t *testing.T) {
|
||||
func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(t *testing.T) {
|
||||
left := credentialCookieFingerprint("unb=1; cookie2=abc; _m_h5_tk=tk_1")
|
||||
right := credentialCookieFingerprint("_m_h5_tk=tk_1; unb=1; cookie2=abc")
|
||||
if left == "" || left != right {
|
||||
t.Fatalf("fingerprints differ: %q != %q", left, right)
|
||||
if left == "" || left == right {
|
||||
t.Fatalf("Cookie Header 顺序变化必须改变指纹: %q == %q", left, right)
|
||||
}
|
||||
if left == credentialCookieFingerprint("unb=1; cookie2=changed; _m_h5_tk=tk_1") {
|
||||
t.Fatal("credential change must alter fingerprint")
|
||||
}
|
||||
if left != credentialCookieFingerprint(" unb = 1 ; cookie2=abc;_m_h5_tk = tk_1 ;") {
|
||||
t.Fatal("无语义空白不应改变指纹")
|
||||
}
|
||||
firstPathToken := credentialCookieFingerprint("_m_h5_tk=first; _m_h5_tk=second; unb=1")
|
||||
secondPathToken := credentialCookieFingerprint("_m_h5_tk=second; _m_h5_tk=first; unb=1")
|
||||
if firstPathToken == secondPathToken {
|
||||
t.Fatal("同名 Cookie 的路径顺序会影响首值签名,不能折叠")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
|
||||
flat := "unb=1; _m_h5_tk=tk_1"
|
||||
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/"},
|
||||
})
|
||||
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
|
||||
{Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/"},
|
||||
})
|
||||
if credentialStateFingerprint(flat, metadataA) == credentialStateFingerprint(flat, metadataB) {
|
||||
t.Fatal("权威 Jar 变化必须改变完整凭证指纹")
|
||||
}
|
||||
emptyJar := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
|
||||
if credentialStateFingerprint("", emptyJar) == credentialStateFingerprint("", "") {
|
||||
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user