推进P1扫码聊天与通知不确定态收口
This commit is contained in:
1 parent
0a756c408e
commit
3fdd0fe267
18 files changed
+1414
-155
No files matched your search
@@ -0,0 +1,184 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrQRLoginIncomplete 表示平台扫码成功结果缺少可持久化的账号标识或 Cookie。
|
||||
var ErrQRLoginIncomplete = errors.New("扫码结果缺少账号标识或 cookies")
|
||||
|
||||
// ErrQRLoginAccountMismatch 表示扫码得到的平台账号与待重新授权账号不一致。
|
||||
var ErrQRLoginAccountMismatch = errors.New("扫码账号与待重新授权账号不一致")
|
||||
|
||||
// CookieSnapshot 是浏览器返回的单个 Cookie 快照;明文值只在当前凭证适配端口调用期间存在。
|
||||
type CookieSnapshot struct {
|
||||
// Name 是浏览器 Cookie 名称。
|
||||
Name string
|
||||
// Value 是浏览器 Cookie 明文值,禁止日志记录、序列化到 HTTP 或进入长期应用状态。
|
||||
Value string
|
||||
// Domain 是浏览器返回的 Cookie 作用域。
|
||||
Domain string
|
||||
// Path 是浏览器返回的 Cookie 路径。
|
||||
Path string
|
||||
// Expires 是浏览器返回的 Unix 时间戳;零值表示会话 Cookie。
|
||||
Expires float64
|
||||
// HTTPOnly 表示浏览器是否禁止脚本访问该 Cookie。
|
||||
HTTPOnly bool
|
||||
// Secure 表示该 Cookie 是否只允许通过安全连接发送。
|
||||
Secure bool
|
||||
// SameSite 是浏览器返回的跨站请求策略。
|
||||
SameSite string
|
||||
// PartitionKey 是浏览器返回的分区键,供 Cookie 快照合并时保持原样。
|
||||
PartitionKey string
|
||||
}
|
||||
|
||||
// QRLoginInput 是扫码登录成功后持久化用例的纯业务输入;不依赖 HTTP 或平台 DTO。
|
||||
type QRLoginInput struct {
|
||||
// UserID 是发起扫码并拥有目标账号的本地用户标识。
|
||||
UserID int64
|
||||
// ScannedAccountID 是扫码结果解析出的平台账号标识。
|
||||
ScannedAccountID string
|
||||
// TargetAccountID 是可选的待重新授权账号标识;为空时按扫码账号创建或更新。
|
||||
TargetAccountID string
|
||||
// Cookies 是平台返回的登录 Cookie 明文,仅由凭证端口在最小作用域内消费。
|
||||
Cookies string
|
||||
// Snapshot 是可选的完整浏览器 Cookie 快照;存在时由端口负责合并到加密 metadata。
|
||||
Snapshot []CookieSnapshot
|
||||
}
|
||||
|
||||
// QRLoginResult 是扫码登录持久化后返回的非敏感结果。
|
||||
type QRLoginResult struct {
|
||||
// AccountID 是最终创建或更新的本地账号标识。
|
||||
AccountID string
|
||||
// IsNew 表示本次是否创建了新账号。
|
||||
IsNew bool
|
||||
}
|
||||
|
||||
// QRLoginAccount 是账号归属查询返回的非敏感身份信息,不包含 Cookie、密码或 metadata。
|
||||
type QRLoginAccount struct {
|
||||
// ID 是本地账号标识。
|
||||
ID string
|
||||
// UserID 是账号所属本地用户标识。
|
||||
UserID int64
|
||||
}
|
||||
|
||||
// QRLoginRepository 定义扫码登录成功后写凭证所需的最小端口。
|
||||
type QRLoginRepository interface {
|
||||
// LockCredentials 串行化同一账号的凭证创建或更新;解锁函数必须由调用方执行。
|
||||
LockCredentials(string) func()
|
||||
// FindAccount 只查询账号存在性与归属,不读取或解密任何凭证字段。
|
||||
FindAccount(context.Context, string) (QRLoginAccount, error)
|
||||
// CreateCookieOwned 创建当前用户拥有的账号 Cookie;明文只在端口内部进入加密存储。
|
||||
CreateCookieOwned(context.Context, string, string, int64) error
|
||||
// UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并由实现方清理旧快照。
|
||||
UpdateFlatCookieOwned(context.Context, string, string) error
|
||||
// UpdateCookieSnapshotOwned 更新 Cookie 并由实现方合并完整浏览器快照到加密 metadata。
|
||||
UpdateCookieSnapshotOwned(context.Context, string, string, []CookieSnapshot) error
|
||||
// ClearTokens 清理账号旧连接 Token;失败由应用生命周期端口记录,且不回滚已成功写入的 Cookie。
|
||||
ClearTokens(context.Context, string) error
|
||||
}
|
||||
|
||||
// QRLoginLifecycle 定义凭证写入完成后执行的审计、资料刷新和运行时同步边界。
|
||||
type QRLoginLifecycle interface {
|
||||
// AfterSuccessfulQRLogin 在凭证锁释放后执行登录后续编排,禁止在实现中重新暴露凭证明文。
|
||||
AfterSuccessfulQRLogin(context.Context, int64, string)
|
||||
// ReportQRLoginCleanupFailure 记录旧 Token 清理失败;该失败不改变已完成的凭证写入结果。
|
||||
ReportQRLoginCleanupFailure(context.Context, string, error)
|
||||
}
|
||||
|
||||
// QRLoginService 编排扫码结果校验、账号归属、凭证写入和登录后续动作。
|
||||
type QRLoginService struct {
|
||||
// repository 提供不泄露凭证字段的账号持久化端口。
|
||||
repository QRLoginRepository
|
||||
// lifecycle 提供凭证写入后的审计、资料刷新和运行时适配。
|
||||
lifecycle QRLoginLifecycle
|
||||
}
|
||||
|
||||
// NewQRLoginService 构造扫码登录应用服务并校验必需端口。
|
||||
func NewQRLoginService(repository QRLoginRepository, lifecycle QRLoginLifecycle) (*QRLoginService, error) {
|
||||
if repository == nil {
|
||||
return nil, errors.New("扫码登录凭证 repository 未初始化")
|
||||
}
|
||||
if lifecycle == nil {
|
||||
return nil, errors.New("扫码登录生命周期端口未初始化")
|
||||
}
|
||||
return &QRLoginService{repository: repository, lifecycle: lifecycle}, nil
|
||||
}
|
||||
|
||||
// PersistSuccess 执行一次扫码登录成功持久化;返回值只包含账号标识和新建标记。
|
||||
func (s *QRLoginService) PersistSuccess(ctx context.Context, input QRLoginInput) (QRLoginResult, error) {
|
||||
if s == nil || s.repository == nil || s.lifecycle == nil {
|
||||
return QRLoginResult{}, errors.New("扫码登录服务未初始化")
|
||||
}
|
||||
// scannedAccountID 是去除空白后的平台账号标识,避免把格式差异带入账号主键。
|
||||
scannedAccountID := strings.TrimSpace(input.ScannedAccountID)
|
||||
// targetAccountID 是去除空白后的重新授权目标账号标识。
|
||||
targetAccountID := strings.TrimSpace(input.TargetAccountID)
|
||||
if scannedAccountID == "" || strings.TrimSpace(input.Cookies) == "" {
|
||||
return QRLoginResult{}, ErrQRLoginIncomplete
|
||||
}
|
||||
// accountID 是最终用于持久化的账号标识;默认采用扫码得到的账号。
|
||||
accountID := scannedAccountID
|
||||
if targetAccountID != "" {
|
||||
if targetAccountID != scannedAccountID {
|
||||
return QRLoginResult{}, ErrQRLoginAccountMismatch
|
||||
}
|
||||
accountID = targetAccountID
|
||||
}
|
||||
// unlock 保护从归属查询到凭证写入的完整串行区间;生命周期动作在释放后执行。
|
||||
unlock := s.repository.LockCredentials(accountID)
|
||||
// account 保存不含凭证字段的账号归属查询结果。
|
||||
account, findErr := s.repository.FindAccount(ctx, accountID)
|
||||
// isNew 标记本次是否需要创建账号。
|
||||
isNew := false
|
||||
switch {
|
||||
case errors.Is(findErr, ErrNotFound):
|
||||
if targetAccountID != "" {
|
||||
unlock()
|
||||
return QRLoginResult{}, errors.New("待重新授权账号不存在")
|
||||
}
|
||||
isNew = true
|
||||
// createErr 保存新账号凭证端口写入错误。
|
||||
if createErr := s.repository.CreateCookieOwned(ctx, accountID, input.Cookies, input.UserID); createErr != nil {
|
||||
unlock()
|
||||
return QRLoginResult{}, createErr
|
||||
}
|
||||
case findErr != nil:
|
||||
unlock()
|
||||
return QRLoginResult{}, findErr
|
||||
case account.UserID != input.UserID:
|
||||
unlock()
|
||||
return QRLoginResult{}, ErrForbidden
|
||||
default:
|
||||
// updateErr 保存已有账号 Cookie 更新错误。
|
||||
if updateErr := s.updateExisting(ctx, accountID, input); updateErr != nil {
|
||||
unlock()
|
||||
return QRLoginResult{}, updateErr
|
||||
}
|
||||
}
|
||||
if isNew && len(input.Snapshot) > 0 {
|
||||
// snapshotErr 保存新账号完整 Cookie 快照写入错误。
|
||||
if snapshotErr := s.repository.UpdateCookieSnapshotOwned(ctx, accountID, input.Cookies, input.Snapshot); snapshotErr != nil {
|
||||
unlock()
|
||||
return QRLoginResult{}, snapshotErr
|
||||
}
|
||||
}
|
||||
// clearErr 保存旧连接 Token 清理结果;凭证已写入成功,因此该尽力而为操作不阻断登录后续动作。
|
||||
clearErr := s.repository.ClearTokens(ctx, accountID)
|
||||
unlock()
|
||||
if clearErr != nil {
|
||||
s.lifecycle.ReportQRLoginCleanupFailure(ctx, accountID, clearErr)
|
||||
}
|
||||
s.lifecycle.AfterSuccessfulQRLogin(ctx, input.UserID, accountID)
|
||||
return QRLoginResult{AccountID: accountID, IsNew: isNew}, nil
|
||||
}
|
||||
|
||||
// updateExisting 更新已存在且已通过归属校验的账号凭证。
|
||||
func (s *QRLoginService) updateExisting(ctx context.Context, accountID string, input QRLoginInput) error {
|
||||
if len(input.Snapshot) > 0 {
|
||||
return s.repository.UpdateCookieSnapshotOwned(ctx, accountID, input.Cookies, input.Snapshot)
|
||||
}
|
||||
return s.repository.UpdateFlatCookieOwned(ctx, accountID, input.Cookies)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeQRLoginRepository 是扫码登录应用服务测试使用的凭证端口替身。
|
||||
type fakeQRLoginRepository struct {
|
||||
// account 保存待返回的非敏感账号归属。
|
||||
account QRLoginAccount
|
||||
// findErr 保存账号存在性查询错误。
|
||||
findErr error
|
||||
// createErr 保存新账号凭证创建错误。
|
||||
createErr error
|
||||
// flatErr 保存扁平 Cookie 更新错误。
|
||||
flatErr error
|
||||
// snapshotErr 保存 Cookie 快照更新错误。
|
||||
snapshotErr error
|
||||
// clearErr 保存旧 Token 清理错误。
|
||||
clearErr error
|
||||
// createdCookies 保存新账号端口收到的 Cookie,用于验证敏感值只在端口边界出现。
|
||||
createdCookies string
|
||||
// updatedCookies 保存已有账号端口收到的 Cookie,用于验证更新路径。
|
||||
updatedCookies string
|
||||
// updatedSnapshot 保存端口收到的完整 Cookie 快照。
|
||||
updatedSnapshot []CookieSnapshot
|
||||
// lockCount 记录凭证锁获取次数。
|
||||
lockCount int
|
||||
// clearCount 记录旧 Token 清理次数。
|
||||
clearCount int
|
||||
}
|
||||
|
||||
// LockCredentials 记录测试服务获取凭证锁,并返回无副作用的解锁函数。
|
||||
func (r *fakeQRLoginRepository) LockCredentials(string) func() {
|
||||
r.lockCount++
|
||||
return func() {}
|
||||
}
|
||||
|
||||
// FindAccount 返回预置账号归属或存在性错误。
|
||||
func (r *fakeQRLoginRepository) FindAccount(context.Context, string) (QRLoginAccount, error) {
|
||||
return r.account, r.findErr
|
||||
}
|
||||
|
||||
// CreateCookieOwned 记录新账号 Cookie 写入请求。
|
||||
func (r *fakeQRLoginRepository) CreateCookieOwned(_ context.Context, _ string, cookies string, _ int64) error {
|
||||
r.createdCookies = cookies
|
||||
return r.createErr
|
||||
}
|
||||
|
||||
// UpdateFlatCookieOwned 记录已有账号的扁平 Cookie 更新。
|
||||
func (r *fakeQRLoginRepository) UpdateFlatCookieOwned(_ context.Context, _ string, cookies string) error {
|
||||
r.updatedCookies = cookies
|
||||
return r.flatErr
|
||||
}
|
||||
|
||||
// UpdateCookieSnapshotOwned 记录带完整快照的 Cookie 更新。
|
||||
func (r *fakeQRLoginRepository) UpdateCookieSnapshotOwned(_ context.Context, _ string, cookies string, snapshot []CookieSnapshot) error {
|
||||
r.updatedCookies = cookies
|
||||
r.updatedSnapshot = snapshot
|
||||
return r.snapshotErr
|
||||
}
|
||||
|
||||
// ClearTokens 记录旧连接 Token 清理请求。
|
||||
func (r *fakeQRLoginRepository) ClearTokens(context.Context, string) error {
|
||||
r.clearCount++
|
||||
return r.clearErr
|
||||
}
|
||||
|
||||
// fakeQRLoginLifecycle 是扫码登录后续动作测试用的生命周期端口替身。
|
||||
type fakeQRLoginLifecycle struct {
|
||||
// calls 记录生命周期端口调用次数。
|
||||
calls int
|
||||
// userID 保存生命周期端口收到的用户标识。
|
||||
userID int64
|
||||
// accountID 保存生命周期端口收到的账号标识。
|
||||
accountID string
|
||||
// cleanupErr 保存生命周期端口收到的旧 Token 清理失败。
|
||||
cleanupErr error
|
||||
}
|
||||
|
||||
// AfterSuccessfulQRLogin 记录扫码成功后的生命周期调用参数。
|
||||
func (l *fakeQRLoginLifecycle) AfterSuccessfulQRLogin(_ context.Context, userID int64, accountID string) {
|
||||
l.calls++
|
||||
l.userID = userID
|
||||
l.accountID = accountID
|
||||
}
|
||||
|
||||
// ReportQRLoginCleanupFailure 记录旧 Token 清理失败,验证该错误不阻断登录成功结果。
|
||||
func (l *fakeQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, _ string, err error) {
|
||||
l.cleanupErr = err
|
||||
}
|
||||
|
||||
// TestNewQRLoginServiceRequiresPorts 验证扫码登录应用服务拒绝缺失依赖。
|
||||
func TestNewQRLoginServiceRequiresPorts(t *testing.T) {
|
||||
// repository 是满足凭证端口的测试替身。
|
||||
repository := &fakeQRLoginRepository{}
|
||||
// lifecycle 是满足登录后续动作端口的测试替身。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// cases 保存构造阶段必须拒绝的依赖缺失场景。
|
||||
cases := []struct {
|
||||
// name 是当前构造失败场景名称。
|
||||
name string
|
||||
// repository 是当前场景的凭证端口。
|
||||
repository QRLoginRepository
|
||||
// lifecycle 是当前场景的生命周期端口。
|
||||
lifecycle QRLoginLifecycle
|
||||
}{
|
||||
{name: "缺少凭证端口", lifecycle: lifecycle},
|
||||
{name: "缺少生命周期端口", repository: repository},
|
||||
}
|
||||
// testCase 表示当前遍历的构造失败场景。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// err 保存当前场景的构造结果错误。
|
||||
_, err := NewQRLoginService(testCase.repository, testCase.lifecycle)
|
||||
if err == nil {
|
||||
t.Fatal("缺少必需端口时应构造失败")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginPersistSuccessCreatesAccountAndHidesCookie 验证新账号成功写入及敏感值不进入结果。
|
||||
func TestQRLoginPersistSuccessCreatesAccountAndHidesCookie(t *testing.T) {
|
||||
// repository 返回账号不存在,模拟首次扫码登录。
|
||||
repository := &fakeQRLoginRepository{findErr: ErrNotFound}
|
||||
// lifecycle 记录成功后的审计与运行时同步调用。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// service 是待验证的扫码登录应用服务。
|
||||
service, err := NewQRLoginService(repository, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造扫码登录服务失败: %v", err)
|
||||
}
|
||||
// input 携带平台扫码成功结果;Cookie 只允许进入凭证端口。
|
||||
input := QRLoginInput{
|
||||
UserID: 7, ScannedAccountID: "unb-7", Cookies: "unb=unb-7; token=secret-cookie",
|
||||
Snapshot: []CookieSnapshot{{Name: "unb", Value: "unb-7", Domain: ".example.com", Path: "/"}},
|
||||
}
|
||||
// result 保存应用服务返回的非敏感成功结果。
|
||||
result, err := service.PersistSuccess(context.Background(), input)
|
||||
if err != nil {
|
||||
t.Fatalf("扫码登录持久化失败: %v", err)
|
||||
}
|
||||
if result.AccountID != "unb-7" || !result.IsNew || lifecycle.calls != 1 {
|
||||
t.Fatalf("成功结果异常: result=%+v lifecycle=%+v", result, lifecycle)
|
||||
}
|
||||
if repository.createdCookies != input.Cookies || len(repository.updatedSnapshot) != 1 || repository.clearCount != 1 {
|
||||
t.Fatalf("凭证端口调用异常: %+v", repository)
|
||||
}
|
||||
// encodedResult 是 HTTP 层可能序列化的应用结果,用于确认不会泄露 Cookie 明文。
|
||||
encodedResult, marshalErr := json.Marshal(result)
|
||||
if marshalErr != nil {
|
||||
t.Fatalf("序列化结果失败: %v", marshalErr)
|
||||
}
|
||||
if strings.Contains(string(encodedResult), "secret-cookie") {
|
||||
t.Fatalf("应用结果泄露 Cookie: %s", encodedResult)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginPersistSuccessUpdatesOwnedAccount 验证已有账号归属通过后更新扁平 Cookie。
|
||||
func TestQRLoginPersistSuccessUpdatesOwnedAccount(t *testing.T) {
|
||||
// repository 返回当前用户拥有的账号,且没有完整快照。
|
||||
repository := &fakeQRLoginRepository{account: QRLoginAccount{ID: "unb-7", UserID: 7}}
|
||||
// lifecycle 记录成功后的后续动作。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// service 是待验证的扫码登录应用服务。
|
||||
service, err := NewQRLoginService(repository, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造扫码登录服务失败: %v", err)
|
||||
}
|
||||
// result 保存已有账号更新后的非敏感结果。
|
||||
result, err := service.PersistSuccess(context.Background(), QRLoginInput{
|
||||
UserID: 7, ScannedAccountID: "unb-7", Cookies: "unb=unb-7; token=rotated",
|
||||
})
|
||||
if err != nil || result.AccountID != "unb-7" || result.IsNew {
|
||||
t.Fatalf("已有账号更新异常: result=%+v err=%v", result, err)
|
||||
}
|
||||
if repository.updatedCookies == "" || lifecycle.accountID != "unb-7" {
|
||||
t.Fatalf("已有账号更新端口未调用: %+v %+v", repository, lifecycle)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginPersistRejectsOwnershipAndMismatch 验证跨用户、目标不一致和不完整结果均不会写入凭证。
|
||||
func TestQRLoginPersistRejectsOwnershipAndMismatch(t *testing.T) {
|
||||
// ownershipRepository 返回其他用户拥有的账号。
|
||||
ownershipRepository := &fakeQRLoginRepository{account: QRLoginAccount{ID: "unb-7", UserID: 8}}
|
||||
// lifecycle 是不应被失败流程调用的生命周期替身。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// ownershipService 是待验证跨用户拒绝服务。
|
||||
ownershipService, err := NewQRLoginService(ownershipRepository, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造归属服务失败: %v", err)
|
||||
}
|
||||
// _, ownershipErr 保存跨用户写入结果。
|
||||
_, ownershipErr := ownershipService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"})
|
||||
if !errors.Is(ownershipErr, ErrForbidden) || lifecycle.calls != 0 {
|
||||
t.Fatalf("跨用户账号未被拒绝: err=%v lifecycle=%d", ownershipErr, lifecycle.calls)
|
||||
}
|
||||
|
||||
// mismatchService 是待验证扫码账号与目标账号不一致的服务。
|
||||
mismatchService, err := NewQRLoginService(&fakeQRLoginRepository{}, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造不一致服务失败: %v", err)
|
||||
}
|
||||
// _, mismatchErr 保存账号不一致结果。
|
||||
_, mismatchErr := mismatchService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", TargetAccountID: "unb-8", Cookies: "secret"})
|
||||
if !errors.Is(mismatchErr, ErrQRLoginAccountMismatch) {
|
||||
t.Fatalf("账号不一致未被拒绝: %v", mismatchErr)
|
||||
}
|
||||
|
||||
// incompleteService 是待验证缺少 Cookie 的服务。
|
||||
incompleteService, err := NewQRLoginService(&fakeQRLoginRepository{}, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造不完整结果服务失败: %v", err)
|
||||
}
|
||||
// _, incompleteErr 保存不完整结果错误。
|
||||
_, incompleteErr := incompleteService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7"})
|
||||
if !errors.Is(incompleteErr, ErrQRLoginIncomplete) {
|
||||
t.Fatalf("不完整扫码结果未被拒绝: %v", incompleteErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginPersistPropagatesWriteFailure 验证凭证写入失败时不触发生命周期动作。
|
||||
func TestQRLoginPersistPropagatesWriteFailure(t *testing.T) {
|
||||
// writeErr 是测试凭证端口返回的持久化错误。
|
||||
writeErr := errors.New("凭证存储不可用")
|
||||
// repository 模拟新账号写入失败。
|
||||
repository := &fakeQRLoginRepository{findErr: ErrNotFound, createErr: writeErr}
|
||||
// lifecycle 记录不应发生的成功后续动作。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// service 是待验证的扫码登录服务。
|
||||
service, err := NewQRLoginService(repository, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造写入失败服务失败: %v", err)
|
||||
}
|
||||
// _, persistErr 保存凭证端口错误。
|
||||
_, persistErr := service.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"})
|
||||
if !errors.Is(persistErr, writeErr) || lifecycle.calls != 0 {
|
||||
t.Fatalf("凭证写入错误未正确传播: err=%v lifecycle=%d", persistErr, lifecycle.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQRLoginPersistIgnoresTokenCleanupFailure 验证凭证已保存时旧 Token 清理失败不会伪装成登录失败。
|
||||
func TestQRLoginPersistIgnoresTokenCleanupFailure(t *testing.T) {
|
||||
// repository 模拟已有账号更新成功但旧 Token 清理失败。
|
||||
repository := &fakeQRLoginRepository{
|
||||
account: QRLoginAccount{ID: "unb-7", UserID: 7},
|
||||
clearErr: errors.New("旧 Token 清理失败"),
|
||||
}
|
||||
// lifecycle 记录凭证保存成功后的后续动作。
|
||||
lifecycle := &fakeQRLoginLifecycle{}
|
||||
// service 是待验证的扫码登录服务。
|
||||
service, err := NewQRLoginService(repository, lifecycle)
|
||||
if err != nil {
|
||||
t.Fatalf("构造 Token 清理失败服务失败: %v", err)
|
||||
}
|
||||
// result、persistErr 保存凭证成功与否以及应用错误。
|
||||
result, persistErr := service.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"})
|
||||
if persistErr != nil || result.AccountID != "unb-7" || lifecycle.calls != 1 {
|
||||
t.Fatalf("Token 清理失败不应阻断登录: result=%+v err=%v lifecycle=%d", result, persistErr, lifecycle.calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// Package chat 提供聊天历史等 HTTP 用例所需的应用层编排,不依赖 HTTP 或数据库模型。
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrInvalidInput 表示聊天历史查询缺少必要的非敏感标识。
|
||||
var ErrInvalidInput = errors.New("聊天历史查询参数无效")
|
||||
|
||||
// Message 是聊天历史用例对外暴露的非敏感消息模型。
|
||||
type Message struct {
|
||||
// ID 是本地消息主键。
|
||||
ID int64
|
||||
// AccountID 是消息所属账号标识,不包含账号凭证。
|
||||
AccountID string
|
||||
// ChatID 是平台聊天会话标识。
|
||||
ChatID string
|
||||
// MessageKey 是消息幂等键。
|
||||
MessageKey string
|
||||
// Direction 是消息方向,例如 incoming 或 outgoing。
|
||||
Direction string
|
||||
// SenderID 是平台发送者标识。
|
||||
SenderID string
|
||||
// SenderName 是发送者展示名称。
|
||||
SenderName string
|
||||
// MessageType 是消息内容类型。
|
||||
MessageType string
|
||||
// Content 是文本或媒体地址,不包含平台凭证。
|
||||
Content string
|
||||
// Status 是消息投递状态。
|
||||
Status string
|
||||
// SentAt 是消息发送时间的 Unix 秒时间戳。
|
||||
SentAt int64
|
||||
}
|
||||
|
||||
// Session 是聊天历史用例使用的会话摘要,不包含 Cookie 或其他秘密。
|
||||
type Session struct {
|
||||
// AccountID 是会话所属账号标识。
|
||||
AccountID string
|
||||
// ChatID 是平台聊天会话标识。
|
||||
ChatID string
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string
|
||||
// BuyerName 是买家展示名称。
|
||||
BuyerName string
|
||||
// BuyerAvatar 是买家头像地址。
|
||||
BuyerAvatar string
|
||||
// ItemID 是会话关联商品标识。
|
||||
ItemID string
|
||||
// ItemTitle 是会话关联商品标题。
|
||||
ItemTitle string
|
||||
// LastMessage 是最近消息摘要。
|
||||
LastMessage string
|
||||
// LastMessageAt 是最近消息时间的 Unix 秒时间戳。
|
||||
LastMessageAt int64
|
||||
// UnreadCount 是当前会话未读消息数量。
|
||||
UnreadCount int
|
||||
}
|
||||
|
||||
// Page 是聊天历史查询的分页结果。
|
||||
type Page struct {
|
||||
// Messages 是按时间正序排列的当前页消息。
|
||||
Messages []Message
|
||||
// Session 是当前会话摘要;找不到摘要时保持零值。
|
||||
Session Session
|
||||
// HasMore 表示是否可能还有更早消息。
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// Repository 定义聊天历史用例需要的最小持久化能力。
|
||||
type Repository interface {
|
||||
// ListMessages 按用户归属查询指定账号和会话的消息。
|
||||
ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]Message, error)
|
||||
// ListSessions 按用户归属查询账号的会话摘要。
|
||||
ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]Session, error)
|
||||
}
|
||||
|
||||
// Service 编排聊天历史查询,不持有 HTTP 请求或数据库连接。
|
||||
type Service struct {
|
||||
// repository 保存由调用方注入的最小持久化端口。
|
||||
repository Repository
|
||||
}
|
||||
|
||||
// New 创建聊天历史应用服务;空端口会导致构造结果不可用。
|
||||
func New(repository Repository) *Service {
|
||||
return &Service{repository: repository}
|
||||
}
|
||||
|
||||
// ListStoredMessages 查询当前用户有权访问的本地聊天历史。
|
||||
// userID 用于归属过滤,accountID/chatID 定位账号和会话,beforeID 控制向更早消息翻页,limit 控制页大小;
|
||||
// 返回的 Page 只含非敏感消息和会话摘要,底层端口错误原样返回。
|
||||
func (s *Service) ListStoredMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) (Page, error) {
|
||||
accountID = strings.TrimSpace(accountID)
|
||||
chatID = strings.TrimSpace(chatID)
|
||||
if s == nil || s.repository == nil || userID <= 0 || accountID == "" || chatID == "" {
|
||||
return Page{}, ErrInvalidInput
|
||||
}
|
||||
// messages 保存按用户归属过滤后的聊天消息。
|
||||
messages, err := s.repository.ListMessages(ctx, userID, accountID, chatID, beforeID, limit)
|
||||
if err != nil {
|
||||
return Page{}, err
|
||||
}
|
||||
// session 保存当前会话摘要;查询失败时保持零值。
|
||||
var session Session
|
||||
// sessions 和 sessionErr 保存会话摘要列表及其查询错误;摘要失败不影响消息结果。
|
||||
if sessions, sessionErr := s.repository.ListSessions(ctx, userID, accountID, 500); sessionErr == nil {
|
||||
// candidate 保存当前遍历到的会话摘要。
|
||||
for _, candidate := range sessions {
|
||||
if candidate.ChatID == chatID {
|
||||
session = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return Page{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeRepository 保存测试聊天历史数据,并记录最近一次用户归属参数。
|
||||
type fakeRepository struct {
|
||||
// messages 是模拟聊天消息列表。
|
||||
messages []Message
|
||||
// sessions 是模拟会话摘要列表。
|
||||
sessions []Session
|
||||
// messageErr 是消息查询需要返回的错误。
|
||||
messageErr error
|
||||
// sessionErr 是会话查询需要返回的错误。
|
||||
sessionErr error
|
||||
// userID 保存最近一次消息查询使用的用户 ID。
|
||||
userID int64
|
||||
// allowedUserID 是允许读取测试账号的用户 ID;其他用户模拟归属拒绝。
|
||||
allowedUserID int64
|
||||
}
|
||||
|
||||
// ListMessages 返回测试消息,并记录用户归属参数。
|
||||
func (r *fakeRepository) ListMessages(_ context.Context, userID int64, _ string, _ string, _ int64, _ int) ([]Message, error) {
|
||||
r.userID = userID
|
||||
if r.allowedUserID != 0 && userID != r.allowedUserID {
|
||||
return nil, errors.New("cross-user access denied")
|
||||
}
|
||||
return r.messages, r.messageErr
|
||||
}
|
||||
|
||||
// ListSessions 返回测试会话摘要或预设错误。
|
||||
func (r *fakeRepository) ListSessions(_ context.Context, _ int64, _ string, _ int) ([]Session, error) {
|
||||
return r.sessions, r.sessionErr
|
||||
}
|
||||
|
||||
// TestListStoredMessagesUsesUserScopedPort 验证查询会把用户 ID 传到归属端口并组装分页结果。
|
||||
func TestListStoredMessagesUsesUserScopedPort(t *testing.T) {
|
||||
// repository 是带有一条消息和会话摘要的测试端口。
|
||||
repository := &fakeRepository{
|
||||
messages: []Message{{ID: 1, ChatID: "chat-1", Content: "你好"}},
|
||||
sessions: []Session{{ChatID: "chat-1", BuyerName: "买家甲"}},
|
||||
}
|
||||
// service 是使用测试端口构造的聊天历史服务。
|
||||
service := New(repository)
|
||||
// page 保存当前用户读取到的分页结果。
|
||||
page, err := service.ListStoredMessages(context.Background(), 42, "account-1", "chat-1", 0, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ListStoredMessages() error = %v", err)
|
||||
}
|
||||
if repository.userID != 42 || len(page.Messages) != 1 || page.Session.BuyerName != "买家甲" || !page.HasMore {
|
||||
t.Fatalf("unexpected page=%+v userID=%d", page, repository.userID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStoredMessagesRejectsInvalidIdentity 验证无效用户或账号标识会在访问端口前失败。
|
||||
func TestListStoredMessagesRejectsInvalidIdentity(t *testing.T) {
|
||||
// service 是不应被调用的测试服务。
|
||||
service := New(&fakeRepository{})
|
||||
// testCase 表示当前待验证的无效身份场景。
|
||||
for _, testCase := range []struct {
|
||||
// name 是当前无效输入场景名称。
|
||||
name string
|
||||
// userID 是当前请求用户标识。
|
||||
userID int64
|
||||
// accountID 是当前账号标识。
|
||||
accountID string
|
||||
// chatID 是当前会话标识。
|
||||
chatID string
|
||||
}{
|
||||
{name: "missing-user", userID: 0, accountID: "account-1", chatID: "chat-1"},
|
||||
{name: "missing-account", userID: 1, accountID: "", chatID: "chat-1"},
|
||||
{name: "missing-chat", userID: 1, accountID: "account-1", chatID: ""},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// err 保存当前无效请求返回的应用错误。
|
||||
_, err := service.ListStoredMessages(context.Background(), testCase.userID, testCase.accountID, testCase.chatID, 0, 20)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStoredMessagesRejectsUnavailableService 验证未装配端口或空服务不会触发 panic。
|
||||
func TestListStoredMessagesRejectsUnavailableService(t *testing.T) {
|
||||
// nilService 表示尚未完成依赖装配的聊天服务指针。
|
||||
var nilService *Service
|
||||
// service 表示当前待验证的不可用聊天服务实例。
|
||||
for _, service := range []*Service{nilService, New(nil)} {
|
||||
// err 保存不可用服务返回的应用错误。
|
||||
_, err := service.ListStoredMessages(context.Background(), 1, "account-1", "chat-1", 0, 20)
|
||||
if !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("error = %v, want ErrInvalidInput", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStoredMessagesPropagatesRepositoryFailure 验证消息持久化失败不会被伪装成成功空页。
|
||||
func TestListStoredMessagesPropagatesRepositoryFailure(t *testing.T) {
|
||||
// wantErr 是模拟底层查询失败的稳定错误。
|
||||
wantErr := errors.New("repository unavailable")
|
||||
// service 是返回预设错误的聊天历史服务。
|
||||
service := New(&fakeRepository{messageErr: wantErr})
|
||||
// _, err 保存应用服务返回的分页结果和错误。
|
||||
_, err := service.ListStoredMessages(context.Background(), 7, "account-1", "chat-1", 0, 20)
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, wantErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStoredMessagesKeepsMessagesWhenSessionLookupFails 验证摘要查询失败不会丢弃已成功读取的消息。
|
||||
func TestListStoredMessagesKeepsMessagesWhenSessionLookupFails(t *testing.T) {
|
||||
// service 是消息成功但会话摘要失败的聊天历史服务。
|
||||
service := New(&fakeRepository{messages: []Message{{ID: 2, ChatID: "chat-1"}}, sessionErr: errors.New("session unavailable")})
|
||||
// page 和 err 保存应用服务返回的消息页及错误。
|
||||
page, err := service.ListStoredMessages(context.Background(), 1, "account-1", "chat-1", 0, 20)
|
||||
if err != nil || len(page.Messages) != 1 || page.Session.ChatID != "" {
|
||||
t.Fatalf("page=%+v err=%v", page, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListStoredMessagesDoesNotCrossUserBoundary 验证其他用户的账号消息不会被应用服务当作空结果返回。
|
||||
func TestListStoredMessagesDoesNotCrossUserBoundary(t *testing.T) {
|
||||
// service 是只允许用户 7 读取账号的聊天历史服务。
|
||||
service := New(&fakeRepository{allowedUserID: 7, messages: []Message{{ID: 1}}})
|
||||
// err 保存用户 8 尝试读取用户 7 账号时的归属错误。
|
||||
_, err := service.ListStoredMessages(context.Background(), 8, "account-1", "chat-1", 0, 20)
|
||||
if err == nil || err.Error() != "cross-user access denied" {
|
||||
t.Fatalf("cross-user error = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user