component.rs

 1// Copyright (c) 2018 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
 2//
 3// This Source Code Form is subject to the terms of the Mozilla Public
 4// License, v. 2.0. If a copy of the MPL was not distributed with this
 5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
 6
 7use crate::util::helpers::PlainText;
 8use digest::Digest;
 9use sha1::Sha1;
10
11generate_element!(
12    /// The main authentication mechanism for components.
13    #[derive(Default)]
14    Handshake, "handshake", COMPONENT,
15    text: (
16        /// If Some, contains the hex-encoded SHA-1 of the concatenation of the
17        /// stream id and the password, and is used to authenticate against the
18        /// server.
19        ///
20        /// If None, it is the successful reply from the server, the stream is now
21        /// fully established and both sides can now exchange stanzas.
22        data: PlainText<Option<String>>
23    )
24);
25
26impl Handshake {
27    /// Creates a successful reply from a server.
28    pub fn new() -> Handshake {
29        Handshake::default()
30    }
31
32    /// Creates an authentication request from the component.
33    pub fn from_password_and_stream_id(password: &str, stream_id: &str) -> Handshake {
34        let input = String::from(stream_id) + password;
35        let hash = Sha1::digest(input.as_bytes());
36        let content = format!("{:x}", hash);
37        Handshake {
38            data: Some(content),
39        }
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use crate::Element;
47    use std::convert::TryFrom;
48
49    #[cfg(target_pointer_width = "32")]
50    #[test]
51    fn test_size() {
52        assert_size!(Handshake, 12);
53    }
54
55    #[cfg(target_pointer_width = "64")]
56    #[test]
57    fn test_size() {
58        assert_size!(Handshake, 24);
59    }
60
61    #[test]
62    fn test_simple() {
63        let elem: Element = "<handshake xmlns='jabber:component:accept'/>"
64            .parse()
65            .unwrap();
66        let handshake = Handshake::try_from(elem).unwrap();
67        assert_eq!(handshake.data, None);
68
69        let elem: Element = "<handshake xmlns='jabber:component:accept'>Coucou</handshake>"
70            .parse()
71            .unwrap();
72        let handshake = Handshake::try_from(elem).unwrap();
73        assert_eq!(handshake.data, Some(String::from("Coucou")));
74    }
75
76    #[test]
77    fn test_constructors() {
78        let handshake = Handshake::new();
79        assert_eq!(handshake.data, None);
80
81        let handshake = Handshake::from_password_and_stream_id("123456", "sid");
82        assert_eq!(
83            handshake.data,
84            Some(String::from("9accec263ab84a43c6037ccf7cd48cb1d3f6df8e"))
85        );
86    }
87}