Standardize response request IDs across Codex clients (#65135)

## Why

Different response paths recognize different request ID headers, so
diagnostics can lose the ID needed to correlate a failed request. For
example, an Azure response may carry only `x-ms-request-id`.

## What changed

Use `CodexHeaderMap` to share response header parsing across API clients,
OAuth errors, and response debug context. When a caller needs one
request ID, fall back to the next supported header if the preferred
value is missing, empty, or unreadable.

Preserve recognized request ID headers on Responses WebSocket
handshakes. Use a shared summary for remote control errors and tracing,
omitting sensitive, empty, unreadable, and unrelated values.

## Testing

Cover fallback from an empty or unreadable primary ID, Azure-only debug
context, filtering in diagnostic summaries, and preservation of request
IDs in WebSocket handshakes and remote control pairing errors.

GitOrigin-RevId: f728a4a867f4705b784916b331f413e560f8626b
This commit is contained in:
Adam Perry @ OpenAI
2026-12-02 01:44:46 +00:00
committed by copyberry
parent cf24cd5a93
commit 55ea9a4620
26 changed files with 366 additions and 182 deletions
+2
View File
@@ -4077,6 +4077,7 @@ dependencies = [
"opentelemetry_sdk",
"pretty_assertions",
"rcgen",
"ref-cast",
"reqwest 0.12.28",
"rustls",
"rustls-native-certs",
@@ -4961,6 +4962,7 @@ version = "0.0.0"
dependencies = [
"base64 0.22.1",
"codex-api",
"codex-http-client",
"http 1.4.0",
"pretty_assertions",
"serde_json",
@@ -2,16 +2,15 @@ use super::auth::RemoteControlAuth;
use super::auth::RemoteControlConnectionAuth;
use super::auth::load_remote_control_auth;
use super::auth::recover_remote_control_auth;
use super::enroll::format_headers;
use super::enroll::preview_remote_control_response_body;
use super::protocol::normalize_remote_control_base_url;
use axum::http::HeaderMap;
use codex_app_server_protocol::RemoteControlClient;
use codex_app_server_protocol::RemoteControlClientsListOrder;
use codex_app_server_protocol::RemoteControlClientsListParams;
use codex_app_server_protocol::RemoteControlClientsListResponse;
use codex_app_server_protocol::RemoteControlClientsRevokeParams;
use codex_app_server_protocol::RemoteControlClientsRevokeResponse;
use codex_http_client::CodexHeaderMap;
use serde::Deserialize;
use std::io;
use std::io::ErrorKind;
@@ -60,7 +59,7 @@ enum ClientManagementRequest<'a> {
struct ClientManagementResponse {
status: axum::http::StatusCode,
headers: HeaderMap,
headers: CodexHeaderMap,
body: Vec<u8>,
}
@@ -103,9 +102,9 @@ pub(super) async fn list_remote_control_clients(
ensure_success_response(status, &headers, &url, &body_preview, "client list")?;
let response = serde_json::from_slice::<ListRemoteControlClientsResponse>(&body).map_err(
|err| {
let ids = headers.request_id_summary();
io::Error::other(format!(
"failed to parse remote control client list response from `{url}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
format_headers(&headers)
"failed to parse remote control client list response from `{url}`: HTTP {status}, request IDs: {ids}, body: {body_preview}, decode error: {err}"
))
},
)?;
@@ -224,7 +223,7 @@ async fn send_client_management_request_once(
codex_http_client::HttpError::Policy(_) => super::auth::request_error(error),
error => io::Error::other(format!("failed to {action}: {error}")),
})?;
let headers = response.headers().clone();
let headers = response.codex_headers().copy_request_id_headers();
let status = response.status();
let body = response
.bytes()
@@ -240,7 +239,7 @@ async fn send_client_management_request_once(
fn ensure_success_response(
status: axum::http::StatusCode,
headers: &HeaderMap,
headers: &CodexHeaderMap,
url: &Url,
body_preview: &str,
response_kind: &str,
@@ -254,11 +253,11 @@ fn ensure_success_response(
404 => ErrorKind::NotFound,
_ => ErrorKind::Other,
};
let ids = headers.request_id_summary();
Err(io::Error::new(
error_kind,
format!(
"remote control {response_kind} failed at `{url}`: HTTP {status}, {}, body: {body_preview}",
format_headers(headers)
"remote control {response_kind} failed at `{url}`: HTTP {status}, request IDs: {ids}, body: {body_preview}"
),
))
}
@@ -7,7 +7,6 @@ use super::protocol::StartRemoteControlPairingRequest;
use super::protocol::StartRemoteControlPairingResponse;
use super::server_api::RemoteControlServerRequestError;
use super::server_api::retry_after_with_jitter;
use axum::http::HeaderMap;
use axum::http::StatusCode;
use codex_app_server_protocol::RemoteControlPairingStartResponse;
use codex_app_server_protocol::RemoteControlPairingStatusResponse;
@@ -25,10 +24,6 @@ const REMOTE_CONTROL_PAIRING_TIMEOUT: std::time::Duration = std::time::Duration:
const REMOTE_CONTROL_RESPONSE_BODY_MAX_BYTES: usize = 4096;
const REMOTE_CONTROL_SERVER_TOKEN_REFRESH_SKEW_SECS: i64 = 5 * 60;
const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
const CF_RAY_HEADER: &str = "cf-ray";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct RemoteControlEnrollment {
pub(super) remote_control_target: RemoteControlTarget,
@@ -73,9 +68,10 @@ impl RemoteControlEnrollment {
.send()
.await
.map_err(super::auth::request_error)?;
let headers = response.headers().clone();
let headers = response.codex_headers().copy_request_id_headers();
let ids = headers.request_id_summary();
let status = response.status();
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
let retry_at = retry_after_with_jitter(response.headers(), OffsetDateTime::now_utc());
let body = response.bytes().await.map_err(|err| {
if matches!(err, codex_http_client::HttpError::Policy(_))
&& !(retry_at.is_some() && matches!(status.as_u16(), 429 | 503))
@@ -101,9 +97,8 @@ impl RemoteControlEnrollment {
};
return Err(pairing_response_error(
format!(
"remote control pairing failed at `{}`: HTTP {status}, {}, body: {body_preview}",
"remote control pairing failed at `{}`: HTTP {status}, request IDs: {ids}, body: {body_preview}",
self.remote_control_target.pair_url,
format_headers(&headers)
),
status,
retry_at,
@@ -114,9 +109,8 @@ impl RemoteControlEnrollment {
let pairing = serde_json::from_slice::<StartRemoteControlPairingResponse>(&body).map_err(
|err| {
io::Error::other(format!(
"failed to parse remote control pairing response from `{}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
"failed to parse remote control pairing response from `{}`: HTTP {status}, request IDs: {ids}, body: {body_preview}, decode error: {err}",
self.remote_control_target.pair_url,
format_headers(&headers)
))
},
)?;
@@ -138,9 +132,8 @@ impl RemoteControlEnrollment {
io::Error::new(
ErrorKind::InvalidData,
format!(
"failed to parse remote control pairing response from `{}`: HTTP {status}, {}, body: {body_preview}, expires_at parse error: {err}",
"failed to parse remote control pairing response from `{}`: HTTP {status}, request IDs: {ids}, body: {body_preview}, expires_at parse error: {err}",
self.remote_control_target.pair_url,
format_headers(&headers)
),
)
})?
@@ -181,9 +174,10 @@ impl RemoteControlEnrollment {
.send()
.await
.map_err(super::auth::request_error)?;
let headers = response.headers().clone();
let headers = response.codex_headers().copy_request_id_headers();
let ids = headers.request_id_summary();
let status = response.status();
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
let retry_at = retry_after_with_jitter(response.headers(), OffsetDateTime::now_utc());
let body = response.bytes().await.map_err(|err| {
if matches!(err, codex_http_client::HttpError::Policy(_))
&& !(retry_at.is_some() && matches!(status.as_u16(), 429 | 503))
@@ -209,9 +203,8 @@ impl RemoteControlEnrollment {
};
return Err(pairing_response_error(
format!(
"remote control pairing status failed at `{}`: HTTP {status}, {}, body: {body_preview}",
"remote control pairing status failed at `{}`: HTTP {status}, request IDs: {ids}, body: {body_preview}",
self.remote_control_target.pair_status_url,
format_headers(&headers)
),
status,
retry_at,
@@ -222,9 +215,8 @@ impl RemoteControlEnrollment {
let response = serde_json::from_slice::<BackendRemoteControlPairingStatusResponse>(&body)
.map_err(|err| {
io::Error::other(format!(
"failed to parse remote control pairing status response from `{}`: HTTP {status}, {}, body: {body_preview}, decode error: {err}",
"failed to parse remote control pairing status response from `{}`: HTTP {status}, request IDs: {ids}, body: {body_preview}, decode error: {err}",
self.remote_control_target.pair_status_url,
format_headers(&headers)
))
})?;
Ok(RemoteControlPairingStatusResponse {
@@ -460,19 +452,6 @@ fn redact_remote_control_response_body(body: &str) -> String {
body_json.to_string()
}
pub(crate) fn format_headers(headers: &HeaderMap) -> String {
let request_id_str = headers
.get(REQUEST_ID_HEADER)
.or_else(|| headers.get(OAI_REQUEST_ID_HEADER))
.map(|value| value.to_str().unwrap_or("<invalid utf-8>").to_owned())
.unwrap_or_else(|| "<none>".to_owned());
let cf_ray_str = headers
.get(CF_RAY_HEADER)
.map(|value| value.to_str().unwrap_or("<invalid utf-8>").to_owned())
.unwrap_or_else(|| "<none>".to_owned());
format!("request-id: {request_id_str}, cf-ray: {cf_ray_str}")
}
#[cfg(test)]
mod tests {
use super::*;
@@ -735,7 +714,7 @@ mod tests {
assert_eq!(
err.to_string(),
format!(
"failed to parse remote control server enrollment response from `{enroll_url}`: HTTP 200 OK, request-id: <none>, cf-ray: <none>, body: {expected_body}, decode error: missing field `remote_control_token` at line 1 column {}",
"failed to parse remote control server enrollment response from `{enroll_url}`: HTTP 200 OK, request IDs: none, body: {expected_body}, decode error: missing field `remote_control_token` at line 1 column {}",
expected_body.len()
)
);
@@ -1,7 +1,6 @@
use super::auth::RemoteControlConnectionAuth;
use super::enroll::RemoteControlEnrollment;
use super::enroll::RemoteControlServerTokenRefreshRequirement;
use super::enroll::format_headers;
use super::enroll::preview_remote_control_response_body;
use super::protocol::EnrollRemoteServerRequest;
use super::protocol::EnrollRemoteServerResponse;
@@ -261,9 +260,10 @@ where
timed_out,
)
})?;
let headers = response.headers().clone();
let headers = response.codex_headers().copy_request_id_headers();
let ids = headers.request_id_summary();
let status = response.status();
let retry_at = retry_after_with_jitter(&headers, OffsetDateTime::now_utc());
let retry_at = retry_after_with_jitter(response.headers(), OffsetDateTime::now_utc());
let body = response.bytes().await.map_err(|err| {
if matches!(err, codex_http_client::HttpError::Policy(_))
&& !(retry_at.is_some() && (status.as_u16() == 429 || status.is_server_error()))
@@ -280,10 +280,9 @@ where
})?;
let body_preview = preview_remote_control_response_body(&body);
if !status.is_success() {
let headers_str = format_headers(&headers);
return Err(RemoteControlServerRequestError::io_error(
format!(
"remote control {response_kind} failed at `{url}`: HTTP {status}, {headers_str}, body: {body_preview}"
"remote control {response_kind} failed at `{url}`: HTTP {status}, request IDs: {ids}, body: {body_preview}"
),
Some(status),
retry_at,
@@ -292,9 +291,8 @@ where
}
serde_json::from_slice::<Response>(&body).map_err(|err| {
let headers_str = format_headers(&headers);
io::Error::other(format!(
"failed to parse remote control {response_kind} response from `{url}`: HTTP {status}, {headers_str}, body: {body_preview}, decode error: {err}"
"failed to parse remote control {response_kind} response from `{url}`: HTTP {status}, request IDs: {ids}, body: {body_preview}, decode error: {err}"
))
})
}
@@ -381,7 +381,7 @@ async fn revoke_remote_control_client_does_not_retry_forbidden() {
assert_eq!(
err.to_string(),
format!(
"remote control client revoke failed at `{remote_control_url}wham/remote/control/environments/env-123/clients/client-123`: HTTP 403 Forbidden, request-id: request-123, cf-ray: ray-123, body: forbidden"
"remote control client revoke failed at `{remote_control_url}wham/remote/control/environments/env-123/clients/client-123`: HTTP 403 Forbidden, request IDs: x-request-id: request-123, cf-ray: ray-123, body: forbidden"
)
);
}
@@ -106,7 +106,13 @@ async fn pairing_error(status: &'static str, body: &'static str) -> (String, Str
respond_with_status_and_headers(
pairing_request.stream,
status,
&[("x-request-id", "request-123"), ("cf-ray", "ray-123")],
&[
("x-request-id", "request-123"),
("x-oai-request-id", "oai"),
("x-openai-request-id", "openai"),
("x-ms-request-id", "ms"),
("cf-ray", "ray-123"),
],
body,
)
.await;
@@ -572,7 +578,7 @@ async fn remote_control_pairing_status_preserves_decode_error_context() {
assert!(err.contains(&format!(
"failed to parse remote control pairing status response from `{expected_status_url}`: HTTP 200 OK"
)));
assert!(err.contains("request-id: request-123"));
assert!(err.contains("x-request-id: request-123"));
assert!(err.contains("cf-ray: ray-123"));
assert!(err.contains("body: {"));
assert!(err.contains("decode error:"));
@@ -906,7 +912,7 @@ async fn start_remote_control_pairing_preserves_backend_error_context() {
assert_eq!(
err,
format!(
"remote control pairing failed at `{expected_pair_url}`: HTTP 503 Service Unavailable, request-id: request-123, cf-ray: ray-123, body: pairing unavailable"
"remote control pairing failed at `{expected_pair_url}`: HTTP 503 Service Unavailable, request IDs: x-request-id: request-123, x-oai-request-id: oai, x-openai-request-id: openai, x-ms-request-id: ms, cf-ray: ray-123, body: pairing unavailable"
)
);
}
@@ -917,7 +923,7 @@ async fn start_remote_control_pairing_preserves_decode_error_context() {
assert!(err.contains(&format!(
"failed to parse remote control pairing response from `{expected_pair_url}`: HTTP 200 OK"
)));
assert!(err.contains("request-id: request-123"));
assert!(err.contains("x-request-id: request-123"));
assert!(err.contains("cf-ray: ray-123"));
assert!(err.contains("body: {"));
assert!(err.contains("decode error:"));
@@ -950,9 +956,7 @@ async fn start_remote_control_pairing_preserves_expiry_parse_error_context() {
.await;
assert!(err.contains("failed to parse remote control pairing response"));
assert!(err.contains("HTTP 200 OK"));
assert!(err.contains("request-id: <none>"));
assert!(err.contains("cf-ray: <none>"));
assert!(err.contains("HTTP 200 OK, request IDs: none, body: "));
assert!(err.contains("\"expires_at\":\"not-a-timestamp\""));
assert!(err.contains("expires_at parse error:"));
}
@@ -25,7 +25,6 @@ use crate::transport::remote_control::auth::recover_remote_control_auth;
use crate::transport::remote_control::client_tracker::ClientTracker;
use crate::transport::remote_control::client_tracker::REMOTE_CONTROL_IDLE_SWEEP_INTERVAL;
use crate::transport::remote_control::enroll::RemoteControlEnrollment;
use crate::transport::remote_control::enroll::format_headers;
use crate::transport::remote_control::enroll::load_persisted_remote_control_enrollment;
use crate::transport::remote_control::enroll::preview_remote_control_response_body;
use crate::transport::remote_control::host_device::REMOTE_CONTROL_HOST_DEVICE_KIND_HEADER;
@@ -39,6 +38,7 @@ use axum::http::HeaderValue;
use base64::Engine;
use codex_app_server_protocol::RemoteControlConnectionStatus;
use codex_app_server_protocol::RemoteControlStatusChangedNotification;
use codex_http_client::CodexHeaderMap;
use codex_state::StateRuntime;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use futures::SinkExt;
@@ -48,6 +48,7 @@ use futures::stream::SplitStream;
use rand::Rng;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fmt::Write as _;
use std::io;
use std::io::ErrorKind;
use std::sync::Arc;
@@ -800,7 +801,7 @@ impl RemoteControlWebsocket {
server_id = ?enrollment.as_ref().map(|enrollment| enrollment.server_id.as_str()),
environment_id = ?enrollment.as_ref().map(|enrollment| enrollment.environment_id.as_str()),
subscribe_cursor_present = subscribe_cursor.is_some(),
response_headers = %format_headers(response.headers()),
response_headers = %CodexHeaderMap::from_http(response.headers()).request_id_summary(),
"connected to app-server remote control websocket"
);
return ConnectOutcome::Connected(Box::new(websocket_connection));
@@ -1562,7 +1563,7 @@ pub(super) async fn connect_remote_control_websocket(
server_id = %enrollment.server_id,
environment_id = %enrollment.environment_id,
response_status = %response.status(),
response_headers = %format_headers(response.headers()),
response_headers = %CodexHeaderMap::from_http(response.headers()).request_id_summary(),
response_body = %response_body,
"remote control websocket returned unrecognized HTTP 404; preserving enrollment before retry"
);
@@ -1898,12 +1899,13 @@ fn format_remote_control_websocket_connect_error(
return message;
};
message.push_str(&format!(", {}", format_headers(response.headers())));
let ids = CodexHeaderMap::from_http(response.headers()).request_id_summary();
let _ = write!(message, ", request IDs: {ids}");
if let Some(body) = response.body().as_ref()
&& !body.is_empty()
{
let body_preview = preview_remote_control_response_body(body);
message.push_str(&format!(", body: {body_preview}"));
let _ = write!(message, ", body: {body_preview}");
}
message
@@ -2195,7 +2197,7 @@ mod tests {
let remote_control_target =
normalize_remote_control_url(&remote_control_url).expect("target should parse");
let expected_error = format!(
"failed to connect app-server remote control websocket `{}`: HTTP error: 503 Service Unavailable, request-id: <none>, cf-ray: <none>, body: upstream unavailable",
"failed to connect app-server remote control websocket `{}`: HTTP error: 503 Service Unavailable, request IDs: none, body: upstream unavailable",
remote_control_target.websocket_url
);
let codex_home = TempDir::new().expect("temp dir should create");
@@ -2418,7 +2420,7 @@ mod tests {
assert_eq!(
err.to_string(),
format!(
"remote control server enrollment failed at `{enroll_url}`: HTTP 401 Unauthorized, request-id: <none>, cf-ray: <none>, body: unauthorized; retrying after auth recovery"
"remote control server enrollment failed at `{enroll_url}`: HTTP 401 Unauthorized, request IDs: none, body: unauthorized; retrying after auth recovery"
)
);
assert_eq!(
@@ -2529,7 +2531,7 @@ mod tests {
assert_eq!(
err.to_string(),
format!(
"remote control server refresh failed at `{refresh_url}`: HTTP 401 Unauthorized, request-id: <none>, cf-ray: <none>, body: unauthorized; retrying after auth recovery"
"remote control server refresh failed at `{refresh_url}`: HTTP 401 Unauthorized, request IDs: none, body: unauthorized; retrying after auth recovery"
)
);
assert_eq!(
+1 -1
View File
@@ -449,7 +449,7 @@ impl Client {
.to_string();
let identity_error_code =
codex_response_debug_context::extract_response_debug_context_from_headers(
res.headers(),
res.codex_headers(),
)
.auth_error_code;
let body = res.text().await?;
+21 -38
View File
@@ -7,6 +7,7 @@ use crate::rate_limits::parse_rate_limit_reached_type;
use base64::Engine;
use chrono::DateTime;
use chrono::Utc;
use codex_http_client::CodexHeaderMap;
use codex_protocol::auth::PlanType;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
@@ -16,7 +17,6 @@ use codex_protocol::error::RetryLimitReachedError;
use codex_protocol::error::UnexpectedResponseError;
use codex_protocol::error::UsageLimitReachedError;
use codex_protocol::protocol::MisalignmentErrorDetails;
use http::HeaderMap;
use serde::Deserialize;
use serde_json::Value;
@@ -139,6 +139,7 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
body,
..
} => {
let response_headers = headers.as_ref().map(CodexHeaderMap::from_http);
let body_text = body.unwrap_or_default();
let parsed_body = serde_json::from_str::<Value>(&body_text).ok();
let provider_error = parsed_body.as_ref().and_then(|body| body.get("error"));
@@ -229,15 +230,13 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
} else if status == http::StatusCode::TOO_MANY_REQUESTS {
if let Ok(err) = serde_json::from_str::<UsageErrorResponse>(&body_text) {
if err.error.error_type.as_deref() == Some("usage_limit_reached") {
let limit_id = extract_header(headers.as_ref(), ACTIVE_LIMIT_HEADER);
let limit_id = response_headers.and_then(CodexHeaderMap::active_limit);
let promo_message = headers.as_ref().and_then(parse_promo_message);
let rate_limit_reached_type =
headers.as_ref().and_then(parse_rate_limit_reached_type);
let rate_limits = headers
.as_ref()
.and_then(|map| {
parse_rate_limit_for_limit(map, limit_id.as_deref())
})
.and_then(|map| parse_rate_limit_for_limit(map, limit_id))
.map(|mut snapshot| {
snapshot.rate_limit_reached_type = rate_limit_reached_type;
snapshot
@@ -277,7 +276,11 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
CodexErr::RetryLimit(RetryLimitReachedError {
status,
request_id: extract_request_tracking_id(headers.as_ref()),
request_id: response_headers
.and_then(|headers| {
headers.preferred_request_id().or_else(|| headers.cf_ray())
})
.map(str::to_owned),
})
} else {
let response = UnexpectedResponseError {
@@ -285,13 +288,16 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
user_message: api_error_user_message(status, &body_text),
body: body_text,
url,
cf_ray: extract_header(headers.as_ref(), CF_RAY_HEADER),
request_id: extract_request_id(headers.as_ref()),
identity_authorization_error: extract_header(
headers.as_ref(),
X_OPENAI_AUTHORIZATION_ERROR_HEADER,
),
identity_error_code: extract_x_error_json_code(headers.as_ref()),
cf_ray: response_headers
.and_then(CodexHeaderMap::cf_ray)
.map(str::to_owned),
request_id: response_headers
.and_then(CodexHeaderMap::preferred_request_id)
.map(str::to_owned),
identity_authorization_error: response_headers
.and_then(CodexHeaderMap::authorization_error)
.map(str::to_owned),
identity_error_code: response_headers.and_then(extract_x_error_json_code),
};
let body_code = parsed_body.as_ref().and_then(|body| {
["/detail/code", "/error/code"]
@@ -332,12 +338,6 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
}
}
const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
const CF_RAY_HEADER: &str = "cf-ray";
const X_OPENAI_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
const X_ERROR_JSON_HEADER: &str = "x-error-json";
const INVALID_PROMPT_ERROR_CODE: &str = "invalid_prompt";
const INVALID_PROMPT_FALLBACK_MESSAGE: &str = "Invalid request.";
const CYBER_POLICY_ERROR_CODE: &str = "cyber_policy";
@@ -355,10 +355,6 @@ const CLOUDFLARE_BLOCKED_MESSAGE: &str =
#[path = "api_bridge_tests.rs"]
mod tests;
fn extract_request_tracking_id(headers: Option<&HeaderMap>) -> Option<String> {
extract_request_id(headers).or_else(|| extract_header(headers, CF_RAY_HEADER))
}
fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String> {
if status == http::StatusCode::FORBIDDEN
&& body.contains("Cloudflare")
@@ -370,21 +366,8 @@ fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String
}
}
fn extract_request_id(headers: Option<&HeaderMap>) -> Option<String> {
extract_header(headers, REQUEST_ID_HEADER)
.or_else(|| extract_header(headers, OAI_REQUEST_ID_HEADER))
}
fn extract_header(headers: Option<&HeaderMap>, name: &str) -> Option<String> {
headers.and_then(|map| {
map.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_string)
})
}
fn extract_x_error_json_code(headers: Option<&HeaderMap>) -> Option<String> {
let encoded = extract_header(headers, X_ERROR_JSON_HEADER)?;
fn extract_x_error_json_code(headers: &CodexHeaderMap) -> Option<String> {
let encoded = headers.encoded_error_json()?;
let decoded = base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()?;
+9 -4
View File
@@ -3,8 +3,13 @@ use base64::Engine;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::RateLimitReachedType;
use http::HeaderMap;
use pretty_assertions::assert_eq;
const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
const X_OPENAI_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
const X_ERROR_JSON_HEADER: &str = "x-error-json";
#[test]
fn map_api_error_maps_server_overloaded() {
let err = map_api_error(ApiError::ServerOverloaded { retry_after: None });
@@ -226,7 +231,7 @@ fn map_http_error_classifies_provider_codes() {
#[test]
fn map_api_error_maps_cloudflare_blocked_response_to_user_message() {
let mut headers = HeaderMap::new();
headers.insert(CF_RAY_HEADER, http::HeaderValue::from_static("ray-id"));
headers.insert("cf-ray", http::HeaderValue::from_static("ray-id"));
let err = map_api_error(ApiError::Transport(TransportError::Http {
retry_after: None,
status: http::StatusCode::FORBIDDEN,
@@ -880,7 +885,7 @@ fn only_an_explicit_workspace_403_stops_retries() {
(StatusCode::UNAUTHORIZED, detail, true, false),
] {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, http::HeaderValue::from_static("req-403"));
headers.insert("x-request-id", http::HeaderValue::from_static("req-403"));
if with_header {
headers.insert(X_ERROR_JSON_HEADER, workspace_header.clone());
}
@@ -909,8 +914,8 @@ fn only_an_explicit_workspace_403_stops_retries() {
#[test]
fn map_api_error_extracts_identity_auth_details_from_headers() {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, http::HeaderValue::from_static("req-401"));
headers.insert(CF_RAY_HEADER, http::HeaderValue::from_static("ray-401"));
headers.insert("x-request-id", http::HeaderValue::from_static("req-401"));
headers.insert("cf-ray", http::HeaderValue::from_static("ray-401"));
headers.insert(
X_OPENAI_AUTHORIZATION_ERROR_HEADER,
http::HeaderValue::from_static("missing_authorization_header"),
+1 -1
View File
@@ -566,7 +566,7 @@ pub struct ResponseStream {
/// Routing pin from the connection that produced these responses. Never model metadata.
pub routing_affinity: Option<codex_http_client::ChatGptRoutingAffinity>,
pub rx_event: mpsc::Receiver<Result<ResponseEvent, ApiError>>,
/// Server-assigned `x-request-id` response header, when present.
/// Server-assigned request ID from the response headers.
pub upstream_request_id: Option<String>,
/// Requests a graceful interrupt. Keep consuming events through completion.
/// Only `Cancel` validates and waits for an interruption acknowledgement.
+10 -15
View File
@@ -8,14 +8,13 @@ use crate::provider::Provider;
use codex_client::HttpTransport;
use codex_client::RequestTelemetry;
use codex_client::TransportError;
use codex_http_client::CodexHeaderMap;
use http::HeaderMap;
use http::Method;
use serde::Serialize;
use serde_json::to_value;
use std::sync::Arc;
const X_CODEX_IMAGEGEN_REQUEST_ID_HEADER: &str = "x-codex-imagegen-request-id";
pub struct ImagesClient<T: HttpTransport> {
session: EndpointSession<T>,
}
@@ -30,9 +29,11 @@ pub struct ImageRequestError {
impl ImageRequestError {
fn from_api_error(error: ApiError) -> Self {
let imagegen_request_id = match &error {
ApiError::Transport(TransportError::Http { headers, .. }) => {
headers.as_ref().and_then(imagegen_request_id_from_headers)
}
ApiError::Transport(TransportError::Http { headers, .. }) => headers
.as_ref()
.map(CodexHeaderMap::from_http)
.and_then(CodexHeaderMap::imagegen_request_id)
.map(str::to_owned),
_ => None,
};
Self {
@@ -98,7 +99,9 @@ impl<T: HttpTransport> ImagesClient<T> {
.execute(Method::POST, path, extra_headers, Some(body))
.await
.map_err(ImageRequestError::from_api_error)?;
let imagegen_request_id = imagegen_request_id_from_headers(&resp.headers);
let imagegen_request_id = CodexHeaderMap::from_http(&resp.headers)
.imagegen_request_id()
.map(str::to_owned);
let response = serde_json::from_slice(&resp.body).map_err(|e| ImageRequestError {
error: ApiError::Stream(format!("failed to decode {operation} response: {e}")),
imagegen_request_id: imagegen_request_id.clone(),
@@ -107,14 +110,6 @@ impl<T: HttpTransport> ImagesClient<T> {
}
}
fn imagegen_request_id_from_headers(headers: &HeaderMap) -> Option<String> {
headers
.get(X_CODEX_IMAGEGEN_REQUEST_ID_HEADER)
.and_then(|value| value.to_str().ok())
.filter(|request_id| !request_id.is_empty())
.map(str::to_string)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -249,7 +244,7 @@ mod tests {
async fn generate_posts_typed_request_and_parses_image_response() {
let mut response_headers = HeaderMap::new();
response_headers.insert(
X_CODEX_IMAGEGEN_REQUEST_ID_HEADER,
"x-codex-imagegen-request-id",
http::HeaderValue::from_static("req-imagegen-123"),
);
response_headers.insert(
@@ -21,6 +21,7 @@ use crate::sse::process_responses_event;
use crate::telemetry::WebsocketTelemetry;
use bytes::Bytes;
use codex_client::TransportError;
use codex_http_client::CodexHeaderMap;
use codex_http_client::HttpClientFactory;
use codex_http_client::RetryAfter;
use codex_websocket_client::WebSocketConnection;
@@ -788,17 +789,9 @@ impl ResponsesWebsocketClient {
)
.await?;
let status = response.status();
let mut headers = HeaderMap::new();
for name in [
"x-request-id",
"x-oai-request-id",
"cf-ray",
"x-ms-request-id",
] {
for value in response.headers().get_all(name) {
headers.append(name, value.clone());
}
}
let headers = CodexHeaderMap::from_http(response.headers())
.copy_request_id_headers()
.into_http();
let immediate_close = tokio::time::timeout(immediate_close_timeout, stream.next())
.await
.ok()
+9 -13
View File
@@ -4,7 +4,6 @@ use std::time::Duration;
use crate::AuthProvider;
use bytes::Bytes;
use codex_http_client::HttpResponse;
use codex_http_client::RequestBuilder;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
@@ -272,9 +271,15 @@ where
Ok(response) => {
let upload_status = response.status();
status = Some(upload_status.to_string());
cloudflare_ray_id = upload_response_header(&response, "cf-ray");
azure_request_id = upload_response_header(&response, "x-ms-request-id");
azure_error_code = upload_response_header(&response, "x-ms-error-code");
let headers = response.codex_headers();
cloudflare_ray_id = headers.cf_ray().unwrap_or("missing").to_owned();
azure_request_id = headers.ms_request_id().unwrap_or("missing").to_owned();
azure_error_code = response
.headers()
.get("x-ms-error-code")
.and_then(|value| value.to_str().ok())
.unwrap_or("missing")
.to_owned();
if upload_status.is_success() {
if attempt > 1 {
tracing::event!(
@@ -460,15 +465,6 @@ async fn authorized_request(
.headers(headers))
}
fn upload_response_header(response: &HttpResponse, header: &str) -> String {
response
.headers()
.get(header)
.and_then(|value| value.to_str().ok())
.unwrap_or("missing")
.to_string()
}
fn blob_retry_after(headers: &http::HeaderMap) -> Option<Duration> {
if let Some(delay) = headers
.get("x-ms-retry-after-ms")
+4 -6
View File
@@ -12,6 +12,7 @@ use crate::safety_buffering::treatment_from_headers;
use crate::telemetry::SseTelemetry;
use codex_client::ByteStream;
use codex_client::StreamResponse;
use codex_http_client::CodexHeaderMap;
use codex_protocol::ResponseUsageMetadata;
use codex_protocol::error::ResponseIncompleteError;
use codex_protocol::models::ResponseItem;
@@ -35,7 +36,6 @@ use tracing::trace;
const X_REASONING_INCLUDED_HEADER: &str = "x-reasoning-included";
const X_CODEX_TURN_STATE_HEADER: &str = "x-codex-turn-state";
const OPENAI_MODEL_HEADER: &str = "openai-model";
const REQUEST_ID_HEADER: &str = "x-request-id";
const TRUSTED_ACCESS_FOR_CYBER_VERIFICATION: &str = "trusted_access_for_cyber";
pub fn spawn_response_stream(
@@ -59,10 +59,8 @@ pub fn spawn_response_stream(
.headers
.get(X_REASONING_INCLUDED_HEADER)
.is_some();
let upstream_request_id = stream_response
.headers
.get(REQUEST_ID_HEADER)
.and_then(|value| value.to_str().ok())
let upstream_request_id = CodexHeaderMap::from_http(&stream_response.headers)
.preferred_request_id()
.map(str::to_string);
let safety_buffering_treatment =
treatment_from_headers(&stream_response.headers).unwrap_or_default();
@@ -1641,7 +1639,7 @@ mod tests {
#[tokio::test]
async fn spawn_response_stream_emits_header_events() {
let mut headers = HeaderMap::new();
headers.insert(REQUEST_ID_HEADER, HeaderValue::from_static("req-1"));
headers.insert("x-request-id", HeaderValue::from_static("req-1"));
headers.insert(
OPENAI_MODEL_HEADER,
HeaderValue::from_static(CYBER_RESTRICTED_MODEL_FOR_TESTS),
@@ -143,6 +143,7 @@ async fn probe_preserves_evidence_and_redacts_wire_secrets() {
let headers = concat!(
"x-request-id: fixture-request\r\n",
"x-oai-request-id: fixture-oai-request\r\n",
"x-openai-request-id: fixture-openai-request\r\n",
"cf-ray: fixture-ray\r\n",
"x-ms-request-id: fixture-ms-one\r\n",
"x-ms-request-id: fixture-ms-two\r\n",
@@ -263,6 +264,7 @@ async fn probe_preserves_evidence_and_redacts_wire_secrets() {
for (name, value) in [
("x-request-id", "fixture-request"),
("x-oai-request-id", "fixture-oai-request"),
("x-openai-request-id", "fixture-openai-request"),
("cf-ray", "fixture-ray"),
("x-ms-request-id", "fixture-ms-one"),
("x-ms-request-id", "fixture-ms-two"),
@@ -12,6 +12,7 @@ use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use codex_http_client::RouteAwareRequestError;
use codex_http_client::is_openai_api_url;
use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR;
use codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR;
@@ -189,7 +190,8 @@ impl RouteAwareHttpRequestRunner {
}
}
let request_span = tracing::info_span!(
let request_span = codex_http_client::span_with_request_ids!(
tracing::Level::INFO,
"codex.exec_server.http_request",
otel.kind = "client",
http.request.method = method.as_str(),
@@ -221,6 +223,17 @@ impl RouteAwareHttpRequestRunner {
};
let status = response.status().as_u16();
request_span.record("http.response.status_code", u64::from(status));
if is_openai_api_url(response.url().as_str()) {
response
.codex_headers()
.request_id_summary()
.record_on(&request_span);
tracing::debug!(
parent: &request_span,
response_host = response.url().host_str(),
"received HTTP response headers"
);
}
let headers = Self::response_headers(response.headers());
if params.stream_response {
@@ -36,6 +36,7 @@ async fn delegated_http_success_logs_do_not_expose_sensitive_request_or_response
let client =
RouteAwareHttpClient::new(HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault));
let untrusted_id = "b02d15c7-0cee-4eab-8d22-f402d4783294";
for (redirect_policy, status, query_secret, cookie_secret, location_secret) in [
(
HttpRedirectPolicy::Follow,
@@ -55,7 +56,7 @@ async fn delegated_http_success_logs_do_not_expose_sensitive_request_or_response
let listener = TcpListener::bind(("127.0.0.1", 0)).await?;
let address = listener.local_addr()?;
let response = format!(
"HTTP/1.1 {status}\r\nSet-Cookie: session={cookie_secret}\r\nLocation: http://127.0.0.1/private?token={location_secret}\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
"HTTP/1.1 {status}\r\nX-Oai-Request-Id: {untrusted_id}\r\nSet-Cookie: session={cookie_secret}\r\nLocation: http://127.0.0.1/private?token={location_secret}\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
);
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await?;
@@ -96,6 +97,7 @@ async fn delegated_http_success_logs_do_not_expose_sensitive_request_or_response
let logs = String::from_utf8(log_buffer.lock().expect("log buffer lock").clone())?;
assert!(logs.contains("log capture sentinel"));
for secret in [
untrusted_id,
"follow-query-secret",
"follow-cookie-secret",
"follow-location-secret",
+1
View File
@@ -13,6 +13,7 @@ http-body = "1.0.1"
httpdate = { workspace = true }
native-tls = "0.2"
opentelemetry = { workspace = true }
ref-cast = "1.0.25"
reqwest = { workspace = true, features = ["gzip", "json", "rustls-tls", "rustls-tls-native-roots", "stream", "zstd"] }
rustls = { workspace = true }
rustls-native-certs = { workspace = true }
+150
View File
@@ -0,0 +1,150 @@
//! Typed access to Codex response headers. Text accessors borrow the first
//! value for a name and treat unreadable values and empty IDs as absent.
use std::fmt;
use http::HeaderMap;
/// Owns a complete HTTP header map. Library responses can lend the same
/// typed view without copying header values.
#[derive(Clone, Default, ref_cast::RefCast)]
#[repr(transparent)]
pub struct CodexHeaderMap(HeaderMap);
impl From<HeaderMap> for CodexHeaderMap {
fn from(headers: HeaderMap) -> Self {
Self(headers)
}
}
// tracing needs field names at the span call site. Generate the declaration
// and the lookup table together so a recorded field can't silently go missing.
macro_rules! request_ids {
($d:tt; $($field:ident => $header:literal),+ $(,)?) => {
const REQUEST_IDS: &[(&str, &str)] = &[$((stringify!($field), $header)),+];
impl CodexHeaderMap {
$(pub fn $field(&self) -> Option<&str> {
request_id_value(self.0.get($header)?)
})+
}
/// Create a tracing span with empty fields for [`RequestIdSummary::record_on`].
#[macro_export]
macro_rules! span_with_request_ids {
($level:expr, $name:expr, $d($d fields:tt)*) => {
::tracing::span!($level, $name, $($field = ::tracing::field::Empty,)+ $d($d fields)*)
};
}
};
}
request_ids! { $;
request_id => "x-request-id",
oai_request_id => "x-oai-request-id",
openai_request_id => "x-openai-request-id",
ms_request_id => "x-ms-request-id",
cf_ray => "cf-ray",
}
impl CodexHeaderMap {
pub fn from_http(headers: &HeaderMap) -> &Self {
ref_cast::RefCast::ref_cast(headers)
}
pub fn into_http(self) -> HeaderMap {
self.0
}
fn text(&self, name: &str) -> Option<&str> {
self.0.get(name)?.to_str().ok()
}
pub fn authorization_error(&self) -> Option<&str> {
self.text("x-openai-authorization-error")
}
pub fn encoded_error_json(&self) -> Option<&str> {
self.text("x-error-json")
}
pub fn active_limit(&self) -> Option<&str> {
self.text("x-codex-active-limit")
}
/// Identifies the nested image generation request.
pub fn imagegen_request_id(&self) -> Option<&str> {
request_id_value(self.0.get("x-codex-imagegen-request-id")?)
}
pub fn preferred_request_id(&self) -> Option<&str> {
self.request_id()
.or_else(|| self.oai_request_id())
.or_else(|| self.openai_request_id())
.or_else(|| self.ms_request_id())
}
pub fn request_id_summary(&self) -> RequestIdSummary<'_> {
RequestIdSummary(&self.0)
}
/// Retain all occurrences for callers forwarding the original ID headers.
pub fn copy_request_id_headers(&self) -> Self {
let mut headers = HeaderMap::new();
for &(_, name) in REQUEST_IDS {
for value in self.0.get_all(name) {
headers.append(name, value.clone());
}
}
Self(headers)
}
}
fn request_id_value(value: &http::HeaderValue) -> Option<&str> {
value.to_str().ok().filter(|id| !id.is_empty())
}
/// The readable, non-sensitive correlation IDs on one response.
pub struct RequestIdSummary<'a>(&'a HeaderMap);
impl RequestIdSummary<'_> {
fn entries(&self) -> impl Iterator<Item = (&'static str, &'static str, &str)> {
REQUEST_IDS.iter().filter_map(|&(field, name)| {
let value = self.0.get(name).filter(|v| !v.is_sensitive())?;
Some((field, name, request_id_value(value)?))
})
}
/// Record each present ID on a span created with [`span_with_request_ids!`].
pub fn record_on(&self, span: &tracing::Span) {
for (field, _, value) in self.entries() {
span.record(field, value);
}
}
}
impl fmt::Display for RequestIdSummary<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut entries = self.entries();
let Some((_, name, value)) = entries.next() else {
return f.write_str("none");
};
write!(f, "{name}: {value}")?;
for (_, name, value) in entries {
write!(f, ", {name}: {value}")?;
}
Ok(())
}
}
impl fmt::Debug for RequestIdSummary<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map()
.entries(self.entries().map(|(_, name, value)| (name, value)))
.finish()
}
}
#[cfg(test)]
#[path = "header_map_tests.rs"]
mod tests;
@@ -0,0 +1,48 @@
#![cfg(test)]
use super::*;
use http::HeaderValue;
use pretty_assertions::assert_eq;
/// Both diagnostic formats omit unreadable, sensitive and unrelated headers.
#[test]
fn summary_formats_only_available_ids() {
let mut headers = HeaderMap::new();
headers.insert("x-request-id", HeaderValue::from_bytes(b"\xff").unwrap());
let mut sensitive = HeaderValue::from_static("secret");
sensitive.set_sensitive(true);
headers.insert("x-oai-request-id", sensitive);
assert_eq!(
CodexHeaderMap::from_http(&headers)
.request_id_summary()
.to_string(),
"none"
);
headers.insert("x-ms-request-id", HeaderValue::from_static("ms"));
headers.insert("cf-ray", HeaderValue::from_static("ray"));
headers.insert("authorization", HeaderValue::from_static("bearer"));
let headers = CodexHeaderMap::from(headers);
let ids = headers.request_id_summary();
assert_eq!(ids.to_string(), "x-ms-request-id: ms, cf-ray: ray");
assert_eq!(
format!("{ids:?}"),
r#"{"x-ms-request-id": "ms", "cf-ray": "ray"}"#
);
}
/// An empty primary ID must not hide a usable secondary ID.
#[test]
fn empty_request_id_falls_back_to_oai_request_id() {
let mut headers = HeaderMap::new();
headers.insert("x-request-id", HeaderValue::from_static(""));
headers.insert("x-oai-request-id", HeaderValue::from_static("secondary"));
let headers = CodexHeaderMap::from(headers);
assert_eq!(headers.preferred_request_id(), Some("secondary"));
assert_eq!(
headers.request_id_summary().to_string(),
"x-oai-request-id: secondary"
);
}
+3
View File
@@ -9,6 +9,7 @@ mod client_builder;
mod client_tls;
mod custom_ca;
mod error;
mod header_map;
mod native_roots;
mod network_policy;
mod openai_endpoints;
@@ -44,6 +45,8 @@ pub use crate::custom_ca::build_rustls_client_config_with_custom_ca;
pub use crate::custom_ca::maybe_build_rustls_client_config_with_custom_ca;
pub use crate::error::StreamError;
pub use crate::error::TransportError;
pub use crate::header_map::CodexHeaderMap;
pub use crate::header_map::RequestIdSummary;
pub use crate::network_policy::DestinationPolicy;
pub use crate::network_policy::NetworkPermit;
pub use crate::network_policy::NetworkPolicy;
+5
View File
@@ -13,6 +13,7 @@ use futures::future::BoxFuture;
use futures::stream;
use serde::de::DeserializeOwned;
use crate::CodexHeaderMap;
use crate::HttpError;
use crate::NetworkPermit;
use crate::NetworkPolicy;
@@ -24,6 +25,10 @@ pub struct HttpResponse {
}
impl HttpResponse {
pub fn codex_headers(&self) -> &CodexHeaderMap {
CodexHeaderMap::from_http(self.inner.headers())
}
/// Preserves HTTP frames, including gRPC trailers, while enforcing revocation.
pub fn into_http_response(
self,
+4 -4
View File
@@ -60,10 +60,10 @@ impl TokenRejection {
secrets: &[&str],
) -> Self {
let status = response.status();
let request_id = ["x-request-id", "x-openai-request-id", "cf-ray"]
.iter()
.find_map(|name| response.headers().get(*name))
.and_then(|value| value.to_str().ok())
let headers = response.codex_headers();
let request_id = headers
.preferred_request_id()
.or_else(|| headers.cf_ray())
.map(|value| {
redact_request_secrets(value, secrets)
.chars()
@@ -15,6 +15,7 @@ workspace = true
[dependencies]
base64 = { workspace = true }
codex-api = { workspace = true }
codex-http-client = { workspace = true }
http = { workspace = true }
serde_json = { workspace = true }
+27 -22
View File
@@ -1,12 +1,7 @@
use base64::Engine;
use codex_api::ApiError;
use codex_api::TransportError;
const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
const CF_RAY_HEADER: &str = "cf-ray";
const AUTH_ERROR_HEADER: &str = "x-openai-authorization-error";
const X_ERROR_JSON_HEADER: &str = "x-error-json";
use codex_http_client::CodexHeaderMap;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ResponseDebugContext {
@@ -21,27 +16,15 @@ pub fn extract_response_debug_context(transport: &TransportError) -> ResponseDeb
TransportError::Http {
headers: Some(headers),
..
} => extract_response_debug_context_from_headers(headers),
} => extract_response_debug_context_from_headers(CodexHeaderMap::from_http(headers)),
_ => ResponseDebugContext::default(),
}
}
pub fn extract_response_debug_context_from_headers(
headers: &http::HeaderMap,
headers: &CodexHeaderMap,
) -> ResponseDebugContext {
let mut context = ResponseDebugContext::default();
let extract_header = |name: &str| {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_string)
};
context.request_id =
extract_header(REQUEST_ID_HEADER).or_else(|| extract_header(OAI_REQUEST_ID_HEADER));
context.cf_ray = extract_header(CF_RAY_HEADER);
context.auth_error = extract_header(AUTH_ERROR_HEADER);
context.auth_error_code = extract_header(X_ERROR_JSON_HEADER).and_then(|encoded| {
let auth_error_code = headers.encoded_error_json().and_then(|encoded| {
let decoded = base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()?;
@@ -53,7 +36,12 @@ pub fn extract_response_debug_context_from_headers(
.map(str::to_string)
});
context
ResponseDebugContext {
request_id: headers.preferred_request_id().map(str::to_owned),
cf_ray: headers.cf_ray().map(str::to_owned),
auth_error: headers.authorization_error().map(str::to_owned),
auth_error_code,
}
}
pub fn extract_response_debug_context_from_api_error(error: &ApiError) -> ResponseDebugContext {
@@ -115,10 +103,12 @@ pub fn telemetry_api_error_message(error: &ApiError) -> String {
mod tests {
use super::ResponseDebugContext;
use super::extract_response_debug_context;
use super::extract_response_debug_context_from_headers;
use super::telemetry_api_error_message;
use super::telemetry_transport_error_message;
use codex_api::ApiError;
use codex_api::TransportError;
use codex_http_client::CodexHeaderMap;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
@@ -127,6 +117,7 @@ mod tests {
#[test]
fn extract_response_debug_context_decodes_identity_headers() {
let mut headers = HeaderMap::new();
headers.insert("x-request-id", HeaderValue::from_bytes(b"\xff").unwrap());
headers.insert("x-oai-request-id", HeaderValue::from_static("req-auth"));
headers.insert("cf-ray", HeaderValue::from_static("ray-auth"));
headers.insert(
@@ -157,6 +148,20 @@ mod tests {
);
}
/// Azure can return only its own header on a failed request.
#[test]
fn azure_responses_expose_their_request_id_in_debug_context() {
let mut headers = HeaderMap::new();
headers.insert("x-ms-request-id", HeaderValue::from_static("azure-id"));
assert_eq!(
extract_response_debug_context_from_headers(CodexHeaderMap::from_http(&headers)),
ResponseDebugContext {
request_id: Some("azure-id".to_owned()),
..Default::default()
}
);
}
#[test]
fn telemetry_error_messages_omit_upstream_bodies() {
let transport = TransportError::Http {