推进P1账号生命周期与自动化补偿迁移

This commit is contained in:
Christ committed 2026-08-16 01:44:11 +08:00
1 parent a0ce23e9cf
commit 19a7d5f924
17 files changed
+731 -74

No files matched your search

@@ -72,6 +72,21 @@ func (r storeAccountProfileRepository) GetOwnedSummary(ctx context.Context, user
}, nil
}
// DeleteOwned 在凭证锁内再次确认账号归属并删除账号,避免停止 fencing 期间误删被替换账号。
func (r storeAccountProfileRepository) DeleteOwned(ctx context.Context, userID int64, accountID string) error {
if r.store == nil || r.store.Cookies == nil {
return errors.New("账号删除存储未初始化")
}
// unlock 保护最终归属复核与删除之间的账号凭证状态,避免并发替换穿透删除边界。
unlock := r.store.LockAccountCredentials(accountID)
defer unlock()
// summary、summaryErr 保存锁内的非敏感归属复核结果。
if _, summaryErr := r.GetOwnedSummary(ctx, userID, accountID); summaryErr != nil {
return summaryErr
}
return r.store.Cookies.Delete(ctx, accountID)
}
// LockCredentials 委托账号凭证锁。
func (r storeAccountLoginRepository) LockCredentials(accountID string) func() {
return r.store.LockAccountCredentials(accountID)
+21
View File
@@ -20,6 +20,10 @@ type applicationServices struct {
itemBatchRunner *itemapp.BatchRunner
// accountLogin 是账号登录应用服务。
accountLogin *accountLoginService
// passwordLogin 是密码登录策略应用服务;当前只返回关闭策略,不保存登录秘密或会话。
passwordLogin *accountapp.PasswordLoginService
// accountDelete 是账号删除应用服务,负责停止 fencing 和归属复核后的持久化删除。
accountDelete *accountapp.DeleteService
// accountProfile 是账号资料刷新应用服务。
accountProfile *accountapp.ProfileService
// communication 是聊天、通知和账号任务应用服务。
@@ -47,6 +51,16 @@ func newApplicationServices(server *Server) *applicationServices {
if profileErr != nil {
panic(profileErr)
}
// deleteRuntime 是可选的账号运行时端口;显式保持 nil,避免把 nil *Manager 装入非空接口后触发 panic。
var deleteRuntime accountapp.DeleteRuntime
if server.Manager != nil {
deleteRuntime = server.Manager
}
// accountDelete 是账号删除用例的构造结果,运行时端口可为空以兼容无 Manager 的测试 Server。
accountDelete, deleteErr := accountapp.NewDeleteService(storeAccountProfileRepository{store: server.Store}, deleteRuntime)
if deleteErr != nil {
panic(deleteErr)
}
// itemBatchRunner 是批量发布 worker 的构造结果,失败表示必需端口装配错误。
itemBatchRunner, batchRunnerErr := newItemBatchRunnerApplication(server)
if batchRunnerErr != nil {
@@ -73,6 +87,8 @@ func newApplicationServices(server *Server) *applicationServices {
itemSinglePublish: newItemPublishApplication(server),
itemBatchRunner: itemBatchRunner,
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin},
passwordLogin: accountapp.NewPasswordLoginService(),
accountDelete: accountDelete,
accountProfile: accountProfile,
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
chat: newChatSendingApplication(server),
@@ -92,6 +108,11 @@ func (s *Server) accountProfileApplication() *accountapp.ProfileService {
return s.applicationServiceSet().accountProfile
}
// accountDeleteApplication 返回当前 Server 绑定的账号删除应用服务。
func (s *Server) accountDeleteApplication() *accountapp.DeleteService {
return s.applicationServiceSet().accountDelete
}
// applicationServiceSet 返回当前 Server 的应用服务集合,并兼容测试 Server。
func (s *Server) applicationServiceSet() *applicationServices {
if s.applications != nil {
+1 -1
View File
@@ -12,7 +12,7 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
}
// services 是统一应用服务集合。
services := srv.applicationServiceSet()
if services.orders == nil || services.itemPublish == nil || services.itemSinglePublish == nil || services.accountLogin == nil || services.communication == nil || services.analytics == nil {
if services.orders == nil || services.itemPublish == nil || services.itemSinglePublish == nil || services.accountLogin == nil || services.passwordLogin == nil || services.accountDelete == nil || services.communication == nil || services.analytics == nil {
t.Fatal("应用服务集合存在未装配的服务")
}
if services.orders.services == nil || services.orders.services.List == nil || services.orders.services.Detail == nil || services.orders.services.Refresh == nil || services.orders.services.RefreshJobs == nil {
+24 -51
View File
@@ -703,63 +703,36 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
credentialUnlock := s.Store.LockAccountCredentials(cid)
// latest、err 保存latest、err,供当前处理流程使用
latest, err := s.loadCookiePlatformDetail(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
// sess 保存当前认证用户;删除服务会在持久化边界再次确认账号归属。
sess := authSess(r)
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
// deleteService 负责归属复核、停止 fencing、Context 限制和最终删除。
deleteService := s.accountDeleteApplication()
if deleteService == nil {
writeErr(w, http.StatusInternalServerError, "账号删除服务未启用")
return
}
// deleteErr 保存账号删除应用用例的统一错误结果。
deleteErr := deleteService.Delete(r.Context(), sess.UserID, cid)
if errors.Is(deleteErr, accountapp.ErrDeleteConflict) {
writeErr(w, http.StatusConflict, "账号运行时尚未停止,请稍后重试")
return
}
if errors.Is(deleteErr, accountapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
if errors.Is(deleteErr, accountapp.ErrNotFound) || errors.Is(deleteErr, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
// managerFenced 表示删除流程是否已阻止该账号被新的 runtime 重新启动。
managerFenced := false
if s.Manager != nil {
if !s.Manager.BeginStopping(cid) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号正在停止,请稍后重试")
return
}
managerFenced = true
}
credentialUnlock()
if managerFenced {
// stopCtx、stopCancel 限制删除前 runtime fencing 的等待时间。
stopCtx, stopCancel := context.WithTimeout(r.Context(), 5*time.Second)
// stopErr 表示删除前停止账号 runtime 的错误。
stopErr := s.Manager.StopContext(stopCtx, cid)
stopCancel()
if stopErr != nil {
s.Manager.EndStopping(cid)
writeErr(w, http.StatusConflict, "账号运行时尚未停止,请稍后重试")
return
}
}
// 删除前重新取得凭证锁,避免删除与其他凭证更新并发写入。
credentialUnlock = s.Store.LockAccountCredentials(cid)
// latestAfterStop 重新确认停止期间账号仍归当前用户所有,避免误删被替换的账号。
latestAfterStop, latestErr := s.loadCookiePlatformDetail(r.Context(), cid)
if latestErr != nil || latestAfterStop == nil || latestAfterStop.UserID != ownedDetail.UserID {
if managerFenced {
s.Manager.EndStopping(cid)
}
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if // err 保存err,供当前处理流程使用
err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
if managerFenced {
s.Manager.EndStopping(cid)
}
credentialUnlock()
if deleteErr != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
credentialUnlock()
if managerFenced {
s.Manager.EndStopping(cid)
}
s.Logger.Info("账号已删除",
"cookie_id", cid,
"nickname", cachedAccountNickname(ownedDetail),
+2 -2
View File
@@ -59,8 +59,8 @@ type storeNotificationChannelRepository struct {
// ListChannels 查询渠道摘要并丢弃配置,避免敏感配置进入应用展示模型。
func (r storeNotificationChannelRepository) ListChannels(ctx context.Context, userID int64) ([]notificationsapp.ChannelSummary, error) {
// rows、err 保存数据库渠道读取结果;Config 仅在适配器内部被解密读取。
rows, err := r.store.Notifications.AllChannelsForUser(ctx, userID)
// rows、err 保存数据库渠道非敏感摘要;列表路径不会读取或解密 Config。
rows, err := r.store.Notifications.ListChannelSummariesForUser(ctx, userID)
if err != nil {
return nil, err
}
+43 -7
View File
@@ -1,9 +1,12 @@
package server
import (
"errors"
"net/http"
"github.com/go-chi/chi/v5"
accountapp "xianyu-go/internal/application/account"
)
// mountPasswordLogin 保留历史 API 路径,避免旧前端收到 404。Go 客户端的
@@ -15,11 +18,44 @@ func (s *Server) mountPasswordLogin(r chi.Router) {
r.Delete("/password-login/cancel/{session_id}", s.passwordLoginDisabled)
}
// passwordLoginDisabled 返回密码登录已禁用的统一错误响应,保留旧路径兼容性。
func (s *Server) passwordLoginDisabled(w http.ResponseWriter, _ *http.Request) {
writeErrCode(
w,
http.StatusNotImplemented,
"password_login_disabled",
"Go 客户端仅支持扫码登录,密码登录已禁用", "")
// passwordLoginApplication 返回当前 Server 绑定的密码登录应用服务。
func (s *Server) passwordLoginApplication() *accountapp.PasswordLoginService {
return s.applicationServiceSet().passwordLogin
}
// passwordLoginDisabled 通过应用层关闭策略返回统一错误,保留旧路径和版本化路径兼容性。
func (s *Server) passwordLoginDisabled(w http.ResponseWriter, r *http.Request) {
// service 是当前 Server 装配的密码登录应用服务。
service := s.passwordLoginApplication()
if service == nil {
writeErrCode(w, http.StatusInternalServerError, "internal_error", "密码登录应用服务未初始化", "")
return
}
// userID 保存鉴权中间件注入的本地用户身份;密码和 Cookie 不从请求体读取。
var userID int64
// sess 保存当前请求的认证会话;未经过完整路由装配时允许为空。
sess := authSess(r)
if sess != nil {
userID = sess.UserID
}
// operationErr 保存应用服务对当前 HTTP 操作返回的关闭策略结果。
var operationErr error
switch r.Method {
case http.MethodPost:
operationErr = service.Start(r.Context(), accountapp.PasswordLoginStartInput{UserID: userID})
case http.MethodGet:
operationErr = service.Check(r.Context(), accountapp.PasswordLoginSessionInput{UserID: userID, SessionID: chi.URLParam(r, "session_id")})
case http.MethodDelete:
operationErr = service.Cancel(r.Context(), accountapp.PasswordLoginSessionInput{UserID: userID, SessionID: chi.URLParam(r, "session_id")})
default:
writeErrCode(w, http.StatusMethodNotAllowed, "method_not_allowed", "不支持的密码登录操作", "")
return
}
if errors.Is(operationErr, accountapp.ErrPasswordLoginDisabled) {
writeErrCode(w, http.StatusNotImplemented, "password_login_disabled", "Go 客户端仅支持扫码登录,密码登录已禁用", "")
return
}
if operationErr != nil {
writeErrCode(w, http.StatusInternalServerError, "internal_error", "密码登录操作失败", "")
}
}
@@ -44,3 +44,30 @@ func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
}
}
}
// TestPasswordLoginRouteDelegatesDisabledPolicy 验证旧路径与版本化路径均通过应用服务返回关闭策略,而不是解析或传播密码。
func TestPasswordLoginRouteDelegatesDisabledPolicy(t *testing.T) {
// srv、cleanup 保存带完整应用服务装配的 HTTP 测试服务及其释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 保存当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 保存管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// paths 保存需要验证的旧路径和版本化路径。
paths := []string{"/password-login", "/api/v1/password-login"}
for _, path := range paths { // path 表示当前待验证的密码登录入口。
// request 使用故意无法解析的正文,确认关闭策略先于请求体解析执行。
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader("not-json-password-body"))
request.AddCookie(sessionCookie)
// recorder 捕获当前入口的 HTTP 响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusNotImplemented {
t.Fatalf("%s 应由应用策略返回 501,got %d body=%s", path, recorder.Code, recorder.Body.String())
}
if strings.Contains(recorder.Body.String(), "not-json-password-body") {
t.Fatalf("%s 不得回显密码登录请求体", path)
}
}
}