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
use crate::error::Result;
use crate::types::CBytes;

/// Handles SASL authentication.
///
/// The lifecycle of an authenticator consists of:
/// - The `initial_response` function will be called. The initial return value will be sent to the
/// server to initiate the handshake.
/// - The server will respond to each client response by either issuing a challenge or indicating
///  that the authentication is complete (successfully or not). If a new challenge is issued,
///  the authenticator's `evaluate_challenge` function will be called to produce a response
///  that will be sent to the server. This challenge/response negotiation will continue until
///  the server responds that authentication is successful or an error is raised.
/// - On success, the `handle_success` will be called with data returned by the server.
pub trait SaslAuthenticator {
    fn initial_response(&self) -> CBytes;

    fn evaluate_challenge(&self, challenge: CBytes) -> Result<CBytes>;

    fn handle_success(&self, data: CBytes) -> Result<()>;
}

/// Provides authenticators per new connection.
pub trait SaslAuthenticatorProvider {
    fn name(&self) -> Option<&str>;

    fn create_authenticator(&self) -> Box<dyn SaslAuthenticator + Send>;
}

#[derive(Debug, Clone)]
pub struct StaticPasswordAuthenticator {
    username: String,
    password: String,
}

impl StaticPasswordAuthenticator {
    pub fn new<S: ToString>(username: S, password: S) -> StaticPasswordAuthenticator {
        StaticPasswordAuthenticator {
            username: username.to_string(),
            password: password.to_string(),
        }
    }
}

impl SaslAuthenticator for StaticPasswordAuthenticator {
    fn initial_response(&self) -> CBytes {
        let mut token = vec![0];
        token.extend_from_slice(self.username.as_bytes());
        token.push(0);
        token.extend_from_slice(self.password.as_bytes());

        CBytes::new(token)
    }

    fn evaluate_challenge(&self, _challenge: CBytes) -> Result<CBytes> {
        Err("Server challenge is not supported for StaticPasswordAuthenticator!".into())
    }

    fn handle_success(&self, _data: CBytes) -> Result<()> {
        Ok(())
    }
}

/// Authentication provider with a username and password.
#[derive(Debug, Clone)]
pub struct StaticPasswordAuthenticatorProvider {
    username: String,
    password: String,
}

impl SaslAuthenticatorProvider for StaticPasswordAuthenticatorProvider {
    fn name(&self) -> Option<&str> {
        Some("org.apache.cassandra.auth.PasswordAuthenticator")
    }

    fn create_authenticator(&self) -> Box<dyn SaslAuthenticator + Send> {
        Box::new(StaticPasswordAuthenticator::new(
            self.username.clone(),
            self.password.clone(),
        ))
    }
}

impl StaticPasswordAuthenticatorProvider {
    pub fn new<S: ToString>(username: S, password: S) -> Self {
        StaticPasswordAuthenticatorProvider {
            username: username.to_string(),
            password: password.to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct NoneAuthenticator;

impl SaslAuthenticator for NoneAuthenticator {
    fn initial_response(&self) -> CBytes {
        CBytes::new(vec![0])
    }

    fn evaluate_challenge(&self, _challenge: CBytes) -> Result<CBytes> {
        Err("Server challenge is not supported for NoneAuthenticator!".into())
    }

    fn handle_success(&self, _data: CBytes) -> Result<()> {
        Ok(())
    }
}

/// Provider for no authentication.
#[derive(Debug, Clone)]
pub struct NoneAuthenticatorProvider;

impl SaslAuthenticatorProvider for NoneAuthenticatorProvider {
    fn name(&self) -> Option<&str> {
        None
    }

    fn create_authenticator(&self) -> Box<dyn SaslAuthenticator + Send> {
        Box::new(NoneAuthenticator)
    }
}

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

    #[test]
    fn test_static_password_authenticator_new() {
        StaticPasswordAuthenticator::new("foo", "bar");
    }

    #[test]
    fn test_static_password_authenticator_cassandra_name() {
        let auth = StaticPasswordAuthenticatorProvider::new("foo", "bar");
        assert_eq!(
            auth.name(),
            Some("org.apache.cassandra.auth.PasswordAuthenticator")
        );
    }

    #[test]
    fn test_authenticator_none_cassandra_name() {
        let auth = NoneAuthenticator;
        let provider = NoneAuthenticatorProvider;
        assert_eq!(provider.name(), None);
        assert_eq!(auth.initial_response().into_bytes().unwrap(), vec![0]);
    }
}