delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! The standalone 3-D Secure authentication model.

use serde::Deserialize;
use serde_json::Value;

use crate::core::models::common::Currency;

/// Lifecycle status of a 3DS authentication, e.g. `"started"`, `"success"`,
/// `"failed"`. A string rather than an enum so a new status does not break
/// deserialization.
pub type AuthenticationStatus = String;

/// A standalone 3-D Secure authentication as returned by the API.
///
/// Unmodeled fields are preserved in [`extra`](AuthenticationResponse::extra)
/// so new API fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthenticationResponse {
    /// Unique authentication ID.
    pub authentication_id: String,
    /// Merchant account that owns this authentication.
    pub merchant_id: String,
    /// Current lifecycle status.
    pub status: AuthenticationStatus,
    /// Amount being authenticated, in the currency's minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,

    /// Client secret for client-side completion of the challenge.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// 3DS connector the authentication was routed to.
    #[serde(default)]
    pub authentication_connector: Option<String>,
    /// Whether a challenge was forced rather than allowing a frictionless
    /// flow.
    #[serde(default)]
    pub force_3ds_challenge: Option<bool>,
    /// URL the customer is returned to after the challenge.
    #[serde(default)]
    pub return_url: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `client_secret` authorises client-side completion of this
// authentication, so it must never reach a log line through `{:?}`. The
// `Option` shape survives redaction so callers can still see whether one was
// issued. Pinned by `authentication_response_debug_redacts_the_client_secret`
// and its `None` companion.
impl std::fmt::Debug for AuthenticationResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthenticationResponse")
            .field("authentication_id", &self.authentication_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("authentication_connector", &self.authentication_connector)
            .field("force_3ds_challenge", &self.force_3ds_challenge)
            .field("return_url", &self.return_url)
            .field("extra", &self.extra)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn de(json: &str) -> AuthenticationResponse {
        serde_json::from_str(json).expect("fixture deserializes")
    }

    const BASE: &str = r#""authentication_id":"auth_1","merchant_id":"mer_1",
        "status":"started","amount":1000,"currency":"USD""#;

    #[test]
    fn authentication_response_debug_redacts_the_client_secret() {
        // Fails if the hand-written `Debug` is deleted (the derive would print
        // the secret) or if `client_secret` is rendered with `&self.x`.
        let res = de(&format!(
            r#"{{{BASE},"client_secret":"auth_1_secret_abc","return_url":"https://shop.example/r"}}"#
        ));
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("auth_1_secret_abc"), "{rendered}");
        assert!(rendered.contains("auth_1"), "{rendered}");
        assert!(rendered.contains("https://shop.example/r"), "{rendered}");
        assert!(rendered.contains("Some("), "{rendered}");
    }

    #[test]
    fn authentication_response_debug_shows_none_when_no_client_secret() {
        // Companion: catches an impl that always prints `Some("[redacted]")`.
        let res = de(&format!(r#"{{{BASE}}}"#));
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    #[test]
    fn authentication_response_keeps_unknown_fields_in_extra() {
        let res = de(&format!(r#"{{{BASE},"three_ds_server_id":"srv_9"}}"#));
        assert_eq!(res.amount, 1000);
        assert_eq!(res.currency, "USD");
        assert_eq!(res.extra["three_ds_server_id"], "srv_9");
        assert_eq!(res.force_3ds_challenge, None);
    }
}