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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use crate::{
    utils, Auth, AuthErrorKind, AuthQuestion, AuthRequest, AuthResponse, AuthVerifyKind, Codec,
    Handshake, Server, ServerCtx, XChaCha20Poly1305Codec,
};
use async_trait::async_trait;
use bytes::BytesMut;
use log::*;
use std::{collections::HashMap, io};
use tokio::sync::RwLock;

/// Type signature for a dynamic on_challenge function
pub type AuthChallengeFn =
    dyn Fn(Vec<AuthQuestion>, HashMap<String, String>) -> Vec<String> + Send + Sync;

/// Type signature for a dynamic on_verify function
pub type AuthVerifyFn = dyn Fn(AuthVerifyKind, String) -> bool + Send + Sync;

/// Type signature for a dynamic on_info function
pub type AuthInfoFn = dyn Fn(String) + Send + Sync;

/// Type signature for a dynamic on_error function
pub type AuthErrorFn = dyn Fn(AuthErrorKind, String) + Send + Sync;

/// Represents an [`AuthServer`] where all handlers are stored on the heap
pub type HeapAuthServer =
    AuthServer<Box<AuthChallengeFn>, Box<AuthVerifyFn>, Box<AuthInfoFn>, Box<AuthErrorFn>>;

/// Server that handles authentication
pub struct AuthServer<ChallengeFn, VerifyFn, InfoFn, ErrorFn>
where
    ChallengeFn: Fn(Vec<AuthQuestion>, HashMap<String, String>) -> Vec<String> + Send + Sync,
    VerifyFn: Fn(AuthVerifyKind, String) -> bool + Send + Sync,
    InfoFn: Fn(String) + Send + Sync,
    ErrorFn: Fn(AuthErrorKind, String) + Send + Sync,
{
    pub on_challenge: ChallengeFn,
    pub on_verify: VerifyFn,
    pub on_info: InfoFn,
    pub on_error: ErrorFn,
}

#[async_trait]
impl<ChallengeFn, VerifyFn, InfoFn, ErrorFn> Server
    for AuthServer<ChallengeFn, VerifyFn, InfoFn, ErrorFn>
where
    ChallengeFn: Fn(Vec<AuthQuestion>, HashMap<String, String>) -> Vec<String> + Send + Sync,
    VerifyFn: Fn(AuthVerifyKind, String) -> bool + Send + Sync,
    InfoFn: Fn(String) + Send + Sync,
    ErrorFn: Fn(AuthErrorKind, String) + Send + Sync,
{
    type Request = Auth;
    type Response = Auth;
    type LocalData = RwLock<Option<XChaCha20Poly1305Codec>>;

    async fn on_request(&self, ctx: ServerCtx<Self::Request, Self::Response, Self::LocalData>) {
        let reply = ctx.reply.clone();

        match ctx.request.payload {
            Auth::Handshake { public_key, salt } => {
                trace!(
                    "Received handshake request from client, request id = {}",
                    ctx.request.id
                );
                let handshake = Handshake::default();
                match handshake.handshake(public_key, salt) {
                    Ok(key) => {
                        ctx.local_data
                            .write()
                            .await
                            .replace(XChaCha20Poly1305Codec::new(&key));

                        trace!(
                            "Sending reciprocal handshake to client, response origin id = {}",
                            ctx.request.id
                        );
                        if let Err(x) = reply
                            .send(Auth::Handshake {
                                public_key: handshake.pk_bytes(),
                                salt: *handshake.salt(),
                            })
                            .await
                        {
                            error!("[Conn {}] {}", ctx.connection_id, x);
                        }
                    }
                    Err(x) => {
                        error!("[Conn {}] {}", ctx.connection_id, x);
                        return;
                    }
                }
            }
            Auth::Msg {
                ref encrypted_payload,
            } => {
                trace!(
                    "Received auth msg, encrypted payload size = {}",
                    encrypted_payload.len()
                );

                // Attempt to decrypt the message so we can understand what to do
                let request = match ctx.local_data.write().await.as_mut() {
                    Some(codec) => {
                        let mut payload = BytesMut::from(encrypted_payload.as_slice());
                        match codec.decode(&mut payload) {
                            Ok(Some(payload)) => {
                                utils::deserialize_from_slice::<AuthRequest>(&payload)
                            }
                            Ok(None) => Err(io::Error::new(
                                io::ErrorKind::InvalidData,
                                "Incomplete message received",
                            )),
                            Err(x) => Err(x),
                        }
                    }
                    None => Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Handshake must be performed first (server decrypt message)",
                    )),
                };

                let response = match request {
                    Ok(request) => match request {
                        AuthRequest::Challenge { questions, extra } => {
                            trace!("Received challenge request");
                            trace!("questions = {:?}", questions);
                            trace!("extra = {:?}", extra);

                            let answers = (self.on_challenge)(questions, extra);
                            AuthResponse::Challenge { answers }
                        }
                        AuthRequest::Verify { kind, text } => {
                            trace!("Received verify request");
                            trace!("kind = {:?}", kind);
                            trace!("text = {:?}", text);

                            let valid = (self.on_verify)(kind, text);
                            AuthResponse::Verify { valid }
                        }
                        AuthRequest::Info { text } => {
                            trace!("Received info request");
                            trace!("text = {:?}", text);

                            (self.on_info)(text);
                            return;
                        }
                        AuthRequest::Error { kind, text } => {
                            trace!("Received error request");
                            trace!("kind = {:?}", kind);
                            trace!("text = {:?}", text);

                            (self.on_error)(kind, text);
                            return;
                        }
                    },
                    Err(x) => {
                        error!("[Conn {}] {}", ctx.connection_id, x);
                        return;
                    }
                };

                // Serialize and encrypt the message before sending it back
                let encrypted_payload = match ctx.local_data.write().await.as_mut() {
                    Some(codec) => {
                        let mut encrypted_payload = BytesMut::new();

                        // Convert the response into bytes for us to send back
                        match utils::serialize_to_vec(&response) {
                            Ok(bytes) => match codec.encode(&bytes, &mut encrypted_payload) {
                                Ok(_) => Ok(encrypted_payload.freeze().to_vec()),
                                Err(x) => Err(x),
                            },
                            Err(x) => Err(x),
                        }
                    }
                    None => Err(io::Error::new(
                        io::ErrorKind::Other,
                        "Handshake must be performed first (server encrypt messaage)",
                    )),
                };

                match encrypted_payload {
                    Ok(encrypted_payload) => {
                        if let Err(x) = reply.send(Auth::Msg { encrypted_payload }).await {
                            error!("[Conn {}] {}", ctx.connection_id, x);
                            return;
                        }
                    }
                    Err(x) => {
                        error!("[Conn {}] {}", ctx.connection_id, x);
                        return;
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        IntoSplit, MpscListener, MpscTransport, Request, Response, ServerExt, ServerRef,
        TypedAsyncRead, TypedAsyncWrite,
    };
    use tokio::sync::mpsc;

    const TIMEOUT_MILLIS: u64 = 100;

    #[tokio::test]
    async fn should_not_reply_if_receive_encrypted_msg_without_handshake_first() {
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */ |_, _| false,
            /* on_info      */ |_| {},
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send an encrypted message before establishing a handshake
        t.write(Request::new(Auth::Msg {
            encrypted_payload: Vec::new(),
        }))
        .await
        .expect("Failed to send request to server");

        // Wait for a response, failing if we get one
        tokio::select! {
            x = t.read() => panic!("Unexpectedly resolved: {:?}", x),
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    #[tokio::test]
    async fn should_reply_to_handshake_request_with_new_public_key_and_salt() {
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */ |_, _| false,
            /* on_info      */ |_| {},
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Wait for a handshake response
        tokio::select! {
            x = t.read() => {
                let response = x.expect("Request failed").expect("Response missing");
                match response.payload {
                    Auth::Handshake { .. } => {},
                    Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
                }
            }
            _ = wait_ms(TIMEOUT_MILLIS) => panic!("Ran out of time waiting on response"),
        }
    }

    #[tokio::test]
    async fn should_not_reply_if_receive_invalid_encrypted_msg() {
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */ |_, _| false,
            /* on_info      */ |_| {},
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Complete handshake
        let key = match t.read().await.unwrap().unwrap().payload {
            Auth::Handshake { public_key, salt } => handshake.handshake(public_key, salt).unwrap(),
            Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
        };

        // Send a bad chunk of data
        let _codec = XChaCha20Poly1305Codec::new(&key);
        t.write(Request::new(Auth::Msg {
            encrypted_payload: vec![1, 2, 3, 4],
        }))
        .await
        .unwrap();

        // Wait for a response, failing if we get one
        tokio::select! {
            x = t.read() => panic!("Unexpectedly resolved: {:?}", x),
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    #[tokio::test]
    async fn should_invoke_appropriate_function_when_receive_challenge_request_and_reply() {
        let (tx, mut rx) = mpsc::channel(1);
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */
            move |questions, extra| {
                tx.try_send((questions, extra)).unwrap();
                vec!["answer1".to_string(), "answer2".to_string()]
            },
            /* on_verify    */ |_, _| false,
            /* on_info      */ |_| {},
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Complete handshake
        let key = match t.read().await.unwrap().unwrap().payload {
            Auth::Handshake { public_key, salt } => handshake.handshake(public_key, salt).unwrap(),
            Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
        };

        // Send an error request
        let mut codec = XChaCha20Poly1305Codec::new(&key);
        t.write(Request::new(Auth::Msg {
            encrypted_payload: serialize_and_encrypt(
                &mut codec,
                &AuthRequest::Challenge {
                    questions: vec![
                        AuthQuestion::new("question1".to_string()),
                        AuthQuestion {
                            text: "question2".to_string(),
                            extra: vec![("key".to_string(), "value".to_string())]
                                .into_iter()
                                .collect(),
                        },
                    ],
                    extra: vec![("hello".to_string(), "world".to_string())]
                        .into_iter()
                        .collect(),
                },
            )
            .unwrap(),
        }))
        .await
        .unwrap();

        // Verify that the handler was triggered
        let (questions, extra) = rx.recv().await.expect("Channel closed unexpectedly");
        assert_eq!(
            questions,
            vec![
                AuthQuestion::new("question1".to_string()),
                AuthQuestion {
                    text: "question2".to_string(),
                    extra: vec![("key".to_string(), "value".to_string())]
                        .into_iter()
                        .collect(),
                }
            ]
        );
        assert_eq!(
            extra,
            vec![("hello".to_string(), "world".to_string())]
                .into_iter()
                .collect()
        );

        // Wait for a response and verify that it matches what we expect
        tokio::select! {
            x = t.read() => {
                let response = x.expect("Request failed").expect("Response missing");
                match response.payload {
                    Auth::Handshake { .. } => panic!("Received unexpected handshake"),
                    Auth::Msg { encrypted_payload } => {
                        match decrypt_and_deserialize(&mut codec, &encrypted_payload).unwrap() {
                            AuthResponse::Challenge { answers } =>
                                assert_eq!(
                                    answers,
                                    vec!["answer1".to_string(), "answer2".to_string()]
                                ),
                            _ => panic!("Got wrong response for verify"),
                        }
                    },
                }
            }
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    #[tokio::test]
    async fn should_invoke_appropriate_function_when_receive_verify_request_and_reply() {
        let (tx, mut rx) = mpsc::channel(1);
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */
            move |kind, text| {
                tx.try_send((kind, text)).unwrap();
                true
            },
            /* on_info      */ |_| {},
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Complete handshake
        let key = match t.read().await.unwrap().unwrap().payload {
            Auth::Handshake { public_key, salt } => handshake.handshake(public_key, salt).unwrap(),
            Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
        };

        // Send an error request
        let mut codec = XChaCha20Poly1305Codec::new(&key);
        t.write(Request::new(Auth::Msg {
            encrypted_payload: serialize_and_encrypt(
                &mut codec,
                &AuthRequest::Verify {
                    kind: AuthVerifyKind::Host,
                    text: "some text".to_string(),
                },
            )
            .unwrap(),
        }))
        .await
        .unwrap();

        // Verify that the handler was triggered
        let (kind, text) = rx.recv().await.expect("Channel closed unexpectedly");
        assert_eq!(kind, AuthVerifyKind::Host);
        assert_eq!(text, "some text");

        // Wait for a response and verify that it matches what we expect
        tokio::select! {
            x = t.read() => {
                let response = x.expect("Request failed").expect("Response missing");
                match response.payload {
                    Auth::Handshake { .. } => panic!("Received unexpected handshake"),
                    Auth::Msg { encrypted_payload } => {
                        match decrypt_and_deserialize(&mut codec, &encrypted_payload).unwrap() {
                            AuthResponse::Verify { valid } =>
                                assert!(valid, "Got verify, but valid was wrong"),
                            _ => panic!("Got wrong response for verify"),
                        }
                    },
                }
            }
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    #[tokio::test]
    async fn should_invoke_appropriate_function_when_receive_info_request() {
        let (tx, mut rx) = mpsc::channel(1);
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */ |_, _| false,
            /* on_info      */
            move |text| {
                tx.try_send(text).unwrap();
            },
            /* on_error     */ |_, _| {},
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Complete handshake
        let key = match t.read().await.unwrap().unwrap().payload {
            Auth::Handshake { public_key, salt } => handshake.handshake(public_key, salt).unwrap(),
            Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
        };

        // Send an error request
        let mut codec = XChaCha20Poly1305Codec::new(&key);
        t.write(Request::new(Auth::Msg {
            encrypted_payload: serialize_and_encrypt(
                &mut codec,
                &AuthRequest::Info {
                    text: "some text".to_string(),
                },
            )
            .unwrap(),
        }))
        .await
        .unwrap();

        // Verify that the handler was triggered
        let text = rx.recv().await.expect("Channel closed unexpectedly");
        assert_eq!(text, "some text");

        // Wait for a response, failing if we get one
        tokio::select! {
            x = t.read() => panic!("Unexpectedly resolved: {:?}", x),
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    #[tokio::test]
    async fn should_invoke_appropriate_function_when_receive_error_request() {
        let (tx, mut rx) = mpsc::channel(1);
        let (mut t, _) = spawn_auth_server(
            /* on_challenge */ |_, _| Vec::new(),
            /* on_verify    */ |_, _| false,
            /* on_info      */ |_| {},
            /* on_error     */
            move |kind, text| {
                tx.try_send((kind, text)).unwrap();
            },
        )
        .await
        .expect("Failed to spawn server");

        // Send a handshake
        let handshake = Handshake::default();
        t.write(Request::new(Auth::Handshake {
            public_key: handshake.pk_bytes(),
            salt: *handshake.salt(),
        }))
        .await
        .expect("Failed to send request to server");

        // Complete handshake
        let key = match t.read().await.unwrap().unwrap().payload {
            Auth::Handshake { public_key, salt } => handshake.handshake(public_key, salt).unwrap(),
            Auth::Msg { .. } => panic!("Received unexpected encryped message during handshake"),
        };

        // Send an error request
        let mut codec = XChaCha20Poly1305Codec::new(&key);
        t.write(Request::new(Auth::Msg {
            encrypted_payload: serialize_and_encrypt(
                &mut codec,
                &AuthRequest::Error {
                    kind: AuthErrorKind::FailedChallenge,
                    text: "some text".to_string(),
                },
            )
            .unwrap(),
        }))
        .await
        .unwrap();

        // Verify that the handler was triggered
        let (kind, text) = rx.recv().await.expect("Channel closed unexpectedly");
        assert_eq!(kind, AuthErrorKind::FailedChallenge);
        assert_eq!(text, "some text");

        // Wait for a response, failing if we get one
        tokio::select! {
            x = t.read() => panic!("Unexpectedly resolved: {:?}", x),
            _ = wait_ms(TIMEOUT_MILLIS) => {}
        }
    }

    async fn wait_ms(ms: u64) {
        use std::time::Duration;
        tokio::time::sleep(Duration::from_millis(ms)).await;
    }

    fn serialize_and_encrypt(
        codec: &mut XChaCha20Poly1305Codec,
        payload: &AuthRequest,
    ) -> io::Result<Vec<u8>> {
        let mut encryped_payload = BytesMut::new();
        let payload = utils::serialize_to_vec(payload)?;
        codec.encode(&payload, &mut encryped_payload)?;
        Ok(encryped_payload.freeze().to_vec())
    }

    fn decrypt_and_deserialize(
        codec: &mut XChaCha20Poly1305Codec,
        payload: &[u8],
    ) -> io::Result<AuthResponse> {
        let mut payload = BytesMut::from(payload);
        match codec.decode(&mut payload)? {
            Some(payload) => utils::deserialize_from_slice::<AuthResponse>(&payload),
            None => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Incomplete message received",
            )),
        }
    }

    async fn spawn_auth_server<ChallengeFn, VerifyFn, InfoFn, ErrorFn>(
        on_challenge: ChallengeFn,
        on_verify: VerifyFn,
        on_info: InfoFn,
        on_error: ErrorFn,
    ) -> io::Result<(
        MpscTransport<Request<Auth>, Response<Auth>>,
        Box<dyn ServerRef>,
    )>
    where
        ChallengeFn:
            Fn(Vec<AuthQuestion>, HashMap<String, String>) -> Vec<String> + Send + Sync + 'static,
        VerifyFn: Fn(AuthVerifyKind, String) -> bool + Send + Sync + 'static,
        InfoFn: Fn(String) + Send + Sync + 'static,
        ErrorFn: Fn(AuthErrorKind, String) + Send + Sync + 'static,
    {
        let server = AuthServer {
            on_challenge,
            on_verify,
            on_info,
            on_error,
        };

        // Create a test listener where we will forward a connection
        let (tx, listener) = MpscListener::channel(100);

        // Make bounded transport pair and send off one of them to act as our connection
        let (transport, connection) = MpscTransport::<Request<Auth>, Response<Auth>>::pair(100);
        tx.send(connection.into_split())
            .await
            .expect("Failed to feed listener a connection");

        let server = server.start(listener)?;
        Ok((transport, server))
    }
}