diff --git a/backend/crates/gateway-admin/src/model/provider_credentials.rs b/backend/crates/gateway-admin/src/model/provider_credentials.rs index d57ee2766..8cf1734a5 100644 --- a/backend/crates/gateway-admin/src/model/provider_credentials.rs +++ b/backend/crates/gateway-admin/src/model/provider_credentials.rs @@ -698,7 +698,7 @@ pub struct PreparedCredentialRotationFacts { pub plan_type: Option, /// Token 刷新保留提交时的资料,不以准备阶段的副本覆盖新套餐 pub preserve_profile: bool, - /// 连接配置变更保留当前凭据健康状态与错误事实 + /// 凭据或连接配置更新保留提交时的健康状态与错误事实 pub preserve_credential_state: bool, pub preserve_access_token_expiry: bool, pub provider_material: ProviderDocument, @@ -722,7 +722,7 @@ impl PreparedCredentialRotation { Self { facts, guard } } - /// 仅修改连接配置时,不把配置更新视为凭据恢复成功 + /// 更新本身不能证明账号已恢复时,保留提交时的状态 #[must_use] pub fn preserving_credential_state(mut self) -> Self { self.facts.preserve_credential_state = true; diff --git a/backend/crates/providers/antigravity/src/credential/catalog.rs b/backend/crates/providers/antigravity/src/credential/catalog.rs index eb826ebb6..a6535114c 100644 --- a/backend/crates/providers/antigravity/src/credential/catalog.rs +++ b/backend/crates/providers/antigravity/src/credential/catalog.rs @@ -308,6 +308,18 @@ impl CatalogService { } } } + if !refresh + && matches!( + current.account.credential_state(), + gateway_core::account::CredentialState::Invalid + | gateway_core::account::CredentialState::Banned + ) + { + return Ok(ProviderModels { + models: Vec::new(), + observed_at: None, + }); + } if current.account.authentication_kind() == super::api_key::API_KEY { let material = super::api_key::ApiKeyMaterial::load(¤t)?; let client = crate::transport::GenAiClient::new( @@ -316,7 +328,12 @@ impl CatalogService { ) .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; let observed_at = SystemTime::now(); - let catalog = client.catalog(&material.api_key).await.map_err(|e| { + let result = client.catalog(&material.api_key).await; + if let Err(failure) = &result { + super::record_account_failure(self.accounts.as_ref(), ¤t.account, failure) + .await; + } + let catalog = result.map_err(|e| { error(AdminKind::Unavailable) .with_public_message("GenAI 模型目录查询失败") .with_source(e) @@ -333,15 +350,16 @@ impl CatalogService { let client = CloudCodeClient::new(&self.origin, current.account.outbound_proxy(), &profile) .map_err(|e| error(AdminKind::Unavailable).with_source(e))?; let observed_at = SystemTime::now(); - let catalog = client - .catalog(&material.access_token) - .await - .map_err(|e| match e.kind() { - Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e), - _ => error(AdminKind::Unavailable) - .with_public_message("Antigravity 项目或模型目录查询失败") - .with_source(e), - })?; + let result = client.catalog(&material.access_token).await; + if let Err(error) = &result { + super::record_account_failure(self.accounts.as_ref(), ¤t.account, error).await; + } + let catalog = result.map_err(|e| match e.kind() { + Kind::Unauthorized => error(AdminKind::CredentialRefreshRequired).with_source(e), + _ => error(AdminKind::Unavailable) + .with_public_message("Antigravity 项目或模型目录查询失败") + .with_source(e), + })?; self.publish( ¤t.account, current.account.plan_type().map(str::to_owned), @@ -476,7 +494,11 @@ impl CatalogService { .await .map_err(|e| WorkerTaskError::safe("读取 Antigravity 账号失败").with_source(e))?; due.retain(|account| { - matches!(account.authentication_kind(), "oauth" | "api_key") + !matches!( + account.credential_state(), + gateway_core::account::CredentialState::Invalid + | gateway_core::account::CredentialState::Banned + ) && matches!(account.authentication_kind(), "oauth" | "api_key") && observations.get(account.id()).is_none_or(|observation| { observation.revision != account.revision() || observation.observed_at.elapsed().unwrap_or_default() diff --git a/backend/crates/providers/antigravity/src/credential/failure.rs b/backend/crates/providers/antigravity/src/credential/failure.rs new file mode 100644 index 000000000..4f34a7f4b --- /dev/null +++ b/backend/crates/providers/antigravity/src/credential/failure.rs @@ -0,0 +1,70 @@ +//! 资源服务的明确拒绝更新账号访问状态,普通授权失败只触发 AT 续期 + +use crate::transport::{AccountRejection, account_rejection}; +use gateway_core::{ + account::{ + AccountErrorReason, AccountStateChange, CredentialState, ProviderAccount, + ProviderAccountStore, + }, + error::{ProviderError, ProviderErrorKind, StoreError}, + upstream::UpstreamSendState, +}; +use std::time::{Duration, SystemTime}; + +pub(crate) async fn record_account_failure( + accounts: &dyn ProviderAccountStore, + account: &ProviderAccount, + error: &ProviderError, +) { + if error.send_state() != UpstreamSendState::Sent { + return; + } + let state = match account_rejection(error) { + Some(AccountRejection::VerificationRequired) => Some(( + CredentialState::Invalid, + AccountErrorReason::AccountUnverified, + "Google 要求验证账号,完成验证后恢复账号状态", + )), + Some(AccountRejection::Banned) => Some(( + CredentialState::Banned, + AccountErrorReason::AccountBanned, + "Google 已停用账号", + )), + None if error.kind() == ProviderErrorKind::Unauthorized + && account.authentication_kind() == super::api_key::API_KEY => + { + Some(( + CredentialState::Invalid, + AccountErrorReason::CredentialInvalid, + "上游拒绝 API Key", + )) + } + None => None, + }; + let feedback = async { + if let Some((credential_state, error_reason, message)) = state { + accounts + .apply_state_change(AccountStateChange { + account_id: account.id().clone(), + expected_revision: account.revision(), + credential_state, + observed_at: SystemTime::now(), + error_reason: Some(error_reason), + message: Some(message.into()), + }) + .await?; + } else if error.kind() == ProviderErrorKind::Unauthorized { + // 资源服务拒绝 AT 不能证明 RT 失效,续期由 OAuth worker 负责 + accounts + .expire_access_token(account, SystemTime::now()) + .await?; + } + Ok::<_, StoreError>(()) + }; + if !matches!( + tokio::time::timeout(Duration::from_millis(100), feedback).await, + Ok(Ok(())) + ) { + tracing::warn!("Antigravity 账号失败反馈未能写入共享状态"); + } +} diff --git a/backend/crates/providers/antigravity/src/credential/mod.rs b/backend/crates/providers/antigravity/src/credential/mod.rs index 902e5ed40..f2c62f732 100644 --- a/backend/crates/providers/antigravity/src/credential/mod.rs +++ b/backend/crates/providers/antigravity/src/credential/mod.rs @@ -4,6 +4,8 @@ pub(crate) mod api_key; mod authorization; pub(crate) mod catalog; mod documents; +mod failure; +pub(crate) use failure::record_account_failure; mod model_groups; pub(crate) mod oauth; pub(crate) mod quota; diff --git a/backend/crates/providers/antigravity/src/credential/quota/service.rs b/backend/crates/providers/antigravity/src/credential/quota/service.rs index fc8520c1c..a0b5322bb 100644 --- a/backend/crates/providers/antigravity/src/credential/quota/service.rs +++ b/backend/crates/providers/antigravity/src/credential/quota/service.rs @@ -175,15 +175,20 @@ impl QuotaService { .map_err(upstream)?; // 用查询开始时间隔离交错返回的旧结果,失败不覆盖已有快照 let observed_at = SystemTime::now(); - let info = client - .account_info(&material.access_token) - .await - .map_err(upstream)?; - let (catalog, summary) = tokio::try_join!( - client.catalog_for_project(&material.access_token, info.project.clone()), - client.quota_summary(&material.access_token, &info.project), - ) - .map_err(upstream)?; + let result = async { + let info = client.account_info(&material.access_token).await?; + let (catalog, summary) = tokio::try_join!( + client.catalog_for_project(&material.access_token, info.project.clone()), + client.quota_summary(&material.access_token, &info.project), + )?; + Ok::<_, gateway_core::error::ProviderError>((info, catalog, summary)) + } + .await; + if let Err(error) = &result { + super::super::record_account_failure(self.accounts.as_ref(), ¤t.account, error) + .await; + } + let (info, catalog, summary) = result.map_err(upstream)?; let (tier, plan_description) = match info.paid_tier { Some(paid) => (Some(paid.tier), paid.description), None => (info.current_tier, None), @@ -324,10 +329,15 @@ impl QuotaService { let stale_before = now - interval; let mut due = Vec::new(); let mut stale = Vec::new(); - for account in accounts - .iter() - .filter(|a| a.enabled() && a.authentication_kind() == "oauth") - { + for account in accounts.iter().filter(|a| { + a.enabled() + && a.authentication_kind() == "oauth" + && !matches!( + a.credential_state(), + gateway_core::account::CredentialState::Invalid + | gateway_core::account::CredentialState::Banned + ) + }) { let snapshot = observations .remove(account.id()) .filter(|s| s.credential_revision == account.revision()); diff --git a/backend/crates/providers/antigravity/src/credential/refresh.rs b/backend/crates/providers/antigravity/src/credential/refresh.rs index 19f9dff97..5265bee68 100644 --- a/backend/crates/providers/antigravity/src/credential/refresh.rs +++ b/backend/crates/providers/antigravity/src/credential/refresh.rs @@ -4,8 +4,8 @@ use super::{oauth::error, service::CredentialService}; use gateway_admin::ports::provider::{ProviderAdminError, ProviderAdminErrorKind as Kind}; use gateway_core::{ account::{ - CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, CredentialState, - LoadedCredential, PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery, + CredentialCasOutcome, CredentialCasUpdate, CredentialRevision, LoadedCredential, + PlaintextCredential, ProviderAccountUpdate, ProviderRefreshQuery, }, provider_ports::provider_refresh_backoff_at, task::WorkerTaskError, @@ -79,8 +79,8 @@ impl CredentialService { material, facts.access_token_expires_at.map(Into::into), None, - )? - .with_account_state(CredentialState::Ready, SystemTime::now(), None, None); + )?; + // AT 续期不证明资源服务已解除验证或封禁,提交时保留当前账号访问状态 match self .accounts .compare_and_swap_credential(record) diff --git a/backend/crates/providers/antigravity/src/credential/service.rs b/backend/crates/providers/antigravity/src/credential/service.rs index 706b7cf59..780c3ca0e 100644 --- a/backend/crates/providers/antigravity/src/credential/service.rs +++ b/backend/crates/providers/antigravity/src/credential/service.rs @@ -304,6 +304,7 @@ impl CredentialService { Ok(grant) => grant, }; self.rotation(¤t.account, grant, guards) + .map(PreparedCredentialRotation::preserving_credential_state) } pub(super) fn rotation( diff --git a/backend/crates/providers/antigravity/src/provider/execution.rs b/backend/crates/providers/antigravity/src/provider/execution.rs index 5c5c0839f..5858ecc66 100644 --- a/backend/crates/providers/antigravity/src/provider/execution.rs +++ b/backend/crates/providers/antigravity/src/provider/execution.rs @@ -137,6 +137,7 @@ impl AntigravityProvider { }; let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?; let translated_chat = translator.is_some(); + let native_error = !translated_chat && count_translator.is_none(); let events = async_stream::try_stream! { if cancellation.is_cancelled() { Err(unsent(Kind::Cancelled))?; @@ -144,12 +145,12 @@ impl AntigravityProvider { if deadline.is_elapsed() { Err(unsent(Kind::Timeout))?; } - let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic) - .then(|| selected.material.token().to_owned()); + let error_token = selected.material.token().to_owned(); let record_failure = async |error| { - let error = match &probe_token { - Some(token) => crate::transport::connection_test_error(error, token), - None => error, + let error = match terminal_context.account_eligibility() { + AccountEligibilityPolicy::BypassForDiagnostic => crate::transport::connection_test_error(error, &error_token), + AccountEligibilityPolicy::Enforce => crate::transport::client_error(error, &error_token, native_error), + _ => error, }; feedback.record_failure(&selected.account, &model, records_account_feedback, error).await }; diff --git a/backend/crates/providers/antigravity/src/provider/feedback.rs b/backend/crates/providers/antigravity/src/provider/feedback.rs index f2f7ac292..5cde25940 100644 --- a/backend/crates/providers/antigravity/src/provider/feedback.rs +++ b/backend/crates/providers/antigravity/src/provider/feedback.rs @@ -18,42 +18,29 @@ impl AntigravityProvider { records_account_feedback: bool, error: ProviderError, ) -> ProviderError { - if error.send_state() != UpstreamSendState::Sent - || !matches!(error.kind(), Kind::Unauthorized | Kind::RateLimited) - { + if error.send_state() != UpstreamSendState::Sent { return error; } // 明确拒绝没有生成结果;换号仍受 Core 的交付屏障、范围与预算约束 - let error = error.with_replay_safe().with_pre_delivery_retry(); + let error = if !error.retry_is_prohibited() + && matches!( + error.kind(), + Kind::Unauthorized + | Kind::RateLimited + | Kind::QuotaExhausted + | Kind::UpstreamCapacityUnavailable + ) { + error.with_replay_safe().with_pre_delivery_retry() + } else { + error + }; if !records_account_feedback { return error; } + crate::credential::record_account_failure(self.accounts.as_ref(), account, &error).await; let feedback = async { match error.kind() { - Kind::Unauthorized => { - if account.authentication_kind() == crate::credential::api_key::API_KEY { - self.accounts - .apply_state_change(gateway_core::account::AccountStateChange { - account_id: account.id().clone(), - expected_revision: account.revision(), - credential_state: gateway_core::account::CredentialState::Invalid, - observed_at: SystemTime::now(), - error_reason: Some( - gateway_core::account::AccountErrorReason::CredentialInvalid, - ), - message: Some("上游拒绝 API Key".into()), - }) - .await - .map_err(|_| ())?; - return Ok(()); - } - // 资源服务拒绝 AT 不能证明 RT 失效,续期仍由已有 OAuth worker 负责 - self.accounts - .expire_access_token(account, SystemTime::now()) - .await - .map_err(|_| ())?; - } - Kind::RateLimited => { + Kind::RateLimited | Kind::QuotaExhausted | Kind::UpstreamCapacityUnavailable => { if let Some(until) = error .retry_after() .and_then(|delay| SystemTime::now().checked_add(delay)) diff --git a/backend/crates/providers/antigravity/src/transport/client.rs b/backend/crates/providers/antigravity/src/transport/client.rs index 3227b5a29..cfe0b48b2 100644 --- a/backend/crates/providers/antigravity/src/transport/client.rs +++ b/backend/crates/providers/antigravity/src/transport/client.rs @@ -368,7 +368,16 @@ pub(super) async fn control( } data.extend_from_slice(&chunk); } - serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e)) + let document: serde_json::Value = + serde_json::from_slice(&data).map_err(|e| sent(Kind::Protocol).with_source(e))?; + if super::failure::google_error(&document).is_some_and(serde_json::Value::is_object) { + return Err(super::failure::body_error( + None, + &String::from_utf8_lossy(&data), + token, + )); + } + serde_json::from_value(document).map_err(|e| sent(Kind::Protocol).with_source(e)) } #[derive(Deserialize)] diff --git a/backend/crates/providers/antigravity/src/transport/count.rs b/backend/crates/providers/antigravity/src/transport/count.rs index 2486c8718..8d8c307a0 100644 --- a/backend/crates/providers/antigravity/src/transport/count.rs +++ b/backend/crates/providers/antigravity/src/transport/count.rs @@ -35,6 +35,9 @@ pub(crate) fn count_events( body.extend_from_slice(&chunk); } let value: Value = serde_json::from_slice(&body).map_err(|_| sent(Kind::Protocol))?; + if super::failure::google_error(&value).is_some_and(Value::is_object) { + Err(super::failure::body_error(None, &String::from_utf8_lossy(&body), &context.token))?; + } // Cloud Code 的 protobuf JSON 会省略零值;公开计数接口显式交付 totalTokens if value.as_object().is_some_and(serde_json::Map::is_empty) { body = br#"{"totalTokens":0}"#.to_vec(); diff --git a/backend/crates/providers/antigravity/src/transport/failure.rs b/backend/crates/providers/antigravity/src/transport/failure.rs index 88289e469..b0a906216 100644 --- a/backend/crates/providers/antigravity/src/transport/failure.rs +++ b/backend/crates/providers/antigravity/src/transport/failure.rs @@ -2,10 +2,10 @@ use gateway_core::{ error::{ - ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind, - RawUpstreamError, + ClientVisibleUpstreamError, ClientVisibleUpstreamResponse, GatewayError, + OpaqueUpstreamValue, ProviderError, ProviderErrorKind as Kind, RawUpstreamError, }, - upstream::UpstreamSendState, + upstream::{UpstreamFailureFields, UpstreamSendState}, }; use reqwest::{Response, StatusCode}; use serde_json::Value; @@ -44,13 +44,41 @@ fn status_kind(status: StatusCode) -> Kind { } } pub(super) fn body_error(status: Option, body: &str, token: &str) -> ProviderError { - let status = status.and_then(|code| StatusCode::from_u16(code).ok()); - let error = sent(status.map_or(Kind::Unavailable, status_kind)); - let error = if let Some(status) = status { - error.with_status(status.as_u16()) - } else { - error + let document = serde_json::from_str::(body).ok(); + let failure = document.as_ref().and_then(google_error); + let status = status + .filter(|code| (400..=599).contains(code)) + .or_else(|| failure.and_then(rpc_status)); + let fields = UpstreamFailureFields { + status, + code: None, + error_type: None, + message: None, }; + let mut kind = status + .and_then(|code| StatusCode::from_u16(code).ok()) + .map_or(Kind::Unavailable, status_kind); + if matches!(status, Some(429 | 503)) { + match failure + .and_then(error_info) + .and_then(|info| info["reason"].as_str()) + { + Some("MODEL_CAPACITY_EXHAUSTED") if status == Some(503) => { + kind = Kind::UpstreamCapacityUnavailable + } + Some( + "QUOTA_EXHAUSTED" + | "QUOTA_ENDPOINT_EXHAUSTED" + | "QUOTA_PRODUCT_EXHAUSTED" + | "QUOTA_RECIPE_EXHAUSTED", + ) if status == Some(429) => kind = Kind::QuotaExhausted, + _ => {} + } + } + let mut error = sent(kind).with_upstream_failure_fields(fields); + if let Some(status) = status { + error = error.with_status(status); + } attach_body(error, body, token) } fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError { @@ -68,6 +96,34 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError { if body.is_empty() { return error; } + let mut error = error; + if let Ok(document) = serde_json::from_str::(body) + && let Some(failure) = google_error(&document) + { + let info = error_info(failure); + let code = info + .and_then(|info| info["reason"].as_str()) + .map(str::to_owned) + .or_else(|| failure["code"].as_u64().map(|code| code.to_string())); + let status = error.upstream_status(); + error = error.with_upstream_failure_fields(UpstreamFailureFields { + status, + code: code.clone(), + error_type: failure["status"].as_str().map(str::to_owned), + message: failure["message"].as_str().map(str::to_owned), + }); + if let Some(code) = code { + error = error.with_upstream_code(OpaqueUpstreamValue::new(code)); + } + if account_rejection(&error).is_some() + || (error.upstream_status() == Some(403) + && error + .upstream_code() + .is_some_and(|code| request_rejection(code.as_str()))) + { + error = error.with_retry_prohibited(); + } + } let end = body.floor_char_boundary(MAX_ERROR_BYTES.min(body.len())); let text = if end < body.len() { format!("{}\n[truncated]", &body[..end]) @@ -88,7 +144,7 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid let Some(failure) = google_error(&document) else { return error; }; - let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo"); + let info = error_info(failure); let safe_text = |value: &Value| { value .as_str() @@ -117,12 +173,178 @@ pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> Provid )) } -fn google_error(document: &Value) -> Option<&Value> { +pub(super) fn google_error(document: &Value) -> Option<&Value> { document .get("error") .or_else(|| document.pointer("/response/error")) } +fn error_info(error: &Value) -> Option<&Value> { + error + .get("details")? + .as_array()? + .iter() + .filter(|detail| { + detail["@type"] == "type.googleapis.com/google.rpc.ErrorInfo" + && detail["reason"] + .as_str() + .is_some_and(|reason| !reason.is_empty()) + }) + .max_by_key(|detail| { + let reason = detail["reason"].as_str().unwrap_or_default(); + match account_rejection_reason(reason) { + Some(AccountRejection::Banned) => 4, + Some(AccountRejection::VerificationRequired) => 3, + None if request_rejection(reason) => 2, + None => 1, + } + }) +} + +#[derive(Clone, Copy)] +pub(crate) enum AccountRejection { + VerificationRequired, + Banned, +} + +pub(crate) fn account_rejection(error: &ProviderError) -> Option { + if error.send_state() != UpstreamSendState::Sent || error.upstream_status() != Some(403) { + return None; + } + account_rejection_reason(error.upstream_code()?.as_str()) +} + +fn account_rejection_reason(reason: &str) -> Option { + match reason { + "VALIDATION_REQUIRED" => Some(AccountRejection::VerificationRequired), + "TOS_VIOLATION" | "ACCOUNT_SUSPENDED" | "ACCOUNT_DISABLED" | "USER_SUSPENDED" + | "USER_DISABLED" => Some(AccountRejection::Banned), + _ => None, + } +} + +fn request_rejection(reason: &str) -> bool { + matches!( + reason, + "AI_POLICY_REQUIRED" + | "AI_POLICY_SOFT_BLOCK_BANNER" + | "AI_POLICY_SOFT_BLOCK_CLI" + | "UNSUPPORTED_CLIENT" + ) +} + +fn rpc_status(error: &Value) -> Option { + let code = error["code"].as_u64(); + if let Some(code @ 400..=599) = code { + return u16::try_from(code).ok(); + } + match error["status"].as_str() { + Some("INVALID_ARGUMENT" | "FAILED_PRECONDITION" | "OUT_OF_RANGE") => Some(400), + Some("UNAUTHENTICATED") => Some(401), + Some("PERMISSION_DENIED") => Some(403), + Some("NOT_FOUND") => Some(404), + Some("ALREADY_EXISTS" | "ABORTED") => Some(409), + Some("RESOURCE_EXHAUSTED") => Some(429), + Some("CANCELLED") => Some(499), + Some("UNKNOWN" | "INTERNAL" | "DATA_LOSS") => Some(500), + Some("UNIMPLEMENTED") => Some(501), + Some("UNAVAILABLE") => Some(503), + Some("DEADLINE_EXCEEDED") => Some(504), + _ => match code { + Some(1) => Some(499), + Some(2 | 13 | 15) => Some(500), + Some(3 | 9 | 11) => Some(400), + Some(4) => Some(504), + Some(5) => Some(404), + Some(6 | 10) => Some(409), + Some(7) => Some(403), + Some(8) => Some(429), + Some(12) => Some(501), + Some(14) => Some(503), + Some(16) => Some(401), + _ => None, + }, + } +} + +/// 模型客户端只收到协议字段,账号验证链接和其他 metadata 留在受控诊断中 +pub(crate) fn client_error(error: ProviderError, token: &str, native: bool) -> ProviderError { + let error = connection_test_error(error, token); + let Some(status) = error + .upstream_status() + .filter(|status| (400..=599).contains(status)) + else { + return error; + }; + let gateway = GatewayError::from_provider(&error); + let detail = error.client_visible_upstream_error(); + let message = detail.map_or(gateway.safe_message(), ClientVisibleUpstreamError::message); + let code = detail.and_then(ClientVisibleUpstreamError::code); + let body = if native { + let rpc = match status { + 400 | 413 | 422 => "INVALID_ARGUMENT", + 401 => "UNAUTHENTICATED", + 403 => "PERMISSION_DENIED", + 404 => "NOT_FOUND", + 408 | 504 => "DEADLINE_EXCEEDED", + 409 => "ABORTED", + 429 => "RESOURCE_EXHAUSTED", + 499 => "CANCELLED", + 501 => "UNIMPLEMENTED", + 502 | 503 => "UNAVAILABLE", + _ => "INTERNAL", + }; + let mut body = serde_json::json!({"error":{"code":status,"status":rpc,"message":message}}); + if let Some(kind) = detail.and_then(ClientVisibleUpstreamError::error_type) { + body["error"]["status"] = Value::String(kind.into()); + } + if let Some(code) = code { + body["error"]["details"] = serde_json::json!([{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":code}]); + } + if let Some(delay) = error.retry_after() { + let detail = serde_json::json!({"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":format!("{}.{:09}s", delay.as_secs(), delay.subsec_nanos())}); + let details = body["error"].as_object_mut().and_then(|error| { + error + .entry("details") + .or_insert_with(|| serde_json::json!([])) + .as_array_mut() + }); + if let Some(details) = details { + details.push(detail); + } + } + body + } else { + serde_json::json!({"error":{"message":message,"type":detail.and_then(ClientVisibleUpstreamError::error_type).unwrap_or("upstream_error"),"code":code}}) + }; + let mut response = ClientVisibleUpstreamResponse::new( + status, + Some(b"application/json".to_vec()), + body.to_string().into(), + ); + if let Some(delay) = error.retry_after() { + let seconds = delay + .as_secs() + .saturating_add(u64::from(delay.subsec_nanos() != 0)); + response = response.with_headers(vec![gateway_core::event::ProviderResponseHeader::new( + "retry-after", + seconds.to_string().into(), + )]); + } + let error = error.with_client_visible_upstream_response(response); + if native + && let Ok(wire) = gateway_core::event::ProtocolWireEvent::json( + gateway_protocol::genai::GENAI_PROTOCOL, + None, + body, + ) + { + return error + .with_atomic_client_events(vec![gateway_core::event::ProviderEvent::wire(wire)]); + } + error +} + fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> { error .get("details")? @@ -177,10 +399,6 @@ pub(super) async fn successful( .get(reqwest::header::RETRY_AFTER) .and_then(|v| v.to_str().ok()) .and_then(retry_after); - let mut error = sent(status_kind(status)).with_status(status.as_u16()); - if let Some(delay) = retry_after { - error = error.with_retry_after(delay); - } let mut body = Vec::new(); let mut truncated = false; let read = tokio::time::timeout(Duration::from_secs(10), async { @@ -195,14 +413,25 @@ pub(super) async fn successful( Ok::<_, reqwest::Error>(()) }) .await; + let text = String::from_utf8_lossy(&body).into_owned(); + let mut error = body_error( + Some(status.as_u16()), + if truncated { "" } else { &text }, + token, + ); + if let Some(delay) = retry_after { + let delay = error + .retry_after() + .map_or(delay, |current| current.max(delay)); + error = error.with_retry_after(delay); + } match read { Ok(Ok(())) => {} Ok(Err(source)) => error = error.with_source(source.without_url()), Err(source) => error = error.with_source(source), } - let text = String::from_utf8_lossy(&body).into_owned(); if truncated { return Err(error.redact_sensitive_context(&text)); } - Err(attach_body(error, &text, token)) + Err(error) } diff --git a/backend/crates/providers/antigravity/src/transport/mod.rs b/backend/crates/providers/antigravity/src/transport/mod.rs index 3985db8ca..fa5129dc0 100644 --- a/backend/crates/providers/antigravity/src/transport/mod.rs +++ b/backend/crates/providers/antigravity/src/transport/mod.rs @@ -14,7 +14,9 @@ mod tool_ids; pub(crate) use api_key::GenAiClient; pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame}; pub(crate) use count::count_events; -pub(crate) use failure::{connection_test_error, sent, unsent}; +pub(crate) use failure::{ + AccountRejection, account_rejection, client_error, connection_test_error, sent, unsent, +}; pub(crate) use headers::request_headers; pub(crate) use pool::ClientPool; pub(crate) use response::{ResponseContext, events, genai_events}; diff --git a/backend/crates/providers/antigravity/tests/credential/mod.rs b/backend/crates/providers/antigravity/tests/credential/mod.rs index 7c6cd7c41..46f696b82 100644 --- a/backend/crates/providers/antigravity/tests/credential/mod.rs +++ b/backend/crates/providers/antigravity/tests/credential/mod.rs @@ -8,12 +8,17 @@ mod api_key_tests; mod authorization; #[path = "../../src/credential/documents.rs"] mod documents; +#[path = "../../src/credential/failure.rs"] +mod failure; +pub(crate) use failure::record_account_failure; #[path = "../../src/credential/model_groups.rs"] mod model_groups; #[path = "../../src/credential/oauth.rs"] pub(crate) mod oauth; #[path = "../../src/credential/refresh.rs"] mod refresh; +#[path = "refresh.rs"] +mod refresh_tests; #[path = "../../src/credential/service.rs"] mod service; pub(crate) use authorization::AuthorizationService; diff --git a/backend/crates/providers/antigravity/tests/credential/refresh.rs b/backend/crates/providers/antigravity/tests/credential/refresh.rs new file mode 100644 index 000000000..706847e99 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/credential/refresh.rs @@ -0,0 +1,58 @@ +//! OAuth 续期保留资源服务拒绝,旧凭据反馈不能污染新授权 + +use super::documents_tests::fixture; +use gateway_core::account::{AccountErrorReason, CredentialState, PlaintextCredential}; +use serde_json::json; +use wiremock::{Mock, ResponseTemplate, matchers::path}; + +#[tokio::test] +async fn token_refresh_preserves_a_denial_recorded_while_refresh_was_in_flight() { + let (server, credentials, store) = fixture().await; + let loaded = { + let mut loaded = store.primary().loaded.lock().unwrap(); + let mut material = loaded.credential.expose_to_provider().clone(); + material.insert( + "registration".into(), + json!(credentials.oauth.registration()), + ); + loaded.credential = PlaintextCredential::new(material); + loaded.clone() + }; + Mock::given(path("/token")).respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "access_token":"fresh-access","token_type":"Bearer","expires_in":3600,"scope":"email fixture-resource" + }))).expect(2).mount(&server).await; + { + let mut current = store.primary().loaded.lock().unwrap(); + current.account = current.account.clone().with_account_facts( + true, + CredentialState::Invalid, + current.account.quota(), + Some(AccountErrorReason::AccountUnverified), + Some("需验证".into()), + ); + } + let prepared = credentials.refresh_current(&loaded).await.unwrap(); + assert!(prepared.facts().preserve_credential_state); + drop(prepared); + let revision = credentials.refresh_due(&loaded).await.unwrap(); + let stale = gateway_core::error::ProviderError::new( + gateway_core::error::ProviderErrorKind::PermissionDenied, + gateway_core::upstream::UpstreamSendState::Sent, + ) + .with_status(403) + .with_upstream_code(gateway_core::error::OpaqueUpstreamValue::new( + "TOS_VIOLATION", + )); + super::record_account_failure(store.as_ref(), &loaded.account, &stale).await; + let current = store.primary().loaded.lock().unwrap(); + assert_eq!(current.account.revision(), revision); + assert_eq!(current.account.credential_state(), CredentialState::Invalid); + assert_eq!( + current.account.last_error_reason(), + Some(AccountErrorReason::AccountUnverified) + ); + assert_eq!( + current.credential.expose_to_provider()["access_token"], + "fresh-access" + ); +} diff --git a/backend/crates/providers/antigravity/tests/provider/execution.rs b/backend/crates/providers/antigravity/tests/provider/execution.rs index 01c8b27ef..1b54b6afe 100644 --- a/backend/crates/providers/antigravity/tests/provider/execution.rs +++ b/backend/crates/providers/antigravity/tests/provider/execution.rs @@ -528,13 +528,14 @@ async fn connection_probe_reports_google_rejection_without_verification_links() async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() { for (status, kind) in [ (401, ProviderErrorKind::Unauthorized), + (403, ProviderErrorKind::PermissionDenied), (429, ProviderErrorKind::RateLimited), ] { let upstream = MockServer::start().await; mock_project(&upstream).await; Mock::given(path("/v1internal:generateContent")) .and(body_partial_json(json!({"project":"probe-project"}))) - .respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30")) + .respond_with(ResponseTemplate::new(status).insert_header("retry-after", "30").set_body_json(if status == 403 {json!({"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}})} else {json!({})})) .expect(1) .mount(&upstream) .await; @@ -560,6 +561,17 @@ async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feed assert_eq!(error.upstream_status(), Some(status)); assert!(!fixture.store.expired.load(Ordering::SeqCst)); assert!(fixture.store.cooldowns.lock().unwrap().is_empty()); + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .credential_state(), + CredentialState::Ready + ); assert_eq!( fixture .feedback diff --git a/backend/crates/providers/antigravity/tests/provider/feedback.rs b/backend/crates/providers/antigravity/tests/provider/feedback.rs new file mode 100644 index 000000000..d0a11a234 --- /dev/null +++ b/backend/crates/providers/antigravity/tests/provider/feedback.rs @@ -0,0 +1,454 @@ +//! Google 拒绝的协议交付、账号范围与查询反馈合同 + +use crate::support::{Fixture, context, request}; +use futures::TryStreamExt; +use gateway_core::{ + account::{AccountErrorReason, CredentialState, ProviderAccountId, ProviderAccountStore}, + engine::provider::Provider, + error::ProviderErrorKind as Kind, + lifecycle::CancellationToken, +}; +use serde_json::json; +use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path}; + +#[tokio::test] +async fn a_late_stream_denial_finishes_with_an_error_frame_and_disables_the_account() { + let server = MockServer::start().await; + let rejection = json!({"error":{"code":7,"status":"PERMISSION_DENIED","message":"Verify account.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}}); + let body = format!( + "data: {}\n\ndata: {rejection}\n\n", + json!({"response":{"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}}) + ); + Mock::given(path("/v1internal:streamGenerateContent")) + .respond_with(ResponseTemplate::new(200).set_body_raw(body, "text/event-stream")) + .expect(1) + .mount(&server) + .await; + let fixture = Fixture::new(&server.uri()); + let mut stream = fixture + .provider + .clone() + .execute( + request(true), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await + .unwrap(); + let first = stream.try_next().await.unwrap().unwrap(); + assert!( + first + .wire_event() + .unwrap() + .data() + .to_string() + .contains("partial") + ); + let mut error = stream.try_next().await.unwrap_err(); + assert!(error.retry_is_prohibited()); + let events = error.take_atomic_client_events(); + assert_eq!(events.len(), 1); + assert_eq!( + events[0].wire_event().unwrap().data()["error"]["details"][0]["reason"], + "VALIDATION_REQUIRED" + ); + assert!(stream.try_next().await.unwrap().is_none()); + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .credential_state(), + CredentialState::Invalid + ); +} + +#[tokio::test] +async fn count_tokens_recognizes_a_success_status_containing_an_rpc_denial() { + use gateway_core::{ + engine::provider::ProviderRequest, + operation::{Operation, RawJsonPayload, TokenCountRequest}, + }; + let server = MockServer::start().await; + Mock::given(path("/v1internal:countTokens")).respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}}))).expect(1).mount(&server).await; + let fixture = Fixture::new(&server.uri()); + let input = ProviderRequest::new( + Operation::CountTokens(TokenCountRequest::from_raw_json( + RawJsonPayload::new("genai", br#"{"contents":[]}"#.as_slice().into()).unwrap(), + )), + request(false).candidate().clone(), + ); + let error = fixture + .provider + .clone() + .execute( + input, + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap_err(); + assert_eq!(error.kind(), Kind::PermissionDenied); + assert_eq!( + error.client_visible_upstream_response().unwrap().status(), + 403 + ); + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .last_error_reason(), + Some(AccountErrorReason::AccountUnverified) + ); +} + +#[tokio::test] +async fn structured_denials_preserve_protocol_and_only_suspend_the_confirmed_account() { + for (status, reason, state, error_reason) in [ + ( + 403, + "VALIDATION_REQUIRED", + CredentialState::Invalid, + Some(AccountErrorReason::AccountUnverified), + ), + ( + 403, + "TOS_VIOLATION", + CredentialState::Banned, + Some(AccountErrorReason::AccountBanned), + ), + ( + 403, + "ACCESS_TOKEN_SCOPE_INSUFFICIENT", + CredentialState::Ready, + None, + ), + (403, "PROJECT_DISABLED", CredentialState::Ready, None), + (403, "AI_POLICY_REQUIRED", CredentialState::Ready, None), + ( + 200, + "VALIDATION_REQUIRED", + CredentialState::Invalid, + Some(AccountErrorReason::AccountUnverified), + ), + ] { + let server = MockServer::start().await; + let mut body = json!({"error":{"code": if status == 200 {7} else {403},"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":[ + {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"ACCESS_TOKEN_SCOPE_INSUFFICIENT"}, + {"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason,"metadata":{"validation_url":"https://accounts.example.test/verify?nonce=private"}} + ]}}); + if reason == "TOS_VIOLATION" { + body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"})); + } else if reason == "AI_POLICY_REQUIRED" { + body["error"]["details"].as_array_mut().unwrap().push(json!({"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"PROJECT_DISABLED"})); + } + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(status).set_body_json(body)) + .expect(1) + .mount(&server) + .await; + let fixture = Fixture::with_two_accounts(&server.uri()); + let mut error = fixture + .provider + .clone() + .execute( + request(false), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap_err(); + assert_eq!(error.kind(), Kind::PermissionDenied); + assert_eq!(error.upstream_status(), Some(403)); + assert_eq!( + error.retry_is_prohibited(), + error_reason.is_some() || reason == "AI_POLICY_REQUIRED" + ); + let fields = error.upstream_failure_fields().unwrap(); + assert_eq!(fields.code.as_deref(), Some(reason)); + let response = error.client_visible_upstream_response().unwrap(); + assert_eq!(response.status(), 403); + let response: serde_json::Value = serde_json::from_slice(response.body()).unwrap(); + assert_eq!(response["error"]["code"], 403); + assert_eq!(response["error"]["status"], "PERMISSION_DENIED"); + assert_eq!(response["error"]["details"][0]["reason"], reason); + assert!(!response.to_string().contains("nonce=private")); + assert!( + error + .raw_upstream_error() + .unwrap() + .as_str() + .contains("nonce=private") + ); + let events = error.take_atomic_client_events(); + assert_eq!(events.len(), 1); + assert_eq!(events[0].wire_event().unwrap().data(), &response); + { + let loaded = fixture.store.primary().loaded.lock().unwrap(); + assert_eq!(loaded.account.credential_state(), state); + assert_eq!(loaded.account.last_error_reason(), error_reason); + } + let standby = fixture + .store + .get_account(&ProviderAccountId::new("acct_standby").unwrap()) + .await + .unwrap() + .unwrap(); + assert_eq!(standby.credential_state(), CredentialState::Ready); + if error_reason.is_some() { + assert_eq!( + fixture + .provider + .clone() + .execute( + request(false), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new() + ) + ) + .await + .err() + .unwrap() + .kind(), + Kind::NoEligibleAccount + ); + } + } +} + +#[tokio::test] +async fn untyped_and_sensitive_denials_cannot_change_account_state_or_escape_diagnostics() { + for (typed, message) in [(false, "VALIDATION_REQUIRED"), (true, "fixture-access")] { + let server = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(403).set_body_json(json!({"error":{"status":"PERMISSION_DENIED","message":message,"details":[{"@type":if typed {"type.googleapis.com/google.rpc.ErrorInfo"} else {"unknown"},"reason":"VALIDATION_REQUIRED"}]}}))) + .expect(1).mount(&server).await; + let fixture = Fixture::new(&server.uri()); + let error = fixture + .provider + .clone() + .execute( + request(false), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap_err(); + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .credential_state(), + CredentialState::Ready + ); + assert!(error.upstream_code().is_none()); + assert!( + !String::from_utf8_lossy(error.client_visible_upstream_response().unwrap().body()) + .contains("fixture-access") + ); + assert_eq!(error.raw_upstream_error().is_some(), !typed); + } +} + +#[tokio::test] +async fn resource_queries_share_denial_state_and_background_queries_stop() { + for (quota, api_key) in [(false, false), (true, false), (false, true)] { + let server = MockServer::start().await; + Mock::given(path(if api_key {"/v1beta/models"} else {"/v1internal:loadCodeAssist"})) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"error":{"code":7,"status":"PERMISSION_DENIED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"VALIDATION_REQUIRED"}]}}))) + .expect(1).mount(&server).await; + let fixture = Fixture::new(&server.uri()); + if api_key { + fixture + .store + .use_api_key(&format!("{}/v1beta", server.uri())); + } + let account = fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .clone(); + if quota { + assert!(fixture.quota.refresh(account.id()).await.is_err()); + } else { + assert!( + fixture + .catalog + .account_models(account.id(), true) + .await + .is_err() + ); + } + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .last_error_reason(), + Some(AccountErrorReason::AccountUnverified) + ); + *fixture.store.primary().catalog.lock().unwrap() = None; + if !api_key { + fixture + .quota + .reconcile(&CancellationToken::new()) + .await + .unwrap(); + } + fixture + .catalog + .reconcile(&CancellationToken::new()) + .await + .unwrap(); + fixture + .catalog + .account_models(account.id(), false) + .await + .unwrap(); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } +} + +#[tokio::test] +async fn quota_capacity_and_symbolic_rpc_errors_keep_distinct_facts() { + for (status, code, rpc, reason, kind, mapped) in [ + ( + 429, + Some(429), + "RESOURCE_EXHAUSTED", + "QUOTA_EXHAUSTED", + Kind::QuotaExhausted, + 429, + ), + ( + 429, + Some(429), + "RESOURCE_EXHAUSTED", + "MODEL_CAPACITY_EXHAUSTED", + Kind::RateLimited, + 429, + ), + ( + 503, + Some(503), + "UNAVAILABLE", + "MODEL_CAPACITY_EXHAUSTED", + Kind::UpstreamCapacityUnavailable, + 503, + ), + ( + 200, + Some(8), + "RESOURCE_EXHAUSTED", + "RATE_LIMIT_EXCEEDED", + Kind::RateLimited, + 429, + ), + ( + 200, + None, + "PERMISSION_DENIED", + "ACCESS_TOKEN_SCOPE_INSUFFICIENT", + Kind::PermissionDenied, + 403, + ), + ] { + let server = MockServer::start().await; + Mock::given(path("/v1internal:generateContent")) + .respond_with(ResponseTemplate::new(status).set_body_json(json!({"error":{"code":code,"status":rpc,"message":"Rejected.","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":reason},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"30s"}]}}))) + .expect(1).mount(&server).await; + let fixture = Fixture::new(&server.uri()); + let error = fixture + .provider + .clone() + .execute( + request(false), + context( + crate::profile::Selection::default() + .resolve("2.34.0") + .frozen(), + CancellationToken::new(), + ), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap_err(); + assert_eq!(error.kind(), kind); + assert_eq!(error.upstream_status(), Some(mapped)); + let response = error.client_visible_upstream_response().unwrap(); + let body: serde_json::Value = serde_json::from_slice(response.body()).unwrap(); + assert_eq!(body["error"]["details"][1]["retryDelay"], "30.000000000s"); + assert!( + response + .headers() + .iter() + .any(|header| header.name() == "retry-after" && header.value().as_ref() == b"30") + ); + assert_eq!( + error.upstream_failure_fields().unwrap().code.as_deref(), + Some(reason) + ); + assert_eq!( + fixture + .store + .primary() + .loaded + .lock() + .unwrap() + .account + .credential_state(), + CredentialState::Ready + ); + assert_eq!( + fixture.store.cooldowns.lock().unwrap().len(), + usize::from(mapped != 403) + ); + } +} diff --git a/backend/crates/providers/antigravity/tests/provider/mod.rs b/backend/crates/providers/antigravity/tests/provider/mod.rs index d92d91162..bd5e6b58a 100644 --- a/backend/crates/providers/antigravity/tests/provider/mod.rs +++ b/backend/crates/providers/antigravity/tests/provider/mod.rs @@ -3,6 +3,7 @@ mod affinity; mod api_key; mod execution; +mod feedback; mod headers; mod middleware; mod round_robin; diff --git a/backend/crates/providers/antigravity/tests/support/ports.rs b/backend/crates/providers/antigravity/tests/support/ports.rs index e701c053b..e5d7a0bd0 100644 --- a/backend/crates/providers/antigravity/tests/support/ports.rs +++ b/backend/crates/providers/antigravity/tests/support/ports.rs @@ -144,7 +144,7 @@ impl ProviderCredentialStatePort for MemoryPorts { &'a self, _account_id: &'a ProviderAccountId, ) -> BoxFuture<'a, Result<(), ProviderStoreError>> { - unreachable!("unused fixture port: ProviderCredentialStatePort::clear_refresh_backoff") + Box::pin(async { Ok(()) }) } } @@ -548,9 +548,43 @@ impl ProviderAccountStore for MemoryPorts { } async fn compare_and_swap_credential( &self, - _update: CredentialCasUpdate, + update: CredentialCasUpdate, ) -> Result { - unreachable!("unused fixture port: ProviderAccountStore::compare_and_swap_credential") + let update = update.into_parts(); + let entry = &self.accounts[&update.account_id]; + let mut loaded = entry.loaded.lock().unwrap(); + if loaded.account.revision() != update.expected_revision { + return Ok(CredentialCasOutcome::Conflict); + } + let revision = CredentialRevision::new(update.expected_revision.get() + 1).unwrap(); + let previous = &loaded.account; + let (state, reason, message) = update.account_state.map_or_else( + || { + ( + previous.credential_state(), + previous.last_error_reason(), + previous.last_error_message().map(str::to_owned), + ) + }, + |state| (state.credential_state, state.error_reason, state.message), + ); + loaded.account = ProviderAccount::new( + previous.id().clone(), + previous.provider().clone(), + previous.name().into(), + previous.upstream_user_id().map(str::to_owned), + previous.authentication_kind().into(), + revision, + if update.preserve_access_token_expiry { + previous.access_token_expires_at() + } else { + update.access_token_expires_at + }, + ) + .with_account_facts(previous.enabled(), state, previous.quota(), reason, message) + .with_refresh_schedule(update.has_refresh_token, update.next_refresh_at); + loaded.credential = update.credential; + Ok(CredentialCasOutcome::Updated(revision)) } async fn get_quotas( &self, diff --git a/docs/api.md b/docs/api.md index f0c1f9f6e..a0f12e723 100644 --- a/docs/api.md +++ b/docs/api.md @@ -268,6 +268,8 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的 OAuth 普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 Cloud Code SSE 数据帧。API Key 直接保留 GenAI JSON 和 SSE 数据正文。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果和未知字段;OAuth 的思考签名按下述来源规则处理,API Key 不改写签名。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content) +上游结构化拒绝保留 HTTP 状态、`ErrorInfo.reason` 和重试时间;HTTP 200 中的 RPC 错误按同一规则处理。已开始交付的原生流通过 SSE 错误帧结束,不重放已输出内容。账号验证链接及其他错误 metadata 仅保留在受控诊断中,不发送给模型客户端 + CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;OAuth 的认证、项目和 UA 由所选账号与冻结画像生成;API Key 仅使用所选账号的 `x-goog-api-key`,不附带 Google 项目或 AGY 画像。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters) 以下提示词、工具 ID 和签名处理只适用于 OAuth Cloud Code 上游,API Key 保留调用方原生正文。 diff --git a/docs/architecture.md b/docs/architecture.md index bf0d5bd27..13fdc3b81 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1138,6 +1138,7 @@ OpenAI、xAI、Antigravity 的 OAuth 认证及账号后台操作由各 Provider Provider 在额度观测中保存与同次模型目录核对的分组成员 ID。Admin 按模型和窗口边界汇总本地 Token,账号用量另按部署时区今天及前 6 天统计,展示为“近一周”。选号及互联分别读取同一份模型额度事实,失效观测保持未知。 账号列表和展开的额度面板读取已保存的快照,点击“刷新额度”时立即查询上游。后台补齐启用账号缺失或凭据版本失效的快照。健康账号仅在距上次观测已满 5 分钟、且有生成请求在该次观测后成功完成时补查。整号耗尽按重置时间复查,缺少重置时间时在耗尽观测满 5 分钟后复查 正常续期后续接同一身份的目录,保留原观测时间并校验新凭据版本与套餐;目录缺失立即尝试重新发现,失败由后台重试 + 生成、计数、目录和额度查询共用 Google 结构化错误分类。明确的账号验证要求写入 `invalid/account_unverified`,账号停用写入 `banned/account_banned`;普通权限拒绝不推断为账号封禁。后台目录和额度查询跳过这些账号,管理员完成上游验证后显式恢复账号状态。普通令牌续期保留提交时的访问状态,不能解除在途请求确认的拒绝 - 账号导入和 OAuth complete(包括重新授权)在凭据提交、Provider 缓存失效与运行快照发布后, 由 Admin 共用流程后台读取一次额度;不等待观测完成才返回管理请求,失败记录告警但不回滚账号事务。 同身份重新授权在事务内保留额度观测和按桶预热进度,旧凭据版本的在途观测无法覆盖新版本。