mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-20 08:01:46 +00:00
test: align backend coverage with current behavior
Remove obsolete field assertions and the ignored Codex binary TLS comparison. Keep coverage for request validation, compatibility, and local TLS handshakes. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -60,7 +60,7 @@ async fn explicit_service_calls_freeze_empty_plan_and_cancel_before_entering_ter
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// 内部 pricing 不再单独进入插件链;显式调用只解析一次发布集合
|
||||
// 每次显式调价只解析一次插件发布集合
|
||||
assert_eq!(resolutions.load(Ordering::SeqCst), expected);
|
||||
}
|
||||
store.updated.lock().unwrap().take();
|
||||
|
||||
@@ -215,7 +215,7 @@ async fn mutation_route_should_reject_unknown_json_fields() {
|
||||
"name": "Unknown field",
|
||||
"description": null,
|
||||
"color": "#2563EBFF",
|
||||
"providerKind": "openai"
|
||||
"unknownField": true
|
||||
})),
|
||||
true,
|
||||
)
|
||||
@@ -232,7 +232,7 @@ async fn create_route_should_reject_six_digit_color_without_alpha() {
|
||||
Method::POST,
|
||||
"/api/admin/account-groups/create",
|
||||
Some(json!({
|
||||
"name": "Opaque legacy color",
|
||||
"name": "Color without alpha",
|
||||
"description": null,
|
||||
"color": "#2563EB"
|
||||
})),
|
||||
|
||||
@@ -341,7 +341,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
|
||||
));
|
||||
let future = now + Duration::days(1);
|
||||
let future_display = zone.local(future).format("%Y-%m-%d %H:%M:%S").to_string();
|
||||
for (observed_at, expected, legacy) in [
|
||||
for (observed_at, expected, display) in [
|
||||
(None, json!(null), "—"),
|
||||
(Some(now), json!({ "kind": "just_now" }), "刚刚"),
|
||||
(
|
||||
@@ -389,7 +389,7 @@ async fn account_quota_refresh_time_uses_server_clock_and_deployment_timezone()
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let quota = &value["data"]["items"][0]["quota"];
|
||||
assert_eq!(quota["refreshedAtRelative"], expected);
|
||||
assert_eq!(quota["refreshedAtDisplay"], legacy);
|
||||
assert_eq!(quota["refreshedAtDisplay"], display);
|
||||
let refreshed_at = quota["refreshedAt"]
|
||||
.as_str()
|
||||
.map(|value| DateTime::parse_from_rfc3339(value).unwrap().to_utc());
|
||||
|
||||
@@ -610,7 +610,7 @@ fn xai_profile_override_distinguishes_omission_from_explicit_inheritance() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_profile_overrides_accept_native_providers_and_reject_legacy_conflicts() {
|
||||
fn profile_overrides_accept_matching_native_values_and_reject_conflicts_and_unknown_providers() {
|
||||
let profile = json!({"preset":"desktop"});
|
||||
let xai = json!({"preset":"managed"});
|
||||
let request: CreateClientKeyRequest = serde_json::from_value(json!({
|
||||
@@ -676,7 +676,7 @@ fn generic_profile_overrides_accept_native_providers_and_reject_legacy_conflicts
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_profile_override_clear_rejects_conflicting_legacy_update() {
|
||||
fn clearing_an_xai_profile_override_conflicts_with_an_explicit_xai_value() {
|
||||
let request: UpdateClientKeyRequest = serde_json::from_value(json!({
|
||||
"id":"key_profile",
|
||||
"name":"profile",
|
||||
|
||||
@@ -2082,7 +2082,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
("Asia/Kathmandu", "2026-06-15 05:45:01"),
|
||||
("America/New_York", "2026-06-14 20:00:01"),
|
||||
] {
|
||||
for (elapsed_ms, expected, legacy) in [
|
||||
for (elapsed_ms, expected, display) in [
|
||||
(None, json!(null), "—"),
|
||||
(
|
||||
Some(-1_000),
|
||||
@@ -2197,7 +2197,7 @@ async fn dashboard_relative_time_preserves_server_anchor_boundaries_and_deployme
|
||||
account["lastUsedRelative"], expected,
|
||||
"{zone}: {elapsed_ms:?}"
|
||||
);
|
||||
assert_eq!(account["lastUsed"], legacy, "{zone}: {elapsed_ms:?}");
|
||||
assert_eq!(account["lastUsed"], display, "{zone}: {elapsed_ms:?}");
|
||||
assert_eq!(account["lastUsedAt"], json!(last_used_at));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -431,7 +431,7 @@ fn settings_request_accepts_unlimited_default_account_concurrency() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_request_validates_cron_and_allows_disabled_empty_schedule() {
|
||||
fn warmup_cron_is_required_and_may_be_empty_only_when_disabled() {
|
||||
for (enabled, cron, valid) in [
|
||||
(false, "", true),
|
||||
(true, "", false),
|
||||
@@ -461,10 +461,9 @@ fn settings_request_validates_cron_and_allows_disabled_empty_schedule() {
|
||||
let request: UpdateRuntimeSettingsRequest = serde_json::from_value(oversized).unwrap();
|
||||
assert_eq!(request.validate().unwrap_err().field(), "accountWarmupCron");
|
||||
|
||||
let mut legacy = update_body();
|
||||
legacy.as_object_mut().unwrap().remove("accountWarmupCron");
|
||||
legacy["accountWarmupScheduleTime"] = json!("08:00");
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(legacy).is_err());
|
||||
let mut missing = update_body();
|
||||
missing.as_object_mut().unwrap().remove("accountWarmupCron");
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -705,8 +704,6 @@ async fn admin_auth_should_accept_a_configured_request_id_header_name() {
|
||||
|
||||
let fixture = AdminTestFixture::new().await;
|
||||
fixture.auth.insert_session("valid-session");
|
||||
// 部署把 api.request_id_header 改名后,注入的 header 不再叫 x-request-id;
|
||||
// 管理请求仍须拿到请求上下文,而不是退化为 500
|
||||
let custom = HeaderName::from_static("x-trace-id");
|
||||
let app = app(fixture.state()).layer(SetRequestIdLayer::new(custom, MakeRequestUuid));
|
||||
let unlabelled = Request::builder()
|
||||
@@ -919,7 +916,7 @@ fn global_profile_can_be_omitted_but_cannot_be_cleared() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generic_global_profiles_decode_native_providers_and_reject_legacy_conflicts() {
|
||||
async fn global_profiles_decode_native_providers_and_reject_conflicting_openai_settings() {
|
||||
let mut body = update_body();
|
||||
body["providerRequestProfiles"] = json!({
|
||||
"openai":{"preset":"desktop"},
|
||||
|
||||
@@ -743,7 +743,7 @@ async fn request_context_should_resolve_forwarded_precedence_and_peer_fallback()
|
||||
operation_kind: OperationKind::Generate,
|
||||
input: Some(json!("hello")),
|
||||
client_metadata: None,
|
||||
// 客户端 User-Agent 仅用于本地展示,不再透传给上游指纹上下文
|
||||
// 客户端 User-Agent 仅用于本地展示
|
||||
protocol_context: Some(json!({"opaque_request_headers": [
|
||||
["cf-connecting-ip", STANDARD.encode(b"198.51.100.1")],
|
||||
["x-real-ip", STANDARD.encode(b"198.51.100.2")],
|
||||
|
||||
@@ -492,7 +492,7 @@ fn decoder_should_strip_http_transport_but_leave_source_headers_for_provider() {
|
||||
HeaderValue::from_static(r#"{"scheme":"https"}"#),
|
||||
);
|
||||
headers.insert("accept-encoding", HeaderValue::from_static("br, gzip"));
|
||||
// 正文未压缩;入口现在消费 Content-Encoding,但仍不得向上游透传
|
||||
// identity 与未压缩的正文匹配,Content-Encoding 由入口消费
|
||||
headers.insert("content-encoding", HeaderValue::from_static("identity"));
|
||||
headers.insert("x-openai-future-mode", HeaderValue::from_static("keep"));
|
||||
|
||||
|
||||
+1
-1
@@ -358,7 +358,7 @@ async fn rewrite_upgrade_and_control_active_response_keep_http_context_until_con
|
||||
);
|
||||
let (trace, mut socket, server) =
|
||||
start_active_response_with(Some(frozen), "/custom/websocket", "codex-tui/0.166.0").await;
|
||||
// 升级后的默认会话仍持有入口上下文;101 正文结束不再提前取消它
|
||||
// 101 响应完成后,WebSocket 会话继续持有入口上下文
|
||||
assert!(
|
||||
!plan
|
||||
.http_cancellation
|
||||
|
||||
@@ -255,7 +255,7 @@ impl Stream for TestSocket {
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let event = self.incoming.poll_recv(context);
|
||||
// 模拟 Axum transport 的自动 Pong;pump 不再重复实现协议层应答
|
||||
// 模拟 Axum 传输层收到 Ping 时自动回复 Pong
|
||||
if let Poll::Ready(Some(Ok(Message::Ping(payload)))) = &event {
|
||||
self.written
|
||||
.send(Message::Pong(payload.clone()))
|
||||
|
||||
@@ -143,10 +143,10 @@ fn zero_or_absent_window_weights_disable_reset_scores_and_tolerance() {
|
||||
}]
|
||||
.into(),
|
||||
);
|
||||
let legacy = json!({"loadWeight":0,"quotaWeight":0,"healthWeight":0,"latencyWeight":0,"resetWeight":10,"queueWeight":0});
|
||||
let mut disabled = legacy.clone();
|
||||
let omitted = json!({"loadWeight":0,"quotaWeight":0,"healthWeight":0,"latencyWeight":0,"resetWeight":10,"queueWeight":0});
|
||||
let mut disabled = omitted.clone();
|
||||
disabled["resetWindowWeights"] = json!({"fiveHour":0,"weekly":0,"monthly":0});
|
||||
for wire in [legacy, disabled] {
|
||||
for wire in [omitted, disabled] {
|
||||
let config: SmartSchedulingConfig = serde_json::from_value(wire).unwrap();
|
||||
context.policy = context.policy.with_smart_scheduling(config);
|
||||
let trace = gateway_core::diagnostics::TraceContext::new("req_zero_windows");
|
||||
|
||||
@@ -69,7 +69,7 @@ fn privacy_rule_requires_steps_and_rejects_unknown_fields() {
|
||||
missing_steps.as_object_mut().unwrap().remove("steps");
|
||||
assert!(serde_json::from_value::<PrivacyRule>(missing_steps).is_err());
|
||||
let mut unknown_rule_field = value.clone();
|
||||
unknown_rule_field["scope"] = serde_json::json!("request_body");
|
||||
unknown_rule_field["unexpected"] = serde_json::json!(true);
|
||||
assert!(serde_json::from_value::<PrivacyRule>(unknown_rule_field).is_err());
|
||||
let mut unknown_step_field = value;
|
||||
unknown_step_field["steps"][0]["unexpected"] = serde_json::json!(true);
|
||||
|
||||
@@ -139,7 +139,7 @@ fn blocked_file_output_keeps_http_and_streaming_responsive_and_reserves_errors()
|
||||
);
|
||||
let (release, released) = std::sync::mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
// 超时只用于让旧的同步实现能退出测试,接口必须在解除阻塞之前完成
|
||||
// 请求必须在读端放行前完成,超时让写入阻塞时的测试也能退出
|
||||
let _ = released.recv_timeout(Duration::from_secs(3));
|
||||
let mut body = String::new();
|
||||
fs::File::open(fifo)
|
||||
|
||||
@@ -327,7 +327,6 @@ async fn managed_http_enforces_the_callers_body_limit_before_sending() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = HttpClient::new().unwrap();
|
||||
// 覆盖旧固定上限之外的正文,并验证同一个客户端逐次使用调用方的预算
|
||||
let maximum = 17 * 1024 * 1024;
|
||||
for (size, limit, accepted) in [
|
||||
(maximum, maximum, true),
|
||||
|
||||
@@ -24,9 +24,9 @@ async fn invalid_update_state_should_keep_raw_details_out_of_public_error() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_status_should_reconcile_manual_deployment_without_reusing_legacy_success() {
|
||||
async fn manual_deployment_reports_the_running_version_and_preserves_the_last_operation() {
|
||||
let fixture = Fixture::new();
|
||||
fs::write(fixture.state(), r#"{"previousVersion":"3.14.0","currentVersion":"3.14.1","operation":{"operationId":"legacy","kind":"update","status":"succeeded","targetVersion":"3.14.1"}}"#).expect("legacy state");
|
||||
fs::write(fixture.state(), r#"{"previousVersion":"3.14.0","currentVersion":"3.14.1","operation":{"operationId":"completed-update","kind":"update","status":"succeeded","targetVersion":"3.14.1"}}"#).expect("completed update state");
|
||||
let mut config = fixture.config("https://api.github.com/repos");
|
||||
config.version = "3.15.0".to_owned();
|
||||
config.deployment_mode = "docker".to_owned();
|
||||
|
||||
@@ -645,7 +645,7 @@ async fn concurrent_calls_keep_their_wire_ids_monotonic() {
|
||||
}
|
||||
ready.wait().await;
|
||||
entered.await;
|
||||
// 旧实现会在 begin 前分配后续 ID;等其他线程进入该窗口后再释放首调用
|
||||
// 暂停首个 begin,给其他并发调用留出竞争发送顺序的时间
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
callbacks.release();
|
||||
for call in calls {
|
||||
|
||||
@@ -542,8 +542,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
);
|
||||
if let Some(expected) = configuration.get("expected_fast_source") {
|
||||
let sources = &call.request.head.settings_sources["execution"];
|
||||
assert!(sources.get("disable_fast").is_none());
|
||||
assert!(sources["input"].get("disable_fast").is_none());
|
||||
assert_eq!(sources["input"]["fast_mode"], "default");
|
||||
assert_eq!(&sources["fast_mode"], expected);
|
||||
}
|
||||
|
||||
@@ -406,7 +406,7 @@ async fn health_counters_match_for_rollups_and_facts_without_counting_recovery_o
|
||||
sqlx::query("update model_requests set recovered_at=completed_at,recovery_request_id='health_success',recovery_attempt_count=1,request_observation_json=request_observation_json||jsonb_build_object('recovery',jsonb_build_object('retryDelayMs',0,'totalLatencyMs',1)) where id='health_recovered'")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
drain_analytics(&database.pool).await;
|
||||
// 模拟旧桶曾把取消的 499 计入调用方错误,无需重建也应得到相同结果
|
||||
// 即使已存储的桶把 499 计入调用方错误,查询也应将其归为取消
|
||||
sqlx::raw_sql("update request_analytics_15m set counts=jsonb_set(counts,'{caller_error_count}','1') where outcome='cancelled'; update request_analytics_1h set counts=jsonb_set(counts,'{caller_error_count}','1') where outcome='cancelled'")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
let repo = observability_repository(&database.pool);
|
||||
@@ -930,7 +930,7 @@ async fn interrupted_quarters_restart_changed_versions_and_publish_one_consisten
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
// 独立重建请求改变版本,验证旧前缀废弃后仍可恢复,普通源变更不再重启整桶
|
||||
// 显式重建会更换版本,Worker 需要丢弃已处理的前缀并恢复构建
|
||||
sqlx::query("update request_analytics_pending_buckets set change_version=nextval('request_analytics_change_version')")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
drop(worker);
|
||||
@@ -1034,7 +1034,7 @@ async fn backfill_coverage_uses_contiguous_cursor_instead_of_old_corrected_facts
|
||||
] {
|
||||
seed(&database.pool, id, now - TimeDelta::hours(age), &[]).await;
|
||||
}
|
||||
// 模拟迁移后历史队列为空,随后最旧请求发生单点修正
|
||||
// 清空待处理队列后只修正最早的请求,验证中间的时间段仍需回填
|
||||
sqlx::query("delete from request_analytics_pending_requests")
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
|
||||
@@ -811,12 +811,6 @@ async fn openai_admin_provider_persists_the_full_pending_envelope_and_binds_owne
|
||||
.get("mutation")
|
||||
.and_then(Value::as_object)
|
||||
.expect("pending mutation");
|
||||
assert!(
|
||||
payload
|
||||
.expose_to_provider()
|
||||
.get("reauthorization_credential_revision")
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
payload
|
||||
.expose_to_provider()
|
||||
@@ -829,13 +823,8 @@ async fn openai_admin_provider_persists_the_full_pending_envelope_and_binds_owne
|
||||
mutation.get("schema_version").and_then(Value::as_u64),
|
||||
Some(3)
|
||||
);
|
||||
assert!(mutation.get("expected_config_revision").is_none());
|
||||
assert!(
|
||||
mutation
|
||||
.get("target")
|
||||
.and_then(Value::as_object)
|
||||
.is_some_and(|target| target.get("expected_credential_revision").is_none())
|
||||
);
|
||||
assert_eq!(mutation["target"]["kind"], "create");
|
||||
assert_eq!(mutation["target"]["name"], "OAuth account");
|
||||
assert_eq!(
|
||||
mutation.get("started_request_id").and_then(Value::as_str),
|
||||
Some("request-start")
|
||||
@@ -1037,11 +1026,6 @@ async fn openai_reauthorization_pending_payload_reuses_the_account_installation_
|
||||
document.get("installation_id").and_then(Value::as_str),
|
||||
Some(expected_installation_id.as_str())
|
||||
);
|
||||
assert!(
|
||||
document
|
||||
.get("reauthorization_credential_revision")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
target.get("kind").and_then(Value::as_str),
|
||||
Some("reauthorize")
|
||||
@@ -1050,7 +1034,6 @@ async fn openai_reauthorization_pending_payload_reuses_the_account_installation_
|
||||
target.get("account_id").and_then(Value::as_str),
|
||||
Some("acct_pending_reauth")
|
||||
);
|
||||
assert!(target.get("expected_credential_revision").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2942,7 +2925,6 @@ mod errors {
|
||||
.prepare_refresh(command())
|
||||
.await
|
||||
.unwrap_err();
|
||||
// 既有 transport 策略未认定此错误为安全重试,本次不能因展示更详细而放宽重试边界
|
||||
assert_eq!(error.kind(), Kind::Ambiguous);
|
||||
assert_eq!(
|
||||
error.public_message(),
|
||||
|
||||
@@ -232,7 +232,6 @@ async fn warmup_uses_global_profile_and_lowest_reasoning_effort() {
|
||||
zstd::stream::decode_all(requests[0].body.as_slice()).expect("zstd body should decode");
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(&decoded).expect("warmup body should be valid JSON");
|
||||
// 上游按目录拒绝目录外的档位,none 曾让全部定时预热只留下 error 终态
|
||||
assert_eq!(body["reasoning"]["effort"], "low");
|
||||
*policy.0.lock().unwrap() = OpaqueProviderData::new(
|
||||
json!({"mode":"custom","userAgent":"invalid"})
|
||||
|
||||
@@ -3559,7 +3559,7 @@ async fn assert_cross_endpoint_affinity(thread_id: Option<&str>) {
|
||||
}
|
||||
drop(same);
|
||||
|
||||
// 仍由旧租约流程报告繁忙并换号,亲和不绕过并发限制
|
||||
// 亲和账号的并发租约已满时,请求应切换账号
|
||||
leases
|
||||
.busy_accounts
|
||||
.lock()
|
||||
|
||||
@@ -432,8 +432,7 @@ async fn lagged_profiles_track_observed_release_history() {
|
||||
);
|
||||
}
|
||||
|
||||
/// 重启后恢复缓存、首次检查即发现新版:恢复版本必须进入发布历史,
|
||||
/// 滞后一档不能跳回启动种子(PR #339 审查反馈的触发序列)。
|
||||
/// 重启后首次检查发现新版时,滞后一档应选中从缓存恢复的版本
|
||||
#[tokio::test]
|
||||
async fn restored_cache_release_should_stay_in_version_lag_history() {
|
||||
use provider_openai::transport::profile::selection::ClientProfileSelection;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! 验证 HTTP 与 WebSocket 的 TLS 握手特征
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
|
||||
use bytes::{Buf as _, Bytes};
|
||||
|
||||
@@ -10,11 +8,8 @@ use super::*;
|
||||
|
||||
const CASE_ENV: &str = "CODEX_PROXY_TEST_HTTP_CLIENT_HELLO";
|
||||
const CASE_COMPLETED: &str = "http-tls-client-hello-case-completed";
|
||||
const REFERENCE_ENV: &str = "CODEX_PROXY_TEST_REFERENCE_BINARY";
|
||||
|
||||
// 基线来自官方 Codex 823ea830c0 的客户端源码,各路径重复采样五次
|
||||
// HTTP 另与本机 Core 0.160.0 的采样核对,源码客户端与本项目还通过真实 models 请求验证
|
||||
// HTTP/native-tls 的扩展顺序固定;WebSocket/rustls 会随机化扩展顺序和临时密钥
|
||||
// 握手基线对应官方 Codex 823ea830c0,rustls 的扩展顺序和临时密钥按连接变化
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ClientHello {
|
||||
legacy_version: u16,
|
||||
@@ -57,81 +52,22 @@ fn http_client_hellos_should_match_official_tls_transports() {
|
||||
return;
|
||||
}
|
||||
|
||||
run_isolated_cases(
|
||||
"transport::tls::http_client_hellos_should_match_official_tls_transports",
|
||||
&["native", "custom-ca"],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires CODEX_PROXY_TEST_REFERENCE_BINARY pointing to the official Codex executable"]
|
||||
fn client_hellos_should_match_the_official_binary_on_this_platform() {
|
||||
let reference = std::env::var_os(REFERENCE_ENV)
|
||||
.map(std::path::PathBuf::from)
|
||||
.expect("set CODEX_PROXY_TEST_REFERENCE_BINARY to the official Codex executable")
|
||||
.canonicalize()
|
||||
.expect("official Codex executable path");
|
||||
if let Ok(case) = std::env::var(CASE_ENV) {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
for sample in 0..3 {
|
||||
let mut expected = capture_official_hello(&reference, case == "websocket").await;
|
||||
let mut actual = if case == "websocket" {
|
||||
capture_websocket_hello().await
|
||||
} else {
|
||||
capture_http_hello(provider_openai::transport::build_reqwest_client().unwrap())
|
||||
.await
|
||||
};
|
||||
// rustls 随机排列扩展,其他字段及各自列表的顺序仍逐项核对
|
||||
if case != "native" {
|
||||
expected.extensions.sort_unstable();
|
||||
actual.extensions.sort_unstable();
|
||||
}
|
||||
assert_eq!(actual, expected, "{case} ClientHello sample {sample}");
|
||||
}
|
||||
});
|
||||
println!("\n{CASE_COMPLETED}");
|
||||
return;
|
||||
}
|
||||
|
||||
let version = Command::new(&reference)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.expect("read official Codex version");
|
||||
assert!(version.status.success());
|
||||
println!(
|
||||
"TLS reference: {} on {}-{}",
|
||||
String::from_utf8_lossy(&version.stdout).trim(),
|
||||
std::env::consts::OS,
|
||||
std::env::consts::ARCH,
|
||||
);
|
||||
run_isolated_cases(
|
||||
"transport::tls::client_hellos_should_match_the_official_binary_on_this_platform",
|
||||
&["native", "custom-ca", "websocket"],
|
||||
);
|
||||
}
|
||||
|
||||
fn run_isolated_cases(test_name: &str, cases: &[&str]) {
|
||||
// Cargo 运行测试时可能注入 SSL_CERT_FILE,生产代码会把它视作自定义 CA 并切到 rustls;
|
||||
// 因此在清理相关环境变量的子进程里验证默认路径
|
||||
let current_exe = std::env::current_exe().expect("current test binary path");
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let ca_path = directory.path().join("ca.pem");
|
||||
std::fs::write(&ca_path, TEST_CA_PEM).unwrap();
|
||||
for case in cases {
|
||||
for case in ["native", "custom-ca"] {
|
||||
let mut command = Command::new(¤t_exe);
|
||||
command
|
||||
.arg("--exact")
|
||||
.arg(test_name)
|
||||
.arg("--include-ignored")
|
||||
.arg("transport::tls::http_client_hellos_should_match_official_tls_transports")
|
||||
.arg("--nocapture")
|
||||
.env(CASE_ENV, case)
|
||||
.env_remove(provider_openai::transport::tls::CODEX_CA_CERT_ENV)
|
||||
.env_remove(provider_openai::transport::tls::SSL_CERT_FILE_ENV);
|
||||
if *case == "custom-ca" {
|
||||
if case == "custom-ca" {
|
||||
command.env(provider_openai::transport::tls::CODEX_CA_CERT_ENV, &ca_path);
|
||||
}
|
||||
let output = command.output().expect("run isolated TLS ClientHello case");
|
||||
@@ -153,70 +89,6 @@ fn run_isolated_cases(test_name: &str, cases: &[&str]) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn capture_official_hello(reference: &Path, websocket: bool) -> ClientHello {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let endpoint = format!(
|
||||
"https://localhost:{}/v1",
|
||||
listener.local_addr().unwrap().port()
|
||||
);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
// 官方进程只访问本机采集端点,握手后即终止,认证使用无效测试值
|
||||
let mut command = tokio::process::Command::new(reference);
|
||||
command
|
||||
.args([
|
||||
"exec",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
"--ephemeral",
|
||||
"--skip-git-repo-check",
|
||||
"--sandbox",
|
||||
"read-only",
|
||||
"--json",
|
||||
"--model",
|
||||
"tls-probe",
|
||||
])
|
||||
.current_dir(directory.path())
|
||||
.env("CPR_TLS_PROBE_API_KEY", "test-local-handshake-only")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true);
|
||||
for name in [
|
||||
"HTTP_PROXY",
|
||||
"HTTPS_PROXY",
|
||||
"ALL_PROXY",
|
||||
"http_proxy",
|
||||
"https_proxy",
|
||||
"all_proxy",
|
||||
] {
|
||||
command.env_remove(name);
|
||||
}
|
||||
for setting in [
|
||||
"model_provider=\"cpr_tls_probe\"".to_owned(),
|
||||
"model_providers.cpr_tls_probe.name=\"CPR TLS Probe\"".to_owned(),
|
||||
format!("model_providers.cpr_tls_probe.base_url=\"{endpoint}\""),
|
||||
"model_providers.cpr_tls_probe.env_key=\"CPR_TLS_PROBE_API_KEY\"".to_owned(),
|
||||
"model_providers.cpr_tls_probe.wire_api=\"responses\"".to_owned(),
|
||||
format!("model_providers.cpr_tls_probe.supports_websockets={websocket}"),
|
||||
"model_providers.cpr_tls_probe.request_max_retries=0".to_owned(),
|
||||
"model_providers.cpr_tls_probe.stream_max_retries=0".to_owned(),
|
||||
"project_doc_max_bytes=0".to_owned(),
|
||||
] {
|
||||
command.args(["--config", &setting]);
|
||||
}
|
||||
let mut child = command
|
||||
.arg("TLS handshake capture")
|
||||
.spawn()
|
||||
.expect("start official Codex TLS reference");
|
||||
let hello = timeout(Duration::from_secs(30), read_client_hello(listener)).await;
|
||||
let _ = child.kill().await;
|
||||
child
|
||||
.wait()
|
||||
.await
|
||||
.expect("reap official Codex TLS reference");
|
||||
hello.expect("official Codex ClientHello within timeout")
|
||||
}
|
||||
|
||||
async fn capture_http_hello(client: reqwest::Client) -> ClientHello {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!(
|
||||
@@ -237,19 +109,13 @@ async fn capture_http_hello(client: reqwest::Client) -> ClientHello {
|
||||
|
||||
#[tokio::test]
|
||||
async fn websocket_client_hello_should_match_official_rustls_transport() {
|
||||
let mut hello = capture_websocket_hello().await;
|
||||
hello.extensions.sort_unstable();
|
||||
assert_eq!(hello, official_websocket_hello());
|
||||
}
|
||||
|
||||
async fn capture_websocket_hello() -> ClientHello {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("wss://localhost:{}/", listener.local_addr().unwrap().port());
|
||||
let connector =
|
||||
provider_openai::transport::tls::maybe_build_rustls_client_config_with_custom_ca()
|
||||
.unwrap()
|
||||
.map(tokio_tungstenite::Connector::Rustls);
|
||||
let (hello, response) = timeout(Duration::from_secs(10), async {
|
||||
let (mut hello, response) = timeout(Duration::from_secs(10), async {
|
||||
tokio::join!(
|
||||
read_client_hello(listener),
|
||||
tokio_tungstenite::connect_async_tls_with_config(url, None, false, connector)
|
||||
@@ -261,7 +127,8 @@ async fn capture_websocket_hello() -> ClientHello {
|
||||
response.is_err(),
|
||||
"capture endpoint rejects TLS after ClientHello"
|
||||
);
|
||||
hello
|
||||
hello.extensions.sort_unstable();
|
||||
assert_eq!(hello, official_websocket_hello());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
|
||||
@@ -875,7 +875,6 @@ async fn websocket_execute_response_create_request_should_forward_typed_events_w
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket(stream).await;
|
||||
let _message = websocket.next().await.unwrap().unwrap();
|
||||
// 透明代理:缺官方必需字段的 delta 事件不再被丢弃,原样转发
|
||||
websocket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
|
||||
@@ -982,8 +982,7 @@ async fn websocket_pool_should_release_slot_when_client_drops_stream() {
|
||||
.contains("streaming has begun")
|
||||
);
|
||||
|
||||
// 客户端断开:drop stream → rx 被 drop → tx.closed() 完成 →
|
||||
// 代理丢弃上游连接并释放 slot(不再等 idle 超时)
|
||||
// 客户端丢弃响应流会触发上游连接关闭,池槽位在空闲超时前释放
|
||||
drop(stream);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
|
||||
@@ -403,18 +403,7 @@ async fn xai_admin_provider_restores_full_pending_envelope_and_binds_owner() {
|
||||
let flow_id = "pending-envelope";
|
||||
let owner_ref = admin_session_owner_ref("admin-owner");
|
||||
let payload = pending_payload(flow_id, &owner_ref);
|
||||
pending.insert(flow_id, owner_ref, payload.clone());
|
||||
|
||||
let mutation = payload
|
||||
.expose_to_provider()
|
||||
.get("mutation")
|
||||
.and_then(Value::as_object)
|
||||
.expect("pending mutation");
|
||||
assert_eq!(mutation.get("expected_config_revision"), None);
|
||||
assert_eq!(
|
||||
mutation.get("started_request_id").and_then(Value::as_str),
|
||||
Some("request-start")
|
||||
);
|
||||
pending.insert(flow_id, owner_ref, payload);
|
||||
|
||||
let wrong_owner = bundle
|
||||
.admin_provider()
|
||||
@@ -610,8 +599,6 @@ async fn xai_admin_provider_projects_cached_quota_models_and_canonical_export()
|
||||
assert_eq!(window_data["onDemandCapCents"], 500);
|
||||
assert_eq!(window_data["onDemandUsedCents"], 100);
|
||||
assert_eq!(window_data["prepaidBalanceCents"], -500);
|
||||
assert!(!window_data.contains_key("monthlyLimitCents"));
|
||||
assert!(!window_data.contains_key("includedUsedCents"));
|
||||
let models = admin
|
||||
.models(account.id(), false)
|
||||
.await
|
||||
|
||||
@@ -26,7 +26,7 @@ fn repository() -> (Arc<MemoryProviderAccountStore>, GrokCredentialRepository) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_persists_plaintext_oauth_json_without_envelope_fields() {
|
||||
async fn create_persists_oauth_method_and_tokens_in_provider_json() {
|
||||
let (store, _) = repository();
|
||||
let input = create_input("plain", "subject-plain");
|
||||
seed_input(&store, &input).await.expect("create account");
|
||||
@@ -47,8 +47,6 @@ async fn create_persists_plaintext_oauth_json_without_envelope_fields() {
|
||||
object.get("refresh_token").and_then(|v| v.as_str()),
|
||||
Some("refresh-plain")
|
||||
);
|
||||
assert!(!object.contains_key("secret_envelope"));
|
||||
assert!(!object.contains_key("secret_key_id"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -159,8 +159,7 @@ impl GrokEndpointPolicy for CatalogExitPolicy {
|
||||
timeout: Option<Duration>,
|
||||
proxy: Option<&OutboundProxy>,
|
||||
) -> Result<reqwest::Client, GrokReqwestTransportBuildError> {
|
||||
// “直连”也终止于本地 sink,旧实现漏代理时不会触达真实上游
|
||||
// 显式代理分支仍使用生产构造器及官方 HTTPS/CONNECT 目标
|
||||
// 直连请求落到本地监听器,显式代理请求通过生产构造器连接 HTTPS 目标
|
||||
OfficialGrokEndpointPolicy
|
||||
.build_inference_client(timeout, Some(proxy.unwrap_or(&self.direct_sink)))
|
||||
}
|
||||
|
||||
@@ -405,7 +405,7 @@ async fn inference_proxy_client_is_built_once_for_concurrent_same_binding() {
|
||||
for task in tasks {
|
||||
assert!(task.await.unwrap().iter().all(Result::is_ok));
|
||||
}
|
||||
// 启动时的直连 client + 一个代理 client;不再先构建并丢弃另一个直连 client
|
||||
// 一个启动时创建的直连客户端和一个并发请求共用的代理客户端
|
||||
assert_eq!(builds.load(Ordering::SeqCst), 2);
|
||||
assert!(origin_server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
@@ -1097,7 +1097,7 @@ fn history_sanitizer_should_only_strip_known_grok_injection_sites() {
|
||||
.expect("history normalization");
|
||||
let body = Value::Object(encoded.body().clone());
|
||||
|
||||
// 工具 schema 里恰好叫 phase 的属性与语义 null 不再被误删
|
||||
// 工具 schema 内的属性名和 null 值属于用户数据
|
||||
assert_eq!(
|
||||
body.pointer("/input/0/tools/0/input_schema/properties/phase"),
|
||||
Some(&json!({"type": "string"}))
|
||||
@@ -1312,7 +1312,7 @@ fn unsupported_tools_should_be_filtered_with_their_orphaned_choice() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_tool_contracts_should_fail_before_upstream_io() {
|
||||
fn invalid_responses_requests_report_the_offending_field() {
|
||||
for (body, field) in [
|
||||
(
|
||||
json!({"model": "client", "input": "x", "tools": [
|
||||
@@ -1339,33 +1339,34 @@ fn ambiguous_tool_contracts_should_fail_before_upstream_io() {
|
||||
json!({"model": "client", "input": [{"type": "compaction_trigger"}]}),
|
||||
"input",
|
||||
),
|
||||
(
|
||||
json!({"input": [{"type":"local_shell_call", "call_id":"call_shell",
|
||||
"action":{"type":"exec", "command":["pwd"]}}]}),
|
||||
"input",
|
||||
),
|
||||
(
|
||||
json!({"input": [{"type":"local_shell_call_output", "call_id":"call_shell", "output":"ok"}]}),
|
||||
"input",
|
||||
),
|
||||
(
|
||||
json!({"input":"hello", "response_format":{"type":"json_object"}}),
|
||||
"response_format",
|
||||
),
|
||||
(
|
||||
json!({"input":"hello", "reasoning_effort":"high"}),
|
||||
"reasoning_effort",
|
||||
),
|
||||
(
|
||||
json!({"input":"hello", "reasoningEffort":"high"}),
|
||||
"reasoningEffort",
|
||||
),
|
||||
] {
|
||||
let request = raw_request(body);
|
||||
assert_eq!(
|
||||
GrokResponsesRequest::encode(&request, "grok-4.5", &client_key())
|
||||
.expect_err("invalid tool contract"),
|
||||
GrokRequestEncodeError::InvalidRequestField { field }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_wire_formats_are_rejected_without_fallback() {
|
||||
for field in ["response_format", "reasoning_effort", "reasoningEffort"] {
|
||||
let mut body = json!({"input":"hello"});
|
||||
body[field] = json!("high");
|
||||
assert!(
|
||||
GrokResponsesRequest::encode(&raw_request(body), "grok-4.6", &client_key()).is_err()
|
||||
);
|
||||
}
|
||||
for kind in ["local_shell_call", "local_shell_call_output"] {
|
||||
assert!(
|
||||
GrokResponsesRequest::encode(
|
||||
&raw_request(json!({"input":[{"type":kind,"call_id":"old"}]})),
|
||||
"grok-4.6",
|
||||
&client_key()
|
||||
)
|
||||
.is_err()
|
||||
.expect_err("invalid Responses request"),
|
||||
GrokRequestEncodeError::InvalidRequestField { field },
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-25
@@ -66,31 +66,7 @@ HTTP 入口位于 `backend/crates/gateway-api/src/openai/messages.rs`,
|
||||
再核对工具往返、取消、错误和输入计数;请求格式及六种组合见 [模型数据面](api.md#3-模型数据面与模型目录)。
|
||||
Messages 账号只配置 HTTP;本地计数估算不能替代上游计费核对
|
||||
|
||||
TLS 指纹在发布目标对应的操作系统和架构上核验,参考程序使用同机运行的官方 Codex CLI 可执行文件。
|
||||
`CODEX_PROXY_TEST_REFERENCE_BINARY` 指向实际二进制,Windows 使用 `.exe`,npm 安装时使用平台包中的二进制。
|
||||
macOS / Linux 可设置:
|
||||
|
||||
```bash
|
||||
export CODEX_PROXY_TEST_REFERENCE_BINARY=/absolute/path/to/codex
|
||||
export RUST_MIN_STACK=16777216
|
||||
```
|
||||
|
||||
Windows PowerShell 可设置:
|
||||
|
||||
```powershell
|
||||
$env:CODEX_PROXY_TEST_REFERENCE_BINARY = 'C:\path\to\codex.exe'
|
||||
$env:RUST_MIN_STACK = '16777216'
|
||||
```
|
||||
|
||||
随后在仓库根目录执行:
|
||||
|
||||
```text
|
||||
cargo +1.99.1 test --manifest-path backend/Cargo.toml --locked -p provider-openai --test main transport::tls:: -- --include-ignored --nocapture --test-threads=1
|
||||
```
|
||||
|
||||
对照用例记录官方版本及运行平台,分别采样默认 HTTP、自定义 CA 的 HTTP 和 WebSocket,各重复三次。
|
||||
默认 HTTP 保留扩展顺序逐项比较;rustls 路径对随机扩展顺序排序后比较,算法列表、密钥交换组和 ALPN 仍核对原有顺序。
|
||||
采集在本机 TLS 握手阶段结束,使用测试认证值,无需真实账号。普通测试默认忽略官方二进制对照用例,须以上述命令显式执行
|
||||
OpenAI 的 `transport::tls::` 测试在本机回环地址采集 ClientHello,覆盖默认 HTTP、自定义 CA 的 HTTP 和 WebSocket。运行方式见[后端验证命令](architecture.md#验证命令)
|
||||
|
||||
## 源码联调
|
||||
|
||||
|
||||
Reference in New Issue
Block a user