From 260a729f1a38ba9c06f5d0149fcc5f85dba7e08a Mon Sep 17 00:00:00 2001 From: Epinephrine <27862058+luvs01@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:58:12 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20AUTH=5FRECOVERY=20?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E8=AE=A4=E8=AF=81=E5=A4=B1=E6=95=88=E5=90=8E?= =?UTF-8?q?=E7=9A=84=E7=BB=AD=E7=AD=BE=E6=9D=90=E6=96=99=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 3 + README.md | 1 + README_en.md | 1 + docs/development.md | 1 + internal/api/admin.go | 1 + internal/app/admin.go | 2 + internal/app/admin_config_test.go | 65 +++++++++++++++++++ internal/app/auth_retry.go | 11 +++- internal/app/auth_retry_test.go | 103 ++++++++++++++++++++++++++++++ internal/app/lifecycle.go | 2 + internal/app/runtime.go | 2 +- internal/config/config.go | 5 ++ internal/config/env_test.go | 86 +++++++++++++++++++++++++ 13 files changed, 280 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index b6a7fe9b..fd6bb03a 100644 --- a/.env.example +++ b/.env.example @@ -63,6 +63,9 @@ ACCOUNT_ORDER= # 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,0 为不换号;额度用尽不计入 MAX_ACCOUNT_SWITCHES=3 +# 控制账户会话失效(上游 401 等)后的恢复:true 时自动读取已保存的续签材料为账户原地续签并重放请求;false 时账户直接标为需要重新登录,由人工登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行。修改后重启生成服务生效 +AUTH_RECOVERY=true + # 生成请求使用的上游通道:playground、build(旧通道,上游已停用其生成),逗号分隔 UPSTREAM_CHANNELS=playground diff --git a/README.md b/README.md index 27dcb656..6bb9c3f1 100644 --- a/README.md +++ b/README.md @@ -648,6 +648,7 @@ cp .env.example .env | `ROUTING_STRATEGY` | `round-robin` | `round-robin` 轮询;`fill-first` 账号粘性优先 | | `ACCOUNT_ORDER` | 空 | `fill-first` 依次使用的账户,逗号分隔,未列出的账户排在后面并按 ID 排序;也可在设置页调整,保存后立即生效 | | `MAX_ACCOUNT_SWITCHES` | `3` | 上游返回 403、5xx 等非额度错误时一个请求最多换几次账户重试,`0` 为不换号;额度用尽不计入,照常依次尝试其余账户 | +| `AUTH_RECOVERY` | `true` | 控制账户会话失效(上游 401 等)后的恢复:`true` 时自动读取已保存的续签材料为账户原地续签并重放请求;`false` 时账户直接标为“需要重新登录”,由人工在账户页重新登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行。修改后重启生成服务生效 | | `UPSTREAM_CHANNELS` | `playground` | 生成请求使用的上游通道,`playground`、`build` 逗号分隔;`build` 为旧通道,上游已停用其生成 | | `MODEL_MAPPING` | 空 | 客户端模型名到目录模型的映射,每项写成 `别名:模型 ID`,逗号分隔多项 | | `MODEL_CHANNELS` | 空 | 限定模型只走一个通道,每项写成 `模型 ID:playground` 或 `模型 ID:build`;也可在“模型目录”的模型详情中选择,保存后立即生效 | diff --git a/README_en.md b/README_en.md index 3d383ffc..c2003d1c 100644 --- a/README_en.md +++ b/README_en.md @@ -648,6 +648,7 @@ Process environment variables override the same keys in `.env`, and those settin | `ROUTING_STRATEGY` | `round-robin` | `round-robin` rotates accounts; `fill-first` reuses the first available account | | `ACCOUNT_ORDER` | empty | Accounts `fill-first` uses in order, comma-separated; unlisted accounts follow in ID order. Also adjustable on the Settings page, applied on save | | `MAX_ACCOUNT_SWITCHES` | `3` | How many times a request moves to another account after a non-quota upstream error such as 403 or 5xx; `0` disables switching. Quota errors do not count, and the remaining accounts are still tried in turn | +| `AUTH_RECOVERY` | `true` | Controls recovery after an account session is judged expired (upstream 401 and similar): `true` renews in place from the account's saved renewal material and replays the request; `false` marks the account as sign-in required for a manual re-login on the Accounts page. Proactive DBSC refresh and manual sign-in/import follow their existing lifecycle. Applies when the generation service restarts | | `UPSTREAM_CHANNELS` | `playground` | Upstream channels for generation requests, `playground` and `build` comma separated; `build` is the legacy channel whose generation upstream has disabled | | `MODEL_MAPPING` | empty | Client model names mapped to catalog models, each item `alias:model ID`, comma separated | | `MODEL_CHANNELS` | empty | Limit a model to one channel, each item `model ID:playground` or `model ID:build`; also selectable in model details on the Model catalog page, applied on save | diff --git a/docs/development.md b/docs/development.md index 428d4f30..8b2cd886 100644 --- a/docs/development.md +++ b/docs/development.md @@ -214,6 +214,7 @@ Camoufox 由 Go 通过 WebDriver BiDi 直接管理。启动数据面时,服务 | `ROUTING_STRATEGY` | 账户轮询 `round-robin` 或粘性优先 `fill-first` | `round-robin` | | `ACCOUNT_ORDER` | 逗号分隔的账户 ID,`fill-first` 依次使用并按此顺序预热,未列出的账户排在后面并按 ID 排序;保存后立即生效 | 空 | | `MAX_ACCOUNT_SWITCHES` | 一个请求因上游 401、403、404、5xx、连接断开等非额度失败换号的次数上限,`0` 为不换号;额度失败不计入;保存后停止再启动生成服务生效 | `3` | +| `AUTH_RECOVERY` | 控制账户会话失效(上游 401 等)后的恢复:`true` 时自动读取已保存的续签材料原地续签;`false` 时账户直接标记需要重新登录,由人工登录。DBSC 会话的主动刷新与人工登录、导入按原有规则执行;修改后重启生成服务生效 | `true` | | `UPSTREAM_CHANNELS` | 生成请求的上游通道 `playground`、`build`(旧通道,上游已停用其生成),逗号分隔 | `playground` | | `MODEL_MAPPING` | 逗号分隔,每项以最后一个 `:` 分成别名与模型 ID | 空 | | `MODEL_CHANNELS` | 逗号分隔,每项以最后一个 `:` 分成模型 ID 与通道 `playground` 或 `build`;保存后立即生效 | 空 | diff --git a/internal/api/admin.go b/internal/api/admin.go index 9a6d32d1..560de827 100644 --- a/internal/api/admin.go +++ b/internal/api/admin.go @@ -289,6 +289,7 @@ type RuntimeConfig struct { AdminPassword *string `json:"admin_password,omitempty"` AdminPasswordSet bool `json:"admin_password_set"` SavedAdminPassword string `json:"-"` + SavedAuthRecovery bool `json:"-"` BuildNativeNonstream bool `json:"build_native_nonstream"` NonstreamKeepalive bool `json:"nonstream_keepalive"` FakeStream bool `json:"fake_stream"` diff --git a/internal/app/admin.go b/internal/app/admin.go index 63791a75..86f532e7 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -1158,6 +1158,7 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt RoutingStrategy: value.RoutingStrategy, AccountOrder: strings.TrimSpace(value.AccountOrder), MaxAccountSwitches: value.MaxAccountSwitches, + AuthRecovery: saved.AuthRecovery, UpstreamChannels: value.UpstreamChannels, ModelMapping: strings.TrimSpace(value.ModelMapping), ModelChannels: strings.TrimSpace(value.ModelChannels), @@ -1460,6 +1461,7 @@ func runtimeConfigDTO(cfg config.Config) api.RuntimeConfig { LogFile: cfg.LogFile, LogMaxTotalMB: cfg.LogMaxTotalMB, AdminAuthEnabled: cfg.AdminAuthEnabled, AdminUsername: cfg.AdminUsername, AdminPasswordSet: cfg.AdminPassword != "", SavedAdminPassword: cfg.AdminPassword, + SavedAuthRecovery: cfg.AuthRecovery, BuildNativeNonstream: cfg.BuildNativeNonstream, NonstreamKeepalive: cfg.NonstreamKeepalive, FakeStream: cfg.FakeStream, YouTubeLinks: cfg.YouTubeLinks, SearchModelAliases: cfg.SearchModelAliases, DiscoverHiddenModels: cfg.DiscoverHiddenModels, GoogleSearch: cfg.GoogleSearch, StripThoughtSignatures: cfg.StripThoughtSignatures, diff --git a/internal/app/admin_config_test.go b/internal/app/admin_config_test.go index fb709a3f..3ee8bcf5 100644 --- a/internal/app/admin_config_test.go +++ b/internal/app/admin_config_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "net/http" + "os" "path/filepath" "strings" "testing" @@ -72,3 +73,67 @@ func TestAdminConfig(t *testing.T) { t.Fatal(err) } } + +// TestAuthRecoveryLifecycle 核对保存与运行的 AUTH_RECOVERY 不一致的两个方向都标为需要重启,一致则不标,无关保存保留 .env 与环境变量取值 +func TestAuthRecoveryLifecycle(t *testing.T) { + path := filepath.Join(t.TempDir(), ".env") + cfg := config.Default() + cfg.AuthRecovery = false + if err := cfg.Save(path); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + pool := aistudio.NewAccountPool(nil, 1) + admin := &runtimeAdmin{configPath: path, requests: newRequestRegistry(ctx), pool: pool, service: &trackedService{pool: pool}} + manager := &runtimeManager{} + + value, err := admin.RuntimeConfig(ctx) + if err != nil { + t.Fatal(err) + } + if value.SavedAuthRecovery { + t.Fatal("SavedAuthRecovery 未载入保存值") + } + raw, err := json.Marshal(value) + if err != nil || strings.Contains(string(raw), "saved_auth_recovery") { + t.Fatalf("保存值泄漏到前端配置: %s", raw) + } + + active := config.Default() + if decorated := manager.decorateRuntimeConfig(value, active); !decorated.ServiceRestartRequired { + t.Fatal("保存 false、运行 true 未标为需要重启") + } + active.AuthRecovery = false + if decorated := manager.decorateRuntimeConfig(value, active); decorated.ServiceRestartRequired { + t.Fatal("保存与运行一致仍标为需要重启") + } + + t.Setenv("AUTH_RECOVERY", "true") + value, err = admin.RuntimeConfig(ctx) + if err != nil { + t.Fatal(err) + } + if !value.SavedAuthRecovery { + t.Fatal("环境变量决定的 AUTH_RECOVERY 未进入重启判定") + } + if decorated := manager.decorateRuntimeConfig(value, active); !decorated.ServiceRestartRequired { + t.Fatal("环境变量 true、运行 false 未标为需要重启") + } + value.AutoStart = true + updated, err := admin.UpdateRuntimeConfig(ctx, value) + if err != nil { + t.Fatal(err) + } + if !updated.SavedAuthRecovery { + t.Fatal("无关保存丢失了环境变量决定的 AUTH_RECOVERY") + } + saved, err := config.Load(path) + if err != nil || !saved.AuthRecovery { + t.Fatalf("保存值被改写: %+v err=%v", saved, err) + } + content, err := os.ReadFile(path) + if err != nil || !strings.Contains(string(content), "AUTH_RECOVERY=false") { + t.Fatalf(".env 原值被改写: %s err=%v", content, err) + } +} diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go index 05c5e859..2c0f97aa 100644 --- a/internal/app/auth_retry.go +++ b/internal/app/auth_retry.go @@ -37,6 +37,8 @@ type authRuntimeRefresher struct { boundLocks sync.Map globalProxy string requests *requestRegistry + // authRecovery 为 false 时账户认证失败不读取续签材料,直接标记需要重新登录 + authRecovery bool } // authRetryTransport 为普通 RPC 执行一次认证续签重试 @@ -156,14 +158,16 @@ func newAuthRuntimeRefresher( workers *accountWorkerManager, requests *requestRegistry, globalProxy string, + authRecovery bool, ) *authRuntimeRefresher { return &authRuntimeRefresher{ pool: workers.pool, refresh: chromeauth.Refresh, importCurrent: importCurrentChromeState, chromeHas: chromeIdentityImportable, reset: workers.Reset, prepareWorker: workers.prepareUpdate, rotate: chromeauth.RotateBoundCookies, mergeWorker: workers.MergeCookies, - globalProxy: globalProxy, - requests: requests, + globalProxy: globalProxy, + requests: requests, + authRecovery: authRecovery, } } @@ -249,6 +253,9 @@ func (refresher *authRuntimeRefresher) Recover(ctx context.Context, cause error, if errors.As(cause, &startup) && startup.authHandled { return cause } + if !refresher.authRecovery { + return refresher.markAuthenticationRequired(ctx, cause) + } if refresher.Available(ctx) { if err := refresher.Refresh(ctx, generation); err == nil { return nil diff --git a/internal/app/auth_retry_test.go b/internal/app/auth_retry_test.go index 610ada1e..ceb3bb6a 100644 --- a/internal/app/auth_retry_test.go +++ b/internal/app/auth_retry_test.go @@ -2,11 +2,14 @@ package app import ( "context" + "errors" + "fmt" "os" "path/filepath" "testing" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" ) // TestAuthRefreshWithoutExtension 验证缺少续签扩展的账户从当前 Chrome 导入同一邮箱并写回扩展,重新登录保留扩展 @@ -73,3 +76,103 @@ func TestAuthRefreshWithoutExtension(t *testing.T) { t.Fatalf("重新登录丢失续签扩展: %+v", kept) } } + +// newAuthRecoveryFixture 创建有一个账户、已注入账户租约上下文的续签测试环境 +func newAuthRecoveryFixture(t *testing.T) (*aistudio.Account, *aistudio.AccountLease, *aistudio.AccountPool, context.Context) { + t.Helper() + directory := t.TempDir() + storage := filepath.Join(directory, "storage-state.json") + state := `{"cookies":[{"name":"SAPISID","value":"old","domain":".google.com","path":"/","secure":true,"sameSite":"Lax"}],"origins":[]}` + if err := os.WriteFile(storage, []byte(state), 0o600); err != nil { + t.Fatal(err) + } + loaded, err := aistudio.LoadStorageState(storage) + if err != nil { + t.Fatal(err) + } + account := &aistudio.Account{ + ID: "user@example.com", Directory: directory, StoragePath: storage, + RuntimePath: filepath.Join(directory, "runtime-state.json"), StorageState: loaded, + Config: aistudio.DefaultAccountConfig("user@example.com"), + } + pool := aistudio.NewAccountPool([]*aistudio.Account{account}, 1) + lease, err := pool.AcquireAccount(t.Context(), account.ID) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { lease.Release() }) + return account, lease, pool, aistudio.ContextWithAccountLease(t.Context(), lease) +} + +// TestAuthRecoveryDisabledMarksRequired 验证关闭续签时认证失败不读取续签材料,账户仍按官网确认的结果标记为需要重新登录 +func TestAuthRecoveryDisabledMarksRequired(t *testing.T) { + account, lease, pool, ctx := newAuthRecoveryFixture(t) + used := false + refresher := &authRuntimeRefresher{ + pool: pool, requests: newRequestRegistry(t.Context()), authRecovery: false, + refresh: func(context.Context, aistudio.AuthSource, aistudio.ChromeOAuthMaterial, string) ([]aistudio.StateCookie, *aistudio.BoundSession, error) { + used = true + return nil, nil, nil + }, + importCurrent: func(context.Context, aistudio.AuthSource, *aistudio.ChromeOAuthMaterial, string) (aistudio.StorageState, error) { + used = true + return aistudio.StorageState{}, nil + }, + chromeHas: func(email string) bool { return email == account.ID }, + reset: func(string) error { return nil }, + } + if !refresher.Available(ctx) { + t.Fatal("账户在 Chrome 中登录但被判定为不可续签") + } + cause := fmt.Errorf("%w: test", camoufoxnative.ErrAuthenticationRequired) + err := refresher.Recover(ctx, cause, lease.AuthGeneration()) + if err == nil || !errors.Is(err, camoufoxnative.ErrAuthenticationRequired) { + t.Fatalf("Recover err = %v", err) + } + if used { + t.Fatal("关闭续签后仍读取了续签材料") + } + if account.State != aistudio.AccountAuthRequired { + t.Fatalf("account.State = %v", account.State) + } +} + +// TestAuthRecoveryEnabledRenews 验证默认开启续签时认证失败按账户保存的材料原地续签 +func TestAuthRecoveryEnabledRenews(t *testing.T) { + account, lease, pool, ctx := newAuthRecoveryFixture(t) + var cookies []aistudio.StateCookie + for _, name := range []string{"SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID"} { + cookies = append(cookies, aistudio.StateCookie{Name: name, Value: "renewed", Domain: ".google.com", Path: "/", Expires: -1, Secure: true, SameSite: "Lax"}) + } + imported := false + refresher := &authRuntimeRefresher{ + pool: pool, requests: newRequestRegistry(t.Context()), authRecovery: true, + refresh: func(context.Context, aistudio.AuthSource, aistudio.ChromeOAuthMaterial, string) ([]aistudio.StateCookie, *aistudio.BoundSession, error) { + return nil, nil, fmt.Errorf("没有 OAuth 材料时不应调用 refresh") + }, + importCurrent: func(_ context.Context, source aistudio.AuthSource, _ *aistudio.ChromeOAuthMaterial, _ string) (aistudio.StorageState, error) { + imported = true + updated := aistudio.StorageState{Cookies: cookies} + updated.SetAuthExtension(aistudio.AuthExtension{ + Source: source, OAuth: &aistudio.ChromeOAuthMaterial{GaiaID: "gaia", RefreshToken: "token"}, + }) + return updated, nil + }, + chromeHas: func(email string) bool { return email == account.ID }, + reset: func(string) error { return nil }, + } + cause := fmt.Errorf("%w: test", camoufoxnative.ErrAuthenticationRequired) + if err := refresher.Recover(ctx, cause, lease.AuthGeneration()); err != nil { + t.Fatal(err) + } + if !imported { + t.Fatal("开启续签时认证失败没有读取续签材料") + } + stored, err := aistudio.LoadStorageState(account.StoragePath) + if err != nil { + t.Fatal(err) + } + if len(stored.Cookies) == 0 || stored.Cookies[0].Value != "renewed" { + t.Fatalf("续签结果 cookies = %+v", stored.Cookies) + } +} diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 8902f752..50f06c0b 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -723,6 +723,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat UpstreamChannels: value.UpstreamChannels, ModelMapping: value.ModelMapping, MaxAccountSwitches: value.MaxAccountSwitches, + AuthRecovery: value.SavedAuthRecovery, WAABackend: value.WAABackend, BuildNativeNonstream: value.BuildNativeNonstream, NonstreamKeepalive: value.NonstreamKeepalive, @@ -743,6 +744,7 @@ func sameDataConfig(value api.RuntimeConfig, active config.Config, overrides dat saved.InitTimeout == active.InitTimeout && saved.RequestTimeout == active.RequestTimeout && slices.Equal(saved.UpstreamChannels, active.UpstreamChannels) && saved.ModelMapping == active.ModelMapping && saved.MaxAccountSwitches == active.MaxAccountSwitches && + saved.AuthRecovery == active.AuthRecovery && saved.WAABackend == active.WAABackend && saved.BuildNativeNonstream == active.BuildNativeNonstream && saved.NonstreamKeepalive == active.NonstreamKeepalive && saved.FakeStream == active.FakeStream && diff --git a/internal/app/runtime.go b/internal/app/runtime.go index a05b7291..88c885f5 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -89,7 +89,7 @@ func newRuntime( protected := aistudio.NewWorkerProtectedTransport(aistudio.WorkerProtectedTransportOptions{ Transport: transport, Workers: workers, SetupTimeout: cfg.InitTimeout, }) - refresher := newAuthRuntimeRefresher(workers, requests, globalProxy) + refresher := newAuthRuntimeRefresher(workers, requests, globalProxy, cfg.AuthRecovery) workers.refresher = refresher client := aistudio.NewClient(aistudio.ClientOptions{ Transport: &authRetryTransport{transport: transport, refresher: refresher}, diff --git a/internal/config/config.go b/internal/config/config.go index ba46c0bd..750f0882 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -44,6 +44,7 @@ var configKeys = [...]string{ "ROUTING_STRATEGY", "ACCOUNT_ORDER", "MAX_ACCOUNT_SWITCHES", + "AUTH_RECOVERY", "UPSTREAM_CHANNELS", "MODEL_MAPPING", "MODEL_CHANNELS", @@ -146,6 +147,7 @@ type Config struct { RoutingStrategy string AccountOrder string MaxAccountSwitches int + AuthRecovery bool UpstreamChannels []string ModelMapping string ModelChannels string @@ -195,6 +197,7 @@ func Default() Config { PerAccountConcurrency: defaultAccountConcurrency, RoutingStrategy: "round-robin", MaxAccountSwitches: DefaultMaxAccountSwitches, + AuthRecovery: true, UpstreamChannels: []string{"playground"}, WAABackend: WAABackendSpiderMonkey, MediaOutput: MediaOutputInline, @@ -241,6 +244,7 @@ var configSetters = map[string]func(*Config, string) error{ "WARM_STARTUP_CONCURRENCY": intSetter("WARM_STARTUP_CONCURRENCY", func(c *Config) *int { return &c.WarmStartupConcurrency }), "PER_ACCOUNT_CONCURRENCY": intSetter("PER_ACCOUNT_CONCURRENCY", func(c *Config) *int { return &c.PerAccountConcurrency }), "MAX_ACCOUNT_SWITCHES": setMaxAccountSwitches, + "AUTH_RECOVERY": boolSetter("AUTH_RECOVERY", func(c *Config) *bool { return &c.AuthRecovery }), "INIT_TIMEOUT": durationSetter("INIT_TIMEOUT", func(c *Config) *time.Duration { return &c.InitTimeout }), "REQUEST_TIMEOUT": durationSetter("REQUEST_TIMEOUT", func(c *Config) *time.Duration { return &c.RequestTimeout }), "ADMIN_USERNAME": textSetter(func(c *Config) *string { return &c.AdminUsername }, strings.TrimSpace), @@ -626,6 +630,7 @@ func (c Config) envValues() map[string]string { "ROUTING_STRATEGY": c.RoutingStrategy, "ACCOUNT_ORDER": c.AccountOrder, "MAX_ACCOUNT_SWITCHES": strconv.Itoa(c.MaxAccountSwitches), + "AUTH_RECOVERY": strconv.FormatBool(c.AuthRecovery), "UPSTREAM_CHANNELS": strings.Join(c.UpstreamChannels, ","), "MODEL_MAPPING": c.ModelMapping, "MODEL_CHANNELS": c.ModelChannels, diff --git a/internal/config/env_test.go b/internal/config/env_test.go index b7a1e511..6c59d531 100644 --- a/internal/config/env_test.go +++ b/internal/config/env_test.go @@ -151,3 +151,89 @@ func TestEnvKeepEnvironmentKeepsInvalid(t *testing.T) { t.Fatalf("保存后无效记录=%v 媒体输出=%q", kept.Invalid, kept.MediaOutput) } } + +// TestAuthRecoveryEnvRoundTrip 核对 AUTH_RECOVERY 从 .env 读取、非默认值保存时写回 +func TestAuthRecoveryEnvRoundTrip(t *testing.T) { + path := writeTestEnv(t, "AUTH_RECOVERY=false\n") + cfg, err := Load(path) + if err != nil || cfg.AuthRecovery { + t.Fatalf("loaded AuthRecovery=%t err=%v", cfg.AuthRecovery, err) + } + if err := cfg.Save(path); err != nil { + t.Fatal(err) + } + if got := readTestEnv(t, path); got != "AUTH_RECOVERY=false\nWAA_BACKEND=spidermonkey\n" { + t.Fatalf(".env = %q", got) + } + loaded, err := Load(path) + if err != nil || loaded.AuthRecovery { + t.Fatalf("reload AuthRecovery=%t err=%v", loaded.AuthRecovery, err) + } +} + +// TestAuthRecoveryInvalidValue 核对 AUTH_RECOVERY 取值无效时按默认值 true 加载并记录 +func TestAuthRecoveryInvalidValue(t *testing.T) { + path := writeTestEnv(t, "AUTH_RECOVERY=off\n") + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if !cfg.AuthRecovery { + t.Fatalf("AuthRecovery = %t", cfg.AuthRecovery) + } + if len(cfg.Invalid) != 1 || cfg.Invalid[0].Key != "AUTH_RECOVERY" { + t.Fatalf("invalid = %+v", cfg.Invalid) + } +} + +// TestAuthRecoveryAdminSaveRoundTrip 核对管理端按 UpdateRuntimeConfig 相同方式重建配置时 AUTH_RECOVERY 的表现: +// DTO 未覆盖该键,由 saved 补齐。.env 中 false 经无关设置保存仍写回 false; +// 仅进程环境变量 false 且 .env 未写该键时,保存不把环境值写入文件,环境变量仍决定取值 +func TestAuthRecoveryAdminSaveRoundTrip(t *testing.T) { + t.Run("file false", func(t *testing.T) { + path := writeTestEnv(t, "AUTH_RECOVERY=false\n") + saved, err := Load(path) + if err != nil || saved.AuthRecovery { + t.Fatalf("saved = %+v, err = %v", saved, err) + } + // admin.go UpdateRuntimeConfig: 重建配置带 saved.AuthRecovery 后再 KeepEnvironment + update := Default() + update.AuthRecovery = saved.AuthRecovery + update.RequestBodyLog = true + update = update.KeepEnvironment(saved) + if update.AuthRecovery { + t.Fatalf("重建后 AuthRecovery = %t", update.AuthRecovery) + } + if err := update.Save(path); err != nil { + t.Fatal(err) + } + if got := readTestEnv(t, path); !strings.Contains(got, "AUTH_RECOVERY=false") { + t.Fatalf(".env = %q", got) + } + if loaded, err := Load(path); err != nil || loaded.AuthRecovery { + t.Fatalf("reload AuthRecovery = %t, err = %v", loaded.AuthRecovery, err) + } + }) + + t.Run("env only false", func(t *testing.T) { + t.Setenv("AUTH_RECOVERY", "false") + path := writeTestEnv(t, "") + saved, err := Load(path) + if err != nil || saved.AuthRecovery || !slices.Contains(saved.Environment, "AUTH_RECOVERY") { + t.Fatalf("saved = %+v, err = %v", saved, err) + } + update := Default() + update.AuthRecovery = saved.AuthRecovery + update.RequestBodyLog = true + update = update.KeepEnvironment(saved) + if update.AuthRecovery { + t.Fatalf("重建后 AuthRecovery = %t", update.AuthRecovery) + } + if err := update.Save(path); err != nil { + t.Fatal(err) + } + if got := readTestEnv(t, path); strings.Contains(got, "AUTH_RECOVERY") { + t.Fatalf("仅环境变量决定的键被写入 .env: %q", got) + } + }) +}