bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use std::{
    collections::HashMap,
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use aws_sdk_bedrockagentcore::{
    Client, operation::get_resource_oauth2_token::GetResourceOauth2TokenOutput, types::Oauth2FlowType,
};

use futures_core::Stream;
use tokio::sync::mpsc;

use super::{check_provider_name, poller, resolve_workload_access_token, secret, service_error};
use crate::{
    Error, ErrorKind,
    context::{self, WorkloadAccessToken},
};

type BoxError = Box<dyn std::error::Error + Send + Sync>;
type OnAuthUrl =
    Arc<dyn Fn(AuthorizationUrl) -> Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>> + Send + Sync>;

secret! {
    /// An OAuth2 access token from a credential provider of AgentCore Identity.
    AccessToken
}

secret! {
    /// The URL where a user gives consent to an OAuth2 credential provider.
    ///
    /// Whoever opens the URL can give the consent, so it goes to the user who started
    /// the request and nowhere else.
    AuthorizationUrl
}

/// How AgentCore Identity obtains an OAuth2 token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthFlow {
    /// Machine to machine: the client credentials of the provider. The token arrives
    /// with the first response.
    M2m,
    /// On behalf of a user, who gives consent at an authorization URL unless
    /// AgentCore Identity already holds a token for that user.
    UserFederation,
    /// An exchange of the token of the user for a token of the provider. The token
    /// arrives with the first response.
    OnBehalfOfTokenExchange,
}

impl From<AuthFlow> for Oauth2FlowType {
    fn from(flow: AuthFlow) -> Self {
        match flow {
            AuthFlow::M2m => Self::M2M,
            AuthFlow::UserFederation => Self::UserFederation,
            AuthFlow::OnBehalfOfTokenExchange => Self::OnBehalfOfTokenExchange,
        }
    }
}

/// A request for an OAuth2 access token of one credential provider. Create one with
/// [`IdentityClient::oauth2_token`](super::IdentityClient::oauth2_token).
///
/// # Consent of the user
///
/// With [`AuthFlow::UserFederation`], AgentCore Identity can answer with an
/// authorization URL instead of a token. [`send`](Self::send) then:
///
/// 1. Calls the function given to [`on_auth_url`](Self::on_auth_url) once with the
///    URL and waits for it. Deliver the URL to the user who started the request,
///    through the session of that user in your application.
/// 2. Asks for the token again every 5 seconds until it arrives. No new request
///    starts after 600 seconds, counted from the end of step 1, and `send` then fails
///    with [`ErrorKind::AuthorizationTimedOut`], at once when the next request would
///    start later than that. Change the two times with
///    [`poll_interval`](Self::poll_interval) and [`timeout`](Self::timeout).
///
/// Dropping the future of `send` stops this at any point. The requests that follow the
/// first one repeat its options, except that they never force authentication.
///
/// Behind AgentCore Runtime the agent does not learn that its caller has left, so
/// the requests go on until the token arrives or the time of step 2 has passed. Set
/// a [`timeout`](Self::timeout) that fits how long your callers wait.
///
/// [`into_stream`](Self::into_stream) gives the URL and the token as the items of a
/// stream, for an agent that sends both to its caller.
///
/// Your application also needs the callback endpoint that completes the consent. See
/// [OAuth2 authorization URL session binding](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/oauth2-authorization-url-session-binding.html).
///
/// ```no_run
/// use bedrock_agentcore::identity::{AuthFlow, AuthorizationUrl, IdentityClient};
///
/// async fn deliver(url: AuthorizationUrl) -> Result<(), std::io::Error> {
///     // Send `url.expose()` to the user who started the request, and to nobody else.
///     # let _ = url;
///     Ok(())
/// }
///
/// async fn read_calendar(identity: &IdentityClient) -> Result<(), bedrock_agentcore::Error> {
///     let token = identity
///         .oauth2_token("calendar", AuthFlow::UserFederation)
///         .scopes(["calendar.read"])
///         .on_auth_url(deliver)
///         .send()
///         .await?;
///     # let _ = token;
///     Ok(())
/// }
/// ```
#[derive(Clone)]
#[must_use = "the request is made when `send` is called and awaited"]
pub struct Oauth2TokenBuilder {
    client: Client,
    provider: String,
    flow: AuthFlow,
    workload_access_token: Option<WorkloadAccessToken>,
    scopes: Vec<String>,
    resources: Option<Vec<String>>,
    audiences: Option<Vec<String>>,
    callback_url: Option<String>,
    force_authentication: Option<bool>,
    custom_state: Option<String>,
    custom_parameters: Option<HashMap<String, String>>,
    on_auth_url: Option<OnAuthUrl>,
    poll_interval: Duration,
    timeout: Duration,
}

fn strings(values: impl IntoIterator<Item = impl Into<String>>) -> Vec<String> {
    values.into_iter().map(Into::into).collect()
}

impl Oauth2TokenBuilder {
    pub(super) fn new(client: Client, provider: String, flow: AuthFlow) -> Self {
        Self {
            client,
            provider,
            flow,
            workload_access_token: None,
            scopes: Vec::new(),
            resources: None,
            audiences: None,
            callback_url: None,
            force_authentication: None,
            custom_state: None,
            custom_parameters: None,
            on_auth_url: None,
            poll_interval: poller::INTERVAL,
            timeout: poller::BUDGET,
        }
    }

    /// Sets the workload access token of this request.
    ///
    /// Without this setter the request uses the token of the ambient request context.
    /// A token set here is used as given: when it is empty the request fails, even
    /// inside a context that has a token.
    pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
        self.workload_access_token = Some(token);
        self
    }

    /// Sets the scopes of the token, replacing earlier ones. The default is no scope.
    pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.scopes = strings(scopes);
        self
    }

    /// Sets the resource indicators of the token, replacing earlier ones. Without
    /// this setter the request has no `resources` member. An empty list is sent as an
    /// empty list.
    pub fn resources(mut self, resources: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.resources = Some(strings(resources));
        self
    }

    /// Sets the audiences of the token, replacing earlier ones. Without this setter
    /// the request has no `audiences` member. An empty list is sent as an empty list.
    pub fn audiences(mut self, audiences: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.audiences = Some(strings(audiences));
        self
    }

    /// Sets the URL that the user returns to after giving consent.
    ///
    /// Without this setter the request uses the OAuth2 callback URL of the ambient
    /// request context, when it has one.
    pub fn callback_url(mut self, url: impl Into<String>) -> Self {
        self.callback_url = Some(url.into());
        self
    }

    /// Sets whether the user must give consent again even when AgentCore Identity
    /// holds a token. It applies to the first request only.
    pub fn force_authentication(mut self, force: bool) -> Self {
        self.force_authentication = Some(force);
        self
    }

    /// Sets an opaque value that the callback endpoint of the application receives
    /// back, to check that a consent belongs to the request that started it.
    pub fn custom_state(mut self, state: impl Into<String>) -> Self {
        self.custom_state = Some(state.into());
        self
    }

    /// Sets additional parameters for the authorization endpoint of the provider,
    /// replacing earlier ones.
    pub fn custom_parameters(
        mut self,
        parameters: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        self.custom_parameters =
            Some(parameters.into_iter().map(|(name, value)| (name.into(), value.into())).collect());
        self
    }

    /// Sets the function that receives the authorization URL when the user has to
    /// give consent.
    ///
    /// It is called at most once per `send`, and `send` waits for it before it asks
    /// for the token again. When it returns an error, `send` fails with
    /// [`ErrorKind::AuthorizationCallbackFailed`] and makes no further request. The
    /// error is the [`source`](std::error::Error::source) of that failure.
    ///
    /// Without this setter `send` still waits for the consent, which then has to be
    /// started in another way.
    pub fn on_auth_url<F, Fut, E>(mut self, on_auth_url: F) -> Self
    where
        F: Fn(AuthorizationUrl) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), E>> + Send + 'static,
        E: Into<BoxError>,
    {
        self.on_auth_url = Some(Arc::new(move |url| {
            let notified = on_auth_url(url);
            Box::pin(async move { notified.await.map_err(Into::into) })
        }));
        self
    }

    /// Sets the wait before each request that asks for the token again, while the
    /// user gives consent. The default is 5 seconds. The interval must be greater
    /// than zero.
    pub fn poll_interval(mut self, interval: Duration) -> Self {
        self.poll_interval = interval;
        self
    }

    /// Sets how long new requests for the token are started, while the user gives
    /// consent. The default is 600 seconds. The time counts from the delivery of the
    /// authorization URL.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Requests the token as [`send`](Self::send) does, and returns its steps as a
    /// stream: [`Oauth2Event::AuthorizationUrl`] when the user has to give consent,
    /// then [`Oauth2Event::Token`]. An error is the last item. A token that arrives
    /// with the first response is the only item.
    ///
    /// The stream replaces a function given to [`on_auth_url`](Self::on_auth_url).
    /// The request runs while the stream is polled, and dropping the stream stops it.
    /// Map the items to what the caller of the agent receives, and give the result to
    /// `runtime::Response::stream`:
    ///
    /// ```no_run
    /// use bedrock_agentcore::identity::{AuthFlow, IdentityClient, Oauth2Event};
    /// use futures_util::{Stream, StreamExt};
    /// use serde_json::{Value, json};
    ///
    /// fn consent(identity: &IdentityClient) -> impl Stream<Item = Result<Value, bedrock_agentcore::Error>> {
    ///     let events = identity.oauth2_token("calendar", AuthFlow::UserFederation).into_stream();
    ///     events.map(|event| {
    ///         event.map(|event| match event {
    ///             // The URL goes to the caller that started the request, and to nobody else.
    ///             Oauth2Event::AuthorizationUrl(url) => json!({ "authorization_url": url.expose() }),
    ///             // Give `token.expose()` to the client of the service that needs it.
    ///             Oauth2Event::Token(_token) => json!({ "authorized": true }),
    ///         })
    ///     })
    /// }
    /// ```
    pub fn into_stream(self) -> impl Stream<Item = Result<Oauth2Event, Error>> + Send + 'static {
        let (urls, received) = mpsc::channel(1);
        let request = self.on_auth_url(move |url| {
            let urls = urls.clone();
            async move { urls.send(url).await.map_err(|_| "the stream of the request was dropped") }
        });
        Events { urls: received, token: Some(Box::pin(request.send())), outcome: None }
    }

    /// Requests the token with `GetResourceOauth2Token`.
    ///
    /// The workload access token and the callback URL are read once, when the returned
    /// future is first polled. All requests of this `send` use those values.
    ///
    /// A token in the first response is returned at once, with every flow. See
    /// [the type documentation](Self#consent-of-the-user) for a response with an
    /// authorization URL.
    ///
    /// # Errors
    ///
    /// - [`ErrorKind::InvalidConfig`] when the provider name is not 1 to 128 letters,
    ///   digits, hyphens and underscores, or the poll interval is zero. No request
    ///   is made.
    /// - [`ErrorKind::MissingWorkloadToken`] when there is no nonempty workload access
    ///   token. No request is made.
    /// - [`ErrorKind::Service`] when a call fails. Its text has the provider, the
    ///   error code of the service, the HTTP status and the request ID, and its
    ///   source is the `SdkError` of the generated operation.
    /// - [`ErrorKind::NoTokenOrAuthUrl`] when the first response has neither a token
    ///   nor an authorization URL.
    /// - [`ErrorKind::AuthorizationCallbackFailed`] when the function given to
    ///   [`on_auth_url`](Self::on_auth_url) fails.
    /// - [`ErrorKind::AuthorizationTimedOut`] when no token arrives in time.
    pub async fn send(self) -> Result<AccessToken, Error> {
        check_provider_name(&self.provider)?;
        if self.poll_interval.is_zero() {
            return Err(Error::new(ErrorKind::InvalidConfig, "the poll interval must be greater than zero"));
        }
        let ctx = context::current();
        let workload_access_token = resolve_workload_access_token(self.workload_access_token, ctx.as_ref())?;
        let callback_url =
            self.callback_url.or_else(|| ctx.and_then(|ctx| ctx.oauth2_callback_url().map(str::to_owned)));
        let request = Request {
            client: self.client,
            provider: self.provider,
            flow: self.flow,
            workload_access_token,
            scopes: self.scopes,
            resources: self.resources,
            audiences: self.audiences,
            callback_url,
            custom_state: self.custom_state,
            custom_parameters: self.custom_parameters,
        };

        let first = request.fetch(None, self.force_authentication).await?;
        let session_uri = first.session_uri.clone();
        if let Some(token) = access_token(first.access_token) {
            return Ok(token);
        }
        let Some(url) = first.authorization_url.filter(|url| !url.is_empty()) else {
            return Err(Error::new(
                ErrorKind::NoTokenOrAuthUrl,
                "Identity service did not return a token or authorization URL",
            ));
        };
        if let Some(on_auth_url) = self.on_auth_url {
            on_auth_url(AuthorizationUrl::new(url)).await.map_err(|error| {
                Error::new(ErrorKind::AuthorizationCallbackFailed, "Failed to deliver the authorization URL")
                    .with_source(error)
            })?;
        }
        poller::poll(self.poll_interval, self.timeout, || async {
            Ok(access_token(request.fetch(session_uri.as_deref(), None).await?.access_token))
        })
        .await
    }
}

/// One step of [`Oauth2TokenBuilder::into_stream`].
#[derive(Debug)]
pub enum Oauth2Event {
    /// The user has to give consent at this URL. The token follows as the next item.
    AuthorizationUrl(AuthorizationUrl),
    /// The token. It is the last item.
    Token(AccessToken),
}

type Sending = Pin<Box<dyn Future<Output = Result<AccessToken, Error>> + Send>>;

/// The stream of [`Oauth2TokenBuilder::into_stream`].
struct Events {
    urls: mpsc::Receiver<AuthorizationUrl>,
    /// The request. `None` when it has completed.
    token: Option<Sending>,
    /// The outcome of the request, until the stream has yielded it.
    outcome: Option<Result<AccessToken, Error>>,
}

impl Stream for Events {
    type Item = Result<Oauth2Event, Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // The request is polled first: it puts the URL in the channel. A request
        // that completes in the same poll is not polled again: its outcome is kept
        // until the URL has been yielded.
        if let Some(token) = self.token.as_mut()
            && let Poll::Ready(outcome) = token.as_mut().poll(cx)
        {
            self.token = None;
            self.outcome = Some(outcome);
        }
        if let Ok(url) = self.urls.try_recv() {
            return Poll::Ready(Some(Ok(Oauth2Event::AuthorizationUrl(url))));
        }
        match self.outcome.take() {
            Some(outcome) => Poll::Ready(Some(outcome.map(Oauth2Event::Token))),
            None if self.token.is_some() => Poll::Pending,
            None => Poll::Ready(None),
        }
    }
}

fn access_token(token: Option<String>) -> Option<AccessToken> {
    token.filter(|token| !token.is_empty()).map(AccessToken::new)
}

/// The resolved options that every request of one `send` repeats.
struct Request {
    client: Client,
    provider: String,
    flow: AuthFlow,
    workload_access_token: WorkloadAccessToken,
    scopes: Vec<String>,
    resources: Option<Vec<String>>,
    audiences: Option<Vec<String>>,
    callback_url: Option<String>,
    custom_state: Option<String>,
    custom_parameters: Option<HashMap<String, String>>,
}

impl Request {
    /// One call. The first has no session URI and the caller's choice of forced
    /// authentication. The following ones have the session URI of the first response
    /// and leave `forceAuthentication` out.
    async fn fetch(
        &self,
        session_uri: Option<&str>,
        force_authentication: Option<bool>,
    ) -> Result<GetResourceOauth2TokenOutput, Error> {
        self.client
            .get_resource_oauth2_token()
            .resource_credential_provider_name(&self.provider)
            .workload_identity_token(self.workload_access_token.expose())
            .oauth2_flow(self.flow.into())
            .set_scopes(Some(self.scopes.clone()))
            .set_resources(self.resources.clone())
            .set_audiences(self.audiences.clone())
            .set_resource_oauth2_return_url(self.callback_url.clone())
            .set_custom_state(self.custom_state.clone())
            .set_custom_parameters(self.custom_parameters.clone())
            .set_session_uri(session_uri.map(str::to_owned))
            .set_force_authentication(force_authentication)
            .send()
            .await
            .map_err(|error| service_error("GetResourceOauth2Token", &self.provider, error))
    }
}

impl fmt::Debug for Oauth2TokenBuilder {
    /// Shows the sensitive options only as set or not set.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Oauth2TokenBuilder")
            .field("provider", &self.provider)
            .field("flow", &self.flow)
            .field("scopes", &self.scopes)
            .field("resources", &self.resources)
            .field("audiences", &self.audiences)
            .field("force_authentication", &self.force_authentication)
            .field("workload_access_token", &self.workload_access_token.is_some())
            .field("callback_url", &self.callback_url.is_some())
            .field("custom_state", &self.custom_state.is_some())
            .field("custom_parameters", &self.custom_parameters.is_some())
            .field("on_auth_url", &self.on_auth_url.is_some())
            .field("poll_interval", &self.poll_interval)
            .field("timeout", &self.timeout)
            .finish_non_exhaustive()
    }
}