|
10 | 10 |
|
11 | 11 | use std::collections::HashMap;
|
12 | 12 | use std::fs::File;
|
| 13 | +use std::io::{BufRead, BufReader}; |
13 | 14 | use std::iter::FromIterator;
|
14 | 15 | use std::path::PathBuf;
|
15 | 16 | use std::{fmt, result};
|
@@ -197,19 +198,16 @@ pub enum Auth {
|
197 | 198 | impl Auth {
|
198 | 199 | /// Convert into the arguments that jsonrpc::Client needs.
|
199 | 200 | pub fn get_user_pass(self) -> Result<(Option<String>, Option<String>)> {
|
200 |
| - use std::io::Read; |
201 | 201 | match self {
|
202 | 202 | Auth::None => Ok((None, None)),
|
203 | 203 | Auth::UserPass(u, p) => Ok((Some(u), Some(p))),
|
204 | 204 | Auth::CookieFile(path) => {
|
205 |
| - let mut file = File::open(path)?; |
206 |
| - let mut contents = String::new(); |
207 |
| - file.read_to_string(&mut contents)?; |
208 |
| - let mut split = contents.splitn(2, ":"); |
209 |
| - Ok(( |
210 |
| - Some(split.next().ok_or(Error::InvalidCookieFile)?.into()), |
211 |
| - Some(split.next().ok_or(Error::InvalidCookieFile)?.into()), |
212 |
| - )) |
| 205 | + let line = BufReader::new(File::open(path)?) |
| 206 | + .lines() |
| 207 | + .next() |
| 208 | + .ok_or(Error::InvalidCookieFile)??; |
| 209 | + let colon = line.find(':').ok_or(Error::InvalidCookieFile)?; |
| 210 | + Ok((Some(line[..colon].into()), Some(line[colon + 1..].into()))) |
213 | 211 | }
|
214 | 212 | }
|
215 | 213 | }
|
@@ -1357,4 +1355,34 @@ mod tests {
|
1357 | 1355 | fn test_handle_defaults() {
|
1358 | 1356 | test_handle_defaults_inner().unwrap();
|
1359 | 1357 | }
|
| 1358 | + |
| 1359 | + #[test] |
| 1360 | + fn auth_cookie_file_ignores_newline() { |
| 1361 | + let tempdir = tempfile::tempdir().unwrap(); |
| 1362 | + let path = tempdir.path().join("cookie"); |
| 1363 | + std::fs::write(&path, "foo:bar\n").unwrap(); |
| 1364 | + assert_eq!( |
| 1365 | + Auth::CookieFile(path).get_user_pass().unwrap(), |
| 1366 | + (Some("foo".into()), Some("bar".into())), |
| 1367 | + ); |
| 1368 | + } |
| 1369 | + |
| 1370 | + #[test] |
| 1371 | + fn auth_cookie_file_ignores_additional_lines() { |
| 1372 | + let tempdir = tempfile::tempdir().unwrap(); |
| 1373 | + let path = tempdir.path().join("cookie"); |
| 1374 | + std::fs::write(&path, "foo:bar\nbaz").unwrap(); |
| 1375 | + assert_eq!( |
| 1376 | + Auth::CookieFile(path).get_user_pass().unwrap(), |
| 1377 | + (Some("foo".into()), Some("bar".into())), |
| 1378 | + ); |
| 1379 | + } |
| 1380 | + |
| 1381 | + #[test] |
| 1382 | + fn auth_cookie_file_fails_if_colon_isnt_present() { |
| 1383 | + let tempdir = tempfile::tempdir().unwrap(); |
| 1384 | + let path = tempdir.path().join("cookie"); |
| 1385 | + std::fs::write(&path, "foobar").unwrap(); |
| 1386 | + assert!(matches!(Auth::CookieFile(path).get_user_pass(), Err(Error::InvalidCookieFile))); |
| 1387 | + } |
1360 | 1388 | }
|
0 commit comments