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::text_node_codecs::{Codec, OptionalCodec, Text};
 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: OptionalCodec<Text>
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
48    #[cfg(target_pointer_width = "32")]
49    #[test]
50    fn test_size() {
51        assert_size!(Handshake, 12);
52    }
53
54    #[cfg(target_pointer_width = "64")]
55    #[test]
56    fn test_size() {
57        assert_size!(Handshake, 24);
58    }
59
60    #[test]
61    fn test_simple() {
62        let elem: Element = "<handshake xmlns='jabber:component:accept'/>"
63            .parse()
64            .unwrap();
65        let handshake = Handshake::try_from(elem).unwrap();
66        assert_eq!(handshake.data, None);
67
68        let elem: Element = "<handshake xmlns='jabber:component:accept'>Coucou</handshake>"
69            .parse()
70            .unwrap();
71        let handshake = Handshake::try_from(elem).unwrap();
72        assert_eq!(handshake.data, Some(String::from("Coucou")));
73    }
74
75    #[test]
76    fn test_constructors() {
77        let handshake = Handshake::new();
78        assert_eq!(handshake.data, None);
79
80        let handshake = Handshake::from_password_and_stream_id("123456", "sid");
81        assert_eq!(
82            handshake.data,
83            Some(String::from("9accec263ab84a43c6037ccf7cd48cb1d3f6df8e"))
84        );
85    }
86}