use std::fmt::{self, Write as _};
use reqwest::Url;
use crate::{Error, Service};
pub const HIDDEN: &str = "***";
pub trait Redact: fmt::Debug + Send + Sync {
fn argument(&self, service: &Service, action: &str, name: &str, value: &str) -> String;
fn parameter(&self, name: &str, value: &str) -> String;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct HideValues;
impl Redact for HideValues {
fn argument(&self, _: &Service, _: &str, _: &str, _: &str) -> String {
HIDDEN.to_owned()
}
fn parameter(&self, _: &str, _: &str) -> String {
HIDDEN.to_owned()
}
}
pub(crate) fn url(url: &Url, redact: &dyn Redact) -> String {
let mut text = format!("{}://{}", url.scheme(), url.host_str().unwrap_or_default());
if let Some(port) = url.port() {
let _ = write!(text, ":{port}");
}
text.push_str(url.path());
if url.query().is_some() {
let pairs: Vec<String> = url
.query_pairs()
.map(|(name, value)| format!("{name}={}", redact.parameter(&name, &value)))
.collect();
let _ = write!(text, "?{}", pairs.join("&"));
}
text
}
pub(crate) fn arguments<'a>(
redact: &dyn Redact,
service: &Service,
action: &str,
arguments: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> String {
arguments
.into_iter()
.map(|(name, value)| {
let value = redact.argument(service, action, name, value);
format!("{name}={value:?}")
})
.collect::<Vec<_>>()
.join(", ")
}
pub(crate) fn error(error: &Error) -> String {
match error {
Error::Http(error) => {
let causes = std::iter::successors(std::error::Error::source(error), |e| e.source());
causes.fold("HTTP request failed".to_owned(), |text, cause| {
format!("{text}: {cause}")
})
}
Error::Status { status, .. } => format!("HTTP status {status}"),
Error::UnsupportedAuth(_) => "unsupported authentication challenge".to_owned(),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn service() -> Service {
Service {
service_type: "urn:example:service:Thing:1".to_owned(),
service_id: "urn:example:serviceId:Thing1".to_owned(),
control_url: "/control".to_owned(),
event_sub_url: None,
scpd_url: "/scpd.xml".to_owned(),
}
}
#[test]
fn hides_values_by_default() {
let url = Url::parse("https://user:pw@device:8443/list?id=1&token=abc#top").unwrap();
assert_eq!(
super::url(&url, &HideValues),
"https://device:8443/list?id=***&token=***"
);
let url = Url::parse("http://device/desc.xml").unwrap();
assert_eq!(super::url(&url, &HideValues), "http://device/desc.xml");
assert_eq!(
arguments(&HideValues, &service(), "Get", [("A", "1"), ("B", "x")]),
r#"A="***", B="***""#
);
}
#[test]
fn describes_errors_without_secrets() {
let status = Error::Status {
status: 404,
url: "http://device/list?token=abc".to_owned(),
};
assert_eq!(error(&status), "HTTP status 404");
let auth = Error::UnsupportedAuth("Digest nonce=\"abc\"".to_owned());
assert_eq!(error(&auth), "unsupported authentication challenge");
assert_eq!(
error(&Error::AuthenticationFailed),
"the device rejected the credentials"
);
}
}