mod fcm;
pub use fcm::{Fcm, FcmAccount};
use super::{Application, Message, Platform, Request, Target, apns::valid_bundle_id};
use crate::{Error, Result};
use jsonwebtoken::{Algorithm, EncodingKey, Header, crypto::CryptoProvider};
use serde::Serialize;
use std::{
fmt,
sync::{Arc, Mutex, PoisonError},
time::{Duration, SystemTime, UNIX_EPOCH},
};
const PRODUCTION: &str = "https://api.push.apple.com";
const SANDBOX: &str = "https://api.sandbox.push.apple.com";
const TOKEN_LIFETIME: Duration = Duration::from_secs(50 * 60);
const MAX_ID: usize = 64;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone)]
pub struct ApnsKey {
encoding: EncodingKey,
key_id: String,
team_id: String,
}
impl ApnsKey {
pub fn from_pem(
pem: impl AsRef<[u8]>,
key_id: impl Into<String>,
team_id: impl Into<String>,
) -> Result<Self> {
let refused = || Error::new("INVALID_INPUT", "The APNs key is not a P-256 key in PEM.");
let (key_id, team_id) = (key_id.into(), team_id.into());
if !valid_id(&key_id) || !valid_id(&team_id) {
return Err(Error::new(
"INVALID_INPUT",
"The key id and the team id are 1 to 64 letters and digits.",
));
}
let encoding = EncodingKey::from_ec_pem(pem.as_ref()).map_err(|_| refused())?;
let key = Self {
encoding,
key_id,
team_id,
};
key.sign().map_err(|_| refused())?;
Ok(key)
}
fn sign(&self) -> std::result::Result<String, jsonwebtoken::errors::Error> {
self.sign_at(SystemTime::now())
}
fn sign_at(&self, at: SystemTime) -> std::result::Result<String, jsonwebtoken::errors::Error> {
#[derive(Serialize)]
struct Claims<'a> {
iss: &'a str,
iat: u64,
}
crypto_provider();
let mut header = Header::new(Algorithm::ES256);
header.typ = None;
header.kid = Some(self.key_id.clone());
let iat = at
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
jsonwebtoken::encode(
&header,
&Claims {
iss: &self.team_id,
iat,
},
&self.encoding,
)
}
}
impl fmt::Debug for ApnsKey {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ApnsKey")
.field("key_id", &self.key_id)
.field("team_id", &self.team_id)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone)]
pub struct Apns {
key: ApnsKey,
bundle_id: String,
host: String,
}
impl Apns {
pub fn new(key: ApnsKey, bundle_id: impl Into<String>) -> Self {
Self {
key,
bundle_id: bundle_id.into(),
host: PRODUCTION.into(),
}
}
pub fn sandbox(self) -> Self {
self.host(SANDBOX)
}
pub fn host(self, url: impl Into<String>) -> Self {
Self {
host: url.into().trim_end_matches('/').to_owned(),
..self
}
}
pub fn host_url(&self) -> &str {
&self.host
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Delivery {
pub id: Option<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SendError {
#[error("the push was not sent: {0}")]
Invalid(Error),
#[error("the target is no longer registered")]
Unregistered,
#[error("the platform does not take the target: {reason}")]
BadTarget {
reason: String,
},
#[error("too many pushes")]
TooManyRequests {
retry_after: Option<Duration>,
},
#[error("the platform refused the push ({status}): {reason}")]
Rejected {
status: u16,
reason: String,
},
#[error("the platform is unavailable: {reason}")]
Unavailable {
status: Option<u16>,
reason: String,
},
}
#[derive(Clone)]
pub struct Sender {
shared: Arc<Shared>,
}
struct Shared {
client: reqwest::Client,
timeout: Duration,
apns: Option<ApnsSender>,
fcm: Option<fcm::FcmSender>,
}
struct ApnsSender {
apns: Apns,
token: Mutex<Option<(String, SystemTime)>>,
}
impl fmt::Debug for Sender {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Sender")
.field("apns", &self.shared.apns.as_ref().map(|apns| &apns.apns))
.field("fcm", &self.shared.fcm.as_ref().map(fcm::FcmSender::fcm))
.field("timeout", &self.shared.timeout)
.finish_non_exhaustive()
}
}
#[must_use]
#[derive(Debug, Default)]
pub struct SenderBuilder {
apns: Option<Apns>,
fcm: Option<Fcm>,
client: Option<reqwest::Client>,
timeout: Option<Duration>,
}
impl SenderBuilder {
pub fn apns(self, apns: Apns) -> Self {
Self {
apns: Some(apns),
..self
}
}
pub fn fcm(self, fcm: Fcm) -> Self {
Self {
fcm: Some(fcm),
..self
}
}
pub fn client(self, client: reqwest::Client) -> Self {
Self {
client: Some(client),
..self
}
}
pub fn timeout(self, timeout: Duration) -> Self {
Self {
timeout: Some(timeout),
..self
}
}
pub fn build(self) -> Result<Sender> {
if self.apns.is_none() && self.fcm.is_none() {
return Err(Error::new(
"INVALID_INPUT",
"A sender needs a platform to send to: give it APNs or FCM.",
));
}
if let Some(apns) = &self.apns {
if !valid_bundle_id(&apns.bundle_id) {
return Err(Error::new(
"INVALID_INPUT",
"The bundle id is letters, digits, `.` and `-`.",
));
}
if !web_host(&apns.host) {
return Err(Error::new(
"INVALID_INPUT",
"The APNs host is an https URL without a path.",
));
}
}
if let Some(fcm) = &self.fcm
&& !web_host(fcm.host_url())
{
return Err(Error::new(
"INVALID_INPUT",
"The FCM host is an https URL without a path.",
));
}
let client = match self.client {
Some(client) => client,
None => reqwest::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.build()
.map_err(|_| Error::native())?,
};
Ok(Sender {
shared: Arc::new(Shared {
client,
timeout: self.timeout.unwrap_or(DEFAULT_TIMEOUT),
apns: self.apns.map(|apns| ApnsSender {
apns,
token: Mutex::new(None),
}),
fcm: self.fcm.map(fcm::FcmSender::new),
}),
})
}
}
impl Sender {
pub fn builder() -> SenderBuilder {
SenderBuilder::default()
}
pub async fn send(
&self,
message: &Message,
target: &Target,
) -> std::result::Result<Delivery, SendError> {
match target.platform() {
Platform::Apns => {
let Some(apns) = &self.shared.apns else {
return Err(SendError::Invalid(Error::unsupported_feature(
"This sender was not given APNs.",
)));
};
let application = Application::new().bundle_id(apns.apns.bundle_id.clone());
let request = message
.request(target, &application)
.map_err(SendError::Invalid)?;
self.send_apns(apns, &request).await
}
Platform::Fcm => {
let Some(fcm) = &self.shared.fcm else {
return Err(SendError::Invalid(Error::unsupported_feature(
"This sender was not given FCM.",
)));
};
let application = Application::new().fcm_project(fcm.project());
let request = message
.request(target, &application)
.map_err(SendError::Invalid)?;
fcm.send(&self.shared.client, self.shared.timeout, &request)
.await
}
}
}
async fn send_apns(
&self,
apns: &ApnsSender,
request: &Request,
) -> std::result::Result<Delivery, SendError> {
let (first, token) = self.post(apns, request, None).await?;
let answer = if first.status == 403 && first.reason == "ExpiredProviderToken" {
self.post(apns, request, Some(&token)).await?.0
} else {
first
};
answer.outcome()
}
async fn post(
&self,
apns: &ApnsSender,
request: &Request,
expired: Option<&str>,
) -> std::result::Result<(Answer, String), SendError> {
let token = apns.token(expired)?;
let mut post = self
.shared
.client
.post(format!("{}{}", apns.apns.host, request.path))
.header(reqwest::header::AUTHORIZATION, bearer("bearer", &token)?)
.timeout(self.shared.timeout)
.body(request.body.clone());
for (name, value) in &request.headers {
post = post.header(*name, value);
}
let response = post.send().await.map_err(unreachable)?;
let status = response.status().as_u16();
let header = |name: &str| {
response
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
let id = header("apns-id").or_else(|| header("apns-request-id"));
let retry_after = header("retry-after")
.and_then(|seconds| seconds.trim().parse().ok())
.map(Duration::from_secs);
let text = response.text().await.unwrap_or_default();
let reason = serde_json::from_str::<serde_json::Value>(&text)
.ok()
.and_then(|body| body.get("reason")?.as_str().map(str::to_owned))
.unwrap_or_default();
Ok((
Answer {
status,
id,
retry_after,
reason,
},
token,
))
}
}
impl ApnsSender {
fn token(&self, expired: Option<&str>) -> std::result::Result<String, SendError> {
let mut held = self.token.lock().unwrap_or_else(PoisonError::into_inner);
let now = SystemTime::now();
if let Some((token, made)) = held.as_ref()
&& expired != Some(token.as_str())
&& now
.duration_since(*made)
.is_ok_and(|age| age < TOKEN_LIFETIME)
{
return Ok(token.clone());
}
let token = self.apns.key.sign_at(now).map_err(|_| {
SendError::Invalid(Error::new(
"INVALID_INPUT",
"The APNs key could not sign a provider token.",
))
})?;
*held = Some((token.clone(), now));
Ok(token)
}
}
struct Answer {
status: u16,
id: Option<String>,
retry_after: Option<Duration>,
reason: String,
}
impl Answer {
fn outcome(self) -> std::result::Result<Delivery, SendError> {
match self.status {
200 => Ok(Delivery { id: self.id }),
410 => Err(SendError::Unregistered),
400 if matches!(
self.reason.as_str(),
"BadDeviceToken" | "DeviceTokenNotForTopic" | "MissingDeviceToken"
) =>
{
Err(SendError::BadTarget {
reason: self.reason,
})
}
429 => Err(SendError::TooManyRequests {
retry_after: self.retry_after,
}),
500..=599 => Err(SendError::Unavailable {
status: Some(self.status),
reason: self.reason,
}),
status => Err(SendError::Rejected {
status,
reason: self.reason,
}),
}
}
}
fn crypto_provider() {
if CryptoProvider::try_get_default().is_none() {
let _ = jsonwebtoken::crypto::aws_lc::DEFAULT_PROVIDER.install_default();
}
}
fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= MAX_ID && id.bytes().all(|byte| byte.is_ascii_alphanumeric())
}
fn web_host(url: &str) -> bool {
reqwest::Url::parse(url).is_ok_and(|url| {
matches!(url.scheme(), "https" | "http") && url.has_host() && url.path() == "/"
})
}
fn unreachable(error: reqwest::Error) -> SendError {
if error.is_builder() {
SendError::Invalid(Error::new(
"INVALID_INPUT",
"The request could not be made: check the host.",
))
} else {
SendError::Unavailable {
status: None,
reason: if error.is_timeout() {
"the request timed out".into()
} else {
"the host could not be reached".into()
},
}
}
}
fn bearer(
scheme: &str,
token: &str,
) -> std::result::Result<reqwest::header::HeaderValue, SendError> {
let mut value = reqwest::header::HeaderValue::from_str(&format!("{scheme} {token}"))
.map_err(|_| SendError::Invalid(Error::native()))?;
value.set_sensitive(true);
Ok(value)
}
fn web_host_or_path(url: &str) -> bool {
reqwest::Url::parse(url)
.is_ok_and(|url| matches!(url.scheme(), "https" | "http") && url.has_host())
}