distant-net 0.20.0

Network library for distant, providing implementations to support client/server architecture
Documentation
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
use std::io;

use async_trait::async_trait;
use distant_auth::msg::*;
use distant_auth::{AuthHandler, Authenticate, Authenticator};
use log::*;

use crate::common::{utils, FramedTransport, Transport};

macro_rules! write_frame {
    ($transport:expr, $data:expr) => {{
        let data = utils::serialize_to_vec(&$data)?;
        if log_enabled!(Level::Trace) {
            trace!("Writing data as frame: {data:?}");
        }

        $transport.write_frame(data).await?
    }};
}

macro_rules! next_frame_as {
    ($transport:expr, $type:ident, $variant:ident) => {{
        match { next_frame_as!($transport, $type) } {
            $type::$variant(x) => x,
            x => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Unexpected frame: {x:?}"),
                ))
            }
        }
    }};
    ($transport:expr, $type:ident) => {{
        let frame = $transport.read_frame().await?.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::UnexpectedEof,
                concat!(
                    "Transport closed early waiting for frame of type ",
                    stringify!($type),
                ),
            )
        })?;

        match utils::deserialize_from_slice::<$type>(frame.as_item()) {
            Ok(frame) => frame,
            Err(x) => {
                if log_enabled!(Level::Trace) {
                    trace!(
                        "Failed to deserialize frame item as {}: {:?}",
                        stringify!($type),
                        frame.as_item()
                    );
                }

                Err(x)?;
                unreachable!();
            }
        }
    }};
}

#[async_trait]
impl<T> Authenticate for FramedTransport<T>
where
    T: Transport,
{
    async fn authenticate(&mut self, mut handler: impl AuthHandler + Send) -> io::Result<()> {
        loop {
            trace!("Authenticate::authenticate waiting on next authentication frame");
            match next_frame_as!(self, Authentication) {
                Authentication::Initialization(x) => {
                    trace!("Authenticate::Initialization({x:?})");
                    let response = handler.on_initialization(x).await?;
                    write_frame!(self, AuthenticationResponse::Initialization(response));
                }
                Authentication::Challenge(x) => {
                    trace!("Authenticate::Challenge({x:?})");
                    let response = handler.on_challenge(x).await?;
                    write_frame!(self, AuthenticationResponse::Challenge(response));
                }
                Authentication::Verification(x) => {
                    trace!("Authenticate::Verify({x:?})");
                    let response = handler.on_verification(x).await?;
                    write_frame!(self, AuthenticationResponse::Verification(response));
                }
                Authentication::Info(x) => {
                    trace!("Authenticate::Info({x:?})");
                    handler.on_info(x).await?;
                }
                Authentication::Error(x) => {
                    trace!("Authenticate::Error({x:?})");
                    handler.on_error(x.clone()).await?;

                    if x.is_fatal() {
                        return Err(x.into_io_permission_denied());
                    }
                }
                Authentication::StartMethod(x) => {
                    trace!("Authenticate::StartMethod({x:?})");
                    handler.on_start_method(x).await?;
                }
                Authentication::Finished => {
                    trace!("Authenticate::Finished");
                    handler.on_finished().await?;
                    return Ok(());
                }
            }
        }
    }
}

#[async_trait]
impl<T> Authenticator for FramedTransport<T>
where
    T: Transport,
{
    async fn initialize(
        &mut self,
        initialization: Initialization,
    ) -> io::Result<InitializationResponse> {
        trace!("Authenticator::initialize({initialization:?})");
        write_frame!(self, Authentication::Initialization(initialization));
        let response = next_frame_as!(self, AuthenticationResponse, Initialization);
        Ok(response)
    }

    async fn challenge(&mut self, challenge: Challenge) -> io::Result<ChallengeResponse> {
        trace!("Authenticator::challenge({challenge:?})");
        write_frame!(self, Authentication::Challenge(challenge));
        let response = next_frame_as!(self, AuthenticationResponse, Challenge);
        Ok(response)
    }

    async fn verify(&mut self, verification: Verification) -> io::Result<VerificationResponse> {
        trace!("Authenticator::verify({verification:?})");
        write_frame!(self, Authentication::Verification(verification));
        let response = next_frame_as!(self, AuthenticationResponse, Verification);
        Ok(response)
    }

    async fn info(&mut self, info: Info) -> io::Result<()> {
        trace!("Authenticator::info({info:?})");
        write_frame!(self, Authentication::Info(info));
        Ok(())
    }

    async fn error(&mut self, error: Error) -> io::Result<()> {
        trace!("Authenticator::error({error:?})");
        write_frame!(self, Authentication::Error(error));
        Ok(())
    }

    async fn start_method(&mut self, start_method: StartMethod) -> io::Result<()> {
        trace!("Authenticator::start_method({start_method:?})");
        write_frame!(self, Authentication::StartMethod(start_method));
        Ok(())
    }

    async fn finished(&mut self) -> io::Result<()> {
        trace!("Authenticator::finished()");
        write_frame!(self, Authentication::Finished);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use distant_auth::tests::TestAuthHandler;
    use test_log::test;
    use tokio::sync::mpsc;

    use super::*;

    #[test(tokio::test)]
    async fn authenticator_initialization_should_be_able_to_successfully_complete_round_trip() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_initialization: Box::new(|x| Ok(InitializationResponse { methods: x.methods })),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        let response = t1
            .initialize(Initialization {
                methods: vec!["test method".to_string()].into_iter().collect(),
            })
            .await
            .unwrap();

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );

        assert_eq!(
            response,
            InitializationResponse {
                methods: vec!["test method".to_string()].into_iter().collect()
            }
        );
    }

    #[test(tokio::test)]
    async fn authenticator_challenge_should_be_able_to_successfully_complete_round_trip() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_challenge: Box::new(|challenge| {
                    assert_eq!(
                        challenge.questions,
                        vec![Question {
                            label: "label".to_string(),
                            text: "text".to_string(),
                            options: vec![(
                                "question_key".to_string(),
                                "question_value".to_string()
                            )]
                            .into_iter()
                            .collect(),
                        }]
                    );
                    assert_eq!(
                        challenge.options,
                        vec![("key".to_string(), "value".to_string())]
                            .into_iter()
                            .collect(),
                    );
                    Ok(ChallengeResponse {
                        answers: vec!["some answer".to_string()].into_iter().collect(),
                    })
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        let response = t1
            .challenge(Challenge {
                questions: vec![Question {
                    label: "label".to_string(),
                    text: "text".to_string(),
                    options: vec![("question_key".to_string(), "question_value".to_string())]
                        .into_iter()
                        .collect(),
                }],
                options: vec![("key".to_string(), "value".to_string())]
                    .into_iter()
                    .collect(),
            })
            .await
            .unwrap();

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );

        assert_eq!(
            response,
            ChallengeResponse {
                answers: vec!["some answer".to_string()],
            }
        );
    }

    #[test(tokio::test)]
    async fn authenticator_verification_should_be_able_to_successfully_complete_round_trip() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_verification: Box::new(|verification| {
                    assert_eq!(verification.kind, VerificationKind::Host);
                    assert_eq!(verification.text, "some text");
                    Ok(VerificationResponse { valid: true })
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        let response = t1
            .verify(Verification {
                kind: VerificationKind::Host,
                text: "some text".to_string(),
            })
            .await
            .unwrap();

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );

        assert_eq!(response, VerificationResponse { valid: true });
    }

    #[test(tokio::test)]
    async fn authenticator_info_should_be_able_to_be_sent_to_auth_handler() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);
        let (tx, mut rx) = mpsc::channel(1);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_info: Box::new(move |info| {
                    tx.try_send(info).unwrap();
                    Ok(())
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        t1.info(Info {
            text: "some text".to_string(),
        })
        .await
        .unwrap();

        assert_eq!(
            rx.recv().await.unwrap(),
            Info {
                text: "some text".to_string()
            }
        );

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );
    }

    #[test(tokio::test)]
    async fn authenticator_error_should_be_able_to_be_sent_to_auth_handler() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);
        let (tx, mut rx) = mpsc::channel(1);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_error: Box::new(move |error| {
                    tx.try_send(error).unwrap();
                    Ok(())
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        t1.error(Error {
            kind: ErrorKind::Error,
            text: "some text".to_string(),
        })
        .await
        .unwrap();

        assert_eq!(
            rx.recv().await.unwrap(),
            Error {
                kind: ErrorKind::Error,
                text: "some text".to_string(),
            }
        );

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );
    }

    #[test(tokio::test)]
    async fn auth_handler_received_error_should_fail_auth_handler_if_fatal() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);
        let (tx, mut rx) = mpsc::channel(1);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_error: Box::new(move |error| {
                    tx.try_send(error).unwrap();
                    Ok(())
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        t1.error(Error {
            kind: ErrorKind::Fatal,
            text: "some text".to_string(),
        })
        .await
        .unwrap();

        assert_eq!(
            rx.recv().await.unwrap(),
            Error {
                kind: ErrorKind::Fatal,
                text: "some text".to_string(),
            }
        );

        // Verify that the handler exited with an error
        task.await.unwrap_err();
    }

    #[test(tokio::test)]
    async fn authenticator_start_method_should_be_able_to_be_sent_to_auth_handler() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);
        let (tx, mut rx) = mpsc::channel(1);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_start_method: Box::new(move |start_method| {
                    tx.try_send(start_method).unwrap();
                    Ok(())
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        t1.start_method(StartMethod {
            method: "some method".to_string(),
        })
        .await
        .unwrap();

        assert_eq!(
            rx.recv().await.unwrap(),
            StartMethod {
                method: "some method".to_string()
            }
        );

        assert!(
            !task.is_finished(),
            "Auth handler unexpectedly finished without signal"
        );
    }

    #[test(tokio::test)]
    async fn authenticator_finished_should_be_able_to_be_sent_to_auth_handler() {
        let (mut t1, mut t2) = FramedTransport::test_pair(100);
        let (tx, mut rx) = mpsc::channel(1);

        let task = tokio::spawn(async move {
            t2.authenticate(TestAuthHandler {
                on_finished: Box::new(move || {
                    tx.try_send(()).unwrap();
                    Ok(())
                }),
                ..Default::default()
            })
            .await
            .unwrap()
        });

        t1.finished().await.unwrap();

        // Verify that the callback was triggered
        rx.recv().await.unwrap();

        // Finished should signal that the handler completed successfully
        task.await.unwrap();
    }
}