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(blocklist): scope blocklist entries to the business profile (#13774)
Ayush Anandf140e97df485
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex f7b59bf57b..ab6e6ebeee 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -6576,6 +6576,18 @@"Blocklist"],"operationId": "Unblock a Fingerprint",+ "parameters": [+ {+ "name": "X-Profile-Id",+ "in": "header",+ "description": "The business profile to unblock this entry from. Only entries belonging to that profile, or entries with no profile, are removed - an entry blocked under a different profile is not affected and the request returns 404. Resolution follows the same rules as blocking.",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true+ }+ }+ ],"requestBody": {"content": {"application/json": {@@ -6598,7 +6610,10 @@}},"400": {- "description": "Invalid Data"+ "description": "Invalid Data, or no profile could be resolved"+ },+ "404": {+ "description": "No entry for this fingerprint under the resolved profile"}},"security": [@@ -6621,6 +6636,16 @@"schema": {"$ref": "#/components/schemas/BlocklistDataKind"}+ },+ {+ "name": "X-Profile-Id",+ "in": "header",+ "description": "Restricts the listing to entries belonging to this business profile, plus entries with no profile. When no profile can be resolved - as with publishable-key authentication - all of the merchant's entries are returned, as before.",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true+ }}],"responses": {@@ -6649,6 +6674,18 @@"Blocklist"],"operationId": "Block a Fingerprint",+ "parameters": [+ {+ "name": "X-Profile-Id",+ "in": "header",+ "description": "The business profile to block this entry under. Ignored when authenticating with a JWT, which carries its own 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+ }+ }+ ],"requestBody": {"content": {"application/json": {@@ -6671,7 +6708,7 @@}},"400": {- "description": "Invalid Data"+ "description": "Invalid Data, or no profile could be resolved"}},"security": [@@ -6726,6 +6763,18 @@"Blocklist"],"operationId": "Upload a batch blocklist CSV",+ "parameters": [+ {+ "name": "X-Profile-Id",+ "in": "header",+ "description": "The business profile every entry in this upload is blocked under. Resolution follows the same rules as blocking a single entry.",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true+ }+ }+ ],"requestBody": {"description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). The CSV must have a header row: `type,data,metadata`. `type`: one of `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). Maximum 100,000 data rows.","content": {@@ -6749,7 +6798,7 @@}},"400": {- "description": "CSV validation error or file exceeds 5 MiB limit"+ "description": "CSV validation error, file exceeds 5 MiB limit, or no profile could be resolved"}},"security": [@@ -14992,6 +15041,11 @@"created_at": {"type": "string","format": "date-time"+ },+ "profile_id": {+ "type": "string",+ "example": "pro_abcdefghijklmnop",+ "nullable": true}}},diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex a68995fce8..f7daa45176 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -9677,6 +9677,11 @@"created_at": {"type": "string","format": "date-time"+ },+ "profile_id": {+ "type": "string",+ "example": "pro_abcdefghijklmnop",+ "nullable": true}}},diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rsindex 75bb5bb36a..5da7bf1da8 100644--- a/crates/api_models/src/blocklist.rs+++ b/crates/api_models/src/blocklist.rs@@ -33,6 +33,8 @@ pub struct BlocklistResponse {pub data_kind: enums::BlocklistDataKind,#[serde(with = "common_utils::custom_serde::iso8601")]pub created_at: time::PrimitiveDateTime,+ #[schema(value_type = Option<String>, example = "pro_abcdefghijklmnop")]+ pub profile_id: Option<common_utils::id_type::ProfileId>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]diff --git a/crates/diesel_models/drop_id.patch b/crates/diesel_models/drop_id.patchindex 657db97ae4..c2cedabb3f 100644--- a/crates/diesel_models/drop_id.patch+++ b/crates/diesel_models/drop_id.patch@@ -2,7 +2,7 @@ diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schemindex b35e809a0..749a5dd47 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs-@@ -142,14 +142,13 @@ diesel::table! {+@@ -142,14 +142,34 @@ diesel::table! {}diesel::table! {@@ -11,6 +11,27 @@ index b35e809a0..749a5dd47 100644- blocklist_fingerprint (id) {- id -> Int4,++ blocklist (merchant_id, fingerprint_id) {++ #[max_length = 64]++ merchant_id -> Varchar,++ #[max_length = 64]++ fingerprint_id -> Varchar,++ data_kind -> BlocklistDataKind,++ metadata -> Nullable<Jsonb>,++ created_at -> Timestamp,++ #[max_length = 64]++ processor_merchant_id -> Nullable<Varchar>,++ #[max_length = 255]++ created_by -> Nullable<Varchar>,++ #[max_length = 64]++ profile_id -> Nullable<Varchar>,++ }++}++++diesel::table! {++ use diesel::sql_types::*;++ use crate::enums::diesel_exports::*;+++ blocklist_fingerprint (merchant_id, fingerprint_id) {#[max_length = 64]merchant_id -> Varchar,@@ -18,7 +39,7 @@ index b35e809a0..749a5dd47 100644fingerprint_id -> Varchar,data_kind -> BlocklistDataKind,encrypted_fingerprint -> Text,-@@ -158,14 +157,13 @@ diesel::table! {+@@ -158,14 +178,13 @@ diesel::table! {}diesel::table! {@@ -34,7 +55,7 @@ index b35e809a0..749a5dd47 100644}}-@@ -300,13 +298,12 @@ diesel::table! {+@@ -300,13 +319,12 @@ diesel::table! {diesel::table! {use diesel::sql_types::*;@@ -48,7 +69,7 @@ index b35e809a0..749a5dd47 100644}}-@@ -615,14 +612,13 @@ diesel::table! {+@@ -615,14 +633,13 @@ diesel::table! {}diesel::table! {@@ -64,3 +85,11 @@ index b35e809a0..749a5dd47 100644external_id -> Varchar,#[max_length = 255]card_fingerprint -> Varchar,+@@ -1982,6 +1999,7 @@+ api_keys,+ authentication,+ batch_blocklist_jobs,++ blocklist,+ blocklist_fingerprint,+ blocklist_lookup,+ business_profile,diff --git a/crates/diesel_models/src/batch_blocklist_job.rs b/crates/diesel_models/src/batch_blocklist_job.rsindex bff5f25968..f2354418ab 100644--- a/crates/diesel_models/src/batch_blocklist_job.rs+++ b/crates/diesel_models/src/batch_blocklist_job.rs@@ -6,8 +6,6 @@ use time::PrimitiveDateTime;use crate::schema::batch_blocklist_jobs;-// `profile_id` is read-only for now: the column exists and is selected, but-// nothing writes or filters on it until the profile-scoping change lands.#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)]#[diesel(table_name = batch_blocklist_jobs, primary_key(id), check_for_backend(diesel::pg::Pg))]pub struct BatchBlocklistJob {@@ -33,6 +31,7 @@ pub struct BatchBlocklistJobNew {pub failed_rows: i32,pub created_at: PrimitiveDateTime,pub updated_at: PrimitiveDateTime,+ pub profile_id: id_type::ProfileId,}#[derive(Clone, Debug, AsChangeset)]diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rsindex bff2d0139e..e9bde1a382 100644--- a/crates/diesel_models/src/blocklist.rs+++ b/crates/diesel_models/src/blocklist.rs@@ -13,10 +13,9 @@ pub struct BlocklistNew {pub created_at: time::PrimitiveDateTime,pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<String>,+ pub profile_id: Option<common_utils::id_type::ProfileId>,}-// `profile_id` is read-only for now: the column exists and is selected, but-// nothing writes or filters on it until the profile-scoping change lands.#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize,)]diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rsindex 9db63dca89..1bacb5a2c8 100644--- a/crates/diesel_models/src/query/blocklist.rs+++ b/crates/diesel_models/src/query/blocklist.rs@@ -21,7 +21,11 @@ impl BlocklistNew {) -> StorageResult<usize> {let query = diesel::insert_into(<Blocklist as HasTable>::table()).values(entries)- .on_conflict((dsl::processor_merchant_id, dsl::fingerprint_id))+ .on_conflict((+ dsl::processor_merchant_id,+ dsl::profile_id,+ dsl::fingerprint_id,+ )).do_nothing();generics::db_metrics::track_database_call::<<Blocklist as HasTable>::Table, _, _>(@@ -50,6 +54,28 @@ impl Blocklist {.await}+ // Rows written before profile scoping have a NULL profile_id and block the whole merchant,+ // so they must keep matching every profile.+ pub async fn find_by_processor_merchant_id_profile_id_fingerprint_id(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ )+ .await+ }+// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULLpub async fn find_by_merchant_id_fingerprint_id(conn: &PgPooledConn,@@ -65,6 +91,26 @@ impl Blocklist {.await}+ pub async fn find_by_merchant_id_profile_id_fingerprint_id(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ )+ .await+ }+pub async fn list_by_processor_merchant_id_data_kind(conn: &PgPooledConn,processor_merchant_id: &common_utils::id_type::MerchantId,@@ -87,6 +133,34 @@ impl Blocklist {.await}+ pub async fn list_by_processor_merchant_id_profile_id_data_kind(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ 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(data_kind.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ Some(limit),+ Some(offset),+ Some(dsl::created_at.desc()),+ )+ .await+ }+pub async fn get_count_by_processor_merchant_id_data_kind(conn: &PgPooledConn,processor_merchant_id: &common_utils::id_type::MerchantId,@@ -104,6 +178,29 @@ impl Blocklist {.await}+ pub async fn get_count_by_processor_merchant_id_profile_id_data_kind(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<usize> {+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ 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(data_kind.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ )+ .await+ }+pub async fn list_by_processor_merchant_id(conn: &PgPooledConn,processor_merchant_id: &common_utils::id_type::MerchantId,@@ -136,6 +233,26 @@ impl Blocklist {.await}+ pub async fn delete_by_processor_merchant_id_profile_id_fingerprint_id(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ )+ .await+ }+// Fallback function for stagger release - deletes by merchant_id when processor_merchant_id is NULLpub async fn delete_by_merchant_id_fingerprint_id(conn: &PgPooledConn,@@ -150,4 +267,24 @@ impl Blocklist {).await}++ pub async fn delete_by_merchant_id_profile_id_fingerprint_id(+ conn: &PgPooledConn,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ )+ .await+ }}diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rsindex 303f3c36e0..0493ea3ff9 100644--- a/crates/diesel_models/src/query/utils.rs+++ b/crates/diesel_models/src/query/utils.rs@@ -62,12 +62,6 @@ mod composite_key {self.0}}- impl CompositeKey for <schema_v2::blocklist::table as diesel::Table>::PrimaryKey {- type UK = schema_v2::blocklist::dsl::fingerprint_id;- fn get_local_unique_key(&self) -> Self::UK {- self.1- }- }impl CompositeKey for <schema::payout_attempt::table as diesel::Table>::PrimaryKey {type UK = schema::payout_attempt::dsl::payout_attempt_id;fn get_local_unique_key(&self) -> Self::UK {@@ -161,7 +155,6 @@ impl_get_primary_key_for_composite!(schema::incremental_authorization::table,schema::hyperswitch_ai_interaction::table,schema_v2::incremental_authorization::table,- schema_v2::blocklist::table,schema::payout_attempt::table,schema::payouts::table);diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex ebe1a7eb46..b8a32633b0 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -207,27 +207,6 @@ diesel::table! {}}-diesel::table! {- use diesel::sql_types::*;- use crate::enums::diesel_exports::*;-- blocklist (merchant_id, fingerprint_id) {- #[max_length = 64]- merchant_id -> Varchar,- #[max_length = 64]- fingerprint_id -> Varchar,- data_kind -> BlocklistDataKind,- metadata -> Nullable<Jsonb>,- created_at -> Timestamp,- #[max_length = 64]- processor_merchant_id -> Nullable<Varchar>,- #[max_length = 255]- created_by -> Nullable<Varchar>,- #[max_length = 64]- profile_id -> Nullable<Varchar>,- }-}-diesel::table! {use diesel::sql_types::*;use crate::enums::diesel_exports::*;@@ -1955,7 +1934,6 @@ diesel::allow_tables_to_appear_in_same_query!(api_keys,authentication,batch_blocklist_jobs,- blocklist,blocklist_fingerprint,blocklist_lookup,business_profile,diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rsindex b71b3d865a..6526e95198 100644--- a/crates/openapi/src/routes/blocklist.rs+++ b/crates/openapi/src/routes/blocklist.rs@@ -18,9 +18,15 @@ pub async fn toggle_blocklist_guard() {}post,path = "/blocklist",request_body = BlocklistRequest,+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile to block this \+ entry under. Ignored when authenticating with a JWT, which carries its own 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 = "Fingerprint Blocked", body = BlocklistResponse),- (status = 400, description = "Invalid Data")+ (status = 400, description = "Invalid Data, or no profile could be resolved")),tag = "Blocklist",operation_id = "Block a Fingerprint",@@ -32,9 +38,16 @@ pub async fn add_entry_to_blocklist() {}delete,path = "/blocklist",request_body = BlocklistRequest,+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile to unblock \+ this entry from. Only entries belonging to that profile, or entries with no profile, are \+ removed - an entry blocked under a different profile is not affected and the request \+ returns 404. Resolution follows the same rules as blocking."),+ ),responses((status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),- (status = 400, description = "Invalid Data")+ (status = 400, description = "Invalid Data, or no profile could be resolved"),+ (status = 404, description = "No entry for this fingerprint under the resolved profile")),tag = "Blocklist",operation_id = "Unblock a Fingerprint",@@ -47,6 +60,10 @@ pub async fn remove_entry_from_blocklist() {}path = "/blocklist",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to entries \+ belonging to this business profile, plus entries with no profile. When no profile can be \+ resolved - as with publishable-key authentication - all of the merchant's entries are \+ returned, as before."),),responses((status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),@@ -70,9 +87,14 @@ pub async fn list_blocked_payment_methods() {}`metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \Maximum 100,000 data rows.",),+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile every entry \+ in this upload is blocked under. Resolution follows the same rules as blocking a single \+ entry."),+ ),responses((status = 202, description = "Batch blocklist job initiated", body = BatchBlocklistUploadResponse),- (status = 400, description = "CSV validation error or file exceeds 5 MiB limit"),+ (status = 400, description = "CSV validation error, file exceeds 5 MiB limit, or no profile could be resolved"),),tag = "Blocklist",operation_id = "Upload a batch blocklist CSV",diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rsindex 25738e7264..fd22073eeb 100644--- a/crates/router/src/core/blocklist.rs+++ b/crates/router/src/core/blocklist.rs@@ -14,9 +14,10 @@ use crate::{pub async fn add_entry_to_blocklist(state: SessionState,platform: domain::Platform,+ profile_id: Option<common_utils::id_type::ProfileId>,body: api_blocklist::AddToBlocklistRequest,) -> RouterResponse<api_blocklist::AddToBlocklistResponse> {- utils::insert_entry_into_blocklist(&state, &platform, body)+ utils::insert_entry_into_blocklist(&state, &platform, profile_id, body).await.map(services::ApplicationResponse::Json)}@@ -24,9 +25,10 @@ pub async fn add_entry_to_blocklist(pub async fn remove_entry_from_blocklist(state: SessionState,processor: domain::Processor,+ profile_id: Option<common_utils::id_type::ProfileId>,body: api_blocklist::DeleteFromBlocklistRequest,) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> {- utils::delete_entry_from_blocklist(&state, processor.get_account().get_id(), body)+ utils::delete_entry_from_blocklist(&state, &processor, profile_id, body).await.map(services::ApplicationResponse::Json)}@@ -34,11 +36,17 @@ pub async fn remove_entry_from_blocklist(pub async fn list_blocklist_entries(state: SessionState,processor: domain::Processor,+ profile_id: Option<common_utils::id_type::ProfileId>,query: api_blocklist::ListBlocklistQuery,) -> RouterResponse<api_blocklist::ListBlocklistResponse> {- utils::list_blocklist_entries_for_merchant(&state, processor.get_account().get_id(), query)- .await- .map(services::ApplicationResponse::Json)+ utils::list_blocklist_entries_for_merchant(+ &state,+ processor.get_account().get_id(),+ profile_id.as_ref(),+ query,+ )+ .await+ .map(services::ApplicationResponse::Json)}pub async fn toggle_blocklist_guard(@@ -54,9 +62,10 @@ pub async fn toggle_blocklist_guard(pub async fn upload_batch_blocklist(state: SessionState,platform: domain::Platform,+ profile_id: Option<common_utils::id_type::ProfileId>,csv_bytes: bytes::Bytes,) -> RouterResponse<api_blocklist::BatchBlocklistUploadResponse> {- batch::initiate_batch_blocklist_upload(&state, &platform, csv_bytes)+ batch::initiate_batch_blocklist_upload(&state, &platform, profile_id, csv_bytes).await.map(services::ApplicationResponse::Json)}diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rsindex 212905ba98..6cca6f6920 100644--- a/crates/router/src/core/blocklist/batch.rs+++ b/crates/router/src/core/blocklist/batch.rs@@ -9,7 +9,10 @@ use scheduler::utils as pt_utils;use serde::Deserialize;use crate::{- core::errors::{self, RouterResult, StorageErrorExt},+ core::{+ errors::{self, RouterResult, StorageErrorExt},+ utils as core_utils,+ },logger,routes::SessionState,types::{domain, storage},@@ -305,9 +308,19 @@ fn validate_csv(csv_bytes: &[u8]) -> RouterResult<Vec<BlocklistRow>> {pub async fn initiate_batch_blocklist_upload(state: &SessionState,platform: &domain::Platform,+ profile_id: Option<id_type::ProfileId>,csv_bytes: bytes::Bytes,) -> RouterResult<api_blocklist::BatchBlocklistUploadResponse> {let processor_merchant_id = platform.get_processor().get_account().get_id();+ let profile_id = core_utils::get_profile_id_from_business_details(+ None,+ None,+ platform.get_processor(),+ profile_id.as_ref(),+ &*state.store,+ true,+ )+ .await?;let created_by = platform.get_initiator().and_then(|initiator| initiator.to_created_by())@@ -381,6 +394,7 @@ pub async fn initiate_batch_blocklist_upload(failed_rows: 0,created_at: now,updated_at: now,+ profile_id: profile_id.clone(),};state@@ -396,6 +410,7 @@ pub async fn initiate_batch_blocklist_upload(chunk_total_count,completed_chunks: Vec::new(),created_by: created_by.clone(),+ profile_id: Some(profile_id),};let runner = storage::ProcessTrackerRunner::BatchBlocklistUpload;@@ -447,6 +462,7 @@ pub(crate) async fn process_chunk(state: &SessionState,merchant_id: &id_type::MerchantId,processor_merchant_id: Option<&id_type::MerchantId>,+ profile_id: Option<&id_type::ProfileId>,chunk_idx: u32,chunk_rows: Vec<BlocklistRow>,created_by: Option<String>,@@ -462,6 +478,7 @@ pub(crate) async fn process_chunk(created_at: now,processor_merchant_id: processor_merchant_id.map(|id| id.to_owned()),created_by: created_by.clone(),+ profile_id: profile_id.map(|id| id.to_owned()),}).collect();diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rsindex b8d80d6bce..79241bed37 100644--- a/crates/router/src/core/blocklist/transformers.rs+++ b/crates/router/src/core/blocklist/transformers.rs@@ -20,6 +20,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {fingerprint_id: from.fingerprint_id,data_kind: from.data_kind,created_at: from.created_at,+ profile_id: from.profile_id,}}}diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 42a745e641..372fadce6a 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -17,6 +17,7 @@ use crate::{errors::{RouterResult, StorageErrorExt},metrics,payments::PaymentData,+ utils as core_utils,},logger,types::{domain, storage, transformers::ForeignInto},@@ -24,22 +25,36 @@ use crate::{pub async fn delete_entry_from_blocklist(state: &SessionState,- processor_merchant_id: &common_utils::id_type::MerchantId,+ processor: &domain::Processor,+ profile_id: Option<common_utils::id_type::ProfileId>,request: api_blocklist::DeleteFromBlocklistRequest,) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> {+ 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 blocklist_entry = match request {api_blocklist::DeleteFromBlocklistRequest::CardBin(bin) => {- delete_card_bin_blocklist_entry(state, &bin, processor_merchant_id).await?+ delete_card_bin_blocklist_entry(state, &bin, processor_merchant_id, &profile_id).await?}api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(xbin) => {- delete_card_bin_blocklist_entry(state, &xbin, processor_merchant_id).await?+ delete_card_bin_blocklist_entry(state, &xbin, processor_merchant_id, &profile_id)+ .await?}api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state.store- .delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ .delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ &profile_id,&fingerprint_id,).await@@ -98,12 +113,14 @@ pub async fn toggle_blocklist_guard_for_merchant(pub async fn list_blocklist_entries_for_merchant(state: &SessionState,processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,query: api_blocklist::ListBlocklistQuery,) -> RouterResult<api_blocklist::ListBlocklistResponse> {let entries = state.store- .list_blocklist_entries_by_processor_merchant_id_data_kind(+ .list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ profile_id,query.data_kind,query.limit.into(),query.offset.into(),@@ -115,8 +132,9 @@ pub async fn list_blocklist_entries_for_merchant(let total_count = state.store- .get_blocklist_entries_count_by_processor_merchant_id_data_kind(+ .get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ profile_id,query.data_kind,).await@@ -161,9 +179,19 @@ fn validate_extended_card_bin(bin: &str) -> RouterResult<()> {pub async fn insert_entry_into_blocklist(state: &SessionState,platform: &domain::Platform,+ profile_id: Option<common_utils::id_type::ProfileId>,to_block: api_blocklist::AddToBlocklistRequest,) -> RouterResult<api_blocklist::AddToBlocklistResponse> {let processor_merchant_id = platform.get_processor().get_account().get_id();+ let profile_id = core_utils::get_profile_id_from_business_details(+ None,+ None,+ platform.get_processor(),+ profile_id.as_ref(),+ &*state.store,+ true,+ )+ .await?;let blocklist_entry = match &to_block {api_blocklist::AddToBlocklistRequest::CardBin(bin) => {@@ -172,6 +200,7 @@ pub async fn insert_entry_into_blocklist(bin,state,platform,+ &profile_id,common_enums::BlocklistDataKind::CardBin,).await?@@ -183,6 +212,7 @@ pub async fn insert_entry_into_blocklist(bin,state,platform,+ &profile_id,common_enums::BlocklistDataKind::ExtendedCardBin,).await?@@ -191,8 +221,9 @@ pub async fn insert_entry_into_blocklist(api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => {let blocklist_entry_result = state.store- .find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ &profile_id,fingerprint_id,).await;@@ -228,9 +259,15 @@ pub async fn insert_entry_into_blocklist(.get_initiator().and_then(|initiator| initiator.to_created_by()).map(|created_by| created_by.to_string()),+ profile_id: Some(profile_id.to_owned()),}).await- .change_context(errors::ApiErrorResponse::InternalServerError)+ .map_err(|error| {+ map_blocklist_insert_error(+ error,+ "data associated with the given fingerprint is already blocked",+ )+ }).attach_printable("failed to add fingerprint to blocklist")?}};@@ -265,17 +302,35 @@ pub async fn get_merchant_fingerprint_secret(}}+// The duplicate check is not atomic with the insert, so a collision still means "already blocked".+fn map_blocklist_insert_error(+ error: error_stack::Report<errors::StorageError>,+ already_blocked_message: &str,+) -> error_stack::Report<errors::ApiErrorResponse> {+ match error.current_context().is_db_unique_violation() {+ true => error.change_context(errors::ApiErrorResponse::PreconditionFailed {+ message: already_blocked_message.to_string(),+ }),+ false => error.change_context(errors::ApiErrorResponse::InternalServerError),+ }+}+async fn duplicate_check_insert_bin(bin: &str,state: &SessionState,platform: &domain::Platform,+ profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> RouterResult<storage::Blocklist> {let processor_merchant_id = platform.get_processor().get_account().get_id();let blocklist_entry_result = state.store- .find_blocklist_entry_by_processor_merchant_id_fingerprint_id(processor_merchant_id, bin)+ .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ processor_merchant_id,+ profile_id,+ bin,+ ).await;match blocklist_entry_result {@@ -308,9 +363,10 @@ async fn duplicate_check_insert_bin(.get_initiator().and_then(|initiator| initiator.to_created_by()).map(|created_by| created_by.to_string()),+ profile_id: Some(profile_id.to_owned()),}).await- .change_context(errors::ApiErrorResponse::InternalServerError)+ .map_err(|error| map_blocklist_insert_error(error, "provided bin is already blocked")).attach_printable("error inserting pm blocklist item")}@@ -318,10 +374,15 @@ async fn delete_card_bin_blocklist_entry(state: &SessionState,bin: &str,processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,) -> RouterResult<storage::Blocklist> {state.store- .delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(processor_merchant_id, bin)+ .delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ processor_merchant_id,+ profile_id,+ bin,+ ).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {message: "could not find a blocklist entry for the given bin".to_string(),@@ -389,10 +450,13 @@ pub async fn should_payment_be_blocked(//validating the payment method.let mut blocklist_futures = Vec::new();+ let profile_id = business_profile.get_id();+if let Some(card_number_fingerprint) = card_number_fingerprint.as_ref() {blocklist_futures.push(- db.find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ db.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ profile_id,card_number_fingerprint,),);@@ -400,8 +464,9 @@ pub async fn should_payment_be_blocked(if let Some(card_bin_fingerprint) = card_bin_fingerprint.as_ref() {blocklist_futures.push(- db.find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ db.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ profile_id,card_bin_fingerprint,),);@@ -409,8 +474,9 @@ pub async fn should_payment_be_blocked(if let Some(extended_card_bin_fingerprint) = extended_card_bin_fingerprint.as_ref() {blocklist_futures.push(- db.find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ db.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ profile_id,extended_card_bin_fingerprint,),);@@ -418,8 +484,9 @@ pub async fn should_payment_be_blocked(if let Some(decrypted_token_extended_bin) = decrypted_token_extended_bin.as_ref() {blocklist_futures.push(- db.find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ db.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ profile_id,decrypted_token_extended_bin,),);diff --git a/crates/router/src/db/batch_blocklist_job.rs b/crates/router/src/db/batch_blocklist_job.rsindex 19921c27f2..a8177f6202 100644--- a/crates/router/src/db/batch_blocklist_job.rs+++ b/crates/router/src/db/batch_blocklist_job.rs@@ -126,7 +126,7 @@ impl BatchBlocklistJobInterface for MockDb {failed_rows: new.failed_rows,created_at: new.created_at,updated_at: new.updated_at,- profile_id: None,+ profile_id: Some(new.profile_id),};jobs.push(job.clone());Ok(job)diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rsindex a647724c42..5442dd309c 100644--- a/crates/router/src/db/blocklist.rs+++ b/crates/router/src/db/blocklist.rs@@ -23,12 +23,46 @@ pub trait BlocklistInterface {fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;+ async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError>;+async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;+ async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError>;++ /// `profile_id` is `None` for any caller that has no resolved profile - publishable-key and+ /// SDK auth, and an API key used without `X-Profile-Id`. Unlike the write paths, listing does+ /// not fall back to the default profile or error; absent means merchant-wide, as before+ /// profile scoping.+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;++ async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ ) -> CustomResult<usize, errors::StorageError>;+async fn list_blocklist_entries_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,@@ -108,6 +142,44 @@ impl BlocklistInterface for Store {}}+ #[instrument(skip_all)]+ async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ let result = storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_id(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await;++ match result {+ Ok(blocklist_entry) => Ok(blocklist_entry),+ Err(error) => {+ if matches!(+ error.current_context(),+ diesel_models::errors::DatabaseError::NotFound+ ) {+ storage::Blocklist::find_by_merchant_id_profile_id_fingerprint_id(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ } else {+ Err(report!(errors::StorageError::from(error)))+ }+ }+ }+ }+#[instrument(skip_all)]async fn list_blocklist_entries_by_processor_merchant_id(&self,@@ -196,6 +268,114 @@ impl BlocklistInterface for Store {}}+ #[instrument(skip_all)]+ async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ let result = storage::Blocklist::delete_by_processor_merchant_id_profile_id_fingerprint_id(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await;++ match result {+ Ok(blocklist) => Ok(blocklist),+ Err(error) => {+ if matches!(+ error.current_context(),+ diesel_models::errors::DatabaseError::NotFound+ ) {+ storage::Blocklist::delete_by_merchant_id_profile_id_fingerprint_id(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ } else {+ Err(report!(errors::StorageError::from(error)))+ }+ }+ }+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ match profile_id {+ Some(profile_id) => {+ storage::Blocklist::list_by_processor_merchant_id_profile_id_data_kind(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ None => {+ storage::Blocklist::list_by_processor_merchant_id_data_kind(+ &conn,+ processor_merchant_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ }+ .change_context(errors::StorageError::DatabaseError(report!(+ diesel_models::errors::DatabaseError::Others+ )))+ }++ #[instrument(skip_all)]+ async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ ) -> CustomResult<usize, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ match profile_id {+ Some(profile_id) => {+ storage::Blocklist::get_count_by_processor_merchant_id_profile_id_data_kind(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ )+ .await+ }+ None => {+ storage::Blocklist::get_count_by_processor_merchant_id_data_kind(+ &conn,+ processor_merchant_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,@@ -226,6 +406,15 @@ impl BlocklistInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _profile_id: &common_utils::id_type::ProfileId,+ _fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+async fn list_blocklist_entries_by_processor_merchant_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,@@ -259,6 +448,35 @@ impl BlocklistInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _profile_id: &common_utils::id_type::ProfileId,+ _fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }++ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _profile_id: Option<&common_utils::id_type::ProfileId>,+ _data_kind: common_enums::BlocklistDataKind,+ _limit: i64,+ _offset: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }++ async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _profile_id: Option<&common_utils::id_type::ProfileId>,+ _data_kind: common_enums::BlocklistDataKind,+ ) -> CustomResult<usize, errors::StorageError> {+ Err(errors::StorageError::MockDbError)?+ }+async fn bulk_insert_blocklist_entries(&self,entries: Vec<storage::BlocklistNew>,@@ -268,6 +486,7 @@ impl BlocklistInterface for MockDb {for entry in entries {let already_exists = blocklists.iter().any(|b| {b.processor_merchant_id == entry.processor_merchant_id+ && b.profile_id == entry.profile_id&& b.fingerprint_id == entry.fingerprint_id});if !already_exists {@@ -279,7 +498,7 @@ impl BlocklistInterface for MockDb {created_at: entry.created_at,processor_merchant_id: entry.processor_merchant_id,created_by: entry.created_by,- profile_id: None,+ profile_id: entry.profile_id,});inserted += 1;}@@ -312,6 +531,22 @@ impl BlocklistInterface for KafkaStore {.await}+ #[instrument(skip_all)]+ async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ self.diesel_store+ .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+#[instrument(skip_all)]async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,@@ -344,6 +579,58 @@ impl BlocklistInterface for KafkaStore {.await}+ #[instrument(skip_all)]+ async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<storage::Blocklist, errors::StorageError> {+ self.diesel_store+ .delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ self.diesel_store+ .list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ processor_merchant_id,+ profile_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }++ #[instrument(skip_all)]+ async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: Option<&common_utils::id_type::ProfileId>,+ data_kind: common_enums::BlocklistDataKind,+ ) -> CustomResult<usize, errors::StorageError> {+ self.diesel_store+ .get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ processor_merchant_id,+ profile_id,+ data_kind,+ )+ .await+ }+#[instrument(skip_all)]async fn get_blocklist_entries_count_by_processor_merchant_id_data_kind(&self,diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rsindex 3c9b72c927..d05ca62b5a 100644--- a/crates/router/src/routes/blocklist.rs+++ b/crates/router/src/routes/blocklist.rs@@ -14,9 +14,15 @@ use crate::{post,path = "/blocklist",request_body = BlocklistRequest,+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile to block this \+ entry under. Ignored when authenticating with a JWT, which carries its own 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 = "Fingerprint Blocked", body = BlocklistResponse),- (status = 400, description = "Invalid Data")+ (status = 400, description = "Invalid Data, or no profile could be resolved")),tag = "Blocklist",operation_id = "Block a Fingerprint",@@ -34,7 +40,8 @@ pub async fn add_entry_to_blocklist(&req,json_payload.into_inner(),|state, auth: auth::AuthenticationData, body, _| {- blocklist::add_entry_to_blocklist(state, auth.platform, body)+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ blocklist::add_entry_to_blocklist(state, auth.platform, profile_id, body)},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {@@ -57,9 +64,16 @@ pub async fn add_entry_to_blocklist(delete,path = "/blocklist",request_body = BlocklistRequest,+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile to unblock \+ this entry from. Only entries belonging to that profile, or entries with no profile, are \+ removed - an entry blocked under a different profile is not affected and the request \+ returns 404. Resolution follows the same rules as blocking."),+ ),responses((status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),- (status = 400, description = "Invalid Data")+ (status = 400, description = "Invalid Data, or no profile could be resolved"),+ (status = 404, description = "No entry for this fingerprint under the resolved profile")),tag = "Blocklist",operation_id = "Unblock a Fingerprint",@@ -77,9 +91,11 @@ pub async fn remove_entry_from_blocklist(&req,json_payload.into_inner(),|state, auth: auth::AuthenticationData, body, _| {+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());blocklist::remove_entry_from_blocklist(state,auth.platform.get_processor().clone(),+ profile_id,body,)},@@ -105,6 +121,10 @@ pub async fn remove_entry_from_blocklist(path = "/blocklist",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),+ ("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to entries \+ belonging to this business profile, plus entries with no profile. When no profile can be \+ resolved - as with publishable-key authentication - all of the merchant's entries are \+ returned, as before."),),responses((status = 200, description = "Blocked Fingerprints", body = ListBlocklistResponse),@@ -143,7 +163,15 @@ pub async fn list_blocked_payment_methods(query.client_secret = Some(client_secret);}- blocklist::list_blocklist_entries(state, auth.platform.get_processor().clone(), query)+ // None whenever no profile is resolved - SDK/publishable-key auth, or an API key sent+ // without X-Profile-Id - which keeps the listing merchant-wide+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ blocklist::list_blocklist_entries(+ state,+ auth.platform.get_processor().clone(),+ profile_id,+ query,+ )},auth::auth_type(&*auth_type,@@ -226,9 +254,14 @@ pub struct BatchBlocklistUploadForm {`metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \Maximum 100,000 data rows.",),+ params (+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile every entry \+ in this upload is blocked under. Resolution follows the same rules as blocking a single \+ entry."),+ ),responses((status = 202, description = "Batch blocklist job initiated", body = BatchBlocklistUploadResponse),- (status = 400, description = "CSV validation error or file exceeds 5 MiB limit"),+ (status = 400, description = "CSV validation error, file exceeds 5 MiB limit, or no profile could be resolved"),),tag = "Blocklist",operation_id = "Upload a batch blocklist CSV",@@ -249,7 +282,10 @@ pub async fn upload_batch_blocklist((),|state, auth: auth::AuthenticationData, _payload, _| {let csv_bytes = csv_bytes.clone();- async move { blocklist::upload_batch_blocklist(state, auth.platform, csv_bytes).await }+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ async move {+ blocklist::upload_batch_blocklist(state, auth.platform, profile_id, csv_bytes).await+ }},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {diff --git a/crates/router/src/types/storage/batch_blocklist_job.rs b/crates/router/src/types/storage/batch_blocklist_job.rsindex 26fea7d467..8fc6763b03 100644--- a/crates/router/src/types/storage/batch_blocklist_job.rs+++ b/crates/router/src/types/storage/batch_blocklist_job.rs@@ -11,4 +11,5 @@ pub struct BatchBlocklistTrackingData {pub chunk_total_count: u32,pub completed_chunks: Vec<u32>,pub created_by: Option<String>,+ pub profile_id: Option<id_type::ProfileId>,}diff --git a/crates/router/src/workflows/batch_blocklist_upload.rs b/crates/router/src/workflows/batch_blocklist_upload.rsindex a6f1f6090b..c03dceb6f3 100644--- a/crates/router/src/workflows/batch_blocklist_upload.rs+++ b/crates/router/src/workflows/batch_blocklist_upload.rs@@ -61,6 +61,7 @@ async fn run_batch_job(state,merchant_id_obj,tracking_data.processor_merchant_id.as_ref(),+ tracking_data.profile_id.as_ref(),chunk_idx,chunk_rows,tracking_data.created_by.clone(),diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 923da19ae7..44a50e8bcc 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -7863,6 +7863,7 @@ Cypress.Commands.add((requestBody, cardBin, globalState) => {const apiKey = globalState.get("apiKey");const baseUrl = globalState.get("baseUrl");+ const profileId = globalState.get("profileId");const url = `${baseUrl}/blocklist`;const body = {@@ -7877,6 +7878,7 @@ Cypress.Commands.add(headers: {"Content-Type": "application/json","api-key": apiKey,+ "X-Profile-Id": profileId,},body: body,failOnStatusCode: false,@@ -7906,6 +7908,7 @@ Cypress.Commands.add(Cypress.Commands.add("blocklistDeleteRule", (type, data, globalState) => {const apiKey = globalState.get("apiKey");const baseUrl = globalState.get("baseUrl");+ const profileId = globalState.get("profileId");const url = `${baseUrl}/blocklist`;const body = {@@ -7919,6 +7922,7 @@ Cypress.Commands.add("blocklistDeleteRule", (type, data, globalState) => {headers: {"Content-Type": "application/json","api-key": apiKey,+ "X-Profile-Id": profileId,},body: body,failOnStatusCode: false,diff --git a/diesel.toml b/diesel.tomlindex e4dd50432d..933ada38e6 100644--- a/diesel.toml+++ b/diesel.toml@@ -6,3 +6,6 @@ file = "crates/diesel_models/src/schema.rs"import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"]generate_missing_sql_type_definitions = falsepatch_file="crates/diesel_models/drop_id.patch"+# blocklist has no primary key, which print-schema refuses; the patch file restores its block.+# Anchored because this value is a regex - bare "blocklist" also matches the three sibling tables.+filter = { except_tables = ["^blocklist$"] }diff --git a/diesel_v2.toml b/diesel_v2.tomlindex aaad1eeeb5..52a0217954 100644--- a/diesel_v2.toml+++ b/diesel_v2.toml@@ -6,3 +6,6 @@file = "crates/diesel_models/src/schema_v2.rs"import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"]generate_missing_sql_type_definitions = false+# blocklist has no primary key, which print-schema refuses. Nothing in v2 uses this table, so it is+# simply left out. Anchored because the value is a regex and would otherwise match the sibling tables.+filter = { except_tables = ["^blocklist$"] }diff --git a/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sqlindex 9600ce5add..5ca934d68f 100644--- a/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql+++ b/migrations/2024-07-17-174449_change_primary_key_for_blocklist_table/down.sql@@ -1,5 +1,5 @@-- This file should undo anything in `up.sql`-ALTER TABLE blocklist DROP CONSTRAINT blocklist_pkey;+ALTER TABLE blocklist DROP CONSTRAINT IF EXISTS blocklist_pkey;ALTER TABLE blocklistADD PRIMARY KEY (id);diff --git a/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/down.sql b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/down.sqlnew file mode 100644index 0000000000..0b59c1b42d--- /dev/null+++ b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_processor_merchant_id_fingerprint_id_profile_id_index;diff --git a/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/metadata.toml b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/up.sql b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/up.sqlnew file mode 100644index 0000000000..4e502cc39c--- /dev/null+++ b/migrations/2026-08-17-100000_add_blocklist_profile_id_unique_index/up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS blocklist_processor_merchant_id_fingerprint_id_profile_id_index ON blocklist (processor_merchant_id, fingerprint_id, profile_id);diff --git a/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/down.sql b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/down.sqlnew file mode 100644index 0000000000..4d6ec2ed05--- /dev/null+++ b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_pm_fingerprint_null_profile_index;diff --git a/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/metadata.toml b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/up.sql b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/up.sqlnew file mode 100644index 0000000000..3b974771df--- /dev/null+++ b/migrations/2026-08-17-100100_add_blocklist_null_profile_unique_index/up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS blocklist_pm_fingerprint_null_profile_index ON blocklist (processor_merchant_id, fingerprint_id) WHERE profile_id IS NULL;diff --git a/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/down.sql b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/down.sqlnew file mode 100644index 0000000000..a8662bddc2--- /dev/null+++ b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_merchant_id_fingerprint_id_profile_id_index;diff --git a/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/metadata.toml b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/up.sql b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/up.sqlnew file mode 100644index 0000000000..f51303c889--- /dev/null+++ b/migrations/2026-08-17-100150_add_blocklist_merchant_id_fingerprint_id_index/up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS blocklist_merchant_id_fingerprint_id_profile_id_index ON blocklist (merchant_id, fingerprint_id, profile_id);diff --git a/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/down.sql b/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/up.sql b/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/up.sqlnew file mode 100644index 0000000000..f4057be775--- /dev/null+++ b/migrations/2026-08-17-100200_drop_blocklist_merchant_scoped_pkey/up.sql@@ -0,0 +1 @@+ALTER TABLE blocklist DROP CONSTRAINT IF EXISTS blocklist_pkey;diff --git a/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/down.sql b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/metadata.toml b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/up.sql b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/up.sqlnew file mode 100644index 0000000000..694d2045ec--- /dev/null+++ b/migrations/2026-08-17-100300_drop_blocklist_processor_merchant_id_unique_index/up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_processor_merchant_id_fingerprint_id_index;diff --git a/migrations/2026-08-19-100000_backfill_blocklist_profile_id/down.sql b/migrations/2026-08-19-100000_backfill_blocklist_profile_id/down.sqlnew file mode 100644index 0000000000..e0ac49d1ec--- /dev/null+++ b/migrations/2026-08-19-100000_backfill_blocklist_profile_id/down.sql@@ -0,0 +1 @@+SELECT 1;diff --git a/migrations/2026-08-19-100000_backfill_blocklist_profile_id/up.sql b/migrations/2026-08-19-100000_backfill_blocklist_profile_id/up.sqlnew file mode 100644index 0000000000..3470cc0807--- /dev/null+++ b/migrations/2026-08-19-100000_backfill_blocklist_profile_id/up.sql@@ -0,0 +1,13 @@+-- Create one blocklist entry per business profile for entries that predate profile scoping.+-- Safe to re-run: ON CONFLICT DO NOTHING skips entries that already exist. This backfill should be+-- executed again after deployment is complete, since older code keeps writing entries with a NULL+-- profile_id. The NULL entries are left in place so that a profile created later still inherits them.+INSERT INTO blocklist (merchant_id, fingerprint_id, data_kind, metadata,+ created_at, processor_merchant_id, created_by, profile_id)+SELECT b.merchant_id, b.fingerprint_id, b.data_kind, b.metadata,+ b.created_at, COALESCE(b.processor_merchant_id, b.merchant_id), b.created_by, p.profile_id+ FROM blocklist b+ JOIN business_profile p+ ON p.merchant_id = COALESCE(b.processor_merchant_id, b.merchant_id)+ WHERE b.profile_id IS NULL+ON CONFLICT DO NOTHING;