Skip to main content

strands/models/openai/
mantle.rs

1//! Routing an [`OpenAIModel`](super::OpenAIModel) through Amazon Bedrock's OpenAI-compatible
2//! "Mantle" endpoint, behind the `mantle` feature.
3//!
4//! [`OpenAIModel::bedrock_mantle`] takes a [`BedrockMantleConfig`], which gives the client its base URL and an API key function that mints a
5//! fresh bearer token for every request, so long-running agents outlive a token's lifetime. The
6//! token is the one `@aws/bedrock-token-generator` makes: `bedrock-api-key-` and the base64 of a
7//! SigV4-presigned `CallWithBearerToken` URL, signed with credentials from the provider in the
8//! config or the default AWS credential chain.
9
10use 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
31/// Mantle model lines served from `/openai/v1`; every other model uses `/v1`, and the wrong base
32/// path fails with HTTP 400. No Mantle API reports a model's base path, so these prefixes follow
33/// the verified `us-east-1` catalog. Each prefix covers one model line, never a vendor: one
34/// vendor's lines can split across base paths (`google.gemma-4-*` is on `/openai/v1`,
35/// `google.gemma-3-*` on `/v1`).
36const 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
52/// Credentials within this window of their expiry are fetched again, as the AWS SDKs refresh them.
53const CREDENTIALS_REFRESH_WINDOW: Duration = Duration::from_secs(300);
54
55/// Routes an `OpenAIModel` through Amazon Bedrock's Mantle endpoint (`BedrockMantleConfig`).
56///
57/// Passed to [`OpenAIModel::bedrock_mantle`], which sets the client's base URL and API key from
58/// it.
59#[derive(Clone, Default, bon::Builder)]
60pub struct BedrockMantleConfig {
61    /// AWS region of the Mantle endpoint. Defaults to `AWS_REGION`, else `AWS_DEFAULT_REGION`;
62    /// building the model fails when none is set.
63    #[builder(into)]
64    pub region: Option<String>,
65    /// Credentials the bearer tokens are signed with, replacing the default AWS credential chain.
66    /// This AWS SDK type is part of the public API as an escape hatch; wrap static
67    /// [`Credentials`](super::Credentials) with [`SharedCredentialsProvider::new`].
68    pub credentials_provider: Option<SharedCredentialsProvider>,
69    /// Bearer token lifetime, at most 12 hours, which is also the default.
70    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
86/// Whether `region` looks like an AWS region (`/^[a-z]{2}(-[a-z]+)+-[0-9]+$/`), such as
87/// `us-east-1` or `us-gov-east-1`.
88fn 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
102/// Validates a region before it goes into the endpoint URL, where a malformed one (with `@`, `:`,
103/// `/` or `#`) could point the request, and its bearer token, at another host.
104fn 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
111/// The Mantle region: the config's, else `AWS_REGION`, else
112/// `AWS_DEFAULT_REGION`, validated.
113pub(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(&region);
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
128/// The Mantle base path of a model.
129pub(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
140/// The Mantle base URL for a region and model.
141pub(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
148/// The token lifetime in seconds, checked as the token generator checks it.
149fn 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
162/// Percent-encodes every byte except ASCII letters, digits and `-_.~`, as the AWS SDK's URI escaping
163/// does.
164fn 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
176/// Mints a bearer token: presigns `POST https://bedrock.amazonaws.com/?Action=CallWithBearerToken` for
177/// `bedrock` in `region`, drops the scheme, appends `&Version=1` and base64-encodes it after
178/// `bedrock-api-key-`.
179pub(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, &params)?.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    // The token generator's URL formatter writes the query sorted by key.
213    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
226/// Mints Mantle bearer tokens with the configured or default credentials. The default chain is built
227/// once, on the first token.
228pub(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    /// The credentials, reused until they come within the refresh window of their expiry.
263    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    /// Mints a token.
281    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
292/// An API key function that mints a fresh bearer token on every call,
293/// with an actionable message when minting fails. An out-of-range `expires_in` is reported as is.
294pub(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/// A bearer token could not be minted.
311#[derive(Debug, thiserror::Error)]
312#[error("{message}")]
313struct MantleTokenError {
314    message: String,
315    #[source]
316    source: BoxError,
317}
318
319impl OpenAIModel {
320    /// Creates a model that routes through Amazon Bedrock's OpenAI-compatible Mantle endpoint.
321    ///
322    /// The base URL follows the region and the model's base path, and the API key mints a fresh
323    /// SigV4 bearer token for every request.
324    ///
325    /// ```no_run
326    /// use strands::models::openai::{BedrockMantleConfig, OpenAIModel, OpenAIModelOptions};
327    ///
328    /// # fn main() -> strands::Result<()> {
329    /// let model = OpenAIModel::bedrock_mantle(
330    ///     OpenAIModelOptions::builder().model_id("openai.gpt-oss-120b").build_options(),
331    ///     BedrockMantleConfig::builder().region("us-east-1").build(),
332    /// )?;
333    /// # Ok(())
334    /// # }
335    /// ```
336    ///
337    /// # Errors
338    ///
339    /// Fails when `options` sets `api_key` or `client_config.base_url`, which the Mantle config
340    /// sets instead, when the region is missing or malformed, when `params` is not a JSON object,
341    /// or when the HTTP client cannot be built.
342    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
371/// What a Mantle model keeps to rebuild its client when a model id change moves the base path.
372pub(super) struct MantleRoute {
373    pub(super) region: String,
374    pub(super) client_config: OpenAIClientConfig,
375    /// Built once and reused across reroutes: it holds the token provider and its credentials.
376    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(&region, model_id);
400        let provider = Arc::new(MantleTokenProvider::new(mantle_config, &region));
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    /// Points the Mantle client at the base path of `model_id` when it is the other one; a model
422    /// on the same base path keeps the client and its connections.
423    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}