Add Statsig bootstrap to the Codex backend client (#63448)

## What changed

Expose `Client::statsig_bootstrap` and `StatsigBootstrapContext` so callers
can fetch server-evaluated Statsig values using the client's existing
authentication. The client posts the targeting context to the bootstrap
endpoint for its configured API and returns the `statsigPayload` string.

## Testing

Add a mock-server test that checks the ChatGPT route, bearer token,
account header, and JSON request body, and verifies that the client
returns the payload string from the response.

GitOrigin-RevId: 0bbe812ee036c5bf744f9e07d01b70e9c241cce3
This commit is contained in:
iceweasel-oai
2026-11-23 21:56:18 +00:00
committed by copyberry
parent 9c5ebee9df
commit c7ef448428
4 changed files with 107 additions and 0 deletions
+1
View File
@@ -48,6 +48,7 @@ mod chatgpt_turn_cost;
pub(crate) mod plan_history;
pub(crate) mod profile;
mod rate_limit_resets;
pub(crate) mod statsig;
pub(crate) mod task_usage;
mod thread_usage;
pub(crate) mod turn_usage;
@@ -0,0 +1,58 @@
//! Fetches server-evaluated Statsig values using the existing Codex backend identity.
use std::time::Duration;
use anyhow::Result;
use anyhow::anyhow;
use http::Method;
use serde::Deserialize;
use serde::Serialize;
use super::Client;
use super::PathStyle;
/// Client-supplied targeting fields. The backend adds authenticated account and user fields.
#[derive(Clone, Serialize)]
pub struct StatsigBootstrapContext {
/// Statsig Target App name. The backend maps it to a client SDK key.
pub target_app: &'static str,
pub stable_id: String,
pub app_version: String,
pub locale: Option<String>,
pub system_name: String,
pub system_version: String,
pub window_type: &'static str,
pub brand_name: &'static str,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StatsigBootstrapResponse {
statsig_payload: String,
}
impl Client {
pub async fn statsig_bootstrap(&self, context: &StatsigBootstrapContext) -> Result<String> {
let path = match self.path_style {
PathStyle::CodexApi => "/api/codex/statsig/bootstrap",
PathStyle::ChatGptApi => "/wham/statsig/bootstrap",
};
let url = format!("{}{path}", self.base_url);
self.auth.validate_destination(&self.base_url, &url)?;
let response = self
.request(Method::POST, &url)
.headers(self.headers().await?)
.timeout(Duration::from_secs(10))
.json(context)
.send()
.await
.map_err(codex_http_client::RouteAwareRequestError::without_url)?;
let status = response.status();
anyhow::ensure!(status.is_success(), "Statsig bootstrap returned {status}");
let response: StatsigBootstrapResponse = response
.json()
.await
.map_err(|_| anyhow!("Could not read the Statsig bootstrap response"))?;
Ok(response.statsig_payload)
}
}
@@ -14,6 +14,7 @@ use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
@@ -60,6 +61,52 @@ async fn transcribe_audio_posts_multipart_file_and_returns_text() {
assert_eq!(request.body, expected_body);
}
#[tokio::test]
async fn statsig_bootstrap_uses_chatgpt_auth_and_unwraps_evaluations() -> Result<()> {
let server = MockServer::start().await;
let payload = r#"{"feature_gates":{}}"#;
Mock::given(method("POST"))
.and(path("/backend-api/wham/statsig/bootstrap"))
.and(header("authorization", "Bearer test-token"))
.and(header("chatgpt-account-id", "test-account"))
.and(body_json(serde_json::json!({
"target_app": "PUBLIC-EVERYTHING-LEAKS-codex-cli",
"stable_id": "test-install",
"app_version": "1.0",
"locale": "en-US",
"system_name": "test-os",
"system_version": "1",
"window_type": "cli",
"brand_name": "codex"
})))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"statsigPayload": payload
})))
.expect(1)
.mount(&server)
.await;
let client = Client::new_without_redirects(
format!("{}/backend-api", server.uri()),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.with_bearer_token("test-token".into())?
.with_chatgpt_account_id("test-account");
let values = client
.statsig_bootstrap(&crate::StatsigBootstrapContext {
target_app: "PUBLIC-EVERYTHING-LEAKS-codex-cli",
stable_id: "test-install".into(),
app_version: "1.0".into(),
locale: Some("en-US".into()),
system_name: "test-os".into(),
system_version: "1".into(),
window_type: "cli",
brand_name: "codex",
})
.await?;
assert_eq!(values, payload);
Ok(())
}
#[tokio::test]
async fn client_preserves_supplied_factory_and_typed_policy_denial() {
let controller = codex_http_client::NetworkPolicyController::default();
+1
View File
@@ -19,6 +19,7 @@ pub use client::profile::ProfileInvocation;
pub use client::profile::ProfileInvocationKind;
pub use client::profile::ProfileMetadata;
pub use client::profile::ProfileStats;
pub use client::statsig::StatsigBootstrapContext;
pub use client::turn_usage::ApiKeyResponseCost;
pub use client::turn_usage::ApiKeyTurnCost;
pub use client::turn_usage::ApiKeyTurnCostStatus;