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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(file_storage): add OCI Object Storage backend (#14605)
Jagan6e1292e029cc
diff --git a/config/config.example.toml b/config/config.example.tomlindex dcc74aac6f..454713ef0a 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1417,12 +1417,20 @@ account_updater_topic = "topic" # Kafka topic to be used for account upd# File storage configuration[file_storage]-file_storage_backend = "aws_s3" # File storage backend to be used+file_storage_backend = "aws_s3" # File storage backend to be used (file_system | aws_s3 | oci_object_storage)[file_storage.aws_s3]region = "us-east-1" # The AWS region used by the AWS S3 for file storagebucket_name = "bucket1" # The AWS S3 bucket name for file storage+# Used when file_storage_backend = "oci_object_storage" (requires the `oci_object_storage` feature,+# included in release builds). Files go through OCI's S3 Compatibility API;+# authenticate with an OCI Customer Secret Key in AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY.+# [file_storage.oci_object_storage]+# namespace = "namespace" # The Object Storage namespace of the tenancy+# region = "us-ashburn-1" # The OCI region identifier of the bucket+# bucket_name = "bucket1" # The OCI Object Storage bucket name for file storage+[secrets_management]secrets_manager = "aws_kms" # Secrets manager client to be used (no_encryption | aws_kms | hashicorp_vault | gcp_kms | oci_kms)diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.tomlindex a454c5638e..d2df89822f 100644--- a/config/deployments/env_specific.toml+++ b/config/deployments/env_specific.toml@@ -130,12 +130,20 @@ account_updater_topic = "topic" # Kafka topic to be used for Account Upd# File storage configuration[file_storage]-file_storage_backend = "aws_s3" # File storage backend to be used+file_storage_backend = "aws_s3" # File storage backend to be used (file_system | aws_s3 | oci_object_storage)[file_storage.aws_s3]region = "bucket_region" # The AWS region used by AWS S3 for file storagebucket_name = "bucket" # The AWS S3 bucket name for file storage+# Used when file_storage_backend = "oci_object_storage" (requires the `oci_object_storage` feature,+# included in release builds). Files go through OCI's S3 Compatibility API;+# authenticate with an OCI Customer Secret Key in AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY.+# [file_storage.oci_object_storage]+# namespace = "namespace" # The Object Storage namespace of the tenancy+# region = "bucket_region" # The OCI region identifier of the bucket, such as us-ashburn-1+# bucket_name = "bucket" # The OCI Object Storage bucket name for file storage+# This section provides configs for currency conversion api[forex_api]api_key = "" # Api key for making request to foreign exchange Api@@ -474,12 +482,18 @@ service = "dynamo" # Service namebase_url = "http://127.0.0.1:8080" #Base URL[theme.storage]-file_storage_backend = "aws_s3" # Theme storage backend to be used+file_storage_backend = "aws_s3" # Theme storage backend to be used (file_system | aws_s3 | oci_object_storage)[theme.storage.aws_s3]region = "bucket_region" # AWS region where the S3 bucket for theme storage is locatedbucket_name = "bucket" # AWS S3 bucket name for theme storage+# Used when file_storage_backend = "oci_object_storage"; see [file_storage.oci_object_storage].+# [theme.storage.oci_object_storage]+# namespace = "namespace" # The Object Storage namespace of the tenancy+# region = "bucket_region" # OCI region identifier where the theme storage bucket is located+# bucket_name = "bucket" # OCI Object Storage bucket name for theme storage+[theme.email_config]entity_name = "Hyperswitch" # Name of the entity to be showed in emailsentity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emailsdiff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.tomlindex 67c8a30324..d8349d6f15 100644--- a/crates/external_services/Cargo.toml+++ b/crates/external_services/Cargo.toml@@ -11,6 +11,7 @@ license.workspace = trueaws_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"]hashicorp-vault = ["dep:vaultrs"]diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rsindex cb1966083e..55ed04fb43 100644--- a/crates/external_services/src/file_storage.rs+++ b/crates/external_services/src/file_storage.rs@@ -7,12 +7,17 @@ use std::{use common_utils::errors::CustomResult;-/// Includes functionality for AWS S3 storage operations.-#[cfg(feature = "aws_s3")]+/// Includes functionality for AWS S3 storage operations, and the S3 client that OCI Object+/// Storage also uses.+#[cfg(any(feature = "aws_s3", feature = "oci_object_storage"))]mod aws_s3;mod file_system;+/// Includes functionality for OCI Object Storage, through its S3 Compatibility API.+#[cfg(feature = "oci_object_storage")]+mod oci_object_storage;+/// Enum representing different file storage configurations, allowing for multiple storage schemes.#[derive(Debug, Clone, Default, serde::Deserialize)]#[serde(tag = "file_storage_backend")]@@ -24,6 +29,12 @@ pub enum FileStorageConfig {/// Configuration for AWS S3 file storage.aws_s3: aws_s3::AwsFileStorageConfig,},+ /// OCI Object Storage configuration.+ #[cfg(feature = "oci_object_storage")]+ OciObjectStorage {+ /// Configuration for OCI Object Storage.+ oci_object_storage: oci_object_storage::OciFileStorageConfig,+ },/// Local file system storage configuration.#[default]FileSystem,@@ -35,6 +46,8 @@ impl FileStorageConfig {match self {#[cfg(feature = "aws_s3")]Self::AwsS3 { aws_s3 } => aws_s3.validate(),+ #[cfg(feature = "oci_object_storage")]+ Self::OciObjectStorage { oci_object_storage } => oci_object_storage.validate(),Self::FileSystem => Ok(()),}}@@ -44,6 +57,10 @@ impl FileStorageConfig {match self {#[cfg(feature = "aws_s3")]Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),+ #[cfg(feature = "oci_object_storage")]+ Self::OciObjectStorage { oci_object_storage } => {+ Arc::new(oci_object_storage::client(oci_object_storage).await)+ }Self::FileSystem => Arc::new(file_system::FileSystem),}}diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rsindex 2e13be51e1..bbc9a850dc 100644--- a/crates/external_services/src/file_storage/aws_s3.rs+++ b/crates/external_services/src/file_storage/aws_s3.rs@@ -11,13 +11,17 @@ use aws_sdk_s3::{Client,};use aws_sdk_sts::config::Region;-use common_utils::{errors::CustomResult, ext_traits::ConfigExt};+use common_utils::errors::CustomResult;+#[cfg(feature = "aws_s3")]+use common_utils::ext_traits::ConfigExt;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 {@@ -27,6 +31,7 @@ pub struct AwsFileStorageConfig {bucket_name: String,}+#[cfg(feature = "aws_s3")]impl AwsFileStorageConfig {/// Validates the AWS S3 file storage configuration.pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {@@ -44,6 +49,30 @@ impl AwsFileStorageConfig {}}+/// 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 {@@ -55,12 +84,22 @@ pub(super) struct AwsFileStorageClient {impl AwsFileStorageClient {/// Creates a new AWS S3 file storage client.+ #[cfg(feature = "aws_s3")]pub(super) async fn new(config: &AwsFileStorageConfig) -> Self {- let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));+ 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: Client::new(&sdk_config),- bucket_name: config.bucket_name.clone(),+ inner_client: build_client(endpoint, &sdk_config),+ bucket_name: bucket_name.to_owned(),}}@@ -382,3 +421,77 @@ enum AwsS3StorageError {#[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};++ 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(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");++ #[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()+ }++ #[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/src/file_storage/oci_object_storage.rs b/crates/external_services/src/file_storage/oci_object_storage.rsnew file mode 100644index 0000000000..61ec0fd971--- /dev/null+++ b/crates/external_services/src/file_storage/oci_object_storage.rs@@ -0,0 +1,173 @@+//! OCI Object Storage, accessed through its Amazon S3 Compatibility API.++use common_utils::{ext_traits::ConfigExt, fp_utils::when};++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 == '-')+}++/// 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}"+ );+ }+}diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 462295474c..c2155d96a7 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -60,6 +60,7 @@ frm = [stripe = []gcp_kms = ["external_services/gcp_kms"]oci_kms = ["external_services/oci_kms"]+oci_object_storage = ["external_services/oci_object_storage"]release = ["stripe","email",@@ -70,6 +71,7 @@ release = ["gcp_kms","oci_kms","external_services/aws_s3",+ "oci_object_storage","keymanager_mtls","keymanager_create","encryption_service",