bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
use axum::http::{HeaderMap, HeaderName, HeaderValue, header::AUTHORIZATION};

use crate::{
    RequestContext,
    context::{
        RequestContextBuilder, WORKLOAD_ACCESS_TOKEN_HEADER as WORKLOAD_ACCESS_TOKEN, WorkloadAccessToken,
        WorkloadIdentityContexts,
    },
    tasks::AsyncTasks,
};

const SESSION_ID: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
const REQUEST_ID: &str = "x-amzn-bedrock-agentcore-runtime-request-id";
/// Read only when the canonical header is absent.
const LEGACY_WORKLOAD_ACCESS_TOKEN: &str = "workloadaccesstoken";
const OAUTH2_CALLBACK_URL: &str = "oauth2callbackurl";
const WORKLOAD_IDENTITY_CONTEXT: &str = "x-amzn-bedrock-agentcore-runtime-encrypted-workload-identity-context";
pub(crate) const WARMUP_TYPE: &str = "x-amzn-bedrock-agentcore-runtime-warmup-type";
const CUSTOM_PREFIX: &str = "x-amzn-bedrock-agentcore-runtime-custom-";

/// The first value of a header, when it is not empty and is visible ASCII text.
fn text(headers: &HeaderMap, name: &str) -> Option<String> {
    headers.get(name).and_then(|value| value.to_str().ok()).filter(|value| !value.is_empty()).map(str::to_owned)
}

pub(crate) fn request_id(headers: &HeaderMap) -> String {
    text(headers, REQUEST_ID).unwrap_or_else(|| uuid::Uuid::new_v4().to_string())
}

/// The session header has a value that is not UTF-8.
pub(crate) struct NotUtf8;

/// The session ID of the header, when it is not empty. The API sets no pattern for
/// a session ID, and AgentCore Runtime passes its bytes on, so it can hold
/// characters outside ASCII.
pub(crate) fn session_id(headers: &HeaderMap) -> Result<Option<String>, NotUtf8> {
    let Some(value) = headers.get(SESSION_ID).filter(|value| !value.is_empty()) else { return Ok(None) };
    std::str::from_utf8(value.as_bytes()).map(|id| Some(id.to_owned())).map_err(|_| NotUtf8)
}

fn is_forwarded(name: &HeaderName) -> bool {
    // `HeaderName` is always lowercase.
    name == AUTHORIZATION || name == WORKLOAD_ACCESS_TOKEN || name.as_str().starts_with(CUSTOM_PREFIX)
}

pub(crate) fn context(
    headers: &HeaderMap,
    session_id: String,
    request_id: String,
    tasks: AsyncTasks,
    workload_identity_contexts: WorkloadIdentityContexts,
) -> RequestContext {
    let mut builder: RequestContextBuilder = RequestContext::builder(session_id)
        .request_id(request_id)
        .tasks(tasks)
        .workload_identity_contexts(workload_identity_contexts);
    if let Some(token) = text(headers, WORKLOAD_ACCESS_TOKEN).or_else(|| text(headers, LEGACY_WORKLOAD_ACCESS_TOKEN)) {
        builder = builder.workload_access_token(WorkloadAccessToken::new(token));
    }
    if let Some(url) = text(headers, OAUTH2_CALLBACK_URL) {
        builder = builder.oauth2_callback_url(url);
    }
    // The session keeps the context from here on, also when this invocation makes no AWS call.
    if let Some(context) = text(headers, WORKLOAD_IDENTITY_CONTEXT) {
        builder = builder.workload_identity_context(context);
    }
    // The encrypted workload identity context is for the credentials provider only.
    for (name, value) in headers.iter().filter(|(name, _)| *name != WORKLOAD_IDENTITY_CONTEXT) {
        builder = builder.request_header(name.clone(), value.clone());
    }
    for name in headers.keys().filter(|name| is_forwarded(name)) {
        // Empty values are dropped. Repeated values become one value, as in the TypeScript SDK.
        let values: Vec<&[u8]> =
            headers.get_all(name).iter().map(HeaderValue::as_bytes).filter(|v| !v.is_empty()).collect();
        if let Ok(value) = HeaderValue::from_bytes(&values.join(&b", "[..]))
            && !values.is_empty()
        {
            builder = builder.header(name.clone(), value);
        }
    }
    builder.build()
}