Skip to content

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

feat(platform): add sdk_authorization to PaymentsResponse and implement SDK auth flow (#11079)

Sandeep Kumarad89c39b2cf6
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index a14f5db8b8..928155dd7c 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -28319,6 +28319,12 @@
],
"nullable": true
},
+ "sdk_authorization": {
+ "type": "string",
+ "description": "Token containing encoded information for sdk authorization.",
+ "example": "cHJvZmlsZV9pZD1wcm9mXzEyMyxwdWJsaXNoYWJsZV9rZXk9cGtfbGl2ZV8xMjM=",
+ "nullable": true
+ },
"connector": {
"type": "string",
"description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.",
@@ -29907,6 +29913,12 @@
],
"nullable": true
},
+ "sdk_authorization": {
+ "type": "string",
+ "description": "Token containing encoded information for sdk authorization.",
+ "example": "cHJvZmlsZV9pZD1wcm9mXzEyMyxwdWJsaXNoYWJsZV9rZXk9cGtfbGl2ZV8xMjM=",
+ "nullable": true
+ },
"connector": {
"type": "string",
"description": "The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index c82e688ea1..c4b7dd6ab7 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -7142,6 +7142,11 @@ pub struct PaymentsResponse {
#[smithy(value_type = "Option<Initiator>")]
pub initiator: Option<platform::Initiator>,
+ /// Token containing encoded information for sdk authorization.
+ #[schema(value_type = Option<String>, example = "cHJvZmlsZV9pZD1wcm9mXzEyMyxwdWJsaXNoYWJsZV9rZXk9cGtfbGl2ZV8xMjM=")]
+ #[smithy(value_type = "Option<String>")]
+ pub sdk_authorization: Option<String>,
+
/// The name of the payment connector (e.g., 'stripe', 'adyen') that processed or is processing this payment.
#[schema(example = "stripe")]
#[smithy(value_type = "Option<String>")]
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 9027d65798..9e1a34d04d 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -39,6 +39,7 @@ pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
pub mod routing;
+pub mod sdk_auth;
pub mod subscription;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
diff --git a/crates/hyperswitch_domain_models/src/platform.rs b/crates/hyperswitch_domain_models/src/platform.rs
index febb2595dd..babe4b47d3 100644
--- a/crates/hyperswitch_domain_models/src/platform.rs
+++ b/crates/hyperswitch_domain_models/src/platform.rs
@@ -55,6 +55,7 @@ pub enum Initiator {
Api {
merchant_id: common_utils::id_type::MerchantId,
merchant_account_type: common_enums::MerchantAccountType,
+ publishable_key: String,
},
Jwt {
user_id: String,
diff --git a/crates/hyperswitch_domain_models/src/sdk_auth.rs b/crates/hyperswitch_domain_models/src/sdk_auth.rs
new file mode 100644
index 0000000000..7a07b37f04
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/sdk_auth.rs
@@ -0,0 +1,125 @@
+use std::collections::HashMap;
+
+use base64::Engine;
+use common_utils::{
+ consts::BASE64_ENGINE,
+ errors::{CustomResult, ValidationError},
+ id_type,
+};
+use error_stack::{report, ResultExt};
+
+/// 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
+ pub profile_id: id_type::ProfileId,
+
+ /// The publishable key of the processor merchant (connected or standard)
+ pub publishable_key: String,
+
+ /// Platform publishable key (only for platform-initiated flows)
+ pub platform_publishable_key: Option<String>,
+
+ /// Client secret for the payment (if available)
+ pub client_secret: Option<String>,
+
+ /// Customer ID for the payment (if available)
+ pub customer_id: Option<id_type::CustomerId>,
+}
+
+impl SdkAuthorization {
+ /// Encodes SdkAuthorization into base64-encoded comma-separated key-value pairs
+ ///
+ /// Returns base64-encoded string in format: `base64(key1=value1,key2=value2,...)`
+ pub fn encode(&self) -> CustomResult<String, ValidationError> {
+ let comma_separated = [
+ Some(format!("profile_id={}", self.profile_id.get_string_repr())),
+ Some(format!("publishable_key={}", self.publishable_key)),
+ self.platform_publishable_key
+ .as_ref()
+ .map(|k| format!("platform_publishable_key={}", k)),
+ self.client_secret
+ .as_ref()
+ .map(|s| format!("client_secret={}", s)),
+ self.customer_id
+ .as_ref()
+ .map(|id| format!("customer_id={}", id.get_string_repr())),
+ ]
+ .into_iter()
+ .flatten()
+ .collect::<Vec<_>>()
+ .join(",");
+
+ Ok(BASE64_ENGINE.encode(comma_separated))
+ }
+
+ /// Decodes base64 string to SdkAuthorization
+ ///
+ /// # Arguments
+ /// * `encoded` - Base64-encoded string containing comma-separated key-value pairs
+ ///
+ /// # Returns
+ /// Decoded and validated SdkAuthorization instance
+ pub fn decode(encoded: &str) -> CustomResult<Self, ValidationError> {
+ let decoded_bytes =
+ BASE64_ENGINE
+ .decode(encoded)
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed to decode SDK authorization".to_string(),
+ })?;
+
+ let comma_separated =
+ String::from_utf8(decoded_bytes).change_context(ValidationError::InvalidValue {
+ message: "SDK authorization is not valid UTF-8".to_string(),
+ })?;
+
+ let parts: HashMap<&str, &str> = comma_separated
+ .split(',')
+ .map(|part| {
+ part.split_once('=')
+ .map(|(k, v)| (k.trim(), v.trim()))
+ .ok_or_else(|| {
+ report!(ValidationError::InvalidValue {
+ message: "Invalid SDK authorization format: missing '=' separator"
+ .to_string()
+ })
+ })
+ })
+ .collect::<CustomResult<HashMap<_, _>, _>>()?;
+
+ Ok(Self {
+ profile_id: id_type::ProfileId::try_from(std::borrow::Cow::from(
+ parts
+ .get("profile_id")
+ .ok_or_else(|| {
+ report!(ValidationError::InvalidValue {
+ message: "Missing required field: profile_id".to_string()
+ })
+ })?
+ .to_string(),
+ ))
+ .change_context(ValidationError::InvalidValue {
+ message: "Invalid profile_id format".to_string(),
+ })?,
+ publishable_key: parts
+ .get("publishable_key")
+ .ok_or_else(|| {
+ report!(ValidationError::InvalidValue {
+ message: "Missing required field: publishable_key".to_string()
+ })
+ })?
+ .to_string(),
+ platform_publishable_key: parts.get("platform_publishable_key").map(|v| v.to_string()),
+ client_secret: parts.get("client_secret").map(|v| v.to_string()),
+ customer_id: parts
+ .get("customer_id")
+ .map(|v| {
+ id_type::CustomerId::try_from(std::borrow::Cow::from(v.to_string()))
+ .change_context(ValidationError::InvalidValue {
+ message: "Invalid customer_id format".to_string(),
+ })
+ })
+ .transpose()?,
+ })
+ }
+}
diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs
index 09791f7279..b4ee992036 100644
--- a/crates/router/src/compatibility/stripe/payment_intents.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents.rs
@@ -130,7 +130,7 @@ pub async fn payment_intents_retrieve(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
@@ -384,7 +384,7 @@ pub async fn payment_intents_confirm(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs
index 7b70524b28..04251c9723 100644
--- a/crates/router/src/compatibility/stripe/setup_intents.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents.rs
@@ -116,7 +116,7 @@ pub async fn setup_intents_retrieve(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
@@ -197,7 +197,7 @@ pub async fn setup_intents_update(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
@@ -279,7 +279,7 @@ pub async fn setup_intents_confirm(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 3e0514e26a..c2294554b1 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -10,7 +10,7 @@ use api_models::payments::{
Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,
MandateIds, NetworkDetails, RequestSurchargeDetails,
};
-use common_enums::{Currency, RequestIncrementalAuthorization};
+use common_enums::{Currency, MerchantAccountType, RequestIncrementalAuthorization};
#[cfg(feature = "v1")]
use common_utils::{
consts::X_HS_LATENCY,
@@ -37,7 +37,9 @@ use diesel_models::{
},
};
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
+use hyperswitch_domain_models::{
+ payments::payment_intent::CustomerData, router_request_types, sdk_auth::SdkAuthorization,
+};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
router_data_v2::{flow_common_types, RouterDataV2},
@@ -3908,6 +3910,35 @@ where
.map(api_payments::PaymentMethodTokenizationDetails::foreign_try_from)
.transpose()?;
+ // Construct SDK authorization for client SDK
+ let sdk_auth_data = SdkAuthorization {
+ profile_id: payment_intent
+ .profile_id
+ .clone()
+ .get_required_value("profile_id")?,
+ publishable_key: processor.get_account().publishable_key.clone(),
+ platform_publishable_key: initiator.and_then(|init| match init {
+ domain::Initiator::Api {
+ merchant_account_type,
+ publishable_key,
+ ..
+ } => match merchant_account_type {
+ MerchantAccountType::Platform => Some(publishable_key.clone()),
+ MerchantAccountType::Standard | MerchantAccountType::Connected => None,
+ },
+ domain::Initiator::Admin
+ | domain::Initiator::Jwt { .. }
+ | domain::Initiator::EmbeddedToken { .. } => None,
+ }),
+ client_secret: payment_intent.client_secret.clone(),
+ customer_id: payment_intent.customer_id.clone(),
+ };
+
+ let sdk_authorization = sdk_auth_data
+ .encode()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode SDK authorization")?;
+
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
merchant_id: payment_intent.merchant_id,
@@ -3918,6 +3949,7 @@ where
amount_received: payment_intent.amount_captured,
processor_merchant_id: processor.get_account().get_id().clone(),
initiator: initiator.and_then(|initiator| initiator.to_api_initiator()),
+ sdk_authorization: Some(sdk_authorization),
connector: routed_through,
client_secret: payment_intent.client_secret.map(Secret::new),
created: Some(payment_intent.created_at),
@@ -4298,6 +4330,7 @@ impl
amount_received: None,
processor_merchant_id: pi.processor_merchant_id,
initiator: api_initiator,
+ sdk_authorization: None,
refunds: None,
disputes: None,
attempts: None,
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 735c698392..bbf3863d91 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -1438,6 +1438,7 @@ mod tests {
net_amount: MinorUnit::new(6540),
processor_merchant_id: merchant_id,
initiator: None,
+ sdk_authorization: None,
connector: None,
customer: None,
disputes: None,
diff --git a/crates/router/src/routes/authentication.rs b/crates/router/src/routes/authentication.rs
index 57c56ca220..d2b5f6111f 100644
--- a/crates/router/src/routes/authentication.rs
+++ b/crates/router/src/routes/authentication.rs
@@ -53,8 +53,7 @@ pub async fn authentication_eligibility(
let api_auth = auth::ApiKeyAuth::default();
let payload = json_payload.into_inner();
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
- {
+ let (auth, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -96,7 +95,7 @@ pub async fn authentication_authenticate(
};
let (auth, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -137,7 +136,7 @@ pub async fn authentication_eligibility_check(
};
let (auth, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -212,7 +211,7 @@ pub async fn authentication_sync(
..json_payload.into_inner()
};
let (auth, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -282,7 +281,7 @@ pub async fn authentication_session_token(
};
let (auth, _auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, auth_flow)) => (auth, auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index fe9aa8bfee..224e730907 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -118,11 +118,11 @@ pub async fn list_blocked_payment_methods(
allow_platform_self_operation: false,
};
- let (auth_type, _) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
- Ok(auth) => auth,
- Err(err) => return api::log_and_return_error_response(report!(err)),
- };
+ let (auth_type, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth)
+ {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(report!(err)),
+ };
Box::pin(api::server_wrap(
flow,
diff --git a/crates/router/src/routes/cards_info.rs b/crates/router/src/routes/cards_info.rs
index f534f49dda..e4c6bdc438 100644
--- a/crates/router/src/routes/cards_info.rs
+++ b/crates/router/src/routes/cards_info.rs
@@ -41,8 +41,7 @@ pub async fn card_iin_info(
let api_auth = auth::ApiKeyAuth::default();
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
- {
+ let (auth, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs
index 6bce4f3b49..450bcf75d1 100644
--- a/crates/router/src/routes/payment_link.rs
+++ b/crates/router/src/routes/payment_link.rs
@@ -21,11 +21,22 @@ pub async fn payment_link_retrieve(
let payload = json_payload.into_inner();
let api_auth = auth::ApiKeyAuth::default();
- let (auth_type, _) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
- Ok(auth) => auth,
- Err(err) => return api::log_and_return_error_response(error_stack::report!(err)),
- };
+ let (auth_type, _) = {
+ #[cfg(feature = "v1")]
+ {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(error_stack::report!(err)),
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ }
+ }
+ };
api::server_wrap(
flow,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index a66e672c0f..ff00fa0f46 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -623,8 +623,7 @@ pub async fn save_payment_method_api(
allow_platform_self_operation: true,
};
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
- {
+ let (auth, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -662,8 +661,7 @@ pub async fn list_payment_method_api(
allow_platform_self_operation: true,
};
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
- {
+ let (auth, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
@@ -998,8 +996,7 @@ pub async fn payment_method_update_api(
allow_platform_self_operation: true,
};
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth)
- {
+ let (auth, _) = match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 6f8a392889..bc11637f4d 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1470,8 +1470,7 @@ pub async fn payments_complete_authorize(
};
let (auth_type, auth_flow) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req, api_auth)
- {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payment_confirm_req, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
@@ -2525,7 +2524,7 @@ pub async fn payments_submit_eligibility(
};
let (auth_type, _auth_flow) =
- match auth::check_client_secret_and_get_auth(http_req.headers(), &payload, api_auth) {
+ match auth::check_sdk_auth_and_get_auth(http_req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 92b485e6a5..d94b4d18f9 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -158,11 +158,22 @@ pub async fn payouts_confirm(
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth::default();
- let (auth_type, _auth_flow) =
- 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),
- };
+ let (auth_type, _auth_flow) = {
+ #[cfg(feature = "v1")]
+ {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(e) => return api::log_and_return_error_response(e),
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ 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),
+ }
+ }
+ };
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs
index 92359a7c1b..d918699070 100644
--- a/crates/router/src/routes/pm_auth.rs
+++ b/crates/router/src/routes/pm_auth.rs
@@ -19,13 +19,29 @@ pub async fn link_token_create(
let flow = Flow::PmAuthLinkTokenCreate;
let api_auth = auth::ApiKeyAuth::default();
- let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
- req.headers(),
- &payload,
- api_auth,
- ) {
- Ok((auth, _auth_flow)) => (auth, _auth_flow),
- Err(e) => return api::log_and_return_error_response(e),
+ let (auth, _) = {
+ #[cfg(feature = "v1")]
+ {
+ match crate::services::authentication::check_sdk_auth_and_get_auth(
+ req.headers(),
+ &payload,
+ api_auth,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ match crate::services::authentication::check_client_secret_and_get_auth(
+ req.headers(),
+ &payload,
+ api_auth,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ }
+ }
};
let header_payload =
@@ -65,13 +81,29 @@ pub async fn exchange_token(
let flow = Flow::PmAuthExchangeToken;
let api_auth = auth::ApiKeyAuth::default();
- let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
- req.headers(),
- &payload,
- api_auth,
- ) {
- Ok((auth, _auth_flow)) => (auth, _auth_flow),
- Err(e) => return api::log_and_return_error_response(e),
+ let (auth, _) = {
+ #[cfg(feature = "v1")]
+ {
+ match crate::services::authentication::check_sdk_auth_and_get_auth(
+ req.headers(),
+ &payload,
+ api_auth,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ match crate::services::authentication::check_client_secret_and_get_auth(
+ req.headers(),
+ &payload,
+ api_auth,
+ ) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ }
+ }
};
Box::pin(api::server_wrap(
flow,
diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs
index 2c2fd53ad0..e5a65ce7b3 100644
--- a/crates/router/src/routes/subscription.rs
+++ b/crates/router/src/routes/subscription.rs
@@ -214,11 +214,26 @@ pub async fn confirm_subscription(
let api_auth = auth::ApiKeyAuth::default();
- let (auth_type, _) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
- Ok(auth) => auth,
- Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)),
- };
+ let (auth_type, _) = {
+ #[cfg(feature = "v1")]
+ {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => {
+ return oss_api::log_and_return_error_response(error_stack::report!(err))
+ }
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => {
+ return oss_api::log_and_return_error_response(error_stack::report!(err))
+ }
+ }
+ }
+ };
Box::pin(oss_api::server_wrap(
flow,
@@ -261,11 +276,26 @@ pub async fn get_subscription_items(
Err(response) => return response,
};
- let (auth_type, _) =
- match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
- Ok(auth) => auth,
- Err(err) => return oss_api::log_and_return_error_response(error_stack::report!(err)),
- };
+ let (auth_type, _) = {
+ #[cfg(feature = "v1")]
+ {
+ match auth::check_sdk_auth_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => {
+ return oss_api::log_and_return_error_response(error_stack::report!(err))
+ }
+ }
+ }
+ #[cfg(feature = "v2")]
+ {
+ match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
+ Ok(auth) => auth,
+ Err(err) => {
+ return oss_api::log_and_return_error_response(error_stack::report!(err))
+ }
+ }
+ }
+ };
Box::pin(oss_api::server_wrap(
flow,
state,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 7a08199c07..1d671b6371 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -15,6 +15,7 @@ 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;
use jsonwebtoken::{
decode, errors::ErrorKind::ExpiredSignature, Algorithm, DecodingKey, Validation,
};
@@ -186,6 +187,9 @@ pub enum AuthenticationType {
PublishableKey {
merchant_id: id_type::MerchantId,
},
+ SdkAuthorization {
+ merchant_id: id_type::MerchantId,
+ },
WebhookAuth {
merchant_id: id_type::MerchantId,
},
@@ -228,7 +232,8 @@ impl AuthenticationType {
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id }
| Self::InternalMerchantIdProfileId { merchant_id, .. }
- | Self::EmbeddedJwt { merchant_id, .. } => Some(merchant_id),
+ | Self::EmbeddedJwt { merchant_id, .. }
+ | Self::SdkAuthorization { merchant_id, .. } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
| Self::BasicAuth { .. }
@@ -649,6 +654,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -752,6 +758,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -1021,6 +1028,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant_account.get_id().clone(),
merchant_account_type: initiator_merchant_account.merchant_account_type,
+ publishable_key: initiator_merchant_account.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -1159,6 +1167,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: platform_merchant.get_id().clone(),
merchant_account_type: platform_merchant.merchant_account_type,
+ publishable_key: platform_merchant.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -1394,6 +1403,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -2049,6 +2059,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: api_key_merchant.get_id().clone(),
merchant_account_type: api_key_merchant.merchant_account_type,
+ publishable_key: api_key_merchant.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -2417,6 +2428,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant.get_id().clone(),
merchant_account_type: merchant.merchant_account_type,
+ publishable_key: merchant.publishable_key.clone(),
});
let platform =
@@ -2482,6 +2494,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant.get_id().clone(),
merchant_account_type: merchant.merchant_account_type,
+ publishable_key: merchant.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -2591,6 +2604,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant.get_id().clone(),
merchant_account_type: merchant.merchant_account_type,
+ publishable_key: merchant.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -2668,6 +2682,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant.get_id().clone(),
merchant_account_type: merchant.merchant_account_type,
+ publishable_key: merchant.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -2729,6 +2744,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant_account.get_id().clone(),
merchant_account_type: merchant_account.merchant_account_type,
+ publishable_key: merchant_account.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -2844,6 +2860,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -2963,6 +2980,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: merchant_account.get_id().clone(),
merchant_account_type: merchant_account.merchant_account_type,
+ publishable_key: merchant_account.publishable_key.clone(),
});
let platform = domain::Platform::new(
@@ -3079,6 +3097,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -3139,6 +3158,7 @@ where
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant.get_id().clone(),
merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key.clone(),
});
let platform = resolve_platform(
@@ -3171,6 +3191,225 @@ where
}
}
+/// SDK Authorization authentication using Authorization header
+#[derive(Debug, Default)]
+pub struct SdkAuthorizationAuth {
+ pub allow_connected_scope_operation: bool,
+ pub allow_platform_self_operation: bool,
+}
+
+#[cfg(feature = "v1")]
+#[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)?;
+
+ 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)
+ }
+ };
+ 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 = AuthenticationData {
+ platform,
+ profile: Some(profile),
+ };
+ Ok((
+ auth,
+ AuthenticationType::SdkAuthorization {
+ merchant_id: initiator_merchant.get_id().clone(),
+ },
+ ))
+ }
+}
+
+pub async fn check_sdk_auth_and_resolve_platform<A>(
+ state: &A,
+ sdk_auth: &SdkAuthorization,
+ initiator_merchant: domain::MerchantAccount,
+ initiator_merchant_key_store: domain::MerchantKeyStore,
+ allow_connected_scope_operation: bool,
+ _allow_platform_self_operation: bool,
+) -> RouterResult<domain::Platform>
+where
+ A: SessionStateInfo + Sync,
+{
+ let (processor_merchant_account, processor_key_store, platform_account_with_key_store) =
+ match initiator_merchant.merchant_account_type {
+ MerchantAccountType::Platform => {
+ // Check if platform feature is enabled
+ state.conf().platform.enabled.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::PlatformAccountAuthNotSupported)
+ .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
+ 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")?;
+
+ // Security validations
+ // 1. Check same organization
+ fp_utils::when(
+ processor_merchant.get_org_id() != initiator_merchant.get_org_id(),
+ || {
+ Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
+ "Platform and processor merchants must be in same organization",
+ )
+ },
+ )?;
+
+ // 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")
+ },
+ )?;
+
+ (
+ processor_merchant,
+ processor_key_store,
+ Some(PlatformAccountWithKeyStore {
+ account: initiator_merchant.clone(),
+ key_store: initiator_merchant_key_store,
+ }),
+ )
+ }
+ MerchantAccountType::Connected => {
+ // Check if platform feature is enabled
+ state.conf().platform.enabled.then_some(()).ok_or_else(|| {
+ report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)
+ .attach_printable("Platform feature is not enabled")
+ })?;
+
+ // Connected merchant can perform operation if allow_connected_scope_operation is true
+ allow_connected_scope_operation
+ .then_some(())
+ .ok_or_else(|| {
+ report!(errors::ApiErrorResponse::ConnectedAccountAuthNotSupported)
+ .attach_printable(
+ "Connected Merchant is not authorized to access the resource",
+ )
+ })?;
+
+ // Connected merchant as initiator
+ // Fetch platform merchant and key store using helper function
+ let (platform_merchant, platform_key_store) =
+ get_platform_account_and_key_store(state, &initiator_merchant).await?;
+
+ (
+ initiator_merchant.clone(),
+ initiator_merchant_key_store,
+ Some(PlatformAccountWithKeyStore {
+ account: platform_merchant,
+ key_store: platform_key_store,
+ }),
+ )
+ }
+ MerchantAccountType::Standard => {
+ // Standard merchant flow
+ // Provider and processor are the same merchant
+ (
+ initiator_merchant.clone(),
+ initiator_merchant_key_store,
+ None,
+ )
+ }
+ };
+
+ let initiator = Some(domain::Initiator::Api {
+ merchant_id: initiator_merchant.get_id().clone(),
+ merchant_account_type: initiator_merchant.merchant_account_type,
+ publishable_key: initiator_merchant.publishable_key,
+ });
+
+ let platform = match platform_account_with_key_store {
+ Some(platform_account) => domain::Platform::new(
+ platform_account.account,
+ platform_account.key_store,
+ processor_merchant_account,
+ processor_key_store,
+ initiator,
+ ),
+ None => domain::Platform::new(
+ processor_merchant_account.clone(),
+ processor_key_store.clone(),
+ processor_merchant_account,
+ processor_key_store,
+ initiator,
+ ),
+ };
+
+ Ok(platform)
+}
#[derive(Debug)]
pub(crate) struct JWTAuth {
pub permission: Permission,
@@ -4928,6 +5167,39 @@ where
Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant))
}
+/// Checks Authorization header first for SDK auth, if not exists calls check_client_secret_and_get_auth
+#[cfg(feature = "v1")]
+pub fn check_sdk_auth_and_get_auth<T>(
+ headers: &HeaderMap,
+ payload: &impl ClientSecretFetch,
+ api_auth: ApiKeyAuth,
+) -> RouterResult<(
+ Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
+ api::AuthFlow,
+)>
+where
+ T: SessionStateInfo + Sync + Send,
+ ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+ PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+ SdkAuthorizationAuth: AuthenticateAndFetch<AuthenticationData, T>,
+{
+ // Check Authorization header first
+ match get_header_value_by_key(headers::AUTHORIZATION.into(), headers)? {
+ // SDK authorization flow
+ Some(_auth) => Ok((
+ Box::new(SdkAuthorizationAuth {
+ allow_connected_scope_operation: api_auth.allow_connected_scope_operation,
+ allow_platform_self_operation: api_auth.allow_platform_self_operation,
+ }),
+ api::AuthFlow::Client,
+ )),
+ None => {
+ // Use existing client_secret and publishable key check
+ check_client_secret_and_get_auth(headers, payload, api_auth)
+ }
+ }
+}
+
pub async fn get_ephemeral_or_other_auth<T>(
headers: &HeaderMap,
is_merchant_flow: bool,
@@ -4956,7 +5228,16 @@ where
))
} else {
let payload = payload.get_required_value("ClientSecretFetch")?;
- let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload, api_auth)?;
+ let (auth, auth_flow) = {
+ #[cfg(feature = "v1")]
+ {
+ check_sdk_auth_and_get_auth(headers, payload, api_auth)?
+ }
+ #[cfg(feature = "v2")]
+ {
+ check_client_secret_and_get_auth(headers, payload, api_auth)?
+ }
+ };
Ok((auth, auth_flow, false))
}
}
@@ -5016,7 +5297,7 @@ where
api::AuthFlow::Merchant,
))
} else {
- check_client_secret_and_get_auth(headers, payload, api_auth)
+ check_sdk_auth_and_get_auth(headers, payload, api_auth)
}
}
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 5f419bedb5..6c2977c987 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -389,6 +389,7 @@ async fn payments_create_core() {
net_amount: MinorUnit::new(6540),
processor_merchant_id: merchant_id,
initiator: None,
+ sdk_authorization: None,
connector: None,
customer: None,
disputes: None,
@@ -686,6 +687,7 @@ async fn payments_create_core_adyen_no_redirect() {
net_amount: MinorUnit::new(6540),
processor_merchant_id: merchant_id,
initiator: None,
+ sdk_authorization: None,
connector: None,
customer: None,
disputes: None,
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 5389e2a486..5831f8606e 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -149,6 +149,7 @@ async fn payments_create_core() {
net_amount: MinorUnit::new(6540),
processor_merchant_id: merchant_id,
initiator: None,
+ sdk_authorization: None,
connector: None,
customer: None,
disputes: None,
@@ -455,6 +456,7 @@ async fn payments_create_core_adyen_no_redirect() {
net_amount: MinorUnit::new(6540),
processor_merchant_id: merchant_id,
initiator: None,
+ sdk_authorization: None,
connector: None,
customer: None,
disputes: None,