1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! The client module for sending requests and parsing responses

use signer::Signer;
use hyper_alpn::AlpnConnector;
use error::Error;
use error::Error::ResponseError;

use futures::{
    Future,
    Poll,
    future::{err, ok, Either},
    stream::Stream,
};

use hyper::{
    self,
    Client as HttpClient,
    StatusCode,
    Body
};

use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE};
use request::payload::Payload;
use response::Response;
use serde_json;
use std::{fmt, str};
use std::time::Duration;
use openssl::pkcs12::Pkcs12;
use std::io::Read;
use tokio_timer::{Timeout, Timer};

/// The APNs service endpoint to connect.
#[derive(Debug, Clone)]
pub enum Endpoint {
    /// The production environment (api.push.apple.com)
    Production,
    /// The development/test environment (api.development.push.apple.com)
    Sandbox,
}

impl fmt::Display for Endpoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let host = match self {
            &Endpoint::Production => "api.push.apple.com",
            &Endpoint::Sandbox => "api.development.push.apple.com",
        };

        write!(f, "{}", host)
    }
}

/// Handles requests to and responses from Apple Push Notification service.
/// Connects using a given connector. Handles the needed authentication and
/// maps responses.
///
/// The `send` method returns a future, which is successful when APNs receives
/// the notification and responds with a status OK. In any other case the future
/// fails. If APNs gives a reason for the failure, the returned `Err`
/// holds the response for handling.
pub struct Client {
    endpoint: Endpoint,
    signer: Option<Signer>,
    http_client: HttpClient<AlpnConnector>,
    timer: Timer,
}

impl Client {
    fn new(
        connector: AlpnConnector,
        signer: Option<Signer>,
        endpoint: Endpoint,
    ) -> Client {
        let mut builder = HttpClient::builder();
        builder.keep_alive_timeout(Some(Duration::from_secs(600)));
        builder.http2_only(true);
        builder.keep_alive(true);

        Client {
            http_client: builder.build(connector),
            signer: signer,
            endpoint: endpoint,
            timer: Timer::default(),
        }
    }

    /// Create a connection to APNs using the provider client certificate which
    /// you obtain from your [Apple developer
    /// account](https://developer.apple.com/account/).
    pub fn certificate<R>(
        certificate: &mut R,
        password: &str,
        endpoint: Endpoint,
    ) -> Result<Client, Error>
    where
        R: Read,
    {
        let mut cert_der: Vec<u8> = Vec::new();
        certificate.read_to_end(&mut cert_der)?;

        let pkcs = Pkcs12::from_der(&cert_der)?.parse(password)?;
        let connector = AlpnConnector::with_client_cert(
            &pkcs.cert.to_pem()?,
            &pkcs.pkey.private_key_to_pem_pkcs8()?,
        )?;

        Ok(Self::new(connector, None, endpoint))
    }

    /// Create a connection to APNs using system certificates, signing every
    /// request with a signature using a private key, key id and team id
    /// provisioned from your [Apple developer
    /// account](https://developer.apple.com/account/).
    pub fn token<S, T, R>(
        pkcs8_pem: R,
        key_id: S,
        team_id: T,
        endpoint: Endpoint,
    ) -> Result<Client, Error>
    where
        S: Into<String>,
        T: Into<String>,
        R: Read,
    {
        let connector = AlpnConnector::new();
        let signature_ttl = 60 * 45; // seconds
        let signer = Signer::new(pkcs8_pem, key_id, team_id, signature_ttl)?;

        Ok(Self::new(connector, Some(signer), endpoint))
    }

    /// Send a notification payload. Returns a future that needs to be given to
    /// an executor.
    #[inline]
    pub fn send<'a>(&self, payload: Payload<'a>) -> FutureResponse {
        let request = self.build_request(payload);
        let path = format!("{}", request.uri());

        let send_request = self.http_client
            .request(request)
            .map_err(|e| {
                trace!("Request error: {}", e);
                Error::ConnectionError
            });

        trace!(
            "Client::call requesting ({:?})",
            path
        );

        let requesting = send_request.and_then(move |response| {
            trace!(
                "Client::call got response status {} from ({:?})",
                response.status(),
                path
            );

            let apns_id = response.headers()
                .get("apns-id")
                .and_then(|s| s.to_str().ok())
                .map(|id| String::from(id));

            match response.status() {
                StatusCode::OK => {
                    Either::A(ok(Response {
                        apns_id: apns_id,
                        error: None,
                        code: response.status().as_u16(),
                    }))
                },
                _ => {
                    Either::B(
                        Self::handle_body(
                            apns_id,
                            response
                        )
                    )
                }
            }
        });

        FutureResponse(Box::new(requesting))
    }

    /// Sends a notification with a timeout. Triggers `Error::TimeoutError` if
    /// the request takes too long.
    #[inline]
    pub fn send_with_timeout<'a>(
        &self,
        message: Payload<'a>,
        timeout: Duration,
    ) -> Timeout<FutureResponse> {
        self.timer.timeout(self.send(message), timeout)
    }

    fn handle_body(
        apns_id: Option<String>,
        response: hyper::Response<Body>,
    ) -> impl Future<Item=Response, Error=Error> + 'static + Send
    {
        let response_status = response.status().clone();

        let get_body = response
            .into_body()
            .map_err(|e| {
                trace!("Body error: {}", e);
                Error::ConnectionError
            })
            .concat2();

        get_body.and_then(move |body_chunk| {
            if let Ok(body) = str::from_utf8(&body_chunk.to_vec()) {
                err(ResponseError(Response {
                    apns_id: apns_id,
                    error: serde_json::from_str(body).ok(),
                    code: response_status.as_u16(),
                }))
            } else {
                err(ResponseError(Response {
                    apns_id: None,
                    error: None,
                    code: response_status.as_u16(),
                }))
            }
        })
    }

    fn build_request(&self, payload: Payload) -> hyper::Request<Body> {
        let path = format!(
            "https://{}/3/device/{}",
            self.endpoint, payload.device_token
        );

        let mut builder = hyper::Request::builder();

        builder.uri(&path);
        builder.method("POST");
        builder.header(CONTENT_TYPE, "application/json");
        builder.header("apns-priority", format!("{}", payload.options.apns_priority).as_bytes());

        if let Some(ref apns_id) = payload.options.apns_id {
            builder.header("apns-id", apns_id.as_bytes());
        }
        if let Some(ref apns_expiration) = payload.options.apns_expiration {
            builder.header("apns-expiration", format!("{}", apns_expiration).as_bytes());
        }
        if let Some(ref apns_collapse_id) = payload.options.apns_collapse_id {
            builder.header("apns-collapse-id", format!("{}", apns_collapse_id.value).as_bytes());
        }
        if let Some(ref apns_topic) = payload.options.apns_topic {
            builder.header("apns-topic", apns_topic.as_bytes());
        }
        if let Some(ref signer) = self.signer {
            signer.with_signature(|signature| {
                builder.header(AUTHORIZATION, format!("Bearer {}", signature).as_bytes());
            }).unwrap();
        }

        let payload_json = payload.to_json_string().unwrap();
        builder.header(CONTENT_LENGTH, format!("{}", payload_json.len()).as_bytes());

        let request_body = Body::from(payload_json);
        builder.body(request_body).unwrap()
    }
}

pub struct FutureResponse(Box<Future<Item = Response, Error = Error> + Send + 'static>);

impl fmt::Debug for FutureResponse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Future<Response>")
    }
}

impl Future for FutureResponse {
    type Item = Response;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.0.poll()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use request::notification::PlainNotificationBuilder;
    use request::notification::NotificationBuilder;
    use request::notification::{NotificationOptions, Priority, CollapseId};
    use hyper_alpn::AlpnConnector;
    use hyper::Method;
    use http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE};
    use signer::Signer;

    const PRIVATE_KEY: &'static str = indoc!(
        "-----BEGIN PRIVATE KEY-----
        MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8g/n6j9roKvnUkwu
        lCEIvbDqlUhA5FOzcakkG90E8L+hRANCAATKS2ZExEybUvchRDuKBftotMwVEus3
        jDwmlD1Gg0yJt1e38djFwsxsfr5q2hv0Rj9fTEqAPr8H7mGm0wKxZ7iQ
        -----END PRIVATE KEY-----"
    );

    #[test]
    fn test_production_request_uri() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let uri = format!("{}", request.uri());

        assert_eq!("https://api.push.apple.com/3/device/a_test_id", &uri);
    }

    #[test]
    fn test_sandbox_request_uri() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Sandbox);
        let request = client.build_request(payload);
        let uri = format!("{}", request.uri());

        assert_eq!("https://api.development.push.apple.com/3/device/a_test_id", &uri);
    }

    #[test]
    fn test_request_method() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);

        assert_eq!(&Method::POST, request.method());
    }

    #[test]
    fn test_request_content_type() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);

        assert_eq!("application/json", request.headers().get(CONTENT_TYPE).unwrap());
    }

    #[test]
    fn test_request_content_length() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload.clone());
        let payload_json = payload.to_json_string().unwrap();
        let content_length = request.headers().get(CONTENT_LENGTH).unwrap().to_str().unwrap();

        assert_eq!(
            &format!("{}", payload_json.len()),
            content_length
        );
    }

    #[test]
    fn test_request_authorization_with_no_signer() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);

        assert_eq!(None, request.headers().get(AUTHORIZATION));
    }

    #[test]
    fn test_request_authorization_with_a_signer() {
        let signer = Signer::new(PRIVATE_KEY.as_bytes(), "89AFRD1X22", "ASDFQWERTY", 100).unwrap();
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), Some(signer), Endpoint::Production);
        let request = client.build_request(payload);

        assert_ne!(None, request.headers().get(AUTHORIZATION));
    }

    #[test]
    fn test_request_with_normal_priority() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_priority = request.headers().get("apns-priority").unwrap();

        assert_eq!("5", apns_priority);
    }

    #[test]
    fn test_request_with_high_priority() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            NotificationOptions {
                apns_priority: Priority::High,
                ..Default::default()
            }
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_priority = request.headers().get("apns-priority").unwrap();

        assert_eq!("10", apns_priority);
    }

    #[test]
    fn test_request_with_default_apns_id() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            Default::default(),
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_id = request.headers().get("apns-id");

        assert_eq!(None, apns_id);
    }

    #[test]
    fn test_request_with_an_apns_id() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            NotificationOptions {
                apns_id: Some("a-test-apns-id"),
                ..Default::default()
            },
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_id = request.headers().get("apns-id").unwrap();

        assert_eq!("a-test-apns-id", apns_id);
    }

    #[test]
    fn test_request_with_default_apns_expiration() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            Default::default(),
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_expiration = request.headers().get("apns-expiration");

        assert_eq!(None, apns_expiration);
    }

    #[test]
    fn test_request_with_an_apns_expiration() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            NotificationOptions {
                apns_expiration: Some(420),
                ..Default::default()
            },
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_expiration = request.headers().get("apns-expiration").unwrap();

        assert_eq!("420", apns_expiration);
    }

    #[test]
    fn test_request_with_default_apns_collapse_id() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            Default::default(),
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_collapse_id = request.headers().get("apns-collapse-id");

        assert_eq!(None, apns_collapse_id);
    }

    #[test]
    fn test_request_with_an_apns_collapse_id() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            NotificationOptions {
                apns_collapse_id: Some(CollapseId::new("a_collapse_id").unwrap()),
                ..Default::default()
            },
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_collapse_id = request.headers().get("apns-collapse-id").unwrap();

        assert_eq!("a_collapse_id", apns_collapse_id);
    }

    #[test]
    fn test_request_with_default_apns_topic() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            Default::default(),
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_topic = request.headers().get("apns-topic");

        assert_eq!(None, apns_topic);
    }

    #[test]
    fn test_request_with_an_apns_topic() {
        let builder = PlainNotificationBuilder::new("test");

        let payload = builder.build(
            "a_test_id",
            NotificationOptions {
                apns_topic: Some("a_topic"),
                ..Default::default()
            },
        );

        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload);
        let apns_topic = request.headers().get("apns-topic").unwrap();

        assert_eq!("a_topic", apns_topic);
    }

    #[test]
    fn test_request_body() {
        let builder = PlainNotificationBuilder::new("test");
        let payload = builder.build("a_test_id", Default::default());
        let client = Client::new(AlpnConnector::new(), None, Endpoint::Production);
        let request = client.build_request(payload.clone());
        let body_chunk = request.into_body().concat2().wait().unwrap();
        let body_str = String::from_utf8(body_chunk.to_vec()).unwrap();

        assert_eq!(
            payload.to_json_string().unwrap(),
            body_str,
        );
    }
}