delopay 0.3.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The `three_ds_rules` resource: evaluate a 3-D Secure decision rule against
//! a payment context.
//!
//! The request context blocks and the response are open shapes — see the API
//! reference.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::to_json_vec;
use crate::core::error::{DelopayError, Result};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `three_ds_rules` resource, obtained via
/// [`crate::Delopay::three_ds_rules`].
#[derive(Debug, Clone)]
pub struct ThreeDsRules {
    inner: Arc<Inner>,
}

impl ThreeDsRules {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Execute a 3-D Secure decision rule
    /// (`POST /three-ds-decision/execute`), returning the decision the rule
    /// produced for the supplied context.
    pub async fn execute(&self, params: &ThreeDsRuleExecuteRequest) -> Result<Value> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/three-ds-decision/execute",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// Parameters for [`ThreeDsRules::execute`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ThreeDsRuleExecuteRequest {
    /// ID of the routing configuration holding the 3-D Secure decision rule.
    pub routing_id: String,
    /// The payment context to evaluate (open shape — see the API reference).
    pub payment: Value,
    /// Payment method context (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<Value>,
    /// Customer device context (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_device: Option<Value>,
    /// Issuer context (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer: Option<Value>,
    /// Acquirer context (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acquirer: Option<Value>,
    /// Any additional fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `ThreeDsRuleExecuteRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const THREE_DS_RULE_EXECUTE_REQUEST_NAMED: &[&str] = &[
    "routing_id",
    "payment",
    "payment_method",
    "customer_device",
    "issuer",
    "acquirer",
];

impl ValidateRequest for ThreeDsRuleExecuteRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if THREE_DS_RULE_EXECUTE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on ThreeDsRuleExecuteRequest"
                )));
            }
        }
        Ok(())
    }
}

impl ThreeDsRuleExecuteRequest {
    /// A request evaluating `routing_id`'s rule against `payment`.
    pub fn new(routing_id: impl Into<String>, payment: Value) -> Self {
        Self {
            routing_id: routing_id.into(),
            payment,
            ..Default::default()
        }
    }

    /// Set the payment method context.
    pub fn payment_method(mut self, payment_method: Value) -> Self {
        self.payment_method = Some(payment_method);
        self
    }

    /// Set the customer device context.
    pub fn customer_device(mut self, customer_device: Value) -> Self {
        self.customer_device = Some(customer_device);
        self
    }

    /// Set the issuer context.
    pub fn issuer(mut self, issuer: Value) -> Self {
        self.issuer = Some(issuer);
        self
    }

    /// Set the acquirer context.
    pub fn acquirer(mut self, acquirer: Value) -> Self {
        self.acquirer = Some(acquirer);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};
    use serde_json::json;

    #[tokio::test]
    async fn execute_posts_the_context_to_the_decision_path() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"decision":"challenge"}"#)]);
        let req =
            ThreeDsRuleExecuteRequest::new("rou_1", json!({"amount": 1000, "currency": "EUR"}))
                .payment_method(json!({"payment_method": "card"}))
                .customer_device(json!({"platform": "web"}))
                .issuer(json!({"name": "issuer_bank"}))
                .acquirer(json!({"country": "DE"}));
        let out = client.three_ds_rules().execute(&req).await.unwrap();
        assert_eq!(out["decision"], "challenge");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/three-ds-decision/execute");
        let body = seen[0].body_json();
        assert_eq!(body["routing_id"], "rou_1");
        assert_eq!(body["payment"]["currency"], "EUR");
        assert_eq!(body["payment_method"]["payment_method"], "card");
        assert_eq!(body["customer_device"]["platform"], "web");
        assert_eq!(body["issuer"]["name"], "issuer_bank");
        assert_eq!(body["acquirer"]["country"], "DE");
    }

    #[tokio::test]
    async fn execute_omits_absent_context_blocks() {
        // Companion to the test above: without it, an impl that always sent
        // every block (as `null`) would still pass.
        let (client, mock) = client_with(vec![Step::ok(r#"{"decision":"no_three_ds"}"#)]);
        let req = ThreeDsRuleExecuteRequest::new("rou_1", json!({"amount": 1000}));
        client.three_ds_rules().execute(&req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].body_json(),
            json!({"routing_id": "rou_1", "payment": {"amount": 1000}})
        );
    }

    /// Drift guard for `THREE_DS_RULE_EXECUTE_REQUEST_NAMED`.
    #[test]
    fn three_ds_rule_execute_request_named_fields_are_complete() {
        let req = ThreeDsRuleExecuteRequest::new("rou_1", json!({}))
            .payment_method(json!({}))
            .customer_device(json!({}))
            .issuer(json!({}))
            .acquirer(json!({}));
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                THREE_DS_RULE_EXECUTE_REQUEST_NAMED.contains(&key.as_str()),
                "THREE_DS_RULE_EXECUTE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = ThreeDsRuleExecuteRequest::new("rou_1", json!({}));
        req.extra.insert("payment".to_string(), json!({}));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("payment")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}