重构:统一应用服务与基础设施适配边界
将账号、认证、管理员、分析、自动化、卡券、聊天、商品、关键词、设置和订单能力迁移到 application 与 adapter,删除 Server 内对应的旧仓储和业务服务实现,并收紧架构检查。 完善批量发布与订单刷新生命周期、凭证写回、账号任务补偿、订单 reconciliation、通知和敏感数据边界;补充正常、失败、取消、并发、越权及多方言回归测试,并修正 MySQL 延迟任务表的 InnoDB 配置。 修复空卡密响应为 null 时前端加载失败的问题,重建嵌入式前端资产;重写重构总计划,清除历史流水并明确阶段 1 至 10 各对应一次完整迭代和一个 PR。 验证:make check;make test-server-race;npm test/typecheck/comments:check/build;Docker SQLite/MySQL 8.4/PostgreSQL 17 TestMultiDB_*。
This commit is contained in:
1 parent
19a7d5f924
commit
375e84d663
239 files changed
+23870
-7871
No files matched your search
@@ -0,0 +1,405 @@
|
||||
// Package settings 提供系统、用户和账号 AI 设置的应用层用例。
|
||||
// 本包只依赖消费者定义的 Port,不感知 HTTP、数据库模型或具体网络实现。
|
||||
package settings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrInvalidUser 表示调用方没有提供有效的本地用户标识。
|
||||
var ErrInvalidUser = errors.New("设置用户标识无效")
|
||||
|
||||
// ErrAccountNotFound 表示目标账号不存在。
|
||||
var ErrAccountNotFound = errors.New("设置账号不存在")
|
||||
|
||||
// ErrForbidden 表示目标账号属于其他用户。
|
||||
var ErrForbidden = errors.New("无权操作该账号设置")
|
||||
|
||||
// ErrConfigNotFound 表示账号存在但尚未保存 AI 回复设置。
|
||||
var ErrConfigNotFound = errors.New("AI 回复设置不存在")
|
||||
|
||||
// SecretChange 描述敏感系统设置的显式三态变更命令。
|
||||
type SecretChange struct {
|
||||
// Action 是 retain、replace 或 clear 之一。
|
||||
Action string
|
||||
// Value 是 replace 操作要保存的新秘密。
|
||||
Value string
|
||||
}
|
||||
|
||||
// AIReplySettings 是不携带模型地址、API 密钥等系统秘密的账号级 AI 设置。
|
||||
type AIReplySettings struct {
|
||||
// CookieID 是设置所属账号的稳定标识。
|
||||
CookieID string
|
||||
// AIEnabled 表示账号 AI 回复是否启用。
|
||||
AIEnabled bool
|
||||
// MaxDiscountPercent 是允许的最大折扣比例。
|
||||
MaxDiscountPercent int
|
||||
// MaxDiscountAmount 是允许的最大折扣金额。
|
||||
MaxDiscountAmount int
|
||||
// MaxBargainRounds 是允许的最大砍价轮次。
|
||||
MaxBargainRounds int
|
||||
// CustomPrompts 是账号自定义提示词。
|
||||
CustomPrompts string
|
||||
}
|
||||
|
||||
// AuditRecord 是敏感设置访问审计的非敏感应用模型。
|
||||
type AuditRecord struct {
|
||||
// UserID 是执行敏感操作的本地用户标识。
|
||||
UserID int64
|
||||
// Action 是敏感操作类型。
|
||||
Action string
|
||||
// Resource 是被访问的业务资源。
|
||||
Resource string
|
||||
// Keys 是涉及的敏感设置键名,不包含键值。
|
||||
Keys []string
|
||||
// Outcome 是审计结果,例如 accepted。
|
||||
Outcome string
|
||||
}
|
||||
|
||||
// Repository 定义设置用例所需的最小持久化和审计能力。
|
||||
type Repository interface {
|
||||
// IsSensitiveSettingKey 判断设置键是否属于敏感白名单。
|
||||
IsSensitiveSettingKey(key string) bool
|
||||
// SensitiveSettingKeys 返回敏感设置键名,不返回任何秘密值。
|
||||
SensitiveSettingKeys() []string
|
||||
// PublicSystem 返回无需认证展示的系统设置。
|
||||
PublicSystem(ctx context.Context) (map[string]string, error)
|
||||
// RedactedSystem 返回管理员可见但已脱敏的系统设置。
|
||||
RedactedSystem(ctx context.Context) (map[string]string, error)
|
||||
// GetSystem 读取指定系统设置;仅应用服务内部用于受控业务操作。
|
||||
GetSystem(ctx context.Context, key string) (string, error)
|
||||
// ReadSensitiveSystem 审计后读取指定敏感系统设置。
|
||||
ReadSensitiveSystem(ctx context.Context, userID int64, key, action, resource string) (string, error)
|
||||
// ApplySystemChanges 原子保存普通设置和敏感变更命令。
|
||||
ApplySystemChanges(ctx context.Context, values map[string]string, secrets map[string]SecretChange) error
|
||||
// SetSystem 保存一项普通系统设置。
|
||||
SetSystem(ctx context.Context, key, value string) error
|
||||
// AddAudit 写入不包含秘密值的访问审计。
|
||||
AddAudit(ctx context.Context, record AuditRecord) error
|
||||
// ListUser 返回指定用户的全部用户设置。
|
||||
ListUser(ctx context.Context, userID int64) (map[string]string, error)
|
||||
// GetUser 返回指定用户的一项设置;不存在时返回空值。
|
||||
GetUser(ctx context.Context, userID int64, key string) (string, error)
|
||||
// SetUser 保存指定用户的一项设置。
|
||||
SetUser(ctx context.Context, userID int64, key, value string) error
|
||||
// CheckOwnership 返回账号的非敏感所有者标识。
|
||||
CheckOwnership(ctx context.Context, userID int64, cookieID string) (int64, error)
|
||||
// ListAIReply 返回用户范围内的账号 AI 设置摘要。
|
||||
ListAIReply(ctx context.Context, userID int64) ([]AIReplySettings, error)
|
||||
// GetAIReply 返回指定用户账号的 AI 设置摘要。
|
||||
GetAIReply(ctx context.Context, userID int64, cookieID string) (AIReplySettings, error)
|
||||
// UpsertAIReply 保存指定账号的 AI 设置摘要。
|
||||
UpsertAIReply(ctx context.Context, cookieID string, settings AIReplySettings) error
|
||||
}
|
||||
|
||||
// ModelClient 定义读取远端 AI 模型列表所需的最小网络能力。
|
||||
type ModelClient interface {
|
||||
// Fetch 获取指定 AI 服务地址的模型名称,调用方不得把 API 密钥写入日志或响应。
|
||||
Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error)
|
||||
}
|
||||
|
||||
// Service 编排设置读取、校验、审计和持久化,不依赖 HTTP 或数据库类型。
|
||||
type Service struct {
|
||||
// repository 提供设置持久化与敏感访问审计能力。
|
||||
repository Repository
|
||||
// modelClient 提供远端模型目录读取能力。
|
||||
modelClient ModelClient
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断 HTTP 兼容层中的设置键是否属于敏感白名单。
|
||||
func (s *Service) IsSensitiveSettingKey(key string) bool {
|
||||
return s != nil && s.repository != nil && s.repository.IsSensitiveSettingKey(key)
|
||||
}
|
||||
|
||||
// NewService 构造设置应用服务。
|
||||
func NewService(repository Repository, modelClient ModelClient) *Service {
|
||||
// service 保存调用方提供的设置 Port 与模型客户端。
|
||||
service := &Service{repository: repository, modelClient: modelClient}
|
||||
return service
|
||||
}
|
||||
|
||||
// PublicSystem 读取公开系统设置。
|
||||
func (s *Service) PublicSystem(ctx context.Context) (map[string]string, error) {
|
||||
// err 表示设置 Port 未装配或公开设置读取失败。
|
||||
if err := s.validateRepository(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repository.PublicSystem(ctx)
|
||||
}
|
||||
|
||||
// GetSystem 返回管理员可见的系统设置,并先记录完整敏感键白名单的读取审计。
|
||||
func (s *Service) GetSystem(ctx context.Context, userID int64) (map[string]string, error) {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// keys 是本次管理员读取需要审计的敏感键名集合。
|
||||
keys := s.repository.SensitiveSettingKeys()
|
||||
// err 表示敏感设置读取审计写入失败。
|
||||
if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.read", Resource: "system_settings", Keys: keys}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repository.RedactedSystem(ctx)
|
||||
}
|
||||
|
||||
// ApplySystemChanges 校验并原子保存系统设置,敏感命令写入前必须完成审计。
|
||||
func (s *Service) ApplySystemChanges(ctx context.Context, userID int64, values map[string]string, secrets map[string]SecretChange) error {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(values) == 0 && len(secrets) == 0 {
|
||||
return errors.New("设置不能为空")
|
||||
}
|
||||
// err 表示普通设置值违反敏感键或键名约束。
|
||||
if err := s.validateValues(values); err != nil {
|
||||
return err
|
||||
}
|
||||
// keys 保存待写入审计记录的敏感设置键名。
|
||||
keys := make([]string, 0, len(secrets))
|
||||
// key 是待审计的敏感设置键;change 是对应的三态命令。
|
||||
for key, change := range secrets {
|
||||
if !s.repository.IsSensitiveSettingKey(key) || !validSecretAction(change) {
|
||||
return errors.New("敏感设置命令无效")
|
||||
}
|
||||
if change.Action == "replace" && strings.TrimSpace(change.Value) == "" {
|
||||
return errors.New("敏感设置命令无效")
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
if len(keys) > 0 {
|
||||
// err 表示敏感设置写入审计失败。
|
||||
if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.write", Resource: "system_settings", Keys: keys}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, values, secrets)
|
||||
}
|
||||
|
||||
// SetSystem 保存单项系统设置,并把敏感设置的三态命令统一交给应用层校验。
|
||||
func (s *Service) SetSystem(ctx context.Context, userID int64, key, value, action string) error {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" || len(key) > 100 {
|
||||
return errors.New("设置键无效")
|
||||
}
|
||||
if s.repository.IsSensitiveSettingKey(key) {
|
||||
// change 是敏感设置的显式三态命令。
|
||||
change := SecretChange{Action: action, Value: value}
|
||||
if !validSecretAction(change) || change.Action == "replace" && strings.TrimSpace(change.Value) == "" {
|
||||
return errors.New("敏感设置命令无效")
|
||||
}
|
||||
// err 表示敏感设置写入审计失败。
|
||||
if err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.write", Resource: "system_settings", Keys: []string{key}}); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, nil, map[string]SecretChange{key: change})
|
||||
}
|
||||
return s.repository.SetSystem(ctx, key, value)
|
||||
}
|
||||
|
||||
// ListUser 读取当前用户的全部偏好设置。
|
||||
func (s *Service) ListUser(ctx context.Context, userID int64) (map[string]string, error) {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repository.ListUser(ctx, userID)
|
||||
}
|
||||
|
||||
// GetUser 读取当前用户的一项偏好设置。
|
||||
func (s *Service) GetUser(ctx context.Context, userID int64, key string) (string, error) {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.repository.GetUser(ctx, userID, strings.TrimSpace(key))
|
||||
}
|
||||
|
||||
// SetUser 保存当前用户的一项偏好设置。
|
||||
func (s *Service) SetUser(ctx context.Context, userID int64, key, value string) error {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" || len(key) > 100 {
|
||||
return errors.New("设置键无效")
|
||||
}
|
||||
return s.repository.SetUser(ctx, userID, key, value)
|
||||
}
|
||||
|
||||
// ListAIReply 查询当前用户账号的 AI 设置摘要。
|
||||
func (s *Service) ListAIReply(ctx context.Context, userID int64) ([]AIReplySettings, error) {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.repository.ListAIReply(ctx, userID)
|
||||
}
|
||||
|
||||
// GetAIReply 查询账号 AI 设置,并区分账号不存在和未配置设置。
|
||||
func (s *Service) GetAIReply(ctx context.Context, userID int64, cookieID string) (AIReplySettings, error) {
|
||||
// err 表示账号归属校验失败。
|
||||
if err := s.ensureOwned(ctx, userID, cookieID); err != nil {
|
||||
return AIReplySettings{}, err
|
||||
}
|
||||
return s.repository.GetAIReply(ctx, userID, strings.TrimSpace(cookieID))
|
||||
}
|
||||
|
||||
// UpsertAIReply 校验账号归属和数值边界后保存 AI 设置。
|
||||
func (s *Service) UpsertAIReply(ctx context.Context, userID int64, cookieID string, settings AIReplySettings) error {
|
||||
// err 表示账号归属校验失败。
|
||||
if err := s.ensureOwned(ctx, userID, cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
if settings.MaxDiscountPercent < 0 || settings.MaxDiscountPercent > 100 {
|
||||
return errors.New("最大折扣比例必须在 0 到 100 之间")
|
||||
}
|
||||
if settings.MaxDiscountAmount < 0 {
|
||||
return errors.New("最大折扣金额不能小于 0")
|
||||
}
|
||||
if settings.MaxBargainRounds < 1 || settings.MaxBargainRounds > 10 {
|
||||
return errors.New("最大砍价轮次必须在 1 到 10 之间")
|
||||
}
|
||||
settings.CookieID = strings.TrimSpace(cookieID)
|
||||
return s.repository.UpsertAIReply(ctx, settings.CookieID, settings)
|
||||
}
|
||||
|
||||
// ListAIModels 读取远端模型目录,API 密钥使用前必须经过受控读取或审计。
|
||||
func (s *Service) ListAIModels(ctx context.Context, userID int64, baseURL, apiKey string) ([]string, error) {
|
||||
// err 表示设置 Port 未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.modelClient == nil {
|
||||
return nil, errors.New("AI 模型客户端未初始化")
|
||||
}
|
||||
baseURL = strings.TrimSpace(baseURL)
|
||||
if baseURL == "" {
|
||||
// err 表示系统 AI 地址读取失败。
|
||||
var err error
|
||||
baseURL, err = s.repository.GetSystem(ctx, "ai_api_url")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if baseURL == "" {
|
||||
baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
|
||||
}
|
||||
apiKey = strings.TrimSpace(apiKey)
|
||||
if apiKey == "" {
|
||||
// err 表示敏感 API 密钥读取或审计失败。
|
||||
var err error
|
||||
apiKey, err = s.repository.ReadSensitiveSystem(ctx, userID, "ai_api_key", "settings.use", "ai_models")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if // err 表示外部传入 API 密钥的使用审计失败。
|
||||
err := s.audit(ctx, AuditRecord{UserID: userID, Action: "settings.use", Resource: "ai_models", Keys: []string{"ai_api_key"}}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.modelClient.Fetch(ctx, baseURL, apiKey)
|
||||
}
|
||||
|
||||
// validateRepository 检查应用服务的基础设施 Port 是否已装配。
|
||||
func (s *Service) validateRepository() error {
|
||||
if s == nil || s.repository == nil {
|
||||
return errors.New("设置 repository 未初始化")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateUser 检查设置服务及用户身份,避免无效身份进入数据库 Port。
|
||||
func (s *Service) validateUser(userID int64) error {
|
||||
// err 表示设置 Port 未装配。
|
||||
if err := s.validateRepository(); err != nil {
|
||||
return err
|
||||
}
|
||||
if userID <= 0 {
|
||||
return ErrInvalidUser
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureOwned 统一执行用户身份和非敏感账号所有权校验。
|
||||
func (s *Service) ensureOwned(ctx context.Context, userID int64, cookieID string) error {
|
||||
// err 表示设置服务未装配或用户身份无效。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
cookieID = strings.TrimSpace(cookieID)
|
||||
if cookieID == "" {
|
||||
return ErrAccountNotFound
|
||||
}
|
||||
// ownerID、err 保存非敏感账号所有者标识及查询错误。
|
||||
ownerID, err := s.repository.CheckOwnership(ctx, userID, cookieID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ownerID != userID {
|
||||
return ErrForbidden
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateValues 校验批量普通设置键值,阻止敏感值进入普通参数。
|
||||
func (s *Service) validateValues(values map[string]string) error {
|
||||
// key 是待校验的普通设置键名。
|
||||
for key := range values {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" || len(key) > 100 {
|
||||
return errors.New("设置键无效")
|
||||
}
|
||||
if s.repository.IsSensitiveSettingKey(key) {
|
||||
return errors.New("敏感设置必须放入 secrets 命令")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validSecretAction 判断敏感设置命令是否具有受支持的三态语义。
|
||||
func validSecretAction(change SecretChange) bool {
|
||||
switch change.Action {
|
||||
case "retain", "replace", "clear":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// audit 写入排序去重后的敏感设置键名,确保审计内容不包含秘密值。
|
||||
func (s *Service) audit(ctx context.Context, record AuditRecord) error {
|
||||
if len(record.Keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
// normalizedKeys 保存排序去重后的键名。
|
||||
normalizedKeys := make([]string, 0, len(record.Keys))
|
||||
// seen 保存已经加入审计记录的键名。
|
||||
seen := make(map[string]struct{}, len(record.Keys))
|
||||
// key 是当前待规范化的敏感设置键名。
|
||||
for _, key := range record.Keys {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
// exists 表示键名是否已经加入当前审计记录。
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
normalizedKeys = append(normalizedKeys, key)
|
||||
}
|
||||
sort.Strings(normalizedKeys)
|
||||
record.Keys = normalizedKeys
|
||||
if record.Outcome == "" {
|
||||
record.Outcome = "accepted"
|
||||
}
|
||||
return s.repository.AddAudit(ctx, record)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// settingsRepositoryFake 是设置应用服务测试使用的内存 Port。
|
||||
type settingsRepositoryFake struct {
|
||||
// sensitiveKeys 保存测试环境允许的敏感设置键。
|
||||
sensitiveKeys []string
|
||||
// audits 保存收到的非敏感审计记录。
|
||||
audits []AuditRecord
|
||||
// auditErr 模拟敏感审计存储故障。
|
||||
auditErr error
|
||||
// values 保存最近一次系统设置普通值。
|
||||
values map[string]string
|
||||
// secrets 保存最近一次系统设置敏感命令。
|
||||
secrets map[string]SecretChange
|
||||
// ownerID 保存账号所有者标识。
|
||||
ownerID int64
|
||||
// aiSettings 保存账号 AI 设置摘要。
|
||||
aiSettings map[string]AIReplySettings
|
||||
// systemValues 保存系统设置读取值。
|
||||
systemValues map[string]string
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断测试设置键是否属于敏感集合。
|
||||
func (r *settingsRepositoryFake) IsSensitiveSettingKey(key string) bool {
|
||||
// candidate 是测试敏感键集合中的当前候选值。
|
||||
for _, candidate := range r.sensitiveKeys {
|
||||
if candidate == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SensitiveSettingKeys 返回测试敏感设置键名。
|
||||
func (r *settingsRepositoryFake) SensitiveSettingKeys() []string {
|
||||
return append([]string(nil), r.sensitiveKeys...)
|
||||
}
|
||||
|
||||
// PublicSystem 返回测试公开设置。
|
||||
func (r *settingsRepositoryFake) PublicSystem(context.Context) (map[string]string, error) {
|
||||
return map[string]string{"theme_color": "blue"}, nil
|
||||
}
|
||||
|
||||
// RedactedSystem 返回测试脱敏设置。
|
||||
func (r *settingsRepositoryFake) RedactedSystem(context.Context) (map[string]string, error) {
|
||||
return map[string]string{"ai_api_key_configured": "true"}, nil
|
||||
}
|
||||
|
||||
// GetSystem 返回测试系统设置。
|
||||
func (r *settingsRepositoryFake) GetSystem(_ context.Context, key string) (string, error) {
|
||||
return r.systemValues[key], nil
|
||||
}
|
||||
|
||||
// ReadSensitiveSystem 返回测试敏感设置值并模拟数据库已完成审计。
|
||||
func (r *settingsRepositoryFake) ReadSensitiveSystem(_ context.Context, _ int64, _, _, _ string) (string, error) {
|
||||
return "stored-secret", nil
|
||||
}
|
||||
|
||||
// ApplySystemChanges 保存测试系统设置变更。
|
||||
func (r *settingsRepositoryFake) ApplySystemChanges(_ context.Context, values map[string]string, secrets map[string]SecretChange) error {
|
||||
r.values = values
|
||||
r.secrets = secrets
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSystem 保存测试单项系统设置。
|
||||
func (r *settingsRepositoryFake) SetSystem(_ context.Context, key, value string) error {
|
||||
if r.systemValues == nil {
|
||||
r.systemValues = make(map[string]string)
|
||||
}
|
||||
r.systemValues[key] = value
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddAudit 保存测试审计记录。
|
||||
func (r *settingsRepositoryFake) AddAudit(_ context.Context, record AuditRecord) error {
|
||||
if r.auditErr != nil {
|
||||
return r.auditErr
|
||||
}
|
||||
r.audits = append(r.audits, record)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUser 返回测试用户设置。
|
||||
func (r *settingsRepositoryFake) ListUser(context.Context, int64) (map[string]string, error) {
|
||||
return map[string]string{"theme": "dark"}, nil
|
||||
}
|
||||
|
||||
// GetUser 返回测试用户单项设置。
|
||||
func (r *settingsRepositoryFake) GetUser(context.Context, int64, string) (string, error) {
|
||||
return "dark", nil
|
||||
}
|
||||
|
||||
// SetUser 保存测试用户单项设置。
|
||||
func (r *settingsRepositoryFake) SetUser(context.Context, int64, string, string) error { return nil }
|
||||
|
||||
// CheckOwnership 返回测试账号所有者。
|
||||
func (r *settingsRepositoryFake) CheckOwnership(context.Context, int64, string) (int64, error) {
|
||||
if r.ownerID == 0 {
|
||||
return 0, ErrAccountNotFound
|
||||
}
|
||||
return r.ownerID, nil
|
||||
}
|
||||
|
||||
// ListAIReply 返回测试账号 AI 设置列表。
|
||||
func (r *settingsRepositoryFake) ListAIReply(context.Context, int64) ([]AIReplySettings, error) {
|
||||
// result 保存测试账号 AI 设置列表。
|
||||
result := make([]AIReplySettings, 0, len(r.aiSettings))
|
||||
// setting 是当前待复制的测试账号 AI 设置。
|
||||
for _, setting := range r.aiSettings {
|
||||
result = append(result, setting)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetAIReply 返回测试账号 AI 设置。
|
||||
func (r *settingsRepositoryFake) GetAIReply(_ context.Context, _ int64, cookieID string) (AIReplySettings, error) {
|
||||
// setting、ok 保存测试账号 AI 设置及是否存在。
|
||||
setting, ok := r.aiSettings[cookieID]
|
||||
if !ok {
|
||||
return AIReplySettings{}, ErrConfigNotFound
|
||||
}
|
||||
return setting, nil
|
||||
}
|
||||
|
||||
// UpsertAIReply 保存测试账号 AI 设置。
|
||||
func (r *settingsRepositoryFake) UpsertAIReply(_ context.Context, cookieID string, setting AIReplySettings) error {
|
||||
if r.aiSettings == nil {
|
||||
r.aiSettings = make(map[string]AIReplySettings)
|
||||
}
|
||||
r.aiSettings[cookieID] = setting
|
||||
return nil
|
||||
}
|
||||
|
||||
// modelClientFake 是 AI 模型客户端测试替身。
|
||||
type modelClientFake struct {
|
||||
// calls 保存收到的端点和密钥,测试只比较是否传递,不输出秘密。
|
||||
calls int
|
||||
}
|
||||
|
||||
// Fetch 返回固定模型列表并记录调用次数。
|
||||
func (c *modelClientFake) Fetch(context.Context, string, string) ([]string, error) {
|
||||
c.calls++
|
||||
return []string{"qwen-plus"}, nil
|
||||
}
|
||||
|
||||
// TestServiceApplySystemChangesAuditsSecrets 验证敏感系统设置写入先审计再进入 Port。
|
||||
func TestServiceApplySystemChangesAuditsSecrets(t *testing.T) {
|
||||
// repository 保存测试设置 Port。
|
||||
repository := &settingsRepositoryFake{sensitiveKeys: []string{"ai_api_key"}}
|
||||
// service 保存待测试的设置应用服务。
|
||||
service := NewService(repository, nil)
|
||||
// err 表示敏感系统设置写入结果。
|
||||
err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"theme_color": "blue"}, map[string]SecretChange{"ai_api_key": {Action: "replace", Value: "secret"}})
|
||||
if err != nil {
|
||||
t.Fatalf("apply settings: %v", err)
|
||||
}
|
||||
if len(repository.audits) != 1 || repository.audits[0].Action != "settings.write" || repository.audits[0].Keys[0] != "ai_api_key" {
|
||||
t.Fatalf("unexpected audit records: %+v", repository.audits)
|
||||
}
|
||||
// forwarded 表示敏感命令是否完整传递到 Port;断言失败时不输出秘密值。
|
||||
forwarded, ok := repository.secrets["ai_api_key"]
|
||||
if !ok || forwarded.Action != "replace" || forwarded.Value != "secret" {
|
||||
t.Fatalf("secret command was not forwarded: action=%q present=%t", forwarded.Action, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceRejectsSensitivePlainValue 验证敏感键不能通过普通设置值写入。
|
||||
func TestServiceRejectsSensitivePlainValue(t *testing.T) {
|
||||
// repository 保存测试设置 Port。
|
||||
repository := &settingsRepositoryFake{sensitiveKeys: []string{"ai_api_key"}}
|
||||
// service 保存待测试的设置应用服务。
|
||||
service := NewService(repository, nil)
|
||||
// err 表示错误的普通敏感值写入结果。
|
||||
err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"ai_api_key": "secret"}, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "敏感设置") {
|
||||
t.Fatalf("sensitive plain value should fail: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceAIReplyOwnershipAndValidation 验证账号 AI 设置的归属和数值约束。
|
||||
func TestServiceAIReplyOwnershipAndValidation(t *testing.T) {
|
||||
// repository 保存测试账号所有者及配置。
|
||||
repository := &settingsRepositoryFake{ownerID: 7, aiSettings: make(map[string]AIReplySettings)}
|
||||
// service 保存待测试的设置应用服务。
|
||||
service := NewService(repository, nil)
|
||||
// forbiddenErr 保存跨用户更新返回的权限错误。
|
||||
if forbiddenErr := service.UpsertAIReply(context.Background(), 8, "acc1", AIReplySettings{MaxDiscountPercent: 1, MaxDiscountAmount: 1, MaxBargainRounds: 1}); !errors.Is(forbiddenErr, ErrForbidden) {
|
||||
t.Fatalf("cross-user update error=%v", forbiddenErr)
|
||||
}
|
||||
// invalidErr 保存非法折扣边界返回的校验错误。
|
||||
if invalidErr := service.UpsertAIReply(context.Background(), 7, "acc1", AIReplySettings{MaxDiscountPercent: 101, MaxDiscountAmount: 1, MaxBargainRounds: 1}); invalidErr == nil {
|
||||
t.Fatal("invalid discount should fail")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceListAIModelsAuditsExplicitKey 验证外部传入 API 密钥也必须留下使用审计。
|
||||
func TestServiceListAIModelsAuditsExplicitKey(t *testing.T) {
|
||||
// repository 保存测试系统设置 Port。
|
||||
repository := &settingsRepositoryFake{systemValues: map[string]string{"ai_api_url": "https://example.test/v1"}}
|
||||
// client 保存模型目录测试客户端。
|
||||
client := &modelClientFake{}
|
||||
// service 保存待测试的设置应用服务。
|
||||
service := NewService(repository, client)
|
||||
// models、err 保存模型目录结果和调用错误。
|
||||
models, err := service.ListAIModels(context.Background(), 7, "https://example.test/v1", "provided-secret")
|
||||
if err != nil || len(models) != 1 || client.calls != 1 {
|
||||
t.Fatalf("models=%v err=%v calls=%d", models, err, client.calls)
|
||||
}
|
||||
if len(repository.audits) != 1 || repository.audits[0].Resource != "ai_models" {
|
||||
t.Fatalf("missing model access audit: %+v", repository.audits)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceListAIModelsFailsClosedWhenAuditUnavailable 验证模型请求不会绕过敏感密钥审计。
|
||||
func TestServiceListAIModelsFailsClosedWhenAuditUnavailable(t *testing.T) {
|
||||
// repository 保存会返回审计故障的设置 Port。
|
||||
repository := &settingsRepositoryFake{auditErr: errors.New("audit unavailable")}
|
||||
// client 保存模型目录测试客户端。
|
||||
client := &modelClientFake{}
|
||||
// service 保存待测试的设置应用服务。
|
||||
service := NewService(repository, client)
|
||||
// models、err 保存审计失败时的模型结果和错误。
|
||||
models, err := service.ListAIModels(context.Background(), 7, "https://example.test/v1", "provided-secret")
|
||||
if err == nil || models != nil || client.calls != 0 {
|
||||
t.Fatalf("audit failure should stop model request: models=%v err=%v calls=%d", models, err, client.calls)
|
||||
}
|
||||
}
|
||||
|
||||
var _ Repository = (*settingsRepositoryFake)(nil)
|
||||
var _ ModelClient = (*modelClientFake)(nil)
|
||||
Reference in new issue
Block a user