How to redact password from URL in Rust?

156 Views Asked by At

This question is similar to this one but specific to . How can I readact password from a URL?. This is mainly for logging purposes.

To make it clear I am looking for similar kind of API in .

>>> from pip._internal.utils.misc import redact_auth_from_url
>>> 
>>> redact_auth_from_url("https://user:[email protected]/path?key=value#hash")
'https://user:****@example.com/path?key=value#hash'
>>> redact_auth_from_url.__doc__
'Replace the password in a given url with ****.'

I did check the rust-url crate but I could not find an equivalent function.

1

There are 1 best solutions below

1
On BEST ANSWER

You could use set_password in conjunction with password:

if url.password().is_some() {
    url.set_password(Some("****"));
}

Or, as a function mimicking the redact_auth_from_url interface:

fn redact_auth_from_url(url: &Url) -> Cow<'_, Url> {
    if url.password().is_some() {
        let mut owned_url = url.clone();
        if owned_url.set_password(Some("****")).is_ok() {
            Cow::Owned(owned_url)
        } else {
            Cow::Borrowed(url)
        }
    } else {
        Cow::Borrowed(url)
    }
}