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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
mod scram;
#[cfg(test)]
mod test;
use std::{borrow::Cow, str::FromStr};
use bson::Document;
use rand::Rng;
use typed_builder::TypedBuilder;
use self::scram::ScramVersion;
use crate::{
cmap::{Connection, StreamDescription},
error::{Error, ErrorKind, Result},
};
const SCRAM_SHA_1_STR: &str = "SCRAM-SHA-1";
const SCRAM_SHA_256_STR: &str = "SCRAM-SHA-256";
const MONGODB_CR_STR: &str = "MONGODB-CR";
const GSSAPI_STR: &str = "GSSAPI";
const MONGODB_X509_STR: &str = "MONGODB-X509";
const PLAIN_STR: &str = "PLAIN";
#[derive(Clone, PartialEq, Debug)]
pub enum AuthMechanism {
MongoDbCr,
ScramSha1,
ScramSha256,
MongoDbX509,
Gssapi,
Plain,
}
impl AuthMechanism {
pub(crate) fn from_stream_description(description: &StreamDescription) -> AuthMechanism {
let scram_sha_256_found = description
.sasl_supported_mechs
.as_ref()
.map(|ms| ms.iter().any(|m| m == AuthMechanism::ScramSha256.as_str()))
.unwrap_or(false);
if scram_sha_256_found {
AuthMechanism::ScramSha256
} else {
AuthMechanism::ScramSha1
}
}
pub fn validate_credential(&self, credential: &Credential) -> Result<()> {
match self {
AuthMechanism::ScramSha1 | AuthMechanism::ScramSha256 => {
if credential.username.is_none() {
return Err(ErrorKind::ArgumentError {
message: "No username provided for SCRAM authentication".to_string(),
}
.into());
};
Ok(())
}
_ => Ok(()),
}
}
pub fn as_str(&self) -> &'static str {
match self {
AuthMechanism::ScramSha1 => SCRAM_SHA_1_STR,
AuthMechanism::ScramSha256 => SCRAM_SHA_256_STR,
AuthMechanism::MongoDbCr => MONGODB_CR_STR,
AuthMechanism::MongoDbX509 => MONGODB_X509_STR,
AuthMechanism::Gssapi => GSSAPI_STR,
AuthMechanism::Plain => PLAIN_STR,
}
}
pub(crate) fn default_source<'a>(&'a self, uri_db: Option<&'a str>) -> &'a str {
match self {
AuthMechanism::ScramSha1 | AuthMechanism::ScramSha256 | AuthMechanism::MongoDbCr => {
uri_db.unwrap_or("admin")
}
_ => "",
}
}
pub(crate) async fn authenticate_stream(
&self,
stream: &mut Connection,
credential: &Credential,
) -> Result<()> {
match self {
AuthMechanism::ScramSha1 => {
ScramVersion::Sha1
.authenticate_stream(stream, credential)
.await
}
AuthMechanism::ScramSha256 => {
ScramVersion::Sha256
.authenticate_stream(stream, credential)
.await
}
AuthMechanism::MongoDbCr => Err(ErrorKind::AuthenticationError {
message: "MONGODB-CR is deprecated and not supported by this driver. Use SCRAM \
for password-based authentication instead"
.into(),
}
.into()),
_ => Err(ErrorKind::AuthenticationError {
message: format!("Authentication mechanism {:?} not yet implemented.", self),
}
.into()),
}
}
}
impl FromStr for AuthMechanism {
type Err = Error;
fn from_str(str: &str) -> Result<Self> {
match str {
SCRAM_SHA_1_STR => Ok(AuthMechanism::ScramSha1),
SCRAM_SHA_256_STR => Ok(AuthMechanism::ScramSha256),
MONGODB_CR_STR => Ok(AuthMechanism::MongoDbCr),
MONGODB_X509_STR => Ok(AuthMechanism::MongoDbX509),
GSSAPI_STR => Ok(AuthMechanism::Gssapi),
PLAIN_STR => Ok(AuthMechanism::Plain),
_ => Err(ErrorKind::ArgumentError {
message: format!("invalid mechanism string: {}", str),
}
.into()),
}
}
}
#[derive(Clone, Debug, Default, TypedBuilder, PartialEq)]
pub struct Credential {
#[builder(default)]
pub username: Option<String>,
#[builder(default)]
pub source: Option<String>,
#[builder(default)]
pub password: Option<String>,
#[builder(default)]
pub mechanism: Option<AuthMechanism>,
#[builder(default)]
pub mechanism_properties: Option<Document>,
}
impl Credential {
#[cfg(test)]
pub(crate) fn into_document(mut self) -> Document {
use bson::Bson;
let mut doc = Document::new();
if let Some(s) = self.username.take() {
doc.insert("username", s);
}
if let Some(s) = self.password.take() {
doc.insert("password", s);
} else {
doc.insert("password", Bson::Null);
}
if let Some(s) = self.source.take() {
doc.insert("db", s);
}
doc
}
pub(crate) fn resolved_source(&self) -> &str {
self.mechanism
.as_ref()
.map(|m| m.default_source(None))
.unwrap_or("admin")
}
pub(crate) fn append_needed_mechanism_negotiation(&self, command: &mut Document) {
if let (Some(username), None) = (self.username.as_ref(), self.mechanism.as_ref()) {
command.insert(
"saslSupportedMechs",
format!("{}.{}", self.resolved_source(), username),
);
}
}
pub(crate) async fn authenticate_stream(&self, conn: &mut Connection) -> Result<()> {
let stream_description = conn.stream_description()?;
if !stream_description.server_type.can_auth() {
return Ok(());
};
let mechanism = match self.mechanism {
None => Cow::Owned(AuthMechanism::from_stream_description(stream_description)),
Some(ref m) => Cow::Borrowed(m),
};
mechanism.authenticate_stream(conn, self).await
}
}
pub(crate) fn generate_nonce() -> String {
let mut rng = rand::thread_rng();
let result: Vec<u8> = (0..32).map(|_| rng.gen()).collect();
base64::encode(result.as_slice())
}