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(platform): introduce SDK authorization support for v2 (#11280)
Sandeep Kumar52ecea6b549c
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 86594a6496..e3cf85d5ad 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -21600,6 +21600,12 @@}],"nullable": true+ },+ "sdk_authorization": {+ "type": "string",+ "description": "SDK authorization token for client SDK usage\nContains encoded authentication details for subsequent API calls",+ "example": "cHJvZmlsZV9pZD0uLi4=",+ "nullable": true}}},diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex 5ae4022035..7f6407c59a 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -3773,6 +3773,12 @@ pub struct PaymentMethodSessionResponse {#[schema(value_type = Option<PaymentMethodResponseData>)]#[serde(skip_serializing_if = "Option::is_none")]pub payment_method_data: Option<PaymentMethodResponseData>,++ /// SDK authorization token for client SDK usage+ /// Contains encoded authentication details for subsequent API calls+ #[schema(value_type = Option<String>, example = "cHJvZmlsZV9pZD0uLi4=")]+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sdk_authorization: Option<String>,}#[cfg(feature = "v2")]diff --git a/crates/common_utils/src/id_type/global_id/customer.rs b/crates/common_utils/src/id_type/global_id/customer.rsindex 014d56c9aa..b1119e147e 100644--- a/crates/common_utils/src/id_type/global_id/customer.rs+++ b/crates/common_utils/src/id_type/global_id/customer.rs@@ -24,6 +24,14 @@ impl GlobalCustomerId {let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Customer);Self(global_id)}++ /// Create a new GlobalCustomerId without validation+ /// WARNING: This should only be used when the input is already trusted/validated+ pub fn new_unchecked(input_string: String) -> Self {+ let alphanumeric_id = crate::id_type::AlphaNumericId::new_unchecked(input_string);+ let length_id = crate::id_type::LengthId::new_unchecked(alphanumeric_id);+ Self(super::GlobalId(length_id))+ }}impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId {diff --git a/crates/common_utils/src/id_type/global_id/payment_methods.rs b/crates/common_utils/src/id_type/global_id/payment_methods.rsindex b3b314e7fc..cb7099a8b5 100644--- a/crates/common_utils/src/id_type/global_id/payment_methods.rs+++ b/crates/common_utils/src/id_type/global_id/payment_methods.rs@@ -63,6 +63,14 @@ impl GlobalPaymentMethodSessionId {pub fn get_redis_key(&self) -> String {format!("payment_method_session:{}", self.get_string_repr())}++ /// Create a new GlobalPaymentMethodSessionId without validation+ /// WARNING: This should only be used when the input is already trusted/validated+ pub fn new_unchecked(input_string: String) -> Self {+ let alphanumeric_id = crate::id_type::AlphaNumericId::new_unchecked(input_string);+ let length_id = crate::id_type::LengthId::new_unchecked(alphanumeric_id);+ Self(GlobalId(length_id))+ }}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_domain_models/src/sdk_auth.rs b/crates/hyperswitch_domain_models/src/sdk_auth.rsindex 266733845b..b50822c0ed 100644--- a/crates/hyperswitch_domain_models/src/sdk_auth.rs+++ b/crates/hyperswitch_domain_models/src/sdk_auth.rs@@ -8,10 +8,58 @@ use common_utils::{};use error_stack::{report, ResultExt};+#[cfg(feature = "v2")]+use crate::platform::Initiator;+/// Input for constructing SdkAuthorization from a Platform context (V2 only)+#[cfg(feature = "v2")]+pub struct SdkAuthorizationContext {+ pub platform: crate::platform::Platform,+ pub profile_id: id_type::ProfileId,+ pub client_secret: String,+ pub customer_id: Option<id_type::GlobalCustomerId>,+ pub payment_method_session_id: Option<id_type::GlobalPaymentMethodSessionId>,+}++#[cfg(feature = "v2")]+impl From<SdkAuthorizationContext> for Option<SdkAuthorization> {+ fn from(input: SdkAuthorizationContext) -> Self {+ match input.platform.get_initiator()? {+ Initiator::Api {+ merchant_account_type,+ publishable_key,+ ..+ } => {+ let platform_publishable_key = if matches!(+ merchant_account_type,+ common_enums::MerchantAccountType::Platform+ ) {+ Some(publishable_key.clone())+ } else {+ None+ };+ Some(SdkAuthorization {+ profile_id: input.profile_id,+ publishable_key: input+ .platform+ .get_processor()+ .get_account()+ .publishable_key+ .clone(),+ platform_publishable_key,+ client_secret: input.client_secret,+ customer_id: input.customer_id,+ payment_method_session_id: input.payment_method_session_id,+ })+ }+ Initiator::Admin | Initiator::Jwt { .. } | Initiator::EmbeddedToken { .. } => None, // SDK authorization is only applicable for API initiators+ }+ }+}+/// SDK authorization data for client-side SDK authentication#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct SdkAuthorization {- /// The profile ID associated with this payment+ /// The profile ID associated with this payment/sessionpub profile_id: id_type::ProfileId,/// The publishable key of the processor merchant (connected or standard)@@ -20,11 +68,19 @@ pub struct SdkAuthorization {/// Platform publishable key (only for platform-initiated flows)pub platform_publishable_key: Option<String>,- /// Client secret for the payment (required for SDK authorization)+ /// Client secret for the payment/session (required for SDK authorization)pub client_secret: String,- /// Customer ID for the payment (if available)+ /// Customer ID for the payment/session (if available)+ #[cfg(feature = "v1")]pub customer_id: Option<id_type::CustomerId>,++ /// Customer ID for the payment/session (if available)+ #[cfg(feature = "v2")]+ pub customer_id: Option<id_type::GlobalCustomerId>,++ #[cfg(feature = "v2")]+ pub payment_method_session_id: Option<id_type::GlobalPaymentMethodSessionId>,}impl SdkAuthorization {@@ -37,11 +93,17 @@ impl SdkAuthorization {Some(format!("publishable_key={}", self.publishable_key)),self.platform_publishable_key.as_ref()- .map(|k| format!("platform_publishable_key={}", k)),+ .map(|platform_publishable_key| {+ format!("platform_publishable_key={}", platform_publishable_key)+ }),Some(format!("client_secret={}", self.client_secret)),self.customer_id.as_ref().map(|id| format!("customer_id={}", id.get_string_repr())),+ #[cfg(feature = "v2")]+ self.payment_method_session_id+ .as_ref()+ .map(|id| format!("payment_method_session_id={}", id.get_string_repr())),].into_iter().flatten()@@ -75,7 +137,7 @@ impl SdkAuthorization {.split(',').map(|part| {part.split_once('=')- .map(|(k, v)| (k.trim(), v.trim()))+ .map(|(key, value)| (key.trim(), value.trim())).ok_or_else(|| {report!(ValidationError::InvalidValue {message: "Invalid SDK authorization format: missing '=' separator"@@ -107,7 +169,9 @@ impl SdkAuthorization {})})?.to_string(),- platform_publishable_key: parts.get("platform_publishable_key").map(|v| v.to_string()),+ platform_publishable_key: parts+ .get("platform_publishable_key")+ .map(|platform_publishable_key| platform_publishable_key.to_string()),client_secret: parts.get("client_secret").ok_or_else(|| {@@ -116,15 +180,28 @@ impl SdkAuthorization {})})?.to_string(),+ #[cfg(feature = "v1")]customer_id: parts.get("customer_id")- .map(|v| {- id_type::CustomerId::try_from(std::borrow::Cow::from(v.to_string()))+ .map(|customer_id| {+ id_type::CustomerId::try_from(std::borrow::Cow::from(customer_id.to_string())).change_context(ValidationError::InvalidValue {message: "Invalid customer_id format".to_string(),})}).transpose()?,+ #[cfg(feature = "v2")]+ customer_id: parts.get("customer_id").map(|customer_id| {+ id_type::GlobalCustomerId::new_unchecked(customer_id.to_string())+ }),+ #[cfg(feature = "v2")]+ payment_method_session_id: parts.get("payment_method_session_id").map(+ |payment_method_session_id| {+ id_type::GlobalPaymentMethodSessionId::new_unchecked(+ payment_method_session_id.to_string(),+ )+ },+ ),})}}diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex a030438a34..3400c22895 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -53,6 +53,8 @@ use hyperswitch_domain_models::{types::VaultRouterData,};use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;+#[cfg(feature = "v2")]+use masking::ExposeInterface;use masking::{PeekInterface, Secret};use router_env::{instrument, tracing};use time::Duration;@@ -4320,11 +4322,13 @@ impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest {#[cfg(feature = "v2")]pub async fn payment_methods_session_create(state: SessionState,- provider: domain::Provider,+ platform: domain::Platform,+ profile: domain::Profile,request: payment_methods::PaymentMethodSessionRequest,) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {let db = state.store.as_ref();let key_manager_state = &(&state).into();+ let provider = platform.get_provider();if let (Some(customer_id)) = &request.customer_id {db.find_customer_by_global_id_merchant_id(@@ -4404,9 +4408,20 @@ pub async fn payment_methods_session_create(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to insert payment methods session in db")?;+ let sdk_authorization = Option::<hyperswitch_domain_models::sdk_auth::SdkAuthorization>::from(+ hyperswitch_domain_models::sdk_auth::SdkAuthorizationContext {+ platform,+ profile_id: profile.get_id().clone(),+ client_secret: client_secret.secret.clone().expose(),+ customer_id: payment_method_session_domain_model.customer_id.clone(),+ payment_method_session_id: Some(payment_method_session_domain_model.id.clone()),+ },+ );+let response = transformers::generate_payment_method_session_response(payment_method_session_domain_model,client_secret.secret,+ sdk_authorization,None,None,Some(request.storage_type),@@ -4474,6 +4489,7 @@ pub async fn payment_methods_session_update(let response = transformers::generate_payment_method_session_response(update_state_change,Secret::new("CLIENT_SECRET_REDACTED".to_string()),+ None, // sdk_authorization is not returned for non-create flowsNone, // TODO: send associated payments response based on the expandable paramNone,None,@@ -4530,6 +4546,7 @@ pub async fn payment_methods_session_retrieve(let response = transformers::generate_payment_method_session_response(payment_method_session_domain_model,Secret::new("CLIENT_SECRET_REDACTED".to_string()),+ None, // sdk_authorization is not returned for non-create flowsNone, // TODO: send associated payments response based on the expandable paramNone,None,@@ -4627,6 +4644,7 @@ pub async fn payment_methods_session_update_payment_method(let response = transformers::generate_payment_method_session_response(updated_payment_method_session,Secret::new("CLIENT_SECRET_REDACTED".to_string()),+ None, // sdk_authorization is not returned for non-create flowsNone, // TODO: send associated payments response based on the expandable paramNone,None,@@ -4960,6 +4978,7 @@ pub async fn payment_methods_session_confirm(let payment_method_session_response = transformers::generate_payment_method_session_response(payment_method_session,Secret::new("CLIENT_SECRET_REDACTED".to_string()),+ None, // sdk_authorization is not returned for non-create flowspayments_response,(tokenization_response.flatten()),Some(payment_method_response.storage_type),diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 1529587f12..d761e65bd7 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -13,7 +13,7 @@ use common_utils::{};use error_stack::ResultExt;#[cfg(feature = "v2")]-use hyperswitch_domain_models::payment_method_data;+use hyperswitch_domain_models::{payment_method_data, sdk_auth::SdkAuthorization};use josekit::jwe;#[cfg(feature = "v1")]use masking::Mask;@@ -1003,9 +1003,11 @@ impl transformers::ForeignTryFrom<domain::PaymentMethod> for PaymentMethodRespon}#[cfg(feature = "v2")]+#[allow(clippy::too_many_arguments)]pub fn generate_payment_method_session_response(payment_method_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,client_secret: Secret<String>,+ sdk_authorization: Option<hyperswitch_domain_models::sdk_auth::SdkAuthorization>,associated_payment: Option<api_models::payments::PaymentsResponse>,tokenization_service_response: Option<api_models::tokenization::GenericTokenizationResponse>,storage_type: Option<common_enums::StorageType>,@@ -1028,6 +1030,8 @@ pub fn generate_payment_method_session_response(.as_ref().map(|tokenization_service_response| tokenization_service_response.id.clone());+ let sdk_authorization = sdk_authorization.and_then(|auth| auth.encode().ok());+api_models::payment_methods::PaymentMethodSessionResponse {id: payment_method_session.id,customer_id: payment_method_session.customer_id,@@ -1048,6 +1052,7 @@ pub fn generate_payment_method_session_response(storage_type,card_cvc_token_storage,payment_method_data,+ sdk_authorization,}}diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rsindex b278c9f6f9..a90bedce87 100644--- a/crates/router/src/routes/customers.rs+++ b/crates/router/src/routes/customers.rs@@ -122,7 +122,7 @@ pub async fn customers_retrieve(req: HttpRequest,path: web::Path<id_type::GlobalCustomerId>,) -> HttpResponse {- use crate::services::authentication::api_or_client_auth;+ use crate::services::authentication::sdk_or_api_or_client_auth;let flow = Flow::CustomersRetrieve;@@ -131,12 +131,18 @@ pub async fn customers_retrieve(let v2_client_auth = auth::V2ClientAuth(common_utils::types::authentication::ResourceId::Customer(id.clone()),);+ let sdk_auth = auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::Customer(id.clone()),+ };let auth = if auth::is_jwt_auth(req.headers()) {&auth::JWTAuth {permission: Permission::MerchantCustomerRead,}} else {- api_or_client_auth(+ sdk_or_api_or_client_auth(+ &sdk_auth,&auth::V2ApiKeyAuth {allow_connected_scope_operation: false,allow_platform_self_operation: false,diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex a9c68b1d32..2a3c40c118 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1523,14 +1523,15 @@ pub async fn payment_methods_session_create(|state, auth: auth::AuthenticationData, request, _| async move {payment_methods_routes::payment_methods_session_create(state,- auth.platform.get_provider().clone(),+ auth.platform,+ auth.profile,request,).await},&auth::V2ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,},api_locking::LockAction::NotApplicable,))@@ -1566,8 +1567,8 @@ pub async fn payment_methods_session_update(}},&auth::V2ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,},api_locking::LockAction::NotApplicable,))@@ -1597,10 +1598,17 @@ pub async fn payment_methods_session_retrieve().await},- auth::api_or_client_auth(+ auth::sdk_or_api_or_client_auth(+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id.clone(),+ ),+ },&auth::V2ApiKeyAuth {- allow_connected_scope_operation: false,- allow_platform_self_operation: false,+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,},&auth::V2ClientAuth(common_utils::types::authentication::ResourceId::PaymentMethodSession(@@ -1637,10 +1645,20 @@ pub async fn payment_method_session_list_payment_methods(payment_method_session_id,)},- &auth::V2ClientAuth(- common_utils::types::authentication::ResourceId::PaymentMethodSession(- payment_method_session_id,+ auth::sdk_or_client_auth(+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id.clone(),+ ),+ },+ &auth::V2ClientAuth(+ common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id,+ ),),+ req.headers(),),api_locking::LockAction::NotApplicable,))@@ -1698,10 +1716,20 @@ pub async fn payment_method_session_confirm(request.request,)},- &auth::V2ClientAuth(- common_utils::types::authentication::ResourceId::PaymentMethodSession(- payment_method_session_id,+ auth::sdk_or_client_auth(+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id.clone(),+ ),+ },+ &auth::V2ClientAuth(+ common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id,+ ),),+ req.headers(),),api_locking::LockAction::NotApplicable,))@@ -1741,10 +1769,20 @@ pub async fn payment_method_session_update_saved_payment_method(request.request,)},- &auth::V2ClientAuth(- common_utils::types::authentication::ResourceId::PaymentMethodSession(- payment_method_session_id,+ auth::sdk_or_client_auth(+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id.clone(),+ ),+ },+ &auth::V2ClientAuth(+ common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id,+ ),),+ req.headers(),),api_locking::LockAction::NotApplicable,))@@ -1784,10 +1822,20 @@ pub async fn payment_method_session_delete_saved_payment_method(request.payment_method_session_id,)},- &auth::V2ClientAuth(- common_utils::types::authentication::ResourceId::PaymentMethodSession(- payment_method_session_id,+ auth::sdk_or_client_auth(+ &auth::SdkAuthorizationAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: true,+ resource_id: common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id.clone(),+ ),+ },+ &auth::V2ClientAuth(+ common_utils::types::authentication::ResourceId::PaymentMethodSession(+ payment_method_session_id,+ ),),+ req.headers(),),api_locking::LockAction::NotApplicable,))diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex ac5879c780..f150861b25 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -76,6 +76,7 @@ pub struct AuthenticationData {pub struct AuthenticationData {pub platform: domain::Platform,pub profile: domain::Profile,+ pub client_secret: Option<String>,}#[cfg(feature = "v1")]@@ -98,7 +99,11 @@ impl AuthenticationData {platform: domain::Platform,profile: domain::Profile,) -> Self {- Self { platform, profile }+ Self {+ platform,+ profile,+ client_secret: None,+ }}}@@ -668,7 +673,11 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth.clone(),AuthenticationType::ApiKey {@@ -1362,6 +1371,7 @@ wherelet auth = AuthenticationData {platform: auth_data.platform,profile,+ client_secret: None,};Ok((auth, auth_type))}@@ -1794,7 +1804,11 @@ whereinitiator,);- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },@@ -2318,7 +2332,11 @@ whereinitiator,);- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,AuthenticationType::AdminApiAuthWithMerchantId { merchant_id },@@ -2518,7 +2536,11 @@ whereinitiator,);- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth.clone(),AuthenticationType::MerchantId {@@ -2706,7 +2728,11 @@ whereinitiator,);- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth.clone(),AuthenticationType::MerchantId {@@ -2769,7 +2795,11 @@ where);Ok((- AuthenticationData { platform, profile },+ AuthenticationData {+ platform,+ profile,+ client_secret: None,+ },AuthenticationType::PublishableKey {merchant_id: merchant_account.get_id().clone(),},@@ -2855,12 +2885,6 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()- .find_business_profile_by_profile_id(&key_store, &profile_id)- .await- .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;-// Validate access based on merchant type and header presencecheck_merchant_access(state,@@ -2885,7 +2909,21 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let profile = state+ .store()+ .find_business_profile_by_merchant_id_profile_id(+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().get_id(),+ &profile_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;++ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth.clone(),AuthenticationType::ApiKey {@@ -3004,7 +3042,11 @@ whereinitiator,);- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,@@ -3054,6 +3096,41 @@ whereapi_auth}}++#[cfg(feature = "v2")]+pub fn sdk_or_api_or_client_auth<'a, T, A>(+ sdk_auth: &'a dyn AuthenticateAndFetch<T, A>,+ api_auth: &'a dyn AuthenticateAndFetch<T, A>,+ client_auth: &'a dyn AuthenticateAndFetch<T, A>,+ headers: &HeaderMap,+) -> &'a dyn AuthenticateAndFetch<T, A>+where+{+ // Check for SDK authorization (base64-encoded)+ if is_sdk_authorization(headers) {+ return sdk_auth;+ }++ api_or_client_auth(api_auth, client_auth, headers)+}++#[cfg(feature = "v2")]+pub fn sdk_or_client_auth<'a, T, A>(+ sdk_auth: &'a dyn AuthenticateAndFetch<T, A>,+ client_auth: &'a dyn AuthenticateAndFetch<T, A>,+ headers: &HeaderMap,+) -> &'a dyn AuthenticateAndFetch<T, A>+where+{+ // Check for SDK authorization (base64-encoded)+ if is_sdk_authorization(headers) {+ return sdk_auth;+ }++ // Fall back to client auth (publishable-key=)+ client_auth+}+#[derive(Debug, Default)]pub struct PublishableKeyAuth {pub allow_connected_scope_operation: bool,@@ -3196,7 +3273,11 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,AuthenticationType::PublishableKey {@@ -3207,12 +3288,21 @@ where}/// SDK Authorization authentication using Authorization header+#[cfg(feature = "v1")]#[derive(Debug, Default)]pub struct SdkAuthorizationAuth {pub allow_connected_scope_operation: bool,pub allow_platform_self_operation: bool,}+#[cfg(feature = "v2")]+#[derive(Debug)]+pub struct SdkAuthorizationAuth {+ pub allow_connected_scope_operation: bool,+ pub allow_platform_self_operation: bool,+ pub resource_id: common_utils::types::authentication::ResourceId,+}+#[cfg(feature = "v1")]#[async_trait]impl<A> AuthenticateAndFetch<AuthenticationData, A> for SdkAuthorizationAuth@@ -3235,7 +3325,7 @@ where.change_context(errors::ApiErrorResponse::Unauthorized)?;// Extract client_secret from decoded SDK authorization- let client_secret = Some(sdk_auth.client_secret.clone());+ let client_secret = sdk_auth.client_secret.clone();let (initiator_merchant, initiator_merchant_key_store) = match sdk_auth.platform_publishable_key@@ -3284,7 +3374,7 @@ wherelet auth_data = AuthenticationData {platform,profile: Some(profile),- client_secret,+ client_secret: Some(client_secret),};Ok((auth_data,@@ -3301,7 +3391,7 @@ pub async fn check_sdk_auth_and_resolve_platform<A>(initiator_merchant: domain::MerchantAccount,initiator_merchant_key_store: domain::MerchantKeyStore,allow_connected_scope_operation: bool,- _allow_platform_self_operation: bool,+ allow_platform_self_operation: bool,) -> RouterResult<domain::Platform>whereA: SessionStateInfo + Sync,@@ -3315,17 +3405,7 @@ where.attach_printable("Platform feature is not enabled")})?;- allow_connected_scope_operation- .then_some(())- .ok_or_else(|| {- report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)- .attach_printable(- "Connected Merchant is not authorized to access the resource",- )- })?;-- // Platform account flow- // Validate processor publishable key+ // Look up processor by publishable key from SDK authorizationlet (processor_merchant, processor_key_store) = state.store().find_merchant_account_by_publishable_key(&sdk_auth.publishable_key)@@ -3333,8 +3413,7 @@ where.to_not_found_response(errors::ApiErrorResponse::Unauthorized).attach_printable("Invalid processor publishable key in SDK authorization")?;- // Security validations- // 1. Check same organization+ // Validate same organizationfp_utils::when(processor_merchant.get_org_id() != initiator_merchant.get_org_id(),|| {@@ -3344,23 +3423,39 @@ where},)?;- // 2. Check merchant types- fp_utils::when(- processor_merchant.merchant_account_type != MerchantAccountType::Connected,- || {- Err(report!(errors::ApiErrorResponse::Unauthorized))- .attach_printable("Invalid merchant account types for platform flow")- },- )?;+ // Check authorization based on processor type+ let platform_account = match processor_merchant.merchant_account_type {+ MerchantAccountType::Connected => {+ // Platform acting on behalf of connected merchant+ allow_connected_scope_operation.then_some(()).ok_or_else(|| {+ report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)+ .attach_printable(+ "Connected merchant scope operation not allowed for this resource",+ )+ })?;+ Some(PlatformAccountWithKeyStore {+ account: initiator_merchant.clone(),+ key_store: initiator_merchant_key_store,+ })+ }+ MerchantAccountType::Platform => {+ // Platform acting on its own resources+ allow_platform_self_operation.then_some(()).ok_or_else(|| {+ report!(errors::ApiErrorResponse::Unauthorized).attach_printable(+ "Platform self operation not allowed for this resource",+ )+ })?;+ None+ }+ MerchantAccountType::Standard => {+ return Err(report!(errors::ApiErrorResponse::Unauthorized))+ .attach_printable(+ "Standard merchant type is not valid as processor in platform flow",+ );+ }+ };- (- processor_merchant,- processor_key_store,- Some(PlatformAccountWithKeyStore {- account: initiator_merchant.clone(),- key_store: initiator_merchant_key_store,- }),- )+ (processor_merchant, processor_key_store, platform_account)}MerchantAccountType::Connected => {// Check if platform feature is enabled@@ -3467,6 +3562,131 @@ where}}+#[cfg(feature = "v2")]+#[async_trait]+impl<A> AuthenticateAndFetch<AuthenticationData, A> for SdkAuthorizationAuth+where+ A: SessionStateInfo + Sync,+{+ async fn authenticate_and_fetch(+ &self,+ request_headers: &HeaderMap,+ state: &A,+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {+ // Get Authorization header+ let sdk_auth_header =+ get_header_value_by_key(headers::AUTHORIZATION.into(), request_headers)?+ .ok_or(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Missing Authorization header")?;++ // Decode SDK authorization+ let sdk_auth = SdkAuthorization::decode(sdk_auth_header)+ .change_context(errors::ApiErrorResponse::Unauthorized)?;++ // Extract client_secret from decoded SDK authorization+ let client_secret = sdk_auth.client_secret.clone();++ // Validate client_secret against database+ let db_client_secret: diesel_models::ClientSecretType = state+ .store()+ .get_client_secret(&client_secret)+ .await+ .change_context(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Invalid client_secret in SDK authorization")?;++ let (initiator_merchant, initiator_merchant_key_store) = match sdk_auth+ .platform_publishable_key+ {+ Some(ref platform_pub_key) => {+ let (platform_merchant, platform_key_store) = state+ .store()+ .find_merchant_account_by_publishable_key(platform_pub_key)+ .await+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Invalid platform publishable key in SDK authorization")?;++ (platform_merchant, platform_key_store)+ }+ None => {+ let (processor_merchant, processor_key_store) = state+ .store()+ .find_merchant_account_by_publishable_key(&sdk_auth.publishable_key)+ .await+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)+ .attach_printable("Invalid processor publishable key in SDK authorization")?;++ (processor_merchant, processor_key_store)+ }+ };++ if db_client_secret.merchant_id != *initiator_merchant.get_id() {+ return Err(errors::ApiErrorResponse::Unauthorized.into());+ }++ match (&self.resource_id, &db_client_secret.resource_id) {+ (+ common_utils::types::authentication::ResourceId::Payment(self_id),+ common_utils::types::authentication::ResourceId::Payment(db_id),+ ) => {+ fp_utils::when(self_id != db_id, || {+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)+ });+ }+ (+ common_utils::types::authentication::ResourceId::Customer(self_id),+ common_utils::types::authentication::ResourceId::Customer(db_id),+ ) => {+ fp_utils::when(self_id != db_id, || {+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)+ });+ }+ (+ common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id),+ common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id),+ ) => {+ fp_utils::when(self_id != db_id, || {+ Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)+ });+ }+ _ => {+ return Err(errors::ApiErrorResponse::Unauthorized.into());+ }+ }++ let platform = check_sdk_auth_and_resolve_platform(+ state,+ &sdk_auth,+ initiator_merchant.clone(),+ initiator_merchant_key_store,+ self.allow_connected_scope_operation,+ self.allow_platform_self_operation,+ )+ .await?;++ let profile = state+ .store()+ .find_business_profile_by_merchant_id_profile_id(+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().get_id(),+ &sdk_auth.profile_id,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;++ let auth_data = AuthenticationData {+ platform,+ profile,+ client_secret: Some(client_secret),+ };+ Ok((+ auth_data,+ AuthenticationType::SdkAuthorization {+ merchant_id: initiator_merchant.get_id().clone(),+ },+ ))+ }+}+#[cfg(feature = "olap")]#[async_trait]impl<A> AuthenticateAndFetch<UserFromToken, A> for JWTAuth@@ -3888,7 +4108,11 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,@@ -4141,7 +4365,11 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,AuthenticationType::MerchantJwt {@@ -4450,7 +4678,11 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth.clone(),AuthenticationType::MerchantJwt {@@ -4634,7 +4866,11 @@ where).await?;- let auth = AuthenticationData { platform, profile };+ let auth = AuthenticationData {+ platform,+ profile,+ client_secret: None,+ };Ok((auth,AuthenticationType::MerchantJwt {@@ -5325,6 +5561,17 @@ pub fn is_jwt_auth(headers: &HeaderMap) -> bool {}}+/// Checks if Authorization header contains SDK authorization (base64-encoded)+#[cfg(feature = "v2")]+pub fn is_sdk_authorization(headers: &HeaderMap) -> bool {+ if let Ok(auth_val) = HeaderMapStruct::new(headers).get_auth_string_from_header() {+ let trimmed = auth_val.trim();+ // Try to decode using SdkAuthorization::decode - if it succeeds, it's SDK auth+ return SdkAuthorization::decode(trimmed).is_ok();+ }+ false+}+pub fn is_internal_api_key_merchant_id_profile_id_auth(headers: &HeaderMap,internal_api_key_auth: settings::InternalMerchantIdProfileIdAuthSettings,