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(router): add core changes for post and get eligibility check apis for modular authentication (#10131)

Sai Harsha Vardhand11be0e6d9cf
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 61b5a12297..d8dce96335 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -10223,6 +10223,13 @@
}
}
}
+ },
+ {
+ "type": "string",
+ "description": "The next action is to proceed with the payment",
+ "enum": [
+ "proceed"
+ ]
}
]
},
diff --git a/crates/api_models/src/authentication.rs b/crates/api_models/src/authentication.rs
index 4e7d2abc13..6072e66107 100644
--- a/crates/api_models/src/authentication.rs
+++ b/crates/api_models/src/authentication.rs
@@ -359,6 +359,8 @@ pub enum AuthenticationSdkNextAction {
AwaitMerchantCallback,
/// The next action is to deny the payment with an error message
Deny { message: String },
+ /// The next action is to proceed with the payment
+ Proceed,
}
#[cfg(feature = "v1")]
diff --git a/crates/common_utils/src/id_type/merchant.rs b/crates/common_utils/src/id_type/merchant.rs
index ef99a4d1a9..b3f8912a25 100644
--- a/crates/common_utils/src/id_type/merchant.rs
+++ b/crates/common_utils/src/id_type/merchant.rs
@@ -231,4 +231,12 @@ impl MerchantId {
pub fn get_should_perform_eligibility_check_key(&self) -> String {
format!("should_perform_eligibility_{}", self.get_string_repr())
}
+
+ /// Get should store eligibility check data for authentication
+ pub fn get_should_store_eligibility_check_data_for_authentication(&self) -> String {
+ format!(
+ "should_store_eligibility_check_data_for_authentication_{}",
+ self.get_string_repr()
+ )
+ }
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 42cac5800a..6e20a8fa26 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -121,6 +121,12 @@ pub const OUTGOING_CALL_URL: &str = "https://api.stripe.com/healthcheck";
// 15 minutes = 900 seconds
pub const POLL_ID_TTL: i64 = 900;
+// 15 minutes = 900 seconds
+pub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_TTL: i64 = 900;
+
+// Prefix key for storing authentication eligibility check data in redis
+pub const AUTHENTICATION_ELIGIBILITY_CHECK_DATA_KEY: &str = "AUTH_ELIGIBILITY_CHECK_DATA_";
+
// Default Poll Config
pub const DEFAULT_POLL_DELAY_IN_SECS: i8 = 2;
pub const DEFAULT_POLL_FREQUENCY: i8 = 5;
diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs
index 544a3ed584..f5c85728a0 100644
--- a/crates/router/src/core/unified_authentication_service.rs
+++ b/crates/router/src/core/unified_authentication_service.rs
@@ -1,22 +1,30 @@
pub mod types;
use std::str::FromStr;
+use common_utils::ext_traits::StringExt;
+
pub mod utils;
#[cfg(feature = "v1")]
use api_models::authentication::{
+ AuthenticationEligibilityCheckData, AuthenticationEligibilityCheckRequest,
+ AuthenticationEligibilityCheckResponse, AuthenticationEligibilityCheckResponseData,
AuthenticationEligibilityRequest, AuthenticationEligibilityResponse,
+ AuthenticationRetrieveEligibilityCheckRequest, AuthenticationRetrieveEligibilityCheckResponse,
AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse,
+ ClickToPayEligibilityCheckResponseData,
};
use api_models::{
authentication::{
AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse,
- AuthenticationCreateRequest, AuthenticationResponse, AuthenticationSessionTokenRequest,
+ AuthenticationCreateRequest, AuthenticationResponse, AuthenticationSdkNextAction,
+ AuthenticationSessionTokenRequest,
},
payments::{self, CustomerDetails},
};
#[cfg(feature = "v1")]
use common_utils::{
- ext_traits::ValueExt, types::keymanager::ToEncryptable, types::AmountConvertor,
+ errors::CustomResult, ext_traits::ValueExt, types::keymanager::ToEncryptable,
+ types::AmountConvertor,
};
use diesel_models::authentication::{Authentication, AuthenticationNew};
use error_stack::ResultExt;
@@ -1433,6 +1441,250 @@ pub async fn authentication_authenticate_core(
))
}
+// Trait for Eligibility Checks
+#[cfg(feature = "v1")]
+#[async_trait::async_trait]
+trait EligibilityCheck {
+ type Output;
+
+ // Determine if the check should be run based on the runtime checks
+ async fn should_run(
+ &self,
+ state: &SessionState,
+ merchant_context: &domain::MerchantContext,
+ ) -> CustomResult<bool, ApiErrorResponse>;
+
+ // Run the actual check and return the SDK Next Action if applicable
+ async fn execute_check(
+ &self,
+ state: &SessionState,
+ merchant_context: &domain::MerchantContext,
+ authentication_eligibility_check_request: &AuthenticationEligibilityCheckRequest,
+ ) -> CustomResult<Self::Output, ApiErrorResponse>;
+
+ fn transform(output: Self::Output) -> Option<AuthenticationSdkNextAction>;
+}
+
+// Result of an Eligibility Check
+#[cfg(feature = "v1")]
+#[derive(Debug, Clone)]
+pub enum CheckResult {
+ Allow,
+ Deny { message: String },
+ Await,
+}
+
+#[cfg(feature = "v1")]
+impl From<CheckResult> for Option<AuthenticationSdkNextAction> {
+ fn from(result: CheckResult) -> Self {
+ match result {
+ CheckResult::Allow => None,
+ CheckResult::Deny { message } => Some(AuthenticationSdkNextAction::Deny { message }),
+ CheckResult::Await => Some(AuthenticationSdkNextAction::AwaitMerchantCallback),
+ }
+ }
+}
+
+// Perform StoreEligibilityCheckData for the authentication
+#[cfg(feature = "v1")]
+struct StoreEligibilityCheckData;
+
+#[cfg(feature = "v1")]
+#[async_trait::async_trait]
+impl EligibilityCheck for StoreEligibilityCheckData {
+ type Output = CheckResult;
+
+ async fn should_run(
+ &self,
+ state: &SessionState,
+ merchant_context: &domain::MerchantContext,
+ ) -> CustomResult<bool, ApiErrorResponse> {
+ let merchant_id = merchant_context.get_merchant_account().get_id();
+ let should_store_eligibility_check_data_key =
+ merchant_id.get_should_store_eligibility_check_data_for_authentication();
+ let should_store_eligibility_check_data = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &should_store_eligibility_check_data_key,
+ Some("false".to_string()),
+ )
+ .await;
+
+ Ok(match should_store_eligibility_check_data {
+ Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),
+
+ // If it is not present in db we are defaulting it to false
+ Err(inner) => {
+ if !inner.current_context().is_db_not_found() {
+ router_env::logger::error!(
+ "Error fetching should store eligibility check data enabled config {:?}",
+ inner
+ );
+ }
+ false
+ }
+ })
+ }
+
+ async fn execute_check(
+ &self,
+ state: &SessionState,
+ merchant_context: &domain::MerchantContext,
+ authentication_eligibility_check_request: &AuthenticationEligibilityCheckRequest,
+ ) -> CustomResult<CheckResult, ApiErrorResponse> {
+ let redis = &state
+ .store
+ .get_redis_conn()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+ let key = format!(
+ "{}_{}_{}",
+ consts::AUTHENTICATION_ELIGIBILITY_CHECK_DATA_KEY,
+ merchant_context
+ .get_merchant_account()
+ .get_id()
+ .get_string_repr(),
+ authentication_eligibility_check_request
+ .authentication_id
+ .get_string_repr()
+ );
+ redis
+ .serialize_and_set_key_with_expiry(
+ &key.as_str().into(),
+ &authentication_eligibility_check_request.eligibility_check_data,
+ consts::AUTHENTICATION_ELIGIBILITY_CHECK_DATA_TTL,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to set key in redis")?;
+ Ok(CheckResult::Await)
+ }
+
+ fn transform(output: CheckResult) -> Option<AuthenticationSdkNextAction> {
+ output.into()
+ }
+}
+
+// Eligibility handler to run all the eligibility checks
+#[cfg(feature = "v1")]
+pub struct EligibilityHandler {
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ authentication_eligibility_check_request: AuthenticationEligibilityCheckRequest,
+}
+
+#[cfg(feature = "v1")]
+impl EligibilityHandler {
+ fn new(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ authentication_eligibility_check_request: AuthenticationEligibilityCheckRequest,
+ ) -> Self {
+ Self {
+ state,
+ merchant_context,
+ authentication_eligibility_check_request,
+ }
+ }
+
+ async fn run_check<C: EligibilityCheck>(
+ &self,
+ check: C,
+ ) -> CustomResult<Option<AuthenticationSdkNextAction>, ApiErrorResponse> {
+ let should_run = check
+ .should_run(&self.state, &self.merchant_context)
+ .await?;
+ Ok(match should_run {
+ true => check
+ .execute_check(
+ &self.state,
+ &self.merchant_context,
+ &self.authentication_eligibility_check_request,
+ )
+ .await
+ .map(C::transform)?,
+ false => None,
+ })
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn authentication_eligibility_check_core(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ req: AuthenticationEligibilityCheckRequest,
+ _auth_flow: AuthFlow,
+) -> RouterResponse<AuthenticationEligibilityCheckResponse> {
+ let authentication_id = req.authentication_id.clone();
+ let eligibility_handler = EligibilityHandler::new(state, merchant_context, req);
+ // Run the checks in sequence, short-circuiting on the first that returns a next action
+ let sdk_next_action = eligibility_handler
+ .run_check(StoreEligibilityCheckData)
+ .await?
+ .unwrap_or(AuthenticationSdkNextAction::Proceed);
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ AuthenticationEligibilityCheckResponse {
+ authentication_id,
+ sdk_next_action,
+ },
+ ))
+}
+
+#[cfg(feature = "v1")]
+pub async fn authentication_retrieve_eligibility_check_core(
+ state: SessionState,
+ merchant_context: domain::MerchantContext,
+ req: AuthenticationRetrieveEligibilityCheckRequest,
+) -> RouterResponse<AuthenticationRetrieveEligibilityCheckResponse> {
+ let redis = &state
+ .store
+ .get_redis_conn()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+ let key = format!(
+ "{}_{}_{}",
+ consts::AUTHENTICATION_ELIGIBILITY_CHECK_DATA_KEY,
+ merchant_context
+ .get_merchant_account()
+ .get_id()
+ .get_string_repr(),
+ req.authentication_id.get_string_repr()
+ );
+ let eligibility_check_data: AuthenticationEligibilityCheckData = redis
+ .get_key::<String>(&key.as_str().into())
+ .await
+ .change_context(ApiErrorResponse::GenericNotFoundError {
+ message: format!(
+ "Eligibility check data not found for authentication id: {}",
+ req.authentication_id.get_string_repr()
+ ),
+ })
+ .attach_printable("Failed to get key from redis")?
+ .parse_struct("PaymentTokenData")
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to deserialize eligibility check data")?;
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ AuthenticationRetrieveEligibilityCheckResponse {
+ authentication_id: req.authentication_id,
+ eligibility_check_data:
+ AuthenticationEligibilityCheckResponseData::ClickToPayEnrollmentStatus(
+ ClickToPayEligibilityCheckResponseData {
+ visa: eligibility_check_data
+ .get_click_to_pay_data()
+ .and_then(|data| data.visa.clone().map(|visa| visa.consumer_present)),
+ mastercard: eligibility_check_data.get_click_to_pay_data().and_then(
+ |data| {
+ data.mastercard
+ .clone()
+ .map(|mastercard| mastercard.consumer_present)
+ },
+ ),
+ },
+ ),
+ },
+ ))
+}
+
impl
ForeignTryFrom<(
&Authentication,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 24522270b6..a530956fcd 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -3100,6 +3100,13 @@ impl Authentication {
web::resource("/{authentication_id}/authenticate")
.route(web::post().to(authentication::authentication_authenticate)),
)
+ .service(
+ web::resource("/{authentication_id}/eligibility-check")
+ .route(web::post().to(authentication::authentication_eligibility_check))
+ .route(
+ web::get().to(authentication::authentication_retrieve_eligibility_check),
+ ),
+ )
.service(
web::resource("{merchant_id}/{authentication_id}/redirect")
.route(web::post().to(authentication::authentication_sync_post_update)),
diff --git a/crates/router/src/routes/authentication.rs b/crates/router/src/routes/authentication.rs
index f0a12f3fd6..a33d1e3e05 100644
--- a/crates/router/src/routes/authentication.rs
+++ b/crates/router/src/routes/authentication.rs
@@ -2,7 +2,8 @@ use actix_web::{web, HttpRequest, Responder};
use api_models::authentication::{AuthenticationAuthenticateRequest, AuthenticationCreateRequest};
#[cfg(feature = "v1")]
use api_models::authentication::{
- AuthenticationEligibilityRequest, AuthenticationSessionTokenRequest,
+ AuthenticationEligibilityCheckRequest, AuthenticationEligibilityRequest,
+ AuthenticationRetrieveEligibilityCheckRequest, AuthenticationSessionTokenRequest,
AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest,
};
use router_env::{instrument, tracing, Flow};
@@ -129,6 +130,85 @@ pub async fn authentication_authenticate(
.await
}
+#[cfg(feature = "v1")]
+#[instrument(skip_all, fields(flow = ?Flow::AuthenticationEligibilityCheck))]
+pub async fn authentication_eligibility_check(
+ state: web::Data<app::AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<AuthenticationEligibilityCheckRequest>,
+ path: web::Path<common_utils::id_type::AuthenticationId>,
+) -> impl Responder {
+ let flow = Flow::AuthenticationEligibilityCheck;
+ let authentication_id = path.into_inner();
+ let api_auth = auth::ApiKeyAuth::default();
+ let payload = AuthenticationEligibilityCheckRequest {
+ authentication_id,
+ ..json_payload.into_inner()
+ };
+
+ let (auth, auth_flow) =
+ match auth::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,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
+ domain::Context(auth.merchant_account, auth.key_store),
+ ));
+ unified_authentication_service::authentication_eligibility_check_core(
+ state,
+ merchant_context,
+ req,
+ auth_flow,
+ )
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all, fields(flow = ?Flow::AuthenticationRetrieveEligibilityCheck))]
+pub async fn authentication_retrieve_eligibility_check(
+ state: web::Data<app::AppState>,
+ req: HttpRequest,
+ path: web::Path<common_utils::id_type::AuthenticationId>,
+) -> impl Responder {
+ let flow = Flow::AuthenticationRetrieveEligibilityCheck;
+ let authentication_id = path.into_inner();
+ let payload = AuthenticationRetrieveEligibilityCheckRequest { authentication_id };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
+ domain::Context(auth.merchant_account, auth.key_store),
+ ));
+ unified_authentication_service::authentication_retrieve_eligibility_check_core(
+ state,
+ merchant_context,
+ req,
+ )
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ }),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::AuthenticationSync))]
pub async fn authentication_sync(