bedrock_agentcore/identity/oauth2.rs
1use std::{
2 collections::HashMap,
3 fmt,
4 future::Future,
5 pin::Pin,
6 sync::Arc,
7 task::{Context, Poll},
8 time::Duration,
9};
10
11use aws_sdk_bedrockagentcore::{
12 Client, operation::get_resource_oauth2_token::GetResourceOauth2TokenOutput, types::Oauth2FlowType,
13};
14
15use futures_core::Stream;
16use tokio::sync::mpsc;
17
18use super::{check_provider_name, poller, resolve_workload_access_token, secret, service_error};
19use crate::{
20 Error, ErrorKind,
21 context::{self, WorkloadAccessToken},
22};
23
24type BoxError = Box<dyn std::error::Error + Send + Sync>;
25type OnAuthUrl =
26 Arc<dyn Fn(AuthorizationUrl) -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>> + Send + Sync>;
27
28secret! {
29 /// An OAuth2 access token from a credential provider of AgentCore Identity.
30 AccessToken
31}
32
33secret! {
34 /// The URL where a user gives consent to an OAuth2 credential provider.
35 ///
36 /// Whoever opens the URL can give the consent, so it goes to the user who started
37 /// the request and nowhere else.
38 AuthorizationUrl
39}
40
41/// How AgentCore Identity obtains an OAuth2 token.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[non_exhaustive]
44pub enum AuthFlow {
45 /// Machine to machine: the client credentials of the provider. The token arrives
46 /// with the first response.
47 M2m,
48 /// On behalf of a user, who gives consent at an authorization URL unless
49 /// AgentCore Identity already holds a token for that user.
50 UserFederation,
51 /// An exchange of the token of the user for a token of the provider. The token
52 /// arrives with the first response.
53 OnBehalfOfTokenExchange,
54}
55
56impl From<AuthFlow> for Oauth2FlowType {
57 fn from(flow: AuthFlow) -> Self {
58 match flow {
59 AuthFlow::M2m => Self::M2M,
60 AuthFlow::UserFederation => Self::UserFederation,
61 AuthFlow::OnBehalfOfTokenExchange => Self::OnBehalfOfTokenExchange,
62 }
63 }
64}
65
66/// A request for an OAuth2 access token of one credential provider. Create one with
67/// [`IdentityClient::oauth2_token`](super::IdentityClient::oauth2_token).
68///
69/// # Consent of the user
70///
71/// With [`AuthFlow::UserFederation`], AgentCore Identity can answer with an
72/// authorization URL instead of a token. [`send`](Self::send) then:
73///
74/// 1. Calls the function given to [`on_auth_url`](Self::on_auth_url) once with the
75/// URL and waits for it. Deliver the URL to the user who started the request,
76/// through the session of that user in your application.
77/// 2. Asks for the token again every 5 seconds until it arrives. No new request
78/// starts after 600 seconds, counted from the end of step 1, and `send` then fails
79/// with [`ErrorKind::AuthorizationTimedOut`], at once when the next request would
80/// start later than that. Change the two times with
81/// [`poll_interval`](Self::poll_interval) and [`timeout`](Self::timeout).
82///
83/// Dropping the future of `send` stops this at any point. The requests that follow the
84/// first one repeat its options, except that they never force authentication.
85///
86/// Behind AgentCore Runtime the agent does not learn that its caller has left, so
87/// the requests go on until the token arrives or the time of step 2 has passed. Set
88/// a [`timeout`](Self::timeout) that fits how long your callers wait.
89///
90/// [`into_stream`](Self::into_stream) gives the URL and the token as the items of a
91/// stream, for an agent that sends both to its caller.
92///
93/// Your application also needs the callback endpoint that completes the consent. See
94/// [OAuth2 authorization URL session binding](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html).
95///
96/// ```no_run
97/// use bedrock_agentcore::identity::{AuthFlow, AuthorizationUrl, IdentityClient};
98///
99/// async fn deliver(url: AuthorizationUrl) -> Result<(), std::io::Error> {
100/// // Send `url.expose()` to the user who started the request, and to nobody else.
101/// # let _ = url;
102/// Ok(())
103/// }
104///
105/// async fn read_calendar(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
106/// let token = identity
107/// .oauth2_token("calendar", AuthFlow::UserFederation)
108/// .scopes(["calendar.read"])
109/// .on_auth_url(deliver)
110/// .send()
111/// .await?;
112/// # let _ = token;
113/// Ok(())
114/// }
115/// ```
116#[derive(Clone)]
117#[must_use = "the request is made when `send` is called and awaited"]
118pub struct Oauth2TokenBuilder {
119 client: Client,
120 provider: String,
121 flow: AuthFlow,
122 workload_access_token: Option<WorkloadAccessToken>,
123 scopes: Vec<String>,
124 resources: Option<Vec<String>>,
125 audiences: Option<Vec<String>>,
126 callback_url: Option<String>,
127 force_authentication: Option<bool>,
128 custom_state: Option<String>,
129 custom_parameters: Option<HashMap<String, String>>,
130 on_auth_url: Option<OnAuthUrl>,
131 poll_interval: Duration,
132 timeout: Duration,
133}
134
135fn strings(values: impl IntoIterator<Item = impl Into<String>>) -> Vec<String> {
136 values.into_iter().map(Into::into).collect()
137}
138
139impl Oauth2TokenBuilder {
140 pub(super) fn new(client: Client, provider: String, flow: AuthFlow) -> Self {
141 Self {
142 client,
143 provider,
144 flow,
145 workload_access_token: None,
146 scopes: Vec::new(),
147 resources: None,
148 audiences: None,
149 callback_url: None,
150 force_authentication: None,
151 custom_state: None,
152 custom_parameters: None,
153 on_auth_url: None,
154 poll_interval: poller::INTERVAL,
155 timeout: poller::BUDGET,
156 }
157 }
158
159 /// Sets the workload access token of this request.
160 ///
161 /// Without this setter the request uses the token of the ambient request context.
162 /// A token set here is used as given: when it is empty the request fails, even
163 /// inside a context that has a token.
164 pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
165 self.workload_access_token = Some(token);
166 self
167 }
168
169 /// Sets the scopes of the token, replacing earlier ones. The default is no scope.
170 pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
171 self.scopes = strings(scopes);
172 self
173 }
174
175 /// Sets the resource indicators of the token, replacing earlier ones. Without
176 /// this setter the request has no `resources` member. An empty list is sent as an
177 /// empty list.
178 pub fn resources(mut self, resources: impl IntoIterator<Item = impl Into<String>>) -> Self {
179 self.resources = Some(strings(resources));
180 self
181 }
182
183 /// Sets the audiences of the token, replacing earlier ones. Without this setter
184 /// the request has no `audiences` member. An empty list is sent as an empty list.
185 pub fn audiences(mut self, audiences: impl IntoIterator<Item = impl Into<String>>) -> Self {
186 self.audiences = Some(strings(audiences));
187 self
188 }
189
190 /// Sets the URL that the user returns to after giving consent.
191 ///
192 /// Without this setter the request uses the OAuth2 callback URL of the ambient
193 /// request context, when it has one.
194 pub fn callback_url(mut self, url: impl Into<String>) -> Self {
195 self.callback_url = Some(url.into());
196 self
197 }
198
199 /// Sets whether the user must give consent again even when AgentCore Identity
200 /// holds a token. It applies to the first request only.
201 pub fn force_authentication(mut self, force: bool) -> Self {
202 self.force_authentication = Some(force);
203 self
204 }
205
206 /// Sets an opaque value that the callback endpoint of the application receives
207 /// back, to check that a consent belongs to the request that started it.
208 pub fn custom_state(mut self, state: impl Into<String>) -> Self {
209 self.custom_state = Some(state.into());
210 self
211 }
212
213 /// Sets additional parameters for the authorization endpoint of the provider,
214 /// replacing earlier ones.
215 pub fn custom_parameters(
216 mut self,
217 parameters: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
218 ) -> Self {
219 self.custom_parameters =
220 Some(parameters.into_iter().map(|(name, value)| (name.into(), value.into())).collect());
221 self
222 }
223
224 /// Sets the function that receives the authorization URL when the user has to
225 /// give consent.
226 ///
227 /// It is called at most once per `send`, and `send` waits for it before it asks
228 /// for the token again. When it returns an error, `send` fails with
229 /// [`ErrorKind::AuthorizationCallbackFailed`] and makes no further request. The
230 /// error is the [`source`](std::error::Error::source) of that failure.
231 ///
232 /// Without this setter `send` still waits for the consent, which then has to be
233 /// started in another way.
234 pub fn on_auth_url<F, Fut, E>(mut self, on_auth_url: F) -> Self
235 where
236 F: Fn(AuthorizationUrl) -> Fut + Send + Sync + 'static,
237 Fut: Future<Output = Result<(), E>> + Send + 'static,
238 E: Into<BoxError>,
239 {
240 self.on_auth_url = Some(Arc::new(move |url| {
241 let notified = on_auth_url(url);
242 Box::pin(async move { notified.await.map_err(Into::into) })
243 }));
244 self
245 }
246
247 /// Sets the wait before each request that asks for the token again, while the
248 /// user gives consent. The default is 5 seconds. The interval must be greater
249 /// than zero.
250 pub fn poll_interval(mut self, interval: Duration) -> Self {
251 self.poll_interval = interval;
252 self
253 }
254
255 /// Sets how long new requests for the token are started, while the user gives
256 /// consent. The default is 600 seconds. The time counts from the delivery of the
257 /// authorization URL.
258 pub fn timeout(mut self, timeout: Duration) -> Self {
259 self.timeout = timeout;
260 self
261 }
262
263 /// Requests the token as [`send`](Self::send) does, and returns its steps as a
264 /// stream: [`Oauth2Event::AuthorizationUrl`] when the user has to give consent,
265 /// then [`Oauth2Event::Token`]. An error is the last item. A token that arrives
266 /// with the first response is the only item.
267 ///
268 /// The stream replaces a function given to [`on_auth_url`](Self::on_auth_url).
269 /// The request runs while the stream is polled, and dropping the stream stops it.
270 /// Map the items to what the caller of the agent receives, and give the result to
271 /// `runtime::Response::stream`:
272 ///
273 /// ```no_run
274 /// use bedrock_agentcore::identity::{AuthFlow, IdentityClient, Oauth2Event};
275 /// use futures_util::{Stream, StreamExt};
276 /// use serde_json::{Value, json};
277 ///
278 /// fn consent(identity: &IdentityClient) -> impl Stream<Item = Result<Value, bedrock_agentcore::Error>> {
279 /// let events = identity.oauth2_token("calendar", AuthFlow::UserFederation).into_stream();
280 /// events.map(|event| {
281 /// event.map(|event| match event {
282 /// // The URL goes to the caller that started the request, and to nobody else.
283 /// Oauth2Event::AuthorizationUrl(url) => json!({ "authorization_url": url.expose() }),
284 /// // Give `token.expose()` to the client of the service that needs it.
285 /// Oauth2Event::Token(_token) => json!({ "authorized": true }),
286 /// })
287 /// })
288 /// }
289 /// ```
290 pub fn into_stream(self) -> impl Stream<Item = Result<Oauth2Event, Error>> + Send + 'static {
291 let (urls, received) = mpsc::channel(1);
292 let request = self.on_auth_url(move |url| {
293 let urls = urls.clone();
294 async move { urls.send(url).await.map_err(|_| "the stream of the request was dropped") }
295 });
296 Events { urls: received, token: Some(Box::pin(request.send())), outcome: None }
297 }
298
299 /// Requests the token with `GetResourceOauth2Token`.
300 ///
301 /// The workload access token and the callback URL are read once, when the returned
302 /// future is first polled. All requests of this `send` use those values.
303 ///
304 /// A token in the first response is returned at once, with every flow. See
305 /// [the type documentation](Self#consent-of-the-user) for a response with an
306 /// authorization URL.
307 ///
308 /// # Errors
309 ///
310 /// - [`ErrorKind::InvalidConfig`] when the provider name is not 1 to 128 letters,
311 /// digits, hyphens and underscores, or the poll interval is zero. No request
312 /// is made.
313 /// - [`ErrorKind::MissingWorkloadToken`] when there is no nonempty workload access
314 /// token. No request is made.
315 /// - [`ErrorKind::Service`] when a call fails. Its text has the provider, the
316 /// error code of the service, the HTTP status and the request ID, and its
317 /// source is the `SdkError` of the generated operation.
318 /// - [`ErrorKind::NoTokenOrAuthUrl`] when the first response has neither a token
319 /// nor an authorization URL.
320 /// - [`ErrorKind::AuthorizationCallbackFailed`] when the function given to
321 /// [`on_auth_url`](Self::on_auth_url) fails.
322 /// - [`ErrorKind::AuthorizationTimedOut`] when no token arrives in time.
323 pub async fn send(self) -> Result<AccessToken, Error> {
324 check_provider_name(&self.provider)?;
325 if self.poll_interval.is_zero() {
326 return Err(Error::new(ErrorKind::InvalidConfig, "the poll interval must be greater than zero"));
327 }
328 let ctx = context::current();
329 let workload_access_token = resolve_workload_access_token(self.workload_access_token, ctx.as_ref())?;
330 let callback_url =
331 self.callback_url.or_else(|| ctx.and_then(|ctx| ctx.oauth2_callback_url().map(str::to_owned)));
332 let request = Request {
333 client: self.client,
334 provider: self.provider,
335 flow: self.flow,
336 workload_access_token,
337 scopes: self.scopes,
338 resources: self.resources,
339 audiences: self.audiences,
340 callback_url,
341 custom_state: self.custom_state,
342 custom_parameters: self.custom_parameters,
343 };
344
345 let first = request.fetch(None, self.force_authentication).await?;
346 let session_uri = first.session_uri.clone();
347 if let Some(token) = access_token(first.access_token) {
348 return Ok(token);
349 }
350 let Some(url) = first.authorization_url.filter(|url| !url.is_empty()) else {
351 return Err(Error::new(
352 ErrorKind::NoTokenOrAuthUrl,
353 "Identity service did not return a token or authorization URL",
354 ));
355 };
356 if let Some(on_auth_url) = self.on_auth_url {
357 on_auth_url(AuthorizationUrl::new(url)).await.map_err(|error| {
358 Error::new(ErrorKind::AuthorizationCallbackFailed, "Failed to deliver the authorization URL")
359 .with_source(error)
360 })?;
361 }
362 poller::poll(self.poll_interval, self.timeout, || async {
363 Ok(access_token(request.fetch(session_uri.as_deref(), None).await?.access_token))
364 })
365 .await
366 }
367}
368
369/// One step of [`Oauth2TokenBuilder::into_stream`].
370#[derive(Debug)]
371pub enum Oauth2Event {
372 /// The user has to give consent at this URL. The token follows as the next item.
373 AuthorizationUrl(AuthorizationUrl),
374 /// The token. It is the last item.
375 Token(AccessToken),
376}
377
378type Sending = Pin<Box<dyn Future<Output = Result<AccessToken, Error>> + Send>>;
379
380/// The stream of [`Oauth2TokenBuilder::into_stream`].
381struct Events {
382 urls: mpsc::Receiver<AuthorizationUrl>,
383 /// The request. `None` when it has completed.
384 token: Option<Sending>,
385 /// The outcome of the request, until the stream has yielded it.
386 outcome: Option<Result<AccessToken, Error>>,
387}
388
389impl Stream for Events {
390 type Item = Result<Oauth2Event, Error>;
391
392 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
393 // The request is polled first: it puts the URL in the channel. A request
394 // that completes in the same poll is not polled again: its outcome is kept
395 // until the URL has been yielded.
396 if let Some(token) = self.token.as_mut()
397 && let Poll::Ready(outcome) = token.as_mut().poll(cx)
398 {
399 self.token = None;
400 self.outcome = Some(outcome);
401 }
402 if let Ok(url) = self.urls.try_recv() {
403 return Poll::Ready(Some(Ok(Oauth2Event::AuthorizationUrl(url))));
404 }
405 match self.outcome.take() {
406 Some(outcome) => Poll::Ready(Some(outcome.map(Oauth2Event::Token))),
407 None if self.token.is_some() => Poll::Pending,
408 None => Poll::Ready(None),
409 }
410 }
411}
412
413fn access_token(token: Option<String>) -> Option<AccessToken> {
414 token.filter(|token| !token.is_empty()).map(AccessToken::new)
415}
416
417/// The resolved options that every request of one `send` repeats.
418struct Request {
419 client: Client,
420 provider: String,
421 flow: AuthFlow,
422 workload_access_token: WorkloadAccessToken,
423 scopes: Vec<String>,
424 resources: Option<Vec<String>>,
425 audiences: Option<Vec<String>>,
426 callback_url: Option<String>,
427 custom_state: Option<String>,
428 custom_parameters: Option<HashMap<String, String>>,
429}
430
431impl Request {
432 /// One call. The first has no session URI and the caller's choice of forced
433 /// authentication. The following ones have the session URI of the first response
434 /// and leave `forceAuthentication` out.
435 async fn fetch(
436 &self,
437 session_uri: Option<&str>,
438 force_authentication: Option<bool>,
439 ) -> Result<GetResourceOauth2TokenOutput, Error> {
440 self.client
441 .get_resource_oauth2_token()
442 .resource_credential_provider_name(&self.provider)
443 .workload_identity_token(self.workload_access_token.expose())
444 .oauth2_flow(self.flow.into())
445 .set_scopes(Some(self.scopes.clone()))
446 .set_resources(self.resources.clone())
447 .set_audiences(self.audiences.clone())
448 .set_resource_oauth2_return_url(self.callback_url.clone())
449 .set_custom_state(self.custom_state.clone())
450 .set_custom_parameters(self.custom_parameters.clone())
451 .set_session_uri(session_uri.map(str::to_owned))
452 .set_force_authentication(force_authentication)
453 .send()
454 .await
455 .map_err(|error| service_error("GetResourceOauth2Token", &self.provider, error))
456 }
457}
458
459impl fmt::Debug for Oauth2TokenBuilder {
460 /// Shows the sensitive options only as set or not set.
461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462 f.debug_struct("Oauth2TokenBuilder")
463 .field("provider", &self.provider)
464 .field("flow", &self.flow)
465 .field("scopes", &self.scopes)
466 .field("resources", &self.resources)
467 .field("audiences", &self.audiences)
468 .field("force_authentication", &self.force_authentication)
469 .field("workload_access_token", &self.workload_access_token.is_some())
470 .field("callback_url", &self.callback_url.is_some())
471 .field("custom_state", &self.custom_state.is_some())
472 .field("custom_parameters", &self.custom_parameters.is_some())
473 .field("on_auth_url", &self.on_auth_url.is_some())
474 .field("poll_interval", &self.poll_interval)
475 .field("timeout", &self.timeout)
476 .finish_non_exhaustive()
477 }
478}