Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

refactor(external_services): add shared cloud_services crate for storage, KMS and email clients (#14671)

Jagan7793a71aa8cb
diff --git a/Cargo.lock b/Cargo.lock
index 32b7266f18..53aab39307 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2119,6 +2119,33 @@ version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6"
+[[package]]
+name = "cloud_services"
+version = "0.1.0"
+dependencies = [
+ "aws-config",
+ "aws-sdk-kms",
+ "aws-sdk-s3",
+ "aws-sdk-sesv2",
+ "aws-sdk-sts",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "base64 0.22.1",
+ "google-cloud-gax",
+ "google-cloud-kms",
+ "hyper 0.14.32",
+ "hyper-proxy",
+ "lettre",
+ "oci_kms",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+ "tokio 1.48.0",
+ "tokio-socks",
+ "tracing",
+ "url 2.5.4",
+]
+
[[package]]
name = "cloudabi"
version = "0.0.3"
@@ -3608,34 +3635,24 @@ version = "0.1.0"
dependencies = [
"api_models",
"async-trait",
- "aws-config",
- "aws-sdk-kms",
- "aws-sdk-s3",
- "aws-sdk-sesv2",
- "aws-sdk-sts",
- "aws-smithy-runtime",
- "aws-smithy-runtime-api",
"aws-smithy-types",
"base64 0.22.1",
"bytes 1.10.1",
+ "cloud_services",
"common_enums",
"common_utils",
"deja",
"dyn-clone",
"error-stack 0.4.1",
"futures 0.3.31",
- "google-cloud-kms",
"hex",
"http 0.2.12",
"http-body 1.0.1",
"http-body-util",
"hyper 0.14.32",
- "hyper-proxy",
"hyper-util",
"hyperswitch_interfaces",
"hyperswitch_masking",
- "lettre",
- "oci_kms",
"once_cell",
"open-feature",
"prost 0.14.3",
@@ -3654,7 +3671,6 @@ dependencies = [
"thiserror 1.0.69",
"time 0.3.41",
"tokio 1.48.0",
- "tokio-socks",
"tokio-stream",
"tonic 0.14.5",
"tonic-prost",
diff --git a/crates/cloud_services/Cargo.toml b/crates/cloud_services/Cargo.toml
new file mode 100644
index 0000000000..bf2954a795
--- /dev/null
+++ b/crates/cloud_services/Cargo.toml
@@ -0,0 +1,58 @@
+[package]
+name = "cloud_services"
+description = "Cloud provider clients (KMS, object storage) shared across Hyperswitch services"
+version = "0.1.0"
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+
+# Deliberately free of Hyperswitch crates (no `common_utils`, `router_env` or `error-stack`),
+# so services outside this workspace can depend on it without pulling in Hyperswitch.
+[features]
+default = []
+s3 = ["dep:aws-config", "dep:aws-sdk-s3", "dep:url"]
+oci_object_storage = ["s3"]
+aws_kms = ["dep:aws-config", "dep:aws-sdk-kms", "dep:base64"]
+gcp_kms = ["dep:google-cloud-kms", "dep:google-cloud-gax", "dep:base64"]
+ses = [
+ "dep:aws-config",
+ "dep:aws-sdk-sesv2",
+ "dep:aws-sdk-sts",
+ "dep:aws-smithy-runtime",
+ "dep:aws-smithy-runtime-api",
+ "dep:hyper",
+ "dep:hyper-proxy",
+]
+smtp = ["dep:lettre", "dep:tokio", "dep:tokio-socks", "dep:tracing"]
+oci_kms = ["dep:oci_kms"]
+
+[dependencies]
+aws-config = { version = "1.5.10", optional = true, features = [
+ "behavior-version-latest",
+] }
+aws-sdk-kms = { version = "1.51.0", optional = true }
+aws-sdk-s3 = { version = "1.65.0", optional = true }
+aws-sdk-sesv2 = { version = "1.57.0", optional = true }
+aws-sdk-sts = { version = "1.51.0", optional = true }
+aws-smithy-runtime = { version = "1.8.3", optional = true }
+aws-smithy-runtime-api = { version = "1.7", optional = true, features = ["client"] }
+base64 = { version = "0.22.1", optional = true }
+google-cloud-gax = { version = "0.19.2", optional = true }
+google-cloud-kms = { version = "0.6.0", optional = true }
+hyper = { version = "0.14.32", optional = true, features = ["client", "tcp", "http1"] }
+hyper-proxy = { version = "0.9.1", optional = true }
+lettre = { version = "0.11.16", optional = true, features = ["tokio1", "tokio1-native-tls"] }
+oci_kms = { version = "0.1.0", path = "../oci_kms", optional = true }
+serde = { version = "1.0.219", features = ["derive"] }
+thiserror = "1.0.69"
+tokio = { version = "1.48.0", optional = true, features = ["net", "time"] }
+tokio-socks = { version = "0.5", optional = true }
+tracing = { workspace = true, optional = true }
+url = { version = "2.5.4", optional = true }
+
+[dev-dependencies]
+serde_json = "1.0.140"
+tokio = { version = "1.48.0", features = ["macros", "rt-multi-thread"] }
+
+[lints]
+workspace = true
diff --git a/crates/cloud_services/src/email.rs b/crates/cloud_services/src/email.rs
new file mode 100644
index 0000000000..68e837961e
--- /dev/null
+++ b/crates/cloud_services/src/email.rs
@@ -0,0 +1,23 @@
+//! Email delivery clients.
+
+#[cfg(feature = "ses")]
+pub mod ses;
+#[cfg(feature = "smtp")]
+pub mod smtp;
+
+/// One email to send. Addresses are plain strings; the client sending it checks them.
+#[derive(Clone, Debug)]
+pub struct EmailMessage {
+ /// The sender's address.
+ pub from: String,
+ /// Recipients.
+ pub to: Vec<String>,
+ /// Copied recipients.
+ pub cc: Vec<String>,
+ /// Blind-copied recipients.
+ pub bcc: Vec<String>,
+ /// The subject line.
+ pub subject: String,
+ /// The HTML body.
+ pub html_body: String,
+}
diff --git a/crates/cloud_services/src/email/ses.rs b/crates/cloud_services/src/email/ses.rs
new file mode 100644
index 0000000000..5cd32af62c
--- /dev/null
+++ b/crates/cloud_services/src/email/ses.rs
@@ -0,0 +1,223 @@
+//! AWS SES client, sending with credentials from an STS-assumed role.
+
+use std::time::{Duration, SystemTime};
+
+use aws_sdk_sesv2::{
+ config::Region,
+ operation::send_email::SendEmailError,
+ types::{Body, Content, Destination, EmailContent, Message},
+ Client,
+};
+use aws_sdk_sts::{config::Credentials, operation::assume_role::AssumeRoleError};
+use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
+
+use super::EmailMessage;
+
+/// The role SES sends as, assumed through STS.
+#[derive(Clone, Debug, Default, serde::Deserialize)]
+pub struct SesConfig {
+ /// The ARN of the role to assume.
+ pub email_role_arn: String,
+ /// The STS session name for the assumed role.
+ pub sts_role_session_name: String,
+}
+
+impl SesConfig {
+ /// Checks that the role is set.
+ pub fn validate(&self) -> Result<(), &'static str> {
+ if self.email_role_arn.is_empty() {
+ return Err("email.aws_ses.email_role_arn must not be empty");
+ }
+ if self.sts_role_session_name.is_empty() {
+ return Err("email.aws_ses.sts_role_session_name must not be empty");
+ }
+ Ok(())
+ }
+}
+
+/// Errors from sending through SES.
+#[derive(Debug, thiserror::Error)]
+pub enum SesError {
+ /// STS refused to assume the role.
+ #[error(
+ "Failed to STS assume role: Role ARN: {role_arn}, Session name: {session_name}, Region: {region}"
+ )]
+ AssumeRoleFailure {
+ /// The AWS region.
+ region: String,
+ /// The ARN of the role.
+ role_arn: String,
+ /// The STS session name.
+ session_name: String,
+ /// The STS error.
+ #[source]
+ source: Box<aws_sdk_sts::error::SdkError<AssumeRoleError>>,
+ },
+ /// The assumed role came without credentials.
+ #[error("Assumed role does not contain credentials for role user: {0}")]
+ TemporaryCredentialsMissing(String),
+ /// The proxy URL could not be used.
+ #[error("The proxy connector cannot be built: {0}")]
+ BuildingProxyConnectorFailed(String),
+ /// The message could not be built.
+ #[error("Failed to build the email content")]
+ ContentBuildFailure(#[source] aws_sdk_sesv2::error::BuildError),
+ /// SES refused or failed to send.
+ #[error("Failed to send email")]
+ SendingFailure(#[source] Box<aws_sdk_sesv2::error::SdkError<SendEmailError>>),
+}
+
+impl SesError {
+ /// Whether the error happened while building the client, before any message was sent.
+ pub fn is_client_building_failure(&self) -> bool {
+ matches!(
+ self,
+ Self::AssumeRoleFailure { .. }
+ | Self::TemporaryCredentialsMissing(_)
+ | Self::BuildingProxyConnectorFailed(_)
+ )
+ }
+}
+
+/// Sends email through SES in a region, as an STS-assumed role.
+#[derive(Clone, Debug)]
+pub struct SesClient {
+ region: String,
+ config: SesConfig,
+}
+
+impl SesClient {
+ /// Creates the client; nothing is contacted until [`Self::send`] or [`Self::sdk_client`].
+ pub fn new(region: String, config: SesConfig) -> Self {
+ Self { region, config }
+ }
+
+ /// Assumes the role and builds an SDK client, through `proxy_url` when given. [`Self::send`]
+ /// does this for every message, since the role's session expires.
+ pub async fn sdk_client(&self, proxy_url: Option<&str>) -> Result<Client, SesError> {
+ let sts_config = shared_config(&self.region, proxy_url)?.load().await;
+
+ let role = aws_sdk_sts::Client::new(&sts_config)
+ .assume_role()
+ .role_arn(&self.config.email_role_arn)
+ .role_session_name(&self.config.sts_role_session_name)
+ .send()
+ .await
+ .map_err(|source| SesError::AssumeRoleFailure {
+ region: self.region.clone(),
+ role_arn: self.config.email_role_arn.clone(),
+ session_name: self.config.sts_role_session_name.clone(),
+ source: Box::new(source),
+ })?;
+
+ let creds = role
+ .credentials()
+ .ok_or_else(|| SesError::TemporaryCredentialsMissing(format!("{role:?}")))?;
+
+ let credentials = Credentials::new(
+ creds.access_key_id(),
+ creds.secret_access_key(),
+ Some(creds.session_token().to_owned()),
+ u64::try_from(creds.expiration().as_nanos())
+ .ok()
+ .map(Duration::from_nanos)
+ .and_then(|val| SystemTime::UNIX_EPOCH.checked_add(val)),
+ "custom_provider",
+ );
+
+ let ses_config = shared_config(&self.region, proxy_url)?
+ .credentials_provider(credentials)
+ .load()
+ .await;
+
+ Ok(Client::new(&ses_config))
+ }
+
+ /// Sends `message` with fresh credentials, through `proxy_url` when given.
+ pub async fn send(
+ &self,
+ message: EmailMessage,
+ proxy_url: Option<&str>,
+ ) -> Result<(), SesError> {
+ let client = self.sdk_client(proxy_url).await?;
+
+ let body = Body::builder()
+ .html(
+ Content::builder()
+ .data(message.html_body)
+ .charset("UTF-8")
+ .build()
+ .map_err(SesError::ContentBuildFailure)?,
+ )
+ .build();
+ let subject = Content::builder()
+ .data(message.subject)
+ .build()
+ .map_err(SesError::ContentBuildFailure)?;
+
+ client
+ .send_email()
+ .from_email_address(message.from)
+ .destination(
+ Destination::builder()
+ .set_to_addresses(Some(message.to))
+ .set_cc_addresses((!message.cc.is_empty()).then_some(message.cc))
+ .set_bcc_addresses((!message.bcc.is_empty()).then_some(message.bcc))
+ .build(),
+ )
+ .content(
+ EmailContent::builder()
+ .simple(Message::builder().subject(subject).body(body).build())
+ .build(),
+ )
+ .send()
+ .await
+ .map_err(|error| SesError::SendingFailure(Box::new(error)))?;
+
+ Ok(())
+ }
+}
+
+fn shared_config(
+ region: &str,
+ proxy_url: Option<&str>,
+) -> Result<aws_config::ConfigLoader, SesError> {
+ let mut config = aws_config::from_env().region(Region::new(region.to_owned()));
+
+ if let Some(proxy_url) = proxy_url {
+ let proxy_uri = proxy_url
+ .parse::<hyper::Uri>()
+ .map_err(|error| SesError::BuildingProxyConnectorFailed(error.to_string()))?;
+ let proxy = hyper_proxy::Proxy::new(hyper_proxy::Intercept::All, proxy_uri);
+ let proxy_connector =
+ hyper_proxy::ProxyConnector::from_proxy(hyper::client::HttpConnector::new(), proxy)
+ .map_err(|error| SesError::BuildingProxyConnectorFailed(error.to_string()))?;
+ config = config.http_client(HyperClientBuilder::new().build(proxy_connector));
+ }
+ Ok(config)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn validate_requires_the_role() {
+ assert!(SesConfig::default().validate().is_err());
+ let config = SesConfig {
+ email_role_arn: "arn:aws:iam::123456789012:role/ses".to_owned(),
+ sts_role_session_name: "hyperswitch".to_owned(),
+ };
+ assert!(config.validate().is_ok());
+ }
+
+ #[test]
+ fn client_building_failures_are_told_apart() {
+ assert!(
+ SesError::BuildingProxyConnectorFailed("bad".to_owned()).is_client_building_failure()
+ );
+ assert!(
+ SesError::TemporaryCredentialsMissing("role".to_owned()).is_client_building_failure()
+ );
+ }
+}
diff --git a/crates/cloud_services/src/email/smtp.rs b/crates/cloud_services/src/email/smtp.rs
new file mode 100644
index 0000000000..337058e062
--- /dev/null
+++ b/crates/cloud_services/src/email/smtp.rs
@@ -0,0 +1,330 @@
+//! SMTP client, optionally tunnelled through a SOCKS5 proxy.
+
+use std::time::Duration;
+
+use lettre::{
+ address::AddressError,
+ message::{header::ContentType, Mailbox},
+ transport::smtp::{
+ self,
+ authentication::{Credentials, Mechanism},
+ client::{AsyncSmtpConnection, AsyncTokioStream, TlsParameters},
+ extension::ClientId,
+ },
+};
+use tokio::net::TcpStream;
+use tokio_socks::tcp::Socks5Stream;
+
+use super::EmailMessage;
+
+/// Redacts a credential in `Debug` output.
+fn redacted(value: &Option<String>) -> Option<&'static str> {
+ value.as_ref().map(|_| "***")
+}
+
+/// How to reach the SMTP server.
+#[derive(Clone, Default, serde::Deserialize)]
+pub struct SmtpConfig {
+ /// The server's host, e.g. `smtp.gmail.com`.
+ pub host: String,
+ /// The server's port, e.g. `25`.
+ pub port: u16,
+ /// Timeout of each network step (connect, handshake, STARTTLS, AUTH, send, QUIT), in seconds.
+ pub timeout: u64,
+ /// Login username; with `password`, the client authenticates.
+ pub username: Option<String>,
+ /// Login password.
+ pub password: Option<String>,
+ /// Whether the connection upgrades to TLS.
+ #[serde(default)]
+ pub connection: SmtpConnection,
+ /// SOCKS5 proxy to tunnel the connection through; absent means connect directly.
+ #[serde(default)]
+ pub socks5: Option<Socks5Config>,
+}
+
+impl std::fmt::Debug for SmtpConfig {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SmtpConfig")
+ .field("host", &self.host)
+ .field("port", &self.port)
+ .field("timeout", &self.timeout)
+ .field("username", &redacted(&self.username))
+ .field("password", &redacted(&self.password))
+ .field("connection", &self.connection)
+ .field("socks5", &self.socks5)
+ .finish()
+ }
+}
+
+/// A SOCKS5 proxy. Username/password auth (RFC 1929) is sent to the proxy in cleartext.
+#[derive(Clone, Default, serde::Deserialize)]
+pub struct Socks5Config {
+ /// The proxy's hostname or IP.
+ pub host: String,
+ /// The proxy's port.
+ pub port: u16,
+ /// Proxy username, if the proxy requires auth; with `password`.
+ pub username: Option<String>,
+ /// Proxy password.
+ pub password: Option<String>,
+}
+
+impl std::fmt::Debug for Socks5Config {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Socks5Config")
+ .field("host", &self.host)
+ .field("port", &self.port)
+ .field("username", &redacted(&self.username))
+ .field("password", &redacted(&self.password))
+ .finish()
+ }
+}
+
+/// The SMTP connection's security.
+#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SmtpConnection {
+ /// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS.
+ #[default]
+ StartTls,
+ /// Plaintext connection (very insecure).
+ Plaintext,
+}
+
+/// Errors from sending through SMTP.
+#[derive(Debug, thiserror::Error)]
+pub enum SmtpError {
+ /// The server refused or failed the `MAIL FROM`/`RCPT TO`/`DATA` exchange.
+ #[error("Failed to send email")]
+ SendingFailure(#[source] smtp::Error),
+ /// The server rejected the login.
+ #[error("SMTP authentication failed")]
+ AuthenticationFailure(#[source] smtp::Error),
+ /// The SMTP handshake or STARTTLS upgrade failed.
+ #[error("Failed to create the SMTP connection")]
+ ConnectionFailure(#[source] smtp::Error),
+ /// The message could not be built.
+ #[error("Failed to build the email content")]
+ MessageBuildingFailed(#[source] lettre::error::Error),
+ /// An address could not be parsed.
+ #[error("Failed to parse the email address {address:?}")]
+ EmailParsingFailed {
+ /// The address.
+ address: String,
+ /// The parse error.
+ #[source]
+ source: AddressError,
+ },
+ /// The SOCKS5 proxy's hostname could not be resolved.
+ #[error("Failed to resolve the SOCKS5 proxy address")]
+ Socks5ProxyResolutionFailed(#[source] std::io::Error),
+ /// The SOCKS5 tunnel could not be set up (proxy unreachable, auth rejected, protocol error).
+ #[error("SOCKS5 proxy connection failed")]
+ Socks5ConnectionFailed(#[source] tokio_socks::Error),
+ /// The TCP connection to the SMTP server failed.
+ #[error("Failed to connect to the SMTP server")]
+ DirectConnectionFailed(#[source] std::io::Error),
+ /// A network step exceeded the configured timeout.
+ #[error("SMTP operation timed out: {0}")]
+ Timeout(&'static str),
+}
+
+/// Sends email through an SMTP server.
+#[derive(Clone, Debug)]
+pub struct SmtpClient {
+ config: SmtpConfig,
+}
+
+impl SmtpClient {
+ /// Creates the client; nothing is contacted until [`Self::send`].
+ pub fn new(config: SmtpConfig) -> Self {
+ Self { config }
+ }
+
+ /// Sends `message` over a new connection, through the SOCKS5 proxy when one is configured.
+ pub async fn send(&self, message: EmailMessage) -> Result<(), SmtpError> {
+ let mut builder = lettre::Message::builder()
+ .from(mailbox(message.from)?)
+ .subject(message.subject)
+ .header(ContentType::TEXT_HTML);
+ for address in message.to {
+ builder = builder.to(mailbox(address)?);
+ }
+ for address in message.cc {
+ builder = builder.cc(mailbox(address)?);
+ }
+ for address in message.bcc {
+ builder = builder.bcc(mailbox(address)?);
+ }
+ let email = builder
+ .body(message.html_body)
+ .map_err(SmtpError::MessageBuildingFailed)?;
+
+ let config = &self.config;
+ let mut conn = self.connect().await?;
+ let credentials = config
+ .username
+ .clone()
+ .zip(config.password.clone())
+ .map(|(username, password)| Credentials::new(username, password));
+ if let Some(credentials) = credentials {
+ self.timed(
+ "AUTH",
+ conn.auth(&[Mechanism::Plain, Mechanism::Login], &credentials),
+ )
+ .await?
+ .map_err(SmtpError::AuthenticationFailure)?;
+ }
+ self.timed("SEND", conn.send(email.envelope(), &email.formatted()))
+ .await?
+ .map_err(SmtpError::SendingFailure)?;
+
+ // The message is already accepted, so a failed QUIT is only logged.
+ match self.timed("QUIT", conn.quit()).await {
+ Ok(Ok(_)) => {}
+ Ok(Err(error)) => tracing::warn!(?error, "SMTP QUIT failed after the message was sent"),
+ Err(error) => tracing::warn!(%error, "SMTP QUIT failed after the message was sent"),
+ }
+ Ok(())
+ }
+
+ /// Runs one network step within the configured timeout.
+ async fn timed<T>(
+ &self,
+ step: &'static str,
+ future: impl std::future::Future<Output = T>,
+ ) -> Result<T, SmtpError> {
+ tokio::time::timeout(Duration::from_secs(self.config.timeout), future)
+ .await
+ .map_err(|_| SmtpError::Timeout(step))
+ }
+
+ /// Opens the TCP stream (directly or through the proxy), then the SMTP session, upgrading it
+ /// with STARTTLS when configured.
+ async fn connect(&self) -> Result<AsyncSmtpConnection, SmtpError> {
+ let config = &self.config;
+ let client_id = ClientId::default();
+ let stream = self
+ .timed("connect", async {
+ match config.socks5.as_ref() {
+ Some(socks5) => connect_via_socks5(socks5, &config.host, config.port).await,
+ None => TcpStream::connect((config.host.as_str(), config.port))
+ .await
+ .map_err(SmtpError::DirectConnectionFailed),
+ }
+ })
+ .await??;
+ let stream: Box<dyn AsyncTokioStream> = Box::new(stream);
+
+ let mut conn = self
+ .timed(
+ "connect handshake",
+ AsyncSmtpConnection::connect_with_transport(stream, &client_id),
+ )
+ .await?
+ .map_err(SmtpError::ConnectionFailure)?;
+ if matches!(config.connection, SmtpConnection::StartTls) {
+ let tls_parameters = TlsParameters::builder(config.host.clone())
+ .build()
+ .map_err(SmtpError::ConnectionFailure)?;
+ self.timed("STARTTLS", conn.starttls(tls_parameters, &client_id))
+ .await?
+ .map_err(SmtpError::ConnectionFailure)?;
+ }
+ Ok(conn)
+ }
+}
+
+/// Tunnels to the SMTP server through the proxy, trying each address the proxy resolves to.
+async fn connect_via_socks5(
+ socks5: &Socks5Config,
+ smtp_host: &str,
+ smtp_port: u16,
+) -> Result<TcpStream, SmtpError> {
+ let proxy_addrs = tokio::net::lookup_host((socks5.host.as_str(), socks5.port))
+ .await
+ .map_err(SmtpError::Socks5ProxyResolutionFailed)?;
+ let target = (smtp_host, smtp_port);
+
+ let mut last_error = SmtpError::Socks5ProxyResolutionFailed(std::io::Error::new(
+ std::io::ErrorKind::NotFound,
+ "proxy hostname resolved to no addresses",
+ ));
+ for proxy_addr in proxy_addrs {
+ let result = match socks5.username.as_ref().zip(socks5.password.as_ref()) {
+ Some((username, password)) => {
+ Socks5Stream::connect_with_password(proxy_addr, target, username, password).await
+ }
+ None => Socks5Stream::connect(proxy_addr, target).await,
+ };
+ match result {
+ Ok(stream) => return Ok(stream.into_inner()),
+ Err(error) => {
+ tracing::warn!(
+ ?error,
+ proxy_host = %socks5.host,
+ proxy_port = socks5.port,
+ %proxy_addr,
+ "SOCKS5 connection attempt failed, trying the next resolved address if any"
+ );
+ last_error = SmtpError::Socks5ConnectionFailed(error);
+ }
+ }
+ }
+ Err(last_error)
+}
+
+fn mailbox(address: String) -> Result<Mailbox, SmtpError> {
+ match address.parse() {
+ Ok(address) => Ok(Mailbox::new(None, address)),
+ Err(source) => Err(SmtpError::EmailParsingFailed { address, source }),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn debug_redacts_credentials() {
+ let config = SmtpConfig {
+ host: "smtp.example.com".to_owned(),
+ username: Some("user".to_owned()),
+ password: Some("hunter2".to_owned()),
+ ..SmtpConfig::default()
+ };
+ let config = SmtpConfig {
+ socks5: Some(Socks5Config {
+ host: "proxy.example.com".to_owned(),
+ username: Some("proxy-user".to_owned()),
+ password: Some("proxy-pass".to_owned()),
+ ..Socks5Config::default()
+ }),
+ ..config
+ };
+ let debug = format!("{config:?}");
+ assert!(debug.contains("smtp.example.com") && debug.contains("proxy.example.com"));
+ assert!(!debug.contains("user\"") && !debug.contains("hunter2"));
+ assert!(!debug.contains("proxy-user") && !debug.contains("proxy-pass"));
+ }
+
+ #[tokio::test]
+ async fn an_unparsable_address_names_itself() {
+ let client = SmtpClient::new(SmtpConfig::default());
+ let message = EmailMessage {
+ from: "not an address".to_owned(),
+ to: vec!["[email protected]".to_owned()],
+ cc: Vec::new(),
+ bcc: Vec::new(),
+ subject: "s".to_owned(),
+ html_body: "<p>b</p>".to_owned(),
+ };
+ match client.send(message).await {
+ Err(SmtpError::EmailParsingFailed { address, .. }) => {
+ assert_eq!(address, "not an address")
+ }
+ other => panic!("expected a parse failure, got {other:?}"),
+ }
+ }
+}
diff --git a/crates/cloud_services/src/kms.rs b/crates/cloud_services/src/kms.rs
new file mode 100644
index 0000000000..49ddc3a7c1
--- /dev/null
+++ b/crates/cloud_services/src/kms.rs
@@ -0,0 +1,17 @@
+//! Key management service clients.
+
+#[cfg(feature = "aws_kms")]
+pub mod aws;
+#[cfg(feature = "gcp_kms")]
+pub mod gcp;
+
+/// OCI Vault KMS client.
+///
+/// Re-exported from the standalone `oci_kms` crate, which other services already depend on by
+/// git, so it stays in place rather than moving here.
+#[cfg(feature = "oci_kms")]
+pub mod oci {
+ pub use oci_kms::{
+ DataKey, Environment, OciKmsClient, OciKmsConfig, OciKmsError, SystemEnvironment,
+ };
+}
diff --git a/crates/cloud_services/src/kms/aws.rs b/crates/cloud_services/src/kms/aws.rs
new file mode 100644
index 0000000000..b3bc000b86
--- /dev/null
+++ b/crates/cloud_services/src/kms/aws.rs
@@ -0,0 +1,191 @@
+//! Interactions with the AWS KMS SDK
+
+use aws_config::meta::region::RegionProviderChain;
+use aws_sdk_kms::{
+ config::Region,
+ error::SdkError,
+ operation::{decrypt::DecryptError, encrypt::EncryptError},
+ primitives::Blob,
+ Client,
+};
+use base64::Engine;
+
+/// Base64 engine used to encode ciphertext returned to, and decode ciphertext received from, callers.
+const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
+
+/// Configuration parameters required for constructing a [`AwsKmsClient`].
+#[derive(Clone, Debug, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct AwsKmsConfig {
+ /// The AWS key identifier of the KMS key used to encrypt or decrypt data.
+ pub key_id: Option<String>,
+
+ /// The AWS region to send KMS requests to.
+ pub region: String,
+}
+
+impl AwsKmsConfig {
+ /// Verifies that the [`AwsKmsClient`] configuration is usable.
+ pub fn validate(&self) -> Result<(), &'static str> {
+ if self.region.trim().is_empty() {
+ return Err("KMS AWS region must not be empty");
+ }
+
+ Ok(())
+ }
+}
+
+/// Client for AWS KMS operations.
+#[derive(Debug, Clone)]
+pub struct AwsKmsClient {
+ inner_client: Client,
+ key_id: Option<String>,
+}
+
+impl AwsKmsClient {
+ /// Constructs a new AWS KMS client.
+ pub async fn new(config: &AwsKmsConfig) -> Self {
+ let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
+ let sdk_config = aws_config::from_env().region(region_provider).load().await;
+
+ Self {
+ inner_client: Client::new(&sdk_config),
+ key_id: config.key_id.clone(),
+ }
+ }
+
+ /// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that
+ /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
+ /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
+ /// a machine that is able to assume an IAM role.
+ pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> Result<String, AwsKmsError> {
+ let data = BASE64_ENGINE
+ .decode(data)
+ .map_err(AwsKmsError::Base64DecodingFailed)?;
+ let ciphertext_blob = Blob::new(data);
+
+ let mut decryption_builder = self.inner_client.decrypt();
+
+ if let Some(key_id) = &self.key_id {
+ decryption_builder = decryption_builder.key_id(key_id);
+ }
+
+ let decrypt_output = decryption_builder
+ .ciphertext_blob(ciphertext_blob)
+ .send()
+ .await
+ .map_err(|error| AwsKmsError::DecryptionFailed(Box::new(error)))?;
+
+ decrypt_output
+ .plaintext
+ .ok_or(AwsKmsError::MissingPlaintextDecryptionOutput)
+ .and_then(|blob| {
+ String::from_utf8(blob.into_inner()).map_err(AwsKmsError::Utf8DecodingFailed)
+ })
+ }
+
+ /// Encrypts the provided String data using the AWS KMS SDK. We assume that
+ /// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
+ /// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
+ /// a machine that is able to assume an IAM role.
+ pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> Result<String, AwsKmsError> {
+ let plaintext_blob = Blob::new(data.as_ref());
+
+ let mut encryption_builder = self.inner_client.encrypt();
+
+ match &self.key_id {
+ Some(key_id) => encryption_builder = encryption_builder.key_id(key_id),
+ None => return Err(AwsKmsError::MissingKeyId),
+ };
+ let encrypted_output = encryption_builder
+ .plaintext(plaintext_blob)
+ .send()
+ .await
+ .map_err(|error| AwsKmsError::EncryptionFailed(Box::new(error)))?;
+
+ encrypted_output
+ .ciphertext_blob
+ .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
+ .map(|blob| BASE64_ENGINE.encode(blob.into_inner()))
+ }
+}
+
+/// Errors that could occur during KMS operations.
+#[derive(Debug, thiserror::Error)]
+pub enum AwsKmsError {
+ /// An error occurred when base64 decoding input data.
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed(#[source] base64::DecodeError),
+
+ /// An error occurred when AWS KMS decrypting input data.
+ #[error("Failed to AWS KMS decrypt input data")]
+ DecryptionFailed(#[source] Box<SdkError<DecryptError>>),
+
+ /// An error occurred when AWS KMS encrypting input data.
+ #[error("Failed to AWS KMS encrypt input data")]
+ EncryptionFailed(#[source] Box<SdkError<EncryptError>>),
+
+ /// The AWS KMS decrypted output does not include a plaintext output.
+ #[error("Missing plaintext AWS KMS decryption output")]
+ MissingPlaintextDecryptionOutput,
+
+ /// The AWS KMS encrypted output does not include a ciphertext output.
+ #[error("Missing ciphertext AWS KMS encryption output")]
+ MissingCiphertextEncryptionOutput,
+
+ /// An error occurred UTF-8 decoding AWS KMS decrypted output.
+ #[error("Failed to UTF-8 decode decryption output")]
+ Utf8DecodingFailed(#[source] std::string::FromUtf8Error),
+
+ /// AWS KMS key id not provided.
+ #[error("AWS KMS key id not provided")]
+ MissingKeyId,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn config(key_id: Option<&str>) -> AwsKmsConfig {
+ AwsKmsConfig {
+ key_id: key_id.map(ToOwned::to_owned),
+ region: "us-east-1".to_owned(),
+ }
+ }
+
+ #[test]
+ fn validate_requires_region() {
+ assert!(config(None).validate().is_ok());
+ for region in ["", " "] {
+ let config = AwsKmsConfig {
+ key_id: None,
+ region: region.to_owned(),
+ };
+ assert_eq!(config.validate(), Err("KMS AWS region must not be empty"));
+ }
+ }
+
+ #[tokio::test]
+ async fn decrypt_rejects_invalid_base64_before_calling_kms() {
+ let client = AwsKmsClient::new(&config(Some("key"))).await;
+
+ let error = client.decrypt("not base64!").await.err();
+
+ assert!(
+ matches!(error, Some(AwsKmsError::Base64DecodingFailed(_))),
+ "{error:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn encrypt_requires_key_id_before_calling_kms() {
+ let client = AwsKmsClient::new(&config(None)).await;
+
+ let error = client.encrypt("hello").await.err();
+
+ assert!(
+ matches!(error, Some(AwsKmsError::MissingKeyId)),
+ "{error:?}"
+ );
+ }
+}
diff --git a/crates/cloud_services/src/kms/gcp.rs b/crates/cloud_services/src/kms/gcp.rs
new file mode 100644
index 0000000000..1a2b981624
--- /dev/null
+++ b/crates/cloud_services/src/kms/gcp.rs
@@ -0,0 +1,204 @@
+//! Interactions with the GCP Cloud KMS SDK
+
+use base64::Engine;
+use google_cloud_gax::{conn::Error as ConnectionError, grpc::Status};
+use google_cloud_kms::{
+ client::{google_cloud_auth::error::Error as AuthError, Client, ClientConfig},
+ grpc::kms::v1::{DecryptRequest, EncryptRequest},
+};
+
+/// Base64 engine used to encode ciphertext returned to, and decode ciphertext received from, callers.
+const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
+
+/// Configuration parameters required for constructing a [`GcpKmsClient`].
+#[derive(Clone, Debug, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct GcpKmsConfig {
+ /// The GCP project ID that owns the KMS key ring.
+ pub project_id: String,
+
+ /// The location ID (e.g. `"global"`, `"us-east1"`) of the KMS key ring.
+ pub location_id: String,
+
+ /// The ID of the KMS key ring.
+ pub key_ring_id: String,
+
+ /// The ID of the KMS key used to encrypt or decrypt data.
+ pub key_id: String,
+}
+
+impl GcpKmsConfig {
+ /// Verifies that the [`GcpKmsConfig`] is valid.
+ pub fn validate(&self) -> Result<(), &'static str> {
+ if self.project_id.trim().is_empty() {
+ return Err("GCP KMS project ID must not be empty");
+ }
+
+ if self.location_id.trim().is_empty() {
+ return Err("GCP KMS location ID must not be empty");
+ }
+
+ if self.key_ring_id.trim().is_empty() {
+ return Err("GCP KMS key ring ID must not be empty");
+ }
+
+ if self.key_id.trim().is_empty() {
+ return Err("GCP KMS key ID must not be empty");
+ }
+
+ Ok(())
+ }
+
+ /// Resource name of the configured key.
+ fn key_name(&self) -> String {
+ format!(
+ "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}",
+ self.project_id, self.location_id, self.key_ring_id, self.key_id
+ )
+ }
+}
+
+/// Client for GCP Cloud KMS operations.
+#[derive(Clone, Debug)]
+pub struct GcpKmsClient {
+ inner_client: Client,
+ key_name: String,
+}
+
+impl GcpKmsClient {
+ /// Constructs a new GCP KMS client with ambient credentials, targeting the KMS key
+ /// identified by the provided [`GcpKmsConfig`].
+ pub async fn new(config: &GcpKmsConfig) -> Result<Self, GcpKmsError> {
+ let client_config = ClientConfig::default()
+ .with_auth()
+ .await
+ .map_err(GcpKmsError::CredentialsUnavailable)?;
+ let inner_client = Client::new(client_config)
+ .await
+ .map_err(GcpKmsError::ClientCreationFailed)?;
+ Ok(Self {
+ inner_client,
+ key_name: config.key_name(),
+ })
+ }
+
+ /// Decrypts base64-encoded ciphertext via GCP Cloud KMS.
+ pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> Result<String, GcpKmsError> {
+ let ciphertext = BASE64_ENGINE
+ .decode(data)
+ .map_err(GcpKmsError::Base64DecodingFailed)?;
+
+ let request = DecryptRequest {
+ name: self.key_name.clone(),
+ ciphertext,
+ additional_authenticated_data: Vec::new(),
+ ciphertext_crc32c: None,
+ additional_authenticated_data_crc32c: None,
+ };
+
+ let response = self
+ .inner_client
+ .decrypt(request, None)
+ .await
+ .map_err(|status| GcpKmsError::DecryptionFailed(Box::new(status)))?;
+
+ String::from_utf8(response.plaintext).map_err(GcpKmsError::Utf8DecodingFailed)
+ }
+
+ /// Encrypts data via GCP Cloud KMS, returning base64-encoded ciphertext.
+ pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> Result<String, GcpKmsError> {
+ let request = EncryptRequest {
+ name: self.key_name.clone(),
+ plaintext: data.as_ref().to_vec(),
+ additional_authenticated_data: Vec::new(),
+ plaintext_crc32c: None,
+ additional_authenticated_data_crc32c: None,
+ };
+
+ let response = self
+ .inner_client
+ .encrypt(request, None)
+ .await
+ .map_err(|status| GcpKmsError::EncryptionFailed(Box::new(status)))?;
+
+ Ok(BASE64_ENGINE.encode(response.ciphertext))
+ }
+}
+
+/// Errors that could occur during GCP KMS operations.
+#[derive(Debug, thiserror::Error)]
+pub enum GcpKmsError {
+ /// An error occurred when base64 decoding the input data.
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed(#[source] base64::DecodeError),
+
+ /// An error occurred when GCP KMS decrypting the input data.
+ #[error("Failed to GCP KMS decrypt input data")]
+ DecryptionFailed(#[source] Box<Status>),
+
+ /// An error occurred when GCP KMS encrypting the input data.
+ #[error("Failed to GCP KMS encrypt input data")]
+ EncryptionFailed(#[source] Box<Status>),
+
+ /// An error occurred UTF-8 decoding the GCP KMS decrypted output.
+ #[error("Failed UTF-8 decode of GCP KMS decrypted output")]
+ Utf8DecodingFailed(#[source] std::string::FromUtf8Error),
+
+ /// Ambient GCP credentials could not be loaded while creating the client.
+ #[error("Failed to load GCP credentials for the KMS client")]
+ CredentialsUnavailable(#[source] AuthError),
+
+ /// An error occurred when creating the GCP KMS client.
+ #[error("Failed to create GCP KMS client")]
+ ClientCreationFailed(#[source] ConnectionError),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn config() -> GcpKmsConfig {
+ GcpKmsConfig {
+ project_id: "project".to_owned(),
+ location_id: "global".to_owned(),
+ key_ring_id: "key-ring".to_owned(),
+ key_id: "key".to_owned(),
+ }
+ }
+
+ #[test]
+ fn validate_reports_the_first_missing_field() {
+ assert!(config().validate().is_ok());
+
+ type ClearField = fn(&mut GcpKmsConfig);
+
+ let cases: [(ClearField, &str); 4] = [
+ (
+ |c| c.project_id = " ".to_owned(),
+ "GCP KMS project ID must not be empty",
+ ),
+ (
+ |c| c.location_id.clear(),
+ "GCP KMS location ID must not be empty",
+ ),
+ (
+ |c| c.key_ring_id.clear(),
+ "GCP KMS key ring ID must not be empty",
+ ),
+ (|c| c.key_id.clear(), "GCP KMS key ID must not be empty"),
+ ];
+ for (clear_field, message) in cases {
+ let mut config = config();
+ clear_field(&mut config);
+ assert_eq!(config.validate(), Err(message));
+ }
+ }
+
+ #[test]
+ fn key_name_is_the_full_resource_name() {
+ assert_eq!(
+ config().key_name(),
+ "projects/project/locations/global/keyRings/key-ring/cryptoKeys/key"
+ );
+ }
+}
diff --git a/crates/cloud_services/src/lib.rs b/crates/cloud_services/src/lib.rs
new file mode 100644
index 0000000000..3db035476e
--- /dev/null
+++ b/crates/cloud_services/src/lib.rs
@@ -0,0 +1,23 @@
+//! Cloud provider clients shared across Hyperswitch services.
+//!
+//! Each backend sits behind its own Cargo feature, so a service only compiles the providers it
+//! uses:
+//!
+//! | Feature | Module | Backend |
+//! |----------------------|------------------|---------------------------------------------------|
+//! | `s3` | [`storage::s3`] | AWS S3 |
+//! | `oci_object_storage` | [`storage::oci`] | OCI Object Storage, through its S3-compatible API |
+//! | `aws_kms` | [`kms::aws`] | AWS KMS |
+//! | `gcp_kms` | [`kms::gcp`] | GCP Cloud KMS |
+//! | `oci_kms` | [`kms::oci`] | OCI Vault KMS |
+//! | `ses` | [`email::ses`] | AWS SES, as an STS-assumed role |
+//! | `smtp` | [`email::smtp`] | Any SMTP server (OCI Email Delivery, SendGrid, …) |
+//!
+//! Errors are plain [`std::error::Error`] types so callers can wrap them in whatever error
+//! handling they use.
+
+#![warn(missing_docs, missing_debug_implementations)]
+
+pub mod email;
+pub mod kms;
+pub mod storage;
diff --git a/crates/cloud_services/src/storage.rs b/crates/cloud_services/src/storage.rs
new file mode 100644
index 0000000000..5bb650831a
--- /dev/null
+++ b/crates/cloud_services/src/storage.rs
@@ -0,0 +1,11 @@
+//! Object storage clients.
+
+#[cfg(feature = "oci_object_storage")]
+pub mod oci;
+#[cfg(feature = "s3")]
+pub mod s3;
+
+/// A storage configuration value that is missing or malformed.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("{0}")]
+pub struct InvalidStorageConfig(&'static str);
diff --git a/crates/cloud_services/src/storage/oci.rs b/crates/cloud_services/src/storage/oci.rs
new file mode 100644
index 0000000000..18f115a81c
--- /dev/null
+++ b/crates/cloud_services/src/storage/oci.rs
@@ -0,0 +1,156 @@
+//! OCI Object Storage, accessed through its Amazon S3 Compatibility API.
+
+use super::{
+ s3::{S3Endpoint, S3Storage},
+ InvalidStorageConfig,
+};
+
+/// Configuration for OCI Object Storage.
+///
+/// Requests go to the S3 Compatibility API endpoint of the namespace and region, with the bucket
+/// in the path, since OCI's TLS certificate does not cover bucket subdomains. Authenticate with an
+/// OCI Customer Secret Key, through `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`.
+#[derive(Debug, serde::Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct OciObjectStorageConfig {
+ /// The Object Storage namespace of the tenancy
+ namespace: String,
+ /// The OCI region identifier of the bucket, such as `us-ashburn-1`
+ region: String,
+ /// The bucket to send file uploads
+ bucket_name: String,
+}
+
+impl OciObjectStorageConfig {
+ /// Validates the OCI Object Storage configuration, returning a description of the first
+ /// problem.
+ pub fn validate(&self) -> Result<(), InvalidStorageConfig> {
+ if !is_hostname_label(&self.namespace) {
+ return Err(InvalidStorageConfig("oci object storage namespace must be non-empty and contain only letters, digits and hyphens"));
+ }
+
+ if !is_hostname_label(&self.region) {
+ return Err(InvalidStorageConfig("oci object storage region must be non-empty and contain only letters, digits and hyphens"));
+ }
+
+ if self.bucket_name.trim().is_empty() {
+ return Err(InvalidStorageConfig(
+ "oci object storage bucket name must not be empty",
+ ));
+ }
+
+ Ok(())
+ }
+
+ /// The S3 Compatibility API endpoint of the namespace and region, addressed path-style.
+ fn endpoint(&self) -> S3Endpoint {
+ S3Endpoint {
+ url: Some(format!(
+ "https://{}.compat.objectstorage.{}.oraclecloud.com",
+ self.namespace, self.region
+ )),
+ force_path_style: true,
+ }
+ }
+}
+
+/// Whether `value` can be used as one label of the endpoint host name.
+fn is_hostname_label(value: &str) -> bool {
+ !value.is_empty()
+ && value
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || character == '-')
+}
+
+impl S3Storage {
+ /// Creates a file storage client for OCI Object Storage.
+ pub async fn new_oci(config: &OciObjectStorageConfig) -> Self {
+ Self::with_endpoint(&config.region, &config.bucket_name, &config.endpoint()).await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::storage::s3::tests::presigned_url;
+
+ fn config(namespace: &str, region: &str, bucket_name: &str) -> OciObjectStorageConfig {
+ OciObjectStorageConfig {
+ namespace: namespace.to_owned(),
+ region: region.to_owned(),
+ bucket_name: bucket_name.to_owned(),
+ }
+ }
+
+ #[test]
+ fn validate_rejects_values_that_do_not_fit_the_endpoint() {
+ assert_eq!(
+ config("namespace", "ap-hyderabad-1", "bucket").validate(),
+ Ok(())
+ );
+
+ for (config, message) in [
+ (
+ config("", "ap-hyderabad-1", "bucket"),
+ "oci object storage namespace",
+ ),
+ (
+ config("name.space", "ap-hyderabad-1", "bucket"),
+ "oci object storage namespace",
+ ),
+ (
+ config("namespace", "", "bucket"),
+ "oci object storage region",
+ ),
+ (
+ config("namespace", "ap-hyderabad-1/x", "bucket"),
+ "oci object storage region",
+ ),
+ (
+ config("namespace", "ap-hyderabad-1", " "),
+ "oci object storage bucket name",
+ ),
+ ] {
+ let error = config.validate().err();
+ assert!(
+ error
+ .as_ref()
+ .is_some_and(|error| error.0.starts_with(message)),
+ "{config:?}: {error:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn addresses_the_bucket_in_the_path_of_the_compatibility_endpoint() {
+ let config = config("namespace", "ap-hyderabad-1", "bucket");
+
+ let url = presigned_url(&config.endpoint(), &config.bucket_name, None).await;
+
+ assert!(
+ url.starts_with(
+ "https://namespace.compat.objectstorage.ap-hyderabad-1.oraclecloud.com/bucket/files/file_key?"
+ ),
+ "{url}"
+ );
+ }
+
+ #[tokio::test]
+ async fn ignores_an_endpoint_from_the_environment() {
+ let config = config("namespace", "ap-hyderabad-1", "bucket");
+
+ let url = presigned_url(
+ &config.endpoint(),
+ &config.bucket_name,
+ Some("https://endpoint.from.env"),
+ )
+ .await;
+
+ assert!(
+ url.starts_with(
+ "https://namespace.compat.objectstorage.ap-hyderabad-1.oraclecloud.com/bucket/"
+ ),
+ "{url}"
+ );
+ }
+}
diff --git a/crates/cloud_services/src/storage/s3.rs b/crates/cloud_services/src/storage/s3.rs
new file mode 100644
index 0000000000..58123e4610
--- /dev/null
+++ b/crates/cloud_services/src/storage/s3.rs
@@ -0,0 +1,404 @@
+//! S3 object storage, for AWS S3 and S3-compatible stores such as OCI Object Storage.
+
+use aws_config::{meta::region::RegionProviderChain, Region};
+use aws_sdk_s3::{
+ operation::{
+ abort_multipart_upload::AbortMultipartUploadError,
+ complete_multipart_upload::CompleteMultipartUploadError,
+ create_multipart_upload::CreateMultipartUploadError, delete_object::DeleteObjectError,
+ get_object::GetObjectError, put_object::PutObjectError, upload_part::UploadPartError,
+ },
+ presigning::{PresigningConfig, PresigningConfigError},
+ types::{CompletedMultipartUpload, CompletedPart},
+ Client,
+};
+
+use super::InvalidStorageConfig;
+
+/// Configuration for AWS S3 file storage.
+#[derive(Debug, serde::Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct S3StorageConfig {
+ /// The AWS region to send file uploads
+ region: String,
+ /// The AWS s3 bucket to send file uploads
+ bucket_name: String,
+}
+
+impl S3StorageConfig {
+ /// Validates the S3 file storage configuration, returning a description of the first problem.
+ pub fn validate(&self) -> Result<(), InvalidStorageConfig> {
+ if self.region.trim().is_empty() {
+ return Err(InvalidStorageConfig("aws s3 region must not be empty"));
+ }
+
+ if self.bucket_name.trim().is_empty() {
+ return Err(InvalidStorageConfig("aws s3 bucket name must not be empty"));
+ }
+
+ Ok(())
+ }
+}
+
+/// Where the S3 client sends requests, for S3-compatible stores other than AWS S3 itself.
+#[derive(Debug, Clone, Default)]
+pub(crate) struct S3Endpoint {
+ /// Endpoint URL of the store. When unset, the endpoint is resolved from the region or
+ /// `AWS_ENDPOINT_URL_S3`, as for AWS S3.
+ pub(crate) url: Option<String>,
+ /// Addresses buckets as `<endpoint>/<bucket>` rather than `<bucket>.<endpoint>`, for stores
+ /// whose TLS certificate does not cover bucket subdomains.
+ pub(crate) force_path_style: bool,
+}
+
+/// Builds the S3 client, applying the endpoint overrides on top of the SDK config. With the
+/// default [`S3Endpoint`] this is the same client as `Client::new(sdk_config)`.
+fn build_client(endpoint: &S3Endpoint, sdk_config: &aws_config::SdkConfig) -> Client {
+ let mut s3_config = aws_sdk_s3::config::Builder::from(sdk_config);
+ if let Some(url) = &endpoint.url {
+ s3_config = s3_config.endpoint_url(url);
+ }
+ if endpoint.force_path_style {
+ s3_config = s3_config.force_path_style(true);
+ }
+ Client::from_conf(s3_config.build())
+}
+
+/// S3 file storage client.
+#[derive(Debug, Clone)]
+pub struct S3Storage {
+ /// AWS S3 client
+ inner_client: Client,
+ /// The name of the AWS S3 bucket.
+ bucket_name: String,
+}
+
+impl S3Storage {
+ /// Creates a new AWS S3 file storage client.
+ pub async fn new(config: &S3StorageConfig) -> Self {
+ Self::with_endpoint(&config.region, &config.bucket_name, &S3Endpoint::default()).await
+ }
+
+ /// Creates a client for an S3-compatible store reached through `endpoint`.
+ pub(crate) async fn with_endpoint(
+ region: &str,
+ bucket_name: &str,
+ endpoint: &S3Endpoint,
+ ) -> Self {
+ let region_provider = RegionProviderChain::first_try(Region::new(region.to_owned()));
+ let sdk_config = aws_config::from_env().region(region_provider).load().await;
+ Self {
+ inner_client: build_client(endpoint, &sdk_config),
+ bucket_name: bucket_name.to_owned(),
+ }
+ }
+
+ /// Uploads a file to AWS S3.
+ pub async fn upload_file(&self, file_key: &str, file: Vec<u8>) -> Result<(), S3StorageError> {
+ self.inner_client
+ .put_object()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .body(file.into())
+ .send()
+ .await
+ .map_err(|error| S3StorageError::UploadFailure(Box::new(error)))?;
+ Ok(())
+ }
+
+ /// Deletes a file from AWS S3.
+ pub async fn delete_file(&self, file_key: &str) -> Result<(), S3StorageError> {
+ self.inner_client
+ .delete_object()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .send()
+ .await
+ .map_err(|error| S3StorageError::DeleteFailure(Box::new(error)))?;
+ Ok(())
+ }
+
+ /// Retrieves a file from AWS S3.
+ pub async fn retrieve_file(&self, file_key: &str) -> Result<Vec<u8>, S3StorageError> {
+ Ok(self
+ .inner_client
+ .get_object()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .send()
+ .await
+ .map_err(|error| S3StorageError::RetrieveFailure(Box::new(error)))?
+ .body
+ .collect()
+ .await
+ .map_err(S3StorageError::UnknownError)?
+ .to_vec())
+ }
+
+ /// Begins a multipart upload on AWS S3.
+ pub async fn create_multipart_upload(&self, file_key: &str) -> Result<String, S3StorageError> {
+ self.inner_client
+ .create_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .content_type("text/csv")
+ .send()
+ .await
+ .map_err(|error| S3StorageError::MultipartCreateFailure(Box::new(error)))?
+ .upload_id
+ .ok_or(S3StorageError::MissingUploadId)
+ }
+
+ /// Uploads a single part of an in-progress multipart upload to AWS S3.
+ pub async fn upload_part(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ part_number: i32,
+ body: Vec<u8>,
+ ) -> Result<String, S3StorageError> {
+ self.inner_client
+ .upload_part()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .part_number(part_number)
+ .body(body.into())
+ .send()
+ .await
+ .map_err(|error| S3StorageError::MultipartUploadPartFailure(Box::new(error)))?
+ .e_tag
+ .ok_or(S3StorageError::MissingPartETag)
+ }
+
+ /// Assembles the uploaded parts into a single S3 object, in part number order.
+ pub async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ parts: Vec<(i32, String)>,
+ ) -> Result<Option<String>, S3StorageError> {
+ let completed_parts = parts
+ .into_iter()
+ .map(|(part_number, e_tag)| {
+ CompletedPart::builder()
+ .part_number(part_number)
+ .e_tag(e_tag)
+ .build()
+ })
+ .collect();
+
+ Ok(self
+ .inner_client
+ .complete_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .multipart_upload(
+ CompletedMultipartUpload::builder()
+ .set_parts(Some(completed_parts))
+ .build(),
+ )
+ .send()
+ .await
+ .map_err(|error| S3StorageError::MultipartCompleteFailure(Box::new(error)))?
+ .expiration)
+ }
+
+ /// Discards an in-progress multipart upload and the parts already uploaded for it.
+ pub async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ ) -> Result<(), S3StorageError> {
+ self.inner_client
+ .abort_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .send()
+ .await
+ .map_err(|error| S3StorageError::MultipartAbortFailure(Box::new(error)))?;
+ Ok(())
+ }
+
+ /// Signs a time-limited GET for the object with the client's current credentials.
+ pub async fn get_presigned_download_url(
+ &self,
+ file_key: &str,
+ expires_in: std::time::Duration,
+ download_file_name: Option<&str>,
+ ) -> Result<url::Url, S3StorageError> {
+ let presigning_config = PresigningConfig::expires_in(expires_in)
+ .map_err(S3StorageError::PresigningConfigFailure)?;
+
+ let request = self
+ .inner_client
+ .get_object()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .response_content_type("text/csv");
+
+ let request = match download_file_name {
+ Some(name) => {
+ request.response_content_disposition(format!("attachment; filename=\"{name}\""))
+ }
+ None => request,
+ };
+
+ let presigned = request
+ .presigned(presigning_config)
+ .await
+ .map_err(|error| S3StorageError::PresignFailure(Box::new(error)))?;
+
+ url::Url::parse(presigned.uri()).map_err(S3StorageError::PresignedUrlParseFailure)
+ }
+}
+
+/// Errors that can occur during S3 file storage operations.
+#[derive(Debug, thiserror::Error)]
+pub enum S3StorageError {
+ /// Error indicating that file upload to S3 failed.
+ #[error("File upload to S3 failed: {0:?}")]
+ UploadFailure(Box<aws_sdk_s3::error::SdkError<PutObjectError>>),
+
+ /// Error indicating that file retrieval from S3 failed.
+ #[error("File retrieve from S3 failed: {0:?}")]
+ RetrieveFailure(Box<aws_sdk_s3::error::SdkError<GetObjectError>>),
+
+ /// Error indicating that file deletion from S3 failed.
+ #[error("File delete from S3 failed: {0:?}")]
+ DeleteFailure(Box<aws_sdk_s3::error::SdkError<DeleteObjectError>>),
+
+ /// Unknown error occurred.
+ #[error("Unknown error occurred: {0:?}")]
+ UnknownError(aws_sdk_s3::primitives::ByteStreamError),
+
+ /// Error indicating that starting a multipart upload on S3 failed.
+ #[error("Multipart upload create on S3 failed: {0:?}")]
+ MultipartCreateFailure(Box<aws_sdk_s3::error::SdkError<CreateMultipartUploadError>>),
+
+ /// Error indicating that uploading a part to S3 failed.
+ #[error("Multipart part upload to S3 failed: {0:?}")]
+ MultipartUploadPartFailure(Box<aws_sdk_s3::error::SdkError<UploadPartError>>),
+
+ /// Error indicating that assembling a multipart upload on S3 failed.
+ #[error("Multipart upload complete on S3 failed: {0:?}")]
+ MultipartCompleteFailure(Box<aws_sdk_s3::error::SdkError<CompleteMultipartUploadError>>),
+
+ /// Error indicating that discarding a multipart upload on S3 failed.
+ #[error("Multipart upload abort on S3 failed: {0:?}")]
+ MultipartAbortFailure(Box<aws_sdk_s3::error::SdkError<AbortMultipartUploadError>>),
+
+ /// Error indicating S3 accepted the multipart upload but returned no upload id.
+ #[error("S3 did not return an upload id for the multipart upload")]
+ MissingUploadId,
+
+ /// Error indicating S3 accepted the part but returned no entity tag.
+ #[error("S3 did not return an entity tag for the uploaded part")]
+ MissingPartETag,
+
+ /// Error indicating the presigning configuration was rejected by the SDK.
+ #[error("Presigning configuration was rejected: {0:?}")]
+ PresigningConfigFailure(PresigningConfigError),
+
+ /// Error indicating that presigning a GET request failed.
+ #[error("Presigning an S3 get request failed: {0:?}")]
+ PresignFailure(Box<aws_sdk_s3::error::SdkError<GetObjectError>>),
+
+ /// Error indicating the presigned URI could not be parsed as a URL.
+ #[error("Presigned URI is not a valid URL: {0}")]
+ PresignedUrlParseFailure(url::ParseError),
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use std::time::Duration;
+
+ use aws_sdk_s3::config::{BehaviorVersion, Credentials, SharedCredentialsProvider};
+
+ use super::*;
+
+ fn sdk_config(endpoint_url: Option<&str>) -> aws_config::SdkConfig {
+ let builder = aws_config::SdkConfig::builder()
+ .behavior_version(BehaviorVersion::latest())
+ .region(Region::new("ap-hyderabad-1"))
+ .credentials_provider(SharedCredentialsProvider::new(Credentials::new(
+ "access_key",
+ "secret_key",
+ None,
+ None,
+ "test",
+ )));
+ match endpoint_url {
+ Some(endpoint_url) => builder.endpoint_url(endpoint_url).build(),
+ None => builder.build(),
+ }
+ }
+
+ /// Presigns a download of `files/file_key`, which shows where the client sends requests
+ /// without any network call.
+ pub(crate) async fn presigned_url(
+ endpoint: &S3Endpoint,
+ bucket_name: &str,
+ sdk_endpoint_url: Option<&str>,
+ ) -> String {
+ #[allow(clippy::expect_used)]
+ let presigning_config =
+ PresigningConfig::expires_in(Duration::from_secs(60)).expect("valid presigning config");
+
+ #[allow(clippy::expect_used)]
+ build_client(endpoint, &sdk_config(sdk_endpoint_url))
+ .get_object()
+ .bucket(bucket_name)
+ .key("files/file_key")
+ .presigned(presigning_config)
+ .await
+ .expect("presigning is local and should succeed")
+ .uri()
+ .to_owned()
+ }
+
+ #[test]
+ fn validate_requires_region_and_bucket() {
+ let config = |region: &str, bucket_name: &str| S3StorageConfig {
+ region: region.to_owned(),
+ bucket_name: bucket_name.to_owned(),
+ };
+
+ assert_eq!(config("us-east-1", "bucket").validate(), Ok(()));
+ assert_eq!(
+ config(" ", "bucket").validate(),
+ Err(InvalidStorageConfig("aws s3 region must not be empty"))
+ );
+ assert_eq!(
+ config("us-east-1", "").validate(),
+ Err(InvalidStorageConfig("aws s3 bucket name must not be empty"))
+ );
+ }
+
+ #[tokio::test]
+ async fn aws_config_uses_virtual_hosted_aws_endpoint() {
+ let url = presigned_url(&S3Endpoint::default(), "bucket", None).await;
+
+ assert!(
+ url.starts_with("https://bucket.s3.ap-hyderabad-1.amazonaws.com/files/file_key?"),
+ "{url}"
+ );
+ }
+
+ #[tokio::test]
+ async fn endpoint_from_environment_is_kept_when_not_overridden() {
+ let endpoint = S3Endpoint {
+ url: None,
+ force_path_style: true,
+ };
+
+ let url = presigned_url(&endpoint, "bucket", Some("https://endpoint.from.env")).await;
+
+ assert!(
+ url.starts_with("https://endpoint.from.env/bucket/files/file_key?"),
+ "{url}"
+ );
+ }
+}
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index b7dd0d473c..015805234c 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -8,12 +8,12 @@ readme = "README.md"
license.workspace = true
[features]
-aws_kms = ["dep:aws-config", "dep:aws-sdk-kms"]
-email = ["dep:aws-config"]
-aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]
-oci_object_storage = ["dep:aws-config", "dep:aws-sdk-s3"]
-gcp_kms = ["dep:google-cloud-kms"]
-oci_kms = ["dep:oci_kms"]
+aws_kms = ["dep:cloud_services", "cloud_services/aws_kms"]
+email = ["dep:cloud_services", "cloud_services/ses", "cloud_services/smtp"]
+aws_s3 = ["dep:cloud_services", "cloud_services/s3"]
+oci_object_storage = ["dep:cloud_services", "cloud_services/oci_object_storage"]
+gcp_kms = ["dep:cloud_services", "cloud_services/gcp_kms"]
+oci_kms = ["dep:cloud_services", "cloud_services/oci_kms"]
hashicorp-vault = ["dep:vaultrs"]
superposition = [
"dep:open-feature",
@@ -55,25 +55,13 @@ dynamic_routing = [
[dependencies]
async-trait = "0.1.92"
-aws-config = { version = "1.5.10", optional = true, features = [
- "behavior-version-latest",
-] }
-aws-sdk-kms = { version = "1.51.0", optional = true }
-aws-sdk-sesv2 = "1.57.0"
-aws-sdk-sts = "1.51.0"
-aws-sdk-s3 = { version = "1.65.0", optional = true }
-aws-smithy-runtime = "1.8.3"
-aws-smithy-runtime-api = { version = "1.7", features = ["client"] }
aws-smithy-types = "1.3.1"
base64 = "0.22.1"
dyn-clone = "1.0.19"
-google-cloud-kms = { version = "0.6.0", optional = true }
deja = { git = "https://github.com/juspay/deja", rev = "6ace82f8d37c7c5703f9636a608dd8d85a8f6953", optional = true, default-features = false }
error-stack = "0.4.1"
hex = "0.4.3"
hyper = "0.14.32"
-hyper-proxy = "0.9.1"
-lettre = { version = "0.11.16", features = ["tokio1", "tokio1-native-tls"] }
once_cell = "1.21.3"
serde = { version = "1.0.219", features = ["derive"] }
thiserror = "1.0.69"
@@ -85,7 +73,6 @@ prost-reflect = { version = "0.16.5", features = ["serde"], optional = true }
prost-types = { version = "0.14", optional = true }
time = { version = "0.3.41", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.48.0", features = ["net", "io-util", "time", "sync"] }
-tokio-socks = "0.5"
tonic = "0.14"
tonic-prost = { version = "0.14", optional = true }
tonic-reflection = "0.14.0"
@@ -112,7 +99,7 @@ superposition_sdk = { version = "0.115.5", optional = true }
common_utils = { version = "0.1.0", path = "../common_utils" }
common_enums = { version = "0.1.0", path = "../common_enums" }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
-oci_kms = { version = "0.1.0", path = "../oci_kms", optional = true }
+cloud_services = { version = "0.1.0", path = "../cloud_services", optional = true }
hyperswitch_masking = "0.0.1"
router_env = { version = "0.1.0", path = "../router_env", features = [
"log_extra_implicit_fields",
diff --git a/crates/external_services/src/aws_kms/core.rs b/crates/external_services/src/aws_kms/core.rs
index af2bf2c12d..933f67c13a 100644
--- a/crates/external_services/src/aws_kms/core.rs
+++ b/crates/external_services/src/aws_kms/core.rs
@@ -1,43 +1,28 @@
//! Interactions with the AWS KMS SDK
+//!
+//! Hyperswitch adapter over the shared [`cloud_services::kms::aws`] client: it adds logging,
+//! metrics and `error-stack` reports on top of the plain client.
use std::time::Instant;
-use aws_config::meta::region::RegionProviderChain;
-use aws_sdk_kms::{config::Region, primitives::Blob, Client};
-use base64::Engine;
+use cloud_services::kms::aws as shared;
+pub use cloud_services::kms::aws::{AwsKmsConfig, AwsKmsError};
use common_utils::errors::CustomResult;
-use error_stack::{report, ResultExt};
use router_env::logger;
-use crate::{consts, metrics};
-
-/// Configuration parameters required for constructing a [`AwsKmsClient`].
-#[derive(Clone, Debug, Default, serde::Deserialize)]
-#[serde(default)]
-pub struct AwsKmsConfig {
- /// The AWS key identifier of the KMS key used to encrypt or decrypt data.
- pub key_id: Option<String>,
-
- /// The AWS region to send KMS requests to.
- pub region: String,
-}
+use crate::{metrics, report_with_cause};
/// Client for AWS KMS operations.
#[derive(Debug, Clone)]
pub struct AwsKmsClient {
- inner_client: Client,
- key_id: Option<String>,
+ inner: shared::AwsKmsClient,
}
impl AwsKmsClient {
/// Constructs a new AWS KMS client.
pub async fn new(config: &AwsKmsConfig) -> Self {
- let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
- let sdk_config = aws_config::from_env().region(region_provider).load().await;
-
Self {
- inner_client: Client::new(&sdk_config),
- key_id: config.key_id.clone(),
+ inner: shared::AwsKmsClient::new(config).await,
}
}
@@ -47,35 +32,16 @@ impl AwsKmsClient {
/// a machine that is able to assume an IAM role.
pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
- let data = consts::BASE64_ENGINE
- .decode(data)
- .change_context(AwsKmsError::Base64DecodingFailed)?;
- let ciphertext_blob = Blob::new(data);
-
- let mut decryption_builder = self.inner_client.decrypt();
- if let Some(key_id) = &self.key_id {
- decryption_builder = decryption_builder.key_id(key_id);
- }
-
- let decrypt_output = decryption_builder
- .ciphertext_blob(ciphertext_blob)
- .send()
- .await
- .inspect_err(|error| {
+ let output = self.inner.decrypt(data).await.map_err(|error| {
+ if let AwsKmsError::DecryptionFailed(sdk_error) = &error {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
- logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data");
+ logger::error!(aws_kms_sdk_error=?sdk_error, "Failed to AWS KMS decrypt data");
metrics::AWS_KMS_DECRYPTION_FAILURES.add(1, &[]);
- })
- .change_context(AwsKmsError::DecryptionFailed)?;
-
- let output = decrypt_output
- .plaintext
- .ok_or(report!(AwsKmsError::MissingPlaintextDecryptionOutput))
- .and_then(|blob| {
- String::from_utf8(blob.into_inner()).change_context(AwsKmsError::Utf8DecodingFailed)
- })?;
+ }
+ report_with_cause(error)
+ })?;
let time_taken = start.elapsed();
metrics::AWS_KMS_DECRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
@@ -89,32 +55,17 @@ impl AwsKmsClient {
/// a machine that is able to assume an IAM role.
pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
- let plaintext_blob = Blob::new(data.as_ref());
-
- let mut encryption_builder = self.inner_client.encrypt();
- match &self.key_id {
- Some(key_id) => encryption_builder = encryption_builder.key_id(key_id),
- None => {
- return Err(report!(AwsKmsError::MissingKeyId));
- }
- };
- let encrypted_output = encryption_builder
- .plaintext(plaintext_blob)
- .send()
- .await
- .inspect_err(|error| {
+ let output = self.inner.encrypt(data).await.map_err(|error| {
+ if let AwsKmsError::EncryptionFailed(sdk_error) = &error {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
- logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data");
+ logger::error!(aws_kms_sdk_error=?sdk_error, "Failed to AWS KMS encrypt data");
metrics::AWS_KMS_ENCRYPTION_FAILURES.add(1, &[]);
- })
- .change_context(AwsKmsError::EncryptionFailed)?;
+ }
+ report_with_cause(error)
+ })?;
- let output = encrypted_output
- .ciphertext_blob
- .ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
- .map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?;
let time_taken = start.elapsed();
metrics::AWS_KMS_ENCRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
@@ -122,57 +73,6 @@ impl AwsKmsClient {
}
}
-/// Errors that could occur during KMS operations.
-#[derive(Debug, thiserror::Error)]
-pub enum AwsKmsError {
- /// An error occurred when base64 encoding input data.
- #[error("Failed to base64 encode input data")]
- Base64EncodingFailed,
-
- /// An error occurred when base64 decoding input data.
- #[error("Failed to base64 decode input data")]
- Base64DecodingFailed,
-
- /// An error occurred when AWS KMS decrypting input data.
- #[error("Failed to AWS KMS decrypt input data")]
- DecryptionFailed,
-
- /// An error occurred when AWS KMS encrypting input data.
- #[error("Failed to AWS KMS encrypt input data")]
- EncryptionFailed,
-
- /// The AWS KMS decrypted output does not include a plaintext output.
- #[error("Missing plaintext AWS KMS decryption output")]
- MissingPlaintextDecryptionOutput,
-
- /// The AWS KMS encrypted output does not include a ciphertext output.
- #[error("Missing ciphertext AWS KMS encryption output")]
- MissingCiphertextEncryptionOutput,
-
- /// An error occurred UTF-8 decoding AWS KMS decrypted output.
- #[error("Failed to UTF-8 decode decryption output")]
- Utf8DecodingFailed,
-
- /// The AWS KMS client has not been initialized.
- #[error("The AWS KMS client has not been initialized")]
- AwsKmsClientNotInitialized,
-
- /// AWS KMS key id not provided.
- #[error("AWS KMS key id not provided")]
- MissingKeyId,
-}
-
-impl AwsKmsConfig {
- /// Verifies that the [`AwsKmsClient`] configuration is usable.
- pub fn validate(&self) -> Result<(), &'static str> {
- use common_utils::{ext_traits::ConfigExt, fp_utils::when};
-
- when(self.region.is_default_or_empty(), || {
- Err("KMS AWS region must not be empty")
- })
- }
-}
-
#[cfg(test)]
mod tests {
#[tokio::test]
@@ -217,4 +117,66 @@ mod tests {
println!("{kms_encrypted_fingerprint}");
}
+
+ mod error_reports {
+ use error_stack::{AttachmentKind, FrameKind};
+
+ use super::super::*;
+
+ #[tokio::test]
+ async fn invalid_base64_report_keeps_the_decode_error() {
+ let client = AwsKmsClient::new(&AwsKmsConfig {
+ key_id: Some("key".to_owned()),
+ region: "us-east-1".to_owned(),
+ })
+ .await;
+
+ #[allow(clippy::expect_used)]
+ let report = client
+ .decrypt("not base64!")
+ .await
+ .expect_err("invalid base64 must fail");
+
+ assert!(matches!(
+ report.current_context(),
+ AwsKmsError::Base64DecodingFailed(_)
+ ));
+ let printed = format!("{report:?}");
+ assert!(
+ printed.contains("Failed to base64 decode input data"),
+ "{printed}"
+ );
+ assert!(printed.contains("Invalid symbol"), "{printed}");
+ }
+
+ #[tokio::test]
+ async fn missing_key_id_reports_only_missing_key_id() {
+ let client = AwsKmsClient::new(&AwsKmsConfig {
+ key_id: None,
+ region: "us-east-1".to_owned(),
+ })
+ .await;
+
+ #[allow(clippy::expect_used)]
+ let report = client
+ .encrypt("hello")
+ .await
+ .expect_err("encrypting without a key id must fail");
+
+ assert!(matches!(
+ report.current_context(),
+ AwsKmsError::MissingKeyId
+ ));
+ let printable_attachments = report
+ .frames()
+ .filter(|frame| {
+ matches!(
+ frame.kind(),
+ FrameKind::Attachment(AttachmentKind::Printable(_))
+ )
+ })
+ .count();
+ assert_eq!(printable_attachments, 0);
+ }
+ }
}
diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs
index 3913be31b7..f9ba0b789d 100644
--- a/crates/external_services/src/email.rs
+++ b/crates/external_services/src/email.rs
@@ -1,6 +1,8 @@
-//! Interactions with the AWS SES SDK
+//! Sending email through AWS SES or an SMTP server.
+//!
+//! The clients themselves are the shared [`cloud_services::email`] ones; this module adds
+//! Hyperswitch's templating ([`EmailData`]), settings and error reporting.
-use aws_sdk_sesv2::types::Body;
use common_utils::{errors::CustomResult, pii};
use serde::Deserialize;
@@ -22,10 +24,10 @@ pub trait EmailClient: Sync + Send + dyn_clone::DynClone {
/// The rich text type of the email client
type RichText;
- /// Sends an email to the specified recipient with the given subject and body.
+ /// Sends one email to `recipients` with the given subject and body.
async fn send_email(
&self,
- recipient: pii::Email,
+ recipients: EmailRecipients,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
@@ -71,12 +73,12 @@ where
let EmailContents {
subject,
body,
- recipient,
+ recipients,
} = email_data;
let rich_text_string = self.convert_to_rich_text(body)?;
- self.send_email(recipient, subject, rich_text_string, proxy_url)
+ self.send_email(recipients, subject, rich_text_string, proxy_url)
.await
}
}
@@ -107,8 +109,47 @@ pub struct EmailContents {
/// The email clients can convert this intermediate representation to their client specific rich text format
pub body: IntermediateString,
- /// The email of the recipient to whom the email has to be sent
- pub recipient: pii::Email,
+ /// Who the email is sent to; a single address converts into `to`.
+ pub recipients: EmailRecipients,
+}
+
+/// The recipients of one email.
+#[derive(Debug, Clone, Default)]
+pub struct EmailRecipients {
+ /// Recipients
+ pub to: Vec<pii::Email>,
+ /// Copied recipients
+ pub cc: Vec<pii::Email>,
+ /// Blind-copied recipients
+ pub bcc: Vec<pii::Email>,
+}
+
+impl From<pii::Email> for EmailRecipients {
+ fn from(recipient: pii::Email) -> Self {
+ Self {
+ to: vec![recipient],
+ ..Self::default()
+ }
+ }
+}
+
+impl EmailRecipients {
+ fn addresses(emails: Vec<pii::Email>) -> Vec<String> {
+ use hyperswitch_masking::PeekInterface;
+ emails
+ .into_iter()
+ .map(|email| email.peek().to_owned())
+ .collect()
+ }
+
+ /// The recipients as plain addresses, for the shared clients.
+ pub(crate) fn into_addresses(self) -> (Vec<String>, Vec<String>, Vec<String>) {
+ (
+ Self::addresses(self.to),
+ Self::addresses(self.cc),
+ Self::addresses(self.bcc),
+ )
+ }
}
/// A trait which will contain the logic of generating the email subject and body
@@ -118,7 +159,7 @@ pub trait EmailData {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError>;
}
-dyn_clone::clone_trait_object!(EmailClient<RichText = Body>);
+dyn_clone::clone_trait_object!(EmailClient<RichText = String>);
/// List of available email clients to choose from
#[derive(Debug, Clone, Default, Deserialize)]
diff --git a/crates/external_services/src/email/no_email.rs b/crates/external_services/src/email/no_email.rs
index 6ec5d69e1a..c4574e8e14 100644
--- a/crates/external_services/src/email/no_email.rs
+++ b/crates/external_services/src/email/no_email.rs
@@ -1,7 +1,7 @@
-use common_utils::{errors::CustomResult, pii};
+use common_utils::errors::CustomResult;
use router_env::logger;
-use crate::email::{EmailClient, EmailError, EmailResult, IntermediateString};
+use crate::email::{EmailClient, EmailError, EmailRecipients, EmailResult, IntermediateString};
/// Client when email support is disabled
#[derive(Debug, Clone, Default, serde::Deserialize)]
@@ -26,7 +26,7 @@ impl EmailClient for NoEmailClient {
async fn send_email(
&self,
- _recipient: pii::Email,
+ _recipients: EmailRecipients,
_subject: String,
_body: Self::RichText,
_proxy_url: Option<&String>,
diff --git a/crates/external_services/src/email/ses.rs b/crates/external_services/src/email/ses.rs
index 85306f50a1..f9138b9426 100644
--- a/crates/external_services/src/email/ses.rs
+++ b/crates/external_services/src/email/ses.rs
@@ -1,85 +1,26 @@
-use std::time::{Duration, SystemTime};
+//! AWS SES email client.
+//!
+//! Hyperswitch adapter over the shared [`cloud_services::email::ses`] client: it adds logging and
+//! `error-stack` reports on top of the plain client.
-use aws_sdk_sesv2::{
- config::Region,
- operation::send_email::SendEmailError,
- types::{Body, Content, Destination, EmailContent, Message},
- Client,
-};
-use aws_sdk_sts::config::Credentials;
-use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
+pub use cloud_services::email::ses::{SesConfig as SESConfig, SesError as AwsSesError};
+use cloud_services::email::{ses as shared, EmailMessage};
use common_utils::{errors::CustomResult, pii};
-use error_stack::{report, ResultExt};
-use hyper::Uri;
use hyperswitch_masking::PeekInterface;
use router_env::logger;
-use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
+use crate::{
+ email::{
+ EmailClient, EmailError, EmailRecipients, EmailResult, EmailSettings, IntermediateString,
+ },
+ report_with_cause,
+};
/// Client for AWS SES operation
#[derive(Debug, Clone)]
pub struct AwsSes {
sender: pii::Email,
- ses_config: SESConfig,
- settings: EmailSettings,
-}
-
-/// Struct that contains the AWS ses specific configs required to construct an SES email client
-#[derive(Debug, Clone, Default, serde::Deserialize)]
-pub struct SESConfig {
- /// The arn of email role
- pub email_role_arn: String,
-
- /// The name of sts_session role
- pub sts_role_session_name: String,
-}
-
-impl SESConfig {
- /// Validation for the SES client specific configs
- pub fn validate(&self) -> Result<(), &'static str> {
- use common_utils::{ext_traits::ConfigExt, fp_utils::when};
-
- when(self.email_role_arn.is_default_or_empty(), || {
- Err("email.aws_ses.email_role_arn must not be empty")
- })?;
-
- when(self.sts_role_session_name.is_default_or_empty(), || {
- Err("email.aws_ses.sts_role_session_name must not be empty")
- })
- }
-}
-
-/// Errors that could occur during SES operations.
-#[derive(Debug, thiserror::Error)]
-pub enum AwsSesError {
- /// An error occurred in the SDK while sending email.
- #[error("Failed to Send Email {0:?}")]
- SendingFailure(Box<aws_sdk_sesv2::error::SdkError<SendEmailError>>),
-
- /// Configuration variable is missing to construct the email client
- #[error("Missing configuration variable {0}")]
- MissingConfigurationVariable(&'static str),
-
- /// Failed to assume the given STS role
- #[error("Failed to STS assume role: Role ARN: {role_arn}, Session name: {session_name}, Region: {region}")]
- AssumeRoleFailure {
- /// Aws region
- region: String,
-
- /// arn of email role
- role_arn: String,
-
- /// The name of sts_session role
- session_name: String,
- },
-
- /// Temporary credentials are missing
- #[error("Assumed role does not contain credentials for role user: {0:?}")]
- TemporaryCredentialsMissing(String),
-
- /// The proxy Connector cannot be built
- #[error("The proxy build cannot be built")]
- BuildingProxyConnectorFailed,
+ inner: shared::SesClient,
}
impl AwsSes {
@@ -89,165 +30,63 @@ impl AwsSes {
ses_config: &SESConfig,
proxy_url: Option<impl AsRef<str>>,
) -> Self {
+ let inner = shared::SesClient::new(conf.aws_region.to_owned(), ses_config.clone());
+
// Build the client initially which will help us know if the email configuration is correct
- Self::create_client(conf, ses_config, proxy_url)
+ if let Err(error) = inner
+ .sdk_client(proxy_url.as_ref().map(AsRef::as_ref))
.await
- .map_err(|error| logger::error!(?error, "Failed to initialize SES Client"))
- .ok();
+ {
+ logger::error!(error = ?report_with_cause(error), "Failed to initialize SES Client");
+ }
Self {
sender: conf.sender_email.clone(),
- ses_config: ses_config.clone(),
- settings: conf.clone(),
+ inner,
}
}
-
- /// A helper function to create ses client
- pub async fn create_client(
- conf: &EmailSettings,
- ses_config: &SESConfig,
- proxy_url: Option<impl AsRef<str>>,
- ) -> CustomResult<Client, AwsSesError> {
- let sts_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url.as_ref())?
- .load()
- .await;
-
- let role = aws_sdk_sts::Client::new(&sts_config)
- .assume_role()
- .role_arn(&ses_config.email_role_arn)
- .role_session_name(&ses_config.sts_role_session_name)
- .send()
- .await
- .change_context(AwsSesError::AssumeRoleFailure {
- region: conf.aws_region.to_owned(),
- role_arn: ses_config.email_role_arn.to_owned(),
- session_name: ses_config.sts_role_session_name.to_owned(),
- })?;
-
- let creds = role.credentials().ok_or(
- report!(AwsSesError::TemporaryCredentialsMissing(format!(
- "{role:?}"
- )))
- .attach_printable("Credentials object not available"),
- )?;
-
- let credentials = Credentials::new(
- creds.access_key_id(),
- creds.secret_access_key(),
- Some(creds.session_token().to_owned()),
- u64::try_from(creds.expiration().as_nanos())
- .ok()
- .map(Duration::from_nanos)
- .and_then(|val| SystemTime::UNIX_EPOCH.checked_add(val)),
- "custom_provider",
- );
-
- logger::debug!(
- "Obtained SES temporary credentials with expiry {:?}",
- credentials.expiry()
- );
-
- let ses_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url)?
- .credentials_provider(credentials)
- .load()
- .await;
-
- Ok(Client::new(&ses_config))
- }
-
- fn get_shared_config(
- region: String,
- proxy_url: Option<impl AsRef<str>>,
- ) -> CustomResult<aws_config::ConfigLoader, AwsSesError> {
- let region_provider = Region::new(region);
- let mut config = aws_config::from_env().region(region_provider);
-
- if let Some(proxy_url) = proxy_url {
- let proxy_connector = Self::get_proxy_connector(proxy_url)?;
- let http_client = HyperClientBuilder::new().build(proxy_connector);
- config = config.http_client(http_client);
- };
- Ok(config)
- }
-
- fn get_proxy_connector(
- proxy_url: impl AsRef<str>,
- ) -> CustomResult<hyper_proxy::ProxyConnector<hyper::client::HttpConnector>, AwsSesError> {
- let proxy_uri = proxy_url
- .as_ref()
- .parse::<Uri>()
- .attach_printable("Unable to parse the proxy url {proxy_url}")
- .change_context(AwsSesError::BuildingProxyConnectorFailed)?;
-
- let proxy = hyper_proxy::Proxy::new(hyper_proxy::Intercept::All, proxy_uri);
-
- hyper_proxy::ProxyConnector::from_proxy(hyper::client::HttpConnector::new(), proxy)
- .change_context(AwsSesError::BuildingProxyConnectorFailed)
- }
}
#[async_trait::async_trait]
impl EmailClient for AwsSes {
- type RichText = Body;
+ type RichText = String;
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
- let email_body = Body::builder()
- .html(
- Content::builder()
- .data(intermediate_string.into_inner())
- .charset("UTF-8")
- .build()
- .change_context(EmailError::ContentBuildFailure)?,
- )
- .build();
-
- Ok(email_body)
+ Ok(intermediate_string.into_inner())
}
async fn send_email(
&self,
- recipient: pii::Email,
+ recipients: EmailRecipients,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
) -> EmailResult<()> {
- // Not using the same email client which was created at startup as the role session would expire
- // Create a client every time when the email is being sent
- let email_client = Self::create_client(&self.settings, &self.ses_config, proxy_url)
- .await
- .change_context(EmailError::ClientBuildingFailure)?;
-
- email_client
- .send_email()
- .from_email_address(self.sender.peek())
- .destination(
- Destination::builder()
- .to_addresses(recipient.peek())
- .build(),
- )
- .content(
- EmailContent::builder()
- .simple(
- Message::builder()
- .subject(
- Content::builder()
- .data(subject)
- .build()
- .change_context(EmailError::ContentBuildFailure)?,
- )
- .body(body)
- .build(),
- )
- .build(),
- )
- .send()
+ // A new role session for every email, as the one created at startup would expire
+ let (to, cc, bcc) = recipients.into_addresses();
+ let message = EmailMessage {
+ from: self.sender.peek().to_owned(),
+ to,
+ cc,
+ bcc,
+ subject,
+ html_body: body,
+ };
+ self.inner
+ .send(message, proxy_url.map(String::as_str))
.await
- .map_err(|e| AwsSesError::SendingFailure(Box::new(e)))
- .change_context(EmailError::EmailSendingFailure)?;
-
- Ok(())
+ .map_err(|error| {
+ let context = match &error {
+ error if error.is_client_building_failure() => {
+ EmailError::ClientBuildingFailure
+ }
+ AwsSesError::ContentBuildFailure(_) => EmailError::ContentBuildFailure,
+ _ => EmailError::EmailSendingFailure,
+ };
+ report_with_cause(error).change_context(context)
+ })
}
}
diff --git a/crates/external_services/src/email/smtp.rs b/crates/external_services/src/email/smtp.rs
index bcab183d76..3dc076487c 100644
--- a/crates/external_services/src/email/smtp.rs
+++ b/crates/external_services/src/email/smtp.rs
@@ -1,95 +1,19 @@
-use std::time::Duration;
+//! SMTP email client.
+//!
+//! Hyperswitch adapter over the shared [`cloud_services::email::smtp`] client. The configuration
+//! stays here so its credentials remain masked [`Secret`]s.
+pub use cloud_services::email::smtp::{SmtpConnection, SmtpError};
+use cloud_services::email::{smtp as shared, EmailMessage};
use common_utils::{errors::CustomResult, pii};
-use error_stack::ResultExt;
use hyperswitch_masking::{PeekInterface, Secret};
-use lettre::{
- address::AddressError,
- error,
- message::{header::ContentType, Mailbox},
- transport::smtp::{
- self,
- authentication::{Credentials, Mechanism},
- client::{AsyncSmtpConnection, AsyncTokioStream, TlsParameters},
- extension::ClientId,
+
+use crate::{
+ email::{
+ EmailClient, EmailError, EmailRecipients, EmailResult, EmailSettings, IntermediateString,
},
- Message,
+ report_with_cause,
};
-use router_env::logger;
-use tokio::net::TcpStream;
-use tokio_socks::tcp::Socks5Stream;
-
-use crate::email::{EmailClient, EmailError, EmailResult, EmailSettings, IntermediateString};
-
-async fn connect_direct(host: &str, port: u16) -> Result<TcpStream, SmtpError> {
- TcpStream::connect((host, port))
- .await
- .map_err(SmtpError::DirectConnectionFailed)
-}
-
-/// SOCKS5 proxy to tunnel the SMTP connection through (absent means connect directly); username/password auth (RFC 1929) is sent to the proxy in cleartext.
-#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub struct Socks5Config {
- /// SOCKS5 proxy hostname or IP.
- pub host: String,
- /// SOCKS5 proxy port.
- pub port: u16,
- /// SOCKS5 username, if the proxy requires auth.
- pub username: Option<Secret<String>>,
- /// SOCKS5 password, if the proxy requires auth.
- pub password: Option<Secret<String>>,
-}
-
-async fn connect_via_socks5(
- socks5: &Socks5Config,
- smtp_host: &str,
- smtp_port: u16,
-) -> Result<TcpStream, SmtpError> {
- let proxy_addrs = tokio::net::lookup_host((socks5.host.as_str(), socks5.port))
- .await
- .map_err(SmtpError::Socks5ProxyResolutionFailed)?
- .collect::<Vec<_>>();
-
- let target = (smtp_host, smtp_port);
-
- // Try every resolved address, not just the first (matches connect_direct's retry).
- let mut last_error = SmtpError::Socks5ProxyResolutionFailed(std::io::Error::new(
- std::io::ErrorKind::NotFound,
- "proxy hostname resolved to no addresses",
- ));
-
- for proxy_addr in proxy_addrs {
- let result = match socks5.username.as_ref().zip(socks5.password.as_ref()) {
- Some((username, password)) => {
- Socks5Stream::connect_with_password(
- proxy_addr,
- target,
- username.peek().as_str(),
- password.peek().as_str(),
- )
- .await
- }
- None => Socks5Stream::connect(proxy_addr, target).await,
- };
-
- match result {
- Ok(stream) => return Ok(stream.into_inner()),
- Err(error) => {
- logger::warn!(
- ?error,
- proxy_host = %socks5.host,
- proxy_port = socks5.port,
- %proxy_addr,
- "SOCKS5 connection attempt failed, trying next resolved address if any"
- );
- last_error = SmtpError::Socks5ConnectionFailed(error);
- }
- }
- }
-
- Err(last_error)
-}
/// Client for SMTP server operation
#[derive(Debug, Clone, Default, serde::Deserialize)]
@@ -101,63 +25,15 @@ pub struct SmtpServer {
}
impl SmtpServer {
- pub(crate) async fn create_client(&self) -> CustomResult<AsyncSmtpConnection, SmtpError> {
- let host = &self.smtp_config.host;
- let port = self.smtp_config.port;
- let client_id = ClientId::default();
- let timeout = Duration::from_secs(self.smtp_config.timeout);
-
- let stream = tokio::time::timeout(timeout, async {
- match self.smtp_config.socks5.as_ref() {
- Some(socks5) => connect_via_socks5(socks5, host, port).await,
- None => connect_direct(host, port).await,
- }
- })
- .await
- .change_context(SmtpError::Timeout)
- .attach_printable("Timed out establishing the underlying connection to the SMTP host")??;
-
- let stream: Box<dyn AsyncTokioStream> = Box::new(stream);
-
- let mut conn = tokio::time::timeout(
- timeout,
- AsyncSmtpConnection::connect_with_transport(stream, &client_id),
- )
- .await
- .change_context(SmtpError::Timeout)
- .attach_printable("Timed out completing the SMTP connect handshake")?
- .map_err(SmtpError::ConnectionFailure)?;
-
- if matches!(self.smtp_config.connection, SmtpConnection::StartTls) {
- let tls_parameters = TlsParameters::builder(host.clone())
- .build()
- .map_err(SmtpError::ConnectionFailure)?;
- tokio::time::timeout(timeout, conn.starttls(tls_parameters, &client_id))
- .await
- .change_context(SmtpError::Timeout)
- .attach_printable("Timed out during the STARTTLS upgrade")?
- .map_err(SmtpError::ConnectionFailure)?;
- }
-
- Ok(conn)
- }
/// Constructs a new SMTP client
pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self {
Self {
sender: conf.sender_email.clone(),
- smtp_config: smtp_config.clone(),
+ smtp_config,
}
}
- fn to_mail_box(email: String) -> EmailResult<Mailbox> {
- Ok(Mailbox::new(
- None,
- email
- .parse()
- .map_err(SmtpError::EmailParsingFailed)
- .change_context(EmailError::EmailSendingFailure)?,
- ))
- }
}
+
/// Struct that contains the SMTP server specific configs required
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -179,15 +55,18 @@ pub struct SmtpServerConfig {
pub socks5: Option<Socks5Config>,
}
-/// Enum that contains the connection types of the SMTP server
+/// SOCKS5 proxy to tunnel the SMTP connection through (absent means connect directly); username/password auth (RFC 1929) is sent to the proxy in cleartext.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
-pub enum SmtpConnection {
- #[default]
- /// Plaintext connection which MUST then successfully upgrade to TLS via STARTTLS
- StartTls,
- /// Plaintext connection (very insecure)
- Plaintext,
+pub struct Socks5Config {
+ /// SOCKS5 proxy hostname or IP.
+ pub host: String,
+ /// SOCKS5 proxy port.
+ pub port: u16,
+ /// SOCKS5 username, if the proxy requires auth.
+ pub username: Option<Secret<String>>,
+ /// SOCKS5 password, if the proxy requires auth.
+ pub password: Option<Secret<String>>,
}
impl SmtpServerConfig {
@@ -210,6 +89,29 @@ impl SmtpServerConfig {
)?;
self.socks5.as_ref().map_or(Ok(()), Socks5Config::validate)
}
+
+ fn to_shared(&self) -> shared::SmtpConfig {
+ shared::SmtpConfig {
+ host: self.host.clone(),
+ port: self.port,
+ timeout: self.timeout,
+ username: self.username.as_ref().map(|value| value.peek().to_owned()),
+ password: self.password.as_ref().map(|value| value.peek().to_owned()),
+ connection: self.connection.clone(),
+ socks5: self.socks5.as_ref().map(|socks5| shared::Socks5Config {
+ host: socks5.host.clone(),
+ port: socks5.port,
+ username: socks5
+ .username
+ .as_ref()
+ .map(|value| value.peek().to_owned()),
+ password: socks5
+ .password
+ .as_ref()
+ .map(|value| value.peek().to_owned()),
+ }),
+ }
+ }
}
impl Socks5Config {
@@ -248,101 +150,27 @@ impl EmailClient for SmtpServer {
async fn send_email(
&self,
- recipient: pii::Email,
+ recipients: EmailRecipients,
subject: String,
body: Self::RichText,
// Unused here — SES uses this; SMTP's proxy lives in smtp_config.socks5.
_proxy_url: Option<&String>,
) -> EmailResult<()> {
- let email = Message::builder()
- .to(Self::to_mail_box(recipient.peek().to_string())?)
- .from(Self::to_mail_box(self.sender.peek().to_string())?)
- .subject(subject)
- .header(ContentType::TEXT_HTML)
- .body(body)
- .map_err(SmtpError::MessageBuildingFailed)
- .change_context(EmailError::EmailSendingFailure)?;
-
- let mut conn = self
- .create_client()
- .await
- .change_context(EmailError::EmailSendingFailure)?;
-
- let timeout = Duration::from_secs(self.smtp_config.timeout);
-
- let credentials = self
- .smtp_config
- .username
- .clone()
- .zip(self.smtp_config.password.clone())
- .map(|(username, password)| {
- Credentials::new(username.peek().to_owned(), password.peek().to_owned())
- });
-
- if let Some(credentials) = credentials {
- tokio::time::timeout(
- timeout,
- conn.auth(&[Mechanism::Plain, Mechanism::Login], &credentials),
- )
- .await
- .change_context(SmtpError::Timeout)
- .attach_printable("SMTP AUTH command timed out")
- .change_context(EmailError::EmailSendingFailure)?
- .map_err(SmtpError::AuthenticationFailure)
- .change_context(EmailError::EmailSendingFailure)?;
- }
-
- tokio::time::timeout(timeout, conn.send(email.envelope(), &email.formatted()))
+ // A new connection for every email
+ let (to, cc, bcc) = recipients.into_addresses();
+ let message = EmailMessage {
+ from: self.sender.peek().to_owned(),
+ to,
+ cc,
+ bcc,
+ subject,
+ html_body: body,
+ };
+ shared::SmtpClient::new(self.smtp_config.to_shared())
+ .send(message)
.await
- .change_context(SmtpError::Timeout)
- .attach_printable("SMTP SEND command timed out")
- .change_context(EmailError::EmailSendingFailure)?
- .map_err(SmtpError::SendingFailure)
- .change_context(EmailError::EmailSendingFailure)?;
-
- match tokio::time::timeout(timeout, conn.quit()).await {
- Ok(Ok(_)) => {}
- Ok(Err(error)) => {
- logger::warn!(?error, "SMTP QUIT failed after message was already sent");
- }
- Err(_) => {
- logger::warn!("SMTP QUIT timed out after message was already sent");
- }
- }
-
- Ok(())
+ .map_err(|error| {
+ report_with_cause(error).change_context(EmailError::EmailSendingFailure)
+ })
}
}
-
-/// Errors that could occur during SMTP operations.
-#[derive(Debug, thiserror::Error)]
-pub enum SmtpError {
- /// An error occurred in the SMTP client while sending the email (the SMTP `MAIL
- /// FROM`/`RCPT TO`/`DATA` exchange).
- #[error("Failed to Send Email {0:?}")]
- SendingFailure(smtp::Error),
- /// SMTP authentication (AUTH command) failed.
- #[error("SMTP authentication failed: {0:?}")]
- AuthenticationFailure(smtp::Error),
- /// The SMTP connect handshake or STARTTLS upgrade failed.
- #[error("Failed to create connection {0:?}")]
- ConnectionFailure(smtp::Error),
- /// The outgoing email's message content (headers/body) could not be built.
- #[error("Failed to Build Email content {0:?}")]
- MessageBuildingFailed(error::Error),
- /// The sender or recipient email address could not be parsed.
- #[error("Failed to parse given email {0:?}")]
- EmailParsingFailed(AddressError),
- /// The configured SOCKS5 proxy hostname could not be resolved.
- #[error("Failed to resolve SOCKS5 proxy address: {0:?}")]
- Socks5ProxyResolutionFailed(std::io::Error),
- /// Establishing the SOCKS5 tunnel failed (proxy unreachable, auth rejected, or protocol error).
- #[error("SOCKS5 proxy connection failed: {0}")]
- Socks5ConnectionFailed(tokio_socks::Error),
- /// TCP connection to the SMTP host itself failed (non-proxied direct connect).
- #[error("Failed to connect to SMTP server: {0:?}")]
- DirectConnectionFailed(std::io::Error),
- /// A network step exceeded `smtp_config.timeout`.
- #[error("SMTP operation timed out")]
- Timeout,
-}
diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs
index 55ed04fb43..952020f4f1 100644
--- a/crates/external_services/src/file_storage.rs
+++ b/crates/external_services/src/file_storage.rs
@@ -1,9 +1,6 @@
//! Module for managing file storage operations with support for multiple storage schemes.
-use std::{
- fmt::{Display, Formatter},
- sync::Arc,
-};
+use std::sync::Arc;
use common_utils::errors::CustomResult;
@@ -45,11 +42,13 @@ impl FileStorageConfig {
pub fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
match self {
#[cfg(feature = "aws_s3")]
- Self::AwsS3 { aws_s3 } => aws_s3.validate(),
+ Self::AwsS3 { aws_s3 } => aws_s3.validate()?,
#[cfg(feature = "oci_object_storage")]
- Self::OciObjectStorage { oci_object_storage } => oci_object_storage.validate(),
- Self::FileSystem => Ok(()),
+ Self::OciObjectStorage { oci_object_storage } => oci_object_storage.validate()?,
+ Self::FileSystem => {}
}
+
+ Ok(())
}
/// Retrieves the appropriate file storage client based on the file storage configuration.
@@ -126,15 +125,12 @@ pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send {
dyn_clone::clone_trait_object!(FileStorageInterface);
/// Error thrown when the file storage config is invalid
-#[derive(Debug, Clone)]
-pub struct InvalidFileStorageConfig(&'static str);
-
-impl std::error::Error for InvalidFileStorageConfig {}
-
-impl Display for InvalidFileStorageConfig {
- fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(f, "file_storage: {}", self.0)
- }
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum InvalidFileStorageConfig {
+ /// The configuration of a cloud storage backend is invalid.
+ #[cfg(any(feature = "aws_s3", feature = "oci_object_storage"))]
+ #[error("file_storage: {0}")]
+ CloudStorage(#[from] cloud_services::storage::InvalidStorageConfig),
}
/// Represents errors that can occur during file storage operations.
diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs
index bbc9a850dc..b91a1f2b31 100644
--- a/crates/external_services/src/file_storage/aws_s3.rs
+++ b/crates/external_services/src/file_storage/aws_s3.rs
@@ -1,274 +1,37 @@
-use aws_config::meta::region::RegionProviderChain;
-use aws_sdk_s3::{
- operation::{
- abort_multipart_upload::AbortMultipartUploadError,
- complete_multipart_upload::CompleteMultipartUploadError,
- create_multipart_upload::CreateMultipartUploadError, delete_object::DeleteObjectError,
- get_object::GetObjectError, put_object::PutObjectError, upload_part::UploadPartError,
- },
- presigning::{PresigningConfig, PresigningConfigError},
- types::{CompletedMultipartUpload, CompletedPart},
- Client,
-};
-use aws_sdk_sts::config::Region;
-use common_utils::errors::CustomResult;
+//! Hyperswitch adapter over the shared [`cloud_services`] S3 client.
+
+#[cfg(feature = "oci_object_storage")]
+use cloud_services::storage::oci::OciObjectStorageConfig;
+use cloud_services::storage::s3::S3Storage;
#[cfg(feature = "aws_s3")]
-use common_utils::ext_traits::ConfigExt;
+pub use cloud_services::storage::s3::S3StorageConfig as AwsFileStorageConfig;
+use common_utils::errors::CustomResult;
use error_stack::ResultExt;
-#[cfg(feature = "aws_s3")]
-use super::InvalidFileStorageConfig;
use crate::file_storage::{FileStorageError, FileStorageInterface};
-/// Configuration for AWS S3 file storage.
-#[cfg(feature = "aws_s3")]
-#[derive(Debug, serde::Deserialize, Clone, Default)]
-#[serde(default)]
-pub struct AwsFileStorageConfig {
- /// The AWS region to send file uploads
- region: String,
- /// The AWS s3 bucket to send file uploads
- bucket_name: String,
-}
-
-#[cfg(feature = "aws_s3")]
-impl AwsFileStorageConfig {
- /// Validates the AWS S3 file storage configuration.
- pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
- use common_utils::fp_utils::when;
-
- when(self.region.is_default_or_empty(), || {
- Err(InvalidFileStorageConfig("aws s3 region must not be empty"))
- })?;
-
- when(self.bucket_name.is_default_or_empty(), || {
- Err(InvalidFileStorageConfig(
- "aws s3 bucket name must not be empty",
- ))
- })
- }
-}
-
-/// Where the S3 client sends requests, for S3-compatible stores other than AWS S3 itself.
-#[derive(Debug, Clone, Default)]
-pub(super) struct S3Endpoint {
- /// Endpoint URL of the store. When unset, the endpoint is resolved from the region or
- /// `AWS_ENDPOINT_URL_S3`, as for AWS S3.
- pub(super) url: Option<String>,
- /// Addresses buckets as `<endpoint>/<bucket>` rather than `<bucket>.<endpoint>`, for stores
- /// whose TLS certificate does not cover bucket subdomains.
- pub(super) force_path_style: bool,
-}
-
-/// Builds the S3 client, applying the endpoint overrides on top of the SDK config. With the
-/// default [`S3Endpoint`] this is the same client as `Client::new(sdk_config)`.
-pub(super) fn build_client(endpoint: &S3Endpoint, sdk_config: &aws_config::SdkConfig) -> Client {
- let mut s3_config = aws_sdk_s3::config::Builder::from(sdk_config);
- if let Some(url) = &endpoint.url {
- s3_config = s3_config.endpoint_url(url);
- }
- if endpoint.force_path_style {
- s3_config = s3_config.force_path_style(true);
- }
- Client::from_conf(s3_config.build())
-}
-
/// AWS S3 file storage client.
#[derive(Debug, Clone)]
pub(super) struct AwsFileStorageClient {
- /// AWS S3 client
- inner_client: Client,
- /// The name of the AWS S3 bucket.
- bucket_name: String,
+ /// Shared S3 client
+ inner: S3Storage,
}
impl AwsFileStorageClient {
/// Creates a new AWS S3 file storage client.
#[cfg(feature = "aws_s3")]
pub(super) async fn new(config: &AwsFileStorageConfig) -> Self {
- Self::with_endpoint(&config.region, &config.bucket_name, &S3Endpoint::default()).await
- }
-
- /// Creates a client for an S3-compatible store reached through `endpoint`.
- pub(super) async fn with_endpoint(
- region: &str,
- bucket_name: &str,
- endpoint: &S3Endpoint,
- ) -> Self {
- let region_provider = RegionProviderChain::first_try(Region::new(region.to_owned()));
- let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
- inner_client: build_client(endpoint, &sdk_config),
- bucket_name: bucket_name.to_owned(),
+ inner: S3Storage::new(config).await,
}
}
- /// Uploads a file to AWS S3.
- async fn upload_file(
- &self,
- file_key: &str,
- file: Vec<u8>,
- ) -> CustomResult<(), AwsS3StorageError> {
- self.inner_client
- .put_object()
- .bucket(&self.bucket_name)
- .key(file_key)
- .body(file.into())
- .send()
- .await
- .map_err(AwsS3StorageError::UploadFailure)?;
- Ok(())
- }
-
- /// Deletes a file from AWS S3.
- async fn delete_file(&self, file_key: &str) -> CustomResult<(), AwsS3StorageError> {
- self.inner_client
- .delete_object()
- .bucket(&self.bucket_name)
- .key(file_key)
- .send()
- .await
- .map_err(AwsS3StorageError::DeleteFailure)?;
- Ok(())
- }
-
- /// Retrieves a file from AWS S3.
- async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, AwsS3StorageError> {
- Ok(self
- .inner_client
- .get_object()
- .bucket(&self.bucket_name)
- .key(file_key)
- .send()
- .await
- .map_err(AwsS3StorageError::RetrieveFailure)?
- .body
- .collect()
- .await
- .map_err(AwsS3StorageError::UnknownError)?
- .to_vec())
- }
-
- /// Begins a multipart upload on AWS S3.
- async fn create_multipart_upload(
- &self,
- file_key: &str,
- ) -> CustomResult<String, AwsS3StorageError> {
- self.inner_client
- .create_multipart_upload()
- .bucket(&self.bucket_name)
- .key(file_key)
- .content_type("text/csv")
- .send()
- .await
- .map_err(AwsS3StorageError::MultipartCreateFailure)?
- .upload_id
- .ok_or_else(|| error_stack::report!(AwsS3StorageError::MissingUploadId))
- }
-
- /// Uploads a single part of an in-progress multipart upload to AWS S3.
- async fn upload_part(
- &self,
- file_key: &str,
- upload_id: &str,
- part_number: i32,
- body: Vec<u8>,
- ) -> CustomResult<String, AwsS3StorageError> {
- self.inner_client
- .upload_part()
- .bucket(&self.bucket_name)
- .key(file_key)
- .upload_id(upload_id)
- .part_number(part_number)
- .body(body.into())
- .send()
- .await
- .map_err(AwsS3StorageError::MultipartUploadPartFailure)?
- .e_tag
- .ok_or_else(|| error_stack::report!(AwsS3StorageError::MissingPartETag))
- }
-
- /// Assembles the uploaded parts into a single S3 object, in part number order.
- async fn complete_multipart_upload(
- &self,
- file_key: &str,
- upload_id: &str,
- parts: Vec<(i32, String)>,
- ) -> CustomResult<Option<String>, AwsS3StorageError> {
- let completed_parts = parts
- .into_iter()
- .map(|(part_number, e_tag)| {
- CompletedPart::builder()
- .part_number(part_number)
- .e_tag(e_tag)
- .build()
- })
- .collect();
-
- Ok(self
- .inner_client
- .complete_multipart_upload()
- .bucket(&self.bucket_name)
- .key(file_key)
- .upload_id(upload_id)
- .multipart_upload(
- CompletedMultipartUpload::builder()
- .set_parts(Some(completed_parts))
- .build(),
- )
- .send()
- .await
- .map_err(AwsS3StorageError::MultipartCompleteFailure)?
- .expiration)
- }
-
- /// Discards an in-progress multipart upload and the parts already uploaded for it.
- async fn abort_multipart_upload(
- &self,
- file_key: &str,
- upload_id: &str,
- ) -> CustomResult<(), AwsS3StorageError> {
- self.inner_client
- .abort_multipart_upload()
- .bucket(&self.bucket_name)
- .key(file_key)
- .upload_id(upload_id)
- .send()
- .await
- .map_err(AwsS3StorageError::MultipartAbortFailure)?;
- Ok(())
- }
-
- /// Signs a time-limited GET for the object with the client's current credentials.
- async fn get_presigned_download_url(
- &self,
- file_key: &str,
- expires_in: std::time::Duration,
- download_file_name: Option<&str>,
- ) -> CustomResult<url::Url, AwsS3StorageError> {
- let presigning_config = PresigningConfig::expires_in(expires_in)
- .map_err(AwsS3StorageError::PresigningConfigFailure)?;
-
- let request = self
- .inner_client
- .get_object()
- .bucket(&self.bucket_name)
- .key(file_key)
- .response_content_type("text/csv");
-
- let request = match download_file_name {
- Some(name) => {
- request.response_content_disposition(format!("attachment; filename=\"{name}\""))
- }
- None => request,
- };
-
- let presigned = request
- .presigned(presigning_config)
- .await
- .map_err(AwsS3StorageError::PresignFailure)?;
-
- url::Url::parse(presigned.uri()).change_context(AwsS3StorageError::PresignedUrlParseFailure)
+ /// Creates a file storage client for OCI Object Storage, through its S3 Compatibility API.
+ #[cfg(feature = "oci_object_storage")]
+ pub(super) async fn new_oci(config: &OciObjectStorageConfig) -> Self {
+ Self {
+ inner: S3Storage::new_oci(config).await,
+ }
}
}
@@ -280,26 +43,26 @@ impl FileStorageInterface for AwsFileStorageClient {
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
- self.upload_file(file_key, file)
+ self.inner
+ .upload_file(file_key, file)
.await
- .change_context(FileStorageError::UploadFailed)?;
- Ok(())
+ .change_context(FileStorageError::UploadFailed)
}
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
- self.delete_file(file_key)
+ self.inner
+ .delete_file(file_key)
.await
- .change_context(FileStorageError::DeleteFailed)?;
- Ok(())
+ .change_context(FileStorageError::DeleteFailed)
}
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
- Ok(self
+ self.inner
.retrieve_file(file_key)
.await
- .change_context(FileStorageError::RetrieveFailed)?)
+ .change_context(FileStorageError::RetrieveFailed)
}
/// Begins a multipart upload on AWS S3.
@@ -307,10 +70,10 @@ impl FileStorageInterface for AwsFileStorageClient {
&self,
file_key: &str,
) -> CustomResult<String, FileStorageError> {
- Ok(self
+ self.inner
.create_multipart_upload(file_key)
.await
- .change_context(FileStorageError::MultipartCreateFailed)?)
+ .change_context(FileStorageError::MultipartCreateFailed)
}
/// Uploads a single part of an in-progress multipart upload to AWS S3.
@@ -321,10 +84,10 @@ impl FileStorageInterface for AwsFileStorageClient {
part_number: i32,
body: Vec<u8>,
) -> CustomResult<String, FileStorageError> {
- Ok(self
+ self.inner
.upload_part(file_key, upload_id, part_number, body)
.await
- .change_context(FileStorageError::MultipartUploadPartFailed)?)
+ .change_context(FileStorageError::MultipartUploadPartFailed)
}
/// Assembles the uploaded parts into a single S3 object.
@@ -334,10 +97,10 @@ impl FileStorageInterface for AwsFileStorageClient {
upload_id: &str,
parts: Vec<(i32, String)>,
) -> CustomResult<Option<String>, FileStorageError> {
- Ok(self
+ self.inner
.complete_multipart_upload(file_key, upload_id, parts)
.await
- .change_context(FileStorageError::MultipartCompleteFailed)?)
+ .change_context(FileStorageError::MultipartCompleteFailed)
}
/// Discards an in-progress multipart upload on AWS S3.
@@ -346,10 +109,10 @@ impl FileStorageInterface for AwsFileStorageClient {
file_key: &str,
upload_id: &str,
) -> CustomResult<(), FileStorageError> {
- self.abort_multipart_upload(file_key, upload_id)
+ self.inner
+ .abort_multipart_upload(file_key, upload_id)
.await
- .change_context(FileStorageError::MultipartAbortFailed)?;
- Ok(())
+ .change_context(FileStorageError::MultipartAbortFailed)
}
/// Signs a time-limited GET for an object in AWS S3.
@@ -359,139 +122,113 @@ impl FileStorageInterface for AwsFileStorageClient {
expires_in: std::time::Duration,
download_file_name: Option<&str>,
) -> CustomResult<url::Url, FileStorageError> {
- Ok(self
+ self.inner
.get_presigned_download_url(file_key, expires_in, download_file_name)
.await
- .change_context(FileStorageError::PresignFailed)?)
+ .change_context(FileStorageError::PresignFailed)
}
}
-/// Enum representing errors that can occur during AWS S3 file storage operations.
-#[derive(Debug, thiserror::Error)]
-enum AwsS3StorageError {
- /// Error indicating that file upload to S3 failed.
- #[error("File upload to S3 failed: {0:?}")]
- UploadFailure(aws_sdk_s3::error::SdkError<PutObjectError>),
-
- /// Error indicating that file retrieval from S3 failed.
- #[error("File retrieve from S3 failed: {0:?}")]
- RetrieveFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
-
- /// Error indicating that file deletion from S3 failed.
- #[error("File delete from S3 failed: {0:?}")]
- DeleteFailure(aws_sdk_s3::error::SdkError<DeleteObjectError>),
-
- /// Unknown error occurred.
- #[error("Unknown error occurred: {0:?}")]
- UnknownError(aws_sdk_s3::primitives::ByteStreamError),
-
- /// Error indicating that starting a multipart upload on S3 failed.
- #[error("Multipart upload create on S3 failed: {0:?}")]
- MultipartCreateFailure(aws_sdk_s3::error::SdkError<CreateMultipartUploadError>),
-
- /// Error indicating that uploading a part to S3 failed.
- #[error("Multipart part upload to S3 failed: {0:?}")]
- MultipartUploadPartFailure(aws_sdk_s3::error::SdkError<UploadPartError>),
-
- /// Error indicating that assembling a multipart upload on S3 failed.
- #[error("Multipart upload complete on S3 failed: {0:?}")]
- MultipartCompleteFailure(aws_sdk_s3::error::SdkError<CompleteMultipartUploadError>),
-
- /// Error indicating that discarding a multipart upload on S3 failed.
- #[error("Multipart upload abort on S3 failed: {0:?}")]
- MultipartAbortFailure(aws_sdk_s3::error::SdkError<AbortMultipartUploadError>),
-
- /// Error indicating S3 accepted the multipart upload but returned no upload id.
- #[error("S3 did not return an upload id for the multipart upload")]
- MissingUploadId,
-
- /// Error indicating S3 accepted the part but returned no entity tag.
- #[error("S3 did not return an entity tag for the uploaded part")]
- MissingPartETag,
-
- /// Error indicating the presigning configuration was rejected by the SDK.
- #[error("Presigning configuration was rejected: {0:?}")]
- PresigningConfigFailure(PresigningConfigError),
-
- /// Error indicating that presigning a GET request failed.
- #[error("Presigning an S3 get request failed: {0:?}")]
- PresignFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
-
- /// Error indicating the presigned URI could not be parsed as a URL.
- #[error("Presigned URI is not a valid URL")]
- PresignedUrlParseFailure,
-}
-
#[cfg(test)]
-pub(super) mod tests {
- use std::time::Duration;
-
- use aws_sdk_s3::config::{BehaviorVersion, Credentials, SharedCredentialsProvider};
+mod tests {
+ use crate::file_storage::FileStorageConfig;
- use super::*;
-
- fn sdk_config(endpoint_url: Option<&str>) -> aws_config::SdkConfig {
- let builder = aws_config::SdkConfig::builder()
- .behavior_version(BehaviorVersion::latest())
- .region(Region::new("ap-hyderabad-1"))
- .credentials_provider(SharedCredentialsProvider::new(Credentials::new(
- "access_key",
- "secret_key",
- None,
- None,
- "test",
- )));
- match endpoint_url {
- Some(endpoint_url) => builder.endpoint_url(endpoint_url).build(),
- None => builder.build(),
- }
+ fn file_storage_config(value: serde_json::Value) -> FileStorageConfig {
+ #[allow(clippy::expect_used)]
+ serde_json::from_value(value).expect("file storage config should deserialize")
}
- /// Presigns a download of `files/file_key`, which shows where the client sends requests
- /// without any network call.
- pub(in crate::file_storage) async fn presigned_url(
- endpoint: &S3Endpoint,
- bucket_name: &str,
- sdk_endpoint_url: Option<&str>,
- ) -> String {
- #[allow(clippy::expect_used)]
- let presigning_config =
- PresigningConfig::expires_in(Duration::from_secs(60)).expect("valid presigning config");
+ #[cfg(feature = "aws_s3")]
+ #[test]
+ fn aws_s3_backend_config_deserializes_and_validates() {
+ let config = file_storage_config(serde_json::json!({
+ "file_storage_backend": "aws_s3",
+ "aws_s3": {
+ "region": "us-east-1",
+ "bucket_name": "bucket",
+ },
+ }));
- #[allow(clippy::expect_used)]
- build_client(endpoint, &sdk_config(sdk_endpoint_url))
- .get_object()
- .bucket(bucket_name)
- .key("files/file_key")
- .presigned(presigning_config)
- .await
- .expect("presigning is local and should succeed")
- .uri()
- .to_owned()
+ assert!(matches!(config, FileStorageConfig::AwsS3 { .. }));
+ assert!(config.validate().is_ok());
}
- #[tokio::test]
- async fn aws_config_uses_virtual_hosted_aws_endpoint() {
- let url = presigned_url(&S3Endpoint::default(), "bucket", None).await;
+ #[cfg(feature = "aws_s3")]
+ #[test]
+ fn aws_s3_backend_reports_invalid_config() {
+ for (aws_s3, message) in [
+ (
+ serde_json::json!({ "bucket_name": "bucket" }),
+ "file_storage: aws s3 region must not be empty",
+ ),
+ (
+ serde_json::json!({ "region": "us-east-1", "bucket_name": " " }),
+ "file_storage: aws s3 bucket name must not be empty",
+ ),
+ ] {
+ let config = file_storage_config(serde_json::json!({
+ "file_storage_backend": "aws_s3",
+ "aws_s3": aws_s3,
+ }));
+
+ assert_eq!(
+ config.validate().map_err(|error| error.to_string()),
+ Err(message.to_owned())
+ );
+ }
+ }
- assert!(
- url.starts_with("https://bucket.s3.ap-hyderabad-1.amazonaws.com/files/file_key?"),
- "{url}"
+ #[cfg(feature = "aws_s3")]
+ #[test]
+ fn invalid_config_keeps_the_validation_error_as_its_source() {
+ let config = file_storage_config(serde_json::json!({
+ "file_storage_backend": "aws_s3",
+ "aws_s3": { "region": "us-east-1" },
+ }));
+
+ let source = config
+ .validate()
+ .err()
+ .as_ref()
+ .and_then(std::error::Error::source)
+ .map(ToString::to_string);
+
+ assert_eq!(
+ source.as_deref(),
+ Some("aws s3 bucket name must not be empty")
);
}
- #[tokio::test]
- async fn endpoint_from_environment_is_kept_when_not_overridden() {
- let endpoint = S3Endpoint {
- url: None,
- force_path_style: true,
- };
-
- let url = presigned_url(&endpoint, "bucket", Some("https://endpoint.from.env")).await;
-
- assert!(
- url.starts_with("https://endpoint.from.env/bucket/files/file_key?"),
- "{url}"
+ #[cfg(feature = "oci_object_storage")]
+ #[test]
+ fn oci_object_storage_backend_config_deserializes_and_validates() {
+ let config = file_storage_config(serde_json::json!({
+ "file_storage_backend": "oci_object_storage",
+ "oci_object_storage": {
+ "namespace": "namespace",
+ "region": "ap-hyderabad-1",
+ "bucket_name": "bucket",
+ },
+ }));
+
+ assert!(matches!(config, FileStorageConfig::OciObjectStorage { .. }));
+ assert!(config.validate().is_ok());
+ }
+
+ #[cfg(feature = "oci_object_storage")]
+ #[test]
+ fn oci_object_storage_backend_reports_invalid_config() {
+ let config = file_storage_config(serde_json::json!({
+ "file_storage_backend": "oci_object_storage",
+ "oci_object_storage": {
+ "namespace": "namespace",
+ "region": "ap-hyderabad-1",
+ },
+ }));
+
+ assert_eq!(
+ config.validate().map_err(|error| error.to_string()),
+ Err("file_storage: oci object storage bucket name must not be empty".to_owned())
);
}
}
diff --git a/crates/external_services/src/file_storage/oci_object_storage.rs b/crates/external_services/src/file_storage/oci_object_storage.rs
index 61ec0fd971..b760a351f9 100644
--- a/crates/external_services/src/file_storage/oci_object_storage.rs
+++ b/crates/external_services/src/file_storage/oci_object_storage.rs
@@ -1,173 +1,10 @@
//! OCI Object Storage, accessed through its Amazon S3 Compatibility API.
-use common_utils::{ext_traits::ConfigExt, fp_utils::when};
+pub use cloud_services::storage::oci::OciObjectStorageConfig as OciFileStorageConfig;
-use super::{
- aws_s3::{AwsFileStorageClient, S3Endpoint},
- InvalidFileStorageConfig,
-};
-
-/// Configuration for OCI Object Storage.
-///
-/// Requests go to the S3 Compatibility API endpoint of the namespace and region, with the bucket
-/// in the path, since OCI's TLS certificate does not cover bucket subdomains. Authenticate with an
-/// OCI Customer Secret Key, through `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`.
-#[derive(Debug, serde::Deserialize, Clone, Default)]
-#[serde(default)]
-pub struct OciFileStorageConfig {
- /// The Object Storage namespace of the tenancy
- namespace: String,
- /// The OCI region identifier of the bucket, such as `us-ashburn-1`
- region: String,
- /// The bucket to send file uploads
- bucket_name: String,
-}
-
-impl OciFileStorageConfig {
- /// Validates the OCI Object Storage configuration.
- pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
- when(!is_hostname_label(&self.namespace), || {
- Err(InvalidFileStorageConfig(
- "oci object storage namespace must be non-empty and contain only letters, digits and hyphens",
- ))
- })?;
-
- when(!is_hostname_label(&self.region), || {
- Err(InvalidFileStorageConfig(
- "oci object storage region must be non-empty and contain only letters, digits and hyphens",
- ))
- })?;
-
- when(self.bucket_name.is_default_or_empty(), || {
- Err(InvalidFileStorageConfig(
- "oci object storage bucket name must not be empty",
- ))
- })
- }
-
- /// The S3 Compatibility API endpoint of the namespace and region, addressed path-style.
- fn endpoint(&self) -> S3Endpoint {
- S3Endpoint {
- url: Some(format!(
- "https://{}.compat.objectstorage.{}.oraclecloud.com",
- self.namespace, self.region
- )),
- force_path_style: true,
- }
- }
-}
-
-/// Whether `value` can be used as one label of the endpoint host name.
-fn is_hostname_label(value: &str) -> bool {
- !value.is_empty()
- && value
- .chars()
- .all(|character| character.is_ascii_alphanumeric() || character == '-')
-}
+use super::aws_s3::AwsFileStorageClient;
/// Creates a file storage client for OCI Object Storage.
pub(super) async fn client(config: &OciFileStorageConfig) -> AwsFileStorageClient {
- AwsFileStorageClient::with_endpoint(&config.region, &config.bucket_name, &config.endpoint())
- .await
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::file_storage::{aws_s3::tests::presigned_url, FileStorageConfig};
-
- fn config(namespace: &str, region: &str, bucket_name: &str) -> OciFileStorageConfig {
- OciFileStorageConfig {
- namespace: namespace.to_owned(),
- region: region.to_owned(),
- bucket_name: bucket_name.to_owned(),
- }
- }
-
- #[test]
- fn deserializes_as_its_own_backend() {
- #[allow(clippy::expect_used)]
- let file_storage: FileStorageConfig = serde_json::from_value(serde_json::json!({
- "file_storage_backend": "oci_object_storage",
- "oci_object_storage": {
- "namespace": "namespace",
- "region": "ap-hyderabad-1",
- "bucket_name": "bucket",
- },
- }))
- .expect("oci object storage config should deserialize");
-
- assert!(
- matches!(&file_storage, FileStorageConfig::OciObjectStorage { .. }),
- "{file_storage:?}"
- );
- assert!(file_storage.validate().is_ok());
- }
-
- #[test]
- fn rejects_values_that_do_not_fit_the_endpoint() {
- for (config, message) in [
- (
- config("", "ap-hyderabad-1", "bucket"),
- "oci object storage namespace",
- ),
- (
- config("name.space", "ap-hyderabad-1", "bucket"),
- "oci object storage namespace",
- ),
- (
- config("namespace", "", "bucket"),
- "oci object storage region",
- ),
- (
- config("namespace", "ap-hyderabad-1/x", "bucket"),
- "oci object storage region",
- ),
- (
- config("namespace", "ap-hyderabad-1", ""),
- "oci object storage bucket name",
- ),
- ] {
- let error = config.validate().err().map(|error| error.to_string());
- assert!(
- error
- .as_deref()
- .is_some_and(|error| error.starts_with(&format!("file_storage: {message}"))),
- "{config:?}: {error:?}"
- );
- }
- }
-
- #[tokio::test]
- async fn addresses_the_bucket_in_the_path_of_the_compatibility_endpoint() {
- let config = config("namespace", "ap-hyderabad-1", "bucket");
-
- let url = presigned_url(&config.endpoint(), &config.bucket_name, None).await;
-
- assert!(
- url.starts_with(
- "https://namespace.compat.objectstorage.ap-hyderabad-1.oraclecloud.com/bucket/files/file_key?"
- ),
- "{url}"
- );
- }
-
- #[tokio::test]
- async fn ignores_an_endpoint_from_the_environment() {
- let config = config("namespace", "ap-hyderabad-1", "bucket");
-
- let url = presigned_url(
- &config.endpoint(),
- &config.bucket_name,
- Some("https://endpoint.from.env"),
- )
- .await;
-
- assert!(
- url.starts_with(
- "https://namespace.compat.objectstorage.ap-hyderabad-1.oraclecloud.com/bucket/"
- ),
- "{url}"
- );
- }
+ AwsFileStorageClient::new_oci(config).await
}
diff --git a/crates/external_services/src/gcp_kms/core.rs b/crates/external_services/src/gcp_kms/core.rs
index 7b9cf08506..568a79d662 100644
--- a/crates/external_services/src/gcp_kms/core.rs
+++ b/crates/external_services/src/gcp_kms/core.rs
@@ -1,112 +1,44 @@
//! Interactions with the GCP Cloud KMS SDK
+//!
+//! Hyperswitch adapter over the shared [`cloud_services::kms::gcp`] client: it adds logging,
+//! metrics and `error-stack` reports on top of the plain client.
use std::time::Instant;
-use base64::Engine;
+use cloud_services::kms::gcp as shared;
+pub use cloud_services::kms::gcp::{GcpKmsConfig, GcpKmsError};
use common_utils::errors::CustomResult;
-use error_stack::ResultExt;
-use google_cloud_kms::{
- client::{Client, ClientConfig},
- grpc::kms::v1::{DecryptRequest, EncryptRequest},
-};
use router_env::logger;
-use crate::{consts, metrics};
-
-/// Configuration parameters required for constructing a [`GcpKmsClient`].
-#[derive(Clone, Debug, Default, serde::Deserialize)]
-#[serde(default)]
-pub struct GcpKmsConfig {
- /// The GCP project ID that owns the KMS key ring.
- pub project_id: String,
-
- /// The location ID (e.g. `"global"`, `"us-east1"`) of the KMS key ring.
- pub location_id: String,
-
- /// The ID of the KMS key ring.
- pub key_ring_id: String,
-
- /// The ID of the KMS key used to encrypt or decrypt data.
- pub key_id: String,
-}
-
-impl GcpKmsConfig {
- /// Verifies that the [`GcpKmsConfig`] is valid.
- pub fn validate(&self) -> Result<(), &'static str> {
- use common_utils::{ext_traits::ConfigExt, fp_utils::when};
-
- when(self.project_id.is_default_or_empty(), || {
- Err("GCP KMS project ID must not be empty")
- })?;
-
- when(self.location_id.is_default_or_empty(), || {
- Err("GCP KMS location ID must not be empty")
- })?;
-
- when(self.key_ring_id.is_default_or_empty(), || {
- Err("GCP KMS key ring ID must not be empty")
- })?;
-
- when(self.key_id.is_default_or_empty(), || {
- Err("GCP KMS key ID must not be empty")
- })
- }
-}
+use crate::{metrics, report_with_cause};
/// Client for GCP Cloud KMS operations.
#[derive(Clone, Debug)]
pub struct GcpKmsClient {
- inner_client: Client,
- key_name: String,
+ inner: shared::GcpKmsClient,
}
impl GcpKmsClient {
/// Constructs a new GCP KMS client with ambient credentials, targeting the KMS key
/// identified by the provided [`GcpKmsConfig`].
pub async fn new(config: &GcpKmsConfig) -> CustomResult<Self, GcpKmsError> {
- let client_config = ClientConfig::default()
- .with_auth()
- .await
- .change_context(GcpKmsError::ClientCreationFailed)?;
- let inner_client = Client::new(client_config)
+ let inner = shared::GcpKmsClient::new(config)
.await
- .change_context(GcpKmsError::ClientCreationFailed)?;
- Ok(Self {
- inner_client,
- key_name: format!(
- "projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}",
- config.project_id, config.location_id, config.key_ring_id, config.key_id
- ),
- })
+ .map_err(report_with_cause)?;
+ Ok(Self { inner })
}
/// Decrypts base64-encoded ciphertext via GCP Cloud KMS.
pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, GcpKmsError> {
let start = Instant::now();
- let ciphertext = consts::BASE64_ENGINE
- .decode(data)
- .change_context(GcpKmsError::Base64DecodingFailed)?;
-
- let request = DecryptRequest {
- name: self.key_name.clone(),
- ciphertext,
- additional_authenticated_data: Vec::new(),
- ciphertext_crc32c: None,
- additional_authenticated_data_crc32c: None,
- };
- let response = self
- .inner_client
- .decrypt(request, None)
- .await
- .inspect_err(|error| {
- logger::error!(gcp_kms_error=?error, "Failed to GCP KMS decrypt data");
+ let output = self.inner.decrypt(data).await.map_err(|error| {
+ if let GcpKmsError::DecryptionFailed(status) = &error {
+ logger::error!(gcp_kms_error=?status, "Failed to GCP KMS decrypt data");
metrics::GCP_KMS_DECRYPTION_FAILURES.add(1, &[]);
- })
- .change_context(GcpKmsError::DecryptionFailed)?;
-
- let output = String::from_utf8(response.plaintext)
- .change_context(GcpKmsError::Utf8DecodingFailed)?;
+ }
+ report_with_cause(error)
+ })?;
let time_taken = start.elapsed();
metrics::GCP_KMS_DECRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
@@ -118,25 +50,13 @@ impl GcpKmsClient {
pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, GcpKmsError> {
let start = Instant::now();
- let request = EncryptRequest {
- name: self.key_name.clone(),
- plaintext: data.as_ref().to_vec(),
- additional_authenticated_data: Vec::new(),
- plaintext_crc32c: None,
- additional_authenticated_data_crc32c: None,
- };
-
- let response = self
- .inner_client
- .encrypt(request, None)
- .await
- .inspect_err(|error| {
- logger::error!(gcp_kms_error=?error, "Failed to GCP KMS encrypt data");
+ let output = self.inner.encrypt(data).await.map_err(|error| {
+ if let GcpKmsError::EncryptionFailed(status) = &error {
+ logger::error!(gcp_kms_error=?status, "Failed to GCP KMS encrypt data");
metrics::GCP_KMS_ENCRYPTION_FAILURES.add(1, &[]);
- })
- .change_context(GcpKmsError::EncryptionFailed)?;
-
- let output = consts::BASE64_ENGINE.encode(response.ciphertext);
+ }
+ report_with_cause(error)
+ })?;
let time_taken = start.elapsed();
metrics::GCP_KMS_ENCRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
@@ -145,30 +65,6 @@ impl GcpKmsClient {
}
}
-/// Errors that could occur during GCP KMS operations.
-#[derive(Debug, thiserror::Error)]
-pub enum GcpKmsError {
- /// An error occurred when base64 decoding the input data.
- #[error("Failed to base64 decode input data")]
- Base64DecodingFailed,
-
- /// An error occurred when GCP KMS decrypting the input data.
- #[error("Failed to GCP KMS decrypt input data")]
- DecryptionFailed,
-
- /// An error occurred when GCP KMS encrypting the input data.
- #[error("Failed to GCP KMS encrypt input data")]
- EncryptionFailed,
-
- /// An error occurred UTF-8 decoding the GCP KMS decrypted output.
- #[error("Failed UTF-8 decode of GCP KMS decrypted output")]
- Utf8DecodingFailed,
-
- /// An error occurred when creating the GCP KMS client.
- #[error("Failed to create GCP KMS client")]
- ClientCreationFailed,
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -228,6 +124,21 @@ mod tests {
assert!(config.validate().is_ok());
}
+ #[test]
+ fn reports_keep_the_underlying_cause() {
+ #[allow(clippy::expect_used)]
+ let utf8_error = String::from_utf8(vec![0xff]).expect_err("0xff is not UTF-8");
+ let printed = format!(
+ "{:?}",
+ report_with_cause(GcpKmsError::Utf8DecodingFailed(utf8_error))
+ );
+ assert!(
+ printed.contains("Failed UTF-8 decode of GCP KMS decrypted output"),
+ "{printed}"
+ );
+ assert!(printed.contains("invalid utf-8 sequence"), "{printed}");
+ }
+
#[tokio::test]
async fn check_gcp_kms_encrypt() {
let config = GcpKmsConfig {
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index c4de17e207..3167e012b5 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -28,6 +28,22 @@ pub mod superposition;
/// deserializers module_path
pub mod utils;
+/// Builds a report from a shared [`cloud_services`] client error, attaching the error's cause as
+/// text: `error-stack` prints only a context's own message, so the cause would otherwise be
+/// missing from logged reports.
+#[cfg(any(feature = "aws_kms", feature = "gcp_kms", feature = "email"))]
+fn report_with_cause<E>(error: E) -> error_stack::Report<E>
+where
+ E: std::error::Error + Send + Sync + 'static,
+{
+ let cause = error.source().map(ToString::to_string);
+ let report = error_stack::Report::new(error);
+ match cause {
+ Some(cause) => report.attach_printable(cause),
+ None => report,
+ }
+}
+
#[cfg(feature = "revenue_recovery")]
/// date_time module
pub mod date_time {
@@ -83,11 +99,6 @@ pub mod consts {
/// service. OS-level backstop for the HTTP/2 PING keepalive.
pub(crate) const DEFAULT_UCS_TCP_KEEPALIVE_SECS: u64 = 60;
- /// General purpose base64 engine
- #[cfg(any(feature = "aws_kms", feature = "gcp_kms"))]
- pub(crate) const BASE64_ENGINE: base64::engine::GeneralPurpose =
- base64::engine::general_purpose::STANDARD;
-
/// Header key used to specify the connector name in UCS requests.
pub(crate) const UCS_HEADER_CONNECTOR: &str = "x-connector";
diff --git a/crates/external_services/src/oci_kms/core.rs b/crates/external_services/src/oci_kms/core.rs
index 208afe0f5e..b6f5dc9dc4 100644
--- a/crates/external_services/src/oci_kms/core.rs
+++ b/crates/external_services/src/oci_kms/core.rs
@@ -1,4 +1,4 @@
-//! Hyperswitch adapter over the shared [`oci_kms`](::oci_kms) client.
+//! Hyperswitch adapter over the shared OCI KMS client in [`cloud_services::kms::oci`].
//!
//! The client itself (authentication, request signing, timeouts and retries) lives in the
//! standalone `oci_kms` crate so other services can share it. This adapter routes its clock
@@ -6,9 +6,9 @@
use std::{sync::Arc, time::Instant};
+pub use cloud_services::kms::oci::OciKmsConfig;
use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
-pub use oci_kms::OciKmsConfig;
use router_env::logger;
use crate::metrics;
@@ -16,14 +16,17 @@ use crate::metrics;
/// Client for OCI Vault KMS crypto operations.
#[derive(Clone, Debug)]
pub struct OciKmsClient {
- inner: oci_kms::OciKmsClient,
+ inner: cloud_services::kms::oci::OciKmsClient,
}
impl OciKmsClient {
/// Constructs a new client; credentials are resolved lazily per call, not eagerly.
pub async fn new(config: &OciKmsConfig) -> CustomResult<Self, OciKmsError> {
- let inner = oci_kms::OciKmsClient::with_environment(config, Arc::new(CommonUtilsSeams))
- .map_err(|error| report!(error).change_context(OciKmsError::ClientCreationFailed))?;
+ let inner = cloud_services::kms::oci::OciKmsClient::with_environment(
+ config,
+ Arc::new(CommonUtilsSeams),
+ )
+ .map_err(|error| report!(error).change_context(OciKmsError::ClientCreationFailed))?;
Ok(Self { inner })
}
@@ -68,7 +71,7 @@ impl OciKmsClient {
#[derive(Debug)]
struct CommonUtilsSeams;
-impl oci_kms::Environment for CommonUtilsSeams {
+impl cloud_services::kms::oci::Environment for CommonUtilsSeams {
fn now_unix_timestamp(&self) -> i64 {
common_utils::date_time::now_unix_timestamp()
}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 442ab8d0a4..1063410cfe 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -123,18 +123,6 @@ pub enum HealthCheckOutGoing {
OutGoingFailed { message: String },
}
-#[derive(Debug, thiserror::Error)]
-pub enum AwsKmsError {
- #[error("Failed to base64 decode input data")]
- Base64DecodingFailed,
- #[error("Failed to AWS KMS decrypt input data")]
- DecryptionFailed,
- #[error("Missing plaintext AWS KMS decryption output")]
- MissingPlaintextDecryptionOutput,
- #[error("Failed to UTF-8 decode decryption output")]
- Utf8DecodingFailed,
-}
-
#[derive(Debug, thiserror::Error, serde::Serialize)]
pub enum WebhooksFlowError {
#[error("Merchant webhook config not found")]
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 76b6f6c213..41a4a18828 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -397,7 +397,7 @@ impl EmailData for VerifyEmail {
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -447,7 +447,7 @@ impl EmailData for ResetPassword {
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -497,7 +497,7 @@ impl EmailData for MagicLink {
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -547,7 +547,7 @@ impl EmailData for InviteUser {
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -570,7 +570,7 @@ impl EmailData for ReconActivation {
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -642,7 +642,7 @@ impl EmailData for BizEmailProd {
Ok(EmailContents {
subject: "New Prod Intent".to_string(),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -673,7 +673,7 @@ impl EmailData for ProFeatureRequest {
Ok(EmailContents {
subject: self.subject.clone(),
body: external_services::email::IntermediateString::new(body),
- recipient,
+ recipients: recipient.into(),
})
}
}
@@ -702,7 +702,7 @@ impl EmailData for ApiKeyExpiryReminder {
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
- recipient,
+ recipients: recipient.into(),
})
}
}
@@ -719,7 +719,7 @@ impl EmailData for WelcomeToCommunity {
Ok(EmailContents {
subject: "Thank you for signing up on Hyperswitch Dashboard!".to_string(),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}
@@ -781,7 +781,7 @@ impl EmailData for RoleDeleted {
Ok(EmailContents {
subject: format!("Access Removed - {} Role Revoked", self.role_name),
body: external_services::email::IntermediateString::new(body),
- recipient: self.recipient_email.clone().into_inner(),
+ recipients: self.recipient_email.clone().into_inner().into(),
})
}
}