mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 00:00:49 +00:00
fix(antigravity): align GenAI authentication and OAuth requests
Accept x-goog-api-key on GenAI endpoints while preserving Authorization precedence and existing endpoint scopes. Allow the header in CORS preflight responses. Apply OAuth request identity without rebuilding business JSON, filter gateway identity headers and labels, and update the CLI baseline to 1.5.17. Document the authentication and transport contracts. Validation: workspace Rustfmt and strict Clippy for gateway-api and provider-antigravity passed. All 823 API, provider and architecture tests passed, with none skipped. Live upstream validation was not rerun. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -104,8 +104,9 @@ pub(crate) async fn authenticate_client(
|
||||
pub(crate) async fn verify_client(
|
||||
service: &DataPlaneService,
|
||||
headers: &HeaderMap,
|
||||
accepted: ClientKeyHeaders,
|
||||
) -> Result<AuthenticatedClient, ClientApiKeyAuthError> {
|
||||
let request = client_authentication_request(headers, ClientKeyHeaders::Bearer)?;
|
||||
let request = client_authentication_request(headers, accepted)?;
|
||||
service.verify(request).await
|
||||
}
|
||||
|
||||
@@ -114,6 +115,7 @@ pub(crate) async fn verify_client(
|
||||
pub(crate) enum ClientKeyHeaders {
|
||||
Bearer,
|
||||
Anthropic,
|
||||
GenAi,
|
||||
}
|
||||
|
||||
fn client_authentication_request(
|
||||
@@ -125,16 +127,20 @@ fn client_authentication_request(
|
||||
.to_str()
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||
.to_owned()
|
||||
} else if matches!(accepted, ClientKeyHeaders::Anthropic)
|
||||
&& let Some(key) = headers.get("x-api-key")
|
||||
{
|
||||
} else {
|
||||
let header = match accepted {
|
||||
ClientKeyHeaders::Bearer => None,
|
||||
ClientKeyHeaders::Anthropic => Some("x-api-key"),
|
||||
ClientKeyHeaders::GenAi => Some("x-goog-api-key"),
|
||||
};
|
||||
let key = header
|
||||
.and_then(|name| headers.get(name))
|
||||
.ok_or(ClientApiKeyAuthError::MissingAuthorization)?;
|
||||
format!(
|
||||
"Bearer {}",
|
||||
key.to_str()
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||
)
|
||||
} else {
|
||||
return Err(ClientApiKeyAuthError::MissingAuthorization);
|
||||
};
|
||||
let request = ClientAuthenticationRequest::new(raw)
|
||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?;
|
||||
|
||||
@@ -175,7 +175,7 @@ async fn generate(
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let service = state.data_plane().clone();
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error),
|
||||
};
|
||||
@@ -221,7 +221,7 @@ async fn generate(
|
||||
}
|
||||
|
||||
async fn metric(State(state): State<ApiState>, headers: HeaderMap) -> Response {
|
||||
match verify_client(state.data_plane(), &headers).await {
|
||||
match verify_client(state.data_plane(), &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(_) => Json(json!({})).into_response(),
|
||||
Err(error) => client_access_error_response(error.into()),
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ async fn query_response(
|
||||
query: ModelsQuery,
|
||||
) -> Response {
|
||||
let service = state.data_plane();
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await {
|
||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::GenAi).await {
|
||||
Ok(client) => client,
|
||||
Err(err) => return client_access_error_response(err),
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ use gateway_protocol::peer::{MAX_ACCOUNTS, MAX_MODELS, MAX_QUOTA_WINDOWS, MAX_RE
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::{
|
||||
auth::{client_access_error_response, verify_client},
|
||||
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||
error::{missing_client_api_key_response, openai_error_response},
|
||||
};
|
||||
use crate::{
|
||||
@@ -36,7 +36,7 @@ pub(super) fn router() -> Router<ApiState> {
|
||||
struct PeerQuery {}
|
||||
|
||||
async fn peer_link(State(state): State<ApiState>, headers: HeaderMap, uri: Uri) -> Response {
|
||||
let client = match verify_client(state.data_plane(), &headers).await {
|
||||
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error.into()),
|
||||
};
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth::{client_access_error_response, verify_client},
|
||||
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||
error::{missing_client_api_key_response, openai_error_response},
|
||||
};
|
||||
|
||||
@@ -40,7 +40,7 @@ async fn usage(
|
||||
headers: HeaderMap,
|
||||
uri: axum::http::Uri,
|
||||
) -> Response {
|
||||
let client = match verify_client(state.data_plane(), &headers).await {
|
||||
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||
Ok(client) => client,
|
||||
Err(error) => return client_access_error_response(error.into()),
|
||||
};
|
||||
|
||||
@@ -255,6 +255,7 @@ pub fn initialize(
|
||||
axum::http::header::AUTHORIZATION,
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
HeaderName::from_static("x-api-key"),
|
||||
HeaderName::from_static("x-goog-api-key"),
|
||||
HeaderName::from_static("anthropic-version"),
|
||||
HeaderName::from_static("anthropic-beta"),
|
||||
request_id_header.clone(),
|
||||
|
||||
@@ -4,6 +4,116 @@ use super::*;
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_authenticates_native_endpoints_without_changing_wire() {
|
||||
for action in [
|
||||
"generateContent",
|
||||
"streamGenerateContent?alt=sse",
|
||||
"countTokens",
|
||||
] {
|
||||
let stream = action.starts_with("stream");
|
||||
let raw = if action == "countTokens" {
|
||||
Bytes::from_static(br#"{ "totalTokens":42 }"#)
|
||||
} else {
|
||||
Bytes::from_static(br#"{ "candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}] }"#)
|
||||
};
|
||||
let frame = "data: { \"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}] }\n\n";
|
||||
let event = if stream {
|
||||
wire_frame(frame)
|
||||
} else {
|
||||
ProviderEvent::wire(ProtocolWireEvent::raw_json(GENAI_PROTOCOL, raw.clone()).unwrap())
|
||||
};
|
||||
let execution = Arc::new(Execution {
|
||||
session: Mutex::new(Some(Session::new(vec![event]))),
|
||||
..Default::default()
|
||||
});
|
||||
let mut req = request(&format!("{SHORT}:{action}"));
|
||||
req.headers_mut().remove("authorization");
|
||||
req.headers_mut()
|
||||
.insert("x-goog-api-key", KEY.parse().unwrap());
|
||||
let response = api_router(execution.clone())
|
||||
.await
|
||||
.oneshot(req)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK, "{action}");
|
||||
let expected = if stream { frame.as_bytes() } else { &raw };
|
||||
assert_eq!(
|
||||
to_bytes(response.into_body(), 2048).await.unwrap().as_ref(),
|
||||
expected
|
||||
);
|
||||
let captured = execution.seen.lock().unwrap().take().unwrap();
|
||||
assert_eq!(
|
||||
captured.operation.middleware_body().unwrap().as_ref(),
|
||||
BODY.as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_reuses_validation_and_never_overrides_authorization() {
|
||||
use axum::http::HeaderValue;
|
||||
|
||||
let execution = Arc::new(Execution::default());
|
||||
let router = api_router(execution.clone()).await;
|
||||
for (authorization, key, status) in [
|
||||
(None, Some(HeaderValue::from_static(KEY)), StatusCode::OK),
|
||||
(None, None, StatusCode::UNAUTHORIZED),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_static("invalid")),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_static("")),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
None,
|
||||
Some(HeaderValue::from_bytes(b"\xff").unwrap()),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Bearer invalid"),
|
||||
Some(HeaderValue::from_static(KEY)),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Basic invalid"),
|
||||
Some(HeaderValue::from_static(KEY)),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
),
|
||||
(
|
||||
Some("Bearer sk_genai_test"),
|
||||
Some(HeaderValue::from_static("invalid")),
|
||||
StatusCode::OK,
|
||||
),
|
||||
] {
|
||||
let mut req = request("/v1beta:recordCodeAssistMetrics");
|
||||
req.headers_mut().remove("authorization");
|
||||
if let Some(value) = authorization {
|
||||
req.headers_mut()
|
||||
.insert("authorization", value.parse().unwrap());
|
||||
}
|
||||
if let Some(value) = key {
|
||||
req.headers_mut().insert("x-goog-api-key", value);
|
||||
}
|
||||
assert_eq!(router.clone().oneshot(req).await.unwrap().status(), status);
|
||||
}
|
||||
for path in ["/v1/models", "/v1/usage", "/v1/cpr/link"] {
|
||||
let req = Request::get(path)
|
||||
.header("x-goog-api-key", KEY)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
router.clone().oneshot(req).await.unwrap().status(),
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
assert!(execution.seen.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
|
||||
for connection in [None, Some("x-http-session-id")] {
|
||||
|
||||
@@ -123,3 +123,24 @@ async fn directory_errors_follow_google_rpc_and_require_authentication() {
|
||||
assert_eq!(body["error"]["code"], status.as_u16(), "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn google_api_key_reads_the_same_authorized_catalog() {
|
||||
let router = api_router(Arc::new(Execution {
|
||||
client: Some(client()),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
for path in ["/v1beta/models", "/v1beta/models/model-a"] {
|
||||
let (expected_status, expected) = query(&router, path, true).await;
|
||||
let request = Request::get(path)
|
||||
.header("x-goog-api-key", KEY)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let response = router.clone().oneshot(request).await.unwrap();
|
||||
assert_eq!(response.status(), expected_status);
|
||||
let actual: Value =
|
||||
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ async fn configured_cors_origin_assembles_router_and_answers_preflight() {
|
||||
.expect("allow-headers present");
|
||||
assert!(allow_headers.contains("authorization"));
|
||||
assert!(allow_headers.contains("x-api-key"));
|
||||
assert!(allow_headers.contains("x-goog-api-key"));
|
||||
assert!(allow_headers.contains("anthropic-version"));
|
||||
assert!(allow_headers.contains("anthropic-beta"));
|
||||
assert!(allow_headers.contains("x-request-id"));
|
||||
|
||||
@@ -31,8 +31,8 @@ impl ClientKind {
|
||||
changelist: 1_026_637_980,
|
||||
},
|
||||
Self::Cli => ClientBuild {
|
||||
version: "1.5.15",
|
||||
changelist: 1_027_820_220,
|
||||
version: "1.5.17",
|
||||
changelist: 1_029_496_841,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,10 @@ impl Selection {
|
||||
arch: self.target().arch,
|
||||
client_version: version.into(),
|
||||
// 发布资料只有版本号;未知版本不沿用另一个版本的构建号
|
||||
changelist: (version == baseline.version).then_some(baseline.changelist),
|
||||
changelist: match (self.client, version) {
|
||||
(ClientKind::Cli, "1.5.15") => Some(1_027_820_220),
|
||||
_ => (version == baseline.version).then_some(baseline.changelist),
|
||||
},
|
||||
system_prompt: self
|
||||
.system_prompt
|
||||
.as_deref()
|
||||
@@ -194,17 +197,19 @@ impl ClientProfile {
|
||||
}
|
||||
pub(crate) fn verified_at(&self) -> Option<DateTime<Utc>> {
|
||||
let baseline = self.client.baseline();
|
||||
if self.client != ClientKind::Desktop
|
||||
|| self.platform != Platform::Macos
|
||||
|| self.arch != Architecture::Arm64
|
||||
|| self.client_version != baseline.version
|
||||
|| self.changelist != Some(baseline.changelist)
|
||||
{
|
||||
if self.client_version != baseline.version || self.changelist != Some(baseline.changelist) {
|
||||
return None;
|
||||
}
|
||||
// Desktop 完整 UA 已实测;CLI 的 ACP 采样不足以核验普通交互入口的完整画像
|
||||
// 核验时间独立于官方发布资料的轮询时间
|
||||
Utc.with_ymd_and_hms(2026, 11, 23, 11, 11, 15).single()
|
||||
// 对应平台的 OAuth HTTP 请求已实测;此时间不代表 TLS 指纹或发布资料轮询时间
|
||||
match (self.client, self.platform, self.arch) {
|
||||
(ClientKind::Desktop, Platform::Macos, Architecture::Arm64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 23, 11, 11, 15).single()
|
||||
}
|
||||
(ClientKind::Cli, Platform::Linux, Architecture::Amd64) => {
|
||||
Utc.with_ymd_and_hms(2026, 11, 26, 16, 1, 16).single()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(crate) fn client_identifier(&self) -> String {
|
||||
format!(
|
||||
|
||||
@@ -179,18 +179,20 @@ impl CloudCodeClient {
|
||||
struct Envelope<'a> {
|
||||
project: &'a str,
|
||||
model: &'a str,
|
||||
#[serde(rename = "requestType", skip_serializing_if = "Option::is_none")]
|
||||
request_type: Option<&'static str>,
|
||||
#[serde(rename = "userAgent")]
|
||||
user_agent: &'static str,
|
||||
#[serde(rename = "requestType")]
|
||||
request_type: &'static str,
|
||||
#[serde(rename = "enabledCreditTypes", skip_serializing_if = "Option::is_none")]
|
||||
enabled_credit_types: Option<[&'static str; 1]>,
|
||||
request: BTreeMap<String, &'a RawValue>,
|
||||
request: &'a RawValue,
|
||||
}
|
||||
let instruction = if mode == GenerateMode::WebSearch {
|
||||
*SEARCH_INSTRUCTION
|
||||
} else {
|
||||
&self.system_instruction
|
||||
};
|
||||
let request = Self::request_body(body, instruction)?;
|
||||
let request = super::request::request_body(body, instruction, false)?;
|
||||
let (send, media) = if mode == GenerateMode::Stream {
|
||||
(
|
||||
self.post("streamGenerateContent", token)
|
||||
@@ -208,11 +210,16 @@ impl CloudCodeClient {
|
||||
send.json(&Envelope {
|
||||
project,
|
||||
model,
|
||||
request_type: (mode == GenerateMode::WebSearch).then_some("web_search"),
|
||||
user_agent: "antigravity",
|
||||
request_type: if mode == GenerateMode::WebSearch {
|
||||
"web_search"
|
||||
} else {
|
||||
"agent"
|
||||
},
|
||||
enabled_credit_types: self
|
||||
.use_quota_credits
|
||||
.then_some([super::account::GOOGLE_ONE_AI]),
|
||||
request,
|
||||
request: &request,
|
||||
}),
|
||||
token,
|
||||
headers,
|
||||
@@ -227,24 +234,16 @@ impl CloudCodeClient {
|
||||
body: &[u8],
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
let mut request = Self::request_body(body, &self.system_instruction)?;
|
||||
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
|
||||
for field in [
|
||||
"model",
|
||||
"safetySettings",
|
||||
"safety_settings",
|
||||
"toolConfig",
|
||||
"tool_config",
|
||||
"labels",
|
||||
"sessionId",
|
||||
"session_id",
|
||||
] {
|
||||
request.remove(field);
|
||||
let request = super::request::request_body(body, &self.system_instruction, true)?;
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
}
|
||||
self.send(
|
||||
self.post("countTokens", token)
|
||||
.timeout(GENERATION_TIMEOUT)
|
||||
.json(&json!({"request":request})),
|
||||
.json(&Envelope { request: &request }),
|
||||
token,
|
||||
headers,
|
||||
"application/json",
|
||||
@@ -252,18 +251,6 @@ impl CloudCodeClient {
|
||||
.await
|
||||
}
|
||||
|
||||
fn request_body<'a>(
|
||||
body: &'a [u8],
|
||||
instruction: &'a RawValue,
|
||||
) -> Result<BTreeMap<String, &'a RawValue>, ProviderError> {
|
||||
let mut request: BTreeMap<String, &RawValue> = serde_json::from_slice(body)
|
||||
.map_err(|e| unsent(Kind::InvalidRequest).with_source(e))?;
|
||||
// 生成和计数共享同一身份策略,其他字段保留原始 JSON 表达
|
||||
request.remove("system_instruction");
|
||||
request.insert("systemInstruction".to_owned(), instruction);
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
async fn send(
|
||||
&self,
|
||||
mut send: reqwest::RequestBuilder,
|
||||
|
||||
@@ -60,7 +60,7 @@ pub(super) fn managed_header(name: &str) -> bool {
|
||||
name.as_str(),
|
||||
"authorization" | "cookie" | "cookie2" | "content-type" | "accept"
|
||||
| "user-agent" | "x-api-key" | "x-goog-api-key" | "x-goog-user-project"
|
||||
| "x-goog-api-client"
|
||||
| "x-goog-api-client" | "x-goog-ext-525006001-bin"
|
||||
// 跨协议入口的账号身份不能成为 AGY 账号或客户端身份
|
||||
| "chatgpt-account-id" | "chatgpt-project-id" | "openai-organization"
|
||||
| "openai-project" | "x-openai-actor-authorization" | "x-codex-installation-id"
|
||||
|
||||
@@ -5,6 +5,7 @@ mod count;
|
||||
mod failure;
|
||||
mod headers;
|
||||
mod pool;
|
||||
mod request;
|
||||
mod response;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, GenerateMode, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! 只改写 Cloud Code 身份字段,其他字段直接复制原始 JSON 字节
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{MapAccess, Visitor},
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
|
||||
use super::unsent;
|
||||
use gateway_core::error::{ProviderError, ProviderErrorKind};
|
||||
|
||||
pub(super) fn request_body(
|
||||
body: &[u8],
|
||||
instruction: &RawValue,
|
||||
count: bool,
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
if matches!(name, "systemInstruction" | "system_instruction")
|
||||
|| (count
|
||||
&& matches!(
|
||||
name,
|
||||
"model"
|
||||
| "safetySettings"
|
||||
| "safety_settings"
|
||||
| "toolConfig"
|
||||
| "tool_config"
|
||||
| "labels"
|
||||
| "sessionId"
|
||||
| "session_id"
|
||||
))
|
||||
{
|
||||
return Ok(Edit::Remove);
|
||||
}
|
||||
if name == "labels" && value.get().starts_with('{') {
|
||||
// CLI Gateway 添加的产品归属标识不属于个人 OAuth 身份;会话和业务标签保留
|
||||
return edit_object(
|
||||
value,
|
||||
|label, _| {
|
||||
Ok(
|
||||
if matches!(
|
||||
label,
|
||||
"client"
|
||||
| "goog-originating-logical-product-id"
|
||||
| "goog-originating-service-id"
|
||||
) {
|
||||
Edit::Remove
|
||||
} else {
|
||||
Edit::Keep
|
||||
},
|
||||
)
|
||||
},
|
||||
None,
|
||||
)
|
||||
.map(Edit::Replace);
|
||||
}
|
||||
Ok(Edit::Keep)
|
||||
},
|
||||
Some(("systemInstruction", instruction)),
|
||||
)
|
||||
};
|
||||
rewrite().map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))
|
||||
}
|
||||
|
||||
enum Edit {
|
||||
Keep,
|
||||
Remove,
|
||||
Replace(Box<RawValue>),
|
||||
}
|
||||
|
||||
fn edit_object(
|
||||
body: &RawValue,
|
||||
mut edit: impl FnMut(&str, &RawValue) -> Result<Edit, serde_json::Error>,
|
||||
append: Option<(&str, &RawValue)>,
|
||||
) -> Result<Box<RawValue>, serde_json::Error> {
|
||||
let json = body.get();
|
||||
let Fields(fields) = serde_json::from_str(json)?;
|
||||
let mut output = String::with_capacity(json.len());
|
||||
output.push('{');
|
||||
let mut cursor = 1;
|
||||
let mut retained = false;
|
||||
for (name, value) in fields {
|
||||
// RawValue 借自同一输入;位置由 serde JSON 解析器确定,不自行解析值或转码数字
|
||||
let start = value.get().as_ptr() as usize - json.as_ptr() as usize;
|
||||
let prefix = &json[cursor..start];
|
||||
cursor = start + value.get().len();
|
||||
let replacement = match edit(&name, value)? {
|
||||
Edit::Keep => None,
|
||||
Edit::Remove => continue,
|
||||
Edit::Replace(value) => Some(value),
|
||||
};
|
||||
let comma = (!retained)
|
||||
.then(|| prefix.bytes().position(|byte| !byte.is_ascii_whitespace()))
|
||||
.flatten()
|
||||
.filter(|&index| prefix.as_bytes()[index] == b',');
|
||||
if let Some(index) = comma {
|
||||
output.push_str(&prefix[..index]);
|
||||
output.push_str(&prefix[index + 1..]);
|
||||
} else {
|
||||
output.push_str(prefix);
|
||||
}
|
||||
output.push_str(replacement.as_deref().unwrap_or(value).get());
|
||||
retained = true;
|
||||
}
|
||||
if let Some((name, value)) = append {
|
||||
if retained {
|
||||
output.push(',');
|
||||
}
|
||||
output.push_str(&serde_json::to_string(name)?);
|
||||
output.push(':');
|
||||
output.push_str(value.get());
|
||||
}
|
||||
output.push_str(&json[cursor..]);
|
||||
RawValue::from_string(output)
|
||||
}
|
||||
|
||||
// 保留顺序和重复字段;身份字段的重复项也必须全部处理,不能被 Map 的最后值语义遗漏
|
||||
struct Fields<'a>(Vec<(String, &'a RawValue)>);
|
||||
|
||||
impl<'de> Deserialize<'de> for Fields<'de> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct ObjectVisitor;
|
||||
impl<'de> Visitor<'de> for ObjectVisitor {
|
||||
type Value = Fields<'de>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut fields = Vec::new();
|
||||
while let Some(name) = map.next_key()? {
|
||||
fields.push((name, map.next_value()?));
|
||||
}
|
||||
Ok(Fields(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(ObjectVisitor)
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,8 @@ fn client_presets_resolve_platform_and_frozen_version() {
|
||||
assert!(original.user_agent().contains("; cl="));
|
||||
assert_eq!(
|
||||
original.verified_at().is_some(),
|
||||
client == "desktop" && platform == "macos"
|
||||
(client == "desktop" && platform == "macos")
|
||||
|| (client == "cli" && platform == "linux")
|
||||
);
|
||||
assert_ne!(original.user_agent(), profile.user_agent());
|
||||
}
|
||||
@@ -48,10 +49,10 @@ fn fixed_version_rejects_header_injection_and_incomplete_selection() {
|
||||
] {
|
||||
assert!(Selection::parse(&object(value)).is_err());
|
||||
}
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.15","arch":"arm64"}))).unwrap();
|
||||
let selected = Selection::parse(&object(json!({"client":"cli","platform":"linux","versionMode":"fixed","clientVersion":"1.5.17","arch":"arm64"}))).unwrap();
|
||||
assert_eq!(
|
||||
selected.resolve("9.9.9").user_agent(),
|
||||
"antigravity/cli/1.5.15 (aidev_client; os_type=linux; arch=arm64; cl=1027820220; auth_method=consumer)"
|
||||
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=arm64; cl=1029496841; auth_method=consumer)"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,11 @@ use crate::support::{Fixture, context, request};
|
||||
async fn native_and_translated_requests_forward_business_headers_with_account_identity() {
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let profile = crate::profile::default_profile(
|
||||
&crate::profile::ReleaseService::new(crate::support::profile::cache()).unwrap(),
|
||||
)
|
||||
let profile = crate::profile::Selection::parse(&crate::profile::object(json!({
|
||||
"client":"cli", "platform":"linux", "versionMode":"fixed", "clientVersion":"1.5.17"
|
||||
})))
|
||||
.unwrap()
|
||||
.resolve("1.5.17")
|
||||
.frozen();
|
||||
let ctx = || {
|
||||
context(
|
||||
@@ -52,6 +54,8 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
"x-goog-api-key",
|
||||
"x-goog-user-project",
|
||||
"x-goog-api-client",
|
||||
"x-goog-ext-525006001-bin",
|
||||
"x-api-key",
|
||||
"content-encoding",
|
||||
"content-length",
|
||||
"x-request-id",
|
||||
@@ -122,11 +126,9 @@ async fn native_and_translated_requests_forward_business_headers_with_account_id
|
||||
assert_eq!(request.headers["traceparent"], "original-trace");
|
||||
assert_eq!(request.headers["authorization"], "Bearer fixture-access");
|
||||
assert_eq!(request.headers["content-type"], "application/json");
|
||||
assert!(
|
||||
request.headers["user-agent"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("antigravity/hub/")
|
||||
assert_eq!(
|
||||
request.headers["user-agent"],
|
||||
"antigravity/cli/1.5.17 (aidev_client; os_type=linux; arch=amd64; cl=1029496841; auth_method=consumer)"
|
||||
);
|
||||
for name in forbidden {
|
||||
if !matches!(name, "authorization" | "user-agent" | "content-length") {
|
||||
|
||||
@@ -3,3 +3,4 @@
|
||||
mod client;
|
||||
mod count;
|
||||
mod pool;
|
||||
mod request;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! 身份字段局部修改与其余 JSON 原始字节保留
|
||||
|
||||
use crate::{profile, transport::CloudCodeClient};
|
||||
use serde_json::json;
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
|
||||
#[tokio::test]
|
||||
async fn oauth_identity_edits_preserve_remaining_json_bytes_and_duplicate_business_fields() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":{}})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let selection = profile::Selection {
|
||||
system_prompt: Some("OAuth fixture".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let client = CloudCodeClient::new(
|
||||
&server.uri().parse().unwrap(),
|
||||
None,
|
||||
&selection.resolve("2.34.0"),
|
||||
)
|
||||
.unwrap();
|
||||
let instruction = r#""systemInstruction":{"parts":[{"text":"OAuth fixture"}]}"#;
|
||||
for (body, remaining) in [
|
||||
(
|
||||
r#"{ "contents" : [], "unknown":98765432109876543210987654, "unknown":1e+09, "tools" : [ { "functionDeclarations":[] } ] }"#,
|
||||
r#"{ "contents" : [], "unknown":98765432109876543210987654, "unknown":1e+09, "tools" : [ { "functionDeclarations":[] } ]"#,
|
||||
),
|
||||
(
|
||||
r#"{"system_instruction":{}, "system\u0049nstruction":{},"contents":[],"systemInstruction":{}}"#,
|
||||
r#"{"contents":[]"#,
|
||||
),
|
||||
(
|
||||
r#"{"labels":{"client":"gateway", "cascade_id" : "conversation", "goog-originating-service-id":"key-mode","goog-originating-logical-product-id":"key-mode","client":"again","custom" : 1e+09},"sessionId":"unchanged","contents":[{"parts":[{"thoughtSignature":"opaque","functionResponse":{"name":"tool","response":{"text":"auth_method=gateway"}}}]}]}"#,
|
||||
r#"{"labels":{ "cascade_id" : "conversation","custom" : 1e+09},"sessionId":"unchanged","contents":[{"parts":[{"thoughtSignature":"opaque","functionResponse":{"name":"tool","response":{"text":"auth_method=gateway"}}}]}]"#,
|
||||
),
|
||||
(
|
||||
r#"{"labels":{"client":"gateway"},"contents":[]}"#,
|
||||
r#"{"labels":{},"contents":[]"#,
|
||||
),
|
||||
(r#"{}"#, "{"),
|
||||
(r#"{"system_instruction":{}}"#, "{"),
|
||||
] {
|
||||
client
|
||||
.generate(
|
||||
"account-project",
|
||||
"fixture-model",
|
||||
"fixture-access",
|
||||
body.as_bytes(),
|
||||
false.into(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let envelope: std::collections::BTreeMap<String, &serde_json::value::RawValue> =
|
||||
serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||||
let suffix = if body.ends_with(" }") { " }" } else { "}" };
|
||||
let comma = if remaining == "{" { "" } else { "," };
|
||||
assert_eq!(
|
||||
envelope["request"].get(),
|
||||
format!("{remaining}{comma}{instruction}{suffix}")
|
||||
);
|
||||
assert_eq!(envelope["project"].get(), "\"account-project\"");
|
||||
assert_eq!(envelope["userAgent"].get(), "\"antigravity\"");
|
||||
assert_eq!(envelope["requestType"].get(), "\"agent\"");
|
||||
}
|
||||
for invalid in ["[]", "null", "{", "{} trailing"] {
|
||||
assert!(
|
||||
client
|
||||
.generate(
|
||||
"account-project",
|
||||
"fixture-model",
|
||||
"fixture-access",
|
||||
invalid.as_bytes(),
|
||||
false.into(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 6);
|
||||
}
|
||||
+6
-3
@@ -27,6 +27,7 @@ Authorization: Bearer sk_...
|
||||
自动生成的 Key 以 `sk_` 开头,自定义 Key 按原值鉴权,无固定前缀或长度。仅已保存且启用的 Key 有效
|
||||
|
||||
`/v1/messages`、`/v1/messages/count_tokens`、`/v1/models` 和 `/v1/models/{model_id}` 也接受 `x-api-key: <Client Key>`。
|
||||
GenAI 的 `/v1beta/models*` 和 `/v1beta:{method}` 入口也接受 `x-goog-api-key: <Client Key>`。
|
||||
同时提供两个认证头时优先使用 `Authorization`;客户端提交的是网关 Client Key,上游密钥由选中的账号提供
|
||||
|
||||
启用[入口认证插件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#数据面入口认证)时,
|
||||
@@ -249,7 +250,7 @@ WebSocket message 和 frame 不设置网关私有长度上限;请求字段与
|
||||
|
||||
### Antigravity 客户端原生生成
|
||||
|
||||
客户端用 `Authorization: Bearer <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
|
||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。缺少或不支持的档位返回 400,显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||
|
||||
@@ -263,7 +264,9 @@ WebSocket message 和 frame 不设置网关私有长度上限;请求字段与
|
||||
|
||||
普通生成从上游 JSON 的 `response` 中取出原生正文,流式生成逐个解开 SSE 数据帧。等待首帧和后续帧时,网关保持静默。首帧前的失败保留 HTTP 错误状态。原生正文保留工具参数、结果、思考签名和未知字段。客户端归属读取 `User-Agent`、`X-Goog-Api-Client`。网关错误使用 Google RPC 风格的 `error.code`、`error.status` 和 `error.message`。[Google 原生生成协议](https://ai.google.dev/api/generate-content)
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选账号与冻结画像生成。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 OAuth 账号与冻结画像生成。`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)
|
||||
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文只局部替换配置的 `systemInstruction`、移除其蛇形别名,以及 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
|
||||
同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文
|
||||
|
||||
@@ -1825,7 +1828,7 @@ Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravi
|
||||
|
||||
固定版本使用 `"versionMode":"fixed"`,并将 `clientVersion` 设为三段数字版本。Desktop 与 CLI 分别跟随各自的官方发布资料,各实例启动后检查,之后每 24 小时更新一次;检查失败保留上次成功结果,尚无结果时使用已核实的内置版本。请求开始时冻结客户端、平台、架构、版本及对应的 CL 构建号,重试沿用同一画像。发布资料不提供 CL,未知版本省略该字段,不套用旧版本的构建号。[Google 官方下载](https://antigravity.google/download)
|
||||
|
||||
预览与实际出站请求共用 `User-Agent` 生成规则。本机 macOS arm64 的 Desktop 2.34.0 已认证请求为 `antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)`;CLI 1.5.15 经 ACP 入口及打印模式的控制面请求核实使用 `cli` 子客户端标识、CL `1027820220` 及 `auth_method=consumer`。默认身份不添加关闭遥测才出现的 `datacollection_opt_in` 或 ACP 宿主传入的 `host_path`
|
||||
预览与实际出站请求共用 `User-Agent` 生成规则。本机 macOS arm64 的 Desktop 2.34.0 已认证请求为 `antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64; cl=1026637980)`;Linux amd64 的 CLI 1.5.17 经个人 OAuth 打印模式的控制面与生成请求核实使用 `cli` 子客户端标识、CL `1029496841` 及 `auth_method=consumer`。默认身份不添加关闭遥测才出现的 `datacollection_opt_in` 或 ACP 宿主传入的 `host_path`
|
||||
|
||||
Cloud Code 请求固定使用 HTTP/1.1 和 `Accept-Encoding: gzip`,响应按流解压,大小限制作用于解压后的内容。
|
||||
传输显式使用 rustls,TLS 握手与官方 Go 客户端不同;reqwest 的默认 `Accept: */*` 和请求头顺序也不完全一致。画像预览不代表 TLS 或完整网络指纹一致
|
||||
|
||||
Reference in New Issue
Block a user