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
use std::io;
use std::str::FromStr;

use async_trait::async_trait;

use crate::authenticator::Authenticator;
use crate::methods::AuthenticationMethod;
use crate::msg::{Challenge, Error, Question};

/// Authenticaton method for a static secret key
#[derive(Clone, Debug)]
pub struct StaticKeyAuthenticationMethod<T> {
    key: T,
}

impl<T> StaticKeyAuthenticationMethod<T> {
    #[inline]
    pub fn new(key: T) -> Self {
        Self { key }
    }
}

#[async_trait]
impl<T> AuthenticationMethod for StaticKeyAuthenticationMethod<T>
where
    T: FromStr + PartialEq + Send + Sync,
{
    fn id(&self) -> &'static str {
        "static_key"
    }

    async fn authenticate(&self, authenticator: &mut dyn Authenticator) -> io::Result<()> {
        let response = authenticator
            .challenge(Challenge {
                questions: vec![Question {
                    label: "key".to_string(),
                    text: "Provide a key: ".to_string(),
                    options: Default::default(),
                }],
                options: Default::default(),
            })
            .await?;

        if response.answers.is_empty() {
            return Err(Error::non_fatal("missing answer").into_io_permission_denied());
        }

        match response.answers.into_iter().next().unwrap().parse::<T>() {
            Ok(key) if key == self.key => Ok(()),
            _ => Err(Error::non_fatal("answer does not match key").into_io_permission_denied()),
        }
    }
}

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

    use super::*;
    use crate::authenticator::TestAuthenticator;
    use crate::msg::*;

    #[test(tokio::test)]
    async fn authenticate_should_fail_if_key_challenge_fails() {
        let method = StaticKeyAuthenticationMethod::new(String::new());

        let mut authenticator = TestAuthenticator {
            challenge: Box::new(|_| Err(io::Error::new(io::ErrorKind::InvalidData, "test error"))),
            ..Default::default()
        };

        let err = method.authenticate(&mut authenticator).await.unwrap_err();

        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert_eq!(err.to_string(), "test error");
    }

    #[test(tokio::test)]
    async fn authenticate_should_fail_if_no_answer_included_in_challenge_response() {
        let method = StaticKeyAuthenticationMethod::new(String::new());

        let mut authenticator = TestAuthenticator {
            challenge: Box::new(|_| {
                Ok(ChallengeResponse {
                    answers: Vec::new(),
                })
            }),
            ..Default::default()
        };

        let err = method.authenticate(&mut authenticator).await.unwrap_err();

        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
        assert_eq!(err.to_string(), "Error: missing answer");
    }

    #[test(tokio::test)]
    async fn authenticate_should_fail_if_answer_does_not_match_key() {
        let method = StaticKeyAuthenticationMethod::new(String::from("answer"));

        let mut authenticator = TestAuthenticator {
            challenge: Box::new(|_| {
                Ok(ChallengeResponse {
                    answers: vec![String::from("other")],
                })
            }),
            ..Default::default()
        };

        let err = method.authenticate(&mut authenticator).await.unwrap_err();

        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
        assert_eq!(err.to_string(), "Error: answer does not match key");
    }

    #[test(tokio::test)]
    async fn authenticate_should_succeed_if_answer_matches_key() {
        let method = StaticKeyAuthenticationMethod::new(String::from("answer"));

        let mut authenticator = TestAuthenticator {
            challenge: Box::new(|_| {
                Ok(ChallengeResponse {
                    answers: vec![String::from("answer")],
                })
            }),
            ..Default::default()
        };

        method.authenticate(&mut authenticator).await.unwrap();
    }
}