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 blocklist count and lookup endpoints (#13887)

Ayush Anandcfb479e803ae
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 4dfc804873..715698ce44 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -6757,6 +6757,104 @@
]
}
},
+ "/blocklist/count": {
+ "get": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Count blocked fingerprints of a particular kind",
+ "parameters": [
+ {
+ "name": "data_kind",
+ "in": "query",
+ "description": "Kind of blocklist entries to count",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/BlocklistDataKind"
+ }
+ },
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "Restricts the count to entries belonging to this business profile, plus entries with no profile. If omitted, the merchant's default profile is used; merchants with more than one profile have no default and will receive an error asking for this header.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Blocklist entry counts",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BlocklistCountResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data, or no profile could be resolved"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/blocklist/lookup": {
+ "get": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Look up whether a value is blocked",
+ "parameters": [
+ {
+ "name": "data",
+ "in": "query",
+ "description": "The raw value to check against the blocklist, e.g. a card BIN",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "Restricts the lookup to entries belonging to this business profile, plus entries with no profile. If omitted, the merchant's default profile is used; merchants with more than one profile have no default and will receive an error asking for this header.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Blocklist lookup result",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BlocklistLookupResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data, or no profile could be resolved"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/blocklist/batch": {
"post": {
"tags": [
@@ -15461,6 +15559,43 @@
"blocked_issuer"
]
},
+ "BlocklistCountQuery": {
+ "type": "object",
+ "required": [
+ "data_kind"
+ ],
+ "properties": {
+ "data_kind": {
+ "$ref": "#/components/schemas/BlocklistDataKind"
+ }
+ }
+ },
+ "BlocklistCountResponse": {
+ "type": "object",
+ "required": [
+ "data_kind",
+ "total_count"
+ ],
+ "properties": {
+ "data_kind": {
+ "$ref": "#/components/schemas/BlocklistDataKind"
+ },
+ "total_count": {
+ "type": "integer",
+ "description": "The total number of blocked entries for the given data_kind",
+ "minimum": 0
+ },
+ "counts_by_length": {
+ "type": "object",
+ "description": "The number of blocked entries for each BIN length, keyed by the BIN length.\n\nFor `generic_card_bin`, this also includes entries blocked as `card_bin` or\n`extended_card_bin`. Omitted for `payment_method`, since fingerprints have a fixed length.",
+ "additionalProperties": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "nullable": true
+ }
+ }
+ },
"BlocklistDataKind": {
"type": "string",
"description": "`card_bin` (6 digits) and `extended_card_bin` (8 digits) are deprecated, use\n`generic_card_bin`, which accepts 6 to 10 digits.",
@@ -15471,6 +15606,35 @@
"generic_card_bin"
]
},
+ "BlocklistLookupQuery": {
+ "type": "object",
+ "required": [
+ "data"
+ ],
+ "properties": {
+ "data": {
+ "type": "string",
+ "description": "The raw value to check against the blocklist, e.g. a card BIN. Limited to 20 characters,\nthe longest value a `fingerprint_id` can hold.",
+ "maxLength": 20
+ }
+ }
+ },
+ "BlocklistLookupResponse": {
+ "type": "object",
+ "required": [
+ "data",
+ "blocked"
+ ],
+ "properties": {
+ "data": {
+ "type": "string"
+ },
+ "blocked": {
+ "type": "boolean",
+ "description": "Whether an entry matching `data` exists in the blocklist, under any data_kind"
+ }
+ }
+ },
"BlocklistRequest": {
"oneOf": [
{
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs
index a355d18c0a..0f59183b63 100644
--- a/crates/api_models/src/blocklist.rs
+++ b/crates/api_models/src/blocklist.rs
@@ -1,3 +1,5 @@
+use std::collections::BTreeMap;
+
use common_enums::enums;
use common_utils::events::ApiEventMetric;
use hyperswitch_masking::StrongSecret;
@@ -87,6 +89,46 @@ pub struct ToggleBlocklistQuery {
pub status: bool,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistCountQuery {
+ #[schema(value_type = BlocklistDataKind)]
+ pub data_kind: enums::BlocklistDataKind,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistCountResponse {
+ #[schema(value_type = BlocklistDataKind)]
+ pub data_kind: enums::BlocklistDataKind,
+ /// The total number of blocked entries for the given data_kind
+ pub total_count: usize,
+ /// The number of blocked entries for each BIN length, keyed by the BIN length.
+ ///
+ /// For `generic_card_bin`, this also includes entries blocked as `card_bin` or
+ /// `extended_card_bin`. Omitted for `payment_method`, since fingerprints have a fixed length.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub counts_by_length: Option<BTreeMap<usize, usize>>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistLookupQuery {
+ /// The raw value to check against the blocklist, e.g. a card BIN. Limited to 20 characters,
+ /// the longest value a `fingerprint_id` can hold.
+ #[schema(value_type = String, max_length = 20)]
+ pub data: common_utils::types::BlocklistLookupData,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistLookupResponse {
+ pub data: String,
+ /// Whether an entry matching `data` exists in the blocklist, under any data_kind
+ pub blocked: bool,
+}
+
+impl ApiEventMetric for BlocklistCountQuery {}
+impl ApiEventMetric for BlocklistCountResponse {}
+impl ApiEventMetric for BlocklistLookupQuery {}
+impl ApiEventMetric for BlocklistLookupResponse {}
+
impl ApiEventMetric for BlocklistRequest {}
impl ApiEventMetric for BlocklistResponse {}
impl ApiEventMetric for ListBlocklistResponse {}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 657d8449df..9703f2621f 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -174,6 +174,11 @@ pub const MAX_DESCRIPTION_LENGTH: u16 = 255;
/// Max length allowed for Statement Descriptor
pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22;
+
+/// Max length allowed for a blocklist lookup value. Matches the longest value `fingerprint_id` can
+/// legitimately hold: a card BIN is at most 10 digits and a locker fingerprint id is a 20-character
+/// nano id. The column itself is `VARCHAR(64)`, so anything longer could never match a row.
+pub const MAX_BLOCKLIST_LOOKUP_DATA_LENGTH: u16 = 20;
/// Payout flow identifier used for performing GSM operations
pub const PAYOUT_FLOW_STR: &str = "payout_flow";
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index f83f86e65d..b5c4070a88 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -49,7 +49,8 @@ use utoipa::ToSchema;
use crate::{
consts::{
- self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH,
+ self, MAX_BLOCKLIST_LOOKUP_DATA_LENGTH, MAX_DESCRIPTION_LENGTH,
+ MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH,
},
errors::{CustomResult, ParsingError, PercentageError, ValidationError},
fp_utils::when,
@@ -1021,6 +1022,20 @@ impl Description {
#[diesel(sql_type = sql_types::Text)]
pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>);
+/// Domain type for a blocklist lookup value - a card BIN or a locker fingerprint id.
+///
+/// Length is enforced on deserialization, so a value too long to ever match a `fingerprint_id` is
+/// rejected at the API boundary rather than reaching a query.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
+pub struct BlocklistLookupData(LengthString<MAX_BLOCKLIST_LOOKUP_DATA_LENGTH, 1>);
+
+impl BlocklistLookupData {
+ /// Get the string representation of the lookup value
+ pub fn get_string_repr(&self) -> &str {
+ &self.0 .0
+ }
+}
+
impl<DB> Queryable<sql_types::Text, DB> for Description
where
DB: Backend,
diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs
index 3d906a9f02..ab8edefc42 100644
--- a/crates/diesel_models/src/query/blocklist.rs
+++ b/crates/diesel_models/src/query/blocklist.rs
@@ -1,5 +1,11 @@
use async_bb8_diesel::AsyncRunQueryDsl;
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use diesel::{
+ associations::HasTable,
+ dsl::{count_star, sql},
+ expression::SqlLiteral,
+ sql_types::Integer,
+ BoolExpressionMethods, ExpressionMethods, QueryDsl,
+};
use error_stack::ResultExt;
use super::generics;
@@ -10,6 +16,18 @@ use crate::{
DatabaseConnectionWithContext, StorageResult,
};
+/// Postgres `length(fingerprint_id)`, used to bucket blocklist entries by digit-string length for
+/// `/blocklist/count`'s `counts_by_length` without fetching every row into the app.
+///
+/// Written as raw SQL rather than `define_sql_function!` because diesel cannot prove a function-call
+/// expression is valid in its own `GROUP BY`: the generated `pg_length<T>: ValidGrouping<GB>`
+/// delegates to `T: ValidGrouping<GB>`, and a bare column is only valid when
+/// `GB: IsContainedInGroupBy<column>`, which nothing implements for `pg_length<fingerprint_id>`.
+/// `SqlLiteral` sidesteps this with a blanket `impl<ST, T, GB> ValidGrouping<GB>`.
+fn fingerprint_length() -> SqlLiteral<Integer> {
+ sql::<Integer>("length(fingerprint_id)")
+}
+
/// The generic kind also matches the deprecated fixed-width kinds, so rows written before
/// `generic_card_bin` existed stay visible.
fn equivalent_data_kinds(
@@ -248,6 +266,42 @@ impl Blocklist {
.await
}
+ pub async fn count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ conn: &DatabaseConnectionWithContext<'_>,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ data_kind: common_enums::BlocklistDataKind,
+ ) -> StorageResult<Vec<(i32, i64)>> {
+ let data_kinds = equivalent_data_kinds(data_kind);
+ let query = <Self as HasTable>::table()
+ .filter(
+ dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .or(dsl::processor_merchant_id
+ .is_null()
+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))
+ .and(dsl::data_kind.eq_any(data_kinds))
+ .and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ )
+ .group_by(fingerprint_length())
+ .select((fingerprint_length(), count_star()));
+
+ generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
+ conn.request_id(),
+ conn.event_emitter(),
+ generics::db_metrics::DatabaseOperation::Count,
+ query.get_results_async(conn.raw_connection()),
+ )
+ .await
+ .map_err(|e| error_stack::report!(e))
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Failed to count blocklist entries by fingerprint length")
+ }
+
pub async fn list_by_processor_merchant_id(
conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7bda18b097..48036d8ebb 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -203,6 +203,8 @@ Never share your secret api keys. Keep them guarded and secure.
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
+ routes::blocklist::get_blocklist_count,
+ routes::blocklist::lookup_blocklist_entry,
routes::blocklist::upload_batch_blocklist,
routes::blocklist::get_batch_blocklist_job_status,
routes::blocklist::list_batch_blocklist_jobs,
@@ -1019,6 +1021,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
+ api_models::blocklist::BlocklistCountQuery,
+ api_models::blocklist::BlocklistCountResponse,
+ api_models::blocklist::BlocklistLookupQuery,
+ api_models::blocklist::BlocklistLookupResponse,
api_models::blocklist::BatchBlocklistUploadResponse,
api_models::blocklist::BatchBlocklistJobStatusResponse,
api_models::blocklist::ListBatchBlocklistJobsResponse,
diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rs
index 71427ca8fe..95db744c40 100644
--- a/crates/openapi/src/routes/blocklist.rs
+++ b/crates/openapi/src/routes/blocklist.rs
@@ -1,3 +1,43 @@
+#[utoipa::path(
+ get,
+ path = "/blocklist/count",
+ params (
+ ("data_kind" = BlocklistDataKind, Query, description = "Kind of blocklist entries to count"),
+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the count to entries \
+ belonging to this business profile, plus entries with no profile. If omitted, the \
+ merchant's default profile is used; merchants with more than one profile have no default \
+ and will receive an error asking for this header."),
+ ),
+ responses(
+ (status = 200, description = "Blocklist entry counts", body = BlocklistCountResponse),
+ (status = 400, description = "Invalid Data, or no profile could be resolved")
+ ),
+ tag = "Blocklist",
+ operation_id = "Count blocked fingerprints of a particular kind",
+ security(("api_key" = []))
+)]
+pub async fn get_blocklist_count() {}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/lookup",
+ params (
+ ("data" = String, Query, description = "The raw value to check against the blocklist, e.g. a card BIN"),
+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the lookup to entries \
+ belonging to this business profile, plus entries with no profile. If omitted, the \
+ merchant's default profile is used; merchants with more than one profile have no default \
+ and will receive an error asking for this header."),
+ ),
+ responses(
+ (status = 200, description = "Blocklist lookup result", body = BlocklistLookupResponse),
+ (status = 400, description = "Invalid Data, or no profile could be resolved")
+ ),
+ tag = "Blocklist",
+ operation_id = "Look up whether a value is blocked",
+ security(("api_key" = []))
+)]
+pub async fn lookup_blocklist_entry() {}
+
#[utoipa::path(
post,
path = "/blocklist/toggle",
diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs
index fd22073eeb..27d5aea08b 100644
--- a/crates/router/src/core/blocklist.rs
+++ b/crates/router/src/core/blocklist.rs
@@ -49,6 +49,28 @@ pub async fn list_blocklist_entries(
.map(services::ApplicationResponse::Json)
}
+pub async fn get_blocklist_count(
+ state: SessionState,
+ processor: domain::Processor,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ query: api_blocklist::BlocklistCountQuery,
+) -> RouterResponse<api_blocklist::BlocklistCountResponse> {
+ utils::get_blocklist_count(&state, &processor, profile_id, query)
+ .await
+ .map(services::ApplicationResponse::Json)
+}
+
+pub async fn lookup_blocklist_entry(
+ state: SessionState,
+ processor: domain::Processor,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ query: api_blocklist::BlocklistLookupQuery,
+) -> RouterResponse<api_blocklist::BlocklistLookupResponse> {
+ utils::lookup_blocklist_entry(&state, &processor, profile_id, query)
+ .await
+ .map(services::ApplicationResponse::Json)
+}
+
pub async fn toggle_blocklist_guard(
state: SessionState,
processor: domain::Processor,
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 879fab82c1..4674c6f206 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -178,6 +178,124 @@ pub(super) fn validate_bin(
})
}
+pub async fn get_blocklist_count(
+ state: &SessionState,
+ processor: &domain::Processor,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ query: api_blocklist::BlocklistCountQuery,
+) -> RouterResult<api_blocklist::BlocklistCountResponse> {
+ let processor_merchant_id = processor.get_account().get_id();
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ None,
+ None,
+ processor,
+ profile_id.as_ref(),
+ &*state.store,
+ true,
+ )
+ .await?;
+
+ let (total_count, counts_by_length) = match query.data_kind {
+ // Fingerprints are fixed-width hashes, so there is no breakdown worth grouping for.
+ common_enums::BlocklistDataKind::PaymentMethod => {
+ let total_count = state
+ .store
+ .get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(
+ processor_merchant_id,
+ Some(&profile_id),
+ query.data_kind,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to count blocklist entries")?;
+
+ (total_count, None)
+ }
+
+ common_enums::BlocklistDataKind::CardBin
+ | common_enums::BlocklistDataKind::ExtendedCardBin
+ | common_enums::BlocklistDataKind::GenericCardBin => {
+ let length_counts = state
+ .store
+ .count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ processor_merchant_id,
+ &profile_id,
+ query.data_kind,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to count blocklist entries by fingerprint length")?;
+
+ let counts_by_length = length_counts
+ .into_iter()
+ .map(|(length, count)| {
+ let length = usize::try_from(length)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "fingerprint length returned by the database did not fit in usize",
+ )?;
+ let count = usize::try_from(count)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "blocklist entry count returned by the database did not fit in usize",
+ )?;
+ Ok((length, count))
+ })
+ .collect::<RouterResult<std::collections::BTreeMap<_, _>>>()?;
+
+ (counts_by_length.values().sum(), Some(counts_by_length))
+ }
+ };
+
+ Ok(api_blocklist::BlocklistCountResponse {
+ data_kind: query.data_kind,
+ total_count,
+ counts_by_length,
+ })
+}
+
+pub async fn lookup_blocklist_entry(
+ state: &SessionState,
+ processor: &domain::Processor,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+ query: api_blocklist::BlocklistLookupQuery,
+) -> RouterResult<api_blocklist::BlocklistLookupResponse> {
+ let processor_merchant_id = processor.get_account().get_id();
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ None,
+ None,
+ processor,
+ profile_id.as_ref(),
+ &*state.store,
+ true,
+ )
+ .await?;
+
+ let result = state
+ .store
+ .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(
+ processor_merchant_id,
+ &profile_id,
+ query.data.get_string_repr(),
+ )
+ .await;
+
+ let blocked = match result {
+ Ok(_) => true,
+ Err(error) if error.current_context().is_db_not_found() => false,
+ Err(error) => {
+ return Err(error
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to look up blocklist entry"));
+ }
+ };
+
+ Ok(api_blocklist::BlocklistLookupResponse {
+ data: query.data.get_string_repr().to_string(),
+ blocked,
+ })
+}
+
pub async fn insert_entry_into_blocklist(
state: &SessionState,
platform: &domain::Platform,
diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs
index a843310a7f..cdccaf0258 100644
--- a/crates/router/src/db/blocklist.rs
+++ b/crates/router/src/db/blocklist.rs
@@ -70,6 +70,15 @@ pub trait BlocklistInterface {
data_kind: common_enums::BlocklistDataKind,
) -> CustomResult<usize, errors::StorageError>;
+ /// Counts blocklist entries grouped by fingerprint length, computed via a SQL `GROUP BY`
+ /// rather than fetching every row - backs `/blocklist/count`'s `counts_by_length`.
+ async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ data_kind: common_enums::BlocklistDataKind,
+ ) -> CustomResult<Vec<(i32, i64)>, errors::StorageError>;
+
async fn list_blocklist_entries_by_processor_merchant_id(
&self,
processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -401,6 +410,26 @@ impl BlocklistInterface for Store {
)))
}
+ #[instrument(skip_all)]
+ async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ data_kind: common_enums::BlocklistDataKind,
+ ) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Blocklist::count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ &conn,
+ processor_merchant_id,
+ profile_id,
+ data_kind,
+ )
+ .await
+ .change_context(errors::StorageError::DatabaseError(report!(
+ diesel_models::errors::DatabaseError::Others
+ )))
+ }
+
#[instrument(skip_all)]
async fn bulk_insert_blocklist_entries(
&self,
@@ -511,6 +540,15 @@ impl BlocklistInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
+ async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ &self,
+ _processor_merchant_id: &common_utils::id_type::MerchantId,
+ _profile_id: &common_utils::id_type::ProfileId,
+ _data_kind: common_enums::BlocklistDataKind,
+ ) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
+
async fn bulk_insert_blocklist_entries(
&self,
entries: Vec<storage::BlocklistNew>,
@@ -695,6 +733,22 @@ impl BlocklistInterface for KafkaStore {
.await
}
+ #[instrument(skip_all)]
+ async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ data_kind: common_enums::BlocklistDataKind,
+ ) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {
+ self.diesel_store
+ .count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(
+ processor_merchant_id,
+ profile_id,
+ data_kind,
+ )
+ .await
+ }
+
#[instrument(skip_all)]
async fn list_blocklist_entries_by_processor_merchant_id(
&self,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index e9c948e35a..48b5070b59 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1970,6 +1970,10 @@ impl Blocklist {
.service(
web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)),
)
+ .service(web::resource("/count").route(web::get().to(blocklist::get_blocklist_count)))
+ .service(
+ web::resource("/lookup").route(web::get().to(blocklist::lookup_blocklist_entry)),
+ )
.service(
web::resource("/batch")
.route(web::post().to(blocklist::upload_batch_blocklist))
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index d05ca62b5a..9d6854641b 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -187,6 +187,116 @@ pub async fn list_blocked_payment_methods(
.await
}
+#[utoipa::path(
+ get,
+ path = "/blocklist/count",
+ params (
+ ("data_kind" = BlocklistDataKind, Query, description = "Kind of blocklist entries to count"),
+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the count to entries \
+ belonging to this business profile, plus entries with no profile. If omitted, the \
+ merchant's default profile is used; merchants with more than one profile have no default \
+ and will receive an error asking for this header."),
+ ),
+ responses(
+ (status = 200, description = "Blocklist entry counts", body = BlocklistCountResponse),
+ (status = 400, description = "Invalid Data, or no profile could be resolved")
+ ),
+ tag = "Blocklist",
+ operation_id = "Count blocked fingerprints of a particular kind",
+ security(("api_key" = []))
+)]
+pub async fn get_blocklist_count(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_payload: web::Query<api_blocklist::BlocklistCountQuery>,
+) -> HttpResponse {
+ let flow = Flow::GetBlocklistCount;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_payload.into_inner(),
+ |state, auth: auth::AuthenticationData, query, _| {
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ blocklist::get_blocklist_count(
+ state,
+ auth.platform.get_processor().clone(),
+ profile_id,
+ query,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: true,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ allow_connected: true,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/lookup",
+ params (
+ ("data" = String, Query, description = "The raw value to check against the blocklist, e.g. a card BIN"),
+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the lookup to entries \
+ belonging to this business profile, plus entries with no profile. If omitted, the \
+ merchant's default profile is used; merchants with more than one profile have no default \
+ and will receive an error asking for this header."),
+ ),
+ responses(
+ (status = 200, description = "Blocklist lookup result", body = BlocklistLookupResponse),
+ (status = 400, description = "Invalid Data, or no profile could be resolved")
+ ),
+ tag = "Blocklist",
+ operation_id = "Look up whether a value is blocked",
+ security(("api_key" = []))
+)]
+pub async fn lookup_blocklist_entry(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_payload: web::Query<api_blocklist::BlocklistLookupQuery>,
+) -> HttpResponse {
+ let flow = Flow::LookupBlocklistEntry;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_payload.into_inner(),
+ |state, auth: auth::AuthenticationData, query, _| {
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ blocklist::lookup_blocklist_entry(
+ state,
+ auth.platform.get_processor().clone(),
+ profile_id,
+ query,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: true,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ allow_connected: true,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[utoipa::path(
post,
path = "/blocklist/toggle",
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index a6608d9c5c..48a46d8b9d 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -112,6 +112,8 @@ impl From<Flow> for ApiIdentifier {
Flow::BatchBlocklistUpload => Self::Blocklist,
Flow::GetBatchBlocklistJobStatus => Self::Blocklist,
Flow::ListBatchBlocklistJobs => Self::Blocklist,
+ Flow::GetBlocklistCount => Self::Blocklist,
+ Flow::LookupBlocklistEntry => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 6438497c5c..a6b6c8ca15 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -343,6 +343,10 @@ pub enum Flow {
GetBatchBlocklistJobStatus,
/// List batch blocklist upload jobs for a merchant
ListBatchBlocklistJobs,
+ /// Get blocklist entry counts, broken down by fingerprint length
+ GetBlocklistCount,
+ /// Look up whether a value is present in the blocklist
+ LookupBlocklistEntry,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive