1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use super::UserDetail;
use crate::BoxError;
use async_trait::async_trait;
use std::fmt::{Debug, Formatter};
use thiserror::Error;
#[async_trait]
pub trait Authenticator<User>: Sync + Send + Debug
where
User: UserDetail,
{
async fn authenticate(&self, username: &str, creds: &Credentials) -> Result<User, AuthenticationError>;
async fn cert_auth_sufficient(&self, _username: &str) -> bool {
return false;
}
fn name(&self) -> &str {
std::any::type_name::<Self>()
}
}
#[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,
}
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(),
}
}
}
#[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::new(std::io::ErrorKind::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
}
}