Skip to main content

mz_aws_util/
rds.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! AWS RDS IAM database authentication.
11//!
12//! The tokens generated here are not specific to a database engine: the same
13//! token authenticates against RDS and Aurora for MySQL and PostgreSQL. The
14//! caller passes the token as the password when it connects, over TLS.
15
16use aws_config::{Region, SdkConfig};
17use aws_credential_types::provider::ProvideCredentials;
18use aws_credential_types::provider::error::CredentialsError;
19use aws_sigv4::http_request::{
20    self, SignableBody, SignableRequest, SignatureLocation, SigningError, SigningSettings,
21};
22use aws_sigv4::sign::v4::SigningParams;
23use aws_sigv4::sign::v4::signing_params::BuildError;
24use mz_ore::secure::SecureString;
25use std::fmt;
26use std::sync::Arc;
27use std::time::Duration;
28
29const AWS_TOKEN_EXPIRATION_SECONDS: u64 = 900;
30const AWS_SERVICE: &str = "rds-db";
31const DB_ACTION: &str = "connect";
32
33#[derive(Debug, thiserror::Error)]
34pub enum RdsTokenError {
35    /// The AWS SdkConfig did not contain a credentials provider.
36    #[error("Credentials provider required to sign RDS IAM request")]
37    MissingCredentialsProvider,
38
39    /// The supplied credentials provider failed to generate credentials for URL signing.
40    #[error(transparent)]
41    CredentialsError(#[from] CredentialsError),
42
43    /// The signing parameters could not be created due to a missing required argument.
44    #[error(transparent)]
45    SigningParametersBuildError(#[from] BuildError),
46
47    /// The URL could not be signed.
48    #[error(transparent)]
49    SigningError(#[from] SigningError),
50
51    /// The host could not be parsed as a valid URL.
52    #[error("invalid RDS endpoint: {0}")]
53    InvalidEndpoint(#[from] url::ParseError),
54}
55
56/// An RDS IAM authentication token.
57#[derive(Debug, Clone)]
58pub struct RdsAuthToken {
59    /// The token, to use as the database password. It is a credential for as
60    /// long as it is valid, so it is redacted in `Debug` output.
61    pub token: SecureString,
62    /// The access key ID of the credentials that signed the token.
63    pub access_key_id: String,
64}
65
66/// Authenticates database connections to Amazon RDS with AWS IAM.
67#[derive(Clone)]
68pub struct RdsIamAuth {
69    aws_config: SdkConfig,
70    on_token_rejected: Option<Arc<dyn Fn(&str) + Send + Sync>>,
71}
72
73impl fmt::Debug for RdsIamAuth {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("RdsIamAuth")
76            .field("aws_config", &self.aws_config)
77            .field("on_token_rejected", &self.on_token_rejected.is_some())
78            .finish()
79    }
80}
81
82impl RdsIamAuth {
83    /// Signs tokens with the credentials provider of `aws_config`.
84    pub fn new(aws_config: SdkConfig) -> RdsIamAuth {
85        RdsIamAuth {
86            aws_config,
87            on_token_rejected: None,
88        }
89    }
90
91    /// Calls `hook` with the access key ID of the signing credentials whenever
92    /// [`RdsIamAuth::token_rejected`] reports a rejected token.
93    ///
94    /// A provider that caches credentials uses this to replace credentials
95    /// that AWS no longer honors, such as those of a revoked role session.
96    pub fn on_token_rejected(mut self, hook: impl Fn(&str) + Send + Sync + 'static) -> RdsIamAuth {
97        self.on_token_rejected = Some(Arc::new(hook));
98        self
99    }
100
101    /// Generates an RDS IAM authentication token for `username` connecting to
102    /// the database at `host:port`.
103    ///
104    /// `host` and `port` must be the endpoint of the RDS instance or cluster
105    /// itself, not of a tunnel or proxy in front of it, because the token is a
106    /// signature over that endpoint. The token is valid for 15 minutes.
107    ///
108    /// Every call asks the credentials provider for credentials, and nothing
109    /// here caches them. If that provider assumes a role, each token costs a
110    /// round of AWS STS requests unless the provider caches.
111    pub async fn token(
112        &self,
113        host: &str,
114        port: u16,
115        username: &str,
116    ) -> Result<RdsAuthToken, RdsTokenError> {
117        sign_rds_auth_token(host, port, username, &self.aws_config).await
118    }
119
120    /// Reports that the database rejected `token` as an authentication
121    /// failure.
122    pub fn token_rejected(&self, token: &RdsAuthToken) {
123        if let Some(hook) = &self.on_token_rejected {
124            hook(&token.access_key_id);
125        }
126    }
127}
128
129/// This mirrors `aws_sdk_rds::auth_token`, without depending on `aws-sdk-rds`.
130async fn sign_rds_auth_token(
131    host: &str,
132    port: u16,
133    username: &str,
134    aws_config: &SdkConfig,
135) -> Result<RdsAuthToken, RdsTokenError> {
136    let credentials = aws_config
137        .credentials_provider()
138        .ok_or(RdsTokenError::MissingCredentialsProvider)?
139        .provide_credentials()
140        .await?;
141    let access_key_id = credentials.access_key_id().to_owned();
142
143    // mirror existing SDK behaviour: default to us-east-1,
144    let region = aws_config
145        .region()
146        .cloned()
147        .unwrap_or_else(|| Region::new("us-east-1"));
148
149    // defaults to SystemTime
150    let time_source = aws_config.time_source().unwrap_or_default();
151
152    let mut signing_settings = SigningSettings::default();
153    signing_settings.expires_in = Some(Duration::from_secs(AWS_TOKEN_EXPIRATION_SECONDS));
154    signing_settings.signature_location = SignatureLocation::QueryParams;
155
156    let identity = credentials.into();
157    let signing_params = SigningParams::builder()
158        .identity(&identity)
159        .region(region.as_ref())
160        .name(AWS_SERVICE)
161        .time(time_source.now())
162        .settings(signing_settings)
163        .build()?;
164
165    let mut url = url::Url::parse(&format!("https://{}:{}/", host, port))?;
166    url.query_pairs_mut()
167        .append_pair("Action", DB_ACTION)
168        .append_pair("DBUser", username);
169
170    let url_str = url.as_str().to_owned();
171    let signable_req = SignableRequest::new(
172        "GET",
173        &url_str,
174        std::iter::empty(),
175        SignableBody::Bytes(&[]),
176    )?;
177
178    let (signing_instructions, _sig) =
179        http_request::sign(signable_req, &signing_params.into())?.into_parts();
180
181    for (key, val) in signing_instructions.params() {
182        url.query_pairs_mut().append_pair(key, val);
183    }
184
185    Ok(RdsAuthToken {
186        token: SecureString::from(&url.as_str()["https://".len()..]),
187        access_key_id,
188    })
189}
190
191#[cfg(test)]
192mod test {
193    use aws_credential_types::Credentials;
194    use aws_types::sdk_config::{SharedCredentialsProvider, TimeSource};
195    use std::time::SystemTime;
196
197    use super::*;
198    #[derive(Debug)]
199    struct TestTimeSource {
200        time: SystemTime,
201    }
202    impl TimeSource for TestTimeSource {
203        fn now(&self) -> SystemTime {
204            self.time.clone()
205        }
206    }
207
208    #[mz_ore::test(tokio::test)]
209    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `getauxval` on OS `linux`
210    async fn test_signature() {
211        let time_source = TestTimeSource {
212            time: SystemTime::UNIX_EPOCH + Duration::from_secs(1740690000),
213        };
214        let aws_config = SdkConfig::builder()
215            .credentials_provider(SharedCredentialsProvider::new(Credentials::new(
216                "drjekyll", "mrhyde", None, None, "test",
217            )))
218            .time_source(time_source)
219            .build();
220        let iam_auth = RdsIamAuth::new(aws_config);
221        let signature = iam_auth.token("mysql", 3306, "root").await.unwrap();
222        assert_eq!(signature.access_key_id, "drjekyll");
223        assert_eq!(
224            signature.token.unsecure(),
225            "mysql:3306/?Action=connect&DBUser=root&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=drjekyll%2F20250227%2Fus-east-1%2Frds-db%2Faws4_request&X-Amz-Date=20250227T210000Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=6eb04929394feeb9e070621ecafc731145914cc53e542d5302c251b705c4ac72"
226        );
227
228        // Usernames with URL-special characters must be percent-encoded in the
229        // token, not interpolated raw into the query string.
230        for (username, reject_key) in [("root&Foo=bar", Some("Foo")), ("root#admin", None)] {
231            let token = iam_auth.token("mysql", 3306, username).await.unwrap();
232            let url = format!("https://{}", token.token.unsecure());
233            let parsed = url::Url::parse(&url).unwrap();
234            let pairs: std::collections::BTreeMap<_, _> = parsed.query_pairs().collect();
235            assert_eq!(pairs.get("DBUser").unwrap(), username);
236            if let Some(key) = reject_key {
237                assert!(!pairs.contains_key(key));
238            }
239        }
240
241        assert!(iam_auth.token("", 3306, "root").await.is_err());
242    }
243}