Skip to main content

mz_aws_util/
lib.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
10use std::net::IpAddr;
11
12use aws_config::{BehaviorVersion, ConfigLoader};
13use aws_smithy_http_client::tls::{self, rustls_provider::CryptoMode};
14use aws_smithy_runtime_api::client::dns::{DnsFuture, ResolveDns, ResolveDnsError};
15use aws_smithy_runtime_api::client::http::{HttpClient, SharedHttpClient};
16
17use crate::http_pool::{PooledHttpClient, SwitchedHttpClient};
18
19pub use crate::http_pool::HttpPoolMetrics;
20
21mod http_pool;
22#[cfg(feature = "rds")]
23pub mod rds;
24#[cfg(feature = "s3")]
25pub mod s3;
26#[cfg(feature = "s3")]
27pub mod s3_uploader;
28
29/// Creates an AWS SDK configuration loader with the defaults for the latest
30/// behavior version plus some Materialize-specific overrides.
31pub fn defaults() -> ConfigLoader {
32    // Use the SDK's latest behavior version. We already pin the crate versions,
33    // and CI puts version upgrades through rigorous testing, so we're happy to
34    // take the latest behavior version. We can adjust this in the future as
35    // necessary, if the AWS SDK ships a new behavior version that causes
36    // trouble.
37    let behavior_version = BehaviorVersion::latest();
38
39    // This is the only method allowed to call `aws_config::defaults`.
40    #[allow(clippy::disallowed_methods)]
41    let loader = aws_config::defaults(behavior_version);
42
43    // Install our custom HTTP client.
44    let loader = loader.http_client(http_client());
45
46    loader
47}
48
49/// Returns an HTTP client for use with the AWS SDK that is appropriately
50/// configured for Materialize.
51pub fn http_client() -> impl HttpClient {
52    aws_smithy_http_client::Builder::new()
53        .tls_provider(tls_provider())
54        .build_https()
55}
56
57/// Returns an HTTP client for use with the AWS SDK, like [`http_client`], that
58/// opens more connections to a host as requests to it pile up.
59///
60/// Use it for servers that speak HTTP/2, like GCS. Over HTTP/2, [`http_client`]
61/// sends every request to a host over one connection, which caps throughput.
62///
63/// A request opens a new connection once every connection has
64/// `max_in_flight()` requests in flight, read per request. 0 counts as 1.
65pub fn pooled_http_client(
66    max_in_flight: impl Fn() -> usize + Send + Sync + 'static,
67    metrics: HttpPoolMetrics,
68) -> impl HttpClient {
69    PooledHttpClient::new(
70        || SharedHttpClient::new(http_client()),
71        max_in_flight,
72        metrics,
73    )
74}
75
76/// Returns an HTTP client for use with the AWS SDK that sends each request
77/// through [`pooled_http_client`] if `use_pool` returns true when the request
78/// is sent, and through [`http_client`] otherwise.
79pub fn switched_http_client(
80    use_pool: impl Fn() -> bool + Send + Sync + 'static,
81    pool_max_in_flight: impl Fn() -> usize + Send + Sync + 'static,
82    pool_metrics: HttpPoolMetrics,
83) -> impl HttpClient {
84    SwitchedHttpClient::new(
85        SharedHttpClient::new(http_client()),
86        SharedHttpClient::new(pooled_http_client(pool_max_in_flight, pool_metrics)),
87        use_pool,
88    )
89}
90
91/// Returns an AWS SDK HTTP client whose DNS resolver delegates to
92/// [`mz_ore::netio::resolve_address`].
93///
94/// Only the IP resolution step is overridden. The SDK still uses the original
95/// hostname for SNI and TLS certificate validation, so HTTPS endpoints work
96/// unchanged.
97pub fn http_client_with_resolver(enforce_external_addresses: bool) -> SharedHttpClient {
98    aws_smithy_http_client::Builder::new()
99        .tls_provider(tls_provider())
100        .build_with_resolver(MzAwsResolver {
101            enforce_external_addresses,
102        })
103}
104
105/// rustls on the aws-lc-rs provider, trusting the system's root certificates.
106fn tls_provider() -> tls::Provider {
107    // TODO(SEC-218): the rest of the workspace is still migrating from OpenSSL
108    // to rustls on aws-lc-rs.
109    tls::Provider::Rustls(CryptoMode::AwsLc)
110}
111
112/// A [`ResolveDns`] implementation that delegates to
113/// [`mz_ore::netio::resolve_address`], used by [`http_client_with_resolver`].
114#[derive(Clone, Debug)]
115struct MzAwsResolver {
116    enforce_external_addresses: bool,
117}
118
119impl MzAwsResolver {
120    async fn resolve(&self, host: &str) -> Result<Vec<IpAddr>, mz_ore::netio::DnsResolutionError> {
121        let ips = mz_ore::netio::resolve_address(host, self.enforce_external_addresses).await?;
122        Ok(ips.into_iter().collect())
123    }
124}
125
126impl ResolveDns for MzAwsResolver {
127    fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a> {
128        DnsFuture::new(async move { self.resolve(name).await.map_err(ResolveDnsError::new) })
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use mz_ore::netio::DnsResolutionError;
135
136    use super::*;
137
138    #[mz_ore::test(tokio::test)]
139    #[cfg_attr(miri, ignore)]
140    async fn resolver_rejects_loopback_when_enforced() {
141        let resolver = MzAwsResolver {
142            enforce_external_addresses: true,
143        };
144        let err = resolver
145            .resolve("127.0.0.1")
146            .await
147            .expect_err("must reject loopback");
148        assert!(
149            matches!(err, DnsResolutionError::PrivateAddress),
150            "got {err:?}"
151        );
152        let err = resolver
153            .resolve_dns("127.0.0.1")
154            .await
155            .expect_err("must reject loopback");
156        let source = std::error::Error::source(&err).expect("wraps the resolution error");
157        assert!(
158            matches!(
159                source.downcast_ref::<DnsResolutionError>(),
160                Some(DnsResolutionError::PrivateAddress)
161            ),
162            "got {source:?}"
163        );
164    }
165
166    #[mz_ore::test(tokio::test)]
167    #[cfg_attr(miri, ignore)]
168    async fn resolver_allows_loopback_when_not_enforced() {
169        let resolver = MzAwsResolver {
170            enforce_external_addresses: false,
171        };
172        let addrs = resolver
173            .resolve_dns("127.0.0.1")
174            .await
175            .expect("loopback should resolve when enforcement is off");
176        assert!(addrs.contains(&IpAddr::from([127, 0, 0, 1])));
177    }
178
179    #[mz_ore::test(tokio::test)]
180    #[cfg_attr(miri, ignore)]
181    async fn resolver_allows_public_when_enforced() {
182        let resolver = MzAwsResolver {
183            enforce_external_addresses: true,
184        };
185        let addrs = resolver
186            .resolve_dns("8.8.8.8")
187            .await
188            .expect("public IP should resolve");
189        assert!(addrs.contains(&IpAddr::from([8, 8, 8, 8])));
190    }
191}