bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use aws_sdk_bedrockagentcore::{
    Client,
    config::{ConfigBag, Intercept, RuntimeComponents, interceptors::BeforeTransmitInterceptorContextMut},
    error::BoxError,
};
use aws_smithy_runtime_api::client::orchestrator::Metadata;

use crate::context::{self, WORKLOAD_ACCESS_TOKEN_HEADER};

/// The name that identifies the interceptor in the configuration of a client.
const NAME: &str = "bedrock_agentcore::identity::WatPropagation";

/// Forwards the workload access token of the current invocation on the `Invoke*`
/// operations of an AgentCore client.
///
/// The client of [`IdentityClient::data_plane`](super::IdentityClient::data_plane)
/// already has it. Add it yourself to a client that you build separately:
///
/// ```no_run
/// # async fn example() {
/// use aws_sdk_bedrockagentcore::{Client, config::Builder};
/// use bedrock_agentcore::identity::WatPropagation;
///
/// let aws = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
/// let client = Client::from_conf(Builder::from(&aws).interceptor(WatPropagation::new()).build());
/// # }
/// ```
///
/// # What it does
///
/// Before signing each attempt of an `Invoke*` operation, this interceptor sets the
/// `X-Amz-Bedrock-AgentCore-Identity-WAT` header to the workload access token from
/// the current [request context](crate::context), replacing any value set earlier.
/// To override the token for one call, set that header in `.customize().mutate_request(...)`
/// on the operation. This customization runs after the interceptor and before signing,
/// so the SDK signs the override for that call. Subsequent calls still use the context token.
///
/// In version 1.87.0 of the generated client these operations are
/// `InvokeAgentRuntime`, `InvokeAgentRuntimeCommand`, `InvokeBrowser`,
/// `InvokeCodeInterpreter`, `InvokeHarness` and `InvokeWebSearch`. An operation with
/// that prefix in a later version is included.
///
/// Other operations are sent as they are. So is an `Invoke*` operation outside a
/// request context, or in a context without a nonempty token: a task started with
/// `tokio::spawn` needs [`context::scope`](crate::context::scope).
///
/// A token that is not a valid header value fails the operation before it is sent.
/// The error does not contain the token.
///
/// # Logging
///
/// This crate does not log the token, and the AWS SDK does not log it at the `DEBUG`
/// level and above. At `TRACE`, the SDK prints each request with all of its headers
/// when it signs and when it sends it (the `aws_sigv4` and `aws_smithy_runtime`
/// targets), and that output contains the token. Keep these targets above `TRACE`
/// where logs must not hold it.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct WatPropagation;

impl WatPropagation {
    /// Creates the interceptor.
    pub fn new() -> Self {
        Self
    }

    /// `client` with the interceptor. A client that already has it is returned as it
    /// is, with its connection pool.
    pub(super) fn install(client: Client) -> Client {
        if client.config().interceptors().any(|interceptor| interceptor.name() == NAME) {
            return client;
        }
        Client::from_conf(client.config().to_builder().interceptor(Self).build())
    }
}

impl Intercept for WatPropagation {
    fn name(&self) -> &'static str {
        NAME
    }

    fn modify_before_signing(
        &self,
        context: &mut BeforeTransmitInterceptorContextMut<'_>,
        _runtime_components: &RuntimeComponents,
        cfg: &mut ConfigBag,
    ) -> Result<(), BoxError> {
        if !cfg.load::<Metadata>().is_some_and(|operation| operation.name().starts_with("Invoke")) {
            return Ok(());
        }
        let Ok(token) = context::workload_access_token() else { return Ok(()) };
        context
            .request_mut()
            .headers_mut()
            .try_insert(WORKLOAD_ACCESS_TOKEN_HEADER, token.expose().to_owned())
            // The error of `try_insert` is dropped: it can describe the value.
            .map_err(|_| "the workload access token is not a valid HTTP header value")?;
        Ok(())
    }
}