From 1424cea3a9da19045e90138fac40b78c381f0cee Mon Sep 17 00:00:00 2001 From: Zyy Date: Wed, 14 Oct 2026 22:02:54 +0800 Subject: [PATCH] feat(proxies): add enablement and automatic account unbinding Preserve proxy configuration and account bindings while disabled and route subsequent account requests directly. Restore the proxy when enabled. Automatically unbind accounts on deletion in one transaction. Add the status column, action menu, and disable/delete confirmation messages. Refs #416 Co-authored-by: Codex --- .../gateway-admin/src/model/accounts.rs | 11 + .../crates/gateway-admin/src/model/proxies.rs | 2 + .../src/use_case/credential_mutation.rs | 6 +- .../src/use_case/plugins/distribution.rs | 3 + .../gateway-admin/tests/use_case/accounts.rs | 1 + .../tests/use_case/plugins/distribution.rs | 33 +++ .../gateway-admin/tests/use_case/proxies.rs | 1 + .../crates/gateway-api/src/admin/proxies.rs | 4 + .../tests/admin/accounts/handlers.rs | 1 + .../crates/gateway-api/tests/admin/errors.rs | 1 + .../crates/gateway-api/tests/admin/proxies.rs | 41 +++ .../runtime/tests/generation/data.rs | 1 + .../src/postgres/account_groups.rs | 2 +- .../provider_accounts/admin_queries.rs | 2 +- .../src/postgres/provider_accounts/mapping.rs | 1 + .../postgres/provider_accounts/repository.rs | 8 +- .../src/postgres/provider_accounts/rows.rs | 20 +- .../gateway-store/src/postgres/proxies.rs | 57 +++- .../tests/postgres/plugins/sources.rs | 45 ++- .../tests/postgres/provider_accounts/mod.rs | 1 + .../gateway-store/tests/postgres/proxies.rs | 263 ++++++++++++++++-- .../crates/providers/openai/tests/admin.rs | 1 + backend/crates/providers/xai/tests/admin.rs | 1 + backend/migrations/.frozen-sha256 | 1 + .../0031_outbound_proxy_enabled.sql | 2 + docs/api.md | 12 +- docs/architecture.md | 9 +- frontend/src/api/modules/proxies.ts | 3 +- .../accounts/components/AccountProxyField.vue | 3 +- .../components/PluginSourceProxyField.vue | 3 +- .../views/proxies/components/ProxyActions.vue | 52 ++++ .../views/proxies/composables/useProxies.ts | 42 +++ frontend/src/views/proxies/constants.ts | 1 + frontend/src/views/proxies/index.vue | 41 ++- 34 files changed, 614 insertions(+), 61 deletions(-) create mode 100644 backend/migrations/0031_outbound_proxy_enabled.sql create mode 100644 frontend/src/views/proxies/components/ProxyActions.vue diff --git a/backend/crates/gateway-admin/src/model/accounts.rs b/backend/crates/gateway-admin/src/model/accounts.rs index 814c9a8c8..4006ec5d4 100644 --- a/backend/crates/gateway-admin/src/model/accounts.rs +++ b/backend/crates/gateway-admin/src/model/accounts.rs @@ -124,6 +124,7 @@ pub struct AccountRecord { pub weight: AccountWeight, pub model_access: gateway_core::account::AccountModelAccess, pub outbound_proxy: Option, + pub outbound_proxy_enabled: bool, pub credential_state: CredentialState, pub credential_observed_at: DateTime, pub quota: QuotaState, @@ -133,6 +134,16 @@ pub struct AccountRecord { pub updated_at: DateTime, } +impl AccountRecord { + /// 配置保留绑定,执行请求时禁用代理按直连处理 + #[must_use] + pub fn effective_outbound_proxy(&self) -> Option<&gateway_core::account::OutboundProxy> { + self.outbound_proxy + .as_ref() + .filter(|_| self.outbound_proxy_enabled) + } +} + pub use super::observability::{ AccountModelUsage, AccountPoolMetrics as AccountSummary, AccountRequestBucket, CurrencyCost as AccountCost, diff --git a/backend/crates/gateway-admin/src/model/proxies.rs b/backend/crates/gateway-admin/src/model/proxies.rs index d2be116f2..5d5943037 100644 --- a/backend/crates/gateway-admin/src/model/proxies.rs +++ b/backend/crates/gateway-admin/src/model/proxies.rs @@ -69,6 +69,7 @@ pub struct ProxyTestResult { #[derive(Debug, Clone)] pub struct ProxyRecord { + pub enabled: bool, pub auto_location: bool, pub detected_location: Option, pub location: Option, @@ -103,6 +104,7 @@ pub struct NewProxy { #[derive(Debug, Clone)] pub struct UpdateProxy { + pub enabled: Option, pub auto_location: Option, pub test: Option, /// 外层为空保留配置,内层为空恢复全局继承 diff --git a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs index d5cc1d816..fcdc2833a 100644 --- a/backend/crates/gateway-admin/src/use_case/credential_mutation.rs +++ b/backend/crates/gateway-admin/src/use_case/credential_mutation.rs @@ -106,7 +106,8 @@ pub(super) async fn pending_authorization( proxy = required_credential(accounts, provider_kind, account_id, resource) .await? .credential - .outbound_proxy; + .effective_outbound_proxy() + .cloned(); AuthorizationMutationTarget::Reauthorize { account_id: account_id.clone(), } @@ -121,6 +122,9 @@ pub(super) async fn pending_authorization( .await .map_err(|error| map_store_error(error, "proxy"))?; proxy_id = Some(record.id); + if !record.enabled { + return Err(AdminError::invalid("代理已禁用,请启用后再选择")); + } Some(record.proxy) } Some(AccountProxySelection::Direct) | None => None, diff --git a/backend/crates/gateway-admin/src/use_case/plugins/distribution.rs b/backend/crates/gateway-admin/src/use_case/plugins/distribution.rs index 66495510d..c5dee471e 100644 --- a/backend/crates/gateway-admin/src/use_case/plugins/distribution.rs +++ b/backend/crates/gateway-admin/src/use_case/plugins/distribution.rs @@ -305,6 +305,9 @@ impl PluginsService { .get(id) .await .map_err(|error| map_store_error(error, "proxy"))?; + if !record.enabled { + return Err(AdminError::invalid("下载代理已禁用,请启用或改为直连")); + } Ok(Some(PluginDistributionEgress::new( record.id, record.revision, diff --git a/backend/crates/gateway-admin/tests/use_case/accounts.rs b/backend/crates/gateway-admin/tests/use_case/accounts.rs index f60e5d5c7..1dc6decf1 100644 --- a/backend/crates/gateway-admin/tests/use_case/accounts.rs +++ b/backend/crates/gateway-admin/tests/use_case/accounts.rs @@ -3137,6 +3137,7 @@ fn quota_local_usage(account_id: &str, total_tokens: u64) -> AccountUsage { pub(super) fn account_record(kind: &str) -> AccountRecord { let now = Utc::now(); AccountRecord { + outbound_proxy_enabled: true, notes: None, model_access: Default::default(), outbound_proxy: None, diff --git a/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs b/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs index 05b8ef9fc..28777fbd8 100644 --- a/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs +++ b/backend/crates/gateway-admin/tests/use_case/plugins/distribution.rs @@ -534,6 +534,7 @@ fn preview_fixture() -> Fixture { fn source_proxy() -> ProxyRecord { let now = chrono::Utc::now(); ProxyRecord { + enabled: true, auto_location: false, detected_location: None, location: None, @@ -608,6 +609,38 @@ async fn saved_source_proxy_is_resolved_for_queries_and_frozen_into_verified_sou ); } +#[tokio::test] +async fn disabled_source_proxy_rejects_queries_and_downloads_before_network_access() { + let mut fixture = preview_fixture(); + fixture.binding.get_mut().unwrap().outbound_proxy_id = Some("source-proxy".into()); + let mut proxy = source_proxy(); + proxy.enabled = false; + *fixture.proxy.get_mut().unwrap() = Some(proxy); + let fixture = Arc::new(fixture); + assert_eq!( + fixture + .service() + .check_update("test.example", &[]) + .await + .unwrap_err() + .kind(), + AdminErrorKind::Invalid + ); + let mut request = preview_request(); + request.outbound_proxy_id = Some("source-proxy".into()); + assert_eq!( + fixture + .service() + .verify_remote(request) + .await + .unwrap_err() + .kind(), + AdminErrorKind::Invalid + ); + assert!(fixture.egresses.lock().unwrap().is_empty()); + assert_eq!(*fixture.downloads.lock().unwrap(), 0); +} + #[tokio::test] async fn proxy_revision_change_during_download_rejects_the_verified_candidate() { let mut fixture = preview_fixture(); diff --git a/backend/crates/gateway-admin/tests/use_case/proxies.rs b/backend/crates/gateway-admin/tests/use_case/proxies.rs index 8f08ace1e..9438977f7 100644 --- a/backend/crates/gateway-admin/tests/use_case/proxies.rs +++ b/backend/crates/gateway-admin/tests/use_case/proxies.rs @@ -126,6 +126,7 @@ async fn authorization_uses_selected_proxy_regardless_of_probe_status() { .accounts(FakeAccountStore::new(kind, events.clone())) .proxies(Arc::new(TestProxies { record: Some(ProxyRecord { + enabled: true, auto_location: false, detected_location: None, location: None, diff --git a/backend/crates/gateway-api/src/admin/proxies.rs b/backend/crates/gateway-api/src/admin/proxies.rs index c3948decd..b256b8757 100644 --- a/backend/crates/gateway-api/src/admin/proxies.rs +++ b/backend/crates/gateway-api/src/admin/proxies.rs @@ -60,6 +60,7 @@ struct CreateRequest { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct UpdateRequest { + enabled: Option, auto_location: Option, #[serde(default, deserialize_with = "deserialize_location_update")] location: Option>, @@ -145,6 +146,7 @@ struct ProxyAccountView { #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ProxyView { + enabled: bool, auto_location: bool, detected_location: Option, location: Option, @@ -168,6 +170,7 @@ impl From<(ProxyRecord, crate::time::TimePresenter)> for ProxyView { let endpoint = record.proxy.endpoint(); Self { auto_location: record.auto_location, + enabled: record.enabled, detected_location: record.detected_location, location: record.location, id: record.id, @@ -419,6 +422,7 @@ where .proxies() .update( UpdateProxy { + enabled: request.enabled, auto_location: request.auto_location, test: None, location: request.location, diff --git a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs index 5530af702..cb2fd1c4e 100644 --- a/backend/crates/gateway-api/tests/admin/accounts/handlers.rs +++ b/backend/crates/gateway-api/tests/admin/accounts/handlers.rs @@ -112,6 +112,7 @@ fn account_page_item( AccountPageItem { account: AccountRecord { + outbound_proxy_enabled: true, id: "acct_cooldown".to_owned(), provider_kind: gateway_core::routing::ProviderKind::new("openai").unwrap(), groups: Vec::new(), diff --git a/backend/crates/gateway-api/tests/admin/errors.rs b/backend/crates/gateway-api/tests/admin/errors.rs index c326d4d31..e610533c9 100644 --- a/backend/crates/gateway-api/tests/admin/errors.rs +++ b/backend/crates/gateway-api/tests/admin/errors.rs @@ -511,6 +511,7 @@ mod provider { total_slots: None, }, account: AccountRecord { + outbound_proxy_enabled: true, notes: None, model_access: Default::default(), id: "acct_error_test".to_owned(), diff --git a/backend/crates/gateway-api/tests/admin/proxies.rs b/backend/crates/gateway-api/tests/admin/proxies.rs index 11892ef69..8462059ba 100644 --- a/backend/crates/gateway-api/tests/admin/proxies.rs +++ b/backend/crates/gateway-api/tests/admin/proxies.rs @@ -89,6 +89,43 @@ async fn proxy_location_rejects_invalid_and_incomplete_input() { #[derive(Default)] pub(super) struct MemoryProxies(Mutex>); +#[tokio::test] +async fn proxy_enabled_updates_preserve_connection_and_omitted_state() { + let fixture = AdminTestFixture::new().await; + fixture.auth.insert_session("valid-session"); + let (status, created) = request( + &fixture, + "/api/admin/proxies/create", + Some(json!({ + "name":"Office", "proxyUrl":"http://proxy.example:8080" + })), + true, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(created["data"]["record"]["enabled"], true); + for (revision, enabled, expected) in [ + (1, Some(false), false), + (2, None, false), + (3, Some(true), true), + ] { + let mut body = json!({"id":"proxy_test", "revision":revision, "name":"Office"}); + if let Some(enabled) = enabled { + body["enabled"] = json!(enabled); + } + let (status, changed) = + request(&fixture, "/api/admin/proxies/update", Some(body), true).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(changed["data"]["record"]["enabled"], expected); + assert_eq!( + changed["data"]["record"]["endpoint"], + created["data"]["record"]["endpoint"] + ); + let (_, listed) = request(&fixture, "/api/admin/proxies", None, true).await; + assert_eq!(listed["data"]["items"][0]["enabled"], expected); + } +} + fn missing() -> AdminStoreError { AdminStoreError::new(AdminStoreErrorKind::NotFound, "proxy", "missing proxy") } @@ -165,6 +202,7 @@ impl ProxyStore for MemoryProxies { _: &MutationContext, ) -> AdminStoreResult { let mut record = ProxyRecord { + enabled: true, auto_location: command.auto_location, detected_location: None, location: command.location, @@ -197,6 +235,9 @@ impl ProxyStore for MemoryProxies { let mut stored = self.0.lock().unwrap(); let record = stored.as_mut().ok_or_else(missing)?; record.name = command.name; + if let Some(enabled) = command.enabled { + record.enabled = enabled; + } if let Some(auto_location) = command.auto_location { if auto_location != record.auto_location { record.detected_location = None; diff --git a/backend/crates/gateway-plugin/runtime/tests/generation/data.rs b/backend/crates/gateway-plugin/runtime/tests/generation/data.rs index 95fc020e3..1c3af0f3b 100644 --- a/backend/crates/gateway-plugin/runtime/tests/generation/data.rs +++ b/backend/crates/gateway-plugin/runtime/tests/generation/data.rs @@ -27,6 +27,7 @@ struct Facts(AtomicUsize, AtomicUsize, Option); fn account() -> AccountRecord { let at = "2026-01-01T00:00:00Z".parse().unwrap(); AccountRecord { + outbound_proxy_enabled: true, id: "acct_facts".into(), provider_kind: ProviderKind::new("openai").unwrap(), groups: vec![gateway_admin::model::account_groups::AccountGroupRef { diff --git a/backend/crates/gateway-store/src/postgres/account_groups.rs b/backend/crates/gateway-store/src/postgres/account_groups.rs index bc4d88aa9..4ca1b17de 100644 --- a/backend/crates/gateway-store/src/postgres/account_groups.rs +++ b/backend/crates/gateway-store/src/postgres/account_groups.rs @@ -226,7 +226,7 @@ impl AccountGroupStore for PgAccountGroupRepository { .map(|group_id| group_id.as_str().to_owned()) .collect::>(); let rows = sqlx::query( - "select proxy.auto_location, proxy.detected_location_json, proxy.location_country, proxy.location_region, proxy.location_city, proxy.location_timezone, membership.account_group_id, + "select coalesce(proxy.enabled, true) as outbound_proxy_enabled, proxy.auto_location, proxy.detected_location_json, proxy.location_country, proxy.location_region, proxy.location_city, proxy.location_timezone, membership.account_group_id, account.id, account.provider_kind, account.name, account.notes, account.email, account.upstream_user_id, account.upstream_account_id, account.plan_type, account.authentication_kind, account.credential_revision, account.outbound_proxy_url, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs index 4c0b3ebf8..efafa92ea 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/admin_queries.rs @@ -106,7 +106,7 @@ pub(crate) async fn load_admin_account_page( from runtime_settings where id = 1 ) - select p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id, + select coalesce(p.enabled, true) as outbound_proxy_enabled, p.auto_location, p.detected_location_json, p.location_country, p.location_region, p.location_city, p.location_timezone, a.outbound_proxy_url, a.id, a.provider_kind, a.name, a.notes, a.email, a.upstream_user_id, a.upstream_account_id, a.plan_type, a.authentication_kind, a.credential_revision, a.has_refresh_token, a.access_token_expires_at, a.next_refresh_at, a.enabled, a.concurrency_limit, a.weight, a.model_access_json, diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs index 23e6e3482..18f39e23b 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/mapping.rs @@ -10,6 +10,7 @@ pub(crate) fn admin_account_record( summary: ProviderAccountSummary, ) -> AdminStoreResult { Ok(AccountRecord { + outbound_proxy_enabled: summary.outbound_proxy_enabled, outbound_proxy: summary.outbound_proxy, id: summary.id, provider_kind: ProviderKind::new(summary.provider_kind).map_err(|_| { diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs index 00fadcb22..6e741b9fd 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/repository.rs @@ -122,14 +122,14 @@ impl ProviderAccountRepository for PgProviderAccountRepository { return Err(invalid("plugin account page limit must be positive")); } let rows = sqlx::query( - "select auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, + "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token, access_token_expires_at, next_refresh_at, enabled, concurrency_limit, weight, model_access_json, credential_state, credential_observed_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_observed_at, last_error_reason, last_error_message, created_at, updated_at from provider_accounts - left join (select id as location_proxy_id, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location + left join (select id as location_proxy_id, enabled as proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location on outbound_proxy_id = location_proxy_id where ($1::text is null or provider_kind = $1) and ($2::text is null or id > $2) @@ -151,14 +151,14 @@ impl ProviderAccountRepository for PgProviderAccountRepository { include_disabled: bool, ) -> StoreResult> { let rows = sqlx::query( - "select auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, + "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, credential_revision, has_refresh_token, access_token_expires_at, next_refresh_at, enabled, concurrency_limit, weight, model_access_json, credential_state, credential_observed_at, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, quota_observed_at, last_error_reason, last_error_message, created_at, updated_at from provider_accounts - left join (select id as location_proxy_id, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location + left join (select id as location_proxy_id, enabled as proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location on outbound_proxy_id = location_proxy_id where ($1::text is null or provider_kind = $1) and ($2 or enabled) order by provider_kind, name, id", diff --git a/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs b/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs index e1d5991e3..1bc2a1cb4 100644 --- a/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs +++ b/backend/crates/gateway-store/src/postgres/provider_accounts/rows.rs @@ -51,6 +51,7 @@ pub(crate) fn parse_error_reason(value: Option) -> StoreResult, pub outbound_proxy: Option, pub id: String, @@ -323,37 +324,37 @@ impl ProviderAccountStateUpdate { } } -pub(crate) const ACCOUNT_SELECT: &str = "select auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, +pub(crate) const ACCOUNT_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, has_refresh_token, access_token_expires_at, next_refresh_at, enabled, concurrency_limit, weight, model_access_json, credential_state, provider_quota_json, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at from provider_accounts - left join (select id as location_proxy_id, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location + left join (select id as location_proxy_id, enabled as proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location on outbound_proxy_id = location_proxy_id where id = $1"; -pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, +pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, has_refresh_token, access_token_expires_at, next_refresh_at, enabled, concurrency_limit, weight, model_access_json, credential_state, provider_quota_json, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at from provider_accounts - left join (select id as location_proxy_id, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location + left join (select id as location_proxy_id, enabled as proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location on outbound_proxy_id = location_proxy_id where id = any($1::text[]) and provider_kind = $2 order by id"; -pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, +pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id, upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision, has_refresh_token, access_token_expires_at, next_refresh_at, enabled, concurrency_limit, weight, model_access_json, credential_state, provider_quota_json, quota_access_state, quota_evidence, quota_access_observed_at, quota_reset_at, last_error_reason, last_error_message, credential_observed_at, quota_observed_at, created_at, updated_at from provider_accounts - left join (select id as location_proxy_id, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location + left join (select id as location_proxy_id, enabled as proxy_enabled, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location on outbound_proxy_id = location_proxy_id where provider_kind = $1 and has_refresh_token @@ -424,7 +425,11 @@ pub(crate) fn core_account_from_summary( ) .with_scheduling(summary.concurrency_limit, summary.weight) .with_model_access(summary.model_access) - .with_outbound_proxy(summary.outbound_proxy) + .with_outbound_proxy( + summary + .outbound_proxy + .filter(|_| summary.outbound_proxy_enabled), + ) .with_request_location(summary.request_location) .with_refresh_schedule( summary.has_refresh_token, @@ -460,6 +465,7 @@ pub(crate) fn account_summary_from_row( .and_then(AccountWeight::new) .ok_or_else(|| invalid("invalid weight"))?; Ok(ProviderAccountSummary { + outbound_proxy_enabled: get(&row, "outbound_proxy_enabled")?, request_location: super::super::proxies::effective_location_from_row(&row)?, outbound_proxy: get::>(&row, "outbound_proxy_url")? .map(|url| { diff --git a/backend/crates/gateway-store/src/postgres/proxies.rs b/backend/crates/gateway-store/src/postgres/proxies.rs index e7cf5267b..0ae6d3d8c 100644 --- a/backend/crates/gateway-store/src/postgres/proxies.rs +++ b/backend/crates/gateway-store/src/postgres/proxies.rs @@ -113,6 +113,9 @@ fn record(row: PgRow) -> StoreResult { .try_get("last_test_latency_ms") .map_err(|source| invalid().with_source(source))?; Ok(ProxyRecord { + enabled: row + .try_get("enabled") + .map_err(|source| invalid().with_source(source))?, auto_location: row .try_get("auto_location") .map_err(|source| invalid().with_source(source))?, @@ -345,8 +348,8 @@ pub(crate) async fn resolve_proxy_selection( Ok((Some(id), Some(proxy.clone()))) } AccountProxySelection::Saved(id) => { - let value: String = sqlx::query_scalar( - "select proxy_url from outbound_proxies where id = $1 for share", + let (value, enabled): (String, bool) = sqlx::query_as( + "select proxy_url, enabled from outbound_proxies where id = $1 for share", ) .bind(id) .fetch_optional(&mut **transaction) @@ -357,6 +360,9 @@ pub(crate) async fn resolve_proxy_selection( entity: ENTITY, id: id.clone(), })?; + if !enabled { + return Err(conflict(id)); + } Ok(( Some(id.clone()), Some(OutboundProxy::parse(&value).map_err(|source| invalid().with_source(source))?), @@ -561,7 +567,13 @@ impl ProxyStore for PgProxyRepository { if !acquired { return Err(store_error(conflict(id))); } - let record = match self.get(id).await { + let record = match self.get(id).await.and_then(|record| { + if record.enabled { + Ok(record) + } else { + Err(store_error(conflict(id))) + } + }) { Ok(record) => record, Err(error) => { // 拒绝预留时先等待数据库释放锁,避免连接关闭尚未生效就误挡后续代理操作 @@ -730,7 +742,7 @@ impl ProxyStore for PgProxyRepository { } let changed = sqlx::query( "update outbound_proxies set name = $3, proxy_url = coalesce($4, proxy_url), revision = revision + 1, updated_at = now(), - auto_location = coalesce($5, auto_location), + auto_location = coalesce($5, auto_location), enabled = coalesce($6, enabled), detected_location_json = case when ($4 is not null and $4 <> proxy_url) or ($5 is not null and $5 <> auto_location) then null else detected_location_json end, last_location_detection_json = case when ($4 is not null and $4 <> proxy_url) or ($5 is not null and $5 <> auto_location) then '{\"status\":\"notRequested\"}'::jsonb else last_location_detection_json end, last_test_at = case when $4 is not null and $4 <> proxy_url then null else last_test_at end, @@ -743,6 +755,7 @@ impl ProxyStore for PgProxyRepository { where id = $1 and revision = $2") .bind(&command.id).bind(i64::try_from(command.revision.get()).map_err(|_| store_error(invalid()))?) .bind(&command.name).bind(command.proxy.as_ref().map(OutboundProxy::expose_url)).bind(command.auto_location) + .bind(command.enabled) .execute(&mut *transaction).await.map_err(|source| store_error(unavailable(source)))?; if changed.rows_affected() != 1 { return Err(store_error(conflict(&command.id))); @@ -767,7 +780,7 @@ impl ProxyStore for PgProxyRepository { context, MutationAuditOperation::OutboundProxyUpdate, &command.id, - &["name", "proxy_url", "location", "auto_location"], + &["name", "proxy_url", "location", "auto_location", "enabled"], revision, ) .await @@ -799,6 +812,40 @@ impl ProxyStore for PgProxyRepository { let config_revision = bump_config_revision_in_transaction(&mut transaction) .await .map_err(store_error)?; + // 先锁定代理并校验版本,阻止新绑定插入;后续解绑和删除共同提交 + let locked: Option = sqlx::query_scalar( + "select id from outbound_proxies where id = $1 and revision = $2 for update", + ) + .bind(id) + .bind(i64::try_from(revision.get()).map_err(|_| store_error(invalid()))?) + .fetch_optional(&mut *transaction) + .await + .map_err(|source| store_error(unavailable(source)))?; + if locked.is_none() { + return Err(store_error(conflict(id))); + } + let account_ids: Vec = sqlx::query_scalar( + "update provider_accounts set outbound_proxy_id = null, outbound_proxy_url = null, + updated_at = greatest(now(), updated_at) where outbound_proxy_id = $1 returning id", + ) + .bind(id) + .fetch_all(&mut *transaction) + .await + .map_err(|source| store_error(unavailable(source)))?; + for account_id in account_ids { + append_admin_audit_event_in_transaction( + &mut transaction, + mutation_audit( + context, + MutationAuditOperation::ProviderAccountUpdate, + &account_id, + vec!["outbound_proxy".to_owned()], + ), + config_revision, + ) + .await + .map_err(store_error)?; + } let result = sqlx::query("delete from outbound_proxies where id = $1 and revision = $2") .bind(id) .bind(i64::try_from(revision.get()).map_err(|_| store_error(invalid()))?) diff --git a/backend/crates/gateway-store/tests/postgres/plugins/sources.rs b/backend/crates/gateway-store/tests/postgres/plugins/sources.rs index 8ca8dd7af..64daf52f7 100644 --- a/backend/crates/gateway-store/tests/postgres/plugins/sources.rs +++ b/backend/crates/gateway-store/tests/postgres/plugins/sources.rs @@ -11,7 +11,9 @@ use gateway_admin::{ ports::{plugins::PluginStore, proxy::ProxyStore, store::AdminStoreErrorKind}, }; use gateway_core::account::OutboundProxy; -use gateway_store::postgres::{PgPluginStore, PgProxyRepository}; +use gateway_store::postgres::{ + PgPluginStore, PgProviderAccountRepository, PgProxyRepository, ProviderAccountRepository, +}; use super::{ super::TestDatabase, @@ -289,6 +291,7 @@ async fn source_proxy_is_revision_fenced_and_referenced_until_the_artifact_is_de let updated = proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, location: None, @@ -302,6 +305,25 @@ async fn source_proxy_is_revision_fenced_and_referenced_until_the_artifact_is_de .await .unwrap() .record; + let accounts = PgProviderAccountRepository::new(database.pool.clone()); + let mut account = super::super::provider_accounts::account("acct_plugin_proxy", "Plugin proxy"); + account.outbound_proxy = Some(updated.proxy.clone()); + accounts.insert_provider_account(account).await.unwrap(); + let before: serde_json::Value = sqlx::query_scalar( + "select to_jsonb(a) from provider_accounts a where id = 'acct_plugin_proxy'", + ) + .fetch_one(&database.pool) + .await + .unwrap(); + let revision: i64 = + sqlx::query_scalar("select config_revision from runtime_settings where id = 1") + .fetch_one(&database.pool) + .await + .unwrap(); + let audit_count: i64 = sqlx::query_scalar("select count(*) from admin_audit_events") + .fetch_one(&database.pool) + .await + .unwrap(); let mut candidate = artifact('f', &["linux-x86_64"]); candidate.metadata.version = "2.0.0".into(); let Err(error) = plugins @@ -319,6 +341,27 @@ async fn source_proxy_is_revision_fenced_and_referenced_until_the_artifact_is_de .kind(), AdminStoreErrorKind::Conflict ); + let after: serde_json::Value = sqlx::query_scalar( + "select to_jsonb(a) from provider_accounts a where id = 'acct_plugin_proxy'", + ) + .fetch_one(&database.pool) + .await + .unwrap(); + assert_eq!(after, before); + assert_eq!( + sqlx::query_scalar::<_, i64>("select config_revision from runtime_settings where id = 1") + .fetch_one(&database.pool) + .await + .unwrap(), + revision + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("select count(*) from admin_audit_events") + .fetch_one(&database.pool) + .await + .unwrap(), + audit_count + ); plugins .change_update_source( PluginSourceBinding { diff --git a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs index fa9c0e370..15b369262 100644 --- a/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs +++ b/backend/crates/gateway-store/tests/postgres/provider_accounts/mod.rs @@ -2083,6 +2083,7 @@ async fn authorization_import_rejects_a_saved_proxy_changed_during_oauth() { let edited = proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, location: None, diff --git a/backend/crates/gateway-store/tests/postgres/proxies.rs b/backend/crates/gateway-store/tests/postgres/proxies.rs index a2ee4f292..75ce36449 100644 --- a/backend/crates/gateway-store/tests/postgres/proxies.rs +++ b/backend/crates/gateway-store/tests/postgres/proxies.rs @@ -1,4 +1,4 @@ -//! 验证代理位置、账号绑定、分页查询与事务锁释放 +//! 验证代理启停、位置、账号绑定、自动解绑与事务锁释放 use gateway_admin::{ model::{ @@ -68,6 +68,7 @@ async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() { saved = proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: saved.id.clone(), @@ -87,6 +88,7 @@ async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() { saved = proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: saved.id.clone(), @@ -115,6 +117,7 @@ async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() { proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: saved.id.clone(), @@ -132,6 +135,7 @@ async fn proxy_location_is_shared_preserved_cleared_and_removed_with_binding() { proxies .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: saved.id.clone(), @@ -168,6 +172,201 @@ fn context() -> MutationContext { } } +#[tokio::test] +async fn disabled_proxy_projects_direct_while_preserving_bindings_and_credentials() { + use gateway_core::{ + account::{ProviderAccountStore as _, ProviderRefreshQuery, RequestLocation}, + routing::ProviderKind, + }; + use std::{ + num::NonZeroU32, + time::{Duration, SystemTime}, + }; + + let Some(database) = TestDatabase::create("proxy_enabled").await else { + return; + }; + let proxies = PgProxyRepository::new(database.pool.clone()); + let accounts = PgProviderAccountRepository::new(database.pool.clone()); + let admin = admin_account_store(&database.pool); + let location: RequestLocation = serde_json::from_value(serde_json::json!({ + "country":"JP", "region":"Tokyo", "city":"Tokyo", "timezone":"Asia/Tokyo" + })) + .unwrap(); + let mut saved = proxies + .create( + NewProxy { + auto_location: false, + test: None, + location: Some(location.clone()), + name: "启停测试".to_owned(), + proxy: OutboundProxy::parse("http://user:secret@127.0.0.1:18080").unwrap(), + }, + &context(), + ) + .await + .unwrap() + .record; + assert!(saved.enabled); + proxies + .record_test(&saved.id, saved.revision, success(), &context()) + .await + .unwrap(); + for (id, provider) in [ + ("acct_enabled_openai", "openai"), + ("acct_enabled_xai", "xai"), + ] { + let mut seed = account(id, id); + seed.provider_kind = provider.into(); + seed.outbound_proxy = Some(saved.proxy.clone()); + seed.has_refresh_token = true; + seed.access_token_expires_at = Some(chrono::Utc::now()); + accounts.insert_provider_account(seed).await.unwrap(); + } + let original: Vec = + sqlx::query_scalar("select to_jsonb(a) from provider_accounts a order by id") + .fetch_all(&database.pool) + .await + .unwrap(); + let original_revision = accounts.list_accounts().await.unwrap()[0].revision(); + for enabled in [false, true] { + let stale_revision = saved.revision; + saved = proxies + .update( + UpdateProxy { + enabled: Some(enabled), + auto_location: None, + test: None, + location: None, + id: saved.id.clone(), + revision: saved.revision, + name: saved.name.clone(), + proxy: None, + }, + &context(), + ) + .await + .unwrap() + .record; + assert_eq!(saved.enabled, enabled); + assert_eq!(saved.account_count, 2); + assert_eq!(saved.last_test, Some(success())); + assert_eq!(saved.location.as_ref(), Some(&location)); + let current: Vec = + sqlx::query_scalar("select to_jsonb(a) from provider_accounts a order by id") + .fetch_all(&database.pool) + .await + .unwrap(); + assert_eq!(current, original); + let mut projected = accounts.list_accounts().await.unwrap(); + for (id, provider) in [ + ("acct_enabled_openai", "openai"), + ("acct_enabled_xai", "xai"), + ] { + let id = ProviderAccountId::new(id).unwrap(); + projected.push(accounts.get_account(&id).await.unwrap().unwrap()); + projected.push(accounts.load_current_credential(&id).await.unwrap().account); + let kind = ProviderKind::new(provider).unwrap(); + projected.extend(accounts.list_for_provider(&kind).await.unwrap()); + let now = SystemTime::now(); + projected.extend( + accounts + .list_refresh_candidates(ProviderRefreshQuery::new( + kind, + now + Duration::from_secs(300), + now - Duration::from_secs(7200), + now, + vec![], + NonZeroU32::new(10).unwrap(), + )) + .await + .unwrap() + .into_iter() + .map(|loaded| loaded.account), + ); + let configured = admin + .credential_details(&ProviderKind::new(provider).unwrap(), &id) + .await + .unwrap() + .unwrap() + .credential; + assert_eq!(configured.outbound_proxy.as_ref(), Some(&saved.proxy)); + assert_eq!( + configured.effective_outbound_proxy(), + enabled.then_some(&saved.proxy) + ); + } + assert!(projected.iter().all(|account| account.outbound_proxy() + == enabled.then_some(&saved.proxy) + && account.request_location() == enabled.then_some(&location) + && account.revision() == original_revision + && account.enabled())); + assert_eq!( + proxies + .update( + UpdateProxy { + enabled: Some(!enabled), + auto_location: None, + test: None, + location: None, + id: saved.id.clone(), + revision: stale_revision, + name: saved.name.clone(), + proxy: None, + }, + &context() + ) + .await + .unwrap_err() + .kind(), + AdminStoreErrorKind::Conflict + ); + assert_eq!(proxies.get(&saved.id).await.unwrap().enabled, enabled); + let reservation = proxies.reserve_import(&saved.id).await; + assert_eq!(reservation.is_ok(), enabled); + drop(reservation); + if !enabled { + let error = admin + .update_account( + update( + "acct_enabled_openai", + AccountProxySelection::Saved(saved.id.clone()), + ), + &context(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind(), AdminStoreErrorKind::Conflict); + let error = admin + .batch_update_accounts( + BatchUpdateAccounts { + account_ids: vec![ + "acct_enabled_openai".to_owned(), + "acct_enabled_xai".to_owned(), + ], + enabled: Some(false), + concurrency_limit: None, + weight: None, + model_access: None, + group_ids: None, + outbound_proxy: Some(AccountProxySelection::Saved(saved.id.clone())), + }, + &context(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind(), AdminStoreErrorKind::Conflict); + let unchanged: Vec = + sqlx::query_scalar("select to_jsonb(a) from provider_accounts a order by id") + .fetch_all(&database.pool) + .await + .unwrap(); + assert_eq!(unchanged, original); + } + } + database.close().await; +} + fn success() -> ProxyTestResult { ProxyTestResult { location: Default::default(), @@ -575,6 +774,7 @@ async fn stale_proxy_test_releases_lock_before_next_update() { let update = store .update( UpdateProxy { + enabled: None, id: saved.id.clone(), revision: saved.revision, name: saved.name.clone(), @@ -634,6 +834,7 @@ async fn import_reservation_blocks_proxy_mutations_until_rotated_credentials_are .unwrap(); let reservation = store.reserve_import(&saved.id).await.unwrap(); let replacement = UpdateProxy { + enabled: None, auto_location: None, test: None, location: None, @@ -798,14 +999,6 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test .unwrap(); } assert_eq!(store.get(&created.id).await.unwrap().account_count, 2); - assert_eq!( - store - .delete(&created.id, created.revision, &context) - .await - .unwrap_err() - .kind(), - AdminStoreErrorKind::Conflict - ); assert!( read() .await @@ -822,6 +1015,7 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test let renamed = store .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: created.id.clone(), @@ -842,6 +1036,7 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test let edited = store .update( UpdateProxy { + enabled: None, auto_location: None, test: None, id: created.id.clone(), @@ -875,22 +1070,45 @@ async fn managed_proxies_persist_bind_update_all_accounts_and_protect_stale_test .await .unwrap(); - for id in ["acct_one", "acct_two"] { - admin - .update_account(update(id, AccountProxySelection::Direct), &context) + assert_eq!( + store + .delete(&created.id, created.revision, &context) .await - .unwrap(); - } + .unwrap_err() + .kind(), + AdminStoreErrorKind::Conflict + ); + assert!( + read() + .await + .iter() + .all(|row| row.1.as_deref() == Some(created.id.as_str())) + ); + let preserved: Vec = sqlx::query_scalar("select to_jsonb(a) - 'updated_at' - 'outbound_proxy_id' - 'outbound_proxy_url' from provider_accounts a order by id") + .fetch_all(&database.pool).await.unwrap(); + let deleted_revision = store + .delete(&created.id, edited.revision, &context) + .await + .unwrap(); + let after_delete: Vec = sqlx::query_scalar("select to_jsonb(a) - 'updated_at' - 'outbound_proxy_id' - 'outbound_proxy_url' from provider_accounts a order by id") + .fetch_all(&database.pool).await.unwrap(); + assert_eq!(preserved, after_delete); + assert_eq!( + sqlx::query_scalar::<_, i64>( + "select count(*) from admin_audit_events where config_revision = $1" + ) + .bind(i64::try_from(deleted_revision.get()).unwrap()) + .fetch_one(&database.pool) + .await + .unwrap(), + 3 + ); assert!( read() .await .iter() .all(|row| row.1.is_none() && row.2.is_none() && row.3 == 1) ); - store - .delete(&created.id, edited.revision, &context) - .await - .unwrap(); assert!(store.get(&created.id).await.is_err()); let audits: Vec = sqlx::query_scalar("select to_jsonb(a) from admin_audit_events a") @@ -984,6 +1202,12 @@ async fn migration_backfills_shared_proxies_without_changing_credentials() { .unwrap(); } super::TEST_MIGRATOR.run(&database.pool).await.unwrap(); + assert!( + sqlx::query_scalar::<_, bool>("select bool_and(enabled) from outbound_proxies") + .fetch_one(&database.pool) + .await + .unwrap() + ); let accounts = PgProviderAccountRepository::new(database.pool.clone()); let inherited = gateway_core::account::ProviderAccountStore::list_accounts(&accounts) .await @@ -1134,6 +1358,7 @@ async fn automatic_proxy_location_projects_to_accounts_and_guards_refresh_result saved = proxies .update( UpdateProxy { + enabled: None, id: saved.id.clone(), revision: saved.revision, name: saved.name.clone(), @@ -1152,6 +1377,7 @@ async fn automatic_proxy_location_projects_to_accounts_and_guards_refresh_result saved = proxies .update( UpdateProxy { + enabled: None, id: saved.id.clone(), revision: saved.revision, name: saved.name.clone(), @@ -1178,6 +1404,7 @@ async fn automatic_proxy_location_projects_to_accounts_and_guards_refresh_result saved = proxies .update( UpdateProxy { + enabled: None, id: saved.id.clone(), revision: saved.revision, name: saved.name.clone(), diff --git a/backend/crates/providers/openai/tests/admin.rs b/backend/crates/providers/openai/tests/admin.rs index 9604b19c5..11a61c98f 100644 --- a/backend/crates/providers/openai/tests/admin.rs +++ b/backend/crates/providers/openai/tests/admin.rs @@ -1755,6 +1755,7 @@ fn provider_ports_with_catalog( fn account_record(account: &ProviderAccount) -> AccountRecord { let now = Utc::now(); AccountRecord { + outbound_proxy_enabled: true, notes: None, model_access: Default::default(), outbound_proxy: None, diff --git a/backend/crates/providers/xai/tests/admin.rs b/backend/crates/providers/xai/tests/admin.rs index ed69a0909..cc7ae4331 100644 --- a/backend/crates/providers/xai/tests/admin.rs +++ b/backend/crates/providers/xai/tests/admin.rs @@ -739,6 +739,7 @@ fn provider_ports_with_catalog( fn account_record(account: &ProviderAccount) -> AccountRecord { let now = Utc::now(); AccountRecord { + outbound_proxy_enabled: true, notes: None, model_access: Default::default(), outbound_proxy: None, diff --git a/backend/migrations/.frozen-sha256 b/backend/migrations/.frozen-sha256 index 172cf36b9..f712b9043 100644 --- a/backend/migrations/.frozen-sha256 +++ b/backend/migrations/.frozen-sha256 @@ -28,4 +28,5 @@ d4b599066d7382a1c9cb6b3c003200046579e4fce3531f232cbd665a9d92c542 0026_codex_pri 31d6668707186d7c19cdd507e20162a08c7fbb8ba41ff4a4439d0a5e08369cad 0028_request_analytics.sql 1923f14095dac5f808a530db002c37e17168afa0778bc7f3da768c818133eec9 0029_usage_indexes_and_identity_snapshots.sql f10058e2b4c974b6d2ffa11be78b085504a233205253948c03357ef6fe234bca 0030_analytics_and_scheduling.sql +252ba957fa5c4f5171aee2aa238f2da7202a7c53dc6245ee4a210626089ec5a7 0031_outbound_proxy_enabled.sql 24b786f80a8bdebe3d915f60a9d68d5c7c9fc04fd4eaa9912f5d7a997fefa87f 0032_privacy_rule_steps.sql diff --git a/backend/migrations/0031_outbound_proxy_enabled.sql b/backend/migrations/0031_outbound_proxy_enabled.sql new file mode 100644 index 000000000..d25b1aa17 --- /dev/null +++ b/backend/migrations/0031_outbound_proxy_enabled.sql @@ -0,0 +1,2 @@ +-- 命名代理独立启停,保留连接配置和账号绑定 +alter table outbound_proxies add column enabled boolean not null default true; diff --git a/docs/api.md b/docs/api.md index 5039eb7ea..701cbf9c7 100644 --- a/docs/api.md +++ b/docs/api.md @@ -781,16 +781,16 @@ Images 按请求正文的图片模型 ID 检查,不依赖文本模型目录; | `GET` | `/api/admin/proxies/accounts` | `proxyId`、`page`、`pageSize`(1-200)、`search`(账号名称或邮箱) | `{ items, page }` | | `POST` | `/api/admin/proxies/accounts/remove` | `{ proxyId, accountId }` | `{ configRevision }` | | `POST` | `/api/admin/proxies/create` | `{ name, proxyUrl, location?, autoLocation? }` | `201 { record, configRevision }` | -| `POST` | `/api/admin/proxies/update` | `{ id, revision, name, proxyUrl?, location?, autoLocation? }` | `{ record, configRevision }` | +| `POST` | `/api/admin/proxies/update` | `{ id, revision, name, enabled?, proxyUrl?, location?, autoLocation? }` | `{ record, configRevision }` | | `POST` | `/api/admin/proxies/probe` | `{ proxyUrl, detectLocation? }` | 测试未保存的地址,返回连通性及可选位置结果,不创建代理 | | `POST` | `/api/admin/proxies/test` | `{ id, revision, detectLocation? }` | 最新代理记录 / Proxy record with test result | | `POST` | `/api/admin/proxies/delete` | `{ id, revision }` | `{ configRevision }` | -`record` 包含 `id`、`name`、`endpoint`、`hasAuthentication`、`revision`、`accountCount`、`location`、 +`record` 包含 `id`、`name`、`enabled`、`endpoint`、`hasAuthentication`、`revision`、`accountCount`、`location`、 `autoLocation`、`detectedLocation`、`lastTestAt`、 `lastTest: { success, latencyMs, exitIp, exitIpv4, exitIpv6, message, location }`、`createdAt`、`updatedAt`。 未测试时 `lastTestAt` / `lastTest` 为 `null`。连通性失败返回 HTTP 200 和 `lastTest.success=false`; -记录版本过期、重复 URL、删除已绑定的代理返回 409,并发测试满载返回 429 +记录版本过期、重复 URL 或代理正在用于账号导入时返回 409,并发测试满载返回 429 代理列表只返回关联账号数量。关联账号按需查询,每项包含 `id`、`name`、`email`、`provider`、`enabled`、 `authenticationKind`、`planType`、`planTypeDisplay` 和 `groups: [{ id, name, color, enabled }]`, @@ -799,10 +799,16 @@ Images 按请求正文的图片模型 ID 检查,不依赖文本模型目录; 移除关联账号只清除指定账号的代理绑定与连接地址,使其改为直连,保留凭据、调度参数与分组。 若账号已不再绑定请求中的代理,则返回 409 +删除代理会自动解除全部关联账号的代理绑定与连接地址,账号保留其余设置并改为直连。 +代理仍被插件来源或插件包引用时返回 409,账号绑定保持不变 更新省略 `proxyUrl` 保留认证;连接配置改变时清除测试结果并更新所有绑定账号。 测试结果只在请求中的版本仍匹配时保存 +代理默认启用,更新 `enabled: false` 后保留配置、测试结果和账号绑定,关联账号的新请求改为直连, +不应用该代理的位置覆盖;重新启用后恢复原出口及位置规则。省略 `enabled` 保留当前状态。 +禁用代理仍可执行连接测试,但不能以 ID 选择用于账号绑定、新的账号授权、导入或插件下载 + `detectLocation: true` 在测试连接时解析出口位置;结果 `location.status` 为 `notRequested`、 `detected`、`failed` 或 `conflict`。`detected` 携带 `location`,`failed` 携带安全错误说明; 位置查询失败不等同于代理连接失败。管理端的解析按钮把成功结果填入自定义位置表单,保存后生效; diff --git a/docs/architecture.md b/docs/architecture.md index 042225039..61c4abde9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -479,10 +479,10 @@ OpenAI / xAI 导入用例。并发槽位由单个 Worker 统一管理,条目 ### 账号出站代理 出站代理属于账号配置,由各 Provider 在推理、OAuth 服务端交换/刷新、额度、目录和资料等请求中统一使用。 -指定代理不可用时请求失败,不退回直连;未配置时直连,不继承进程的全局代理环境变量,TLS 仍验证证书。 +启用的指定代理不可用时请求失败,不退回直连;未配置或代理被禁用时直连,不继承进程的全局代理环境变量,TLS 仍验证证书。 用户浏览器访问第三方授权页时的出口不受网关设置控制 -连接池按出口隔离。修改代理推进配置 revision,使后续请求使用新出口;已执行请求可沿原连接完成。 +连接池按出口隔离。修改或启停代理推进配置 revision,使后续请求使用新出口;已执行请求可沿原连接完成。 代理变更不推进 `credential_revision`,不会使进行中的令牌刷新因凭据版本冲突而丢失结果。 xAI 的推理连接池继续按账号绑定隔离;OAuth、目录/计费辅助请求在各自 transport 内复用有界出口 client,OIDC 的 JWKS 缓存与单飞归属对应出口状态。自动刷新提交凭据后的目录预热重新读取当前账号 @@ -490,7 +490,10 @@ client,OIDC 的 JWKS 缓存与单飞归属对应出口状态。自动刷新提 代理独立保存和测试,通过 `outboundProxyId` 绑定账号;账号保留解析后的 URL 供 Provider 使用。 出口测试结果属于诊断信息,不作为选择、授权或导入绑定的准入条件。 -连接配置改变时在同一事务内同步关联账号并清除旧测试结果,已绑定的代理不可删除。 +代理启停由代理记录独立持有;关闭时保留绑定、连接配置和位置规则,账号执行投影改为直连, +不使用该代理的位置覆盖,重新启用后恢复原出口。 +连接配置改变时在同一事务内同步关联账号并清除旧测试结果。 +删除代理在同一事务中校验版本、解除全部账号绑定并写入审计与配置 revision,账号其余事实及凭据版本保持不变。 关联账号支持单独移除:在原子更新中校验当前代理 ID,只清除账号的代理 ID 和 URL, 保留账号其他设置;提交配置版本与审计后复用快照发布流程,使后续请求使用直连。 代理目录只携带关联数量;账号明细通过独立分页读端口按需查询, diff --git a/frontend/src/api/modules/proxies.ts b/frontend/src/api/modules/proxies.ts index fdb0b5db0..d20cabf4a 100644 --- a/frontend/src/api/modules/proxies.ts +++ b/frontend/src/api/modules/proxies.ts @@ -27,6 +27,7 @@ export interface OutboundProxyTest { } export interface OutboundProxyRecord { + enabled: boolean autoLocation: boolean detectedLocation: DetectedProxyLocation | null location: RequestLocation | null @@ -107,7 +108,7 @@ export function createProxy(data: { name: string, proxyUrl: string, autoLocation }) } -export function updateProxy(data: { id: string, revision: number, name: string, proxyUrl?: string, autoLocation?: boolean, location?: RequestLocation | null }) { +export function updateProxy(data: { id: string, revision: number, name: string, enabled?: boolean, proxyUrl?: string, autoLocation?: boolean, location?: RequestLocation | null }) { return request({ url: '/api/admin/proxies/update', timeout: 25000, diff --git a/frontend/src/views/accounts/components/AccountProxyField.vue b/frontend/src/views/accounts/components/AccountProxyField.vue index f09218e32..80b150c97 100644 --- a/frontend/src/views/accounts/components/AccountProxyField.vue +++ b/frontend/src/views/accounts/components/AccountProxyField.vue @@ -18,9 +18,10 @@ const options = computed(() => [ : []), { label: '直连', value: 'direct', description: '不使用代理' }, ...proxies.value.map(proxy => ({ - label: `${proxy.name}${proxy.lastTest?.success ? '' : proxy.lastTest ? '(测试失败)' : '(未测试)'}`, + label: `${proxy.name}${!proxy.enabled ? '(已禁用)' : proxy.lastTest?.success ? '' : proxy.lastTest ? '(测试失败)' : '(未测试)'}`, value: proxy.id, description: proxy.endpoint, + disabled: !proxy.enabled, })), ]) const selection = computed({ diff --git a/frontend/src/views/plugins/components/PluginSourceProxyField.vue b/frontend/src/views/plugins/components/PluginSourceProxyField.vue index d32e32111..4f871e3ef 100644 --- a/frontend/src/views/plugins/components/PluginSourceProxyField.vue +++ b/frontend/src/views/plugins/components/PluginSourceProxyField.vue @@ -11,9 +11,10 @@ const { proxies, loading } = useProxyCatalog() const options = computed(() => [ { label: '不使用代理(直连)', value: '' }, ...proxies.value.map(proxy => ({ - label: proxy.name, + label: `${proxy.name}${proxy.enabled ? '' : '(已禁用)'}`, value: proxy.id, description: proxy.endpoint, + disabled: !proxy.enabled, })), // 目录加载失败或代理已被删除时保留已选 ID,不能静默改为直连。 ...(proxyId.value && !proxies.value.some(proxy => proxy.id === proxyId.value) diff --git a/frontend/src/views/proxies/components/ProxyActions.vue b/frontend/src/views/proxies/components/ProxyActions.vue new file mode 100644 index 000000000..eeee08613 --- /dev/null +++ b/frontend/src/views/proxies/components/ProxyActions.vue @@ -0,0 +1,52 @@ + + + diff --git a/frontend/src/views/proxies/composables/useProxies.ts b/frontend/src/views/proxies/composables/useProxies.ts index 8a3b379d3..61f52dee3 100644 --- a/frontend/src/views/proxies/composables/useProxies.ts +++ b/frontend/src/views/proxies/composables/useProxies.ts @@ -32,6 +32,11 @@ export function useProxies() { const pendingDelete = shallowRef(null) const testing = useIdSet() const testingIds = testing.ids + const updating = useIdSet() + const updatingIds = updating.ids + const showDisable = shallowRef(false) + const pendingDisable = shallowRef(null) + const disabling = computed(() => pendingDisable.value !== null && updating.has(pendingDisable.value.id)) const formTestAction = useAsyncAction() const testingForm = computed(() => formTestAction.loading.value || (editing.value !== null && testingIds.value.has(editing.value.id))) const detectingLocation = shallowRef(false) @@ -189,6 +194,37 @@ export function useProxies() { showDelete.value = true } + async function setEnabled(proxy: OutboundProxyRecord, enabled: boolean) { + if (updating.has(proxy.id) || testing.has(proxy.id)) + return + updating.add(proxy.id) + try { + await updateProxy({ id: proxy.id, revision: proxy.revision, name: proxy.name, enabled }) + showDisable.value = false + ZNotification.success({ message: enabled ? '代理已启用' : '代理已禁用,关联账号已改为直连' }) + } + catch {} + finally { + updating.remove(proxy.id) + await query.execute({ silent: true }) + } + } + + function toggleEnabled(proxy: OutboundProxyRecord) { + if (proxy.enabled) { + pendingDisable.value = proxy + showDisable.value = true + } + else { + void setEnabled(proxy, true) + } + } + + async function confirmDisable() { + if (pendingDisable.value) + await setEnabled(pendingDisable.value, false) + } + async function confirmDelete() { const proxy = pendingDelete.value if (!proxy || deleting.value) @@ -242,6 +278,12 @@ export function useProxies() { pendingDelete, deleting, testingIds, + updatingIds, + showDisable, + pendingDisable, + disabling, + toggleEnabled, + confirmDisable, testingConnection, detectingLocation, openForm, diff --git a/frontend/src/views/proxies/constants.ts b/frontend/src/views/proxies/constants.ts index 004dc40b5..5dcd356b9 100644 --- a/frontend/src/views/proxies/constants.ts +++ b/frontend/src/views/proxies/constants.ts @@ -4,6 +4,7 @@ import { defineTableColumns } from '@codex-proxy/ui' export const proxyColumns = defineTableColumns([ { key: 'name', label: '代理名称', kind: 'identity', size: 'lg' }, { key: 'address', label: '代理地址', kind: 'identity', size: 'xl' }, + { key: 'status', label: '状态', kind: 'status' }, { key: 'exitIp', label: '出口 IP', kind: 'custom', size: 'xl' }, { key: 'latency', label: '耗时', kind: 'custom', size: 'sm' }, { key: 'accounts', label: '关联账号', kind: 'custom', size: 'sm' }, diff --git a/frontend/src/views/proxies/index.vue b/frontend/src/views/proxies/index.vue index d02fd88f8..613ed0489 100644 --- a/frontend/src/views/proxies/index.vue +++ b/frontend/src/views/proxies/index.vue @@ -1,9 +1,10 @@