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! {
AccessToken
}
secret! {
AuthorizationUrl
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthFlow {
M2m,
UserFederation,
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,
}
}
}
#[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,
}
}
pub fn workload_access_token(mut self, token: WorkloadAccessToken) -> Self {
self.workload_access_token = Some(token);
self
}
pub fn scopes(mut self, scopes: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.scopes = strings(scopes);
self
}
pub fn resources(mut self, resources: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.resources = Some(strings(resources));
self
}
pub fn audiences(mut self, audiences: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.audiences = Some(strings(audiences));
self
}
pub fn callback_url(mut self, url: impl Into<String>) -> Self {
self.callback_url = Some(url.into());
self
}
pub fn force_authentication(mut self, force: bool) -> Self {
self.force_authentication = Some(force);
self
}
pub fn custom_state(mut self, state: impl Into<String>) -> Self {
self.custom_state = Some(state.into());
self
}
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
}
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
}
pub fn poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
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 }
}
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
}
}
#[derive(Debug)]
pub enum Oauth2Event {
AuthorizationUrl(AuthorizationUrl),
Token(AccessToken),
}
type Sending = Pin<Box<dyn Future<Output = Result<AccessToken, Error>> + Send>>;
struct Events {
urls: mpsc::Receiver<AuthorizationUrl>,
token: Option<Sending>,
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>> {
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)
}
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 {
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 {
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()
}
}