use std::fmt;
use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::buyer_blocklist::{
BuyerBlocklistCapabilitiesResponse, BuyerBlocklistEntryResponse, BuyerBlocklistEventsResponse,
BuyerBlocklistFromPaymentPreviewResponse, BuyerBlocklistListResponse,
PaymentFraudSignalsResponse, RadarSyncSettingsListResponse, RadarSyncSettingsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct BuyerBlocklist {
inner: Arc<Inner>,
}
impl BuyerBlocklist {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn list(
&self,
params: Option<&BuyerBlocklistListParams>,
) -> Result<BuyerBlocklistListResponse> {
let query = params
.map(BuyerBlocklistListParams::to_query)
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, "/buyer-blocklist", None, &query, None)
.await
}
pub async fn create(
&self,
params: &BuyerBlocklistEntryCreateRequest,
) -> Result<BuyerBlocklistEntryResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, "/buyer-blocklist", Some(&body), None)
.await
}
pub async fn delete(
&self,
entry_id: &str,
params: Option<&BuyerBlocklistEntryDeleteRequest>,
) -> Result<BuyerBlocklistEntryResponse> {
let none = BuyerBlocklistEntryDeleteRequest::default();
let body = to_json_vec(params.unwrap_or(&none))?;
self.inner
.request_body_keyed(HttpMethod::Delete, &entry_path(entry_id), Some(&body), None)
.await
}
pub async fn create_from_payment(
&self,
params: &BuyerBlocklistFromPaymentRequest,
) -> Result<BuyerBlocklistEntryResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/buyer-blocklist/from-payment",
Some(&body),
None,
)
.await
}
pub async fn preview_from_payment(
&self,
params: &BuyerBlocklistFromPaymentPreviewRequest,
) -> Result<BuyerBlocklistFromPaymentPreviewResponse> {
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Post,
"/buyer-blocklist/from-payment/preview",
Some(&body),
None,
)
.await
}
pub async fn list_events(
&self,
entry_id: &str,
limit: Option<u32>,
) -> Result<BuyerBlocklistEventsResponse> {
let path = format!("{}/events", entry_path(entry_id));
let query: Vec<(&str, String)> = limit
.map(|v| vec![("limit", v.to_string())])
.unwrap_or_default();
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn capabilities(&self) -> Result<BuyerBlocklistCapabilitiesResponse> {
self.inner
.request(
HttpMethod::Get,
"/buyer-blocklist/capabilities",
None,
&[],
None,
)
.await
}
pub async fn retry_sync(&self, entry_id: &str) -> Result<BuyerBlocklistEntryResponse> {
let path = format!("{}/sync/retry", entry_path(entry_id));
self.inner
.request_body_keyed(HttpMethod::Post, &path, None, None)
.await
}
pub async fn list_radar_sync(&self) -> Result<RadarSyncSettingsListResponse> {
self.inner
.request(
HttpMethod::Get,
"/buyer-blocklist/radar-sync",
None,
&[],
None,
)
.await
}
pub async fn retrieve_radar_sync(
&self,
merchant_connector_id: &str,
) -> Result<RadarSyncSettingsResponse> {
self.inner
.request(
HttpMethod::Get,
&radar_path(merchant_connector_id),
None,
&[],
None,
)
.await
}
pub async fn update_radar_sync(
&self,
merchant_connector_id: &str,
params: &RadarSyncSettingsUpdateRequest,
) -> Result<RadarSyncSettingsResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(
HttpMethod::Put,
&radar_path(merchant_connector_id),
Some(&body),
None,
)
.await
}
pub async fn remove_radar_items(
&self,
merchant_connector_id: &str,
) -> Result<RadarSyncSettingsResponse> {
let path = format!("{}/remove-items", radar_path(merchant_connector_id));
self.inner
.request_body_keyed(HttpMethod::Post, &path, None, None)
.await
}
pub async fn fraud_signals(&self, payment_id: &str) -> Result<PaymentFraudSignalsResponse> {
let path = format!(
"/buyer-blocklist/fraud-signals/{}",
encode_segment(payment_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
}
fn entry_path(entry_id: &str) -> String {
format!("/buyer-blocklist/{}", encode_segment(entry_id))
}
fn radar_path(merchant_connector_id: &str) -> String {
format!(
"/buyer-blocklist/radar-sync/{}",
encode_segment(merchant_connector_id)
)
}
fn reject_extra_collisions(
extra: &serde_json::Map<String, Value>,
named: &[&str],
type_name: &str,
) -> Result<()> {
for key in extra.keys() {
if named.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on {type_name}"
)));
}
}
Ok(())
}
fn redact<T>(value: &Option<T>) -> Option<&'static str> {
value.as_ref().map(|_| "<redacted>")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistKind {
Email,
Ip,
CustomerId,
DeviceId,
CardFingerprint,
CardBin,
IpRange,
IpClass,
DeviceTraits,
}
impl BuyerBlocklistKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Email => "email",
Self::Ip => "ip",
Self::CustomerId => "customer_id",
Self::DeviceId => "device_id",
Self::CardFingerprint => "card_fingerprint",
Self::CardBin => "card_bin",
Self::IpRange => "ip_range",
Self::IpClass => "ip_class",
Self::DeviceTraits => "device_traits",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistIpClass {
Datacenter,
ProxyVpn,
Tor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuyerBlocklistListScope {
All,
Merchant,
Shop,
}
impl BuyerBlocklistListScope {
pub fn as_str(self) -> &'static str {
match self {
Self::All => "all",
Self::Merchant => "merchant",
Self::Shop => "shop",
}
}
}
#[derive(Clone, Default)]
pub struct BuyerBlocklistListParams {
pub scope: Option<BuyerBlocklistListScope>,
pub profile_id: Option<String>,
pub kind: Option<BuyerBlocklistKind>,
pub search: Option<String>,
pub group_id: Option<String>,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl fmt::Debug for BuyerBlocklistListParams {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BuyerBlocklistListParams")
.field("scope", &self.scope)
.field("profile_id", &self.profile_id)
.field("kind", &self.kind)
.field("search", &redact(&self.search))
.field("group_id", &self.group_id)
.field("limit", &self.limit)
.field("offset", &self.offset)
.finish()
}
}
impl BuyerBlocklistListParams {
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.scope {
q.push(("scope", v.as_str().to_string()));
}
if let Some(v) = &self.profile_id {
q.push(("profile_id", v.clone()));
}
if let Some(v) = self.kind {
q.push(("kind", v.as_str().to_string()));
}
if let Some(v) = &self.search {
q.push(("search", v.clone()));
}
if let Some(v) = &self.group_id {
q.push(("group_id", v.clone()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[derive(Clone, Default, Serialize)]
pub struct BuyerBlocklistEntryCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_bin: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ip_range: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ip_class: Option<BuyerBlocklistIpClass>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<BuyerBlocklistKind>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl fmt::Debug for BuyerBlocklistEntryCreateRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BuyerBlocklistEntryCreateRequest")
.field("email", &redact(&self.email))
.field("ip", &redact(&self.ip))
.field("customer_id", &redact(&self.customer_id))
.field("device_id", &redact(&self.device_id))
.field("card_bin", &redact(&self.card_bin))
.field("ip_range", &redact(&self.ip_range))
.field("ip_class", &self.ip_class)
.field("kind", &self.kind)
.field("value", &redact(&self.value))
.field("profile_id", &self.profile_id)
.field("note", &self.note)
.field("expires_at", &self.expires_at)
.finish_non_exhaustive()
}
}
impl BuyerBlocklistEntryCreateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn email(mut self, email: impl Into<String>) -> Self {
self.email = Some(email.into());
self
}
#[must_use]
pub fn ip(mut self, ip: impl Into<String>) -> Self {
self.ip = Some(ip.into());
self
}
#[must_use]
pub fn customer_id(mut self, customer_id: impl Into<String>) -> Self {
self.customer_id = Some(customer_id.into());
self
}
#[must_use]
pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
self.device_id = Some(device_id.into());
self
}
#[must_use]
pub fn card_bin(mut self, card_bin: impl Into<String>) -> Self {
self.card_bin = Some(card_bin.into());
self
}
#[must_use]
pub fn ip_range(mut self, ip_range: impl Into<String>) -> Self {
self.ip_range = Some(ip_range.into());
self
}
#[must_use]
pub fn ip_class(mut self, ip_class: BuyerBlocklistIpClass) -> Self {
self.ip_class = Some(ip_class);
self
}
#[must_use]
pub fn identifier(mut self, kind: BuyerBlocklistKind, value: impl Into<String>) -> Self {
self.kind = Some(kind);
self.value = Some(value.into());
self
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
#[must_use]
pub fn expires_at(mut self, expires_at: impl Into<String>) -> Self {
self.expires_at = Some(expires_at.into());
self
}
}
const BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED: &[&str] = &[
"email",
"ip",
"customer_id",
"device_id",
"card_bin",
"ip_range",
"ip_class",
"kind",
"value",
"profile_id",
"note",
"expires_at",
];
impl ValidateRequest for BuyerBlocklistEntryCreateRequest {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED,
"BuyerBlocklistEntryCreateRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerBlocklistEntryDeleteRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
impl BuyerBlocklistEntryDeleteRequest {
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: Some(reason.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PaymentBlockIdentifier {
Card,
Email,
Ip,
Device,
Customer,
DeviceTraits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum PaymentBlockScope {
Shop,
AllShops,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum BuyerBlocklistTraitAction {
Flag,
Refuse,
}
#[derive(Clone, Serialize)]
pub struct BuyerBlocklistFromPaymentRequest {
pub payment_id: String,
pub identifiers: Vec<PaymentBlockIdentifier>,
pub scope: PaymentBlockScope,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub all_ips: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ips: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trait_action: Option<BuyerBlocklistTraitAction>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl fmt::Debug for BuyerBlocklistFromPaymentRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BuyerBlocklistFromPaymentRequest")
.field("payment_id", &self.payment_id)
.field("identifiers", &self.identifiers)
.field("scope", &self.scope)
.field("note", &self.note)
.field("expires_at", &self.expires_at)
.field("all_ips", &self.all_ips)
.field("ips", &redact(&self.ips))
.field("trait_action", &self.trait_action)
.finish_non_exhaustive()
}
}
impl BuyerBlocklistFromPaymentRequest {
pub fn new(
payment_id: impl Into<String>,
identifiers: Vec<PaymentBlockIdentifier>,
scope: PaymentBlockScope,
) -> Self {
Self {
payment_id: payment_id.into(),
identifiers,
scope,
note: None,
expires_at: None,
all_ips: None,
ips: None,
trait_action: None,
extra: serde_json::Map::new(),
}
}
#[must_use]
pub fn note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
#[must_use]
pub fn expires_at(mut self, expires_at: impl Into<String>) -> Self {
self.expires_at = Some(expires_at.into());
self
}
#[must_use]
pub fn all_ips(mut self, all_ips: bool) -> Self {
self.all_ips = Some(all_ips);
self
}
#[must_use]
pub fn ips(mut self, ips: Vec<String>) -> Self {
self.ips = Some(ips);
self
}
#[must_use]
pub fn trait_action(mut self, trait_action: BuyerBlocklistTraitAction) -> Self {
self.trait_action = Some(trait_action);
self
}
}
const BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED: &[&str] = &[
"payment_id",
"identifiers",
"scope",
"note",
"expires_at",
"all_ips",
"ips",
"trait_action",
];
impl ValidateRequest for BuyerBlocklistFromPaymentRequest {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED,
"BuyerBlocklistFromPaymentRequest",
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerBlocklistFromPaymentPreviewRequest {
pub payment_id: String,
}
impl BuyerBlocklistFromPaymentPreviewRequest {
pub fn new(payment_id: impl Into<String>) -> Self {
Self {
payment_id: payment_id.into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RadarEfwAction {
Notify,
NotifyAndBlock,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RadarReviewAction {
Notify,
None,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct RadarSyncSettingsUpdateRequest {
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub efw_action: Option<RadarEfwAction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub review_action: Option<RadarReviewAction>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl RadarSyncSettingsUpdateRequest {
pub fn new(enabled: bool) -> Self {
Self {
enabled,
..Default::default()
}
}
#[must_use]
pub fn efw_action(mut self, action: RadarEfwAction) -> Self {
self.efw_action = Some(action);
self
}
#[must_use]
pub fn review_action(mut self, action: RadarReviewAction) -> Self {
self.review_action = Some(action);
self
}
}
const RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED: &[&str] =
&["enabled", "efw_action", "review_action"];
impl ValidateRequest for RadarSyncSettingsUpdateRequest {
fn validate(&self) -> Result<()> {
reject_extra_collisions(
&self.extra,
RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED,
"RadarSyncSettingsUpdateRequest",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const ENTRY_JSON: &str = r#"{
"id": "bbl_1", "email": "fraud@example.com", "ip": "203.0.113.9",
"customer_id": "cus_1", "device_id": null, "kind": "email",
"value": "fraud@example.com", "profile_id": "pro_1", "note": "chargebacks",
"expires_at": null, "block_count": 3, "created_at": "2026-01-01T00:00:00Z",
"card_fingerprint": "fp_123", "card_display": "visa 4242", "card_bin": "424242",
"card_source": {"connector": "stripe", "merchant_connector_id": "mca_1"},
"radar": {
"processor_names_hidden": false, "status": "pending",
"connections": [{
"merchant_connector_id": "mca_1", "connector_label": "main",
"profile_id": "pro_1", "environment": "live",
"items": [{"identifier": "email", "status": "pending",
"value_list_alias": "delopay_email", "last_error": null,
"attempts": 1, "updated_at": "2026-01-01T00:00:00Z"}]
}],
"local_only_reason": null
},
"entry_surprise": 1
}"#;
const RADAR_JSON: &str = r#"{
"merchant_connector_id": "mca_1", "connector_label": "main", "profile_id": "pro_1",
"environments": ["live"], "enabled": true, "efw_action": "notify_and_block",
"review_action": "notify",
"lists": [{"identifier": "card_fingerprint", "item_type": "card_fingerprint",
"environment": "live", "value_list_alias": "delopay_cards",
"value_list_id": "rsl_1", "rule_needed": true,
"rule_text": "Block if :card_fingerprint: in @delopay_cards"}],
"counts": {"synced": 4, "pending": 1, "failed": 0, "removing": 0},
"updated_at": "2026-01-01T00:00:00Z", "radar_surprise": 1
}"#;
#[tokio::test]
async fn list_sends_the_filters_and_redacts_identifiers() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"entries":[{ENTRY_JSON}],"total_count":1,"limit":20,"offset":0}}"#
))]);
let params = BuyerBlocklistListParams {
scope: Some(BuyerBlocklistListScope::Shop),
profile_id: Some("pro_1".to_string()),
kind: Some(BuyerBlocklistKind::CardFingerprint),
search: Some("fraud@example.com".to_string()),
limit: Some(20),
..Default::default()
};
assert!(!format!("{params:?}").contains("fraud@example.com"));
let page = client.buyer_blocklist().list(Some(¶ms)).await.unwrap();
let entry = &page.entries[0];
assert_eq!(entry.block_count, 3);
assert_eq!(entry.radar.connections[0].items[0].attempts, 1);
assert_eq!(entry.extra["entry_surprise"], 1);
let printed = format!("{page:?}");
for secret in [
"fraud@example.com",
"203.0.113.9",
"fp_123",
"424242",
"cus_1",
] {
assert!(!printed.contains(secret), "Debug leaked {secret}");
}
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist?scope=shop&profile_id=pro_1\
&kind=card_fingerprint&search=fraud@example.com&limit=20"
);
}
#[tokio::test]
async fn create_posts_the_identifiers() {
let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
let req = BuyerBlocklistEntryCreateRequest::new()
.email("fraud@example.com")
.ip_class(BuyerBlocklistIpClass::ProxyVpn)
.profile_id("pro_1")
.note("chargebacks");
assert!(!format!("{req:?}").contains("fraud@example.com"));
let entry = client.buyer_blocklist().create(&req).await.unwrap();
assert_eq!(entry.id, "bbl_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/buyer-blocklist");
assert_eq!(
seen[0].body_json(),
json!({
"email": "fraud@example.com",
"ip_class": "proxy_vpn",
"profile_id": "pro_1",
"note": "chargebacks"
})
);
}
#[tokio::test]
async fn delete_sends_an_empty_object_without_a_reason() {
let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON), Step::ok(ENTRY_JSON)]);
client
.buyer_blocklist()
.delete("bbl/1", None)
.await
.unwrap();
client
.buyer_blocklist()
.delete(
"bbl_1",
Some(&BuyerBlocklistEntryDeleteRequest::new("resolved")),
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/bbl%2F1");
assert_eq!(seen[0].body_json(), json!({}));
assert_eq!(seen[1].body_json(), json!({"reason": "resolved"}));
}
#[tokio::test]
async fn create_from_payment_posts_the_payment_block() {
let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
let req = BuyerBlocklistFromPaymentRequest::new(
"pay_1",
vec![
PaymentBlockIdentifier::Card,
PaymentBlockIdentifier::DeviceTraits,
],
PaymentBlockScope::AllShops,
)
.all_ips(true)
.ips(vec!["198.51.100.7".to_string()])
.trait_action(BuyerBlocklistTraitAction::Refuse);
assert!(!format!("{req:?}").contains("198.51.100.7"));
client
.buyer_blocklist()
.create_from_payment(&req)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/from-payment");
assert_eq!(
seen[0].body_json(),
json!({
"payment_id": "pay_1",
"identifiers": ["card", "device_traits"],
"scope": "all_shops",
"all_ips": true,
"ips": ["198.51.100.7"],
"trait_action": "refuse"
})
);
}
#[tokio::test]
async fn preview_from_payment_posts_the_payment_id() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","ips":[{"ip":"198.51.100.7","sources":["this_payment"],
"last_seen_at":null,"other_buyers":0,"preselected":true,"x":1}],
"truncated":false,"total":1}"#,
)]);
let out = client
.buyer_blocklist()
.preview_from_payment(&BuyerBlocklistFromPaymentPreviewRequest::new("pay_1"))
.await
.unwrap();
assert!(out.ips[0].preselected);
assert_eq!(out.ips[0].extra["x"], 1);
assert!(!format!("{out:?}").contains("198.51.100.7"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/from-payment/preview"
);
assert_eq!(seen[0].body_json(), json!({"payment_id": "pay_1"}));
}
#[tokio::test]
async fn list_events_gets_the_events_with_a_limit() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"entry_id":"bbl_1","block_count":2,"events":[{"stage":"confirm",
"outcome":"refused","matched_kind":"email","payment_id":"pay_9",
"created_at":"2026-01-01T00:00:00Z","x":1}]}"#,
)]);
let out = client
.buyer_blocklist()
.list_events("bbl_1", Some(5))
.await
.unwrap();
assert_eq!(out.events[0].stage, "confirm");
assert_eq!(out.events[0].extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/bbl_1/events?limit=5"
);
}
#[tokio::test]
async fn capabilities_gets_the_capabilities_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"ip_classes":[{"class":"tor","available":true,"sources":["tor_exit_list"],
"provider_sources":[],"x":1}]}"#,
)]);
let out = client.buyer_blocklist().capabilities().await.unwrap();
assert_eq!(out.ip_classes[0].class, "tor");
assert_eq!(out.ip_classes[0].extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/capabilities");
}
#[tokio::test]
async fn retry_sync_posts_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(ENTRY_JSON)]);
client.buyer_blocklist().retry_sync("bbl/1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/bbl%2F1/sync/retry"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn list_radar_sync_gets_every_connection() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"connections":[{RADAR_JSON}]}}"#
))]);
let out = client.buyer_blocklist().list_radar_sync().await.unwrap();
assert_eq!(out.connections[0].counts.synced, 4);
assert!(out.connections[0].lists[0].rule_needed);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/buyer-blocklist/radar-sync");
}
#[tokio::test]
async fn retrieve_radar_sync_encodes_the_connector_account() {
let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
let out = client
.buyer_blocklist()
.retrieve_radar_sync("mca/1")
.await
.unwrap();
assert_eq!(out.efw_action, "notify_and_block");
assert_eq!(out.extra["radar_surprise"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/radar-sync/mca%2F1"
);
}
#[tokio::test]
async fn update_radar_sync_puts_the_settings() {
let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
let req = RadarSyncSettingsUpdateRequest::new(true)
.efw_action(RadarEfwAction::NotifyAndBlock)
.review_action(RadarReviewAction::None);
client
.buyer_blocklist()
.update_radar_sync("mca_1", &req)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/radar-sync/mca_1"
);
assert_eq!(
seen[0].body_json(),
json!({"enabled": true, "efw_action": "notify_and_block", "review_action": "none"})
);
}
#[tokio::test]
async fn remove_radar_items_posts_to_the_remove_items_path() {
let (client, mock) = client_with(vec![Step::ok(RADAR_JSON)]);
client
.buyer_blocklist()
.remove_radar_items("mca_1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/radar-sync/mca_1/remove-items"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn fraud_signals_gets_the_payment_signals() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","processor_names_hidden":false,"risk_level":"elevated",
"risk_score":71,"early_fraud_warnings":[{"id":"issfr_1","fraud_type":"stolen_card",
"actionable":true,"received_at":"2026-01-01T00:00:00Z"}],"reviews":[],
"blockable":{"card":true,"email":true,"ip":true,"device":false,"customer":true},
"blocked_by":["bbl_1"],"ip_classes":[{"class":"datacenter","sources":["asn"]}],
"device_traits":{"hash":"dt_1","randomized":false,"commonness":3,"history_days":30,
"summary":{"browser":"Firefox","os":"Linux","screen":null,"time_zone":null,"language":"en"}},
"x":1}"#,
)]);
let out = client
.buyer_blocklist()
.fraud_signals("pay/1")
.await
.unwrap();
assert_eq!(out.risk_score, Some(71));
assert!(out.blockable.card);
assert_eq!(
out.early_fraud_warnings[0].fraud_type.as_deref(),
Some("stolen_card")
);
assert_eq!(out.device_traits.unwrap().summary.browser, "Firefox");
assert_eq!(out.extra["x"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/buyer-blocklist/fraud-signals/pay%2F1"
);
}
#[test]
fn kind_tokens_match_their_serialized_form() {
for kind in [
BuyerBlocklistKind::Email,
BuyerBlocklistKind::Ip,
BuyerBlocklistKind::CustomerId,
BuyerBlocklistKind::DeviceId,
BuyerBlocklistKind::CardFingerprint,
BuyerBlocklistKind::CardBin,
BuyerBlocklistKind::IpRange,
BuyerBlocklistKind::IpClass,
BuyerBlocklistKind::DeviceTraits,
] {
assert_eq!(serde_json::to_value(kind).unwrap(), kind.as_str());
}
}
fn assert_named_complete<T: Serialize>(req: &T, named: &[&str]) {
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
named.contains(&key.as_str()),
"NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn buyer_blocklist_entry_create_request_named_fields_are_complete() {
let req = BuyerBlocklistEntryCreateRequest::new()
.email("e")
.ip("i")
.customer_id("c")
.device_id("d")
.card_bin("424242")
.ip_range("10.0.0.0/8")
.ip_class(BuyerBlocklistIpClass::Tor)
.identifier(BuyerBlocklistKind::Email, "e")
.profile_id("p")
.note("n")
.expires_at("2027-01-01T00:00:00Z");
assert_named_complete(&req, BUYER_BLOCKLIST_ENTRY_CREATE_REQUEST_NAMED);
}
#[test]
fn buyer_blocklist_from_payment_request_named_fields_are_complete() {
let req = BuyerBlocklistFromPaymentRequest::new(
"pay_1",
vec![PaymentBlockIdentifier::Email],
PaymentBlockScope::Shop,
)
.note("n")
.expires_at("2027-01-01T00:00:00Z")
.all_ips(true)
.ips(vec![])
.trait_action(BuyerBlocklistTraitAction::Flag);
assert_named_complete(&req, BUYER_BLOCKLIST_FROM_PAYMENT_REQUEST_NAMED);
}
#[test]
fn radar_sync_settings_update_request_named_fields_are_complete() {
let req = RadarSyncSettingsUpdateRequest::new(true)
.efw_action(RadarEfwAction::Notify)
.review_action(RadarReviewAction::Notify);
assert_named_complete(&req, RADAR_SYNC_SETTINGS_UPDATE_REQUEST_NAMED);
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = BuyerBlocklistEntryCreateRequest::new();
req.extra
.insert("email".to_string(), json!("x@example.com"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("email")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn writes_ignore_the_client_wide_idempotency_key() {
let steps = (0..7)
.map(|_| Step::status(503, r#"{"error":{"message":"down"}}"#))
.collect();
let (client, mock) = crate::http::mock::client_with_retries(steps, 2);
let client = client.with_idempotency_key("client-key");
client
.buyer_blocklist()
.create(&BuyerBlocklistEntryCreateRequest::new().email("e@example.com"))
.await
.unwrap_err();
client
.buyer_blocklist()
.delete("bbl_1", None)
.await
.unwrap_err();
client
.buyer_blocklist()
.create_from_payment(&BuyerBlocklistFromPaymentRequest::new(
"pay_1",
vec![PaymentBlockIdentifier::Email],
PaymentBlockScope::Shop,
))
.await
.unwrap_err();
client
.buyer_blocklist()
.preview_from_payment(&BuyerBlocklistFromPaymentPreviewRequest::new("pay_1"))
.await
.unwrap_err();
client
.buyer_blocklist()
.retry_sync("bbl_1")
.await
.unwrap_err();
client
.buyer_blocklist()
.update_radar_sync("mca_1", &RadarSyncSettingsUpdateRequest::new(true))
.await
.unwrap_err();
client
.buyer_blocklist()
.remove_radar_items("mca_1")
.await
.unwrap_err();
assert_eq!(mock.call_count(), 7);
for seen in mock.seen.lock().unwrap().iter() {
assert!(
!seen.had_idempotency_key(),
"{} sent the client key",
seen.url
);
}
}
}