mirror of
https://github.com/openai/codex.git
synced 2026-11-23 07:17:11 +00:00
Isolate MCP resource headers during OAuth requests (#39019)
## Why Headers configured for an MCP resource can contain credentials and must not be forwarded to a different origin during OAuth discovery, registration, or token exchange. ## What changed - Apply configured resource headers only to OAuth requests on the MCP resource origin, while allowing OAuth-generated headers to take precedence. - Follow credentialed OAuth redirects only when each destination remains on the resource origin. Preserve redirect method semantics, the overall timeout, the response size limit, and a maximum of 10 redirects. - Use the Codex MCP user agent for requests to authorization-server origins. ## Testing Add coverage for cross-origin header isolation, same-origin dynamic client registration redirects, OAuth header precedence, token refresh, timeout accounting, and response size limits. GitOrigin-RevId: 609d06e2b065e4aa9ca5382b4ae60455f9e26db9
This commit is contained in:
1 parent
32a383c0ba
commit
02360b48d1
10 files changed
+549
-61
No files matched your search
@@ -2,13 +2,23 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_exec_server::HttpClient;
|
||||
use codex_exec_server::HttpHeader;
|
||||
use codex_exec_server::HttpRedirectPolicy;
|
||||
use codex_exec_server::HttpRequestParams;
|
||||
use http::HeaderMap;
|
||||
use http::HeaderValue;
|
||||
use http::Method;
|
||||
use http::StatusCode;
|
||||
use http::header::AUTHORIZATION;
|
||||
use http::header::CONTENT_ENCODING;
|
||||
use http::header::CONTENT_LENGTH;
|
||||
use http::header::CONTENT_TYPE;
|
||||
use http::header::LOCATION;
|
||||
use http::header::TRANSFER_ENCODING;
|
||||
use http::header::USER_AGENT;
|
||||
use oauth2::HttpRequest;
|
||||
use oauth2::HttpResponse;
|
||||
use rmcp::transport::auth::OAuthHttpClient;
|
||||
@@ -16,17 +26,25 @@ use rmcp::transport::auth::OAuthHttpClientError;
|
||||
use rmcp::transport::auth::OAuthHttpClientFuture;
|
||||
use rmcp::transport::auth::OAuthHttpRedirectPolicy;
|
||||
use rmcp::transport::auth::OAuthHttpRequest;
|
||||
use url::Origin;
|
||||
use url::Url;
|
||||
|
||||
use crate::auth_status::OAuthDiscoveryTimeout;
|
||||
use crate::http_client_adapter::StreamableHttpRedirectMode;
|
||||
use crate::utils::MCP_USER_AGENT;
|
||||
|
||||
const MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
|
||||
const MAX_OAUTH_HTTP_REDIRECTS: usize = 10;
|
||||
static NEXT_OAUTH_REQUEST_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum OAuthHttpClientAdapterError {
|
||||
#[error("unsupported OAuth HTTP redirect policy")]
|
||||
UnsupportedRedirectPolicy,
|
||||
#[error("OAuth HTTP request timed out")]
|
||||
TimedOut,
|
||||
#[error("OAuth HTTP request exceeded {MAX_OAUTH_HTTP_REDIRECTS} redirects")]
|
||||
TooManyRedirects,
|
||||
#[error("OAuth HTTP response body exceeds {maximum_bytes} bytes")]
|
||||
ResponseBodyTooLarge { maximum_bytes: usize },
|
||||
}
|
||||
@@ -41,6 +59,7 @@ fn oauth_http_client_error(
|
||||
pub(crate) struct OAuthHttpClientAdapter {
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
default_headers: HeaderMap,
|
||||
resource_origin: Origin,
|
||||
timeout: OAuthDiscoveryTimeout,
|
||||
has_configured_headers: bool,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
@@ -48,45 +67,54 @@ pub(crate) struct OAuthHttpClientAdapter {
|
||||
|
||||
impl OAuthHttpClientAdapter {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new(http_client: Arc<dyn HttpClient>, default_headers: HeaderMap) -> Self {
|
||||
Self {
|
||||
pub(crate) fn new(
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
default_headers: HeaderMap,
|
||||
resource_url: &str,
|
||||
) -> Self {
|
||||
Self::new_with_redirect_mode(
|
||||
http_client,
|
||||
default_headers,
|
||||
timeout: OAuthDiscoveryTimeout::Requested,
|
||||
has_configured_headers: false,
|
||||
redirect_mode: StreamableHttpRedirectMode::Legacy,
|
||||
}
|
||||
resource_url,
|
||||
/*has_configured_headers*/ false,
|
||||
StreamableHttpRedirectMode::Legacy,
|
||||
)
|
||||
.expect("OAuth resource URL should be valid")
|
||||
}
|
||||
|
||||
pub(crate) fn new_with_redirect_mode(
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
default_headers: HeaderMap,
|
||||
resource_url: &str,
|
||||
has_configured_headers: bool,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
) -> Result<Self, url::ParseError> {
|
||||
Ok(Self {
|
||||
http_client,
|
||||
default_headers,
|
||||
resource_origin: Url::parse(resource_url)?.origin(),
|
||||
timeout: OAuthDiscoveryTimeout::Requested,
|
||||
has_configured_headers,
|
||||
redirect_mode,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn new_with_max_timeout_and_redirect_mode(
|
||||
http_client: Arc<dyn HttpClient>,
|
||||
default_headers: HeaderMap,
|
||||
resource_url: &str,
|
||||
max_timeout: Duration,
|
||||
has_configured_headers: bool,
|
||||
redirect_mode: StreamableHttpRedirectMode,
|
||||
) -> Self {
|
||||
Self {
|
||||
) -> Result<Self, url::ParseError> {
|
||||
Ok(Self {
|
||||
http_client,
|
||||
default_headers,
|
||||
resource_origin: Url::parse(resource_url)?.origin(),
|
||||
timeout: OAuthDiscoveryTimeout::Capped(max_timeout),
|
||||
has_configured_headers,
|
||||
redirect_mode,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn execute_request(
|
||||
@@ -105,17 +133,35 @@ impl OAuthHttpClientAdapter {
|
||||
}
|
||||
};
|
||||
let (parts, body) = request.into_parts();
|
||||
let mut headers = self.default_headers.clone();
|
||||
let mut request_url =
|
||||
Url::parse(&parts.uri.to_string()).map_err(oauth_http_client_error)?;
|
||||
let is_resource_origin = request_url.origin() == self.resource_origin;
|
||||
let mut headers = if is_resource_origin {
|
||||
self.default_headers.clone()
|
||||
} else {
|
||||
HeaderMap::new()
|
||||
};
|
||||
for name in parts.headers.keys() {
|
||||
headers.remove(name);
|
||||
}
|
||||
let has_resource_only_headers = is_resource_origin
|
||||
&& headers.iter().any(|(name, value)| {
|
||||
name != USER_AGENT || value != HeaderValue::from_static(MCP_USER_AGENT)
|
||||
});
|
||||
headers.extend(parts.headers);
|
||||
if !is_resource_origin {
|
||||
headers.insert(USER_AGENT, HeaderValue::from_static(MCP_USER_AGENT));
|
||||
}
|
||||
let redirect_policy = oauth_redirect_policy(
|
||||
self.redirect_mode,
|
||||
&headers,
|
||||
self.has_configured_headers,
|
||||
redirect_policy,
|
||||
);
|
||||
// The executor can only follow every redirect or none, so replay credentialed
|
||||
// requests ourselves after checking that each destination stays on the resource origin.
|
||||
let follow_same_origin_redirects =
|
||||
has_resource_only_headers && redirect_policy == HttpRedirectPolicy::Follow;
|
||||
|
||||
let headers = headers
|
||||
.iter()
|
||||
@@ -137,32 +183,106 @@ impl OAuthHttpClientAdapter {
|
||||
.unwrap_or(u64::MAX)
|
||||
.max(1)
|
||||
});
|
||||
let request_id = NEXT_OAUTH_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let (response, mut body_stream) = self
|
||||
.http_client
|
||||
.http_request_stream(HttpRequestParams {
|
||||
method: parts.method.to_string(),
|
||||
url: parts.uri.to_string(),
|
||||
headers,
|
||||
body: (!body.is_empty()).then_some(body.into()),
|
||||
timeout_ms,
|
||||
redirect_policy,
|
||||
request_id: format!("oauth-request-{request_id}"),
|
||||
stream_response: true,
|
||||
})
|
||||
.await
|
||||
.map_err(oauth_http_client_error)?;
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = body_stream.recv().await.map_err(oauth_http_client_error)? {
|
||||
if chunk.len() > MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES - body.len() {
|
||||
let deadline = timeout.map(|timeout| Instant::now() + timeout);
|
||||
let mut params = HttpRequestParams {
|
||||
method: parts.method.to_string(),
|
||||
url: parts.uri.to_string(),
|
||||
headers,
|
||||
body: (!body.is_empty()).then_some(body.into()),
|
||||
timeout_ms,
|
||||
redirect_policy: if follow_same_origin_redirects {
|
||||
HttpRedirectPolicy::Stop
|
||||
} else {
|
||||
redirect_policy
|
||||
},
|
||||
request_id: String::new(),
|
||||
stream_response: true,
|
||||
};
|
||||
let mut redirects = 0;
|
||||
let (response, body) = loop {
|
||||
let request_id = NEXT_OAUTH_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
|
||||
params.request_id = format!("oauth-request-{request_id}");
|
||||
let (response, mut body_stream) = self
|
||||
.http_client
|
||||
.http_request_stream(params.clone())
|
||||
.await
|
||||
.map_err(oauth_http_client_error)?;
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = body_stream.recv().await.map_err(oauth_http_client_error)? {
|
||||
if chunk.len() > MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES - body.len() {
|
||||
return Err(oauth_http_client_error(
|
||||
OAuthHttpClientAdapterError::ResponseBodyTooLarge {
|
||||
maximum_bytes: MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES,
|
||||
},
|
||||
));
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
let Ok(status) = StatusCode::from_u16(response.status) else {
|
||||
break (response, body);
|
||||
};
|
||||
if !follow_same_origin_redirects
|
||||
|| !matches!(
|
||||
status,
|
||||
StatusCode::MOVED_PERMANENTLY
|
||||
| StatusCode::FOUND
|
||||
| StatusCode::SEE_OTHER
|
||||
| StatusCode::TEMPORARY_REDIRECT
|
||||
| StatusCode::PERMANENT_REDIRECT
|
||||
)
|
||||
{
|
||||
break (response, body);
|
||||
}
|
||||
let Some(next_url) = response
|
||||
.headers
|
||||
.iter()
|
||||
.find(|header| header.name.eq_ignore_ascii_case(LOCATION.as_str()))
|
||||
.and_then(|header| request_url.join(&header.value).ok())
|
||||
.filter(|url| url.origin() == self.resource_origin)
|
||||
else {
|
||||
break (response, body);
|
||||
};
|
||||
if redirects >= MAX_OAUTH_HTTP_REDIRECTS {
|
||||
return Err(oauth_http_client_error(
|
||||
OAuthHttpClientAdapterError::ResponseBodyTooLarge {
|
||||
maximum_bytes: MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES,
|
||||
},
|
||||
OAuthHttpClientAdapterError::TooManyRedirects,
|
||||
));
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
if status == StatusCode::SEE_OTHER
|
||||
|| matches!(status, StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND)
|
||||
&& params.method == Method::POST.as_str()
|
||||
{
|
||||
if params.method != Method::HEAD.as_str() {
|
||||
params.method = Method::GET.to_string();
|
||||
}
|
||||
params.body = None;
|
||||
params.headers.retain(|header| {
|
||||
![
|
||||
CONTENT_TYPE,
|
||||
CONTENT_LENGTH,
|
||||
CONTENT_ENCODING,
|
||||
TRANSFER_ENCODING,
|
||||
]
|
||||
.iter()
|
||||
.any(|name| header.name.eq_ignore_ascii_case(name.as_str()))
|
||||
});
|
||||
}
|
||||
params.url = next_url.to_string();
|
||||
if let Some(deadline) = deadline {
|
||||
let remaining =
|
||||
deadline
|
||||
.checked_duration_since(Instant::now())
|
||||
.ok_or_else(|| {
|
||||
oauth_http_client_error(OAuthHttpClientAdapterError::TimedOut)
|
||||
})?;
|
||||
params.timeout_ms = Some(
|
||||
u64::try_from(remaining.as_millis())
|
||||
.unwrap_or(u64::MAX)
|
||||
.max(1),
|
||||
);
|
||||
}
|
||||
request_url = next_url;
|
||||
redirects += 1;
|
||||
};
|
||||
let mut builder = oauth2::http::Response::builder().status(response.status);
|
||||
for header in response.headers {
|
||||
builder = builder.header(header.name, header.value);
|
||||
@@ -192,6 +312,10 @@ impl OAuthHttpClient for OAuthHttpClientAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "oauth_http_client_security_tests.rs"]
|
||||
mod security_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use http::HeaderValue;
|
||||
|
||||
Reference in new issue
Block a user