http_client: on a tty, read password if no env var is set

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
This commit is contained in:
Wolfgang Bumiller 2019-02-20 14:18:27 +01:00
parent c9b296f117
commit 56458d9764

View File

@ -11,6 +11,8 @@ use futures::stream::Stream;
use serde_json::{Value}; use serde_json::{Value};
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use crate::tools::tty;
/// HTTP(S) API client /// HTTP(S) API client
pub struct HttpClient { pub struct HttpClient {
username: String, username: String,
@ -26,6 +28,24 @@ impl HttpClient {
} }
} }
fn get_password(&self) -> Result<String, Error> {
use std::env::VarError::*;
match std::env::var("PBS_PASSWORD") {
Ok(p) => return Ok(p),
Err(NotUnicode(_)) => bail!("PBS_PASSWORD contains bad characters"),
Err(NotPresent) => {
// Try another method
}
}
// If we're on a TTY, query the user for a password
if tty::stdin_isatty() {
return Ok(String::from_utf8(tty::read_password("Password: ")?)?);
}
bail!("no password input mechanism available");
}
fn run_request( fn run_request(
request: Request<Body>, request: Request<Body>,
) -> Result<Value, Error> { ) -> Result<Value, Error> {
@ -120,10 +140,7 @@ impl HttpClient {
let url: Uri = format!("https://{}:8007/{}", self.server, "/api2/json/access/ticket").parse()?; let url: Uri = format!("https://{}:8007/{}", self.server, "/api2/json/access/ticket").parse()?;
let password = match std::env::var("PBS_PASSWORD") { let password = self.get_password()?;
Ok(p) => p,
Err(err) => bail!("missing passphrase - {}", err),
};
let query = url::form_urlencoded::Serializer::new(String::new()) let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("username", &self.username) .append_pair("username", &self.username)