mirror of
https://github.com/openai/codex.git
synced 2026-12-06 01:10:58 +00:00
Propagate authentication header failures before sending requests (#55607)
## Why Synchronous auth header construction could silently return no credentials when managed authentication became unavailable. Callers need an error to avoid sending requests with missing or partial authentication. ## What changed - Make `AuthProvider::add_auth_headers`, `to_auth_headers`, and auth header telemetry fallible, and propagate failures through request and WebSocket setup. - Return a transient error when managed authentication is unavailable, and preserve network policy denials through auth error conversion. - Retry transient MCP authentication errors while treating build errors and policy denials as terminal. - Cancel local MCP event streams before resolving authentication so cleanup still works when credentials become unavailable. ## Testing Add regression coverage for rejected partial authentication, async header resolution, terminal auth errors without sending requests, managed account changes, MCP retry classification, and local stream cancellation after authentication becomes unavailable. GitOrigin-RevId: 39d981e232cba1e302de502a2fa6239101114ed1
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
use codex_client::Request;
|
||||
use codex_client::TransportError;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use http::HeaderMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
@@ -8,6 +9,8 @@ use std::sync::Arc;
|
||||
/// Error returned while applying authentication to an outbound request.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AuthError {
|
||||
#[error(transparent)]
|
||||
Policy(#[from] NetworkPolicyDenied),
|
||||
#[error("request auth build error: {0}")]
|
||||
Build(String),
|
||||
#[error("transient auth error: {0}")]
|
||||
@@ -17,6 +20,7 @@ pub enum AuthError {
|
||||
impl From<AuthError> for TransportError {
|
||||
fn from(error: AuthError) -> Self {
|
||||
match error {
|
||||
AuthError::Policy(denied) => TransportError::Policy(denied),
|
||||
AuthError::Build(message) => TransportError::Build(message),
|
||||
AuthError::Transient(message) => TransportError::Network(message),
|
||||
}
|
||||
@@ -31,14 +35,16 @@ pub trait AuthProvider: Send + Sync {
|
||||
/// Adds any auth headers that are available without request body access.
|
||||
///
|
||||
/// Implementations should be cheap and non-blocking. This method is also
|
||||
/// used by telemetry and non-HTTP request paths.
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap);
|
||||
/// used by telemetry and non-HTTP request paths. Providers that require async
|
||||
/// work must return an error here and override `resolve_auth_headers`.
|
||||
/// Callers must not send the request if this returns an error.
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError>;
|
||||
|
||||
/// Returns any auth headers that are available without request body access.
|
||||
fn to_auth_headers(&self) -> HeaderMap {
|
||||
fn to_auth_headers(&self) -> Result<HeaderMap, AuthError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
self.add_auth_headers(&mut headers);
|
||||
headers
|
||||
self.add_auth_headers(&mut headers)?;
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// Resolves auth headers for an outbound request.
|
||||
@@ -47,7 +53,7 @@ pub trait AuthProvider: Send + Sync {
|
||||
/// credentials before returning. Header-only providers with static credentials can rely on the
|
||||
/// default implementation.
|
||||
fn resolve_auth_headers(&self) -> AuthHeadersFuture<'_> {
|
||||
Box::pin(async { Ok(self.to_auth_headers()) })
|
||||
Box::pin(async { self.to_auth_headers() })
|
||||
}
|
||||
|
||||
/// Applies auth to a complete outbound request and returns the request to send.
|
||||
@@ -91,14 +97,14 @@ pub struct AuthHeaderTelemetry {
|
||||
pub name: Option<&'static str>,
|
||||
}
|
||||
|
||||
pub fn auth_header_telemetry(auth: &dyn AuthProvider) -> AuthHeaderTelemetry {
|
||||
pub fn auth_header_telemetry(auth: &dyn AuthProvider) -> Result<AuthHeaderTelemetry, AuthError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
auth.add_auth_headers(&mut headers);
|
||||
auth.add_auth_headers(&mut headers)?;
|
||||
let name = headers
|
||||
.contains_key(http::header::AUTHORIZATION)
|
||||
.then_some("authorization");
|
||||
AuthHeaderTelemetry {
|
||||
Ok(AuthHeaderTelemetry {
|
||||
attached: name.is_some(),
|
||||
name,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -139,7 +139,9 @@ mod tests {
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -102,7 +102,9 @@ mod tests {
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -184,7 +184,9 @@ mod tests {
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -193,8 +195,9 @@ mod tests {
|
||||
}
|
||||
|
||||
impl AuthProvider for RetryAuth {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
|
||||
headers.insert(http::header::AUTHORIZATION, "Bearer test".parse().unwrap());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_auth(&self, mut request: Request) -> AuthProviderFuture<'_> {
|
||||
@@ -204,7 +207,7 @@ mod tests {
|
||||
if limits.len() == 1 {
|
||||
return Err(AuthError::Transient("retry authentication".to_string()));
|
||||
}
|
||||
self.add_auth_headers(&mut request.headers);
|
||||
self.add_auth_headers(&mut request.headers)?;
|
||||
Ok(request)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -360,11 +360,12 @@ mod tests {
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) {
|
||||
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
headers.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer test-token"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -466,7 +466,7 @@ impl ResponsesWebsocketClient {
|
||||
|
||||
let mut headers =
|
||||
merge_request_headers(&self.provider.headers, extra_headers, default_headers);
|
||||
self.auth.add_auth_headers(&mut headers);
|
||||
self.auth.add_auth_headers(&mut headers)?;
|
||||
|
||||
let connector = WebSocketConnector::new(http_client_factory)
|
||||
.map_err(|err| ApiError::Stream(format!("failed to configure websocket TLS: {err}")))?;
|
||||
|
||||
@@ -35,7 +35,7 @@ impl ResponsesWebsocketClient {
|
||||
.map_err(|err| ApiError::Stream(format!("failed to build websocket URL: {err}")))?;
|
||||
let mut headers =
|
||||
merge_request_headers(&self.provider.headers, extra_headers, default_headers);
|
||||
self.auth.add_auth_headers(&mut headers);
|
||||
self.auth.add_auth_headers(&mut headers)?;
|
||||
let (stream, _status, server_reasoning_included, server_model) =
|
||||
connect_websocket(ws_url, headers, connector, turn_state).await?;
|
||||
Ok(ResponsesWebsocketConnection::new(
|
||||
|
||||
@@ -83,7 +83,9 @@ mod tests {
|
||||
struct DummyAuth;
|
||||
|
||||
impl AuthProvider for DummyAuth {
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
|
||||
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -66,3 +66,9 @@ pub(crate) fn parse_flex_unavailable(error: &Value) -> Option<ApiError> {
|
||||
(error.get("code").and_then(Value::as_str) == Some("flex_unavailable"))
|
||||
.then_some(ApiError::FlexUnavailable)
|
||||
}
|
||||
|
||||
impl From<crate::AuthError> for ApiError {
|
||||
fn from(error: crate::AuthError) -> Self {
|
||||
Self::Transport(error.into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,8 @@ pub struct UploadedOpenAiFile {
|
||||
pub enum OpenAiFileError {
|
||||
#[error("failed to open OpenAI file upload contents: {0}")]
|
||||
ReadContents(#[source] std::io::Error),
|
||||
#[error(transparent)]
|
||||
Auth(#[from] crate::AuthError),
|
||||
#[error(
|
||||
"file `{file_name}` is too large: {size_bytes} bytes exceeds the limit of {limit_bytes} bytes"
|
||||
)]
|
||||
@@ -152,7 +154,7 @@ where
|
||||
"file_size": file_size_bytes,
|
||||
"use_case": OPENAI_FILE_USE_CASE,
|
||||
});
|
||||
let request = authorized_request(client_pool, auth, Method::POST, &create_url);
|
||||
let request = authorized_request(client_pool, auth, Method::POST, &create_url)?;
|
||||
let create_request = match hosted_upload {
|
||||
Some(context) => serde_json::json!({
|
||||
"file_name": file_name.as_str(),
|
||||
@@ -363,7 +365,7 @@ where
|
||||
};
|
||||
let finalize_started_at = Instant::now();
|
||||
loop {
|
||||
let finalize_response = authorized_request(client_pool, auth, Method::POST, &finalize_url)
|
||||
let finalize_response = authorized_request(client_pool, auth, Method::POST, &finalize_url)?
|
||||
.json(&finalize_request)
|
||||
.send()
|
||||
.await
|
||||
@@ -435,14 +437,14 @@ fn authorized_request(
|
||||
auth: &dyn AuthProvider,
|
||||
method: Method,
|
||||
url: &str,
|
||||
) -> RequestBuilder {
|
||||
) -> Result<RequestBuilder, OpenAiFileError> {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
auth.add_auth_headers(&mut headers);
|
||||
auth.add_auth_headers(&mut headers)?;
|
||||
|
||||
client_pool
|
||||
Ok(client_pool
|
||||
.request(method, url)
|
||||
.timeout(OPENAI_FILE_REQUEST_TIMEOUT)
|
||||
.headers(headers)
|
||||
.headers(headers))
|
||||
}
|
||||
|
||||
fn upload_response_header(response: &HttpResponse, header: &str) -> String {
|
||||
@@ -511,12 +513,13 @@ mod tests {
|
||||
}
|
||||
|
||||
impl AuthProvider for ChatGptTestAuth {
|
||||
fn add_auth_headers(&self, headers: &mut http::HeaderMap) {
|
||||
fn add_auth_headers(&self, headers: &mut http::HeaderMap) -> Result<(), crate::AuthError> {
|
||||
headers.insert(
|
||||
http::header::AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer token"),
|
||||
);
|
||||
headers.insert("ChatGPT-Account-ID", HeaderValue::from_static("account_id"));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user