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
use hyper::body::Bytes;
#[cfg(feature = "basic-auth")]
use hyper::header::HeaderValue;
pub use http_body_util::Full;

#[cfg(feature = "basic-auth")]
use crate::Error;

#[derive(Debug)]
pub struct Request(pub(crate) hyper::Request<Full<Bytes>>);
impl Request {
  #[cfg(feature = "basic-auth")]
  fn username_password_from_uri(&self) -> Result<(String, String), Error> {
    if let Some(authority) = self.0.uri().authority() {
      let authority = authority.as_str();
      if authority.contains('@') {
        // Decode the username and password from the URI
        let mut userpass = authority.split('@').next().unwrap().to_string();

        let mut userpass_iter = userpass.split(':');
        let username = userpass_iter.next().unwrap().to_string();
        let password = userpass_iter.next().map_or_else(String::new, str::to_string);
        zeroize::Zeroize::zeroize(&mut userpass);

        return Ok((username, password));
      }
    }
    Err(Error::InvalidUri)
  }

  #[cfg(feature = "basic-auth")]
  pub fn basic_auth(&mut self, username: &str, password: &str) {
    use zeroize::Zeroize;
    use base64ct::{Encoding, Base64};

    let mut formatted = format!("{username}:{password}");
    let mut encoded = Base64::encode_string(formatted.as_bytes());
    formatted.zeroize();
    self.0.headers_mut().insert(
      hyper::header::AUTHORIZATION,
      HeaderValue::from_str(&format!("Basic {encoded}")).unwrap(),
    );
    encoded.zeroize();
  }

  #[cfg(feature = "basic-auth")]
  pub fn basic_auth_from_uri(&mut self) -> Result<(), Error> {
    let (mut username, mut password) = self.username_password_from_uri()?;
    self.basic_auth(&username, &password);

    use zeroize::Zeroize;
    username.zeroize();
    password.zeroize();

    Ok(())
  }

  #[cfg(feature = "basic-auth")]
  pub fn with_basic_auth(&mut self) {
    let _ = self.basic_auth_from_uri();
  }
}
impl From<hyper::Request<Full<Bytes>>> for Request {
  fn from(request: hyper::Request<Full<Bytes>>) -> Request {
    Request(request)
  }
}