portal-lib 0.3.0

A Secure file transfer library, written in Rust. The library utilizes SPAKE2 for key negotiation over an insecure channel, and ChaCha20Poly1305 Authenticated Encryption to encrypt the file with the derived shared symmetric key. This enables two peers to transfer a file over any channel without needing to trust the intermediary relay.
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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! portal-lib
//!
//! A small Protocol Library for [Portal](https://github.com/landhb/portal) - An encrypted file transfer utility
//!
//! This crate enables a consumer to:
//!
//! - Create/serialize/deserialize Portal request/response messages.
//! - Negoticate a symmetric key with a peer using [SPAKE2](https://docs.rs/spake2/0.2.0/spake2)
//! - Encrypt files with [Chacha20poly1305](https://blog.cloudflare.com/it-takes-two-to-chacha-poly/) using the [RustCrypto implementation](https://github.com/rusticata/tls-parser)
//! - Send/receive files through a Portal relay
//!
//!
//! Example of SPAKE2 key negotiation:
//!
//! ```no_run
//! use portal_lib::{Portal,Direction};
//!
//! // receiver
//! let id = "id".to_string();
//! let pass ="test".to_string();
//! let (mut receiver,receiver_msg) = Portal::init(Direction::Receiver,id,pass,None);
//!
//! // sender
//! let id = "id".to_string();
//! let pass ="test".to_string();
//! let (mut sender,sender_msg) = Portal::init(Direction::Sender,id,pass,None);
//!
//! // Both clients should derive the same key
//! receiver.derive_key(&sender_msg).unwrap();
//! sender.derive_key(&receiver_msg).unwrap();
//!
//! ```
//! You can use the `Portal::confirm_peer()` method to verify that a remote peer has derived the same key
//! as you, as long as the communication stream implements the std::io::Read and std::io::Write traits.
//!
//! Example of Sending a file:
//!
//! ```no_run
//! use portal_lib::{Portal,Direction};
//! use std::net::TcpStream;
//! use std::io::Write;
//!
//! let mut client = TcpStream::connect("127.0.0.1:34254").unwrap();
//!
//! // Create portal request as the Sender
//! let id = "id".to_string();
//! let pass ="test".to_string();
//! let (mut portal,msg) = Portal::init(Direction::Sender,id,pass,None);
//!
//! // complete key derivation + peer verification
//!
//! let mut file = portal.load_file("/tmp/test").unwrap();
//!
//! // Encrypt the file and share state
//! file.encrypt().unwrap();
//! file.sync_file_state(&mut client).unwrap();
//!
//! for data in file.get_chunks(portal_lib::CHUNK_SIZE) {
//!     client.write_all(&data).unwrap();
//! }
//! ```
//!
//! Example of Receiving a file:
//!
//! ```no_run
//! use portal_lib::{Portal,Direction};
//! use std::net::TcpStream;
//! use std::io::Write;
//!
//! let mut client = TcpStream::connect("127.0.0.1:34254").unwrap();
//!
//! // receiver
//! let dir = Direction::Receiver;
//! let pass ="test".to_string();
//! let (mut portal,msg) = Portal::init(dir,"id".to_string(),pass,None);
//!
//! // serialize & send request
//! let request = portal.serialize().unwrap();
//! client.write_all(&request).unwrap();
//!
//! // get response
//! let response = Portal::read_response_from(&client).unwrap();
//!
//! // complete key derivation + peer verification
//!
//! // create outfile
//! let fsize = response.get_file_size();
//! let mut file = portal.create_file("/tmp/test", fsize).unwrap();
//!
//! let callback = |x| { println!("Received {} bytes",x); };
//!
//! // Receive until connection is done
//! let len = file.download_file(&client,callback).unwrap();
//!
//! assert_eq!(len as u64, fsize);
//!
//! // Decrypt the file
//! file.decrypt().unwrap();
//! ```
use anyhow::Result;
use memmap::MmapOptions;
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::fs::File;
use std::fs::OpenOptions;

// Key Exchange
use hkdf::Hkdf;
use sha2::{Digest, Sha256};
use spake2::{Ed25519Group, Identity, Password, SPAKE2};

// File encryption
use chacha20poly1305::aead::NewAead;
use chacha20poly1305::{aead::AeadInPlace, ChaCha20Poly1305, Key, Nonce, Tag};

// Nonce generation
use rand::Rng;

mod chunks;
pub mod errors;
pub mod file;

use errors::PortalError::*;
use file::{PortalFile, StateMetadata};

/**
 * Arbitrary port for the Portal protocol
 */
pub const DEFAULT_PORT: u16 = 13265;

/**
 * Default chunk size
 */
pub const CHUNK_SIZE: usize = 65536;

/**
 * A data format exchanged by each peer to derive
 * the shared session key
 */
pub type PortalConfirmation = [u8; 33];

/**
 * The primary interface into the library. The Portal struct
 * contains data associated with either a new request or a response
 * from a peer.
 */
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct Portal {
    // Information to correlate
    // connections on the relay
    id: String,
    direction: Direction,

    /// Metadata not sent until key is derived
    #[serde(skip)]
    metadata: Metadata,

    // Never serialized or sent to the relay
    #[serde(skip)]
    state: Option<SPAKE2<Ed25519Group>>,

    // Never serialized or sent to the relay
    #[serde(skip)]
    key: Option<Vec<u8>>,
}

/**
 * Metadata about the transfer to be exchanged
 * between peers after key derivation (encrypted)
 */
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Default)]
pub struct Metadata {
    filesize: u64,
    filename: Option<Vec<u8>>,
}

/**
 * An enum to describe the direction of each file transfer
 * participant (i.e Sender/Receiver)
 */
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum Direction {
    Sender,
    Receiver,
}

/**
 * Method to compair arbitrary &[u8] slices, used internally
 * to compare key exchange and derivation data
 */
fn compare_key_derivations(a: &[u8], b: &[u8]) -> std::cmp::Ordering {
    for (ai, bi) in a.iter().zip(b.iter()) {
        match ai.cmp(&bi) {
            std::cmp::Ordering::Equal => continue,
            ord => return ord,
        }
    }

    /* if every single element was equal, compare length */
    a.len().cmp(&b.len())
}

impl Portal {
    /**
     * Initialize a new portal request
     *
     * # Example
     *
     * ```
     * use portal_lib::{Portal,Direction};
     *
     * // the shared password should be secret and hard to guess/crack
     * // see the portal-client as an example of potential usage
     * let id = "my client ID".to_string();
     * let password = "testpasswd".to_string();
     * let portal = Portal::init(Direction::Sender,id,password,None);
     * ```
     */
    pub fn init(
        direction: Direction,
        id: String,
        password: String,
        mut filename: Option<String>,
    ) -> (Portal, PortalConfirmation) {
        // hash the ID string
        let mut hasher = Sha256::new();
        hasher.update(&id);
        let id_bytes = hasher.finalize();
        let id_hash = hex::encode(&id_bytes);

        let (s1, outbound_msg) = SPAKE2::<Ed25519Group>::start_symmetric(
            &Password::new(&password.as_bytes()),
            &Identity::new(&id_bytes),
        );

        // if a file was provided, trim it to just the file name
        if let Some(file) = filename {
            let f = std::path::Path::new(&file);
            let f = f.file_name().unwrap().to_str().unwrap();
            filename = Some(f.to_string());
        }

        // Convert the filename to bytes
        let metadata = Metadata {
            filesize: 0,
            filename: filename.map_or(None, |v| Some(v.as_bytes().to_vec())),
        };

        (
            Portal {
                direction,
                id: id_hash,
                metadata,
                state: Some(s1),
                key: None,
            },
            outbound_msg.try_into().expect("Bad message format"),
        )
    }

    /**
     * Initialize with existing data, attempting to deserialize bytes
     * into a Portal struct
     *
     * # Example
     *
     * ```
     * use portal_lib::Portal;
     * use std::io::Read;
     * fn example(mut client: std::net::TcpStream) {
     *     let mut buf = [0; 1024];
     *     let len = client.read(&mut buf);
     *     let response = match Portal::parse(&buf) {
     *          Ok(r) => r,
     *          Err(_) => {
     *               println!("Failed to read request/response...");
     *               return;
     *          }
     *     };
     * }
     * ```
     */
    pub fn parse(data: &[u8]) -> Result<Portal> {
        Ok(bincode::deserialize(&data)?)
    }

    /**
     * Initialize by reading from a stream that implements the
     * std::io::Read trait, consuming the bytes
     *
     * # Example
     *
     * ```
     * use portal_lib::Portal;
     * fn example(client: std::net::TcpStream) {
     *     let response = match Portal::read_response_from(&client) {
     *          Ok(r) => r,
     *          Err(_) => {
     *               println!("Failed to read response...");
     *               return;
     *          }
     *     };
     * }
     * ```
     */
    pub fn read_response_from<R>(reader: R) -> Result<Portal>
    where
        R: std::io::Read,
    {
        Ok(bincode::deserialize_from::<R, Portal>(reader)?)
    }

    /**
     * Receive the bytes necessary for a confirmation message
     * from a stream that implements std::io::Read, consuming the bytes
     */
    pub fn read_confirmation_from<R>(mut reader: R) -> Result<PortalConfirmation>
    where
        R: std::io::Read,
    {
        let mut res: PortalConfirmation = [0u8; 33];
        reader.read_exact(&mut res)?;
        Ok(res)
    }

    /**
     * Receive the bytes necessary to receive file Metadata
     * from a stream that implements std::io::Read, consuming the bytes
     */
    pub fn read_metadata_from<R>(&mut self, mut reader: R) -> Result<()>
    where
        R: std::io::Read,
    {
        // Obtain the cipher from the key
        let key = self.key.as_ref().ok_or(NoPeer)?;
        let cha_key = Key::from_slice(&key[..]);
        let cipher = ChaCha20Poly1305::new(cha_key);

        // Receive the encryption state
        let state: StateMetadata = bincode::deserialize_from(&mut reader).or(Err(BadMsg))?;

        // Receive the data
        let mut data: Vec<u8> = bincode::deserialize_from(&mut reader).or(Err(BadMsg))?;

        // Verify nonce & tag lengths
        if state.nonce.len() != std::mem::size_of::<Nonce>()
            || state.tag.len() != std::mem::size_of::<Tag>()
        {
            return Err(BadState.into());
        }

        // Decrypt the data
        let nonce = Nonce::from_slice(&state.nonce);
        let tag = Tag::from_slice(&state.tag);
        match cipher.decrypt_in_place_detached(&nonce, b"", &mut data, &tag) {
            Ok(_) => {}
            Err(_e) => return Err(DecryptError.into()),
        }

        // Validate the metadata
        let mdata: Metadata = bincode::deserialize(&data)?;

        // Save to self
        self.metadata = mdata;
        Ok(())
    }

    /**
     * Encrypt & write file metadata to the peer
     */
    pub fn write_metadata_to<W>(&mut self, mut writer: W) -> Result<usize>
    where
        W: std::io::Write,
    {
        // Init state to send
        let mut state = StateMetadata::default();

        // Generate random nonce
        let mut rng = rand::thread_rng();
        let rbytes = rng.gen::<[u8; 12]>();
        let nonce = Nonce::from_slice(&rbytes);
        state.nonce.extend(nonce);

        // Obtain the cipher from the key
        let key = self.key.as_ref().ok_or(NoPeer)?;
        let cha_key = Key::from_slice(&key[..]);
        let cipher = ChaCha20Poly1305::new(cha_key);

        // Serialize all the metadata
        let mut data: Vec<u8> = bincode::serialize(&self.metadata)?;

        // Encrypt the metadata in-place
        let tag = match cipher.encrypt_in_place_detached(nonce, b"", &mut data) {
            Ok(tag) => tag,
            Err(_e) => return Err(EncryptError.into()),
        };
        state.tag.extend(tag);

        // Wrap the encrypted buffer so that it may be deserialized
        let mut finaldata = bincode::serialize(&state)?;
        finaldata.extend_from_slice(&bincode::serialize(&data)?);

        // Send the encrypted state & metadata
        writer.write_all(&finaldata).or(Err(IOError))?;
        Ok(data.len())
    }

    /**
     * Attempt to serialize a Portal struct into a vector
     */
    pub fn serialize(&self) -> Result<Vec<u8>> {
        Ok(bincode::serialize(&self)?)
    }

    /*
     * mmap's a file into memory for reading
     */
    pub fn load_file<'a>(&'a self, f: &str) -> Result<PortalFile> {
        let file = File::open(f)?;
        let mmap = unsafe { MmapOptions::new().map_copy(&file)? };

        let key = self.key.as_ref().ok_or(NoPeer)?;
        let cha_key = Key::from_slice(&key[..]);

        let cipher = ChaCha20Poly1305::new(cha_key);

        Ok(PortalFile::init(mmap, cipher))
    }

    /*
     * mmap's a file into memory for writing
     */
    pub fn create_file<'a>(&'a self, f: &str, size: u64) -> Result<PortalFile> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .open(&f)?;

        file.set_len(size)?;

        let key = self.key.as_ref().ok_or(NoPeer)?;

        let mmap = unsafe { MmapOptions::new().map_mut(&file)? };

        let cha_key = Key::from_slice(&key[..]);
        let cipher = ChaCha20Poly1305::new(cha_key);

        Ok(PortalFile::init(mmap, cipher))
    }

    /**
     * Derive a shared key with the exchanged data
     * at this point in the exchange we have not verified that our peer
     * has derived the same key as us
     */
    pub fn derive_key(&mut self, msg_data: &[u8]) -> Result<()> {
        // after calling finish() the SPAKE2 struct will be consumed
        // so we must replace the value stored in self.state
        let state = std::mem::replace(&mut self.state, None);

        let state = state.ok_or(BadState)?;

        self.key = match state.finish(msg_data) {
            Ok(res) => Some(res),
            Err(_) => {
                return Err(BadMsg.into());
            }
        };

        Ok(())
    }

    /**
     * Confirm that the peer has derived the same key
     */
    pub fn confirm_peer<R>(&mut self, mut client: R) -> Result<()>
    where
        R: std::io::Read + std::io::Write,
    {
        let key = self.key.as_ref().ok_or(NoPeer)?;

        let sender_info = format!("{}-{}", self.id, "senderinfo");
        let receiver_info = format!("{}-{}", self.id, "receiverinfo");

        // Perform key confirmation step
        let h = Hkdf::<Sha256>::new(None, &key);
        let mut peer_msg = [0u8; 42];
        let mut sender_confirm = [0u8; 42];
        let mut receiver_confirm = [0u8; 42];
        h.expand(&sender_info.as_bytes(), &mut sender_confirm)
            .unwrap();
        h.expand(&receiver_info.as_bytes(), &mut receiver_confirm)
            .unwrap();

        match self.direction {
            Direction::Sender => {
                client.write_all(&sender_confirm)?;
                client.read_exact(&mut peer_msg)?;

                if compare_key_derivations(&peer_msg, &receiver_confirm)
                    != std::cmp::Ordering::Equal
                {
                    return Err(BadMsg.into());
                }
            }
            Direction::Receiver => {
                client.write_all(&receiver_confirm)?;
                client.read_exact(&mut peer_msg)?;

                if compare_key_derivations(&peer_msg, &sender_confirm) != std::cmp::Ordering::Equal
                {
                    return Err(BadMsg.into());
                }
            }
        }
        Ok(())
    }

    /**
     * Returns the file size associated with this request
     */
    pub fn get_file_size(&self) -> u64 {
        self.metadata.filesize
    }

    /**
     * Sets the file size associated with this request
     */
    pub fn set_file_size(&mut self, size: u64) {
        self.metadata.filesize = size;
    }

    /**
     * Returns the file name associated with this request
     * or a PortalError::NoneError if none exists
     */
    pub fn get_file_name<'a>(&'a self) -> Result<&'a str> {
        match &self.metadata.filename {
            Some(f) => Ok(std::str::from_utf8(f)?),
            None => Err(NoneError.into()),
        }
    }

    /**
     * Returns a copy of the Portal::Direction associated with
     * this Portal request
     */
    pub fn get_direction(&self) -> Direction {
        self.direction.clone()
    }

    /**
     * Sets the Portal::Direction associated with this Poral request
     */
    pub fn set_direction(&mut self, direction: Direction) {
        self.direction = direction;
    }

    /**
     * Returns a reference to the ID associated with this
     * Portal request
     */
    pub fn get_id(&self) -> &String {
        &self.id
    }

    /**
     * Sets the ID associated with this Poral request
     */
    pub fn set_id(&mut self, id: String) {
        self.id = id;
    }
}

#[cfg(test)]
mod tests {
    use crate::file::tests::MockTcpStream;
    use crate::{errors::PortalError, Direction, Portal, StateMetadata};
    use hkdf::Hkdf;
    use rand::Rng;
    use sha2::Sha256;
    use std::io::Write;

    #[test]
    fn metadata_roundtrip() {
        let fsize = 1337;
        let fname = "filename".to_string();

        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) =
            Portal::init(dir, "id".to_string(), pass, Some(fname.clone()));
        sender.set_file_size(fsize);

        // we need a key to be able to encrypt & decrypt
        receiver.derive_key(sender_msg.as_slice()).unwrap();
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        // Mock channel
        let mut stream = MockTcpStream {
            data: Vec::with_capacity(crate::CHUNK_SIZE),
        };

        // Send metadata
        sender.write_metadata_to(&mut stream).unwrap();

        // Recv metadata
        receiver.read_metadata_from(&mut stream).unwrap();

        // Verify both peers now share the same metadata
        assert_eq!(fsize, receiver.get_file_size());
        assert_eq!(fname, receiver.get_file_name().unwrap());
        assert_eq!(
            sender.get_file_name().unwrap(),
            receiver.get_file_name().unwrap()
        );
        assert_eq!(sender.get_file_size(), receiver.get_file_size());
    }

    #[test]
    fn fail_decrypt_metadata() {
        let fsize = 1337;
        let fname = "filename".to_string();

        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) =
            Portal::init(dir, "id".to_string(), pass, Some(fname.clone()));
        sender.set_file_size(fsize);

        // we need a key to be able to encrypt & decrypt
        receiver.derive_key(sender_msg.as_slice()).unwrap();
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        // Mock channel
        let mut stream = MockTcpStream {
            data: Vec::with_capacity(crate::CHUNK_SIZE),
        };

        // Send garbage state
        let mut garbage = bincode::serialize(&StateMetadata::default()).unwrap();
        garbage.extend_from_slice(&bincode::serialize(&vec![0u8]).unwrap());
        stream.write_all(&garbage).unwrap();

        // Verify error is BadState
        let res = receiver.read_metadata_from(&mut stream);
        assert!(res.is_err());
        let _ = res.map_err(|e| match e.downcast_ref::<PortalError>() {
            Some(PortalError::BadState) => anyhow::Ok(()),
            _ => panic!("Unexpected error"),
        });

        // Send garbage metadata
        let state = StateMetadata {
            nonce: rand::thread_rng().gen::<[u8; 12]>().to_vec(),
            tag: rand::thread_rng().gen::<[u8; 16]>().to_vec(),
        };
        let mut garbage = bincode::serialize(&state).unwrap();
        garbage.extend_from_slice(&bincode::serialize(&vec![0u8]).unwrap());
        stream.write_all(&garbage).unwrap();

        // Verify error is DecryptError
        let res = receiver.read_metadata_from(&mut stream);
        assert!(res.is_err());
        let _ = res.map_err(|e| match e.downcast_ref::<PortalError>() {
            Some(PortalError::DecryptError) => anyhow::Ok(()),
            _ => panic!("Unexpected error"),
        });
    }

    #[test]
    fn key_derivation() {
        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        receiver.derive_key(sender_msg.as_slice()).unwrap();
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        assert_eq!(receiver.key, sender.key);
    }

    #[test]
    fn key_confirmation() {
        let mut receiver_side = MockTcpStream {
            data: Vec::with_capacity(crate::CHUNK_SIZE),
        };

        let mut sender_side = MockTcpStream {
            data: Vec::with_capacity(crate::CHUNK_SIZE),
        };

        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        receiver.derive_key(sender_msg.as_slice()).unwrap();
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        // identifiers known to each party
        let id = receiver.get_id();
        let sender_info = format!("{}-{}", id, "senderinfo");
        let receiver_info = format!("{}-{}", id, "receiverinfo");

        // Perform the HKDF operations
        let h = Hkdf::<Sha256>::new(None, &sender.key.as_ref().unwrap());
        let mut sender_confirm = [0u8; 42];
        let mut receiver_confirm = [0u8; 42];
        h.expand(&sender_info.as_bytes(), &mut sender_confirm)
            .unwrap();
        h.expand(&receiver_info.as_bytes(), &mut receiver_confirm)
            .unwrap();

        // pre-send the appropriate HKDF to each stream, simulating a peer
        receiver_side.write(&sender_confirm).unwrap();
        sender_side.write(&receiver_confirm).unwrap();

        // each side should be able to confirm the other
        receiver.confirm_peer(&mut receiver_side).unwrap();
        sender.confirm_peer(&mut sender_side).unwrap();
    }

    #[test]
    fn portal_load_file() {
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (_receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, _sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // Confirm
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        // TODO change test file
        let _file = sender.load_file("/etc/passwd").unwrap();
    }

    #[test]
    fn portalfile_chunks_iterator() {
        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (_receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, _sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // Confirm
        sender.derive_key(receiver_msg.as_slice()).unwrap();

        // TODO change test file
        let file = sender.load_file("/etc/passwd").unwrap();

        let chunk_size = 10;
        for v in file.get_chunks(chunk_size) {
            assert!(v.len() <= chunk_size);
        }

        let chunk_size = 1024;
        for v in file.get_chunks(chunk_size) {
            assert!(v.len() <= chunk_size);
        }
    }

    #[test]
    fn portal_createfile() {
        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // Confirm
        sender.derive_key(receiver_msg.as_slice()).unwrap();
        receiver.derive_key(sender_msg.as_slice()).unwrap();

        // TODO change test file
        let _file_dst = receiver.create_file("/tmp/passwd", 4096).unwrap();
    }

    #[test]
    fn portal_write_chunk() {
        // receiver
        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (mut receiver, receiver_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // sender
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut sender, sender_msg) = Portal::init(dir, "id".to_string(), pass, None);

        // Confirm
        sender.derive_key(receiver_msg.as_slice()).unwrap();
        receiver.derive_key(sender_msg.as_slice()).unwrap();

        // TODO change test file
        let file_src = sender.load_file("/etc/passwd").unwrap();
        let mut file_dst = receiver.create_file("/tmp/passwd", 4096).unwrap();

        let chunk_size = 4096;
        for v in file_src.get_chunks(chunk_size) {
            assert!(v.len() <= chunk_size);

            // test writing chunk
            file_dst.write_given_chunk(&v).unwrap();
        }
    }

    #[test]
    #[should_panic]
    fn portal_createfile_no_peer() {
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (portal, _msg) = Portal::init(dir, "id".to_string(), pass, None);

        // will panic due to lack of peer
        let _file_dst = portal.create_file("/tmp/passwd", 4096).unwrap();
    }

    #[test]
    #[should_panic]
    fn portal_loadfile_no_peer() {
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (portal, _msg) = Portal::init(dir, "id".to_string(), pass, None);

        // will panic due to lack of peer
        let _file_src = portal.load_file("/etc/passwd").unwrap();
    }

    #[test]
    fn test_file_trim() {
        let file = Some("/my/path/filename.txt".to_string());

        let dir = Direction::Receiver;
        let pass = "test".to_string();
        let (receiver, _receiver_msg) = Portal::init(dir, "id".to_string(), pass, file);

        let result = receiver.get_file_name().unwrap();

        assert_eq!(result, "filename.txt");
    }

    #[test]
    fn test_compressed_edwards_size() {
        // The exchanged message is the CompressedEdwardsY + 1 byte for the SPAKE direction
        let edwards_point = <spake2::Ed25519Group as spake2::Group>::Element::default();
        let compressed = edwards_point.compress();
        let msg_size: usize = std::mem::size_of_val(&compressed) + 1;

        assert_eq!(33, msg_size);
    }

    #[test]
    fn test_getters_setters() {
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (mut portal, _msg) = Portal::init(dir, "id".to_string(), pass, None);

        // get/set ID
        portal.set_id("newID".to_string());
        assert_eq!("newID", portal.get_id());

        // get/set direction
        portal.set_direction(Direction::Receiver);
        assert_eq!(portal.get_direction(), Direction::Receiver);

        // get/set direction
        portal.set_file_size(25);
        assert_eq!(portal.get_file_size(), 25);
    }

    #[test]
    fn test_serialize_deserialize() {
        let dir = Direction::Sender;
        let pass = "test".to_string();
        let (portal, _msg) = Portal::init(dir, "id".to_string(), pass, None);

        let ser = portal.serialize().unwrap();
        let res = Portal::parse(&ser).unwrap();

        // fields that should be the same
        assert_eq!(res.id, portal.id);
        assert_eq!(res.direction, portal.direction);
        assert_eq!(res.metadata.filename, portal.metadata.filename);
        assert_eq!(res.metadata.filesize, portal.metadata.filesize);

        // fields that shouldn't have been serialized
        assert_ne!(res.state, portal.state);
        assert_eq!(res.state, None);
        assert_eq!(res.key, None);
    }
}