apns.rs (14812B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::time::Duration; 18 19 use aws_lc_rs::{ 20 rand::SystemRandom, 21 signature::{ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair}, 22 }; 23 use base64::{display::Base64Display, engine::general_purpose::URL_SAFE_NO_PAD}; 24 use compact_str::CompactString; 25 use http_body_util::{BodyExt, Full}; 26 use hyper::{ 27 Method, StatusCode, 28 body::Bytes, 29 header::{AUTHORIZATION, CONTENT_TYPE}, 30 }; 31 use hyper_rustls::ConfigBuilderExt; 32 use hyper_util::rt::{TokioExecutor, TokioTimer}; 33 use jiff::{SignedDuration, Timestamp}; 34 use rustls::pki_types::{PrivateKeyDer, pem::PemObject}; 35 use serde::Deserialize; 36 use taler_common::error::FmtSource; 37 use taler_macros::EnumMeta; 38 39 use crate::config::{ApnsConfig, ApnsServer}; 40 41 /// Raw JSON body returned by APNs when a push is rejected. 42 #[derive(Debug, Deserialize)] 43 pub struct ApnsErrorBody { 44 pub reason: CompactString, 45 /// Milliseconds since epoch. Only present when status is 410 (Unregistered/ExpiredToken). 46 pub timestamp: Option<u64>, 47 } 48 49 #[derive(Debug, Clone, Copy, PartialEq, Eq, EnumMeta)] 50 #[enum_meta(Description, Str)] 51 pub enum Reason { 52 /// The collapse identifier exceeds the maximum allowed size 53 BadCollapseId, 54 /// The specified device token is invalid 55 BadDeviceToken, 56 /// The apns-expiration value is invalid 57 BadExpirationDate, 58 /// The apns-id value is invalid 59 BadMessageId, 60 /// The apns-priority value is invalid 61 BadPriority, 62 /// The apns-topic value is invalid 63 BadTopic, 64 /// The device token doesn't match the specified topic 65 DeviceTokenNotForTopic, 66 /// One or more headers are repeated 67 DuplicateHeaders, 68 /// Idle timeout 69 IdleTimeout, 70 /// The apns-push-type value is invalid 71 InvalidPushType, 72 /// The device token isn't specified in the request :path 73 MissingDeviceToken, 74 /// The apns-topic header is missing and required 75 MissingTopic, 76 /// The message payload is empty 77 PayloadEmpty, 78 /// Pushing to this topic is not allowed 79 TopicDisallowed, 80 /// The certificate is invalid 81 BadCertificate, 82 /// The client certificate doesn't match the environment 83 BadCertificateEnvironment, 84 /// The provider token is stale 85 ExpiredProviderToken, 86 /// The specified action is not allowed 87 Forbidden, 88 /// The provider token is not valid 89 InvalidProviderToken, 90 /// No provider certificate or token was specified 91 MissingProviderToken, 92 /// The key ID in the provider token is unrelated to this connection 93 UnrelatedKeyIdInToken, 94 /// The key ID in the provider token doesn’t match the environment 95 BadEnvironmentKeyIdInToken, 96 /// The request contained an invalid :path value 97 BadPath, 98 /// The specified :method value isn't POST 99 MethodNotAllowed, 100 /// The device token has expired 101 ExpiredToken, 102 /// The device token is inactive for the specified topic 103 Unregistered, 104 /// The message payload is too large 105 PayloadTooLarge, 106 /// The authentication token is being updated too often 107 TooManyProviderTokenUpdates, 108 /// Too many requests to the same device token 109 TooManyRequests, 110 /// An internal server error 111 InternalServerError, 112 /// The service is unavailable 113 ServiceUnavailable, 114 /// The APNs server is shutting down 115 Shutdown, 116 } 117 118 impl Reason { 119 /// Returns the HTTP status code associated with the error 120 pub fn status_code(&self) -> u16 { 121 match self { 122 Self::BadCollapseId 123 | Self::BadDeviceToken 124 | Self::BadExpirationDate 125 | Self::BadMessageId 126 | Self::BadPriority 127 | Self::BadTopic 128 | Self::DeviceTokenNotForTopic 129 | Self::DuplicateHeaders 130 | Self::IdleTimeout 131 | Self::InvalidPushType 132 | Self::MissingDeviceToken 133 | Self::MissingTopic 134 | Self::PayloadEmpty 135 | Self::TopicDisallowed => 400, 136 137 Self::BadCertificate 138 | Self::BadCertificateEnvironment 139 | Self::ExpiredProviderToken 140 | Self::Forbidden 141 | Self::InvalidProviderToken 142 | Self::MissingProviderToken 143 | Self::UnrelatedKeyIdInToken 144 | Self::BadEnvironmentKeyIdInToken => 403, 145 Self::BadPath => 404, 146 Self::MethodNotAllowed => 405, 147 Self::ExpiredToken | Self::Unregistered => 410, 148 Self::PayloadTooLarge => 413, 149 Self::TooManyProviderTokenUpdates | Self::TooManyRequests => 429, 150 Self::InternalServerError => 500, 151 Self::ServiceUnavailable | Self::Shutdown => 503, 152 } 153 } 154 } 155 156 #[derive(Debug, thiserror::Error)] 157 pub enum ApnsError { 158 #[error("HTTP request: {0}")] 159 ReqTransport(FmtSource<hyper_util::client::legacy::Error>), 160 #[error("HTTP response: {0}")] 161 ResTransport(FmtSource<hyper::Error>), 162 #[error("response {0} JSON body: '{1}' - {2}")] 163 ResJson(StatusCode, Box<str>, serde_json::Error), 164 #[error("APNs unknown error {0}: {1}")] 165 ErrUnknown(StatusCode, CompactString), 166 #[error("APNs error {} {reason} - {}", reason.status_code(), reason.description())] 167 Err { 168 reason: Reason, 169 timestamp: Option<u64>, 170 }, 171 } 172 173 pub struct Client { 174 http: hyper_util::client::legacy::Client< 175 hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>, 176 Full<Bytes>, 177 >, 178 key_pair: EcdsaKeyPair, 179 server: ApnsServer, 180 key_id: CompactString, 181 team_id: CompactString, 182 bundle_id: CompactString, 183 token: Box<str>, 184 issued_at: Timestamp, 185 } 186 187 impl Client { 188 pub fn new(cfg: &ApnsConfig) -> anyhow::Result<Self> { 189 let ApnsConfig { 190 server, 191 key_path, 192 key_id, 193 team_id, 194 bundle_id, 195 } = cfg; 196 197 let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); 198 199 let invalid_key = |message: String| taler_common::config::CfgErr::Invalid { 200 ty: Some("PKCS#8 private key file".into()), 201 section: "apns-relay-worker".into(), 202 option: "KEY_FILE".into(), 203 err: message, 204 }; 205 // Load the signature key pair 206 let private_key_der = PrivateKeyDer::from_pem_file(key_path) 207 .map_err(|e| invalid_key(format!("failed to read key file at '{key_path}': {e}")))?; 208 let PrivateKeyDer::Pkcs8(pkcs8_der) = private_key_der else { 209 return Err(invalid_key(format!( 210 "invalid key file at '{key_path}': not a valid PKCS#8 private key" 211 )) 212 .into()); 213 }; 214 let key_pair = EcdsaKeyPair::from_pkcs8( 215 &ECDSA_P256_SHA256_FIXED_SIGNING, 216 pkcs8_der.secret_pkcs8_der(), 217 ) 218 .map_err(|_| { 219 invalid_key(format!( 220 "invalid key file at '{key_path}': not a valid PKCS#8 private key" 221 )) 222 })?; 223 224 // Make a signature 225 let now = Timestamp::now(); 226 let token = Self::create_token(&key_pair, key_id, team_id, &now); 227 228 // Prepare the TLS client config 229 let tls = rustls::ClientConfig::builder() 230 .try_with_platform_verifier() 231 .expect("failed to setup platform TLS verifier") 232 .with_no_client_auth(); 233 234 // Prepare the HTTPS connector 235 let https = hyper_rustls::HttpsConnectorBuilder::new() 236 .with_tls_config(tls) 237 .https_only() 238 .enable_http2() 239 .build(); 240 241 // Send HTTP/2 PING every 1 hour as per: https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns#Follow-best-practices-while-sending-push-notifications-with-APNs 242 // Reuse a connection as long as possible. In most cases, you can reuse a connection for many hours to days. If your connection is mostly idle, you may send a HTTP2 PING frame after an hour of inactivity. Reusing a connection often results in less bandwidth and CPU consumption. 243 let http = hyper_util::client::legacy::Client::builder(TokioExecutor::new()) 244 .timer(TokioTimer::new()) 245 .pool_idle_timeout(None) 246 .http2_only(true) 247 .http2_keep_alive_interval(Some(Duration::from_secs(60 * 60))) 248 .http2_keep_alive_while_idle(true) 249 .build(https); 250 251 Ok(Self { 252 http, 253 key_pair, 254 server: *server, 255 key_id: key_id.clone(), 256 team_id: team_id.clone(), 257 bundle_id: bundle_id.clone(), 258 token, 259 issued_at: now, 260 }) 261 } 262 263 pub async fn send(&mut self, device_token: &str) -> Result<(), ApnsError> { 264 let now = Timestamp::now(); 265 // Token expire after an hour 266 if now.duration_since(self.issued_at) > SignedDuration::from_mins(55) { 267 self.refresh_token(); 268 } 269 270 let result = self.send_once(device_token).await; 271 if matches!( 272 &result, 273 Err(ApnsError::Err { 274 reason: Reason::ExpiredProviderToken, 275 .. 276 }) 277 ) { 278 self.refresh_token(); 279 return self.send_once(device_token).await; 280 } 281 result 282 } 283 284 fn refresh_token(&mut self) { 285 let now = Timestamp::now(); 286 self.token = Self::create_token(&self.key_pair, &self.key_id, &self.team_id, &now); 287 self.issued_at = now; 288 } 289 290 async fn send_once(&self, device_token: &str) -> Result<(), ApnsError> { 291 let req = hyper::Request::builder() 292 .method(Method::POST) 293 .uri(format!( 294 "https://{}/3/device/{device_token}", 295 self.server.host() 296 )) 297 .header(CONTENT_TYPE, "application/json") 298 .header("apns-push-type", "background") 299 .header("apns-priority", "5") 300 .header("apns-collapse-id", "wakeup") 301 .header("apns-topic", self.bundle_id.as_str()) 302 .header(AUTHORIZATION, self.token.as_ref()) 303 .body(Full::new(Bytes::from_static( 304 r#"{"aps":{"content-available":1}}"#.as_bytes(), 305 ))) 306 .unwrap(); 307 308 let (parts, body) = self 309 .http 310 .request(req) 311 .await 312 .map_err(|e| ApnsError::ReqTransport(e.into()))? 313 .into_parts(); 314 let status = parts.status; 315 if status == StatusCode::OK { 316 return Ok(()); 317 } 318 319 let body = body 320 .collect() 321 .await 322 .map(|it| it.to_bytes()) 323 .map_err(|e| ApnsError::ResTransport(e.into()))?; 324 let body: ApnsErrorBody = serde_json::from_slice(&body).map_err(|e| { 325 ApnsError::ResJson( 326 status, 327 String::from_utf8_lossy(&body).to_string().into_boxed_str(), 328 e, 329 ) 330 })?; 331 let reason = match (status.as_u16(), body.reason.as_str()) { 332 (400, "BadCollapseId") => Reason::BadCollapseId, 333 (400, "BadDeviceToken") => Reason::BadDeviceToken, 334 (400, "BadExpirationDate") => Reason::BadExpirationDate, 335 (400, "BadMessageId") => Reason::BadMessageId, 336 (400, "BadPriority") => Reason::BadPriority, 337 (400, "BadTopic") => Reason::BadTopic, 338 (400, "DeviceTokenNotForTopic") => Reason::DeviceTokenNotForTopic, 339 (400, "DuplicateHeaders") => Reason::DuplicateHeaders, 340 (400, "IdleTimeout") => Reason::IdleTimeout, 341 (400, "InvalidPushType") => Reason::InvalidPushType, 342 (400, "MissingDeviceToken") => Reason::MissingDeviceToken, 343 (400, "MissingTopic") => Reason::MissingTopic, 344 (400, "PayloadEmpty") => Reason::PayloadEmpty, 345 (400, "TopicDisallowed") => Reason::TopicDisallowed, 346 (403, "BadCertificate") => Reason::BadCertificate, 347 (403, "BadCertificateEnvironment") => Reason::BadCertificateEnvironment, 348 (403, "ExpiredProviderToken") => Reason::ExpiredProviderToken, 349 (403, "Forbidden") => Reason::Forbidden, 350 (403, "InvalidProviderToken") => Reason::InvalidProviderToken, 351 (403, "MissingProviderToken") => Reason::MissingProviderToken, 352 (403, "UnrelatedKeyIdInToken") => Reason::UnrelatedKeyIdInToken, 353 (403, "BadEnvironmentKeyIdInToken") => Reason::BadEnvironmentKeyIdInToken, 354 (404, "BadPath") => Reason::BadPath, 355 (405, "MethodNotAllowed") => Reason::MethodNotAllowed, 356 (410, "ExpiredToken") => Reason::ExpiredToken, 357 (410, "Unregistered") => Reason::Unregistered, 358 (413, "PayloadTooLarge") => Reason::PayloadTooLarge, 359 (429, "TooManyProviderTokenUpdates") => Reason::TooManyProviderTokenUpdates, 360 (429, "TooManyRequests") => Reason::TooManyRequests, 361 (500, "InternalServerError") => Reason::InternalServerError, 362 (503, "ServiceUnavailable") => Reason::ServiceUnavailable, 363 (503, "Shutdown") => Reason::Shutdown, 364 _ => return Err(ApnsError::ErrUnknown(status, body.reason)), 365 }; 366 Err(ApnsError::Err { 367 reason, 368 timestamp: body.timestamp, 369 }) 370 } 371 372 fn create_token( 373 key_pair: &EcdsaKeyPair, 374 key_id: &str, 375 team_id: &str, 376 issued_at: &Timestamp, 377 ) -> Box<str> { 378 let headers = format!(r#"{{"alg":"ES256","kid":"{key_id}"}}"#); 379 let payload = format!(r#"{{"iss":"{team_id}","iat":{}}}"#, issued_at.as_second()); 380 let token = format!( 381 "{}.{}", 382 Base64Display::new(headers.as_bytes(), &URL_SAFE_NO_PAD), 383 Base64Display::new(payload.as_bytes(), &URL_SAFE_NO_PAD) 384 ); 385 let signature = key_pair 386 .sign(&SystemRandom::new(), token.as_bytes()) 387 .unwrap(); 388 389 format!( 390 "Bearer {}.{}", 391 token, 392 Base64Display::new(signature.as_ref(), &URL_SAFE_NO_PAD) 393 ) 394 .into_boxed_str() 395 } 396 }