account_credentials_persistence.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package service
  2. import (
  3. "context"
  4. "log/slog"
  5. )
  6. type accountCredentialsUpdater interface {
  7. UpdateCredentials(ctx context.Context, id int64, credentials map[string]any) error
  8. }
  9. func persistAccountCredentials(ctx context.Context, repo AccountRepository, account *Account, credentials map[string]any) error {
  10. if repo == nil || account == nil {
  11. return nil
  12. }
  13. // 安全不变量:spark 影子账号恒不持凭据(凭据透传母账号)。这是凭据写入的唯一汇聚点
  14. // (token 刷新 / 订阅补全 / CRS 创建后刷新等全部经此),在此对影子早返 no-op 是
  15. // defense-in-depth——即便某条上游路径漏判,也不会把凭据落到影子行(外审第6轮 P1)。
  16. if account.IsCredentialShadow() {
  17. slog.Warn("skip persisting credentials to spark shadow account",
  18. "account_id", account.ID, "parent_id", *account.ParentAccountID)
  19. return nil
  20. }
  21. account.Credentials = shallowCopyMap(credentials)
  22. if updater, ok := any(repo).(accountCredentialsUpdater); ok {
  23. return updater.UpdateCredentials(ctx, account.ID, account.Credentials)
  24. }
  25. return repo.Update(ctx, account)
  26. }
  27. // sparkShadowAllowedCredentialKeys 是 spark 影子账号唯一可写的凭据键集合(仅模型映射)。
  28. // 校验(isAllowed)与 sanitize 共用此单一来源,避免两处独立硬编码列表漂移。
  29. var sparkShadowAllowedCredentialKeys = map[string]struct{}{
  30. "model_mapping": {},
  31. "compact_model_mapping": {},
  32. }
  33. func isAllowedSparkShadowCredentialsUpdate(credentials map[string]any) bool {
  34. if credentials == nil {
  35. return true
  36. }
  37. for key := range credentials {
  38. if _, ok := sparkShadowAllowedCredentialKeys[key]; !ok {
  39. return false
  40. }
  41. }
  42. return true
  43. }
  44. func sanitizeSparkShadowCredentials(credentials map[string]any) map[string]any {
  45. if len(credentials) == 0 {
  46. return map[string]any{}
  47. }
  48. out := make(map[string]any, len(sparkShadowAllowedCredentialKeys))
  49. for key := range sparkShadowAllowedCredentialKeys {
  50. if value, ok := credentials[key]; ok && value != nil {
  51. out[key] = value
  52. }
  53. }
  54. return out
  55. }