use crate::BoxError;
use async_trait::async_trait;
use std::fmt::{Debug, Formatter};
use thiserror::Error;
#[async_trait]
pub trait Authenticator: Sync + Send + Debug {
async fn authenticate(&self, username: &str, creds: &Credentials) -> Result<Principal, AuthenticationError>;
async fn cert_auth_sufficient(&self, _username: &str) -> bool {
false
}
fn name(&self) -> &str {
std::any::type_name::<Self>()
}
}
#[derive(Debug, Clone)]
pub struct Principal {
pub username: String,
}
#[derive(Error, Debug)]
pub enum AuthenticationError {
#[error("bad password")]
BadPassword,
#[error("bad username")]
BadUser,
#[error("bad client certificate")]
BadCert,
#[error("client IP address not allowed")]
IpDisallowed,
#[error("certificate does not match allowed CN for this user")]
CnDisallowed,
#[error("authentication error: {0}: {1:?}")]
ImplPropagated(String, #[source] Option<BoxError>),
}
impl AuthenticationError {
pub fn new(s: impl Into<String>) -> AuthenticationError {
AuthenticationError::ImplPropagated(s.into(), None)
}
pub fn with_source<E>(s: impl Into<String>, source: E) -> AuthenticationError
where
E: std::error::Error + Send + Sync + 'static,
{
AuthenticationError::ImplPropagated(s.into(), Some(Box::new(source)))
}
}
#[derive(Clone, Debug)]
pub struct Credentials {
pub password: Option<String>,
pub certificate_chain: Option<Vec<ClientCert>>,
pub source_ip: std::net::IpAddr,
pub command_channel_security: ChannelEncryptionState,
}
impl From<&str> for Credentials {
fn from(s: &str) -> Self {
Credentials {
password: Some(String::from(s)),
certificate_chain: None,
source_ip: [127, 0, 0, 1].into(),
command_channel_security: ChannelEncryptionState::Plaintext,
}
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct ClientCert(pub Vec<u8>);
use x509_parser::prelude::parse_x509_certificate;
impl ClientCert {
pub fn verify_cn(&self, allowed_cn: &str) -> Result<bool, std::io::Error> {
let client_cert = parse_x509_certificate(&self.0);
let subject = match client_cert {
Ok(c) => c.1.subject().to_string(),
Err(e) => return Err(std::io::Error::other(e.to_string())),
};
Ok(subject.contains(allowed_cn))
}
}
impl std::fmt::Debug for ClientCert {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "ClientCert(***)")
}
}
impl AsRef<[u8]> for ClientCert {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChannelEncryptionState {
Plaintext,
Tls,
}