apns.rs (14883B)
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 rustls::crypto::aws_lc_rs::default_provider() 198 .install_default() 199 .expect("failed to install the default TLS provider"); 200 201 let invalid_key = |message: String| taler_common::config::CfgErr::Invalid { 202 ty: Some("PKCS#8 private key file".into()), 203 section: "apns-relay-worker".into(), 204 option: "KEY_FILE".into(), 205 err: message, 206 }; 207 // Load the signature key pair 208 let private_key_der = PrivateKeyDer::from_pem_file(key_path) 209 .map_err(|e| invalid_key(format!("failed to read key file at '{key_path}': {e}")))?; 210 let PrivateKeyDer::Pkcs8(pkcs8_der) = private_key_der else { 211 return Err(invalid_key(format!( 212 "invalid key file at '{key_path}': not a valid PKCS#8 private key" 213 )) 214 .into()); 215 }; 216 let key_pair = EcdsaKeyPair::from_pkcs8( 217 &ECDSA_P256_SHA256_FIXED_SIGNING, 218 pkcs8_der.secret_pkcs8_der(), 219 ) 220 .map_err(|_| { 221 invalid_key(format!( 222 "invalid key file at '{key_path}': not a valid PKCS#8 private key" 223 )) 224 })?; 225 226 // Make a signature 227 let now = Timestamp::now(); 228 let token = Self::create_token(&key_pair, key_id, team_id, &now); 229 230 // Prepare the TLS client config 231 let tls = rustls::ClientConfig::builder() 232 .try_with_platform_verifier() 233 .expect("failed to setup platform TLS verifier") 234 .with_no_client_auth(); 235 236 // Prepare the HTTPS connector 237 let https = hyper_rustls::HttpsConnectorBuilder::new() 238 .with_tls_config(tls) 239 .https_only() 240 .enable_http2() 241 .build(); 242 243 // 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 244 // 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. 245 let http = hyper_util::client::legacy::Client::builder(TokioExecutor::new()) 246 .timer(TokioTimer::new()) 247 .pool_idle_timeout(None) 248 .http2_only(true) 249 .http2_keep_alive_interval(Some(Duration::from_secs(60 * 60))) 250 .http2_keep_alive_while_idle(true) 251 .build(https); 252 253 Ok(Self { 254 http, 255 key_pair, 256 server: *server, 257 key_id: key_id.clone(), 258 team_id: team_id.clone(), 259 bundle_id: bundle_id.clone(), 260 token, 261 issued_at: now, 262 }) 263 } 264 265 pub async fn send(&mut self, device_token: &str) -> Result<(), ApnsError> { 266 let now = Timestamp::now(); 267 // Token expire after an hour 268 if now.duration_since(self.issued_at) > SignedDuration::from_mins(55) { 269 self.refresh_token(); 270 } 271 272 let result = self.send_once(device_token).await; 273 if matches!( 274 &result, 275 Err(ApnsError::Err { 276 reason: Reason::ExpiredProviderToken, 277 .. 278 }) 279 ) { 280 self.refresh_token(); 281 return self.send_once(device_token).await; 282 } 283 result 284 } 285 286 fn refresh_token(&mut self) { 287 let now = Timestamp::now(); 288 self.token = Self::create_token(&self.key_pair, &self.key_id, &self.team_id, &now); 289 self.issued_at = now; 290 } 291 292 async fn send_once(&self, device_token: &str) -> Result<(), ApnsError> { 293 let req = hyper::Request::builder() 294 .method(Method::POST) 295 .uri(format!( 296 "https://{}/3/device/{device_token}", 297 self.server.host() 298 )) 299 .header(CONTENT_TYPE, "application/json") 300 .header("apns-push-type", "background") 301 .header("apns-priority", "5") 302 .header("apns-collapse-id", "wakeup") 303 .header("apns-topic", self.bundle_id.as_str()) 304 .header(AUTHORIZATION, self.token.as_ref()) 305 .body(Full::new(Bytes::from_static( 306 r#"{"aps":{"content-available":1}}"#.as_bytes(), 307 ))) 308 .unwrap(); 309 310 let (parts, body) = self 311 .http 312 .request(req) 313 .await 314 .map_err(|e| ApnsError::ReqTransport(e.into()))? 315 .into_parts(); 316 let status = parts.status; 317 if status == StatusCode::OK { 318 return Ok(()); 319 } 320 321 let body = body 322 .collect() 323 .await 324 .map(|it| it.to_bytes()) 325 .map_err(|e| ApnsError::ResTransport(e.into()))?; 326 let body: ApnsErrorBody = serde_json::from_slice(&body).map_err(|e| { 327 ApnsError::ResJson( 328 status, 329 String::from_utf8_lossy(&body).to_string().into_boxed_str(), 330 e, 331 ) 332 })?; 333 let reason = match (status.as_u16(), body.reason.as_str()) { 334 (400, "BadCollapseId") => Reason::BadCollapseId, 335 (400, "BadDeviceToken") => Reason::BadDeviceToken, 336 (400, "BadExpirationDate") => Reason::BadExpirationDate, 337 (400, "BadMessageId") => Reason::BadMessageId, 338 (400, "BadPriority") => Reason::BadPriority, 339 (400, "BadTopic") => Reason::BadTopic, 340 (400, "DeviceTokenNotForTopic") => Reason::DeviceTokenNotForTopic, 341 (400, "DuplicateHeaders") => Reason::DuplicateHeaders, 342 (400, "IdleTimeout") => Reason::IdleTimeout, 343 (400, "InvalidPushType") => Reason::InvalidPushType, 344 (400, "MissingDeviceToken") => Reason::MissingDeviceToken, 345 (400, "MissingTopic") => Reason::MissingTopic, 346 (400, "PayloadEmpty") => Reason::PayloadEmpty, 347 (400, "TopicDisallowed") => Reason::TopicDisallowed, 348 (403, "BadCertificate") => Reason::BadCertificate, 349 (403, "BadCertificateEnvironment") => Reason::BadCertificateEnvironment, 350 (403, "ExpiredProviderToken") => Reason::ExpiredProviderToken, 351 (403, "Forbidden") => Reason::Forbidden, 352 (403, "InvalidProviderToken") => Reason::InvalidProviderToken, 353 (403, "MissingProviderToken") => Reason::MissingProviderToken, 354 (403, "UnrelatedKeyIdInToken") => Reason::UnrelatedKeyIdInToken, 355 (403, "BadEnvironmentKeyIdInToken") => Reason::BadEnvironmentKeyIdInToken, 356 (404, "BadPath") => Reason::BadPath, 357 (405, "MethodNotAllowed") => Reason::MethodNotAllowed, 358 (410, "ExpiredToken") => Reason::ExpiredToken, 359 (410, "Unregistered") => Reason::Unregistered, 360 (413, "PayloadTooLarge") => Reason::PayloadTooLarge, 361 (429, "TooManyProviderTokenUpdates") => Reason::TooManyProviderTokenUpdates, 362 (429, "TooManyRequests") => Reason::TooManyRequests, 363 (500, "InternalServerError") => Reason::InternalServerError, 364 (503, "ServiceUnavailable") => Reason::ServiceUnavailable, 365 (503, "Shutdown") => Reason::Shutdown, 366 _ => return Err(ApnsError::ErrUnknown(status, body.reason)), 367 }; 368 Err(ApnsError::Err { 369 reason, 370 timestamp: body.timestamp, 371 }) 372 } 373 374 fn create_token( 375 key_pair: &EcdsaKeyPair, 376 key_id: &str, 377 team_id: &str, 378 issued_at: &Timestamp, 379 ) -> Box<str> { 380 let headers = format!(r#"{{"alg":"ES256","kid":"{key_id}"}}"#); 381 let payload = format!(r#"{{"iss":"{team_id}","iat":{}}}"#, issued_at.as_second()); 382 let token = format!( 383 "{}.{}", 384 Base64Display::new(headers.as_bytes(), &URL_SAFE_NO_PAD), 385 Base64Display::new(payload.as_bytes(), &URL_SAFE_NO_PAD) 386 ); 387 let signature = key_pair 388 .sign(&SystemRandom::new(), token.as_bytes()) 389 .unwrap(); 390 391 format!( 392 "Bearer {}.{}", 393 token, 394 Base64Display::new(signature.as_ref(), &URL_SAFE_NO_PAD) 395 ) 396 .into_boxed_str() 397 } 398 }