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
refactor(router): remove deprecated ephemeral key routes (#15099)
Ayush Anandc53f4b4426ac
diff --git a/api-reference/essentials/authentication.mdx b/api-reference/essentials/authentication.mdxindex 956cccca9e..7173f73596 100644--- a/api-reference/essentials/authentication.mdx+++ b/api-reference/essentials/authentication.mdx@@ -70,13 +70,7 @@ Admin credentials in the `api-key` header are no longer accepted. V1 merchant an- Prefix: `pk_{environment}_{uuid}`.- Generated during merchant account creation.-## 4. Ephemeral Key--- **Temporary key** for limited operations.-- Used for single or short-lived access (e.g., accessing a specific customer object).-- Validity is configurable (see `[eph_key] validity` in `development.toml`).--## 5. JWT Key+## 4. JWT Key- **JWT Bearer Token** used for API authentication and session management.- Required for certain JWT-protected endpoints and user authentication flows.@@ -108,7 +102,6 @@ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...| Secret (API Key) | snd_c69***, prod_*** | Backend server API requests | Keep secret || Admin API Key | (admin-specific) | Admin operations | Highly confidential || Publishable Key | pk_snd_3b3*** | Client-side, public usage | Safe to expose |-| Ephemeral Key | (short-lived) | Temporary, limited access | Short validity, limited || JWT Key | (JWT Bearer) | Session/user authentication | Control center calls |</Table>diff --git a/api-reference/essentials/error_codes.mdx b/api-reference/essentials/error_codes.mdxindex 8471c17689..4124fdf7f4 100644--- a/api-reference/essentials/error_codes.mdx+++ b/api-reference/essentials/error_codes.mdx@@ -34,7 +34,6 @@ The section below contains all the error codes and their corresponding error mes| IR_12 | 400 | invalid_request_error | Reached the maximum refund attempts | Maximum refund attempts reached for this payment. Please contact Hyperswitch support for attempting more refunds for the same payment || IR_13 | 400 | invalid_request_error | Refund amount exceeds the payment amount | Please verify and pass a refund amount equal to or less than the payment amount || IR_14 | 400 | invalid_request_error | This Payment could not be “current_flow” because it has a “field_name” of “current_value”. The expected state is “states” | Please verify the status of the payment and make sure that you are performing an action that is allowed for the current status of the payment |-| IR_15 | 400 | invalid_request_error | Invalid Ephemeral Key for the customer | Please pass the right Ephemeral key for the customer || IR_16 | 400 | invalid_request_error | “message” | Typically used when information involving multiple fields or previously provided information doesn’t satisfy a condition. Refer to our API documentation for required fields and format || IR_17 | 401 | invalid_request_error | Access forbidden, an invalid JWT token was used | Provide a valid JWT token to access the APIs || IR_18 | 401 | invalid_request_error | "message" | The user is not authorised to update the customer, Contact Org. Admin for the appropriate access. |diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 34db1b3043..c0f0bbb604 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -349,10 +349,6 @@},"customer_id": "cus_abcdefgh","description": "Its my first payment request",- "ephemeral_key": {- "customer_id": "cus_abcdefgh",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"expires_on": "2023-10-26T10:20:00Z","merchant_id": "merchant_myyyyyyyyyyyy","metadata": {@@ -409,10 +405,6 @@"created": "2023-10-26T10:20:00Z","currency": "USD","customer_id": "StripeCustomer123",- "ephemeral_key": {- "customer_id": "StripeCustomer123",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"mandate_data": {"customer_acceptance": {"acceptance_type": "online",@@ -483,10 +475,6 @@"created": "2023-10-26T10:25:00Z","currency": "USD","customer_id": "StripeCustomer123",- "ephemeral_key": {- "customer_id": "StripeCustomer123",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"merchant_connector_id": "mca_mcaconnectorxxxx","merchant_id": "merchant_myyyyyyyyyyyy","payment_id": "pay_savecard_xxxxxxxxxxxx",@@ -555,10 +543,6 @@"phone": "9123456789"},"customer_id": "cus_abcdefgh",- "ephemeral_key": {- "customer_id": "cus_abcdefgh",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"expires_on": "2023-10-26T10:45:00Z","merchant_id": "merchant_myyyyyyyyyyyy","payment_id": "pay_manualbill_xxxxxxxxxxxx",@@ -597,10 +581,6 @@"phone": "9123456789"},"customer_id": "cus_abcdefgh",- "ephemeral_key": {- "customer_id": "cus_abcdefgh",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"expires_on": "2023-10-26T10:45:00Z","merchant_id": "merchant_myyyyyyyyyyyy","payment_id": "pay_manualbill_xxxxxxxxxxxx",@@ -640,10 +620,6 @@"phone": "9123456789"},"customer_id": "cus_abcdefgh",- "ephemeral_key": {- "customer_id": "cus_abcdefgh",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"expires_on": "2023-10-26T10:45:00Z","merchant_id": "merchant_myyyyyyyyyyyy","payment_id": "pay_manualbill_xxxxxxxxxxxx",@@ -2484,9 +2460,6 @@"security": [{"api_key": []- },- {- "ephemeral_key": []}]}@@ -3934,9 +3907,6 @@"security": [{"api_key": []- },- {- "ephemeral_key": []}]},@@ -4769,7 +4739,7 @@},"security": [{- "ephemeral_key": []+ "api_key": []}]}@@ -24027,39 +23997,6 @@}}},- "EphemeralKeyCreateResponse": {- "type": "object",- "description": "ephemeral_key for the customer_id mentioned",- "required": [- "customer_id",- "created_at",- "expires",- "secret"- ],- "properties": {- "customer_id": {- "type": "string",- "description": "customer_id to which this ephemeral key belongs to",- "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",- "maxLength": 64,- "minLength": 1- },- "created_at": {- "type": "integer",- "format": "int64",- "description": "time at which this ephemeral key was created"- },- "expires": {- "type": "integer",- "format": "int64",- "description": "time at which this ephemeral key would expire"- },- "secret": {- "type": "string",- "description": "ephemeral key"- }- }- },"ErrorCategory": {"type": "string","enum": [@@ -52174,12 +52111,6 @@"scheme": "basic","description": "HTTP Basic authentication with a merchant API key as the password. The username is ignored. Used by endpoints that a third party posts to, such as telephone order providers."},- "ephemeral_key": {- "type": "apiKey",- "in": "header",- "name": "api-key",- "description": "Ephemeral keys provide temporary access to singular data, such as access to a single customer object for a short period of time."- },"jwt_key": {"type": "http","scheme": "bearer",diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 84c9ca5e72..00e91dd5f8 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -5327,9 +5327,6 @@}},"security": [- {- "ephemeral_key": []- },{"api_key": []}@@ -5384,9 +5381,6 @@}},"security": [- {- "ephemeral_key": []- },{"api_key": []}diff --git a/config/config.example.toml b/config/config.example.tomlindex 7c09a301e8..2c989c0573 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -322,7 +322,7 @@ redis_lock_expiry_seconds = 180[merchant_id_auth]merchant_id_auth_enabled = false-# Validity of an Ephemeral Key in Hours+# Validity of a v2 client secret in hours[eph_key]validity = 1diff --git a/crates/api_models/src/ephemeral_key.rs b/crates/api_models/src/client_secret.rssimilarity index 50%rename from crates/api_models/src/ephemeral_key.rsrename to crates/api_models/src/client_secret.rsindex 3a888ece3d..8d78abf59c 100644--- a/crates/api_models/src/ephemeral_key.rs+++ b/crates/api_models/src/client_secret.rs@@ -1,23 +1,8 @@use common_utils::id_type;#[cfg(feature = "v2")]use hyperswitch_masking::Secret;-use smithy::SmithyModel;use utoipa::ToSchema;-#[cfg(feature = "v1")]-/// Information required to create an ephemeral key.-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct EphemeralKeyCreateRequest {- /// Customer ID for which an ephemeral key must be created- #[schema(- min_length = 1,- max_length = 64,- value_type = String,- example = "cus_y3oqhf46pyzuxjbcn2giaqnb44"- )]- pub customer_id: id_type::CustomerId,-}-#[cfg(feature = "v2")]#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]#[serde(rename_all = "snake_case")]@@ -53,20 +38,6 @@ pub struct ClientSecretResponse {pub secret: Secret<String>,}-#[cfg(feature = "v1")]-impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest {- fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {- Some(common_utils::events::ApiEventsType::Miscellaneous)- }-}--#[cfg(feature = "v1")]-impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse {- fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {- Some(common_utils::events::ApiEventsType::Miscellaneous)- }-}-#[cfg(feature = "v2")]impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest {fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {@@ -80,25 +51,3 @@ impl common_utils::events::ApiEventMetric for ClientSecretResponse {Some(common_utils::events::ApiEventsType::Miscellaneous)}}--#[cfg(feature = "v1")]-/// ephemeral_key for the customer_id mentioned-#[derive(- Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema, SmithyModel,-)]-#[smithy(namespace = "com.hyperswitch.smithy.types")]-pub struct EphemeralKeyCreateResponse {- /// customer_id to which this ephemeral key belongs to- #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]- #[smithy(value_type = "String")]- pub customer_id: id_type::CustomerId,- /// time at which this ephemeral key was created- #[smithy(value_type = "i64")]- pub created_at: i64,- /// time at which this ephemeral key would expire- #[smithy(value_type = "i64")]- pub expires: i64,- /// ephemeral key- #[smithy(value_type = "String")]- pub secret: String,-}diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rsindex fa44d620e2..390c19c649 100644--- a/crates/api_models/src/lib.rs+++ b/crates/api_models/src/lib.rs@@ -6,6 +6,8 @@ pub mod authentication;pub mod blocklist;pub mod card_issuer;pub mod cards_info;+#[cfg(feature = "v2")]+pub mod client_secret;pub mod conditional_configs;pub mod connector_enums;pub mod connector_onboarding;@@ -14,7 +16,6 @@ pub mod currency;pub mod customers;pub mod disputes;pub mod enums;-pub mod ephemeral_key;#[cfg(feature = "errors")]pub mod errors;pub mod events;diff --git a/crates/common_utils/src/id_type/client_secret.rs b/crates/common_utils/src/id_type/client_secret.rsindex 5f9de6384e..0524594f47 100644--- a/crates/common_utils/src/id_type/client_secret.rs+++ b/crates/common_utils/src/id_type/client_secret.rs@@ -1,6 +1,6 @@crate::id_type!(ClientSecretId,- "A type for key_id that can be used for Ephemeral key IDs"+ "A type for key_id that can be used for client secret IDs");crate::impl_id_type_methods!(ClientSecretId, "key_id");diff --git a/crates/diesel_models/src/ephemeral_key.rs b/crates/diesel_models/src/client_secret.rssimilarity index 56%rename from crates/diesel_models/src/ephemeral_key.rsrename to crates/diesel_models/src/client_secret.rsindex 7ac9452d17..b3af2863cd 100644--- a/crates/diesel_models/src/ephemeral_key.rs+++ b/crates/diesel_models/src/client_secret.rs@@ -26,26 +26,3 @@ impl ClientSecretType {format!("cs_{}", self.secret.peek())}}--pub struct EphemeralKeyNew {- pub id: String,- pub merchant_id: common_utils::id_type::MerchantId,- pub customer_id: common_utils::id_type::CustomerId,- pub secret: String,-}--#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]-pub struct EphemeralKey {- pub id: String,- pub merchant_id: common_utils::id_type::MerchantId,- pub customer_id: common_utils::id_type::CustomerId,- pub created_at: i64,- pub expires: i64,- pub secret: String,-}--impl common_utils::events::ApiEventMetric for EphemeralKey {- fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {- Some(common_utils::events::ApiEventsType::Miscellaneous)- }-}diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rsindex 6f9e3ea4f4..b8db1a5b8a 100644--- a/crates/diesel_models/src/lib.rs+++ b/crates/diesel_models/src/lib.rs@@ -15,11 +15,11 @@ pub mod authorization;pub mod blocklist;pub mod blocklist_fingerprint;pub mod callback_mapper;+pub mod client_secret;pub mod customers;pub mod dispute;pub mod dynamic_routing_stats;pub mod enums;-pub mod ephemeral_key;pub mod errors;pub mod events;pub mod file;@@ -137,12 +137,14 @@ impl<'pool> DatabaseConnectionWithContext<'pool> {}}+#[cfg(feature = "v2")]+pub use self::client_secret::*;pub use self::{address::*, api_keys::*, callback_mapper::*, capture::*, cards_info::*, configs::*,- customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,- locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*,- payment_attempt::*, payment_intent::*, payment_method::*, payout_attempt::*, payouts::*,- process_tracker::*, refund::*, reverse_lookup::*, user_authentication_method::*,+ customers::*, dispute::*, events::*, file::*, generic_link::*, locker_mock_up::*, mandate::*,+ merchant_account::*, merchant_connector_account::*, payment_attempt::*, payment_intent::*,+ payment_method::*, payout_attempt::*, payouts::*, process_tracker::*, refund::*,+ reverse_lookup::*, user_authentication_method::*,};/// The types and implementations provided by this module are required for the schema generated by/// `diesel_cli` 2.0 to work with the types defined in Rust code. This is becausediff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rsindex 689bb1bbb2..9f93ac593f 100644--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs@@ -222,8 +222,6 @@ pub enum ApiErrorResponse {current_value: String,states: String,},- #[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]- InvalidEphemeralKey,/// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.#[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]PreconditionFailed { message: String },@@ -625,7 +623,6 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponcurrent_value,states,} => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),- Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),Self::PreconditionFailed { message } => {AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex f364d66a2a..1fabe3c352 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -919,7 +919,6 @@ Never share your secret api keys. Keep them guarded and secure.api_models::mandates::NetworkTokenWithVaultCardFallback,api_models::mandates::VaultCardData,api_models::mandates::ProcessorPaymentToken,- api_models::ephemeral_key::EphemeralKeyCreateResponse,api_models::payments::CustomerDetails,api_models::payments::GiftCardData,api_models::payments::GiftCardDetails,@@ -1307,14 +1306,6 @@ impl utoipa::Modify for SecurityAddon {scope of usage."))),),- (- "ephemeral_key",- SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(- "api-key",- "Ephemeral keys provide temporary access to singular data, such as access \- to a single customer object for a short period of time."- ))),- ),("basic_api_key",SecurityScheme::Http(diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 5613341c66..1f4ec82282 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -305,7 +305,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::customers::CustomerUpdateRequest,api_models::customers::CustomerDeleteResponse,api_models::customers::CustomerDocumentDetails,- api_models::ephemeral_key::ResourceId,+ api_models::client_secret::ResourceId,api_models::payment_methods::PaymentMethodCreate,api_models::payment_methods::PaymentMethodIntentCreate,api_models::payment_methods::PaymentMethodIntentConfirm,@@ -786,7 +786,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::mandates::MandateCardDetails,api_models::mandates::RecurringDetails,api_models::mandates::ProcessorPaymentToken,- api_models::ephemeral_key::ClientSecretResponse,+ api_models::client_secret::ClientSecretResponse,api_models::payments::CustomerDetails,api_models::payments::GiftCardData,api_models::payments::BalanceCheckPaymentMethodData,diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rsindex 6202721d80..809fa572f3 100644--- a/crates/openapi/src/routes/customers.rs+++ b/crates/openapi/src/routes/customers.rs@@ -39,7 +39,7 @@ pub async fn customers_create() {}),tag = "Customers",operation_id = "Retrieve a Customer",- security(("api_key" = []), ("ephemeral_key" = []))+ security(("api_key" = [])))]#[cfg(feature = "v1")]pub async fn customers_retrieve() {}diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rsindex 442ed5ee0e..e6e5288c02 100644--- a/crates/openapi/src/routes/payment_method.rs+++ b/crates/openapi/src/routes/payment_method.rs@@ -233,7 +233,7 @@ pub async fn payment_method_delete_api() {}),tag = "Payment Methods",operation_id = "Set the Payment Method as Default",- security(("ephemeral_key" = []))+ security(("api_key" = [])))]#[cfg(feature = "v1")]pub async fn default_payment_method_set_api() {}diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rsindex 83f9e9b450..4d2b38940d 100644--- a/crates/openapi/src/routes/payments.rs+++ b/crates/openapi/src/routes/payments.rs@@ -314,10 +314,6 @@},"client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:05:00Z",- "ephemeral_key": {- "customer_id": "cus_abcdefgh",- "secret": "epk_ephemeralxxxxxxxxxxxx"- },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"expires_on": "2023-10-26T10:20:00Z"@@ -381,7 +377,6 @@"authentication_type": "no_three_ds","client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:20:00Z",- "ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"merchant_connector_id": "mca_mcaconnectorxxxx",@@ -430,7 +425,6 @@"authentication_type": "no_three_ds","client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:25:00Z",- "ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"merchant_connector_id": "mca_mcaconnectorxxxx",@@ -482,7 +476,6 @@},"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:30:00Z",- "ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"expires_on": "2023-10-26T10:45:00Z"@@ -515,7 +508,6 @@},"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:30:00Z",- "ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"expires_on": "2023-10-26T10:45:00Z"@@ -548,7 +540,6 @@},"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz","created": "2023-10-26T10:30:00Z",- "ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },"profile_id": "pro_pzzzzzzzzzzz","attempt_count": 1,"expires_on": "2023-10-26T10:45:00Z"diff --git a/crates/openapi/src/routes/relay.rs b/crates/openapi/src/routes/relay.rsindex cd9540bae5..6cfaffe68b 100644--- a/crates/openapi/src/routes/relay.rs+++ b/crates/openapi/src/routes/relay.rs@@ -65,7 +65,7 @@ pub async fn relay() {}),tag = "Relay",operation_id = "Retrieve a Relay details",- security(("api_key" = []), ("ephemeral_key" = []))+ security(("api_key" = [])))]pub async fn relay_retrieve() {}diff --git a/crates/openapi/src/routes/tokenization.rs b/crates/openapi/src/routes/tokenization.rsindex 8e190960f7..b5fffb5d46 100644--- a/crates/openapi/src/routes/tokenization.rs+++ b/crates/openapi/src/routes/tokenization.rs@@ -31,7 +31,7 @@ use utoipa::OpenApi;),tag = "Tokenization",operation_id = "create_token_vault_api",- security(("ephemeral_key" = []),("api_key" = []))+ security(("api_key" = [])))]pub async fn create_token_vault_api() {}@@ -59,7 +59,7 @@ pub async fn create_token_vault_api() {}),tag = "Tokenization",operation_id = "delete_tokenized_data_api",- security(("ephemeral_key" = []),("api_key" = []))+ security(("api_key" = [])))]pub async fn delete_tokenized_data_api() {}diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rsindex 2853292b4f..6a371fa26d 100644--- a/crates/router/src/compatibility/stripe/customers.rs+++ b/crates/router/src/compatibility/stripe/customers.rs@@ -239,7 +239,6 @@ pub async fn list_customer_payment_method_api(auth.platform,Some(req),Some(&customer_id),- None,)},&auth::HeaderAuth(auth::ApiKeyAuth {diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex 31ed278c00..df9d830009 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -469,7 +469,6 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {| errors::ApiErrorResponse::GenericUnauthorized { .. }| errors::ApiErrorResponse::AccessForbidden { .. }| errors::ApiErrorResponse::InvalidCookie- | errors::ApiErrorResponse::InvalidEphemeralKey| errors::ApiErrorResponse::InvalidPaymentIdProvided { .. }| errors::ApiErrorResponse::ExpiredJwtToken| errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized,diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rsindex dee462b00a..e5fed7a23d 100644--- a/crates/router/src/configs/defaults.rs+++ b/crates/router/src/configs/defaults.rs@@ -104,7 +104,7 @@ impl Default for super::settings::Refund {}}-impl Default for super::settings::EphemeralConfig {+impl Default for super::settings::ClientSecretConfig {fn default() -> Self {Self { validity: 1 }}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 3825c7e5e7..dd6f7dfff3 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -104,7 +104,7 @@ pub struct Settings<S: SecretState> {pub connectors: Connectors,pub forex_api: SecretStateContainer<ForexApi, S>,pub refund: Refund,- pub eph_key: EphemeralConfig,+ pub eph_key: ClientSecretConfig,pub scheduler: Option<SchedulerSettings>,#[cfg(feature = "kv_store")]pub drainer: DrainerSettings,@@ -1166,7 +1166,7 @@ pub struct Refund {#[derive(Debug, Deserialize, Clone)]#[serde(default)]-pub struct EphemeralConfig {+pub struct ClientSecretConfig {pub validity: i64,}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 1ef3642f6c..d2207297ae 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -94,7 +94,7 @@ use crate::{types::{api::{PaymentMethodCreateExt, PaymentMethodSessionExt},domain::types as domain_types,- storage::{ephemeral_key, PaymentMethodListContext},+ storage::PaymentMethodListContext,transformers::{ForeignFrom, ForeignTryFrom},Tokenizable,},diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex a8622969ac..c9cc55a709 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -79,8 +79,6 @@ use crate::core::payment_methods::{use crate::core::payments::helpers as payments_helpers;#[cfg(feature = "v1")]use crate::core::payments::tokenization;-#[cfg(feature = "v1")]-use crate::routes::app::SessionStateInfo;#[cfg(feature = "payouts")]use crate::types::domain::types::AsyncLift;use crate::{@@ -6369,27 +6367,12 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(platform: domain::Platform,req: Option<api::PaymentMethodListRequest>,customer_id: Option<&id_type::CustomerId>,- ephemeral_api_key: Option<&str>,) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {let dimensions = dimension_state::Dimensions::new().with_processor_merchant_id(platform.get_processor().get_processor_merchant_id()).with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());let limit = req.clone().and_then(|pml_req| pml_req.limit);- let auth_cust = if let Some(key) = ephemeral_api_key {- let key = state- .store()- .get_ephemeral_key(key)- .await- .change_context(errors::ApiErrorResponse::Unauthorized)?;-- Some(key.customer_id.clone())- } else {- None- };-- let customer_id = customer_id.or(auth_cust.as_ref());-if let Some(customer_id) = customer_id {Box::pin(list_customer_payment_method(&state,diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex a3e3ae1bcb..1b7389d795 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -5,7 +5,7 @@ pub use ::payment_methods::helpers::{validate_payment_method_type_against_payment_method,};#[cfg(feature = "v2")]-use api_models::ephemeral_key::ClientSecretResponse;+use api_models::client_secret::ClientSecretResponse;#[cfg(feature = "v2")]use api_models::payments::{additional_info::UpiAdditionalData, UpiSource};use api_models::{@@ -86,6 +86,8 @@ use crate::core::{payments::{OperationSessionGetters, OperationSessionSetters},utils as core_utils,};+#[cfg(feature = "v2")]+use crate::types::storage::client_secret;use crate::{configs::settings::{ConnectorRequestReferenceIdConfig, MerchantAdviceCodeConfig,@@ -115,7 +117,7 @@ use crate::{self,types::{self, CryptoOperation},},- storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},+ storage::{self, enums as storage_enums, CardTokenData},transformers::{ForeignFrom, ForeignTryFrom},AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,@@ -4652,40 +4654,17 @@ pub fn make_merchant_url_with_response(Ok(merchant_url_with_response.to_string())}-#[cfg(feature = "v1")]-pub async fn make_ephemeral_key(- state: SessionState,- customer_id: id_type::CustomerId,- merchant_id: id_type::MerchantId,-) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {- let store = &state.store;- let id = utils::generate_id(consts::ID_LENGTH, "eki");- let secret = format!("epk_{}", common_utils::generate_uuid_v4().simple());- let ek = ephemeral_key::EphemeralKeyNew {- id,- customer_id,- merchant_id: merchant_id.to_owned(),- secret,- };- let ek = store- .create_ephemeral_key(ek, state.conf.eph_key.validity)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to create ephemeral key")?;- Ok(services::ApplicationResponse::Json(ek))-}-#[cfg(feature = "v2")]pub async fn make_client_secret(state: SessionState,- resource_id: api_models::ephemeral_key::ResourceId,+ resource_id: api_models::client_secret::ResourceId,platform: domain::Platform,headers: &actix_web::http::header::HeaderMap,) -> errors::RouterResponse<ClientSecretResponse> {let db = &state.store;match &resource_id {- api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => {+ api_models::client_secret::ResourceId::Customer(global_customer_id) => {db.find_customer_by_global_id(global_customer_id,platform.get_processor().get_key_store(),@@ -4697,7 +4676,7 @@ pub async fn make_client_secret(}let resource_id = match resource_id {- api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => {+ api_models::client_secret::ResourceId::Customer(global_customer_id) => {common_utils::types::authentication::ResourceId::Customer(global_customer_id)}};@@ -4721,14 +4700,14 @@ pub async fn create_client_secret(state: &SessionState,merchant_id: &id_type::MerchantId,resource_id: common_utils::types::authentication::ResourceId,-) -> RouterResult<ephemeral_key::ClientSecretType> {+) -> RouterResult<client_secret::ClientSecretType> {use common_utils::generate_time_ordered_id;let store = &state.store;let id = id_type::ClientSecretId::generate();let secret = hyperswitch_masking::Secret::new(generate_time_ordered_id("cs"));- let client_secret = ephemeral_key::ClientSecretTypeNew {+ let client_secret = client_secret::ClientSecretTypeNew {id,merchant_id: merchant_id.to_owned(),secret,@@ -4742,40 +4721,26 @@ pub async fn create_client_secret(Ok(client_secret)}-#[cfg(feature = "v1")]-pub async fn delete_ephemeral_key(- state: SessionState,- ek_id: String,-) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {- let db = state.store.as_ref();- let ek = db- .delete_ephemeral_key(&ek_id)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to delete ephemeral key")?;- Ok(services::ApplicationResponse::Json(ek))-}-#[cfg(feature = "v2")]pub async fn delete_client_secret(state: SessionState,- ephemeral_key_id: String,+ client_secret_id: String,) -> errors::RouterResponse<ClientSecretResponse> {let db = state.store.as_ref();- let ephemeral_key = db- .delete_client_secret(&ephemeral_key_id)+ let client_secret = db+ .delete_client_secret(&client_secret_id).await.map_err(|err| match err.current_context() {errors::StorageError::ValueNotFound(_) => {err.change_context(errors::ApiErrorResponse::GenericNotFoundError {- message: "Ephemeral Key not found".to_string(),+ message: "Client secret not found".to_string(),})}_ => err.change_context(errors::ApiErrorResponse::InternalServerError),})- .attach_printable("Unable to delete ephemeral key")?;+ .attach_printable("Unable to delete client secret")?;- let response = ClientSecretResponse::foreign_try_from(ephemeral_key)+ let response = ClientSecretResponse::foreign_try_from(client_secret).attach_printable("Only customer is supported as resource_id in response")?;Ok(services::ApplicationResponse::Json(response))}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 4cf037531f..a63ef1a339 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -28,12 +28,9 @@ use common_utils::{StringMajorUnitForConnector,},};-use diesel_models::{- ephemeral_key,- payment_attempt::{- ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,- NetworkDetails as DieselNetworkDetails,- },+use diesel_models::payment_attempt::{+ ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,+ NetworkDetails as DieselNetworkDetails,};#[cfg(all(feature = "v1", feature = "olap"))]use diesel_models::{@@ -5164,18 +5161,6 @@ impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)>}}-#[cfg(feature = "v1")]-impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse {- fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self {- Self {- customer_id: from.customer_id,- created_at: from.created_at,- expires: from.expires,- secret: from.secret,- }- }-}-#[cfg(feature = "v1")]pub fn bank_transfer_next_steps_check(payment_attempt: storage::PaymentAttempt,diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex ce9a2cf25e..c3834c95d4 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -11,12 +11,12 @@ pub mod business_profile;pub mod callback_mapper;pub mod capture;pub mod card_issuer;+pub mod client_secret;pub mod configs;pub mod customers;pub mod dashboard_metadata;pub mod dispute;pub mod dynamic_routing_stats;-pub mod ephemeral_key;pub mod events;pub mod file;pub mod fraud_check;@@ -111,8 +111,7 @@ pub trait StorageInterface:+ customers::CustomerInterface<Error = StorageError>+ dashboard_metadata::DashboardMetadataInterface+ dispute::DisputeInterface- + ephemeral_key::EphemeralKeyInterface- + ephemeral_key::ClientSecretInterface+ + client_secret::ClientSecretInterface+ events::EventInterface+ file::FileMetadataInterface+ FraudCheckInterfacediff --git a/crates/router/src/db/client_secret.rs b/crates/router/src/db/client_secret.rsnew file mode 100644index 0000000000..bed6ef8f4a--- /dev/null+++ b/crates/router/src/db/client_secret.rs@@ -0,0 +1,179 @@+#[cfg(feature = "v2")]+use common_utils::{date_time, id_type};+#[cfg(feature = "v2")]+use error_stack::ResultExt;+#[cfg(feature = "v2")]+use hyperswitch_masking::PeekInterface;+#[cfg(feature = "v2")]+use redis_interface::{errors::RedisError, HsetnxReply};+#[cfg(feature = "v2")]+use router_env::{instrument, tracing};+#[cfg(feature = "v2")]+use storage_impl::redis::kv_store::RedisConnInterface;+#[cfg(feature = "v2")]+use time::ext::NumericalDuration;++#[cfg(feature = "v2")]+use crate::core::errors::{self, CustomResult};+#[cfg(feature = "v2")]+use crate::types::storage::client_secret::{ClientSecretType, ClientSecretTypeNew};+use crate::{db::MockDb, services::Store};++#[async_trait::async_trait]+pub trait ClientSecretInterface {+ #[cfg(feature = "v2")]+ async fn create_client_secret(+ &self,+ _ek: ClientSecretTypeNew,+ _validity: i64,+ ) -> CustomResult<ClientSecretType, errors::StorageError>;++ #[cfg(feature = "v2")]+ async fn get_client_secret(+ &self,+ _key: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError>;++ #[cfg(feature = "v2")]+ async fn delete_client_secret(+ &self,+ _id: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError>;+}++#[async_trait::async_trait]+impl ClientSecretInterface for Store {+ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn create_client_secret(+ &self,+ new: ClientSecretTypeNew,+ validity: i64,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ let created_at = date_time::now();+ let expires = created_at.saturating_add(validity.hours());+ let id_key = new.id.generate_redis_key();++ let created_client_secret = ClientSecretType {+ id: new.id,+ created_at,+ expires,+ merchant_id: new.merchant_id,+ secret: new.secret,+ resource_id: new.resource_id,+ };+ let secret_key = created_client_secret.generate_secret_key();++ match self+ .get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .serialize_and_set_multiple_hash_field_if_not_exist(+ &[+ (&secret_key.as_str().into(), &created_client_secret),+ (&id_key.as_str().into(), &created_client_secret),+ ],+ "csh",+ None,+ )+ .await+ {+ Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => {+ Err(errors::StorageError::DuplicateValue {+ entity: "client secret",+ key: None,+ }+ .into())+ }+ Ok(_) => {+ let expire_at = expires.assume_utc().unix_timestamp();+ self.get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .set_expire_at(&secret_key.into(), expire_at)+ .await+ .change_context(errors::StorageError::KVError)?;+ self.get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .set_expire_at(&id_key.into(), expire_at)+ .await+ .change_context(errors::StorageError::KVError)?;+ Ok(created_client_secret)+ }+ Err(er) => Err(er).change_context(errors::StorageError::KVError),+ }+ }++ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn get_client_secret(+ &self,+ key: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ let key = format!("cs_{key}");+ self.get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType")+ .await+ .change_context(errors::StorageError::KVError)+ }++ #[cfg(feature = "v2")]+ async fn delete_client_secret(+ &self,+ id: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ let client_secret = self.get_client_secret(id).await?;+ let redis_id_key = client_secret.id.generate_redis_key();+ let secret_key = client_secret.generate_secret_key();++ self.get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .delete_key(&redis_id_key.as_str().into())+ .await+ .map_err(|err| match err.current_context() {+ RedisError::NotFound => {+ err.change_context(errors::StorageError::ValueNotFound(redis_id_key))+ }+ _ => err.change_context(errors::StorageError::KVError),+ })?;++ self.get_redis_conn()+ .map_err(Into::<errors::StorageError>::into)?+ .delete_key(&secret_key.as_str().into())+ .await+ .map_err(|err| match err.current_context() {+ RedisError::NotFound => {+ err.change_context(errors::StorageError::ValueNotFound(secret_key))+ }+ _ => err.change_context(errors::StorageError::KVError),+ })?;+ Ok(client_secret)+ }+}++#[async_trait::async_trait]+impl ClientSecretInterface for MockDb {+ #[cfg(feature = "v2")]+ async fn create_client_secret(+ &self,+ new: ClientSecretTypeNew,+ validity: i64,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ todo!()+ }++ #[cfg(feature = "v2")]+ async fn get_client_secret(+ &self,+ key: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ todo!()+ }++ #[cfg(feature = "v2")]+ async fn delete_client_secret(+ &self,+ id: &str,+ ) -> CustomResult<ClientSecretType, errors::StorageError> {+ todo!()+ }+}diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rsdeleted file mode 100644index 3f87075eb3..0000000000--- a/crates/router/src/db/ephemeral_key.rs+++ /dev/null@@ -1,373 +0,0 @@-#[cfg(feature = "v2")]-use common_utils::id_type;-use time::ext::NumericalDuration;--#[cfg(feature = "v2")]-use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};-use crate::{- core::errors::{self, CustomResult},- db::MockDb,- types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew},-};--#[async_trait::async_trait]-pub trait EphemeralKeyInterface {- #[cfg(feature = "v1")]- async fn create_ephemeral_key(- &self,- _ek: EphemeralKeyNew,- _validity: i64,- ) -> CustomResult<EphemeralKey, errors::StorageError>;-- #[cfg(feature = "v1")]- async fn get_ephemeral_key(- &self,- _key: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError>;-- #[cfg(feature = "v1")]- async fn delete_ephemeral_key(- &self,- _id: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError>;-}--#[async_trait::async_trait]-pub trait ClientSecretInterface {- #[cfg(feature = "v2")]- async fn create_client_secret(- &self,- _ek: ClientSecretTypeNew,- _validity: i64,- ) -> CustomResult<ClientSecretType, errors::StorageError>;-- #[cfg(feature = "v2")]- async fn get_client_secret(- &self,- _key: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError>;-- #[cfg(feature = "v2")]- async fn delete_client_secret(- &self,- _id: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError>;-}--mod storage {- use common_utils::date_time;- #[cfg(feature = "v2")]- use common_utils::id_type;- use error_stack::ResultExt;- #[cfg(feature = "v2")]- use hyperswitch_masking::PeekInterface;- #[cfg(feature = "v2")]- use redis_interface::errors::RedisError;- use redis_interface::HsetnxReply;- use router_env::{instrument, tracing};- use storage_impl::redis::kv_store::RedisConnInterface;- use time::ext::NumericalDuration;-- use super::{ClientSecretInterface, EphemeralKeyInterface};- #[cfg(feature = "v2")]- use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};- use crate::{- core::errors::{self, CustomResult},- services::Store,- types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew},- };-- #[async_trait::async_trait]- impl EphemeralKeyInterface for Store {- #[cfg(feature = "v1")]- #[instrument(skip_all)]- async fn create_ephemeral_key(- &self,- new: EphemeralKeyNew,- validity: i64,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- let secret_key = format!("epkey_{}", new.secret);- let id_key = format!("epkey_{}", new.id);-- let created_at = date_time::now();- let expires = created_at.saturating_add(validity.hours());- let created_ek = EphemeralKey {- id: new.id,- created_at: created_at.assume_utc().unix_timestamp(),- expires: expires.assume_utc().unix_timestamp(),- customer_id: new.customer_id,- merchant_id: new.merchant_id,- secret: new.secret,- };-- match self- .get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .serialize_and_set_multiple_hash_field_if_not_exist(- &[- (&secret_key.as_str().into(), &created_ek),- (&id_key.as_str().into(), &created_ek),- ],- "ephkey",- None,- )- .await- {- Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => {- Err(errors::StorageError::DuplicateValue {- entity: "ephemeral key",- key: None,- }- .into())- }- Ok(_) => {- let expire_at = expires.assume_utc().unix_timestamp();- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .set_expire_at(&secret_key.into(), expire_at)- .await- .change_context(errors::StorageError::KVError)?;- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .set_expire_at(&id_key.into(), expire_at)- .await- .change_context(errors::StorageError::KVError)?;- Ok(created_ek)- }- Err(er) => Err(er).change_context(errors::StorageError::KVError),- }- }-- #[cfg(feature = "v1")]- #[instrument(skip_all)]- async fn get_ephemeral_key(- &self,- key: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- let key = format!("epkey_{key}");- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey")- .await- .change_context(errors::StorageError::KVError)- }-- #[cfg(feature = "v1")]- async fn delete_ephemeral_key(- &self,- id: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- let ek = self.get_ephemeral_key(id).await?;-- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .delete_key(&format!("epkey_{}", ek.id).into())- .await- .change_context(errors::StorageError::KVError)?;-- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .delete_key(&format!("epkey_{}", ek.secret).into())- .await- .change_context(errors::StorageError::KVError)?;- Ok(ek)- }- }-- #[async_trait::async_trait]- impl ClientSecretInterface for Store {- #[cfg(feature = "v2")]- #[instrument(skip_all)]- async fn create_client_secret(- &self,- new: ClientSecretTypeNew,- validity: i64,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- let created_at = date_time::now();- let expires = created_at.saturating_add(validity.hours());- let id_key = new.id.generate_redis_key();-- let created_client_secret = ClientSecretType {- id: new.id,- created_at,- expires,- merchant_id: new.merchant_id,- secret: new.secret,- resource_id: new.resource_id,- };- let secret_key = created_client_secret.generate_secret_key();-- match self- .get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .serialize_and_set_multiple_hash_field_if_not_exist(- &[- (&secret_key.as_str().into(), &created_client_secret),- (&id_key.as_str().into(), &created_client_secret),- ],- "csh",- None,- )- .await- {- Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => {- Err(errors::StorageError::DuplicateValue {- entity: "ephemeral key",- key: None,- }- .into())- }- Ok(_) => {- let expire_at = expires.assume_utc().unix_timestamp();- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .set_expire_at(&secret_key.into(), expire_at)- .await- .change_context(errors::StorageError::KVError)?;- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .set_expire_at(&id_key.into(), expire_at)- .await- .change_context(errors::StorageError::KVError)?;- Ok(created_client_secret)- }- Err(er) => Err(er).change_context(errors::StorageError::KVError),- }- }-- #[cfg(feature = "v2")]- #[instrument(skip_all)]- async fn get_client_secret(- &self,- key: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- let key = format!("cs_{key}");- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType")- .await- .change_context(errors::StorageError::KVError)- }-- #[cfg(feature = "v2")]- async fn delete_client_secret(- &self,- id: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- let client_secret = self.get_client_secret(id).await?;- let redis_id_key = client_secret.id.generate_redis_key();- let secret_key = client_secret.generate_secret_key();-- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .delete_key(&redis_id_key.as_str().into())- .await- .map_err(|err| match err.current_context() {- RedisError::NotFound => {- err.change_context(errors::StorageError::ValueNotFound(redis_id_key))- }- _ => err.change_context(errors::StorageError::KVError),- })?;-- self.get_redis_conn()- .map_err(Into::<errors::StorageError>::into)?- .delete_key(&secret_key.as_str().into())- .await- .map_err(|err| match err.current_context() {- RedisError::NotFound => {- err.change_context(errors::StorageError::ValueNotFound(secret_key))- }- _ => err.change_context(errors::StorageError::KVError),- })?;- Ok(client_secret)- }- }-}--#[async_trait::async_trait]-impl EphemeralKeyInterface for MockDb {- #[cfg(feature = "v1")]- async fn create_ephemeral_key(- &self,- ek: EphemeralKeyNew,- validity: i64,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- let mut ephemeral_keys = self.ephemeral_keys.lock().await;- let created_at = common_utils::date_time::now();- let expires = created_at.saturating_add(validity.hours());-- let ephemeral_key = EphemeralKey {- id: ek.id,- merchant_id: ek.merchant_id,- customer_id: ek.customer_id,- created_at: created_at.assume_utc().unix_timestamp(),- expires: expires.assume_utc().unix_timestamp(),- secret: ek.secret,- };- ephemeral_keys.push(ephemeral_key.clone());- Ok(ephemeral_key)- }-- #[cfg(feature = "v1")]- async fn get_ephemeral_key(- &self,- key: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- match self- .ephemeral_keys- .lock()- .await- .iter()- .find(|ephemeral_key| ephemeral_key.secret.eq(key))- {- Some(ephemeral_key) => Ok(ephemeral_key.clone()),- None => Err(- errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(),- ),- }- }-- #[cfg(feature = "v1")]- async fn delete_ephemeral_key(- &self,- id: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- let mut ephemeral_keys = self.ephemeral_keys.lock().await;- if let Some(pos) = ephemeral_keys.iter().position(|x| (*x.id).eq(id)) {- let ek = ephemeral_keys.remove(pos);- Ok(ek)- } else {- return Err(- errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(),- );- }- }-}--#[async_trait::async_trait]-impl ClientSecretInterface for MockDb {- #[cfg(feature = "v2")]- async fn create_client_secret(- &self,- new: ClientSecretTypeNew,- validity: i64,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- todo!()- }-- #[cfg(feature = "v2")]- async fn get_client_secret(- &self,- key: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- todo!()- }-- #[cfg(feature = "v2")]- async fn delete_client_secret(- &self,- id: &str,- ) -> CustomResult<ClientSecretType, errors::StorageError> {- todo!()- }-}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 3ceb6d294a..7ffb45e545 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -8,10 +8,9 @@ use common_utils::{types::{keymanager::KeyManagerState, user::ThemeLineage, TenantConfig},};#[cfg(feature = "v2")]-use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};+use diesel_models::client_secret::{ClientSecretType, ClientSecretTypeNew};use diesel_models::{enums::{self, ProcessTrackerStatus},- ephemeral_key::{EphemeralKey, EphemeralKeyNew},refund as diesel_refund,reverse_lookup::{ReverseLookup, ReverseLookupNew},user_role as user_storage,@@ -55,8 +54,8 @@ use storage_impl::revenue_recovery_retry_stats;use time::PrimitiveDateTime;use super::{+ client_secret::ClientSecretInterface,dashboard_metadata::DashboardMetadataInterface,- ephemeral_key::ClientSecretInterface,role::RoleInterface,user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface},user_authentication_method::UserAuthenticationMethodInterface,@@ -78,7 +77,6 @@ use crate::{configs::ConfigInterface,customers::CustomerInterface,dispute::DisputeInterface,- ephemeral_key::EphemeralKeyInterface,events::EventInterface,file::FileMetadataInterface,generic_link::GenericLinkInterface,@@ -736,34 +734,6 @@ impl DisputeInterface for KafkaStore {}}-#[async_trait::async_trait]-impl EphemeralKeyInterface for KafkaStore {- #[cfg(feature = "v1")]- async fn create_ephemeral_key(- &self,- ek: EphemeralKeyNew,- validity: i64,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- self.diesel_store.create_ephemeral_key(ek, validity).await- }-- #[cfg(feature = "v1")]- async fn get_ephemeral_key(- &self,- key: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- self.diesel_store.get_ephemeral_key(key).await- }-- #[cfg(feature = "v1")]- async fn delete_ephemeral_key(- &self,- id: &str,- ) -> CustomResult<EphemeralKey, errors::StorageError> {- self.diesel_store.delete_ephemeral_key(id).await- }-}-#[async_trait::async_trait]impl ClientSecretInterface for KafkaStore {#[cfg(feature = "v2")]diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rsindex 87dc38e345..5e0fda646b 100644--- a/crates/router/src/lib.rs+++ b/crates/router/src/lib.rs@@ -309,9 +309,9 @@ pub fn mk_app(}}- #[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))]+ #[cfg(all(feature = "oltp", feature = "v2"))]{- server_app = server_app.service(routes::EphemeralKey::server(state.clone()))+ server_app = server_app.service(routes::ClientSecret::server(state.clone()))}#[cfg(all(feature = "oltp", feature = "v1"))]{diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rsindex b24effd4c9..ddd3a2fd37 100644--- a/crates/router/src/routes.rs+++ b/crates/router/src/routes.rs@@ -9,6 +9,8 @@ pub mod blocklist;pub mod cache;pub mod card_issuer;pub mod cards_info;+#[cfg(feature = "v2")]+pub mod client_secret;pub mod configs;#[cfg(feature = "olap")]pub mod connector_onboarding;@@ -18,7 +20,6 @@ pub mod customers;pub mod disputes;#[cfg(feature = "dummy_connector")]pub mod dummy_connector;-pub mod ephemeral_key;pub mod external_service_auth;pub mod feature_matrix;pub mod files;@@ -94,24 +95,24 @@ pub mod proxy;#[cfg(feature = "dummy_connector")]pub use self::app::DummyConnector;-#[cfg(feature = "v2")]-pub use self::app::PaymentMethodSession;#[cfg(all(feature = "oltp", feature = "v2"))]pub use self::app::Proxy;pub use self::app::{ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, CardIssuers, Cards,- Configs, ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, ExternalService,- FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount,- MerchantConnectorAccount, OfferEngine, Oidc, PaymentLink, PaymentMethods, Payments, Poll,- ProcessTracker, ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew, Refunds, Relay,- RelayWebhooks, SdkConfig, SessionState, SuperpositionProxy, TelephoneOrder,- ThreeDsDecisionRule, User, UserDeprecated, Webhooks,+ Configs, ConnectorOnboarding, Customers, Disputes, Embedded, ExternalService, FeatureMatrix,+ Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount,+ OfferEngine, Oidc, PaymentLink, PaymentMethods, Payments, Poll, ProcessTracker,+ ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks,+ SdkConfig, SessionState, SuperpositionProxy, TelephoneOrder, ThreeDsDecisionRule, User,+ UserDeprecated, Webhooks,};#[cfg(feature = "olap")]pub use self::app::{Blocklist, HierarchicalResources, Organization, Routing, Subscription, UnifiedConnectorService,Verify, WebhookEvents,};+#[cfg(feature = "v2")]+pub use self::app::{ClientSecret, PaymentMethodSession};#[cfg(feature = "payouts")]pub use self::app::{PayoutLink, Payouts};#[cfg(feature = "v2")]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex e5b448834b..7d14a7b85b 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -39,12 +39,12 @@ use storage_impl::{use tokio::sync::oneshot;use self::settings::Tenant;+#[cfg(all(feature = "v2", feature = "oltp"))]+use super::client_secret::{client_secret_create, client_secret_delete};#[cfg(any(feature = "olap", feature = "oltp"))]use super::currency;#[cfg(feature = "dummy_connector")]use super::dummy_connector::*;-#[cfg(all(any(feature = "v1", feature = "v2"), feature = "oltp"))]-use super::ephemeral_key::*;#[cfg(any(feature = "olap", feature = "oltp"))]use super::payment_methods;#[cfg(feature = "payouts")]@@ -2269,20 +2269,11 @@ impl HierarchicalResources {}}-pub struct EphemeralKey;--#[cfg(all(feature = "v1", feature = "oltp"))]-impl EphemeralKey {- pub fn server(config: AppState) -> Scope {- web::scope("/ephemeral_keys")- .app_data(web::Data::new(config))- .service(web::resource("").route(web::post().to(ephemeral_key_create)))- .service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete)))- }-}+#[cfg(feature = "v2")]+pub struct ClientSecret;#[cfg(feature = "v2")]-impl EphemeralKey {+impl ClientSecret {pub fn server(config: AppState) -> Scope {web::scope("/v2/client-secret").app_data(web::Data::new(config))diff --git a/crates/router/src/routes/client_secret.rs b/crates/router/src/routes/client_secret.rsnew file mode 100644index 0000000000..c765f6422f--- /dev/null+++ b/crates/router/src/routes/client_secret.rs@@ -0,0 +1,63 @@+use actix_web::{web, HttpRequest, HttpResponse};+use router_env::{instrument, tracing, Flow};++use super::AppState;+use crate::{+ core::{api_locking, payments::helpers},+ services::{api, authentication as auth},+};++#[cfg(feature = "v2")]+#[instrument(skip_all, fields(flow = ?Flow::ClientSecretCreate))]+pub async fn client_secret_create(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<api_models::client_secret::ClientSecretCreateRequest>,+) -> HttpResponse {+ let flow = Flow::ClientSecretCreate;+ let payload = json_payload.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, payload, _| {+ helpers::make_client_secret(+ state,+ payload.resource_id.to_owned(),+ auth.platform,+ req.headers(),+ )+ },+ &auth::V2ApiKeyAuth {+ allow_connected_scope_operation: false,+ allow_platform_self_operation: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++#[cfg(feature = "v2")]+#[instrument(skip_all, fields(flow = ?Flow::ClientSecretDelete))]+pub async fn client_secret_delete(+ state: web::Data<AppState>,+ req: HttpRequest,+ path: web::Path<String>,+) -> HttpResponse {+ let flow = Flow::ClientSecretDelete;+ let payload = path.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req),+ &auth::V2ApiKeyAuth {+ allow_connected_scope_operation: false,+ allow_platform_self_operation: false,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rsindex c2a3cf2aff..a21bf63691 100644--- a/crates/router/src/routes/customers.rs+++ b/crates/router/src/routes/customers.rs@@ -107,22 +107,19 @@ pub async fn customers_retrieve(let customer_id = path.into_inner();- let auth = if auth::is_jwt_auth(req.headers()) {- Box::new(auth::JWTAuth {- permission: Permission::MerchantCustomerRead,- allow_connected: true,- allow_platform: true,- })- } else {- let api_auth = auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: true,+ let auth: Box<dyn auth::AuthenticateAndFetch<auth::AuthenticationData, _>> =+ if auth::is_jwt_auth(req.headers()) {+ Box::new(auth::JWTAuth {+ permission: Permission::MerchantCustomerRead,+ allow_connected: true,+ allow_platform: true,+ })+ } else {+ Box::new(auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ }))};- match auth::is_ephemeral_auth(req.headers(), api_auth) {- Ok(auth) => auth,- Err(err) => return api::log_and_return_error_response(err),- }- };Box::pin(api::server_wrap(flow,diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rsdeleted file mode 100644index ebe5f0f2ce..0000000000--- a/crates/router/src/routes/ephemeral_key.rs+++ /dev/null@@ -1,123 +0,0 @@-use actix_web::{web, HttpRequest, HttpResponse};-use router_env::{instrument, tracing, Flow};--use super::AppState;-#[cfg(feature = "v2")]-use crate::types::domain;-use crate::{- core::{api_locking, payments::helpers},- services::{api, authentication as auth},-};--#[cfg(feature = "v1")]-#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))]-pub async fn ephemeral_key_create(- state: web::Data<AppState>,- req: HttpRequest,- json_payload: web::Json<api_models::ephemeral_key::EphemeralKeyCreateRequest>,-) -> HttpResponse {- let flow = Flow::EphemeralKeyCreate;- let payload = json_payload.into_inner();- api::server_wrap(- flow,- state,- &req,- payload,- |state, auth: auth::AuthenticationData, payload, _| {- helpers::make_ephemeral_key(- state,- payload.customer_id,- auth.platform- .get_processor()- .get_account()- .get_id()- .to_owned(),- )- },- &auth::HeaderAuth(auth::ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,- }),- api_locking::LockAction::NotApplicable,- )- .await-}--#[cfg(feature = "v1")]-#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]-pub async fn ephemeral_key_delete(- state: web::Data<AppState>,- req: HttpRequest,- path: web::Path<String>,-) -> HttpResponse {- let flow = Flow::EphemeralKeyDelete;- let payload = path.into_inner();- api::server_wrap(- flow,- state,- &req,- payload,- |state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req),- &auth::HeaderAuth(auth::ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,- }),- api_locking::LockAction::NotApplicable,- )- .await-}--#[cfg(feature = "v2")]-#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))]-pub async fn client_secret_create(- state: web::Data<AppState>,- req: HttpRequest,- json_payload: web::Json<api_models::ephemeral_key::ClientSecretCreateRequest>,-) -> HttpResponse {- let flow = Flow::EphemeralKeyCreate;- let payload = json_payload.into_inner();- Box::pin(api::server_wrap(- flow,- state,- &req,- payload,- |state, auth: auth::AuthenticationData, payload, _| {- helpers::make_client_secret(- state,- payload.resource_id.to_owned(),- auth.platform,- req.headers(),- )- },- &auth::V2ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,- },- api_locking::LockAction::NotApplicable,- ))- .await-}--#[cfg(feature = "v2")]-#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]-pub async fn client_secret_delete(- state: web::Data<AppState>,- req: HttpRequest,- path: web::Path<String>,-) -> HttpResponse {- let flow = Flow::EphemeralKeyDelete;- let payload = path.into_inner();- Box::pin(api::server_wrap(- flow,- state,- &req,- payload,- |state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req),- &auth::V2ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,- },- api_locking::LockAction::NotApplicable,- ))- .await-}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex c146b97b99..a6b08713c0 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -12,7 +12,7 @@ pub enum ApiIdentifier {MerchantConnectorWebhookManagement,Configs,Customers,- Ephemeral,+ ClientSecret,Health,Mandates,PaymentMethods,@@ -138,7 +138,7 @@ impl From<Flow> for ApiIdentifier {| Flow::CustomersGlobalIdMigration| Flow::CustomersList| Flow::CustomersListWithConstraints => Self::Customers,- Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,+ Flow::ClientSecretCreate | Flow::ClientSecretDelete => Self::ClientSecret,Flow::DeepHealthCheck | Flow::HealthCheck => Self::Health,Flow::OfferEngineConnectivityCheck => Self::Health,Flow::OfferEngineBrowseOffers => Self::OfferEngine,diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex d2cdce160d..11d564f194 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -820,10 +820,7 @@ pub async fn list_customer_payment_method_api(allow_connected_scope_operation: api_auth.allow_connected_scope_operation,allow_platform_self_operation: api_auth.allow_platform_self_operation,}),- None => match auth::is_ephemeral_auth(req.headers(), api_auth) {- Ok(auth) => auth,- Err(err) => return api::log_and_return_error_response(err),- },+ None => Box::new(auth::HeaderAuth(api_auth)),};Box::pin(api::server_wrap(flow,@@ -843,7 +840,6 @@ pub async fn list_customer_payment_method_api(auth.platform,Some(req),Some(&customer_id),- None,).await})@@ -866,17 +862,13 @@ pub async fn list_customer_payment_method_api_client() -> HttpResponse {let flow = Flow::CustomerPaymentMethodsList;let payload = query_payload.into_inner();- let api_key = auth::get_api_key(req.headers()).ok();let api_auth = auth::ApiKeyAuth {allow_connected_scope_operation: true,allow_platform_self_operation: false,};// Check if Authorization header is present for SDK authorization- let (auth, _, is_ephemeral_auth) = match req- .headers()- .get(actix_web::http::header::AUTHORIZATION)- {+ let auth = match req.headers().get(actix_web::http::header::AUTHORIZATION) {Some(_) => {// If Authorization header is present, use SdkAuthorizationAuthlet auth: Box<dyn auth::AuthenticateAndFetch<auth::AuthenticationData, _>> =@@ -884,17 +876,12 @@ pub async fn list_customer_payment_method_api_client(allow_connected_scope_operation: api_auth.allow_connected_scope_operation,allow_platform_self_operation: api_auth.allow_platform_self_operation,});- (auth, api::AuthFlow::Client, false)- }- None => {- // If Authorization header is not present, use existing logic- match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload), api_auth)- .await- {- Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),- Err(e) => return api::log_and_return_error_response(e),- }+ auth}+ None => match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {+ Ok((auth, _)) => auth,+ Err(e) => return api::log_and_return_error_response(e),+ },};Box::pin(api::server_wrap(@@ -915,7 +902,6 @@ pub async fn list_customer_payment_method_api_client(auth.platform,Some(req),None,- is_ephemeral_auth.then_some(api_key).flatten(),).await})@@ -1263,11 +1249,6 @@ pub async fn payment_method_delete_api(allow_platform_self_operation: true,};- let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), api_auth) {- Ok(auth) => auth,- Err(err) => return api::log_and_return_error_response(err),- };-Box::pin(api::server_wrap(flow,state,@@ -1282,7 +1263,7 @@ pub async fn payment_method_delete_api(.delete_payment_method(req, auth.platform.get_initiator()).await},- &*ephemeral_auth,+ &auth::HeaderAuth(api_auth),api_locking::LockAction::NotApplicable,)).await@@ -1400,10 +1381,7 @@ pub async fn default_payment_method_set_api(allow_connected_scope_operation: api_auth.allow_connected_scope_operation,allow_platform_self_operation: api_auth.allow_platform_self_operation,}),- None => match auth::is_ephemeral_auth(req.headers(), api_auth) {- Ok(auth) => auth,- Err(err) => return api::log_and_return_error_response(err),- },+ None => Box::new(auth::HeaderAuth(api_auth)),};Box::pin(api::server_wrap(flow,diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex cc466d4ef8..56661d5e16 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -12,8 +12,6 @@ use async_trait::async_trait;use base64::Engine;use common_enums::{MerchantAccountType, TokenPurpose};use common_utils::{date_time, fp_utils, id_type};-#[cfg(feature = "v2")]-use diesel_models::ephemeral_key;use error_stack::{report, ResultExt};use hyperswitch_domain_models::sdk_auth::SdkAuthorization;#[cfg(feature = "v2")]@@ -2473,34 +2471,6 @@ where}}-#[derive(Debug)]-pub struct EphemeralKeyAuth;--#[cfg(feature = "v1")]-#[async_trait]-impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth-where- A: SessionStateInfo + Sync,-{- async fn authenticate_and_fetch(- &self,- request_headers: &HeaderMap,- state: &A,- ) -> RouterResult<(AuthenticationData, AuthenticationType)> {- let api_key =- get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;- let ephemeral_key = state- .store()- .get_ephemeral_key(api_key)- .await- .change_context(errors::ApiErrorResponse::Unauthorized)?;-- MerchantIdAuth(ephemeral_key.merchant_id)- .authenticate_and_fetch(request_headers, state)- .await- }-}-#[derive(Debug)]#[cfg(feature = "v1")]pub struct MerchantIdAuth(pub id_type::MerchantId);@@ -3175,7 +3145,7 @@ where.get_client_secret(client_secret).await.change_context(errors::ApiErrorResponse::Unauthorized)- .attach_printable("Invalid ephemeral_key")?;+ .attach_printable("Invalid client secret")?;let profile_id =get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?@@ -6206,53 +6176,6 @@ where}}-pub async fn get_ephemeral_or_other_auth<T>(- headers: &HeaderMap,- is_merchant_flow: bool,- payload: Option<&impl ClientSecretFetch>,- api_auth: ApiKeyAuth,-) -> RouterResult<(- Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,- api::AuthFlow,- bool,-)>-where- T: SessionStateInfo + Sync + Send,- ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,- PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,- EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,-{- let api_key = get_api_key(headers)?;-- if api_key.starts_with("epk") {- Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true))- } else if is_merchant_flow {- Ok((- Box::new(HeaderAuth(api_auth)),- api::AuthFlow::Merchant,- false,- ))- } else {- let payload = payload.get_required_value("ClientSecretFetch")?;- let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload, api_auth)?;- Ok((auth, auth_flow, false))- }-}--#[cfg(feature = "v1")]-pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>(- headers: &HeaderMap,- api_auth: ApiKeyAuth,-) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {- let api_key = get_api_key(headers)?;-- if !api_key.starts_with("epk") {- Ok(Box::new(HeaderAuth(api_auth)))- } else {- Ok(Box::new(EphemeralKeyAuth))- }-}-pub fn is_jwt_auth(headers: &HeaderMap) -> bool {let header_map_struct = HeaderMapStruct::new(headers);match header_map_struct.get_auth_string_from_header() {diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex ee19a8dd53..222128565b 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -1,13 +1,14 @@pub mod admin;pub mod api_keys;pub mod authentication;+#[cfg(feature = "v2")]+pub mod client_secret;pub mod configs;#[cfg(feature = "olap")]pub mod connector_onboarding;pub mod customers;pub mod disputes;pub mod enums;-pub mod ephemeral_key;pub mod files;#[cfg(feature = "frm")]pub mod fraud_check;diff --git a/crates/router/src/types/api/client_secret.rs b/crates/router/src/types/api/client_secret.rsnew file mode 100644index 0000000000..0fa97ab007--- /dev/null+++ b/crates/router/src/types/api/client_secret.rs@@ -0,0 +1 @@+pub use api_models::client_secret::*;diff --git a/crates/router/src/types/api/ephemeral_key.rs b/crates/router/src/types/api/ephemeral_key.rsdeleted file mode 100644index 4b2218f56c..0000000000--- a/crates/router/src/types/api/ephemeral_key.rs+++ /dev/null@@ -1 +0,0 @@-pub use api_models::ephemeral_key::*;diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rsindex 5dc6cb6806..a4b4980b9a 100644--- a/crates/router/src/types/storage.rs+++ b/crates/router/src/types/storage.rs@@ -11,13 +11,13 @@ pub mod callback_mapper;pub mod capture;pub mod card_issuer;pub mod cards_info;+pub mod client_secret;pub mod configs;pub mod customers;pub mod dashboard_metadata;pub mod dispute;pub mod dynamic_routing_stats;pub mod enums;-pub mod ephemeral_key;pub mod events;pub mod file;pub mod fraud_check;@@ -69,14 +69,15 @@ pub use hyperswitch_domain_models::{};pub use scheduler::db::process_tracker;+#[cfg(feature = "v2")]+pub use self::client_secret::*;pub use self::{address::*, api_keys::*, authentication::*, authorization::*, batch_blocklist_job::*,blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*,callback_mapper::*, capture::*, card_issuer::*, cards_info::*, configs::*, customers::*,- dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*,- file::*, fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*,- merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,- payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,- routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,- user_role::*,+ dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, events::*, file::*,+ fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*, merchant_account::*,+ merchant_connector_account::*, merchant_key_store::*, payment_link::*, payment_method::*,+ process_tracker::*, refund::*, reverse_lookup::*, role::*, routing_algorithm::*,+ unified_translations::*, user::*, user_authentication_method::*, user_role::*,};diff --git a/crates/router/src/types/storage/ephemeral_key.rs b/crates/router/src/types/storage/client_secret.rssimilarity index 79%rename from crates/router/src/types/storage/ephemeral_key.rsrename to crates/router/src/types/storage/client_secret.rsindex 46bf185194..0a6bc9851d 100644--- a/crates/router/src/types/storage/ephemeral_key.rs+++ b/crates/router/src/types/storage/client_secret.rs@@ -1,13 +1,12 @@#[cfg(feature = "v2")]-pub use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};-pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew};+pub use diesel_models::client_secret::{ClientSecretType, ClientSecretTypeNew};#[cfg(feature = "v2")]use crate::db::errors;#[cfg(feature = "v2")]use crate::types::transformers::ForeignTryFrom;#[cfg(feature = "v2")]-impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecretResponse {+impl ForeignTryFrom<ClientSecretType> for api_models::client_secret::ClientSecretResponse {type Error = errors::ApiErrorResponse;fn foreign_try_from(from: ClientSecretType) -> Result<Self, errors::ApiErrorResponse> {match from.resource_id {@@ -19,7 +18,7 @@ impl ForeignTryFrom<ClientSecretType> for api_models::ephemeral_key::ClientSecre) => Err(errors::ApiErrorResponse::InternalServerError),common_utils::types::authentication::ResourceId::Customer(global_customer_id) => {Ok(Self {- resource_id: api_models::ephemeral_key::ResourceId::Customer(+ resource_id: api_models::client_secret::ResourceId::Customer(global_customer_id.clone(),),created_at: from.created_at,diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 2055ae40c8..142dbe613d 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -134,10 +134,10 @@ pub enum Flow {CustomersGetMandates,/// Customers global id migration flow.CustomersGlobalIdMigration,- /// Create an Ephemeral Key.- EphemeralKeyCreate,- /// Delete an Ephemeral Key.- EphemeralKeyDelete,+ /// Create a v2 client secret.+ ClientSecretCreate,+ /// Delete a v2 client secret.+ ClientSecretDelete,/// Mandates retrieve flow.MandatesRetrieve,/// Mandates revoke flow.diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rsindex 464a527de8..58d75d81de 100644--- a/crates/storage_impl/src/mock_db.rs+++ b/crates/storage_impl/src/mock_db.rs@@ -43,7 +43,6 @@ pub struct MockDb {/// take them from.pub caches: Arc<Caches>,pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,- pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,pub events: Arc<Mutex<Vec<store::Event>>>,pub disputes: Arc<Mutex<Vec<store::Dispute>>>,@@ -106,7 +105,6 @@ impl MockDb {),caches: Arc::new(Caches::default()),api_keys: Default::default(),- ephemeral_keys: Default::default(),cards_info: Default::default(),events: Default::default(),disputes: Default::default(),diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 0b8aaa02e0..3fd2232508 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -2797,31 +2797,6 @@ Cypress.Commands.add(});-Cypress.Commands.add("ephemeralGenerateCall", (globalState) => {- const customer_id = globalState.get("customerId");- const merchant_id = globalState.get("merchantId");-- cy.request({- method: "POST",- url: `${globalState.get("baseUrl")}/ephemeral_keys`,- headers: {- "Content-Type": "application/json",- "api-key": globalState.get("apiKey"),- },- body: { customer_id: customer_id },- failOnStatusCode: false,- }).then((response) => {- logRequestId(response.headers["x-request-id"]);-- cy.wrap(response).then(() => {- expect(response.body.customer_id).to.equal(customer_id);- expect(response.body.merchant_id).to.equal(merchant_id);- expect(response.body.id).to.exist.and.not.be.empty;- expect(response.body.secret).to.exist.and.not.be.empty;- });- });-});-Cypress.Commands.add("customerDeleteCall", (globalState) => {const customer_id = globalState.get("customerId");diff --git a/postman/collection-dir/hyperswitch/Customers/.meta.json b/postman/collection-dir/hyperswitch/Customers/.meta.jsonindex db26627bb9..a598bd4a9e 100644--- a/postman/collection-dir/hyperswitch/Customers/.meta.json+++ b/postman/collection-dir/hyperswitch/Customers/.meta.json@@ -3,7 +3,6 @@"Create Customer","Retrieve Customer","Update Customer",- "Ephemeral Key","Delete Customer"],"description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods."diff --git a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/.event.meta.json b/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/.event.meta.jsondeleted file mode 100644index 0731450e6b..0000000000--- a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/.event.meta.json+++ /dev/null@@ -1,3 +0,0 @@-{- "eventOrder": ["event.test.js"]-}diff --git a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/event.test.js b/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/event.test.jsdeleted file mode 100644index 854d248cbb..0000000000--- a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/event.test.js+++ /dev/null@@ -1,14 +0,0 @@-// Validate status 2xx-pm.test("[POST]::/ephemeral_keys - Status code is 2xx", function () {- pm.response.to.be.success;-});--// Validate if response header has matching content-type-pm.test(- "[POST]::/ephemeral_keys - Content-Type is application/json",- function () {- pm.expect(pm.response.headers.get("Content-Type")).to.include(- "application/json",- );- },-);diff --git a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/request.json b/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/request.jsondeleted file mode 100644index 7ea8a49c30..0000000000--- a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/request.json+++ /dev/null@@ -1,20 +0,0 @@-{- "method": "POST",- "header": [- {- "key": "Content-Type",- "value": "application/json"- }- ],- "body": {- "mode": "raw",- "raw_json_formatted": {- "customer_id": "{{customer_id}}"- }- },- "url": {- "raw": "{{baseUrl}}/ephemeral_keys",- "host": ["{{baseUrl}}"],- "path": ["ephemeral_keys"]- }-}diff --git a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/response.json b/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/response.jsondeleted file mode 100644index fe51488c70..0000000000--- a/postman/collection-dir/hyperswitch/Customers/Ephemeral Key/response.json+++ /dev/null@@ -1 +0,0 @@-[]diff --git a/postman/collection-dir/stripe/Customers/.meta.json b/postman/collection-dir/stripe/Customers/.meta.jsonindex 3b7497b1ea..35441739ce 100644--- a/postman/collection-dir/stripe/Customers/.meta.json+++ b/postman/collection-dir/stripe/Customers/.meta.json@@ -4,7 +4,6 @@"List Customer","Retrieve Customer","Update Customer",- "Ephemeral Key","Delete Customer"],"description": "Create a Customer entity which you can use to store and retrieve specific customers' data and payment methods."diff --git a/postman/collection-dir/stripe/Customers/Ephemeral Key/.event.meta.json b/postman/collection-dir/stripe/Customers/Ephemeral Key/.event.meta.jsondeleted file mode 100644index 0731450e6b..0000000000--- a/postman/collection-dir/stripe/Customers/Ephemeral Key/.event.meta.json+++ /dev/null@@ -1,3 +0,0 @@-{- "eventOrder": ["event.test.js"]-}diff --git a/postman/collection-dir/stripe/Customers/Ephemeral Key/event.test.js b/postman/collection-dir/stripe/Customers/Ephemeral Key/event.test.jsdeleted file mode 100644index 854d248cbb..0000000000--- a/postman/collection-dir/stripe/Customers/Ephemeral Key/event.test.js+++ /dev/null@@ -1,14 +0,0 @@-// Validate status 2xx-pm.test("[POST]::/ephemeral_keys - Status code is 2xx", function () {- pm.response.to.be.success;-});--// Validate if response header has matching content-type-pm.test(- "[POST]::/ephemeral_keys - Content-Type is application/json",- function () {- pm.expect(pm.response.headers.get("Content-Type")).to.include(- "application/json",- );- },-);diff --git a/postman/collection-dir/stripe/Customers/Ephemeral Key/request.json b/postman/collection-dir/stripe/Customers/Ephemeral Key/request.jsondeleted file mode 100644index 7ea8a49c30..0000000000--- a/postman/collection-dir/stripe/Customers/Ephemeral Key/request.json+++ /dev/null@@ -1,20 +0,0 @@-{- "method": "POST",- "header": [- {- "key": "Content-Type",- "value": "application/json"- }- ],- "body": {- "mode": "raw",- "raw_json_formatted": {- "customer_id": "{{customer_id}}"- }- },- "url": {- "raw": "{{baseUrl}}/ephemeral_keys",- "host": ["{{baseUrl}}"],- "path": ["ephemeral_keys"]- }-}diff --git a/postman/collection-dir/stripe/Customers/Ephemeral Key/response.json b/postman/collection-dir/stripe/Customers/Ephemeral Key/response.jsondeleted file mode 100644index fe51488c70..0000000000--- a/postman/collection-dir/stripe/Customers/Ephemeral Key/response.json+++ /dev/null@@ -1 +0,0 @@-[]diff --git a/postman/collection-json/hyperswitch.postman_collection.json b/postman/collection-json/hyperswitch.postman_collection.jsonindex f22ff100f4..7047a60f49 100644--- a/postman/collection-json/hyperswitch.postman_collection.json+++ b/postman/collection-json/hyperswitch.postman_collection.json@@ -2533,57 +2533,6 @@},"response": []},- {- "name": "Ephemeral Key",- "event": [- {- "listen": "test",- "script": {- "exec": [- "// Validate status 2xx",- "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {",- " pm.response.to.be.success;",- "});",- "",- "// Validate if response header has matching content-type",- "pm.test(",- " \"[POST]::/ephemeral_keys - Content-Type is application/json\",",- " function () {",- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",- " \"application/json\",",- " );",- " },",- ");",- ""- ],- "type": "text/javascript"- }- }- ],- "request": {- "method": "POST",- "header": [- {- "key": "Content-Type",- "value": "application/json"- }- ],- "body": {- "mode": "raw",- "raw": "{\"customer_id\":\"{{customer_id}}\"}"- },- "url": {- "raw": "{{baseUrl}}/ephemeral_keys",- "host": [- "{{baseUrl}}"- ],- "path": [- "ephemeral_keys"- ]- }- },- "response": []- },{"name": "Delete Customer","event": [diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.jsonindex 8f2b9142f8..db37d5472e 100644--- a/postman/collection-json/stripe.postman_collection.json+++ b/postman/collection-json/stripe.postman_collection.json@@ -3389,57 +3389,6 @@},"response": []},- {- "name": "Ephemeral Key",- "event": [- {- "listen": "test",- "script": {- "exec": [- "// Validate status 2xx",- "pm.test(\"[POST]::/ephemeral_keys - Status code is 2xx\", function () {",- " pm.response.to.be.success;",- "});",- "",- "// Validate if response header has matching content-type",- "pm.test(",- " \"[POST]::/ephemeral_keys - Content-Type is application/json\",",- " function () {",- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",- " \"application/json\",",- " );",- " },",- ");",- ""- ],- "type": "text/javascript"- }- }- ],- "request": {- "method": "POST",- "header": [- {- "key": "Content-Type",- "value": "application/json"- }- ],- "body": {- "mode": "raw",- "raw": "{\"customer_id\":\"{{customer_id}}\"}"- },- "url": {- "raw": "{{baseUrl}}/ephemeral_keys",- "host": [- "{{baseUrl}}"- ],- "path": [- "ephemeral_keys"- ]- }- },- "response": []- },{"name": "Delete Customer","event": [