1use std::fmt;
11use std::sync::{Arc, Mutex, PoisonError, RwLock};
12use std::time::{Duration, SystemTime};
13
14use aws_config::Region;
15use aws_config::default_provider::credentials::DefaultCredentialsChain;
16use aws_credential_types::Credentials;
17use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
18use aws_sigv4::http_request::{SignableBody, SignableRequest, SignatureLocation, SigningSettings, sign};
19use aws_sigv4::sign::v4;
20use base64::Engine;
21use tokio::sync::OnceCell;
22
23use super::client::{Env, HttpOpenAIClient};
24use super::{
25 ApiKey, Inner, OpenAIClientConfig, OpenAIModel, OpenAIModelOptions, model_error, model_id_of, prepare_config,
26};
27use crate::error::{BoxError, Error, Result};
28
29const MANTLE_DOCS_URL: &str = "https://docs.aws.amazon.com/bedrock/latest/userguide/inference-openai.html";
30
31const OPENAI_PATH_MODEL_PREFIXES: [&str; 6] = [
37 "openai.gpt-5.",
38 "openai.gpt-daybreak-",
39 "openai.gpt-6-",
40 "openai.gpt-6.",
41 "xai.grok-4.",
42 "google.gemma-4-",
43];
44
45const MAX_TOKEN_EXPIRES_IN_SECONDS: u64 = 43_200;
46const SERVICE_NAME: &str = "bedrock";
47const TOKEN_HOST: &str = "bedrock.amazonaws.com";
48const TOKEN_ACTION: &str = "CallWithBearerToken";
49const AUTH_PREFIX: &str = "bedrock-api-key-";
50const TOKEN_VERSION: &str = "&Version=1";
51
52const CREDENTIALS_REFRESH_WINDOW: Duration = Duration::from_secs(300);
54
55#[derive(Clone, Default, bon::Builder)]
60pub struct BedrockMantleConfig {
61 #[builder(into)]
64 pub region: Option<String>,
65 pub credentials_provider: Option<SharedCredentialsProvider>,
69 pub expires_in: Option<Duration>,
71}
72
73impl fmt::Debug for BedrockMantleConfig {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("BedrockMantleConfig")
76 .field("region", &self.region)
77 .field(
78 "credentials_provider",
79 &self.credentials_provider.as_ref().map(|_| "<set>"),
80 )
81 .field("expires_in", &self.expires_in)
82 .finish()
83 }
84}
85
86fn is_valid_region(region: &str) -> bool {
89 let parts: Vec<&str> = region.split('-').collect();
90 let [first, middle @ .., last] = parts.as_slice() else {
91 return false;
92 };
93 let letters = |part: &&str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_lowercase());
94 first.len() == 2
95 && letters(first)
96 && !middle.is_empty()
97 && middle.iter().all(letters)
98 && !last.is_empty()
99 && last.bytes().all(|byte| byte.is_ascii_digit())
100}
101
102fn validate_region(region: &str) -> Result<String> {
105 if !is_valid_region(region) {
106 return Err(Error::other(format!("invalid AWS region: '{region}'")));
107 }
108 Ok(region.to_owned())
109}
110
111pub(super) fn resolve_mantle_region(config: &BedrockMantleConfig, env: Env<'_>) -> Result<String> {
114 if let Some(region) = config.region.as_deref().filter(|region| !region.is_empty()) {
115 return validate_region(region);
116 }
117 let from_env = env("AWS_REGION")
118 .filter(|region| !region.is_empty())
119 .or_else(|| env("AWS_DEFAULT_REGION").filter(|region| !region.is_empty()));
120 if let Some(region) = from_env {
121 return validate_region(®ion);
122 }
123 Err(Error::other(format!(
124 "could not resolve an AWS region for Bedrock Mantle. Pass 'region' in BedrockMantleConfig or set AWS_REGION in the environment. See {MANTLE_DOCS_URL} for supported regions."
125 )))
126}
127
128pub(super) fn resolve_mantle_base_path(model_id: &str) -> &'static str {
130 if OPENAI_PATH_MODEL_PREFIXES
131 .iter()
132 .any(|prefix| model_id.starts_with(prefix))
133 {
134 "/openai/v1"
135 } else {
136 "/v1"
137 }
138}
139
140pub(super) fn bedrock_mantle_base_url(region: &str, model_id: &str) -> String {
142 format!(
143 "https://bedrock-mantle.{region}.api.aws{}",
144 resolve_mantle_base_path(model_id)
145 )
146}
147
148fn token_expires_in_seconds(expires_in: Option<Duration>) -> Result<u64, BoxError> {
150 let Some(expires_in) = expires_in else {
151 return Ok(MAX_TOKEN_EXPIRES_IN_SECONDS);
152 };
153 let seconds = expires_in.as_secs();
154 if seconds == 0 || seconds > MAX_TOKEN_EXPIRES_IN_SECONDS {
155 return Err(
156 format!("ExpiresInSeconds must be in the range (0, {MAX_TOKEN_EXPIRES_IN_SECONDS}] seconds.").into(),
157 );
158 }
159 Ok(seconds)
160}
161
162fn escape_uri(text: &str) -> String {
165 let mut escaped = String::with_capacity(text.len());
166 for byte in text.bytes() {
167 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
168 escaped.push(char::from(byte));
169 } else {
170 escaped.push_str(&format!("%{byte:02X}"));
171 }
172 }
173 escaped
174}
175
176pub(super) fn mint_token(
180 credentials: Credentials,
181 region: &str,
182 expires_in_seconds: u64,
183 time: SystemTime,
184) -> Result<String, BoxError> {
185 let identity = credentials.into();
186 let mut settings = SigningSettings::default();
187 settings.signature_location = SignatureLocation::QueryParams;
188 settings.expires_in = Some(Duration::from_secs(expires_in_seconds));
189 let params = v4::SigningParams::builder()
190 .identity(&identity)
191 .region(region)
192 .name(SERVICE_NAME)
193 .time(time)
194 .settings(settings)
195 .build()?
196 .into();
197 let url = format!("https://{TOKEN_HOST}/?Action={TOKEN_ACTION}");
198 let request = SignableRequest::new(
199 "POST",
200 url,
201 std::iter::once(("host", TOKEN_HOST)),
202 SignableBody::Bytes(&[]),
203 )?;
204 let (instructions, _signature) = sign(request, ¶ms)?.into_parts();
205 let mut query: Vec<(&str, String)> = vec![("Action", TOKEN_ACTION.to_owned())];
206 query.extend(
207 instructions
208 .params()
209 .iter()
210 .map(|(name, value)| (*name, value.to_string())),
211 );
212 query.sort_by(|left, right| left.0.cmp(right.0));
214 let query = query
215 .iter()
216 .map(|(name, value)| format!("{}={}", escape_uri(name), escape_uri(value)))
217 .collect::<Vec<_>>()
218 .join("&");
219 let presigned = format!("{TOKEN_HOST}/?{query}{TOKEN_VERSION}");
220 Ok(format!(
221 "{AUTH_PREFIX}{}",
222 base64::engine::general_purpose::STANDARD.encode(presigned)
223 ))
224}
225
226pub(super) struct MantleTokenProvider {
229 region: String,
230 configured: Option<SharedCredentialsProvider>,
231 expires_in: Option<Duration>,
232 default_chain: OnceCell<SharedCredentialsProvider>,
233 cached: Mutex<Option<Credentials>>,
234}
235
236impl MantleTokenProvider {
237 pub(super) fn new(config: BedrockMantleConfig, region: &str) -> Self {
238 Self {
239 region: region.to_owned(),
240 configured: config.credentials_provider,
241 expires_in: config.expires_in,
242 default_chain: OnceCell::new(),
243 cached: Mutex::new(None),
244 }
245 }
246
247 async fn provider(&self) -> &SharedCredentialsProvider {
248 if let Some(provider) = &self.configured {
249 return provider;
250 }
251 self.default_chain
252 .get_or_init(|| async {
253 let chain = DefaultCredentialsChain::builder()
254 .region(Region::new(self.region.clone()))
255 .build()
256 .await;
257 SharedCredentialsProvider::new(chain)
258 })
259 .await
260 }
261
262 async fn credentials(&self) -> Result<Credentials, BoxError> {
264 let fresh = |credentials: &Credentials| {
265 credentials.expiry().is_none_or(|expiry| {
266 expiry
267 .duration_since(SystemTime::now())
268 .is_ok_and(|left| left > CREDENTIALS_REFRESH_WINDOW)
269 })
270 };
271 let cached = self.cached.lock().unwrap_or_else(PoisonError::into_inner).clone();
272 if let Some(credentials) = cached.filter(fresh) {
273 return Ok(credentials);
274 }
275 let credentials = self.provider().await.provide_credentials().await?;
276 *self.cached.lock().unwrap_or_else(PoisonError::into_inner) = Some(credentials.clone());
277 Ok(credentials)
278 }
279
280 async fn token(&self) -> Result<String, BoxError> {
282 let credentials = self.credentials().await?;
283 mint_token(
284 credentials,
285 &self.region,
286 token_expires_in_seconds(self.expires_in)?,
287 SystemTime::now(),
288 )
289 }
290}
291
292pub(super) fn mantle_api_key(provider: Arc<MantleTokenProvider>) -> ApiKey {
295 ApiKey::setter(move || {
296 let provider = Arc::clone(&provider);
297 async move {
298 token_expires_in_seconds(provider.expires_in)?;
299 provider.token().await.map_err(|cause| {
300 let message = format!(
301 "failed to mint Bedrock Mantle bearer token for region '{}' | verify your AWS credentials and network connectivity",
302 provider.region
303 );
304 BoxError::from(MantleTokenError { message, source: cause })
305 })
306 }
307 })
308}
309
310#[derive(Debug, thiserror::Error)]
312#[error("{message}")]
313struct MantleTokenError {
314 message: String,
315 #[source]
316 source: BoxError,
317}
318
319impl OpenAIModel {
320 pub fn bedrock_mantle(options: impl Into<OpenAIModelOptions>, mantle_config: BedrockMantleConfig) -> Result<Self> {
343 Self::bedrock_mantle_with_env(options.into(), mantle_config, &|name| std::env::var(name).ok())
344 }
345
346 pub(super) fn bedrock_mantle_with_env(
347 options: OpenAIModelOptions,
348 mantle_config: BedrockMantleConfig,
349 env: Env<'_>,
350 ) -> Result<Self> {
351 let parts = options.into_parts();
352 let config = prepare_config(parts.api, parts.config)?;
353 let route = MantleRoute::new(
354 mantle_config,
355 parts.api_key.as_ref(),
356 parts.client_config,
357 model_id_of(&config),
358 env,
359 )?;
360 let client = route.client(env)?;
361 Ok(Self::from_inner(Inner {
362 api: parts.api,
363 config: RwLock::new(config),
364 client: RwLock::new(Arc::new(client)),
365 rejected_reasoning_model_id: RwLock::new(None),
366 mantle: Some(RwLock::new(route)),
367 }))
368 }
369}
370
371pub(super) struct MantleRoute {
373 pub(super) region: String,
374 pub(super) client_config: OpenAIClientConfig,
375 pub(super) api_key: ApiKey,
377 pub(super) base_url: String,
378}
379
380impl MantleRoute {
381 fn new(
382 mantle_config: BedrockMantleConfig,
383 api_key: Option<&ApiKey>,
384 client_config: OpenAIClientConfig,
385 model_id: &str,
386 env: Env<'_>,
387 ) -> Result<Self> {
388 if api_key.is_some() {
389 return Err(Error::other(
390 "'api_key' cannot be combined with Bedrock Mantle; the API key is derived from the Mantle config automatically.",
391 ));
392 }
393 if client_config.base_url.is_some() {
394 return Err(Error::other(
395 "client_config must not contain base_url for Bedrock Mantle; it is derived from the Mantle config automatically.",
396 ));
397 }
398 let region = resolve_mantle_region(&mantle_config, env)?;
399 let base_url = bedrock_mantle_base_url(®ion, model_id);
400 let provider = Arc::new(MantleTokenProvider::new(mantle_config, ®ion));
401 Ok(Self {
402 api_key: mantle_api_key(provider),
403 region,
404 client_config,
405 base_url,
406 })
407 }
408
409 fn client(&self, env: Env<'_>) -> Result<HttpOpenAIClient> {
410 HttpOpenAIClient::new(
411 Some(&self.api_key),
412 Some(self.base_url.clone()),
413 &self.client_config,
414 env,
415 )
416 .map_err(model_error)
417 }
418}
419
420impl Inner {
421 pub(super) fn reroute_mantle(&self, model_id: &str) -> Result<()> {
424 let Some(mantle) = &self.mantle else {
425 return Ok(());
426 };
427 let mut route = mantle.write().unwrap_or_else(PoisonError::into_inner);
428 let next_base_url = bedrock_mantle_base_url(&route.region, model_id);
429 if next_base_url == route.base_url {
430 return Ok(());
431 }
432 tracing::debug!(
433 "model_id=<{model_id}> | rerouting the Bedrock Mantle client from <{}> to <{next_base_url}>",
434 route.base_url
435 );
436 let previous = std::mem::replace(&mut route.base_url, next_base_url);
437 let client = match route.client(&|name| std::env::var(name).ok()) {
438 Ok(client) => client,
439 Err(error) => {
440 route.base_url = previous;
441 return Err(error);
442 }
443 };
444 *self.client.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(client);
445 Ok(())
446 }
447}