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/";
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct GravatarId(String);
impl GravatarId {
#[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))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[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])")
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct Profile {
hash: String,
display_name: String,
profile_url: String,
avatar_url: String,
}
impl Profile {
#[must_use]
pub fn id(&self) -> &str {
&self.hash
}
#[must_use]
pub fn display_name(&self) -> &str {
&self.display_name
}
#[must_use]
pub fn profile_url(&self) -> &str {
&self.profile_url
}
#[must_use]
pub fn avatar_url(&self) -> &str {
&self.avatar_url
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProfileUnavailable {
Transport,
Authentication,
RateLimited {
retry_after: Option<std::time::Duration>,
},
Provider,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProfileStatus {
Found(Profile),
NotFound,
Unavailable(ProfileUnavailable),
}
#[derive(Clone)]
pub struct GravatarClient {
http: tez::Client,
}
impl GravatarClient {
pub fn new() -> Result<Self, GravatarClientError> {
Self::build(None)
}
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 })
}
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()
}
}
#[derive(Clone, Copy, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GravatarClientError {
#[error("Gravatar client configuration is invalid: {0}")]
Configuration(&'static str),
#[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)
);
}
}