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

use log::*;
use sha1::Sha1;

/// authentication using hashes based on a shared secret

pub fn sha_auth(login: &String, token: &String, secret: &String, secret_timeout: i64, now: i64) -> Result<String, ()> {

    let mut sha1 = Sha1::new();
    sha1.update(login.as_bytes());
    sha1.update(secret.as_bytes());
    let sha_res = sha1.digest().bytes();
    let encoded = base64::encode(sha_res.as_ref());
    if encoded.eq(token) {
        return check_timeout(login, secret_timeout, now);
    } else {
        debug!("sha check failed '{}' '{}'", encoded, token);
    }


    Err(())
}


/// Check that the login has not timed out, login must be   login + ' ' + timestamp + ' ' + random
fn check_timeout(login: &String, secret_timeout: i64, now: i64) -> Result<String, ()> {
    let mut username = "";
    for (i, part) in login.split_whitespace().enumerate() {
        if i == 0 {
            username = part;
        }
        if i == 1 {
            if let Ok(timestamp) = part.parse::<i64>() {
                if  timestamp * 1000 > now - secret_timeout {
                    return Ok(String::from(username));
                }
            }
        }
    }

    debug!("timeout check failed");
    Err(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_happy_path() {
        let secret = String::from("XIxoIl6ngolYKQOrXpunRLCMWxR6O0lDI+HycNN4Ffo=");
        // for test purposes set the timestamp of the hash and the current date to zero
        // hash generated with  echo -n "harry 0 randXIxoIl6ngolYKQOrXpunRLCMWxR6O0lDI+HycNN4Ffo=" | sha1sum | awk '{print $1}' | xxd -r -p - - | base64
        assert_eq!("harry", sha_auth(&String::from("harry 0 rand"), &String::from("9hdbYaisq45xkYhCJQCubqzxBZU="), &secret, 60000, 0).unwrap());

    }

    #[test]
    fn test_auth_timeout() {
        let secret = String::from("XIxoIl6ngolYKQOrXpunRLCMWxR6O0lDI+HycNN4Ffo=");

        assert_eq!(Some(()), sha_auth(&String::from("harry 0 rand"), &String::from("9hdbYaisq45xkYhCJQCubqzxBZU="), &secret, 60000, 60001).err());
    }
}