use jsonwebtoken::{Algorithm, EncodingKey, Header};
use sea_orm::entity::prelude::*;
use sea_orm::{
ActiveValue::Set, ColumnTrait, Condition, ConnectionTrait, DatabaseConnection, DbBackend,
DbErr, EntityTrait, QueryFilter, Schema, sea_query::Expr,
};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
const MAX_PAYLOAD: usize = 4096;
const MAX_TRIES: u32 = 3;
const MAX_CONCURRENCY: usize = 16;
const TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, thiserror::Error)]
pub enum PushError {
#[error("database: {0}")]
Db(#[from] DbErr),
#[error("invalid input: {0}")]
Invalid(String),
#[error("payload: {0}")]
Payload(String),
#[error("push config: {0}")]
Config(String),
#[error("provider answered {status}: {detail}")]
Provider {
status: u16,
detail: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
Ios,
Android,
}
impl Platform {
pub fn as_str(self) -> &'static str {
match self {
Platform::Ios => "ios",
Platform::Android => "android",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"ios" => Some(Platform::Ios),
"android" => Some(Platform::Android),
_ => None,
}
}
}
pub mod push_devices {
use sea_orm::entity::prelude::*;
#[derive(Clone, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "push_devices")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(indexed)]
pub user_id: i64,
pub platform: String,
#[sea_orm(column_type = "Text")]
pub token: String,
#[sea_orm(unique)]
pub token_hash: String,
pub app_id: Option<String>,
pub name: Option<String>,
pub created_at: i64,
pub last_seen_at: i64,
pub invalid_at: Option<i64>,
}
impl std::fmt::Debug for Model {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("push_devices::Model")
.field("id", &self.id)
.field("user_id", &self.user_id)
.field("platform", &self.platform)
.field("token", &"<redacted>")
.finish_non_exhaustive()
}
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
use push_devices::{Column, Entity};
#[derive(Clone, PartialEq)]
pub struct Device {
pub id: i64,
pub user_id: i64,
pub platform: Platform,
pub token: String,
pub app_id: Option<String>,
}
impl std::fmt::Debug for Device {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Device")
.field("id", &self.id)
.field("user_id", &self.user_id)
.field("platform", &self.platform)
.field("token", &"<redacted>")
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceInfo {
pub id: i64,
pub user_id: i64,
pub platform: Platform,
pub app_id: Option<String>,
pub name: Option<String>,
pub created_at: i64,
pub last_seen_at: i64,
pub invalid_at: Option<i64>,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn platform_of(s: &str) -> Platform {
Platform::parse(s).unwrap_or(Platform::Android)
}
fn info(m: push_devices::Model) -> DeviceInfo {
DeviceInfo {
id: m.id,
user_id: m.user_id,
platform: platform_of(&m.platform),
app_id: m.app_id,
name: m.name,
created_at: m.created_at,
last_seen_at: m.last_seen_at,
invalid_at: m.invalid_at,
}
}
fn sha256_hex(data: &[u8]) -> String {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let mut msg = data.to_vec();
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
for block in msg.chunks(64) {
let mut w = [0u32; 64];
for (i, c) in block.chunks(4).enumerate() {
w[i] = u32::from_be_bytes([c[0], c[1], c[2], c[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut v = h;
for i in 0..64 {
let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
let t1 = v[7]
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
let t2 = s0.wrapping_add(maj);
v = [
t1.wrapping_add(t2),
v[0],
v[1],
v[2],
v[3].wrapping_add(t1),
v[4],
v[5],
v[6],
];
}
for (a, b) in h.iter_mut().zip(v) {
*a = a.wrapping_add(b);
}
}
h.iter().map(|x| format!("{x:08x}")).collect()
}
fn token_hash(p: Platform, token: &str) -> String {
sha256_hex(format!("{}:{token}", p.as_str()).as_bytes())
}
#[derive(Clone)]
pub struct Devices {
db: DatabaseConnection,
max_per_user: usize,
}
pub const MAX_DEVICES_PER_USER: usize = 20;
impl Devices {
pub fn new(db: DatabaseConnection) -> Self {
Self {
db,
max_per_user: MAX_DEVICES_PER_USER,
}
}
pub fn max_per_user(mut self, n: usize) -> Self {
self.max_per_user = n.max(1);
self
}
async fn evict(&self, user_id: i64, keep: i64) -> Result<(), PushError> {
use sea_orm::QueryOrder;
let stale = Entity::find()
.filter(Column::UserId.eq(user_id))
.order_by_desc(Column::LastSeenAt)
.order_by_desc(Column::Id)
.all(&self.db)
.await?;
let extra = stale
.into_iter()
.filter(|d| d.id != keep)
.skip(self.max_per_user - 1);
let ids: Vec<i64> = extra.map(|d| d.id).collect();
if !ids.is_empty() {
Entity::delete_many()
.filter(Column::Id.is_in(ids))
.exec(&self.db)
.await?;
}
Ok(())
}
pub async fn ensure_tables(&self) -> Result<(), PushError> {
let b = self.db.get_database_backend();
let schema = Schema::new(b);
if b == DbBackend::MySql {
let mut t = schema.create_table_with_index_from_entity(Entity);
self.db.execute(t.if_not_exists()).await?;
} else {
let mut t = schema.create_table_from_entity(Entity);
self.db.execute(t.if_not_exists()).await?;
for mut i in schema.create_index_from_entity(Entity) {
self.db.execute(i.if_not_exists()).await?;
}
}
Ok(())
}
pub async fn register(
&self,
user_id: i64,
platform: Platform,
token: &str,
app_id: Option<&str>,
name: Option<&str>,
) -> Result<DeviceInfo, PushError> {
let bad = |m: &str| Err(PushError::Invalid(m.into()));
if !(8..=4096).contains(&token.chars().count()) || token.chars().any(char::is_whitespace) {
return bad("token must be 8..=4096 characters without whitespace");
}
if platform == Platform::Ios && !token.chars().all(|c| c.is_ascii_alphanumeric()) {
return bad("an iOS token is alphanumeric (hex)");
}
if name.is_some_and(|n| n.chars().count() > 100) {
return bad("name is at most 100 characters");
}
if app_id.is_some_and(|a| a.chars().count() > 200) {
return bad("app_id is at most 200 characters");
}
let h = token_hash(platform, token);
let t = now();
let mut insert_err = None;
for _ in 0..2 {
if let Some(row) = Entity::find()
.filter(Column::TokenHash.eq(h.as_str()))
.one(&self.db)
.await?
{
Entity::update_many()
.col_expr(Column::UserId, Expr::value(user_id))
.col_expr(Column::AppId, Expr::value(app_id.map(String::from)))
.col_expr(Column::Name, Expr::value(name.map(String::from)))
.col_expr(Column::LastSeenAt, Expr::value(t))
.col_expr(Column::InvalidAt, Expr::value(None::<i64>))
.filter(Column::Id.eq(row.id))
.exec(&self.db)
.await?;
self.evict(user_id, row.id).await?;
let row = Entity::find_by_id(row.id).one(&self.db).await?;
return row
.map(info)
.ok_or_else(|| PushError::Invalid("device vanished".into()));
}
match (push_devices::ActiveModel {
user_id: Set(user_id),
platform: Set(platform.as_str().into()),
token: Set(token.into()),
token_hash: Set(h.clone()),
app_id: Set(app_id.map(String::from)),
name: Set(name.map(String::from)),
created_at: Set(t),
last_seen_at: Set(t),
invalid_at: Set(None),
..Default::default()
})
.insert(&self.db)
.await
{
Ok(m) => {
self.evict(user_id, m.id).await?;
return Ok(info(m));
}
Err(e) => insert_err = Some(e),
}
}
Err(insert_err.map(PushError::Db).unwrap())
}
pub async fn list(&self, user_id: i64) -> Result<Vec<DeviceInfo>, PushError> {
use sea_orm::QueryOrder;
Ok(Entity::find()
.filter(Column::UserId.eq(user_id))
.order_by_desc(Column::Id)
.all(&self.db)
.await?
.into_iter()
.map(info)
.collect())
}
pub async fn unregister(&self, user_id: i64, id: i64) -> Result<bool, PushError> {
let q = || {
Entity::delete_many()
.filter(Column::Id.eq(id))
.filter(Column::UserId.eq(user_id))
};
let exists = Entity::find()
.filter(Column::Id.eq(id))
.filter(Column::UserId.eq(user_id))
.one(&self.db)
.await?
.is_some();
q().exec(&self.db).await?;
Ok(exists)
}
pub async fn mark_invalid(&self, platform: Platform, token: &str) -> Result<(), PushError> {
Entity::update_many()
.col_expr(Column::InvalidAt, Expr::value(now()))
.filter(Column::TokenHash.eq(token_hash(platform, token)))
.exec(&self.db)
.await?;
Ok(())
}
pub async fn valid_for_user(&self, user_id: i64) -> Result<Vec<Device>, PushError> {
Ok(Entity::find()
.filter(Column::UserId.eq(user_id))
.filter(Column::InvalidAt.is_null())
.all(&self.db)
.await?
.into_iter()
.map(|m| Device {
id: m.id,
user_id: m.user_id,
platform: platform_of(&m.platform),
token: m.token,
app_id: m.app_id,
})
.collect())
}
pub async fn prune(
&self,
invalid_older_than: Duration,
idle_older_than: Duration,
) -> Result<u64, PushError> {
let cut = |d: Duration| now().saturating_sub(d.as_secs().min(i64::MAX as u64 / 2) as i64);
Ok(Entity::delete_many()
.filter(
Condition::any()
.add(Column::InvalidAt.lt(cut(invalid_older_than)))
.add(Column::LastSeenAt.lt(cut(idle_older_than))),
)
.exec(&self.db)
.await?
.rows_affected)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
High,
Normal,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Notification {
title: Option<String>,
body: Option<String>,
data: BTreeMap<String, String>,
badge: Option<u32>,
sound: Option<String>,
collapse_key: Option<String>,
ttl: Option<Duration>,
priority: Priority,
content_available: bool,
}
impl Default for Notification {
fn default() -> Self {
Self {
title: None,
body: None,
data: BTreeMap::new(),
badge: None,
sound: None,
collapse_key: None,
ttl: None,
priority: Priority::High,
content_available: false,
}
}
}
impl Notification {
pub fn new() -> Self {
Self::default()
}
pub fn title(mut self, s: impl Into<String>) -> Self {
self.title = Some(s.into());
self
}
pub fn body(mut self, s: impl Into<String>) -> Self {
self.body = Some(s.into());
self
}
pub fn data(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
self.data.insert(k.into(), v.into());
self
}
pub fn badge(mut self, n: u32) -> Self {
self.badge = Some(n);
self
}
pub fn sound(mut self, s: impl Into<String>) -> Self {
self.sound = Some(s.into());
self
}
pub fn collapse_key(mut self, s: impl Into<String>) -> Self {
self.collapse_key = Some(s.into());
self
}
pub fn ttl(mut self, d: Duration) -> Self {
self.ttl = Some(d);
self
}
pub fn priority(mut self, p: Priority) -> Self {
self.priority = p;
self
}
pub fn content_available(mut self) -> Self {
self.content_available = true;
self
}
fn silent(&self) -> bool {
self.title.is_none() && self.body.is_none()
}
fn validate(&self) -> Result<(), PushError> {
let bad = |m: &str| Err(PushError::Payload(m.into()));
if self.silent() && !self.content_available {
return bad("a notification needs a title, a body or content_available");
}
if self.data.keys().any(|k| k.is_empty() || k == "aps") {
return bad("data keys must be non-empty and not `aps`");
}
if self.collapse_key.as_ref().is_some_and(|c| c.len() > 64) {
return bad("collapse_key is at most 64 bytes");
}
Ok(())
}
fn fcm_message(&self, token: &str) -> Value {
let mut m = json!({ "token": token });
if !self.data.is_empty() {
m["data"] = json!(self.data);
}
if !self.silent() {
let mut n = json!({});
if let Some(t) = &self.title {
n["title"] = json!(t);
}
if let Some(b) = &self.body {
n["body"] = json!(b);
}
m["notification"] = n;
}
let high = self.priority == Priority::High || self.content_available;
let mut a = json!({ "priority": if high { "HIGH" } else { "NORMAL" } });
if let Some(t) = self.ttl {
a["ttl"] = json!(format!("{}s", t.as_secs()));
}
if let Some(c) = &self.collapse_key {
a["collapse_key"] = json!(c);
}
if let Some(s) = &self.sound {
a["notification"] = json!({ "sound": s });
}
m["android"] = a;
json!({ "message": m })
}
fn apns_body(&self) -> Value {
let mut aps = json!({});
if !self.silent() {
let mut alert = json!({});
if let Some(t) = &self.title {
alert["title"] = json!(t);
}
if let Some(b) = &self.body {
alert["body"] = json!(b);
}
aps["alert"] = alert;
}
if let Some(b) = self.badge {
aps["badge"] = json!(b);
}
if let Some(s) = &self.sound {
aps["sound"] = json!(s);
}
if self.content_available {
aps["content-available"] = json!(1);
}
let mut v = json!({ "aps": aps });
for (k, val) in &self.data {
v[k] = json!(val);
}
v
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Delivery {
Sent,
Invalid,
Transient(String),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SendReport {
pub sent: usize,
pub failed: usize,
pub invalidated: usize,
}
fn check_url(u: &str, what: &str, allow_http: bool) -> Result<(), PushError> {
if allow_http || u.starts_with("https://") {
Ok(())
} else {
Err(PushError::Config(format!("{what} must be an https:// URL")))
}
}
fn http(prior_h2: bool) -> reqwest::Client {
let mut b = reqwest::Client::builder()
.timeout(TIMEOUT)
.connect_timeout(TIMEOUT)
.redirect(reqwest::redirect::Policy::none());
if prior_h2 {
b = b.http2_prior_knowledge();
}
b.build().expect("reqwest client")
}
fn truncate(s: &str) -> String {
s.chars().take(200).collect()
}
enum Step {
Done(Delivery),
Retry(Option<Duration>, String),
Reauth,
Fail(PushError),
}
fn retry_after(r: &reqwest::Response) -> Option<Duration> {
r.headers()
.get("retry-after")?
.to_str()
.ok()?
.trim()
.parse::<u64>()
.ok()
.map(Duration::from_secs)
}
fn net_err(e: reqwest::Error) -> Step {
Step::Retry(None, format!("network: {}", e.without_url()))
}
async fn retrying<F, Fut>(base: Duration, mut attempt: F) -> Result<Delivery, PushError>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Step>,
{
let (mut tries, mut reauthed) = (0u32, false);
loop {
match attempt().await {
Step::Done(d) => return Ok(d),
Step::Fail(e) => return Err(e),
Step::Reauth if !reauthed => reauthed = true,
Step::Reauth => {
return Err(PushError::Provider {
status: 401,
detail: "credentials rejected after refresh".into(),
});
}
Step::Retry(wait, why) => {
tries += 1;
if tries >= MAX_TRIES {
return Ok(Delivery::Transient(why));
}
let jitter = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos() % 250)
.unwrap_or(0) as u64;
let backoff = base * 2u32.pow(tries - 1) + Duration::from_millis(jitter) / 10;
let sleep = wait.map_or(backoff, |w| w.max(backoff));
tokio::time::sleep(sleep.min(Duration::from_secs(30))).await;
}
}
}
}
#[derive(Clone)]
pub struct Fcm {
project_id: String,
client_email: String,
key: Arc<EncodingKey>,
token_uri: String,
endpoint: String,
http: reqwest::Client,
token: Arc<tokio::sync::Mutex<Option<(String, Instant)>>>,
backoff: Duration,
}
impl std::fmt::Debug for Fcm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Fcm")
.field("project_id", &self.project_id)
.field("client_email", &self.client_email)
.finish_non_exhaustive()
}
}
impl Fcm {
pub fn new(project_id: &str, service_account_json: &str) -> Result<Self, PushError> {
#[derive(serde::Deserialize)]
struct Sa {
client_email: String,
private_key: String,
token_uri: String,
#[serde(default)]
project_id: String,
}
let sa: Sa = serde_json::from_str(service_account_json)
.map_err(|_| PushError::Config("FCM service account JSON is invalid".into()))?;
check_url(&sa.token_uri, "FCM token_uri", cfg!(test))?;
let project_id = if project_id.is_empty() {
sa.project_id
} else {
project_id.into()
};
if project_id.is_empty()
|| !project_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ':' || c == '.')
{
return Err(PushError::Config(
"FCM project id missing or invalid".into(),
));
}
let key = EncodingKey::from_rsa_pem(sa.private_key.as_bytes())
.map_err(|_| PushError::Config("FCM private_key is not a valid RSA PEM".into()))?;
Ok(Self {
project_id,
client_email: sa.client_email,
key: Arc::new(key),
token_uri: sa.token_uri,
endpoint: "https://fcm.googleapis.com".into(),
http: http(false),
token: Default::default(),
backoff: Duration::from_millis(500),
})
}
#[cfg(test)]
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))] fn for_test(mut self, base: &str) -> Self {
self.token_uri = format!("{base}/token");
self.endpoint = base.into();
self.backoff = Duration::from_millis(5);
self
}
async fn access_token(&self) -> Result<String, Step> {
let mut g = self.token.lock().await;
if let Some((t, exp)) = g.as_ref()
&& Instant::now() < *exp
{
return Ok(t.clone());
}
let iat = now();
let claims = json!({
"iss": self.client_email,
"scope": "https://www.googleapis.com/auth/firebase.messaging",
"aud": self.token_uri, "iat": iat, "exp": iat + 3600,
});
let jwt = jsonwebtoken::encode(&Header::new(Algorithm::RS256), &claims, &self.key)
.map_err(|_| Step::Fail(PushError::Config("FCM JWT signing failed".into())))?;
let r = self
.http
.post(&self.token_uri)
.header("content-type", "application/x-www-form-urlencoded")
.body(format!(
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={jwt}"
))
.send()
.await
.map_err(net_err)?;
let st = r.status();
let ra = retry_after(&r);
if !st.is_success() {
let body = truncate(&r.text().await.unwrap_or_default());
return Err(if st.as_u16() == 429 || st.is_server_error() {
Step::Retry(ra, format!("FCM token endpoint {st}"))
} else {
Step::Fail(PushError::Provider {
status: st.as_u16(),
detail: format!("token endpoint: {body}"),
})
});
}
#[derive(serde::Deserialize)]
struct Tok {
access_token: String,
#[serde(default = "d3600")]
expires_in: u64,
}
fn d3600() -> u64 {
3600
}
let t: Tok = r.json().await.map_err(|_| {
Step::Fail(PushError::Provider {
status: 200,
detail: "token endpoint returned unexpected JSON".into(),
})
})?;
let exp = Instant::now() + Duration::from_secs(t.expires_in.saturating_sub(60));
*g = Some((t.access_token.clone(), exp));
Ok(t.access_token)
}
async fn send(&self, token: &str, n: &Notification) -> Result<Delivery, PushError> {
let body = serde_json::to_vec(&n.fcm_message(token)).expect("json");
if body.len() > MAX_PAYLOAD {
return Err(PushError::Payload("FCM payload exceeds 4096 bytes".into()));
}
let url = format!(
"{}/v1/projects/{}/messages:send",
self.endpoint, self.project_id
);
retrying(self.backoff, || async {
let at = match self.access_token().await {
Ok(t) => t,
Err(s) => return s,
};
let r = match self
.http
.post(&url)
.bearer_auth(at)
.header("content-type", "application/json")
.body(body.clone())
.send()
.await
{
Ok(r) => r,
Err(e) => return net_err(e),
};
let st = r.status().as_u16();
let ra = retry_after(&r);
let text = r.text().await.unwrap_or_default();
match st {
200..=299 => Step::Done(Delivery::Sent),
401 => {
*self.token.lock().await = None;
Step::Reauth
}
404 => Step::Done(Delivery::Invalid),
400 if text.contains("INVALID_ARGUMENT")
&& text.to_lowercase().contains("registration token") =>
{
Step::Done(Delivery::Invalid)
}
429 | 500..=599 => Step::Retry(ra, format!("FCM answered {st}")),
_ => Step::Fail(PushError::Provider {
status: st,
detail: truncate(&text),
}),
}
})
.await
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApnsEnv {
Production,
Sandbox,
}
#[derive(Clone)]
pub struct Apns {
key: Arc<EncodingKey>,
key_id: String,
team_id: String,
topic: String,
base: String,
http: reqwest::Client,
jwt: Arc<std::sync::Mutex<Option<(String, Instant)>>>,
jwt_ttl: Duration,
backoff: Duration,
}
impl std::fmt::Debug for Apns {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Apns")
.field("key_id", &self.key_id)
.field("team_id", &self.team_id)
.field("topic", &self.topic)
.finish_non_exhaustive()
}
}
impl Apns {
pub fn new(
key_pem: &str,
key_id: &str,
team_id: &str,
topic: &str,
env: ApnsEnv,
) -> Result<Self, PushError> {
if key_id.is_empty() || team_id.is_empty() || topic.is_empty() {
return Err(PushError::Config(
"APNs key id, team id and topic are required".into(),
));
}
let key = EncodingKey::from_ec_pem(key_pem.as_bytes())
.map_err(|_| PushError::Config("APNS key is not a valid EC PEM (.p8)".into()))?;
let base = match env {
ApnsEnv::Production => "https://api.push.apple.com",
ApnsEnv::Sandbox => "https://api.sandbox.push.apple.com",
};
Ok(Self {
key: Arc::new(key),
key_id: key_id.into(),
team_id: team_id.into(),
topic: topic.into(),
base: base.into(),
http: http(false),
jwt: Default::default(),
jwt_ttl: Duration::from_secs(50 * 60),
backoff: Duration::from_millis(500),
})
}
#[cfg(test)]
#[cfg_attr(not(feature = "sqlite"), allow(dead_code))] fn for_test(mut self, base: &str) -> Self {
check_url(base, "base", true).unwrap();
self.base = base.into();
self.http = http(base.starts_with("http://")); self.backoff = Duration::from_millis(5);
self
}
fn provider_token(&self) -> Result<String, PushError> {
let mut g = self.jwt.lock().unwrap();
if let Some((t, exp)) = g.as_ref()
&& Instant::now() < *exp
{
return Ok(t.clone());
}
let mut h = Header::new(Algorithm::ES256);
h.kid = Some(self.key_id.clone());
let t = jsonwebtoken::encode(&h, &json!({"iss": self.team_id, "iat": now()}), &self.key)
.map_err(|_| PushError::Config("APNs JWT signing failed".into()))?;
*g = Some((t.clone(), Instant::now() + self.jwt_ttl));
Ok(t)
}
async fn send(&self, token: &str, n: &Notification) -> Result<Delivery, PushError> {
let body = serde_json::to_vec(&n.apns_body()).expect("json");
if body.len() > MAX_PAYLOAD {
return Err(PushError::Payload("APNs payload exceeds 4096 bytes".into()));
}
if token.is_empty() || !token.chars().all(|c| c.is_ascii_alphanumeric()) {
return Ok(Delivery::Invalid);
}
let background = n.silent();
let url = format!("{}/3/device/{token}", self.base);
retrying(self.backoff, || async {
let jwt = match self.provider_token() {
Ok(j) => j,
Err(e) => return Step::Fail(e),
};
let mut rb = self
.http
.post(&url)
.header("authorization", format!("bearer {jwt}"))
.header("apns-topic", &self.topic)
.header(
"apns-push-type",
if background { "background" } else { "alert" },
)
.header(
"apns-priority",
if n.priority == Priority::High && !background {
"10"
} else {
"5"
},
)
.header("content-type", "application/json");
if let Some(t) = n.ttl {
rb = rb.header("apns-expiration", (now() + t.as_secs() as i64).to_string());
}
if let Some(c) = &n.collapse_key {
rb = rb.header("apns-collapse-id", c);
}
let r = match rb.body(body.clone()).send().await {
Ok(r) => r,
Err(e) => return net_err(e),
};
let st = r.status().as_u16();
let ra = retry_after(&r);
let text = r.text().await.unwrap_or_default();
let reason = serde_json::from_str::<Value>(&text)
.ok()
.and_then(|v| v["reason"].as_str().map(String::from))
.unwrap_or_default();
match (st, reason.as_str()) {
(200..=299, _) => Step::Done(Delivery::Sent),
(410, _) | (400, "BadDeviceToken" | "DeviceTokenNotForTopic") => {
Step::Done(Delivery::Invalid)
}
(403, "ExpiredProviderToken") => {
*self.jwt.lock().unwrap() = None;
Step::Reauth
}
(429, _) | (500..=599, _) => Step::Retry(ra, format!("APNs answered {st}")),
_ => Step::Fail(PushError::Provider {
status: st,
detail: truncate(&text),
}),
}
})
.await
}
}
struct Inner {
devices: Devices,
fcm: Option<Fcm>,
apns: Option<Apns>,
gate: tokio::sync::Semaphore,
}
#[derive(Clone)]
pub struct Push {
inner: Arc<Inner>,
}
impl std::fmt::Debug for Push {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Push")
.field("fcm", &self.inner.fcm)
.field("apns", &self.inner.apns)
.finish_non_exhaustive()
}
}
impl Push {
pub fn new(devices: Devices) -> Self {
Self {
inner: Arc::new(Inner {
devices,
fcm: None,
apns: None,
gate: tokio::sync::Semaphore::new(MAX_CONCURRENCY),
}),
}
}
fn edit(mut self, f: impl FnOnce(&mut Inner)) -> Self {
let i = Arc::get_mut(&mut self.inner).expect("configure Push before cloning it");
f(i);
self
}
pub fn fcm(self, fcm: Fcm) -> Self {
self.edit(|i| i.fcm = Some(fcm))
}
pub fn apns(self, apns: Apns) -> Self {
self.edit(|i| i.apns = Some(apns))
}
pub fn devices(&self) -> &Devices {
&self.inner.devices
}
pub async fn from_env(db: DatabaseConnection) -> Result<Self, PushError> {
Self::from_lookup(db, |k| std::env::var(k).ok().filter(|v| !v.is_empty()))
}
fn from_lookup(
db: DatabaseConnection,
get: impl Fn(&str) -> Option<String>,
) -> Result<Self, PushError> {
let mut p = Self::new(Devices::new(db));
let driver = get("PUSH_DRIVER").unwrap_or_default();
match driver.as_str() {
"log" => return Ok(p),
"" | "live" => {}
other => return Err(PushError::Config(format!("unknown PUSH_DRIVER `{other}`"))),
}
let read = |inline: &str, path: &str| -> Result<Option<String>, PushError> {
match (get(inline), get(path)) {
(Some(v), _) => Ok(Some(v)),
(None, Some(p)) => std::fs::read_to_string(&p)
.map(Some)
.map_err(|e| PushError::Config(format!("cannot read {path}: {}", e.kind()))),
_ => Ok(None),
}
};
if let Some(json) = read("FCM_SERVICE_ACCOUNT_JSON", "FCM_SERVICE_ACCOUNT_PATH")? {
let fcm = Fcm::new(&get("FCM_PROJECT_ID").unwrap_or_default(), &json)?;
p = p.fcm(fcm);
}
if let Some(key) = read("APNS_KEY", "APNS_KEY_PATH")? {
let env = match get("APNS_ENV").as_deref() {
None | Some("production") => ApnsEnv::Production,
Some("sandbox") => ApnsEnv::Sandbox,
Some(_) => return Err(PushError::Config("APNS_ENV is production|sandbox".into())),
};
let req = |k: &str| get(k).ok_or_else(|| PushError::Config(format!("{k} is required")));
let apns = Apns::new(
&key,
&req("APNS_KEY_ID")?,
&req("APNS_TEAM_ID")?,
&req("APNS_TOPIC")?,
env,
)?;
p = p.apns(apns);
}
if driver == "live" && p.inner.fcm.is_none() && p.inner.apns.is_none() {
return Err(PushError::Config(
"PUSH_DRIVER=live but neither FCM nor APNs is configured".into(),
));
}
Ok(p)
}
fn is_log(&self) -> bool {
self.inner.fcm.is_none() && self.inner.apns.is_none()
}
pub async fn send_to_device(
&self,
d: &Device,
n: &Notification,
) -> Result<Delivery, PushError> {
n.validate()?;
let _permit = self.inner.gate.acquire().await.expect("semaphore open");
let out = if self.is_log() {
tracing::info!(
platform = d.platform.as_str(), title = ?n.title, body = ?n.body, data = ?n.data,
"push (log driver)"
);
Delivery::Sent
} else {
match (d.platform, &self.inner.fcm, &self.inner.apns) {
(Platform::Android, Some(f), _) => f.send(&d.token, n).await?,
(Platform::Ios, _, Some(a)) => a.send(&d.token, n).await?,
_ => {
return Err(PushError::Config(format!(
"no provider configured for {}",
d.platform.as_str()
)));
}
}
};
if out == Delivery::Invalid {
self.inner
.devices
.mark_invalid(d.platform, &d.token)
.await?;
}
Ok(out)
}
pub async fn send_to_user(
&self,
user_id: i64,
n: &Notification,
) -> Result<SendReport, PushError> {
n.validate()?;
let devices = self.inner.devices.valid_for_user(user_id).await?;
if self.is_log() {
tracing::info!(
user_id,
devices = devices.len(),
"push (log driver) to user"
);
}
let mut set = tokio::task::JoinSet::new();
for d in devices {
let (this, n) = (self.clone(), n.clone());
set.spawn(async move { this.send_to_device(&d, &n).await });
}
let mut r = SendReport::default();
while let Some(res) = set.join_next().await {
match res {
Ok(Ok(Delivery::Sent)) => r.sent += 1,
Ok(Ok(Delivery::Invalid)) => r.invalidated += 1,
Ok(Ok(Delivery::Transient(_))) | Err(_) => r.failed += 1,
Ok(Err(e)) => {
tracing::warn!("push to one device failed: {e}");
r.failed += 1;
}
}
}
Ok(r)
}
}
#[cfg(all(test, feature = "sqlite"))]
mod tests {
use super::*;
use axum::body::to_bytes;
use axum::extract::{Request, State};
use axum::response::{IntoResponse, Response};
use jsonwebtoken::{DecodingKey, Validation};
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
const EC_PRIV: &str = r#"-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgfp8BgpRhlPdNNJ1j
o00Lm4/eHWZAzQcVgXKXQlZ1doChRANCAAQATRjY6DtJ13iPJZPeO22NTgH60tez
t7q3SZMrvJ9KOrGcK5UL70eGwmM0OQDoYb3yFTeLclIvK966yP6Mf+Jl
-----END PRIVATE KEY-----
"#;
const EC_PUB: &str = r#"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAE0Y2Og7Sdd4jyWT3jttjU4B+tLX
s7e6t0mTK7yfSjqxnCuVC+9HhsJjNDkA6GG98hU3i3JSLyveusj+jH/iZQ==
-----END PUBLIC KEY-----
"#;
const RSA_PRIV: &str = r#"-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvxuXx65vYB39b
xUvAmcihrnWyMfI6n8b8NbhvgHILGsGvDo3FXWLKCjb5tggi/JQ/ZbBSU9n8ovQt
a8L4AVPKr4cj3+kceVCAPntPvz2+0usYOkiXLgfe4Evqv7TxowD9uxEyavq07nlf
pYSlErU3aYThxawe02hdAHl8EBGEkbkJZ+JnHA0YW7Z2568DhDW3exApm2atldtU
BntaZs1T7zWFwhXpihUAXirvQQudp/oEK9vThh6OB30LcOO2jrz+RwWFSOLEOo5A
0XWhEbhmpQlgSD06K9hBFYZJkHRqbcvuUtl9ZhqBDsxoaYN4q9vfd3FxeQoS0Dxd
By8Ew/HfAgMBAAECggEAEV5s1qX/3RhckCkOLlwOdFTPV3TSU9L5msQE01ZqA8k4
jeo5EwwCbia/6OvWS6gRTrRnIwjFwk4oekaAL6O977S+0fTW+CklTbl0KNyjpslO
UV4M/IygBXi8t60KyFJhj4YzvFDQMMmxtO704kosyEAae86zDna4Whw+ZNvCR2A5
mlHxL8Hdhl02US3UdY/8bKzMurGzQ4foTPF8+h1DHu01TQV7DqsyC8fgbY4663JG
pWmmaymppc6ftIghjdRmyANSrzRLdMQDk9lPnBaWBNm5pEKjj3mxzwKQzKHJ8eZm
k8TevpsIMQMxMXa1UpVK0REhhGtOOQViaYU60N6mfQKBgQDWQ74dJQhPH17TTe03
T/mbaIsdWZplaebSUfDgfZxICtOgf2gNQRwL9MuariR9Aordn8Xq9OnKmUsvTolH
nqB4straD2j9iVjCFpyTiRCV6P00q/gBRICJAewQI4kk5a8KCBEEJS+S5Ct3kGrk
JjjzJ/DWUHSb4qEeIFog+DrBCwKBgQDSA/nyakJJNPzIBqOvBgGoxUJ5dsVOq9lr
cpzim7ZvlqR9pV6cGtgSAbMCu+JDGaWH4LGO7k0uFf9LycJLjKZGffP1pnkRQlx7
waZhSLgpaVBDGn3SPAZ8CoYmn3kDfDgRThvWHcz9CHikBPPYYzgJi/87uV2q2YbN
RFOKxGe+/QKBgDJxbl+kKUmfZA6xKOi9vlD1EtNNFglMHlhjjCb9y342dk4x0IhW
TMkPz6NR3itEHvdANzMyh5v37PhtL+qZkMP5r4Zo3FncLPY8po4hVbNFT99HoTKD
MxOOTUobY505KbVd4susCYA2kXkrmc6upPex7oQ2Gs3cU/wot69NYV+zAoGAG73c
uXHh2au/LGj8HDWN6I5ODp9qxs6ahL/6C1EIU0sx5Ur/6Vz+Z7qDu/u3kqeDnyRG
MBw4Y7sSIx++o54rpKoknLFl0qrSbqKQ6M7jTM0VhheswSWesanuOJHeOWCiQ17u
/GSpXE9PKFNjJpVMpK4yg+AjiFr9nIXHB1CUZ70CgYApx2HeboWFCTcOnbelZmdp
qcNp8AiIMLlp/gwzfHOgl4BerGArCevLCsM1acZTtEum/fx0ruRhTR43VYYuVCOj
GlM8ujpx6MX6gtf/8VTnGco6YJVIN+BnjprldewInMG+c+2OyD84vOuyGKAbz9WJ
cgPW3vRe37myhhfdirH4Rw==
-----END PRIVATE KEY-----
"#;
const RSA_PUB: &str = r#"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr8bl8eub2Ad/W8VLwJnI
oa51sjHyOp/G/DW4b4ByCxrBrw6NxV1iygo2+bYIIvyUP2WwUlPZ/KL0LWvC+AFT
yq+HI9/pHHlQgD57T789vtLrGDpIly4H3uBL6r+08aMA/bsRMmr6tO55X6WEpRK1
N2mE4cWsHtNoXQB5fBARhJG5CWfiZxwNGFu2duevA4Q1t3sQKZtmrZXbVAZ7WmbN
U+81hcIV6YoVAF4q70ELnaf6BCvb04Yejgd9C3Djto68/kcFhUjixDqOQNF1oRG4
ZqUJYEg9OivYQRWGSZB0am3L7lLZfWYagQ7MaGmDeKvb33dxcXkKEtA8XQcvBMPx
3wIDAQAB
-----END PUBLIC KEY-----
"#;
fn uniq() -> i64 {
static N: AtomicUsize = AtomicUsize::new(0);
let ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos() as i64;
(ns % 1_000_000_000_000) * 100 + N.fetch_add(1, Ordering::SeqCst) as i64
}
fn tok(prefix: &str) -> String {
format!("{prefix}{:x}", uniq())
}
async fn sqlite() -> DatabaseConnection {
let path = std::env::temp_dir().join(format!("ryuk-push-{}.db", uniq()));
let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
.await
.unwrap();
Devices::new(db.clone()).ensure_tables().await.unwrap();
db
}
async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
let mut v = vec![("sqlite", sqlite().await)];
for (name, var) in [
("postgres", "TEST_POSTGRES_URL"),
("mysql", "TEST_MYSQL_URL"),
] {
if let Ok(url) = std::env::var(var) {
let db = sea_orm::Database::connect(url).await.unwrap();
Devices::new(db.clone()).ensure_tables().await.unwrap();
v.push((name, db));
}
}
v
}
#[test]
fn sha256_known_vectors() {
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(&[b'a'; 1000]),
"41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3"
);
}
#[tokio::test]
async fn the_21st_device_evicts_the_least_recently_seen() {
for (name, db) in dbs().await {
let d = Devices::new(db.clone());
let u = uniq();
let mut ids = vec![];
for i in 0..MAX_DEVICES_PER_USER {
let r = d
.register(u, Platform::Android, &tok(&format!("c{i}")), None, None)
.await
.unwrap();
let seen = if i == 5 { 1 } else { 1000 + i as i64 };
Entity::update_many()
.col_expr(Column::LastSeenAt, Expr::value(seen))
.filter(Column::Id.eq(r.id))
.exec(&db)
.await
.unwrap();
ids.push(r.id);
}
assert_eq!(d.list(u).await.unwrap().len(), 20, "{name}");
let new = d
.register(u, Platform::Android, &tok("c-new"), None, None)
.await
.unwrap();
let left: Vec<i64> = d.list(u).await.unwrap().iter().map(|x| x.id).collect();
assert_eq!(left.len(), 20, "{name}");
assert!(!left.contains(&ids[5]) && left.contains(&new.id), "{name}");
let d2 = Devices::new(db.clone()).max_per_user(3);
let n2 = d2
.register(u, Platform::Android, &tok("c-new2"), None, None)
.await
.unwrap();
let left: Vec<i64> = d2.list(u).await.unwrap().iter().map(|x| x.id).collect();
assert_eq!(left.len(), 3, "{name}");
assert!(left.contains(&n2.id), "{name}");
let u = uniq();
let hs: Vec<_> = (0..30)
.map(|i| {
let d = d.clone();
tokio::spawn(async move {
d.register(u, Platform::Android, &tok(&format!("k{i}")), None, None)
.await
.unwrap()
})
})
.collect();
for h in hs {
h.await.unwrap();
}
d.register(u, Platform::Android, &tok("k-last"), None, None)
.await
.unwrap();
assert_eq!(d.list(u).await.unwrap().len(), 20, "{name}");
}
}
#[tokio::test]
async fn registry_semantics_on_every_backend() {
for (name, db) in dbs().await {
let d = Devices::new(db);
let (u1, u2) = (uniq(), uniq());
let t = tok("tok");
let a = d
.register(u1, Platform::Android, &t, Some("com.acme"), Some("Pixel"))
.await
.unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!((a.user_id, a.invalid_at), (u1, None));
let b = d
.register(u2, Platform::Android, &t, None, None)
.await
.unwrap();
assert_eq!((b.id, b.user_id), (a.id, u2), "{name}");
assert!(d.list(u1).await.unwrap().is_empty());
let ios = d.register(u2, Platform::Ios, &t, None, None).await.unwrap();
assert_ne!(ios.id, a.id);
d.mark_invalid(Platform::Android, &t).await.unwrap();
assert_eq!(d.valid_for_user(u2).await.unwrap().len(), 1, "{name}");
assert!(
d.list(u2)
.await
.unwrap()
.iter()
.any(|i| i.invalid_at.is_some())
);
d.register(u2, Platform::Android, &t, None, None)
.await
.unwrap();
assert_eq!(d.valid_for_user(u2).await.unwrap().len(), 2);
assert!(!d.unregister(u1, a.id).await.unwrap());
assert!(d.unregister(u2, a.id).await.unwrap());
assert!(!d.unregister(u2, a.id).await.unwrap());
let t2 = tok("old");
d.register(u1, Platform::Android, &t2, None, None)
.await
.unwrap();
d.mark_invalid(Platform::Android, &t2).await.unwrap();
tokio::time::sleep(Duration::from_millis(1100)).await;
d.prune(Duration::ZERO, Duration::from_secs(86400))
.await
.unwrap();
assert!(
d.list(u1).await.unwrap().is_empty(),
"{name}: invalid pruned"
);
assert_eq!(d.list(u2).await.unwrap().len(), 1, "{name}: fresh kept");
}
}
#[tokio::test]
async fn registry_validation_and_redaction() {
let d = Devices::new(sqlite().await);
let u = uniq();
for (p, t, n) in [
(Platform::Android, "short", None),
(Platform::Android, "has space inside", None),
(Platform::Ios, "not-hex-token-1234", None),
(Platform::Android, "validtoken123", Some("x".repeat(101))),
] {
assert!(
matches!(
d.register(u, p, t, None, n.as_deref()).await,
Err(PushError::Invalid(_))
),
"{t}"
);
}
assert!(
d.register(u, Platform::Android, &"a".repeat(4097), None, None)
.await
.is_err()
);
d.register(u, Platform::Android, &"a".repeat(4096), None, None)
.await
.unwrap();
let t = tok("secrettoken");
d.register(u, Platform::Android, &t, None, None)
.await
.unwrap();
let dev = d.valid_for_user(u).await.unwrap().remove(0);
let shown = format!("{dev:?} {:?}", d.list(u).await.unwrap());
assert!(!shown.contains("aaaaaaaa") && !shown.contains(&t));
let m = push_devices::Model {
id: 1,
user_id: 1,
platform: "ios".into(),
token: t.clone(),
token_hash: "h".into(),
app_id: None,
name: None,
created_at: 0,
last_seen_at: 0,
invalid_at: None,
};
assert!(!format!("{m:?}").contains(&t));
}
#[test]
fn ddl_indexes_the_hash_not_the_token() {
let my = Schema::new(DbBackend::MySql).create_table_with_index_from_entity(Entity);
let sql = DbBackend::MySql.build(&my).to_string();
assert!(sql.contains("`token` text NOT NULL"), "{sql}");
assert!(
sql.contains("UNIQUE") && sql.contains("`token_hash`"),
"{sql}"
);
assert!(!sql.contains("(`token`)"));
}
#[test]
fn payload_shapes_and_validation() {
let n = Notification::new()
.title("T")
.body("B")
.data("k", "v")
.badge(3)
.sound("default")
.collapse_key("c")
.ttl(Duration::from_secs(60))
.priority(Priority::Normal);
let a = n.apns_body();
assert_eq!(a["aps"]["alert"], json!({"title":"T","body":"B"}));
assert_eq!(
(a["aps"]["badge"].clone(), a["k"].clone()),
(json!(3), json!("v"))
);
let f = n.fcm_message("tk");
assert_eq!(f["message"]["token"], "tk");
assert_eq!(f["message"]["android"]["priority"], "NORMAL");
assert_eq!(f["message"]["android"]["ttl"], "60s");
assert_eq!(f["message"]["data"]["k"], "v");
assert!(Notification::new().validate().is_err());
assert!(
Notification::new()
.title("t")
.data("aps", "x")
.validate()
.is_err()
);
assert!(Notification::new().content_available().validate().is_ok());
assert!(
Notification::new().content_available().apns_body()["aps"]
.get("alert")
.is_none()
);
}
#[derive(Clone)]
struct R(u16, Option<&'static str>, &'static str);
struct Rec {
path: String,
headers: HashMap<String, String>,
body: String,
version: axum::http::Version,
}
#[derive(Default)]
struct Mock {
recs: Mutex<Vec<Rec>>,
queue: Mutex<VecDeque<R>>,
by_token: Mutex<HashMap<String, R>>,
tokens: AtomicUsize,
expires_in: AtomicU64,
}
impl Mock {
fn pushes(&self) -> Vec<(String, HashMap<String, String>, String)> {
self.recs
.lock()
.unwrap()
.iter()
.filter(|r| r.path != "/token")
.map(|r| (r.path.clone(), r.headers.clone(), r.body.clone()))
.collect()
}
fn script(&self, r: &[R]) {
self.queue.lock().unwrap().extend(r.iter().cloned());
}
}
async fn mock_handler(State(m): State<Arc<Mock>>, req: Request) -> Response {
let (p, b) = req.into_parts();
let body = String::from_utf8(to_bytes(b, 1 << 20).await.unwrap().to_vec()).unwrap();
let path = p.uri.path().to_string();
let headers = p
.headers
.iter()
.map(|(k, v)| (k.to_string(), v.to_str().unwrap().to_string()))
.collect();
m.recs.lock().unwrap().push(Rec {
path: path.clone(),
headers,
body: body.clone(),
version: p.version,
});
if path == "/token" {
let n = m.tokens.fetch_add(1, Ordering::SeqCst) + 1;
return axum::Json(json!({"access_token": format!("at-{n}"), "expires_in": m.expires_in.load(Ordering::SeqCst)})).into_response();
}
let hay = format!("{path} {body}");
let by = m
.by_token
.lock()
.unwrap()
.iter()
.find(|(k, _)| hay.contains(k.as_str()))
.map(|(_, r)| r.clone());
let R(st, ra, text) = by
.or_else(|| m.queue.lock().unwrap().pop_front())
.unwrap_or(R(200, None, "{}"));
let mut resp = (axum::http::StatusCode::from_u16(st).unwrap(), text).into_response();
if let Some(ra) = ra {
resp.headers_mut()
.insert("retry-after", ra.parse().unwrap());
}
resp
}
async fn start() -> (String, Arc<Mock>) {
let m = Arc::new(Mock::default());
m.expires_in.store(3600, Ordering::SeqCst);
let app = axum::Router::new()
.fallback(mock_handler)
.with_state(m.clone());
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", l.local_addr().unwrap());
tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
(base, m)
}
fn sa_json() -> String {
json!({"type":"service_account","project_id":"proj-1","client_email":"svc@proj-1.iam.test",
"private_key": RSA_PRIV, "token_uri": "https://oauth2.example/token"})
.to_string()
}
fn fcm(base: &str) -> Fcm {
Fcm::new("", &sa_json()).unwrap().for_test(base)
}
fn apns(base: &str) -> Apns {
Apns::new(
EC_PRIV,
"KEY123",
"TEAM456",
"com.acme.app",
ApnsEnv::Sandbox,
)
.unwrap()
.for_test(base)
}
fn dev(p: Platform, token: &str) -> Device {
Device {
id: 0,
user_id: 0,
platform: p,
token: token.into(),
app_id: None,
}
}
async fn svc(db: DatabaseConnection, f: Option<Fcm>, a: Option<Apns>) -> Push {
let mut p = Push::new(Devices::new(db));
if let Some(f) = f {
p = p.fcm(f);
}
if let Some(a) = a {
p = p.apns(a);
}
p
}
fn verify(jwt: &str, pubkey: &str, alg: Algorithm) -> (Header, Value) {
let mut v = Validation::new(alg);
v.validate_exp = false;
v.validate_aud = false;
v.required_spec_claims.clear();
let key = if alg == Algorithm::RS256 {
DecodingKey::from_rsa_pem(pubkey.as_bytes())
} else {
DecodingKey::from_ec_pem(pubkey.as_bytes())
}
.unwrap();
let d =
jsonwebtoken::decode::<Value>(jwt, &key, &v).expect("JWT verifies with the public key");
(d.header, d.claims)
}
#[tokio::test]
async fn fcm_request_shape_jwt_and_token_cache() {
let (base, m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), None).await;
let n = Notification::new()
.title("Hi")
.body("There")
.data("a", "b")
.collapse_key("c")
.sound("default");
let ts: Vec<_> = (0..6).map(|_| tok("fcmtok")).collect();
let mut set = tokio::task::JoinSet::new();
for t in &ts {
let (p, n, d) = (p.clone(), n.clone(), dev(Platform::Android, t));
set.spawn(async move { p.send_to_device(&d, &n).await.unwrap() });
}
while let Some(r) = set.join_next().await {
assert_eq!(r.unwrap(), Delivery::Sent);
}
assert_eq!(
m.tokens.load(Ordering::SeqCst),
1,
"one token request for 6 sends"
);
let recs = m.recs.lock().unwrap();
let tr = recs.iter().find(|r| r.path == "/token").unwrap();
assert_eq!(
tr.headers["content-type"],
"application/x-www-form-urlencoded"
);
let jwt = tr.body.split("assertion=").nth(1).unwrap();
assert!(
tr.body
.starts_with("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&")
);
let (h, c) = verify(jwt, RSA_PUB, Algorithm::RS256);
assert_eq!(h.alg, Algorithm::RS256);
assert_eq!(c["iss"], "svc@proj-1.iam.test");
assert_eq!(
c["scope"],
"https://www.googleapis.com/auth/firebase.messaging"
);
assert_eq!(c["aud"], format!("{base}/token"));
assert_eq!(
c["exp"].as_i64().unwrap() - c["iat"].as_i64().unwrap(),
3600
);
let send = recs.iter().find(|r| r.path != "/token").unwrap();
assert_eq!(send.path, "/v1/projects/proj-1/messages:send");
assert_eq!(send.headers["authorization"], "Bearer at-1");
let b: Value = serde_json::from_str(&send.body).unwrap();
assert_eq!(
b["message"]["notification"],
json!({"title":"Hi","body":"There"})
);
assert_eq!(b["message"]["data"], json!({"a":"b"}));
assert_eq!(b["message"]["android"]["collapse_key"], "c");
assert_eq!(b["message"]["android"]["notification"]["sound"], "default");
assert!(ts.iter().any(|t| b["message"]["token"] == *t));
}
#[tokio::test]
async fn fcm_token_refreshes_on_expiry_and_on_401() {
let (base, m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), None).await;
let (n, d) = (
Notification::new().title("t"),
dev(Platform::Android, &tok("fcm")),
);
m.expires_in.store(60, Ordering::SeqCst); p.send_to_device(&d, &n).await.unwrap();
p.send_to_device(&d, &n).await.unwrap();
assert_eq!(m.tokens.load(Ordering::SeqCst), 2);
m.expires_in.store(3600, Ordering::SeqCst);
p.send_to_device(&d, &n).await.unwrap(); m.script(&[R(401, None, "{}")]);
assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
let auth: Vec<_> = m
.pushes()
.iter()
.map(|x| x.1["authorization"].clone())
.collect();
assert_eq!(
auth[auth.len() - 2..],
["Bearer at-3", "Bearer at-4"],
"{auth:?}"
);
assert_eq!(m.tokens.load(Ordering::SeqCst), 4);
}
#[tokio::test]
async fn fcm_outcomes_invalid_retry_and_fatal() {
let (base, m) = start().await;
let db = sqlite().await;
let p = svc(db.clone(), Some(fcm(&base)), None).await;
let n = Notification::new().title("t");
let u = uniq();
let (t404, t400, tbad) = (tok("gone"), tok("badarg"), tok("payload"));
for t in [&t404, &t400, &tbad] {
p.devices()
.register(u, Platform::Android, t, None, None)
.await
.unwrap();
}
m.by_token.lock().unwrap().extend([
(t404.clone(), R(404, None, r#"{"error":{"status":"NOT_FOUND","details":[{"errorCode":"UNREGISTERED"}]}}"#)),
(t400.clone(), R(400, None, r#"{"error":{"status":"INVALID_ARGUMENT","message":"The registration token is not a valid FCM registration token"}}"#)),
(tbad.clone(), R(400, None, r#"{"error":{"status":"INVALID_ARGUMENT","message":"Invalid JSON payload"}}"#)),
]);
let before = m.pushes().len();
assert_eq!(
p.send_to_device(&dev(Platform::Android, &t404), &n)
.await
.unwrap(),
Delivery::Invalid
);
assert_eq!(
p.send_to_device(&dev(Platform::Android, &t400), &n)
.await
.unwrap(),
Delivery::Invalid
);
assert_eq!(
m.pushes().len() - before,
2,
"invalid tokens are not retried"
);
assert!(matches!(
p.send_to_device(&dev(Platform::Android, &tbad), &n).await,
Err(PushError::Provider { status: 400, .. })
));
assert_eq!(
p.devices().valid_for_user(u).await.unwrap().len(),
1,
"only the payload-rejected one stays"
);
let d = dev(Platform::Android, &tok("retry"));
let before = m.pushes().len();
m.script(&[R(503, None, "x"), R(503, None, "x")]);
assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
assert_eq!(m.pushes().len() - before, 3);
let before = m.pushes().len();
m.script(&[R(503, None, "x"), R(500, None, "x"), R(503, None, "x")]);
assert!(matches!(
p.send_to_device(&d, &n).await.unwrap(),
Delivery::Transient(_)
));
assert_eq!(m.pushes().len() - before, 3);
}
#[tokio::test]
async fn retry_after_is_honored() {
let (base, m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), None).await;
let d = dev(Platform::Android, &tok("ra"));
m.script(&[R(429, Some("1"), "slow down")]);
let t = Instant::now();
assert_eq!(
p.send_to_device(&d, &Notification::new().title("t"))
.await
.unwrap(),
Delivery::Sent
);
assert!(
t.elapsed() >= Duration::from_millis(990),
"{:?}",
t.elapsed()
);
}
#[tokio::test]
async fn apns_http2_request_shape_and_jwt() {
let (base, m) = start().await;
let p = svc(sqlite().await, None, Some(apns(&base))).await;
let t = tok("abcdef");
let n = Notification::new()
.title("Hi")
.body("Yo")
.badge(2)
.sound("default")
.data("order", "42")
.collapse_key("col")
.ttl(Duration::from_secs(120));
assert_eq!(
p.send_to_device(&dev(Platform::Ios, &t), &n).await.unwrap(),
Delivery::Sent
);
let recs = m.recs.lock().unwrap();
let r = &recs[0];
assert_eq!(
r.version,
axum::http::Version::HTTP_2,
"cleartext HTTP/2 was spoken"
);
assert_eq!(r.path, format!("/3/device/{t}"));
let h = &r.headers;
assert_eq!(h["apns-topic"], "com.acme.app");
assert_eq!(h["apns-push-type"], "alert");
assert_eq!(h["apns-priority"], "10");
assert_eq!(h["apns-collapse-id"], "col");
let exp: i64 = h["apns-expiration"].parse().unwrap();
assert!((exp - now() - 120).abs() <= 5);
let jwt = h["authorization"].strip_prefix("bearer ").unwrap();
let (hd, c) = verify(jwt, EC_PUB, Algorithm::ES256);
assert_eq!(hd.kid.as_deref(), Some("KEY123"));
assert_eq!(c["iss"], "TEAM456");
assert!((c["iat"].as_i64().unwrap() - now()).abs() <= 5);
let b: Value = serde_json::from_str(&r.body).unwrap();
assert_eq!(
b,
json!({"aps":{"alert":{"title":"Hi","body":"Yo"},"badge":2,"sound":"default"},"order":"42"})
);
}
#[tokio::test]
async fn apns_silent_push_and_priorities() {
let (base, m) = start().await;
let p = svc(sqlite().await, None, Some(apns(&base))).await;
let d = dev(Platform::Ios, &tok("abc"));
p.send_to_device(
&d,
&Notification::new().content_available().data("sync", "1"),
)
.await
.unwrap();
p.send_to_device(
&d,
&Notification::new().title("t").priority(Priority::Normal),
)
.await
.unwrap();
let ps = m.pushes();
assert_eq!(ps[0].1["apns-push-type"], "background");
assert_eq!(ps[0].1["apns-priority"], "5");
assert_eq!(
serde_json::from_str::<Value>(&ps[0].2).unwrap(),
json!({"aps":{"content-available":1},"sync":"1"})
);
assert_eq!(ps[1].1["apns-priority"], "5");
assert!(!ps[1].1.contains_key("apns-expiration"));
}
#[tokio::test]
async fn apns_jwt_cached_then_refreshed_on_expiry_and_403() {
let (base, m) = start().await;
let a = apns(&base);
let p = svc(sqlite().await, None, Some(a)).await;
let (d, n) = (
dev(Platform::Ios, &tok("abc")),
Notification::new().title("t"),
);
let jwts = |m: &Mock| -> Vec<String> {
m.pushes()
.iter()
.map(|x| x.1["authorization"].clone())
.collect()
};
for _ in 0..3 {
p.send_to_device(&d, &n).await.unwrap();
}
let j = jwts(&m);
assert!(j.iter().all(|x| *x == j[0]), "one provider token reused");
tokio::time::sleep(Duration::from_millis(1100)).await;
m.script(&[R(403, None, r#"{"reason":"ExpiredProviderToken"}"#)]);
assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
let j = jwts(&m);
assert_eq!(j.len(), 5);
assert_eq!(j[3], j[0], "the rejected request used the cached token");
assert_ne!(j[4], j[3], "token was regenerated after 403");
m.script(&[R(403, None, r#"{"reason":"InvalidProviderToken"}"#)]);
assert!(matches!(
p.send_to_device(&d, &n).await,
Err(PushError::Provider { status: 403, .. })
));
assert_eq!(m.pushes().len(), 6);
let mut a2 = apns(&base);
a2.jwt_ttl = Duration::ZERO;
let p2 = svc(sqlite().await, None, Some(a2)).await;
let before = m.pushes().len();
tokio::time::sleep(Duration::from_millis(1100)).await;
p2.send_to_device(&d, &n).await.unwrap();
p2.send_to_device(&d, &n).await.unwrap();
let j = jwts(&m);
assert_ne!(j[before], j[before + 1]);
}
#[tokio::test]
async fn apns_invalid_tokens_are_flagged() {
let (base, m) = start().await;
let db = sqlite().await;
let p = svc(db, None, Some(apns(&base))).await;
let u = uniq();
let (a, b, c) = (tok("aa"), tok("bb"), tok("cc"));
for t in [&a, &b, &c] {
p.devices()
.register(u, Platform::Ios, t, None, None)
.await
.unwrap();
}
m.by_token.lock().unwrap().extend([
(a.clone(), R(410, None, r#"{"reason":"Unregistered"}"#)),
(b.clone(), R(400, None, r#"{"reason":"BadDeviceToken"}"#)),
]);
let r = p
.send_to_user(u, &Notification::new().title("t"))
.await
.unwrap();
assert_eq!(
r,
SendReport {
sent: 1,
failed: 0,
invalidated: 2
}
);
assert_eq!(p.devices().valid_for_user(u).await.unwrap().len(), 1);
let r = p
.send_to_user(u, &Notification::new().title("t"))
.await
.unwrap();
assert_eq!(
r,
SendReport {
sent: 1,
failed: 0,
invalidated: 0
}
);
}
#[tokio::test]
async fn one_bad_device_does_not_stop_the_others() {
let (base, m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), Some(apns(&base))).await;
let u = uniq();
let (good_a, flaky, gone, good_i) = (tok("ga"), tok("flaky"), tok("gone"), tok("1a"));
for t in [&good_a, &flaky, &gone] {
p.devices()
.register(u, Platform::Android, t, None, None)
.await
.unwrap();
}
p.devices()
.register(u, Platform::Ios, &good_i, None, None)
.await
.unwrap();
m.by_token.lock().unwrap().extend([
(flaky.clone(), R(503, None, "x")),
(gone.clone(), R(404, None, "{}")),
]);
let r = p
.send_to_user(u, &Notification::new().title("t"))
.await
.unwrap();
assert_eq!(
r,
SendReport {
sent: 2,
failed: 1,
invalidated: 1
}
);
}
#[tokio::test]
async fn missing_provider_is_a_failure_not_a_panic() {
let (base, _m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), None).await;
let u = uniq();
p.devices()
.register(u, Platform::Ios, &tok("ab"), None, None)
.await
.unwrap();
let r = p
.send_to_user(u, &Notification::new().title("t"))
.await
.unwrap();
assert_eq!(
r,
SendReport {
sent: 0,
failed: 1,
invalidated: 0
}
);
}
#[tokio::test]
async fn oversize_payload_is_rejected_before_sending() {
let (base, m) = start().await;
let p = svc(sqlite().await, Some(fcm(&base)), Some(apns(&base))).await;
let big = Notification::new().title("t").data("k", "x".repeat(5000));
for d in [
dev(Platform::Android, &tok("big")),
dev(Platform::Ios, &tok("ab")),
] {
assert!(matches!(
p.send_to_device(&d, &big).await,
Err(PushError::Payload(_))
));
}
assert!(m.recs.lock().unwrap().is_empty());
}
#[test]
fn config_validation_and_debug_redaction() {
let rsa_marker = RSA_PRIV.lines().nth(2).unwrap();
let f = Fcm::new("", &sa_json()).unwrap();
let a = Apns::new(EC_PRIV, "K", "T", "com.x", ApnsEnv::Production).unwrap();
let shown = format!("{f:?} {a:?}");
assert!(!shown.contains(rsa_marker) && !shown.contains(EC_PRIV.lines().nth(1).unwrap()));
assert!(shown.contains("svc@proj-1.iam.test"));
assert!(Fcm::new("", "{").is_err());
assert!(Fcm::new("bad/id", &sa_json()).is_err());
assert!(Apns::new("not a key", "K", "T", "t", ApnsEnv::Production).is_err());
assert!(Apns::new(EC_PRIV, "", "T", "t", ApnsEnv::Production).is_err());
assert_eq!(a.base, "https://api.push.apple.com");
assert!(
check_url("http://x", "u", false).is_err()
&& check_url("https://x", "u", false).is_ok()
);
}
#[tokio::test]
async fn from_env_lookup() {
let db = sqlite().await;
let env = |pairs: &[(&str, String)]| {
let m: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (ToString::to_string(&k), v.clone()))
.collect();
Push::from_lookup(db.clone(), move |k| m.get(k).cloned())
};
assert!(env(&[]).unwrap().is_log());
assert!(
env(&[
("PUSH_DRIVER", "log".into()),
("APNS_KEY", "garbage".into())
])
.unwrap()
.is_log()
);
assert!(env(&[("PUSH_DRIVER", "live".into())]).is_err());
assert!(env(&[("PUSH_DRIVER", "nope".into())]).is_err());
let p = env(&[("FCM_SERVICE_ACCOUNT_JSON", sa_json())]).unwrap();
assert!(!p.is_log() && p.inner.apns.is_none());
assert!(
env(&[("APNS_KEY", EC_PRIV.into())]).is_err(),
"key id etc. required"
);
let p = env(&[
("APNS_KEY", EC_PRIV.into()),
("APNS_KEY_ID", "K".into()),
("APNS_TEAM_ID", "T".into()),
("APNS_TOPIC", "com.x".into()),
("APNS_ENV", "sandbox".into()),
])
.unwrap();
assert_eq!(
p.inner.apns.as_ref().unwrap().base,
"https://api.sandbox.push.apple.com"
);
assert!(env(&[("FCM_SERVICE_ACCOUNT_PATH", "/nonexistent/sa.json".into())]).is_err());
}
#[derive(Clone, Default)]
struct Buf(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for Buf {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(b);
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
type Writer = Buf;
fn make_writer(&'a self) -> Buf {
self.clone()
}
}
#[tokio::test]
async fn log_driver_logs_content_but_never_tokens() {
let buf = Buf::default();
let _g = tracing::subscriber::set_default(
tracing_subscriber::fmt()
.with_writer(buf.clone())
.with_ansi(false)
.finish(),
);
let p = Push::new(Devices::new(sqlite().await));
assert!(p.is_log());
let u = uniq();
let t = tok("verysecrettoken");
p.devices()
.register(u, Platform::Android, &t, None, None)
.await
.unwrap();
let n = Notification::new()
.title("Hello title")
.body("Hello body")
.data("k", "v");
let r = p.send_to_user(u, &n).await.unwrap();
assert_eq!(
r,
SendReport {
sent: 1,
failed: 0,
invalidated: 0
}
);
let out = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap();
assert!(
out.contains("Hello title") && out.contains("Hello body") && out.contains("devices=1"),
"{out}"
);
assert!(!out.contains(&t), "token leaked into logs: {out}");
assert!(!format!("{p:?}").contains(&t));
}
}