1use std::collections::{HashMap, VecDeque};
6use std::net::IpAddr;
7use std::sync::Mutex;
8use std::time::Duration;
9
10use axum::http::{HeaderValue, Uri};
11use base64ct::{Base64UrlUnpadded, Encoding as _};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use web_push_native::{Auth, WebPushBuilder};
15
16use super::error::MobileError;
17use super::vapid::Vapid;
18use crate::web::phone::Delivery;
19
20const PUSH_SERVICES: [&str; 4] = [
23 "*.push.apple.com",
24 "fcm.googleapis.com",
25 "*.push.services.mozilla.com",
26 "*.notify.windows.com",
27];
28
29pub(crate) const PUSH_TTL: Duration = Duration::from_secs(12 * 60 * 60);
31const MAX_ENDPOINT: usize = 2048;
33const DELIVERIES_KEPT: usize = 256;
35const SENT_KEPT: usize = 1024;
37
38#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct PushAllowlist {
55 hosts: Vec<String>,
56 http_localhost: bool,
57}
58
59impl Default for PushAllowlist {
60 fn default() -> Self {
62 Self::new(PUSH_SERVICES)
63 }
64}
65
66impl PushAllowlist {
67 pub fn new(hosts: impl IntoIterator<Item = impl Into<String>>) -> Self {
70 Self {
71 hosts: hosts.into_iter().map(|host| host.into().to_ascii_lowercase()).collect(),
72 http_localhost: false,
73 }
74 }
75
76 #[must_use]
79 pub fn with_plain_http_to_localhost(mut self) -> Self {
80 self.http_localhost = true;
81 self
82 }
83
84 pub fn allows(&self, endpoint: &str) -> bool {
86 self.origin_of(endpoint).is_ok()
87 }
88
89 pub(crate) fn origin_of(&self, endpoint: &str) -> Result<String, MobileError> {
92 let refused = |reason: &str| MobileError::PushEndpoint { reason: reason.to_string() };
93 if endpoint.len() > MAX_ENDPOINT {
94 return Err(refused("the endpoint is too long"));
95 }
96 let uri: Uri = endpoint.parse().map_err(|_| refused("the endpoint is not a URL"))?;
97 let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else {
98 return Err(refused("the endpoint is not an absolute URL"));
99 };
100 if authority.as_str().contains('@') {
101 return Err(refused("the endpoint carries credentials"));
102 }
103 let host = authority.host().to_ascii_lowercase();
104 if host.starts_with('[') || host.parse::<IpAddr>().is_ok() {
105 return Err(refused("the endpoint is an IP address, not a push service"));
106 }
107 match scheme {
108 "https" => {}
109 "http" if self.http_localhost && host == "localhost" => {}
110 _ => return Err(refused("the endpoint is not https")),
111 }
112 if !self.hosts.iter().any(|allowed| host_matches(allowed, &host)) {
113 return Err(refused("the host is not a push service this server sends to"));
114 }
115 Ok(format!("{scheme}://{}", authority.as_str().to_ascii_lowercase()))
116 }
117}
118
119fn host_matches(allowed: &str, host: &str) -> bool {
120 match allowed.strip_prefix("*.") {
121 Some(domain) => {
122 host.strip_suffix(domain).is_some_and(|label| label.len() > 1 && label.ends_with('.'))
123 }
124 None => allowed == host,
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(rename_all = "camelCase")]
132pub(crate) struct Subscription {
133 pub(crate) endpoint: String,
134 pub(crate) p256dh: String,
135 pub(crate) auth: String,
136 pub(crate) key_id: String,
137}
138
139impl Subscription {
140 pub(crate) fn new(
143 allowlist: &PushAllowlist,
144 endpoint: &str,
145 p256dh: &str,
146 auth: &str,
147 key_id: &str,
148 ) -> Result<Self, MobileError> {
149 allowlist.origin_of(endpoint)?;
150 let subscription = Self {
151 endpoint: endpoint.to_string(),
152 p256dh: p256dh.to_string(),
153 auth: auth.to_string(),
154 key_id: key_id.to_string(),
155 };
156 subscription.keys()?;
157 Ok(subscription)
158 }
159
160 fn keys(&self) -> Result<(p256::PublicKey, Auth), MobileError> {
161 let refused = |reason: &str| MobileError::PushEndpoint { reason: reason.to_string() };
162 let public = Base64UrlUnpadded::decode_vec(self.p256dh.trim_end_matches('='))
163 .ok()
164 .and_then(|bytes| p256::PublicKey::from_sec1_bytes(&bytes).ok())
165 .ok_or_else(|| refused("the subscription's p256dh key is not a P-256 public key"))?;
166 let auth = Base64UrlUnpadded::decode_vec(self.auth.trim_end_matches('='))
167 .ok()
168 .filter(|bytes| bytes.len() == 16)
169 .ok_or_else(|| refused("the subscription's auth secret is not 16 bytes"))?;
170 Ok((public, Auth::clone_from_slice(&auth)))
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
176pub(crate) enum Sent {
177 Delivered,
179 Gone,
181 Failed(String),
183 Unavailable(String),
186}
187
188#[derive(Debug, Clone)]
192pub(crate) struct PushSender {
193 client: reqwest::Client,
194 vapid: Vapid,
195 allowlist: PushAllowlist,
196 ttl: Duration,
197 backoff: Duration,
198 attempts: u32,
199}
200
201impl PushSender {
202 pub(crate) fn new(
209 vapid: Vapid,
210 allowlist: PushAllowlist,
211 backoff: Duration,
212 ) -> Result<Self, MobileError> {
213 let client = reqwest::Client::builder()
215 .redirect(reqwest::redirect::Policy::none())
216 .timeout(Duration::from_secs(15))
217 .build()
218 .map_err(|error| {
219 MobileError::Source(adk_core::AdkError::new(
220 adk_core::ErrorComponent::Server,
221 adk_core::ErrorCategory::Internal,
222 "surface.phone.push_client",
223 format!(
224 "the push client could not be built ({error}); the phone sends no \
225 wake-up through a client that follows redirects. Fix the TLS setup the \
226 error names, such as a native root certificate store with no valid \
227 certificate"
228 ),
229 ))
230 })?;
231 Ok(Self { client, vapid, allowlist, ttl: PUSH_TTL, backoff, attempts: 3 })
232 }
233
234 pub(crate) fn vapid(&self) -> &Vapid {
235 &self.vapid
236 }
237
238 pub(crate) fn allowlist(&self) -> &PushAllowlist {
239 &self.allowlist
240 }
241
242 pub(crate) async fn send(&self, subscription: &Subscription, body: &[u8]) -> Sent {
244 if subscription.key_id != self.vapid.key().id() {
245 return Sent::Failed(format!(
246 "the phone subscribed with push key {}, and this server holds {}: share one key \
247 with --push-key",
248 subscription.key_id,
249 self.vapid.key().id()
250 ));
251 }
252 let origin = match self.allowlist.origin_of(&subscription.endpoint) {
253 Ok(origin) => origin,
254 Err(error) => return Sent::Failed(error.to_string()),
255 };
256 let request = match self.request(subscription, &origin, body) {
257 Ok(request) => request,
258 Err(reason) => return Sent::Failed(reason),
259 };
260 let mut wait = self.backoff;
261 let mut last = String::new();
262 for attempt in 1..=self.attempts {
263 let Some(request) = request.try_clone() else {
264 return Sent::Failed("the push request could not be repeated".into());
265 };
266 match self.client.execute(request).await {
267 Ok(response) if response.status().is_success() => return Sent::Delivered,
268 Ok(response) if matches!(response.status().as_u16(), 404 | 410) => {
269 return Sent::Gone;
270 }
271 Ok(response)
272 if response.status().as_u16() == 429 || response.status().is_server_error() =>
273 {
274 last = format!("the push service answered {}", response.status());
275 }
276 Ok(response) => {
277 return Sent::Failed(format!(
278 "the push service answered {}",
279 response.status()
280 ));
281 }
282 Err(error) => last = format!("the push service could not be reached: {error}"),
283 }
284 if attempt < self.attempts {
285 tracing::debug!(push.attempt = attempt, error = %last, "a wake-up will be sent again");
286 tokio::time::sleep(wait).await;
287 wait = wait.saturating_mul(2);
288 }
289 }
290 Sent::Unavailable(last)
291 }
292
293 fn request(
294 &self,
295 subscription: &Subscription,
296 origin: &str,
297 body: &[u8],
298 ) -> Result<reqwest::Request, String> {
299 let (public, auth) = subscription.keys().map_err(|error| error.to_string())?;
300 let uri: Uri =
301 subscription.endpoint.parse().map_err(|_| "the endpoint is not a URL".to_string())?;
302 let mut request = WebPushBuilder::new(uri, public, auth)
303 .with_valid_duration(self.ttl)
304 .build(body.to_vec())
305 .map_err(|error| format!("the wake-up could not be encrypted: {error}"))?;
306 let authorization = HeaderValue::from_str(&self.vapid.authorization(origin))
307 .map_err(|_| "the VAPID header is not valid".to_string())?;
308 request.headers_mut().insert(axum::http::header::AUTHORIZATION, authorization);
309 request.headers_mut().insert("urgency", HeaderValue::from_static("high"));
310 reqwest::Request::try_from(request).map_err(|error| error.to_string())
311 }
312}
313
314pub(crate) fn wake_up(id: &str) -> Vec<u8> {
318 serde_json::to_vec(&serde_json::json!({ "v": 1, "id": id })).unwrap_or_default()
319}
320
321pub(crate) fn new_wake_id() -> String {
323 let mut bytes = [0u8; 16];
324 if getrandom::fill(&mut bytes).is_err() {
325 return uuid::Uuid::new_v4().simple().to_string();
326 }
327 Base64UrlUnpadded::encode_string(&bytes)
328}
329
330#[derive(Debug, Default)]
333pub(crate) struct Deliveries {
334 inner: Mutex<DeliveriesInner>,
335}
336
337#[derive(Debug, Default)]
338struct DeliveriesInner {
339 sent: HashMap<String, (String, DateTime<Utc>)>,
340 order: VecDeque<String>,
341 received: VecDeque<Delivery>,
342}
343
344impl Deliveries {
345 pub(crate) fn sent(&self, id: &str, device: &str, at: DateTime<Utc>) {
347 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
348 if inner.order.len() >= SENT_KEPT
349 && let Some(oldest) = inner.order.pop_front()
350 {
351 inner.sent.remove(&oldest);
352 }
353 inner.order.push_back(id.to_string());
354 inner.sent.insert(id.to_string(), (device.to_string(), at));
355 }
356
357 pub(crate) fn received(&self, id: &str, device: &str, at: DateTime<Utc>) -> Option<Delivery> {
359 let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
360 match inner.sent.get(id) {
361 Some((to, _)) if to == device => {}
362 _ => return None,
363 }
364 let (device, sent_at) = inner.sent.remove(id)?;
365 inner.order.retain(|kept| kept != id);
366 let delivery = Delivery {
367 device_id: device,
368 sent_at,
369 received_at: at,
370 latency_ms: u64::try_from((at - sent_at).num_milliseconds()).unwrap_or(0),
371 };
372 if inner.received.len() >= DELIVERIES_KEPT {
373 inner.received.pop_front();
374 }
375 inner.received.push_back(delivery.clone());
376 Some(delivery)
377 }
378
379 pub(crate) fn list(&self) -> Vec<Delivery> {
381 self.inner.lock().unwrap_or_else(|e| e.into_inner()).received.iter().cloned().collect()
382 }
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 #[test]
390 fn the_browsers_push_services_are_allowed_over_https_only() {
391 let allow = PushAllowlist::default();
392 for endpoint in [
393 "https://web.push.apple.com/QGu1",
394 "https://api.push.apple.com/x",
395 "https://fcm.googleapis.com/fcm/send/abc",
396 "https://updates.push.services.mozilla.com/wpush/v2/x",
397 "https://wns2-by3p.notify.windows.com/w/?token=x",
398 ] {
399 assert!(allow.allows(endpoint), "{endpoint}");
400 }
401 for endpoint in [
402 "http://web.push.apple.com/QGu1",
403 "https://push.apple.com/x",
404 "https://evilpush.apple.com.example.com/x",
405 "https://fcm.googleapis.com.example.com/x",
406 "https://user:pw@fcm.googleapis.com/x",
407 "https://192.0.2.7/push",
408 "https://[2001:db8::1]/push",
409 "https://localhost/push",
410 "http://localhost:8080/push",
411 "web.push.apple.com/x",
412 "not a url",
413 ] {
414 assert!(!allow.allows(endpoint), "{endpoint}");
415 }
416 }
417
418 #[test]
419 fn plain_http_is_for_localhost_in_tests_only() {
420 let allow = PushAllowlist::new(["localhost"]).with_plain_http_to_localhost();
421 assert_eq!(allow.origin_of("http://localhost:4100/p/1").unwrap(), "http://localhost:4100");
422 assert!(!allow.allows("http://127.0.0.1:4100/p/1"));
423 assert!(!PushAllowlist::new(["localhost"]).allows("http://localhost:4100/p/1"));
424 }
425
426 #[test]
427 fn the_wake_up_body_is_a_version_and_an_id() {
428 let body: serde_json::Value = serde_json::from_slice(&wake_up("w1")).unwrap();
429 assert_eq!(body, serde_json::json!({ "v": 1, "id": "w1" }));
430 assert_ne!(new_wake_id(), new_wake_id());
431 }
432
433 #[test]
434 fn only_the_device_a_wake_up_went_to_acknowledges_it() {
435 let deliveries = Deliveries::default();
436 let at = Utc::now();
437 deliveries.sent("w1", "dev-a", at);
438 assert_eq!(deliveries.received("w1", "dev-b", at), None);
439 let delivery =
440 deliveries.received("w1", "dev-a", at + chrono::Duration::milliseconds(840)).unwrap();
441 assert_eq!(delivery.latency_ms, 840);
442 assert_eq!(deliveries.received("w1", "dev-a", at), None, "acknowledged once");
443 assert_eq!(deliveries.list(), vec![delivery]);
444 }
445}