tez 0.0.1

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

use std::fmt;

use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use tez::AuthProvider;

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, Deserialize, Serialize)]
pub(crate) enum Credentials {
    Basic { username: String, password: String },
    Bearer { token: String },
}

impl Credentials {
    pub(crate) fn provider(&self) -> AuthProvider {
        match self {
            Self::Basic { username, password } => AuthProvider::basic(username, password),
            Self::Bearer { token } => AuthProvider::bearer(token),
        }
    }
}

impl fmt::Debug for Credentials {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("Credentials")
            .field(&self.provider())
            .finish()
    }
}

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.to_owned(),
        })),
    }
}

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.to_owned(),
        }),
        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,
            })
        }
    }
}

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

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

        let provider = auth.provider();
        assert_eq!(format!("{provider:?}"), "AuthProvider::Bearer(..)");
    }

    #[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".to_owned(),
        };
        let bearer = Credentials::Bearer {
            token: "token".to_owned(),
        };

        assert_eq!(format!("{basic:?}"), "Credentials(AuthProvider::Basic(..))");
        assert_eq!(
            format!("{bearer:?}"),
            "Credentials(AuthProvider::Bearer(..))"
        );
    }
}