|
| 1 | +//! Aurora DSQL requires an IAM token in place of a password. Tokens are |
| 2 | +//! generated by the AWS SDK using your AWS credentials. |
| 3 | +
|
| 4 | +use std::{ |
| 5 | + borrow::Cow, |
| 6 | + fmt, |
| 7 | + sync::{Arc, RwLock}, |
| 8 | + time::Duration, |
| 9 | +}; |
| 10 | + |
| 11 | +use aws_config::{BehaviorVersion, SdkConfig}; |
| 12 | +use aws_sdk_dsql::{ |
| 13 | + auth_token::{AuthToken, AuthTokenGenerator, Config}, |
| 14 | + error::BoxError, |
| 15 | +}; |
| 16 | +use sqlx_postgres::PasswordProvider; |
| 17 | +use tokio::{task::JoinHandle, time::sleep}; |
| 18 | + |
| 19 | +/// A builder type to get you build a customized [`DsqlIamProvider`], in case |
| 20 | +/// the AWS SDK defaults aren't what you're looking for. |
| 21 | +/// |
| 22 | +/// If you're happy with the AWS SDK defaults, prefer using |
| 23 | +/// [`DsqlIamProvider::new`]. |
| 24 | +/// |
| 25 | +/// |
| 26 | +/// ```ignore |
| 27 | +/// use sqlx_aws::iam::dsql::*; |
| 28 | +/// |
| 29 | +/// let b = DsqlIamProviderBuilder::defaults().await; |
| 30 | +/// let my_config = Config::builder().hostname("...").build()?; |
| 31 | +/// let provider = b.with_generator_config(my_config).await?; |
| 32 | +/// ``` |
| 33 | +pub struct DsqlIamProviderBuilder { |
| 34 | + cfg: SdkConfig, |
| 35 | + is_admin: bool, |
| 36 | +} |
| 37 | + |
| 38 | +impl DsqlIamProviderBuilder { |
| 39 | + /// A new builder. The AWS SDK is automatically configured. |
| 40 | + pub async fn defaults() -> Self { |
| 41 | + let cfg = aws_config::load_defaults(BehaviorVersion::latest()).await; |
| 42 | + Self::new_with_sdk_cfg(cfg) |
| 43 | + } |
| 44 | + |
| 45 | + /// A new builder with custom SDK config. |
| 46 | + pub fn new_with_sdk_cfg(cfg: SdkConfig) -> Self { |
| 47 | + Self { |
| 48 | + cfg, |
| 49 | + is_admin: false, |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /// Build a provider with the given [`auth_token::Config`]. |
| 54 | + pub async fn with_generator_config(self, config: Config) -> Result<DsqlIamProvider, BoxError> { |
| 55 | + let DsqlIamProviderBuilder { cfg, is_admin } = self; |
| 56 | + |
| 57 | + // This default value is hardcoded in the AuthTokenGenerator. There is |
| 58 | + // no way to share the value. |
| 59 | + let expires_in = config.expires_in().unwrap_or(900); |
| 60 | + |
| 61 | + // Token generation is fast (because it is a local operation). However, |
| 62 | + // there is some coordination involved (such as loading AWS credentials, |
| 63 | + // or tokio scheduling). We want to avoid ever having stale tokens, and so schedule refreshes slightly ahead of expiry. |
| 64 | + let refresh_interval = Duration::from_secs(if expires_in > 60 { |
| 65 | + expires_in - 60 |
| 66 | + } else { |
| 67 | + expires_in |
| 68 | + }); |
| 69 | + |
| 70 | + let generator = AuthTokenGenerator::new(config); |
| 71 | + |
| 72 | + // Boostrap: try once. This allows for failing fast for the case where |
| 73 | + // things haven't been correctly configured. |
| 74 | + let auth_token = match is_admin { |
| 75 | + true => generator.db_connect_admin_auth_token(&cfg).await, |
| 76 | + false => generator.db_connect_auth_token(&cfg).await, |
| 77 | + }?; |
| 78 | + |
| 79 | + let token = Arc::new(RwLock::new(Ok(auth_token))); |
| 80 | + let _token = token.clone(); |
| 81 | + |
| 82 | + let task = tokio::spawn(async move { |
| 83 | + sleep(refresh_interval).await; |
| 84 | + |
| 85 | + loop { |
| 86 | + let res = match is_admin { |
| 87 | + true => generator.db_connect_admin_auth_token(&cfg).await, |
| 88 | + false => generator.db_connect_auth_token(&cfg).await, |
| 89 | + }; |
| 90 | + match res { |
| 91 | + Ok(auth_token) => { |
| 92 | + *_token.write().expect("never poisoned") = Ok(auth_token); |
| 93 | + sleep(refresh_interval).await; |
| 94 | + } |
| 95 | + // XXX: In theory, this should almost never happen, because |
| 96 | + // we did a boostrap token generation, which should catch |
| 97 | + // nearly all errors. However, it is possible that the |
| 98 | + // underlying credential provider has failed in some way. |
| 99 | + Err(err) => { |
| 100 | + // Refreshes are eager, which means it may be possible |
| 101 | + // that we're about to replace perfectly good token with |
| 102 | + // an error. It doesn't seem worthwhile to guard against |
| 103 | + // that, since tokens are short lived and are likely to |
| 104 | + // expire shortly anyways. |
| 105 | + *_token.write().expect("never poisoned") = Err(err); |
| 106 | + |
| 107 | + // sleep an arbitrary amount of time to prevent busy |
| 108 | + // loops, but not so long that we don't try again (if |
| 109 | + // the underlying error has been resolved). |
| 110 | + sleep(Duration::from_secs(1)).await; |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + }); |
| 115 | + |
| 116 | + Ok(DsqlIamProvider { token, task }) |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +/// A sqlx [`PasswordProvider`] that automatically manages IAM tokens. |
| 121 | +/// |
| 122 | +/// ```ignore |
| 123 | +/// use sqlx_postgres::PgConnectOptions; |
| 124 | +/// use sqlx_aws::iam::dsql::*; |
| 125 | +/// |
| 126 | +/// let provider = DsqlIamProvider::new("peccy.dsql.us-east-1.on.aws").await?; |
| 127 | +/// let opts = PgConnectOptions::new_without_pgpass() |
| 128 | +/// .password(provider); |
| 129 | +/// ``` |
| 130 | +pub struct DsqlIamProvider { |
| 131 | + token: Arc<RwLock<Result<AuthToken, BoxError>>>, |
| 132 | + task: JoinHandle<()>, |
| 133 | +} |
| 134 | + |
| 135 | +impl Drop for DsqlIamProvider { |
| 136 | + fn drop(&mut self) { |
| 137 | + self.task.abort(); |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +impl DsqlIamProvider { |
| 142 | + pub async fn new(hostname: impl Into<String>) -> Result<Self, BoxError> { |
| 143 | + let builder = DsqlIamProviderBuilder::defaults().await; |
| 144 | + let config = Config::builder() |
| 145 | + .hostname(hostname) |
| 146 | + .build() |
| 147 | + .expect("hostname was provided"); |
| 148 | + builder.with_generator_config(config).await |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +impl PasswordProvider for DsqlIamProvider { |
| 153 | + fn password<'a>(&'a self) -> Result<Cow<'a, str>, sqlx_core::error::BoxDynError> { |
| 154 | + match &*self.token.read().expect("never poisoned") { |
| 155 | + Ok(auth_token) => Ok(Cow::Owned(auth_token.as_str().to_string())), |
| 156 | + Err(err) => Err(Box::new(RefreshError(format!("{err}")))), |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +#[derive(Debug)] |
| 162 | +pub struct RefreshError(String); |
| 163 | + |
| 164 | +impl fmt::Display for RefreshError { |
| 165 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 166 | + write!(f, "unable to refresh auth token: {}", self.0) |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +impl std::error::Error for RefreshError {} |
0 commit comments