bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
//! Credentials from AgentCore Identity for the services an agent calls.
//!
//! An [`IdentityClient`] asks AgentCore Identity for a credential of a credential
//! provider. Each request names the provider and carries the workload access token of
//! the invocation, which says on whose behalf the agent acts.
//!
//! ```no_run
//! use bedrock_agentcore::identity::{AuthFlow, IdentityClient};
//!
//! async fn call_orders(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
//!     let key = identity.api_key("orders-api").send().await?;
//!     let token = identity.oauth2_token("orders", AuthFlow::M2m).scopes(["orders/read"]).send().await?;
//!     // Pass `key.expose()` or `token.expose()` to the orders client where the
//!     // request is made.
//!     # let _ = (key, token);
//!     Ok(())
//! }
//! ```
//!
//! [`Oauth2TokenBuilder`] describes the flow in which a user gives consent.
//!
//! # One client for all requests
//!
//! Create the client once at startup and share it, or clone it: clones use the same
//! connection pool. The client holds no token. Each operation reads the workload
//! access token when it is sent:
//!
//! 1. The token given to the operation with `.workload_access_token(..)`.
//! 2. Otherwise the token of the ambient [request context](crate::context).
//!
//! Inside a handler of the runtime server the second case needs no code. The ambient
//! context also covers the items of a streamed response. A task started with
//! `tokio::spawn` does not inherit it: wrap its future in
//! [`context::scope`], or give the operation a token. Outside
//! AgentCore Runtime, for example in local development, give the operation a token.
//!
//! An operation without a usable token fails with
//! [`ErrorKind::MissingWorkloadToken`] before
//! any request is made. The text of the error names the cause.
//!
//! # When an invocation carries a token
//!
//! AgentCore Runtime sends a workload access token only when the caller names a
//! user: a `runtimeUserId` with IAM authorization, which needs the
//! `bedrock-agentcore:InvokeAgentRuntimeForUser` permission, or a JWT. A call of
//! `InvokeAgentRuntime` with IAM authorization and no user ID reaches the agent
//! without a token.
//!
//! A local call has no token either. The workload identity of a deployed agent
//! runtime belongs to the service and gives no token to a caller. Create a workload
//! identity for local tests once, get a token for it, and send the token in the
//! `X-Amz-Bedrock-AgentCore-Identity-WAT` header:
//!
//! ```text
//! aws bedrock-agentcore-control create-workload-identity --name my-agent-local
//! TOKEN=$(aws bedrock-agentcore get-workload-access-token --workload-name my-agent-local \
//!   --query workloadAccessToken --output text)
//! curl -s localhost:8080/invocations \
//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
//!   -H "X-Amz-Bedrock-AgentCore-Identity-WAT: $TOKEN" \
//!   -d '{}'
//! ```
//!
//! For a flow that acts for a user, get the token with
//! `get-workload-access-token-for-user-id`.
//!
//! # Calling other AgentCore services for the same user
//!
//! [`IdentityClient::data_plane`] is the generated AgentCore client. By default,
//! its `Invoke*` operations carry the workload access token of the current
//! invocation. An agent that invokes another agent, or a tool such as Code
//! Interpreter, then does so for the same user:
//!
//! ```no_run
//! # use bedrock_agentcore::identity::IdentityClient;
//! # async fn example(identity: &IdentityClient) -> Result<(), Box<dyn std::error::Error>> {
//! let reply = identity
//!     .data_plane()
//!     .invoke_agent_runtime()
//!     .agent_runtime_arn("arn:aws:bedrock-agentcore:us-west-2:111122223333:runtime/other-agent")
//!     .payload(r#"{"prompt": "hello"}"#.as_bytes().into())
//!     .send()
//!     .await?;
//! # let _ = reply;
//! # Ok(())
//! # }
//! ```
//!
//! See [`WatPropagation`] for the rule and for a client that you build yourself.
//!
//! # Secrets
//!
//! Credentials are returned in [`ApiKey`] and [`AccessToken`], whose `Debug` output never
//! contains the value. Read the value with `expose()` where it is used, and keep it
//! out of logs. See [`Error`] for the source of a failed operation.

use std::fmt;

use aws_sdk_bedrockagentcore::{
    Client,
    config::http::HttpResponse,
    error::{ProvideErrorMetadata, SdkError},
    operation::RequestId,
};
use aws_types::SdkConfig;

use crate::{
    Error, ErrorKind, RequestContext,
    context::{self, WorkloadAccessToken},
};

mod api_key;
mod oauth2;
mod poller;
mod propagation;
#[cfg(test)]
mod tests;
mod workload_identity;

pub use api_key::{ApiKey, ApiKeyBuilder};
pub use oauth2::{AccessToken, AuthFlow, AuthorizationUrl, Oauth2Event, Oauth2TokenBuilder};
pub use propagation::WatPropagation;
pub use workload_identity::WorkloadIdentityCredentials;

/// Defines a credential type that follows [`WorkloadAccessToken`]: an owned string
/// that `Debug` never prints.
macro_rules! secret {
    ($(#[$attribute:meta])* $name:ident) => {
        $(#[$attribute])*
        ///
        /// Its `Debug` output never contains the value. Read the value with
        /// [`expose`](Self::expose).
        #[derive(Clone, PartialEq, Eq)]
        pub struct $name(String);

        impl $name {
            /// Wraps a value.
            pub fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }

            /// The value. Keep it out of logs.
            pub fn expose(&self) -> &str {
                &self.0
            }
        }

        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("*** Sensitive Data Redacted ***")
            }
        }
    };
}
use secret;

/// A client of AgentCore Identity.
///
/// It is cheap to clone, and clones share one connection pool. See the
/// [module documentation](self) for how an operation finds its workload access token.
#[derive(Clone)]
pub struct IdentityClient {
    client: Client,
}

impl IdentityClient {
    /// Creates a client from the AWS configuration of the application.
    ///
    /// Region, credentials, retries, timeouts and endpoint come from `config`, for the
    /// requests of this client and for [`data_plane`](Self::data_plane). Load it
    /// once at startup, for example with
    /// `aws_config::load_defaults(BehaviorVersion::latest()).await`.
    ///
    /// A configuration without a region is accepted here. Each operation then fails
    /// with [`ErrorKind::Service`] when it is sent.
    ///
    /// # Panics
    ///
    /// As `aws_sdk_bedrockagentcore::Client::new` does: when `config` has no behavior
    /// version, no HTTP client, or no async sleep implementation while retries or
    /// timeouts are enabled. `aws_config::load_defaults` sets all three.
    pub fn new(config: &SdkConfig) -> Self {
        let config = aws_sdk_bedrockagentcore::config::Builder::from(config).interceptor(WatPropagation::new());
        Self { client: Client::from_conf(config.build()) }
    }

    /// Creates a client that sends its requests through `client`, for example a
    /// client with a custom configuration or a mocked client in a test.
    ///
    /// The configuration of `client` is kept, with its interceptors, runtime plugins,
    /// credentials and endpoint, and [`WatPropagation`] is added to it.
    ///
    /// # Connection pool
    ///
    /// Adding the interceptor builds a new generated client from the configuration of
    /// `client`. An HTTP client that was set on that configuration is shared, so both
    /// clients use its connection pool. Without one, the new client gets a default
    /// HTTP client of its own, and with it a new, empty pool. To keep the connections
    /// of such a client, add [`WatPropagation`] when you build it: a client that
    /// already has the interceptor is used as it is.
    pub fn from_client(client: Client) -> Self {
        Self { client: WatPropagation::install(client) }
    }

    /// The generated AgentCore client of this `IdentityClient`, for the operations
    /// that this crate does not wrap.
    ///
    /// By default, its `Invoke*` operations carry the current invocation's workload
    /// access token. See [`WatPropagation`] to override the token for one call.
    pub fn data_plane(&self) -> &Client {
        &self.client
    }

    /// Starts a request for the API key of the credential provider `provider`.
    pub fn api_key(&self, provider: impl Into<String>) -> ApiKeyBuilder {
        ApiKeyBuilder::new(self.client.clone(), provider.into())
    }

    /// Starts a request for an OAuth2 access token of the credential provider
    /// `provider`, obtained with `flow`.
    pub fn oauth2_token(&self, provider: impl Into<String>, flow: AuthFlow) -> Oauth2TokenBuilder {
        Oauth2TokenBuilder::new(self.client.clone(), provider.into(), flow)
    }
}

impl fmt::Debug for IdentityClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IdentityClient").finish_non_exhaustive()
    }
}

/// The workload access token of one operation: `explicit` when the operation was given
/// one, otherwise the token of `ctx`.
///
/// An explicit token is not replaced when it is empty. The operation fails instead,
/// as in the TypeScript SDK.
fn resolve_workload_access_token(
    explicit: Option<WorkloadAccessToken>,
    ctx: Option<&RequestContext>,
) -> Result<WorkloadAccessToken, Error> {
    if let Some(token) = explicit {
        return Some(token).filter(|token| !token.expose().is_empty()).ok_or_else(|| {
            Error::new(
                ErrorKind::MissingWorkloadToken,
                "The token given to .workload_access_token(..) is empty. Give a nonempty token, or remove that \
                 call to use the token of the request context.",
            )
        });
    }
    ctx.and_then(|ctx| ctx.workload_access_token().cloned())
        .filter(|token| !token.expose().is_empty())
        .ok_or_else(|| context::missing_workload_access_token(ctx.is_some()))
}

/// The name of a credential provider as the API defines it: 1 to 128 letters,
/// digits, hyphens and underscores.
fn is_provider_name(name: &str) -> bool {
    (1..=128).contains(&name.len()) && name.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
}

/// Refuses a provider name that the service would refuse. The service answers such
/// a name with an error that does not name the cause, and the call leaves no
/// CloudTrail event.
fn check_provider_name(provider: &str) -> Result<(), Error> {
    if is_provider_name(provider) {
        return Ok(());
    }
    let message = format!(
        "The credential provider name must have 1 to 128 letters, digits, hyphens and underscores, got {provider:?}"
    );
    Err(Error::new(ErrorKind::InvalidConfig, message))
}

/// The error of a failed call of `operation` for the credential provider `provider`.
///
/// Its text names what the log of an agent needs to tell failures apart: the
/// provider, the error code of the service, the HTTP status and the request ID, or
/// how the AWS SDK classifies a failure that has no code, such as `dispatch failure`.
/// The message of the service and the response stay in the source, because they can
/// hold more than that.
fn service_error<E>(operation: &str, provider: &str, error: SdkError<E, HttpResponse>) -> Error
where
    E: ProvideErrorMetadata + std::error::Error + Send + Sync + 'static,
{
    // An identifier, and not text that a response could carry in its place.
    fn identifier(value: Option<&str>) -> Option<&str> {
        value.filter(|value| {
            (1..=128).contains(&value.len())
                && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"-_.:#".contains(&byte))
        })
    }
    let cause = match identifier(error.code()) {
        Some(code) => code.to_owned(),
        // The `Display` text of an `SdkError` is one of five fixed phrases.
        None => error.to_string(),
    };
    // The status is a number, so it cannot carry text of the response.
    let status = error.raw_response().map(|response| format!("HTTP {}", response.status().as_u16()));
    let request_id = identifier(error.request_id()).map(|request_id| format!("request ID: {request_id}"));
    let mut message = format!("{operation} for provider {provider} failed: {cause}");
    let details: Vec<String> = status.into_iter().chain(request_id).collect();
    if !details.is_empty() {
        message.push_str(&format!(" ({})", details.join(", ")));
    }
    Error::new(ErrorKind::Service, message).with_source(error)
}