Skip to main content

bedrock_agentcore/identity/
mod.rs

1//! Credentials from AgentCore Identity for the services an agent calls.
2//!
3//! An [`IdentityClient`] asks AgentCore Identity for a credential of a credential
4//! provider. Each request names the provider and carries the workload access token of
5//! the invocation, which says on whose behalf the agent acts.
6//!
7//! ```no_run
8//! use bedrock_agentcore::identity::{AuthFlow, IdentityClient};
9//!
10//! async fn call_orders(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
11//!     let key = identity.api_key("orders-api").send().await?;
12//!     let token = identity.oauth2_token("orders", AuthFlow::M2m).scopes(["orders/read"]).send().await?;
13//!     // Pass `key.expose()` or `token.expose()` to the orders client where the
14//!     // request is made.
15//!     # let _ = (key, token);
16//!     Ok(())
17//! }
18//! ```
19//!
20//! [`Oauth2TokenBuilder`] describes the flow in which a user gives consent.
21//!
22//! # One client for all requests
23//!
24//! Create the client once at startup and share it, or clone it: clones use the same
25//! connection pool. The client holds no token. Each operation reads the workload
26//! access token when it is sent:
27//!
28//! 1. The token given to the operation with `.workload_access_token(..)`.
29//! 2. Otherwise the token of the ambient [request context](crate::context).
30//!
31//! Inside a handler of the runtime server the second case needs no code. The ambient
32//! context also covers the items of a streamed response. A task started with
33//! `tokio::spawn` does not inherit it: wrap its future in
34//! [`context::scope`], or give the operation a token. Outside
35//! AgentCore Runtime, for example in local development, give the operation a token.
36//!
37//! An operation without a usable token fails with
38//! [`ErrorKind::MissingWorkloadToken`] before
39//! any request is made. The text of the error names the cause.
40//!
41//! # When an invocation carries a token
42//!
43//! AgentCore Runtime sends a workload access token only when the caller names a
44//! user: a `runtimeUserId` with IAM authorization, which needs the
45//! `bedrock-agentcore:InvokeAgentRuntimeForUser` permission, or a JWT. A call of
46//! `InvokeAgentRuntime` with IAM authorization and no user ID reaches the agent
47//! without a token.
48//!
49//! A local call has no token either. The workload identity of a deployed agent
50//! runtime belongs to the service and gives no token to a caller. Create a workload
51//! identity for local tests once, get a token for it, and send the token in the
52//! `X-Amz-Bedrock-AgentCore-Identity-WAT` header:
53//!
54//! ```text
55//! aws bedrock-agentcore-control create-workload-identity --name my-agent-local
56//! TOKEN=$(aws bedrock-agentcore get-workload-access-token --workload-name my-agent-local \
57//!   --query workloadAccessToken --output text)
58//! curl -s localhost:8080/invocations \
59//!   -H 'X-Amzn-Bedrock-AgentCore-Runtime-Session-Id: local-session' \
60//!   -H "X-Amz-Bedrock-AgentCore-Identity-WAT: $TOKEN" \
61//!   -d '{}'
62//! ```
63//!
64//! For a flow that acts for a user, get the token with
65//! `get-workload-access-token-for-user-id`.
66//!
67//! # Calling other AgentCore services for the same user
68//!
69//! [`IdentityClient::data_plane`] is the generated AgentCore client. By default,
70//! its `Invoke*` operations carry the workload access token of the current
71//! invocation. An agent that invokes another agent, or a tool such as Code
72//! Interpreter, then does so for the same user:
73//!
74//! ```no_run
75//! # use bedrock_agentcore::identity::IdentityClient;
76//! # async fn example(identity: &IdentityClient) -> Result<(), Box<dyn std::error::Error>> {
77//! let reply = identity
78//!     .data_plane()
79//!     .invoke_agent_runtime()
80//!     .agent_runtime_arn("arn:aws:bedrock-agentcore:us-west-2:111122223333:runtime/other-agent")
81//!     .payload(r#"{"prompt": "hello"}"#.as_bytes().into())
82//!     .send()
83//!     .await?;
84//! # let _ = reply;
85//! # Ok(())
86//! # }
87//! ```
88//!
89//! See [`WatPropagation`] for the rule and for a client that you build yourself.
90//!
91//! # Secrets
92//!
93//! Credentials are returned in [`ApiKey`] and [`AccessToken`], whose `Debug` output never
94//! contains the value. Read the value with `expose()` where it is used, and keep it
95//! out of logs. See [`Error`] for the source of a failed operation.
96
97use std::fmt;
98
99use aws_sdk_bedrockagentcore::{
100    Client,
101    config::http::HttpResponse,
102    error::{ProvideErrorMetadata, SdkError},
103    operation::RequestId,
104};
105use aws_types::SdkConfig;
106
107use crate::{
108    Error, ErrorKind, RequestContext,
109    context::{self, WorkloadAccessToken},
110};
111
112mod api_key;
113mod oauth2;
114mod poller;
115mod propagation;
116#[cfg(test)]
117mod tests;
118mod workload_identity;
119
120pub use api_key::{ApiKey, ApiKeyBuilder};
121pub use oauth2::{AccessToken, AuthFlow, AuthorizationUrl, Oauth2Event, Oauth2TokenBuilder};
122pub use propagation::WatPropagation;
123pub use workload_identity::WorkloadIdentityCredentials;
124
125/// Defines a credential type that follows [`WorkloadAccessToken`]: an owned string
126/// that `Debug` never prints.
127macro_rules! secret {
128    ($(#[$attribute:meta])* $name:ident) => {
129        $(#[$attribute])*
130        ///
131        /// Its `Debug` output never contains the value. Read the value with
132        /// [`expose`](Self::expose).
133        #[derive(Clone, PartialEq, Eq)]
134        pub struct $name(String);
135
136        impl $name {
137            /// Wraps a value.
138            pub fn new(value: impl Into<String>) -> Self {
139                Self(value.into())
140            }
141
142            /// The value. Keep it out of logs.
143            pub fn expose(&self) -> &str {
144                &self.0
145            }
146        }
147
148        impl std::fmt::Debug for $name {
149            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150                f.write_str("*** Sensitive Data Redacted ***")
151            }
152        }
153    };
154}
155use secret;
156
157/// A client of AgentCore Identity.
158///
159/// It is cheap to clone, and clones share one connection pool. See the
160/// [module documentation](self) for how an operation finds its workload access token.
161#[derive(Clone)]
162pub struct IdentityClient {
163    client: Client,
164}
165
166impl IdentityClient {
167    /// Creates a client from the AWS configuration of the application.
168    ///
169    /// Region, credentials, retries, timeouts and endpoint come from `config`, for the
170    /// requests of this client and for [`data_plane`](Self::data_plane). Load it
171    /// once at startup, for example with
172    /// `aws_config::load_defaults(BehaviorVersion::latest()).await`.
173    ///
174    /// A configuration without a region is accepted here. Each operation then fails
175    /// with [`ErrorKind::Service`] when it is sent.
176    ///
177    /// # Panics
178    ///
179    /// As `aws_sdk_bedrockagentcore::Client::new` does: when `config` has no behavior
180    /// version, no HTTP client, or no async sleep implementation while retries or
181    /// timeouts are enabled. `aws_config::load_defaults` sets all three.
182    pub fn new(config: &SdkConfig) -> Self {
183        let config = aws_sdk_bedrockagentcore::config::Builder::from(config).interceptor(WatPropagation::new());
184        Self { client: Client::from_conf(config.build()) }
185    }
186
187    /// Creates a client that sends its requests through `client`, for example a
188    /// client with a custom configuration or a mocked client in a test.
189    ///
190    /// The configuration of `client` is kept, with its interceptors, runtime plugins,
191    /// credentials and endpoint, and [`WatPropagation`] is added to it.
192    ///
193    /// # Connection pool
194    ///
195    /// Adding the interceptor builds a new generated client from the configuration of
196    /// `client`. An HTTP client that was set on that configuration is shared, so both
197    /// clients use its connection pool. Without one, the new client gets a default
198    /// HTTP client of its own, and with it a new, empty pool. To keep the connections
199    /// of such a client, add [`WatPropagation`] when you build it: a client that
200    /// already has the interceptor is used as it is.
201    pub fn from_client(client: Client) -> Self {
202        Self { client: WatPropagation::install(client) }
203    }
204
205    /// The generated AgentCore client of this `IdentityClient`, for the operations
206    /// that this crate does not wrap.
207    ///
208    /// By default, its `Invoke*` operations carry the current invocation's workload
209    /// access token. See [`WatPropagation`] to override the token for one call.
210    pub fn data_plane(&self) -> &Client {
211        &self.client
212    }
213
214    /// Starts a request for the API key of the credential provider `provider`.
215    pub fn api_key(&self, provider: impl Into<String>) -> ApiKeyBuilder {
216        ApiKeyBuilder::new(self.client.clone(), provider.into())
217    }
218
219    /// Starts a request for an OAuth2 access token of the credential provider
220    /// `provider`, obtained with `flow`.
221    pub fn oauth2_token(&self, provider: impl Into<String>, flow: AuthFlow) -> Oauth2TokenBuilder {
222        Oauth2TokenBuilder::new(self.client.clone(), provider.into(), flow)
223    }
224}
225
226impl fmt::Debug for IdentityClient {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.debug_struct("IdentityClient").finish_non_exhaustive()
229    }
230}
231
232/// The workload access token of one operation: `explicit` when the operation was given
233/// one, otherwise the token of `ctx`.
234///
235/// An explicit token is not replaced when it is empty. The operation fails instead,
236/// as in the TypeScript SDK.
237fn resolve_workload_access_token(
238    explicit: Option<WorkloadAccessToken>,
239    ctx: Option<&RequestContext>,
240) -> Result<WorkloadAccessToken, Error> {
241    if let Some(token) = explicit {
242        return Some(token).filter(|token| !token.expose().is_empty()).ok_or_else(|| {
243            Error::new(
244                ErrorKind::MissingWorkloadToken,
245                "The token given to .workload_access_token(..) is empty. Give a nonempty token, or remove that \
246                 call to use the token of the request context.",
247            )
248        });
249    }
250    ctx.and_then(|ctx| ctx.workload_access_token().cloned())
251        .filter(|token| !token.expose().is_empty())
252        .ok_or_else(|| context::missing_workload_access_token(ctx.is_some()))
253}
254
255/// The name of a credential provider as the API defines it: 1 to 128 letters,
256/// digits, hyphens and underscores.
257fn is_provider_name(name: &str) -> bool {
258    (1..=128).contains(&name.len()) && name.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
259}
260
261/// Refuses a provider name that the service would refuse. The service answers such
262/// a name with an error that does not name the cause, and the call leaves no
263/// CloudTrail event.
264fn check_provider_name(provider: &str) -> Result<(), Error> {
265    if is_provider_name(provider) {
266        return Ok(());
267    }
268    let message = format!(
269        "The credential provider name must have 1 to 128 letters, digits, hyphens and underscores, got {provider:?}"
270    );
271    Err(Error::new(ErrorKind::InvalidConfig, message))
272}
273
274/// The error of a failed call of `operation` for the credential provider `provider`.
275///
276/// Its text names what the log of an agent needs to tell failures apart: the
277/// provider, the error code of the service, the HTTP status and the request ID, or
278/// how the AWS SDK classifies a failure that has no code, such as `dispatch failure`.
279/// The message of the service and the response stay in the source, because they can
280/// hold more than that.
281fn service_error<E>(operation: &str, provider: &str, error: SdkError<E, HttpResponse>) -> Error
282where
283    E: ProvideErrorMetadata + std::error::Error + Send + Sync + 'static,
284{
285    // An identifier, and not text that a response could carry in its place.
286    fn identifier(value: Option<&str>) -> Option<&str> {
287        value.filter(|value| {
288            (1..=128).contains(&value.len())
289                && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || b"-_.:#".contains(&byte))
290        })
291    }
292    let cause = match identifier(error.code()) {
293        Some(code) => code.to_owned(),
294        // The `Display` text of an `SdkError` is one of five fixed phrases.
295        None => error.to_string(),
296    };
297    // The status is a number, so it cannot carry text of the response.
298    let status = error.raw_response().map(|response| format!("HTTP {}", response.status().as_u16()));
299    let request_id = identifier(error.request_id()).map(|request_id| format!("request ID: {request_id}"));
300    let mut message = format!("{operation} for provider {provider} failed: {cause}");
301    let details: Vec<String> = status.into_iter().chain(request_id).collect();
302    if !details.is_empty() {
303        message.push_str(&format!(" ({})", details.join(", ")));
304    }
305    Error::new(ErrorKind::Service, message).with_source(error)
306}