修复 token 与 Cookie 绑定并完善认证恢复
This commit is contained in:
1 parent
16d63dc7c9
commit
3cc1d4094d
30 files changed
+990
-998
No files matched your search
@@ -13,10 +13,11 @@ import (
|
||||
// - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控;
|
||||
// - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。
|
||||
type AccountToken struct {
|
||||
CookieID string
|
||||
DeviceID string
|
||||
AccessToken string
|
||||
ExpireAt int64 // unix 秒,0 表示无有效 token
|
||||
CookieID string
|
||||
DeviceID string
|
||||
AccessToken string
|
||||
ExpireAt int64 // unix 秒,0 表示无有效 token
|
||||
CookieFingerprint string
|
||||
}
|
||||
|
||||
// AccountTokens 读写 account_tokens 表。
|
||||
@@ -31,8 +32,8 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
|
||||
var tk AccountToken
|
||||
tk.CookieID = cookieID
|
||||
err := t.DB.QueryRowContext(ctx,
|
||||
`SELECT device_id, access_token, expire_at FROM account_tokens WHERE cookie_id=?`,
|
||||
cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt)
|
||||
`SELECT device_id, access_token, expire_at, cookie_fingerprint FROM account_tokens WHERE cookie_id=?`,
|
||||
cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt, &tk.CookieFingerprint)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return AccountToken{}, ErrNotFound
|
||||
@@ -52,6 +53,13 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
|
||||
|
||||
// Save upsert 缓存的 device_id + accessToken + expire_at。
|
||||
func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64) error {
|
||||
return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "")
|
||||
}
|
||||
|
||||
// SaveBound persists an access token together with the canonical Cookie state
|
||||
// from which it was issued. The binding lets a later reconnect reject a stale
|
||||
// token after an independent Cookie renewal without rotating device_id.
|
||||
func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error {
|
||||
// device_id is an account identity, not part of the expiring token cache.
|
||||
// Once stored, token refreshes must never replace it.
|
||||
if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" {
|
||||
@@ -68,15 +76,16 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke
|
||||
return err
|
||||
}
|
||||
_, err = t.DB.ExecContext(ctx,
|
||||
`INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
`INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, cookie_fingerprint, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+
|
||||
dialectUpsert(t.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
"device_id": "excluded.device_id",
|
||||
"access_token": "excluded.access_token",
|
||||
"expire_at": "excluded.expire_at",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
"device_id": "excluded.device_id",
|
||||
"access_token": "excluded.access_token",
|
||||
"expire_at": "excluded.expire_at",
|
||||
"cookie_fingerprint": "excluded.cookie_fingerprint",
|
||||
"updated_at": "CURRENT_TIMESTAMP",
|
||||
}),
|
||||
cookieID, encryptedDeviceID, encryptedToken, expireAt)
|
||||
cookieID, encryptedDeviceID, encryptedToken, expireAt, cookieFingerprint)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存 account_tokens: %w", err)
|
||||
}
|
||||
@@ -123,7 +132,7 @@ func (t *AccountTokens) Clear(ctx context.Context, cookieID string) error {
|
||||
return err
|
||||
}
|
||||
_, err = t.DB.ExecContext(ctx,
|
||||
`UPDATE account_tokens SET access_token=?, expire_at=0, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
|
||||
`UPDATE account_tokens SET access_token=?, expire_at=0, cookie_fingerprint='', updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
|
||||
encryptedToken, cookieID)
|
||||
return err
|
||||
}
|
||||
@@ -26,25 +26,25 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
t.Fatalf("不存在应返回 ErrNotFound,got %v", err)
|
||||
}
|
||||
|
||||
// Save(首次写入)。
|
||||
// SaveBound(首次写入)。
|
||||
expire := time.Now().Add(time.Hour).Unix()
|
||||
if err := store.Tokens.Save(ctx, "cid", "dev-1", "tok-1", expire); err != nil {
|
||||
if err := store.Tokens.SaveBound(ctx, "cid", "dev-1", "tok-1", expire, "cookie-hash-1"); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
tk, err := store.Tokens.Get(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire {
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire || tk.CookieFingerprint != "cookie-hash-1" {
|
||||
t.Fatalf("Get 返回不匹配: %+v", tk)
|
||||
}
|
||||
|
||||
// 再次 Save 更新 token,但永久 device ID 不允许覆盖。
|
||||
if err := store.Tokens.Save(ctx, "cid", "dev-2", "tok-2", expire+1); err != nil {
|
||||
if err := store.Tokens.SaveBound(ctx, "cid", "dev-2", "tok-2", expire+1, "cookie-hash-2"); err != nil {
|
||||
t.Fatalf("Save upsert: %v", err)
|
||||
}
|
||||
tk, _ = store.Tokens.Get(ctx, "cid")
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 {
|
||||
if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" {
|
||||
t.Fatalf("upsert 后字段应更新: %+v", tk)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func TestAccountTokens_CRUD(t *testing.T) {
|
||||
t.Fatalf("Clear: %v", err)
|
||||
}
|
||||
tk, err = store.Tokens.Get(ctx, "cid")
|
||||
if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 {
|
||||
if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" {
|
||||
t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
t.Fatalf("goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
// 依次回滚 21 到 14,再整体升级。
|
||||
for i := 0; i < 8; i++ {
|
||||
// 依次回滚 22 到 14,再整体升级。
|
||||
for i := 0; i < 9; i++ {
|
||||
if err := goose.Down(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("down migration #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -140,6 +140,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
if columnExists(t, d, "default_reply_records", "status") {
|
||||
t.Fatal("default_reply_records.status should be removed after migration 16 down")
|
||||
}
|
||||
if columnExists(t, d, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after migration 22 down")
|
||||
}
|
||||
|
||||
if err := goose.Up(d, "migrations/sqlite"); err != nil {
|
||||
t.Fatalf("up after down: %v", err)
|
||||
@@ -156,6 +159,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
|
||||
{"risk_control_logs", "processing_status"},
|
||||
{"default_reply_records", "status"},
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
} {
|
||||
if !columnExists(t, d, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint VARCHAR(64) NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
|
||||
@@ -641,7 +641,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
t.Fatalf("set goose dialect: %v", err)
|
||||
}
|
||||
goose.SetBaseFS(migrationsFS)
|
||||
for i := 0; i < 8; i++ {
|
||||
for i := 0; i < 9; i++ {
|
||||
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration down #%d: %v", i+1, err)
|
||||
}
|
||||
@@ -655,6 +655,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "default_reply_records", "status") {
|
||||
t.Fatal("default_reply_records.status should be removed after down")
|
||||
}
|
||||
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "account_tokens", "cookie_fingerprint") {
|
||||
t.Fatal("account_tokens.cookie_fingerprint should be removed after down")
|
||||
}
|
||||
|
||||
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
|
||||
t.Fatalf("migration up after down: %v", err)
|
||||
@@ -673,6 +676,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
|
||||
{"default_reply_records", "text_sent"},
|
||||
{"automation_runs", "action_cursor"},
|
||||
{"automation_runs", "action_started"},
|
||||
{"account_tokens", "cookie_fingerprint"},
|
||||
} {
|
||||
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
|
||||
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
|
||||
|
||||
+50
-22
@@ -1,6 +1,9 @@
|
||||
package db
|
||||
|
||||
import "database/sql"
|
||||
import (
|
||||
"database/sql"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。
|
||||
type Store struct {
|
||||
@@ -25,32 +28,57 @@ type Store struct {
|
||||
Renewal *RenewalStore
|
||||
LoginLogs *AccountLoginLogs
|
||||
RiskLogs *RiskControlLogs
|
||||
|
||||
credentialMu sync.Mutex
|
||||
credentialLocks map[string]*sync.Mutex
|
||||
}
|
||||
|
||||
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
|
||||
func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
codec := secretCodecFromEnvironment()
|
||||
return &Store{
|
||||
DB: db,
|
||||
Dialect: dialect,
|
||||
Users: &Users{DB: db},
|
||||
Sessions: &Sessions{DB: db},
|
||||
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
|
||||
Items: &Items{DB: db, Dialect: dialect},
|
||||
Cards: &Cards{DB: db, Dialect: dialect},
|
||||
Automation: &AutomationRules{DB: db, Dialect: dialect},
|
||||
Orders: &Orders{DB: db, Dialect: dialect},
|
||||
Keywords: &Keywords{DB: db, Dialect: dialect},
|
||||
DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
|
||||
ItemReps: &ItemReplies{DB: db, Dialect: dialect},
|
||||
AIReply: &AIReply{DB: db, codec: codec},
|
||||
Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
|
||||
Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
|
||||
WSMessages: &WSMessageStore{DB: db},
|
||||
PublishBatches: &ItemPublishBatches{DB: db},
|
||||
Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
|
||||
Renewal: &RenewalStore{DB: db, Dialect: dialect},
|
||||
LoginLogs: &AccountLoginLogs{DB: db},
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
DB: db,
|
||||
Dialect: dialect,
|
||||
Users: &Users{DB: db},
|
||||
Sessions: &Sessions{DB: db},
|
||||
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
|
||||
Items: &Items{DB: db, Dialect: dialect},
|
||||
Cards: &Cards{DB: db, Dialect: dialect},
|
||||
Automation: &AutomationRules{DB: db, Dialect: dialect},
|
||||
Orders: &Orders{DB: db, Dialect: dialect},
|
||||
Keywords: &Keywords{DB: db, Dialect: dialect},
|
||||
DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
|
||||
ItemReps: &ItemReplies{DB: db, Dialect: dialect},
|
||||
AIReply: &AIReply{DB: db, codec: codec},
|
||||
Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
|
||||
Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
|
||||
WSMessages: &WSMessageStore{DB: db},
|
||||
PublishBatches: &ItemPublishBatches{DB: db},
|
||||
Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
|
||||
Renewal: &RenewalStore{DB: db, Dialect: dialect},
|
||||
LoginLogs: &AccountLoginLogs{DB: db},
|
||||
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
|
||||
credentialLocks: make(map[string]*sync.Mutex),
|
||||
}
|
||||
}
|
||||
|
||||
// LockAccountCredentials serializes Cookie/token state transitions for one
|
||||
// account across the IM runtime and renewal scheduler. The returned function
|
||||
// must be called exactly once.
|
||||
func (s *Store) LockAccountCredentials(cookieID string) func() {
|
||||
if s == nil {
|
||||
return func() {}
|
||||
}
|
||||
s.credentialMu.Lock()
|
||||
if s.credentialLocks == nil {
|
||||
s.credentialLocks = make(map[string]*sync.Mutex)
|
||||
}
|
||||
lock := s.credentialLocks[cookieID]
|
||||
if lock == nil {
|
||||
lock = &sync.Mutex{}
|
||||
s.credentialLocks[cookieID] = lock
|
||||
}
|
||||
s.credentialMu.Unlock()
|
||||
lock.Lock()
|
||||
return lock.Unlock
|
||||
}
|
||||
Reference in new issue
Block a user