delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Typed API credentials.
//!
//! DeloPay issues three credentials with genuinely different reach:
//!
//! | Credential | Prefix | Reach |
//! |---|---|---|
//! | [`SecretKey`] | `prd_` / `snd_` | every merchant route — server-side only |
//! | [`PublishableKey`] | `pk_prd_` / `pk_snd_` | the browser-safe checkout subset |
//! | [`ClientSecret`] | per payment | one payment, as a bearer token or parameter |
//!
//! They are separate types rather than three `&str` parameters so that
//! handing the wrong one to a call is a **compile error**, not a leak. A
//! [`crate::Delopay`] client takes a `SecretKey`; a
//! [`crate::CheckoutSession`] — the buyer-side client that runs where a
//! shopper can read it — takes a `PublishableKey` and a `ClientSecret` and
//! has no way to accept a secret key.
//!
//! `String` and `&str` convert into all three, because the value normally
//! arrives from an environment variable or a checkout payload. What does not
//! convert is one credential type into another.
//!
//! Lives in `core`, so a `default-features = false` build can still name the
//! types.

/// A secret API key (`prd_…` for production, `snd_…` for sandbox).
///
/// Server-side only. Never ship one to a browser or a mobile app — it
/// authenticates every merchant route, including refunds and payouts.
///
/// The prefix is **not** enforced: deployments front the API with proxies
/// that mint their own key formats, and rejecting an unfamiliar shape would
/// break them for no security gain (the server is the authority on whether a
/// key is valid). What the type buys is direction: a [`PublishableKey`]
/// cannot become a `SecretKey` by accident.
#[derive(Clone, PartialEq, Eq)]
pub struct SecretKey(String);

impl SecretKey {
    /// Wrap a key value.
    pub fn new(key: impl Into<String>) -> Self {
        Self(key.into())
    }

    /// The key as it goes on the wire.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper, returning the key value.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<String> for SecretKey {
    fn from(key: String) -> Self {
        Self(key)
    }
}

impl From<&str> for SecretKey {
    fn from(key: &str) -> Self {
        Self(key.to_string())
    }
}

// Hand-written: a derived `Debug` would print the key into any log line that
// formats a client, which is the leak this whole module exists to prevent.
impl std::fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("SecretKey(<redacted>)")
    }
}

/// A publishable, browser-safe API key (`pk_prd_…` / `pk_snd_…`).
///
/// Reaches only the checkout subset of the API, and only alongside a
/// [`ClientSecret`] that names the one payment being paid. This is the
/// credential a hosted checkout page may hold.
///
/// Unlike [`SecretKey`], the `pk_` prefix **is** enforced at construction —
/// see [`PublishableKey::new`]. The mistake being guarded against is putting
/// a secret key on a page, and a secret key is exactly what fails that check.
#[derive(Clone, PartialEq, Eq)]
pub struct PublishableKey(String);

impl PublishableKey {
    /// Wrap a publishable key, rejecting anything without the `pk_` prefix.
    ///
    /// ```
    /// use delopay::credentials::PublishableKey;
    ///
    /// assert!(PublishableKey::new("pk_snd_abc").is_ok());
    /// // A secret key cannot be smuggled into a browser-side credential.
    /// assert!(PublishableKey::new("snd_abc").is_err());
    /// ```
    ///
    /// # Errors
    ///
    /// [`crate::DelopayError::Config`] when the value does not start with
    /// `pk_`.
    pub fn new(key: impl Into<String>) -> crate::core::error::Result<Self> {
        let key = key.into();
        if !key.starts_with("pk_") {
            return Err(crate::core::error::DelopayError::Config(
                "a publishable key must start with `pk_` — a secret key must never reach a \
                 buyer-side client"
                    .to_string(),
            ));
        }
        Ok(Self(key))
    }

    /// The key as it goes on the wire.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper, returning the key value.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl std::str::FromStr for PublishableKey {
    type Err = crate::core::error::DelopayError;

    fn from_str(key: &str) -> Result<Self, Self::Err> {
        Self::new(key)
    }
}

impl TryFrom<String> for PublishableKey {
    type Error = crate::core::error::DelopayError;

    fn try_from(key: String) -> Result<Self, Self::Error> {
        Self::new(key)
    }
}

impl TryFrom<&str> for PublishableKey {
    type Error = crate::core::error::DelopayError;

    fn try_from(key: &str) -> Result<Self, Self::Error> {
        Self::new(key)
    }
}

// A publishable key is not a secret, but it is still an identifier worth
// keeping out of logs by default, and redacting all three credentials keeps
// the rule easy to remember.
impl std::fmt::Debug for PublishableKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("PublishableKey(<redacted>)")
    }
}

/// A payment's client secret, from the checkout payload.
///
/// Scoped to one payment: it authorises reading and confirming that payment
/// and nothing else. Travels as `Authorization: Bearer …` on the
/// `/payment-link/*` routes and as a `client_secret` parameter on the
/// publishable-key routes — never as an `api-key`.
#[derive(Clone, PartialEq, Eq)]
pub struct ClientSecret(String);

impl ClientSecret {
    /// Wrap a client secret.
    pub fn new(secret: impl Into<String>) -> Self {
        Self(secret.into())
    }

    /// The secret as it goes on the wire.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper, returning the secret value.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl From<String> for ClientSecret {
    fn from(secret: String) -> Self {
        Self(secret)
    }
}

impl From<&str> for ClientSecret {
    fn from(secret: &str) -> Self {
        Self(secret.to_string())
    }
}

impl std::fmt::Debug for ClientSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ClientSecret(<redacted>)")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::error::DelopayError;

    #[test]
    fn publishable_key_rejects_a_secret_key() {
        // Both live-key shapes, since either one on a checkout page is the
        // incident this check exists to stop.
        for secret in ["prd_live_abc", "snd_test_abc"] {
            match PublishableKey::new(secret).unwrap_err() {
                DelopayError::Config(msg) => assert!(msg.contains("pk_"), "unexpected: {msg}"),
                other => panic!("expected Config, got {other:?}"),
            }
        }
    }

    #[test]
    fn publishable_key_accepts_both_environments() {
        assert_eq!(
            PublishableKey::new("pk_prd_abc").unwrap().as_str(),
            "pk_prd_abc"
        );
        assert_eq!(
            PublishableKey::new("pk_snd_abc").unwrap().as_str(),
            "pk_snd_abc"
        );
    }

    #[test]
    fn publishable_key_parses_from_str() {
        let parsed: PublishableKey = "pk_snd_abc".parse().unwrap();
        assert_eq!(parsed.as_str(), "pk_snd_abc");
        assert!("snd_abc".parse::<PublishableKey>().is_err());
    }

    #[test]
    fn credentials_redact_in_debug() {
        // Each is asserted separately: a single shared helper would let one
        // type lose its impl without failing anything.
        assert_eq!(
            format!("{:?}", SecretKey::new("prd_supersecret")),
            "SecretKey(<redacted>)"
        );
        assert_eq!(
            format!("{:?}", PublishableKey::new("pk_snd_abc").unwrap()),
            "PublishableKey(<redacted>)"
        );
        assert_eq!(
            format!("{:?}", ClientSecret::new("pay_123_secret_xyz")),
            "ClientSecret(<redacted>)"
        );
    }

    #[test]
    fn debug_of_a_credential_never_contains_its_value() {
        let rendered = format!(
            "{:?} {:?} {:?}",
            SecretKey::new("prd_supersecret"),
            PublishableKey::new("pk_snd_visible").unwrap(),
            ClientSecret::new("cs_visible")
        );
        assert!(!rendered.contains("supersecret"));
        assert!(!rendered.contains("visible"));
    }
}