mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-01 08:01:06 +00:00
fix(antigravity): explain Google account connection test failures
Refs #805 Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -1342,7 +1342,8 @@ impl AccountsService for DefaultAccountsService {
|
||||
.map(ToOwned::to_owned);
|
||||
let upstream_body = error
|
||||
.upstream_response()
|
||||
.map(|response| String::from_utf8_lossy(response.body()).into_owned());
|
||||
.and_then(gateway_core::engine::probe::AccountProbeUpstreamResponse::body)
|
||||
.map(|body| String::from_utf8_lossy(body).into_owned());
|
||||
let message = error.client_message().to_owned();
|
||||
vec![AccountConnectionTestEvent::Failed {
|
||||
source: error.source(),
|
||||
|
||||
@@ -1547,11 +1547,8 @@ impl DefaultExecutionService {
|
||||
) -> AccountProbeError {
|
||||
let (source, send_state, upstream_response) = match error {
|
||||
EngineError::Provider(provider_error) => {
|
||||
let upstream_response = provider_error
|
||||
.client_visible_upstream_response()
|
||||
.map(AccountProbeUpstreamResponse::from_client_response);
|
||||
let upstream_response = AccountProbeUpstreamResponse::from_provider(provider_error);
|
||||
let has_upstream_facts = provider_error.send_state() != UpstreamSendState::NotSent
|
||||
|| provider_error.upstream_status().is_some()
|
||||
|| provider_error.upstream_code().is_some()
|
||||
|| provider_error.client_visible_upstream_error().is_some()
|
||||
|| upstream_response.is_some();
|
||||
|
||||
@@ -5,9 +5,7 @@ use std::fmt;
|
||||
use bytes::Bytes;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
use crate::error::{
|
||||
ClientVisibleUpstreamResponse, GatewayError, GatewayErrorKind, ProxyConnectionHint,
|
||||
};
|
||||
use crate::error::{GatewayError, GatewayErrorKind, ProviderError, ProxyConnectionHint};
|
||||
use crate::identity::ProviderKind;
|
||||
use crate::routing::UpstreamModelId;
|
||||
use crate::{
|
||||
@@ -60,16 +58,18 @@ pub struct AccountProbeResult {
|
||||
pub struct AccountProbeUpstreamResponse {
|
||||
status: u16,
|
||||
content_type: Option<Vec<u8>>,
|
||||
body: Bytes,
|
||||
body: Option<Bytes>,
|
||||
}
|
||||
|
||||
impl AccountProbeUpstreamResponse {
|
||||
pub(crate) fn from_client_response(response: &ClientVisibleUpstreamResponse) -> Self {
|
||||
Self {
|
||||
status: response.status(),
|
||||
content_type: response.content_type().map(<[u8]>::to_vec),
|
||||
body: response.body().clone(),
|
||||
}
|
||||
pub(crate) fn from_provider(error: &ProviderError) -> Option<Self> {
|
||||
let response = error.client_visible_upstream_response();
|
||||
// 即使没有可展示的响应正文,Provider 收到的状态码仍可用于诊断
|
||||
Some(Self {
|
||||
status: response.map(|r| r.status()).or(error.upstream_status())?,
|
||||
content_type: response.and_then(|r| r.content_type()).map(<[u8]>::to_vec),
|
||||
body: response.map(|r| r.body().clone()),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
@@ -83,8 +83,8 @@ impl AccountProbeUpstreamResponse {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn body(&self) -> &Bytes {
|
||||
&self.body
|
||||
pub const fn body(&self) -> Option<&Bytes> {
|
||||
self.body.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ impl fmt::Debug for AccountProbeUpstreamResponse {
|
||||
"content_type",
|
||||
&self.content_type.as_ref().map(|_| "<present>"),
|
||||
)
|
||||
.field("body", &"<redacted>")
|
||||
.field("body", &self.body.as_ref().map(|_| "<redacted>"))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3509,8 +3509,10 @@ fn account_probe_should_not_write_to_the_persistent_execution_store() {
|
||||
#[test]
|
||||
fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
let store = Arc::new(TrackingExecutionStore::default());
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([
|
||||
Arc::new(FailingProvider { include_body: true }) as Arc<dyn Provider>
|
||||
])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3547,7 +3549,9 @@ fn probe_failures_should_be_observable_without_a_model_request_row() {
|
||||
);
|
||||
assert_eq!(
|
||||
upstream.body(),
|
||||
&Bytes::from_static(br#"{"error":{"message":"source upstream failure"}}"#),
|
||||
Some(&Bytes::from_static(
|
||||
br#"{"error":{"message":"source upstream failure"}}"#
|
||||
)),
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("source upstream failure"));
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
@@ -3687,8 +3691,10 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
fail_probe_observation: AtomicBool::new(true),
|
||||
..TrackingExecutionStore::default()
|
||||
});
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let providers = ProviderRegistry::new([Arc::new(FailingProvider {
|
||||
include_body: false,
|
||||
}) as Arc<dyn Provider>])
|
||||
.expect("provider registry");
|
||||
let service = DefaultExecutionService::new(
|
||||
RuntimeSnapshotHandle::new(probe_snapshot()),
|
||||
store.clone(),
|
||||
@@ -3715,9 +3721,15 @@ fn probe_observation_store_failure_preserves_the_provider_error() {
|
||||
assert_eq!(error.kind(), GatewayErrorKind::UpstreamUnavailable);
|
||||
assert!(!store.touched.load(Ordering::SeqCst));
|
||||
assert!(store.probe_failures().is_empty());
|
||||
let upstream = error.upstream_response().unwrap();
|
||||
assert_eq!(upstream.status(), 403);
|
||||
assert!(upstream.body().is_none());
|
||||
assert!(upstream.content_type().is_none());
|
||||
}
|
||||
|
||||
struct FailingProvider;
|
||||
struct FailingProvider {
|
||||
include_body: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CatalogProvider {
|
||||
@@ -4055,6 +4067,13 @@ impl Provider for FailingProvider {
|
||||
_request: ProviderRequest,
|
||||
_context: AttemptContext,
|
||||
) -> Result<ProviderStream, ProviderError> {
|
||||
if !self.include_body {
|
||||
return Err(ProviderError::new(
|
||||
ProviderErrorKind::PermissionDenied,
|
||||
UpstreamSendState::Sent,
|
||||
)
|
||||
.with_status(403));
|
||||
}
|
||||
Err(
|
||||
ProviderError::new(ProviderErrorKind::Transport, UpstreamSendState::NotSent)
|
||||
.with_client_visible_upstream_response(ClientVisibleUpstreamResponse::new(
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::{AntigravityProvider, candidates::Project};
|
||||
use crate::transport::unsent;
|
||||
use futures::StreamExt;
|
||||
use gateway_core::{
|
||||
account::AccountEligibilityPolicy,
|
||||
engine::{
|
||||
AttemptContext,
|
||||
provider::{
|
||||
@@ -122,7 +123,13 @@ impl AntigravityProvider {
|
||||
if deadline.is_elapsed() {
|
||||
Err(unsent(Kind::Timeout))?;
|
||||
}
|
||||
let probe_token = (terminal_context.account_eligibility() == AccountEligibilityPolicy::BypassForDiagnostic)
|
||||
.then(|| selected.material.access_token.clone());
|
||||
let record_failure = async |error| {
|
||||
let error = match &probe_token {
|
||||
Some(token) => crate::transport::connection_test_error(error, token),
|
||||
None => error,
|
||||
};
|
||||
feedback.record_failure(&selected.account, &model, records_account_feedback, error).await
|
||||
};
|
||||
let response = tokio::select! {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
//! 保留上游错误事实与本地来源,敏感凭据不得进入运维正文
|
||||
|
||||
use gateway_core::{
|
||||
error::{ProviderError, ProviderErrorKind as Kind, RawUpstreamError},
|
||||
error::{
|
||||
ClientVisibleUpstreamError, GatewayError, ProviderError, ProviderErrorKind as Kind,
|
||||
RawUpstreamError,
|
||||
},
|
||||
upstream::UpstreamSendState,
|
||||
};
|
||||
use reqwest::{Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
const MAX_ERROR_BYTES: usize = 64 * 1024;
|
||||
@@ -73,15 +77,66 @@ fn attach_body(error: ProviderError, body: &str, token: &str) -> ProviderError {
|
||||
error.with_raw_upstream_error(RawUpstreamError::new(text))
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let error = document
|
||||
/// 连接测试只取 Google 的错误字段,验证链接和其他 metadata 留在受控详情中
|
||||
pub(crate) fn connection_test_error(error: ProviderError, token: &str) -> ProviderError {
|
||||
let Some(document) = error
|
||||
.raw_upstream_error()
|
||||
.and_then(|raw| serde_json::from_str::<Value>(raw.as_str()).ok())
|
||||
else {
|
||||
return error;
|
||||
};
|
||||
let Some(failure) = google_error(&document) else {
|
||||
return error;
|
||||
};
|
||||
let info = google_error_detail(failure, "type.googleapis.com/google.rpc.ErrorInfo");
|
||||
let safe_text = |value: &Value| {
|
||||
value
|
||||
.as_str()
|
||||
.filter(|s| {
|
||||
!s.trim().is_empty()
|
||||
&& !s.contains("://")
|
||||
&& (token.is_empty() || !s.contains(token))
|
||||
})
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let code = info.and_then(|detail| safe_text(&detail["reason"]));
|
||||
let error_type = safe_text(&failure["status"]);
|
||||
let message = info
|
||||
.and_then(|detail| safe_text(&detail["metadata"]["validation_error_message"]))
|
||||
.or_else(|| safe_text(&failure["message"]));
|
||||
if code.is_none() && error_type.is_none() && message.is_none() {
|
||||
return error;
|
||||
}
|
||||
let message = message.unwrap_or_else(|| {
|
||||
GatewayError::from_provider(&error)
|
||||
.safe_message()
|
||||
.to_owned()
|
||||
});
|
||||
error.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
||||
message, code, error_type,
|
||||
))
|
||||
}
|
||||
|
||||
fn google_error(document: &Value) -> Option<&Value> {
|
||||
document
|
||||
.get("error")
|
||||
.or_else(|| document.pointer("/response/error"))?;
|
||||
let detail = error.get("details")?.as_array()?.iter().find(|detail| {
|
||||
detail.get("@type").and_then(serde_json::Value::as_str)
|
||||
== Some("type.googleapis.com/google.rpc.RetryInfo")
|
||||
})?;
|
||||
.or_else(|| document.pointer("/response/error"))
|
||||
}
|
||||
|
||||
fn google_error_detail<'a>(error: &'a Value, kind: &str) -> Option<&'a Value> {
|
||||
error
|
||||
.get("details")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|detail| detail["@type"] == kind)
|
||||
}
|
||||
|
||||
fn retry_info(body: &str) -> Option<Duration> {
|
||||
let document: Value = serde_json::from_str(body).ok()?;
|
||||
let detail = google_error_detail(
|
||||
google_error(&document)?,
|
||||
"type.googleapis.com/google.rpc.RetryInfo",
|
||||
)?;
|
||||
let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?;
|
||||
let (seconds, fraction) = delay.split_once('.').unwrap_or((delay, ""));
|
||||
if seconds.is_empty()
|
||||
|
||||
@@ -12,7 +12,7 @@ mod signatures;
|
||||
mod tool_ids;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
pub(crate) use failure::{connection_test_error, sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
pub(crate) use pool::ClientPool;
|
||||
pub(crate) use response::{ResponseContext, events};
|
||||
|
||||
@@ -455,6 +455,75 @@ async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connection_probe_reports_google_rejection_without_verification_links() {
|
||||
let details = json!([{
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": "VALIDATION_REQUIRED",
|
||||
"metadata": {"validation_error_message": "Complete SMS verification.", "validation_url": "https://accounts.example.test/verify?nonce=private"}
|
||||
}]);
|
||||
for (status, body, reason, message) in [
|
||||
(401, json!({}), None, None),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Access denied."}}),
|
||||
None,
|
||||
Some("Access denied."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"status":"PERMISSION_DENIED","message":"Verify your account to continue.","details":details}}),
|
||||
Some("VALIDATION_REQUIRED"),
|
||||
Some("Complete SMS verification."),
|
||||
),
|
||||
(
|
||||
403,
|
||||
json!({"error":{"message":"fixture-access","details":details}}),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:loadCodeAssist"))
|
||||
.respond_with(ResponseTemplate::new(status).set_body_json(body))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
let account = fixture
|
||||
.store
|
||||
.primary()
|
||||
.loaded
|
||||
.lock()
|
||||
.unwrap()
|
||||
.account
|
||||
.id()
|
||||
.clone();
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
request(false),
|
||||
diagnostic_context(AccountProbeTarget::ConnectionTest(account)),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.expect_err("Google rejected the project lookup");
|
||||
assert_eq!(error.upstream_status(), Some(status));
|
||||
let visible = error.client_visible_upstream_error();
|
||||
assert_eq!(visible.and_then(|e| e.code()), reason);
|
||||
assert_eq!(visible.map(|e| e.message()), message);
|
||||
assert_eq!(
|
||||
visible.and_then(|e| e.error_type()),
|
||||
message.map(|_| "PERMISSION_DENIED")
|
||||
);
|
||||
assert!(error.client_visible_upstream_response().is_none());
|
||||
released(&fixture).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recovery_probe_does_not_mutate_credentials_cooldowns_or_scheduling_feedback() {
|
||||
for (status, kind) in [
|
||||
|
||||
+3
-2
@@ -1648,8 +1648,9 @@ OAuth 等待回调期间允许修改代理。提交时若代理已删除、停
|
||||
`unreachable` 表示无法连接代理端点,`tunnel_failed` 表示代理隧道协商失败。
|
||||
`check_proxy` 表示本次使用代理且建连失败,不能据此判定故障在代理;无提示时为 `null`
|
||||
- `sendState` 为 `not_sent`、`sent`、`ambiguous`,非 Provider 错误为 `null`
|
||||
- `error`、`providerErrorCode`、`providerErrorType`、`upstreamStatus`、`upstreamContentType` 和
|
||||
`upstreamBody` 是实际捕获的原始诊断字段;缺失时为 `null`,不会由本地猜测或翻译
|
||||
- `upstreamStatus` 可单独返回;`upstreamContentType` 和 `upstreamBody` 仅在有可展示的原始响应时返回
|
||||
- Antigravity 的 `providerErrorCode` 取 Google ErrorInfo 的 `reason`,`providerErrorType` 取 Google 的 `status`。
|
||||
`error` 优先展示可安全返回的上游消息,缺失时使用网关提示。验证链接不随连接测试返回
|
||||
|
||||
### 后台导入任务
|
||||
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "Could not connect to the account proxy — test it in Proxies",
|
||||
"proxyTunnelFailed": "Could not establish a tunnel through the account proxy — check its settings",
|
||||
"checkProxy": "The request could not be sent upstream — test the account proxy in Proxies",
|
||||
"googleCredentials": "Google rejected the credentials for this account (401)",
|
||||
"googleAccessDenied": "Google denied this account access to Antigravity (403)",
|
||||
"googleVerification": "Sign in to Google and verify this account, then test again (403)",
|
||||
"upstreamUnavailable": "Upstream service temporarily unavailable",
|
||||
"timeout": "Upstream request timed out",
|
||||
"canceled": "Test canceled",
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "无法连接账号代理,请在「代理管理」中测试该代理",
|
||||
"proxyTunnelFailed": "未能通过账号代理建立隧道,请检查代理设置",
|
||||
"checkProxy": "请求未能发往上游,可在「代理管理」中测试账号代理",
|
||||
"googleCredentials": "Google 未接受此账号的登录凭据(401)",
|
||||
"googleAccessDenied": "Google 拒绝此账号访问 Antigravity(403)",
|
||||
"googleVerification": "请登录 Google 完成账号验证后再测试(403)",
|
||||
"upstreamUnavailable": "上游服务暂不可用",
|
||||
"timeout": "上游请求超时",
|
||||
"canceled": "测试请求已取消",
|
||||
|
||||
@@ -111,6 +111,9 @@
|
||||
"proxyUnreachable": "無法連線至帳號代理,請在「代理管理」中測試該代理",
|
||||
"proxyTunnelFailed": "無法透過帳號代理建立通道,請檢查代理設定",
|
||||
"checkProxy": "請求未能送往上游,可在「代理管理」中測試帳號代理",
|
||||
"googleCredentials": "Google 未接受此帳號的登入憑證(401)",
|
||||
"googleAccessDenied": "Google 拒絕此帳號存取 Antigravity(403)",
|
||||
"googleVerification": "請登入 Google 完成帳號驗證後再測試(403)",
|
||||
"upstreamUnavailable": "上游服務暫不可用",
|
||||
"timeout": "上游請求超時",
|
||||
"canceled": "測試請求已取消",
|
||||
|
||||
@@ -123,7 +123,16 @@ function parseConnectionTestEvent(raw: string): ConnectionTestEvent | null {
|
||||
return value as ConnectionTestEvent
|
||||
}
|
||||
|
||||
function connectionTestFailureText(event: ConnectionTestFailureEvent) {
|
||||
function connectionTestFailureText(event: ConnectionTestFailureEvent, provider?: string) {
|
||||
if (provider === 'antigravity' && event.source === 'upstream') {
|
||||
if (event.upstreamStatus === 401)
|
||||
return t('accounts.connectionTest.errors.googleCredentials')
|
||||
if (event.upstreamStatus === 403) {
|
||||
return event.providerErrorCode === 'VALIDATION_REQUIRED'
|
||||
? t('accounts.connectionTest.errors.googleVerification')
|
||||
: t('accounts.connectionTest.errors.googleAccessDenied')
|
||||
}
|
||||
}
|
||||
if (event.source === 'provider' && event.sendState === 'not_sent') {
|
||||
switch (event.proxyHint) {
|
||||
case 'invalid_configuration': return t('accounts.connectionTest.errors.proxyInvalid')
|
||||
@@ -394,7 +403,7 @@ export function useAccountConnectionTest(options: { reload: () => Promise<unknow
|
||||
recordConnectionTestFailure(
|
||||
`failure-${event.source || 'unknown'}`,
|
||||
connectionTestFailureLabel(event),
|
||||
connectionTestFailureText(event),
|
||||
connectionTestFailureText(event, testingAccount.value?.provider),
|
||||
connectionTestFailureDiagnostics(event),
|
||||
event,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user