Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 77 additions & 2 deletions generators/rust/base/src/asIs/http_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,12 @@ impl HttpClient {
/// The request body and response are keyed by the property names configured on the
/// API's OAuth scheme (via `exchange`), so non-standard token contracts (e.g. camelCase
/// field names or an absent `grant_type`) are honored instead of a hardcoded shape.
///
/// Config-level custom headers are applied to the token request, since gateways often
/// require them on the token endpoint too. Request-level headers are deliberately not
/// applied: the token is cached and shared across requests, so it must not depend on the
/// options of whichever request happens to trigger the fetch. Auth headers are also not
/// applied, as this request is what produces the credential they would carry.
async fn fetch_oauth_token(
&self,
base_url: &str,
Expand All @@ -445,11 +451,17 @@ impl HttpClient {
}
let body = serde_json::Value::Object(body);

let response = self
let mut request = self
.client
.request(Method::POST, &url)
.json(&body)
.send()
.build()
.map_err(ApiError::Network)?;
self.apply_custom_headers(&mut request, &None)?;

let response = self
.client
.execute(request)
.await
.map_err(ApiError::Network)?;

Expand Down Expand Up @@ -755,4 +767,67 @@ mod tests {
assert!(!HttpClient::is_retryable_status(401));
assert!(!HttpClient::is_retryable_status(404));
}

/// Accepts a single connection, returns the raw request text and replies with a token.
async fn serve_one_token_request(
listener: tokio::net::TcpListener,
) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};

let (mut socket, _) = listener.accept().await.expect("accept");
let mut raw = Vec::new();
let mut buffer = [0u8; 1024];
loop {
let read = socket.read(&mut buffer).await.expect("read");
raw.extend_from_slice(&buffer[..read]);
if read == 0 || String::from_utf8_lossy(&raw).contains("\r\n\r\n") {
break;
}
}
Comment on lines +780 to +786

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 warning

The read loop has no timeout: if a client ever sends headers without a terminating \r\n\r\n and keeps the connection open, this hangs forever and takes CI with it. Wrap the accept/read in tokio::time::timeout (or at least bound the loop iterations) so a failure surfaces as a test failure rather than a hung job.


let body = r#"{"access_token":"token-from-server","expires_in":3600}"#;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.expect("write");
socket.flush().await.expect("flush");

String::from_utf8_lossy(&raw).to_string()
}

#[tokio::test]
async fn test_oauth_token_request_sends_custom_headers() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let base_url = format!("http://{}", listener.local_addr().expect("addr"));
let server = tokio::spawn(serve_one_token_request(listener));
Comment on lines +800 to +806

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 warning

This test ships into every generated SDK, so it hard-depends on tokio being available at test time with the net, io-util, rt-multi-thread and macros features. If any generated Cargo.toml template pins tokio with a narrower feature set (or as a non-dev dependency only), cargo test breaks for all consumers. Given cargo test couldn't be run locally, please confirm the generated Cargo.toml feature list before merging — a compile failure here lands in 178 SDKs at once.


let mut config = ClientConfig::default();
config.base_url = base_url;
config
.custom_headers
.insert("X-Gateway-Token".to_string(), "sunflower".to_string());
let client = HttpClient::new(config).expect("client");

let (access_token, _) = client
.fetch_oauth_token(
&client.config.base_url.clone(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 suggestion

&client.config.base_url.clone() allocates a String just to take a &str of it. &client.config.base_url works via deref coercion (and avoids a redundant_clone clippy hit).

"/token",
"client-id",
"client-secret",
&OAuthTokenExchangeConfig::default(),
)
.await
.expect("token");

let raw_request = server.await.expect("server");
assert_eq!(access_token, "token-from-server");
assert!(
raw_request.contains("x-gateway-token: sunflower"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 suggestion

Asserting the exact lowercase wire form couples the test to hyper's header serialization. A case-insensitive check is more robust:

Suggested change
raw_request.contains("x-gateway-token: sunflower"),
raw_request.to_ascii_lowercase().contains("x-gateway-token: sunflower"),

"token request is missing the client's custom headers: {raw_request}"
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# yaml-language-server: $schema=../../../../../fern-changes-yml.schema.json

- summary: |
Apply client-level custom headers to the OAuth token request. The client-credentials
token exchange was built directly on the underlying HTTP client, so it was the only
request that skipped `ClientConfig.custom_headers` — APIs whose gateway requires a
header on the token endpoint rejected the exchange with a 401, and the
`X-Fern-SDK-*` headers were missing from token requests.

Request-level headers and auth headers are intentionally still not applied: the token
is cached and shared across requests, and the token request is what produces the
credential auth headers would carry.
type: fix
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,12 @@ impl HttpClient {
/// The request body and response are keyed by the property names configured on the
/// API's OAuth scheme (via `exchange`), so non-standard token contracts (e.g. camelCase
/// field names or an absent `grant_type`) are honored instead of a hardcoded shape.
///
/// Config-level custom headers are applied to the token request, since gateways often
/// require them on the token endpoint too. Request-level headers are deliberately not
/// applied: the token is cached and shared across requests, so it must not depend on the
/// options of whichever request happens to trigger the fetch. Auth headers are also not
/// applied, as this request is what produces the credential they would carry.
async fn fetch_oauth_token(
&self,
base_url: &str,
Expand All @@ -445,11 +451,17 @@ impl HttpClient {
}
let body = serde_json::Value::Object(body);

let response = self
let mut request = self
.client
.request(Method::POST, &url)
.json(&body)
.send()
.build()
.map_err(ApiError::Network)?;
self.apply_custom_headers(&mut request, &None)?;

let response = self
.client
.execute(request)
.await
.map_err(ApiError::Network)?;

Expand Down Expand Up @@ -755,4 +767,67 @@ mod tests {
assert!(!HttpClient::is_retryable_status(401));
assert!(!HttpClient::is_retryable_status(404));
}

/// Accepts a single connection, returns the raw request text and replies with a token.
async fn serve_one_token_request(
listener: tokio::net::TcpListener,
) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};

let (mut socket, _) = listener.accept().await.expect("accept");
let mut raw = Vec::new();
let mut buffer = [0u8; 1024];
loop {
let read = socket.read(&mut buffer).await.expect("read");
raw.extend_from_slice(&buffer[..read]);
if read == 0 || String::from_utf8_lossy(&raw).contains("\r\n\r\n") {
break;
}
}

let body = r#"{"access_token":"token-from-server","expires_in":3600}"#;
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.expect("write");
socket.flush().await.expect("flush");

String::from_utf8_lossy(&raw).to_string()
}

#[tokio::test]
async fn test_oauth_token_request_sends_custom_headers() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let base_url = format!("http://{}", listener.local_addr().expect("addr"));
let server = tokio::spawn(serve_one_token_request(listener));

let mut config = ClientConfig::default();
config.base_url = base_url;
config
.custom_headers
.insert("X-Gateway-Token".to_string(), "sunflower".to_string());
let client = HttpClient::new(config).expect("client");

let (access_token, _) = client
.fetch_oauth_token(
&client.config.base_url.clone(),
"/token",
"client-id",
"client-secret",
&OAuthTokenExchangeConfig::default(),
)
.await
.expect("token");

let raw_request = server.await.expect("server");
assert_eq!(access_token, "token-from-server");
assert!(
raw_request.contains("x-gateway-token: sunflower"),
"token request is missing the client's custom headers: {raw_request}"
);
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading