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

23.8 KB
Raw Blame
use actix_multipart::form::{bytes::Bytes as MultipartBytes, MultipartForm};
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
use router_env::Flow;

use crate::{
    core::{api_locking, blocklist},
    routes::AppState,
    services::{api, authentication as auth, authorization::permissions::Permission},
};

#[utoipa::path(
    post,
    path = "/blocklist",
    request_body = BlocklistEntryRequest,
    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, or no profile could be resolved")
    ),
    tag = "Blocklist",
    operation_id = "Block a Fingerprint",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn add_entry_to_blocklist(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<api_blocklist::BlocklistEntryRequest>,
) -> HttpResponse {
    let flow = Flow::AddToBlocklist;
    let body = json_payload.into_inner();
    let transaction_type = body.transaction_type;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        body.entry,
        |state, auth: auth::AuthenticationData, body, _| {
            let profile_id = auth.profile.map(|profile| profile.get_id().clone());
            blocklist::add_entry_to_blocklist(
                state,
                auth.platform,
                profile_id,
                transaction_type,
                body,
            )
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    delete,
    path = "/blocklist",
    request_body = BlocklistEntryRequest,
    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, 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",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn remove_entry_from_blocklist(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<api_blocklist::BlocklistEntryRequest>,
) -> HttpResponse {
    let flow = Flow::DeleteFromBlocklist;
    let body = json_payload.into_inner();
    let transaction_type = body.transaction_type;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        body.entry,
        |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,
                transaction_type,
                body,
            )
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    get,
    path = "/blocklist",
    params (
        ("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
        ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Blocklist flow: payment (default) or payout."),
        ("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to entries \
         belonging to this business profile, plus entries with no profile. Ignored when \
         authenticating with a JWT, which carries its own profile. If no profile is resolved \
         for an API key, all of the merchant's entries are returned."),
    ),
    responses(
        (status = 200, description = "Blocked Fingerprints", body = ListBlocklistResponse),
        (status = 400, description = "Invalid Data")
    ),
    tag = "Blocklist",
    operation_id = "List Blocked fingerprints of a particular kind",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_blocked_payment_methods(
    state: web::Data<AppState>,
    req: HttpRequest,
    query_payload: web::Query<api_blocklist::ListBlocklistQuery>,
) -> HttpResponse {
    let flow = Flow::ListBlocklist;
    let payload = query_payload.into_inner();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        payload,
        |state, auth: auth::AuthenticationData, query, _| {
            // An API key without a resolved profile 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::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountRead,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    get,
    path = "/blocklist/count",
    params (
        ("data_kind" = BlocklistDataKind, Query, description = "Kind of blocklist entries to count"),
        ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Counts only payment or payout when selected. When omitted, counts both, including legacy NULL entries. Legacy NULL entries belong to payment when filtered."),
        ("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" = []), ("jwt_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::ProfileAccountRead,
                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"),
        ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Looks up only payment or payout when selected. When omitted, both are included. Legacy NULL transaction namespaces belong to payment."),
        ("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 = "All matches within the resolved profile, including merchant-wide entries. transaction_types contains distinct matching payment/payout namespaces, without data kinds or profile IDs.", 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" = []), ("jwt_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::ProfileAccountRead,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    post,
    path = "/blocklist/toggle",
    params (
        ("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
    ),
    responses(
        (status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
        (status = 400, description = "Invalid Data")
    ),
    tag = "Blocklist",
    operation_id = "Toggle blocklist guard for a particular merchant",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_blocklist_guard(
    state: web::Data<AppState>,
    req: HttpRequest,
    query_payload: web::Query<api_blocklist::ToggleBlocklistQuery>,
) -> HttpResponse {
    let flow = Flow::ListBlocklist;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        query_payload.into_inner(),
        |state, auth: auth::AuthenticationData, query, _| {
            blocklist::toggle_blocklist_guard(state, auth.platform.get_processor().clone(), query)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

// ---- Batch blocklist upload route handlers ----

#[derive(Debug, MultipartForm)]
pub struct BatchBlocklistUploadForm {
    // Also charged against `consts::MULTIPART_MEMORY_LIMIT`, the global in-memory budget for
    // multipart fields. That global must stay >= this limit, or this one is unreachable.
    #[multipart(limit = "5MiB")]
    pub file: MultipartBytes,
}

#[utoipa::path(
    post,
    path = "/blocklist/batch",
    request_body(
        content = String,
        content_type = "multipart/form-data",
        description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). \
            The CSV header is `type,data,metadata,transaction_type`; older headers without `transaction_type` are accepted. \
            `type`: one of `generic_card_bin` (6 to 10 digits), `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \
            `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \
            `transaction_type`: optional, `payment` (default) or `payout`; selection may differ per row. \
            Invalid CSV transaction-type values are rejected even when a query override is selected. \
            Maximum 100,000 data rows.",
    ),
    params (
        ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Overrides every CSV row with payment or payout when selected. When omitted, row selections are used; missing or empty row values default to payment."),
        ("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, file exceeds 5 MiB limit, or no profile could be resolved"),
    ),
    tag = "Blocklist",
    operation_id = "Upload a batch blocklist CSV",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn upload_batch_blocklist(
    state: web::Data<AppState>,
    req: HttpRequest,
    MultipartForm(form): MultipartForm<BatchBlocklistUploadForm>,
    query_payload: web::Query<api_blocklist::BatchBlocklistUploadQuery>,
) -> HttpResponse {
    let flow = Flow::BatchBlocklistUpload;
    let csv_bytes = bytes::Bytes::from(form.file.data.to_vec());
    let file_name = form.file.file_name.clone();

    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        query_payload.into_inner(),
        |state, auth: auth::AuthenticationData, query, _| {
            let csv_bytes = csv_bytes.clone();
            let file_name = file_name.clone();
            let profile_id = auth.profile.map(|profile| profile.get_id().clone());
            let transaction_type = query.transaction_type;
            async move {
                blocklist::upload_batch_blocklist(
                    state,
                    auth.platform,
                    profile_id,
                    csv_bytes,
                    file_name,
                    transaction_type,
                )
                .await
            }
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    get,
    path = "/blocklist/batch/{job_id}",
    params(
        ("job_id" = String, Path, description = "The job ID returned by the batch upload endpoint"),
    ),
    responses(
        (status = 200, description = "Batch blocklist job status", body = BatchBlocklistJobStatusResponse),
        (status = 404, description = "Job not found"),
    ),
    tag = "Blocklist",
    operation_id = "Get batch blocklist job status",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn get_batch_blocklist_job_status(
    state: web::Data<AppState>,
    req: HttpRequest,
    path: web::Path<String>,
) -> HttpResponse {
    let flow = Flow::GetBatchBlocklistJobStatus;
    let job_id = path.into_inner();
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        job_id,
        |state, auth: auth::AuthenticationData, job_id, _| {
            let profile_id = auth.profile.map(|profile| profile.get_id().clone());
            blocklist::get_batch_blocklist_job_status(state, auth.platform, profile_id, job_id)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountRead,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    get,
    path = "/blocklist/batch",
    params(
        ("limit" = Option<u32>, Query, description = "Maximum number of jobs to return (default 10)"),
        ("offset" = Option<u32>, Query, description = "Zero-based offset for pagination (default 0)"),
        ("job_type" = Option<BatchBlocklistJobType>, Query, description = "Restricts the listing to \
         `upload`, `export`, or `profile_clone` jobs. All kinds are returned when omitted"),
        ("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to jobs run \
         for this business profile, plus jobs that predate profile scoping. When no profile can be \
         resolved, all of the merchant's jobs are returned, as before."),
    ),
    responses(
        (status = 200, description = "List of batch blocklist jobs", body = ListBatchBlocklistJobsResponse),
    ),
    tag = "Blocklist",
    operation_id = "List batch blocklist jobs",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_batch_blocklist_jobs(
    state: web::Data<AppState>,
    req: HttpRequest,
    query_payload: web::Query<api_blocklist::ListBatchBlocklistJobsQuery>,
) -> HttpResponse {
    let flow = Flow::ListBatchBlocklistJobs;
    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::list_batch_blocklist_jobs(state, auth.platform, profile_id, query)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountRead,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

// ---- Blocklist CSV export route handlers ----

#[utoipa::path(
    post,
    path = "/blocklist/export",
    params (
        ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Exports only \
         `payment` or `payout` entries when selected. Both are exported when omitted."),
        ("X-Profile-Id" = Option<String>, Header, description = "The business profile whose \
         blocklist is exported. Resolution follows the same rules as blocking a single entry."),
    ),
    responses(
        (status = 202, description = "Blocklist export started", body = BlocklistExportResponse),
        (status = 400, description = "Invalid transaction type, or no profile could be resolved"),
    ),
    tag = "Blocklist",
    operation_id = "Start a blocklist CSV export",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn create_blocklist_export(
    state: web::Data<AppState>,
    req: HttpRequest,
    query_payload: web::Query<api_blocklist::BlocklistExportQuery>,
) -> HttpResponse {
    let flow = Flow::CreateBlocklistExport;
    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::create_blocklist_export(
                state,
                auth.platform,
                profile_id,
                query.transaction_type,
            )
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::ProfileAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}

#[utoipa::path(
    post,
    path = "/blocklist/clone",
    request_body = CloneBlocklistEntriesRequest,
    params(
        ("X-Profile-Id" = Option<String>, Header, description = "Source profile whose entries are copied; it also owns the clone job. Required when the authenticated dashboard session does not provide a profile context")
    ),
    responses(
        (status = 200, description = "One background job was started; it clones onto the target profiles one at a time", body = CloneBlocklistEntriesResponse),
        (status = 400, description = "Missing profile context, no targets given, or a target is the source profile"),
        (status = 404, description = "The source or a target profile does not belong to the merchant")
    ),
    tag = "Blocklist",
    operation_id = "Clone blocklist entries across profiles",
    security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn clone_blocklist_entries(
    state: web::Data<AppState>,
    req: HttpRequest,
    json_payload: web::Json<api_blocklist::CloneBlocklistEntriesRequest>,
) -> HttpResponse {
    let flow = Flow::CloneBlocklistEntries;
    Box::pin(api::server_wrap(
        flow,
        state,
        &req,
        json_payload.into_inner(),
        |state, auth: auth::AuthenticationData, body, _| {
            let profile_id = auth.profile.map(|profile| profile.get_id().clone());
            blocklist::clone_blocklist_entries(state, auth.platform, profile_id, body)
        },
        auth::auth_type(
            &auth::HeaderAuth(auth::ApiKeyAuth {
                allow_connected_scope_operation: true,
                allow_platform_self_operation: false,
            }),
            &auth::JWTAuth {
                permission: Permission::MerchantAccountWrite,
                allow_connected: true,
                allow_platform: false,
            },
            req.headers(),
        ),
        api_locking::LockAction::NotApplicable,
    ))
    .await
}