pata 0.0.1

A fast, lightweight, and evidence-driven email validation library for Rust
Documentation
//! Explicit Gravatar profile enrichment.
//!
//! Profile lookup is separate from validation: its presence does not prove
//! mailbox ownership or deliverability. A lookup discloses a deterministic
//! hash of the address to Gravatar.

use std::fmt;

use serde::Deserialize;
use sha2::{Digest as _, Sha256};

use crate::Address;

const PROFILE_BASE: &str = "https://api.gravatar.com/v3/profiles/";
const AVATAR_BASE: &str = "https://gravatar.com/avatar/";

/// The normalized SHA-256 identifier used by Gravatar.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct GravatarId(String);

impl GravatarId {
    /// Derives an identifier using Gravatar's trim-and-lowercase rule.
    #[must_use]
    pub fn new(address: &Address) -> Self {
        let normalized = address.to_string().trim().to_lowercase();
        let digest = Sha256::digest(normalized.as_bytes());
        Self(hex(&digest))
    }

    /// Returns the lowercase hexadecimal identifier.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the canonical avatar URL without making a request.
    #[must_use]
    pub fn avatar_url(&self) -> String {
        format!("{AVATAR_BASE}{}", self.0)
    }
}

impl fmt::Debug for GravatarId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("GravatarId([redacted])")
    }
}

/// Public profile fields returned by Gravatar.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct Profile {
    hash: String,
    display_name: String,
    profile_url: String,
    avatar_url: String,
}

impl Profile {
    /// Returns the identifier reported by Gravatar.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.hash
    }

    /// Returns the profile's display name.
    #[must_use]
    pub fn display_name(&self) -> &str {
        &self.display_name
    }

    /// Returns the public profile URL.
    #[must_use]
    pub fn profile_url(&self) -> &str {
        &self.profile_url
    }

    /// Returns the public avatar URL.
    #[must_use]
    pub fn avatar_url(&self) -> &str {
        &self.avatar_url
    }
}

/// Why a profile lookup could not produce a profile or authoritative absence.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProfileUnavailable {
    /// The request could not be completed.
    Transport,
    /// Gravatar rejected the configured credentials.
    Authentication,
    /// Gravatar rate-limited the request.
    RateLimited {
        /// The provider's requested delay when it supplied whole seconds.
        retry_after: Option<std::time::Duration>,
    },
    /// Gravatar returned an unexpected response.
    Provider,
}

/// The semantic result of an explicit Gravatar lookup.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProfileStatus {
    /// A public profile was returned.
    Found(Profile),
    /// Gravatar authoritatively reported no profile.
    NotFound,
    /// The provider could not answer authoritatively.
    Unavailable(ProfileUnavailable),
}

/// A bounded, runtime-neutral Gravatar profile client.
///
/// A response larger than 256 KiB produces a provider-unavailable result.
#[derive(Clone)]
pub struct GravatarClient {
    http: tez::Client,
}

impl GravatarClient {
    /// Builds a client without authentication.
    pub fn new() -> Result<Self, GravatarClientError> {
        Self::build(None)
    }

    /// Builds a client with a Gravatar API token.
    pub fn with_token(token: impl AsRef<str>) -> Result<Self, GravatarClientError> {
        let authentication =
            tez::auth::BearerAuth::new(secrecy::SecretString::from(token.as_ref().to_owned()))
                .map_err(|_| {
                    GravatarClientError::Configuration("Gravatar access token is invalid")
                })?;
        Self::build(Some(authentication))
    }

    fn build(authentication: Option<tez::auth::BearerAuth>) -> Result<Self, GravatarClientError> {
        let http = tez::Client::builder()
            .user_agent(concat!("pata/", env!("CARGO_PKG_VERSION")))
            .timeout(std::time::Duration::from_secs(10));
        let http = match authentication {
            Some(authentication) => http.auth(authentication),
            None => http,
        }
        .build()
        .map_err(|_| GravatarClientError::Initialization)?;
        Ok(Self { http })
    }

    /// Looks up the public profile associated with `address`.
    pub async fn lookup(&self, address: &Address) -> ProfileStatus {
        let id = GravatarId::new(address);
        let response = self
            .http
            .get(format!("{PROFILE_BASE}{}", id.as_str()))
            .send()
            .await;
        let response = match response {
            Ok(response) => response,
            Err(_) => return ProfileStatus::Unavailable(ProfileUnavailable::Transport),
        };

        match response.status().as_u16() {
            200 => match crate::provider_response::json::<Profile>(response, 256 * 1024).await {
                Ok(profile) => profile_status(profile, &id),
                Err(_) => ProfileStatus::Unavailable(ProfileUnavailable::Provider),
            },
            status => response_status(status, crate::provider_response::retry_after(&response)),
        }
    }
}

fn response_status(status: u16, retry_after: Option<std::time::Duration>) -> ProfileStatus {
    match status {
        404 => ProfileStatus::NotFound,
        401 | 403 => ProfileStatus::Unavailable(ProfileUnavailable::Authentication),
        429 => ProfileStatus::Unavailable(ProfileUnavailable::RateLimited { retry_after }),
        _ => ProfileStatus::Unavailable(ProfileUnavailable::Provider),
    }
}

fn profile_status(profile: Profile, expected: &GravatarId) -> ProfileStatus {
    if profile.hash.eq_ignore_ascii_case(expected.as_str()) {
        ProfileStatus::Found(profile)
    } else {
        ProfileStatus::Unavailable(ProfileUnavailable::Provider)
    }
}

impl fmt::Debug for GravatarClient {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GravatarClient")
            .finish_non_exhaustive()
    }
}

/// A Gravatar client construction failure.
#[derive(Clone, Copy, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GravatarClientError {
    /// A caller-supplied setting is invalid.
    #[error("Gravatar client configuration is invalid: {0}")]
    Configuration(&'static str),
    /// The private HTTP capability could not be initialized.
    #[error("Gravatar HTTP client could not be initialized")]
    Initialization,
}

fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(DIGITS[usize::from(byte >> 4)]));
        output.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
    }
    output
}

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

    #[test]
    fn identifier_matches_gravatar_normalization() {
        let address = Address::parse("MyEmailAddress@example.com").unwrap();
        assert_eq!(
            GravatarId::new(&address).as_str(),
            "84059b07d4be67b806386c0aad8070a23f18836bbaae342275dc0a83414c32ee"
        );
    }

    #[test]
    fn debug_redacts_identifier_and_credentials() {
        let id = GravatarId::new(&Address::parse("private@example.com").unwrap());
        assert!(!format!("{id:?}").contains(id.as_str()));

        let client = GravatarClient::with_token("private-token").unwrap();
        assert!(!format!("{client:?}").contains("private-token"));
    }

    #[test]
    fn client_does_not_require_authentication() {
        GravatarClient::new().unwrap();
    }

    #[test]
    fn profile_decodes_the_provider_field_names() {
        let profile: Profile = serde_json::from_str(
            r#"{
                "hash": "abc123",
                "display_name": "Maya",
                "profile_url": "https://gravatar.com/maya",
                "avatar_url": "https://gravatar.com/avatar/abc123"
            }"#,
        )
        .unwrap();

        assert_eq!(profile.id(), "abc123");
        assert_eq!(profile.display_name(), "Maya");
    }

    #[test]
    fn profile_identity_must_match_the_requested_hash() {
        let address = Address::parse("maya@example.com").unwrap();
        let expected = GravatarId::new(&address);
        let matching: Profile = serde_json::from_str(&format!(
            r#"{{
                "hash": "{}",
                "display_name": "Maya",
                "profile_url": "https://gravatar.com/maya",
                "avatar_url": "https://gravatar.com/avatar/{}"
            }}"#,
            expected.as_str(),
            expected.as_str()
        ))
        .unwrap();
        let mismatched = Profile {
            hash: "different".to_owned(),
            ..matching.clone()
        };

        assert!(matches!(
            profile_status(matching, &expected),
            ProfileStatus::Found(_)
        ));
        assert_eq!(
            profile_status(mismatched, &expected),
            ProfileStatus::Unavailable(ProfileUnavailable::Provider)
        );
    }

    #[test]
    fn response_statuses_preserve_provider_meaning() {
        let retry_after = Some(std::time::Duration::from_secs(30));

        assert_eq!(response_status(404, None), ProfileStatus::NotFound);
        assert_eq!(
            response_status(401, None),
            ProfileStatus::Unavailable(ProfileUnavailable::Authentication)
        );
        assert_eq!(
            response_status(403, None),
            ProfileStatus::Unavailable(ProfileUnavailable::Authentication)
        );
        assert_eq!(
            response_status(429, retry_after),
            ProfileStatus::Unavailable(ProfileUnavailable::RateLimited { retry_after })
        );
        assert_eq!(
            response_status(500, None),
            ProfileStatus::Unavailable(ProfileUnavailable::Provider)
        );
    }
}