tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
//! Basic and bearer authentication parsing for the Tez command.

use std::{future::Future, pin::Pin};

use clap::ValueEnum;
use secrecy::{ExposeSecret as _, SecretString};
use serde::{Deserialize, Serialize, Serializer};
use tez::auth::{Authentication, BasicAuth, BearerAuth};

use crate::error::{Error, Result};

/// The authentication schemes available through `--auth-type`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
pub(crate) enum AuthScheme {
    #[default]
    Basic,
    Bearer,
}

/// Credentials parsed by the command and optionally kept in a CLI session.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) enum Credentials {
    Basic {
        username: String,
        #[serde(serialize_with = "serialize_secret")]
        password: SecretString,
    },
    Bearer {
        #[serde(serialize_with = "serialize_secret")]
        token: SecretString,
    },
}

impl Authentication for Credentials {
    fn authenticate<'request>(
        &'request self,
        request: &'request mut tez::Request,
    ) -> Pin<Box<dyn Future<Output = tez::Result<()>> + Send + 'request>> {
        Box::pin(async move {
            match self {
                Self::Basic { username, password } => {
                    BasicAuth::new(username, password.clone())?
                        .authenticate(request)
                        .await
                }
                Self::Bearer { token } => {
                    BearerAuth::new(token.clone())?.authenticate(request).await
                }
            }
        })
    }
}

pub(crate) fn resolve(
    scheme: AuthScheme,
    credentials: Option<&str>,
    reads_stdin: bool,
) -> Result<Option<Credentials>> {
    let Some(credentials) = credentials else {
        return Ok(None);
    };

    match scheme {
        AuthScheme::Basic => basic(credentials, reads_stdin).map(Some),
        AuthScheme::Bearer => Ok(Some(Credentials::Bearer {
            token: credentials.into(),
        })),
    }
}

fn basic(credentials: &str, reads_stdin: bool) -> Result<Credentials> {
    match credentials.split_once(':') {
        Some((username, password)) => Ok(Credentials::Basic {
            username: username.to_owned(),
            password: password.into(),
        }),
        None if reads_stdin => Err(Error::usage(
            "a Basic auth password cannot be prompted for while reading the request body from standard input",
        )),
        None => {
            let password = rpassword::prompt_password("Password: ")
                .map_err(|_| Error::usage("Basic auth password could not be read"))?;
            Ok(Credentials::Basic {
                username: credentials.to_owned(),
                password: password.into(),
            })
        }
    }
}

fn serialize_secret<S>(secret: &SecretString, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    secret.expose_secret().serialize(serializer)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bearer_credentials_stay_whole() {
        let auth = resolve(AuthScheme::Bearer, Some("part:one"), false)
            .unwrap()
            .unwrap();

        assert!(!format!("{auth:?}").contains("part:one"));
    }

    #[test]
    fn basic_auth_does_not_prompt_while_stdin_is_a_body() {
        let error = resolve(AuthScheme::Basic, Some("user"), true).unwrap_err();

        assert_eq!(
            error.to_string(),
            "a Basic auth password cannot be prompted for while reading the request body from standard input"
        );
    }

    #[test]
    fn credentials_redact_their_contents() {
        let basic = Credentials::Basic {
            username: "user".to_owned(),
            password: "secret".into(),
        };
        let bearer = Credentials::Bearer {
            token: "bearer-credential".into(),
        };

        assert!(!format!("{basic:?}").contains("secret"));
        assert!(!format!("{bearer:?}").contains("bearer-credential"));
    }
}