kanidmd_lib/idm/
authentication.rs

1use crate::prelude::{OperationError, Url};
2use crate::server::identity::Source;
3use compact_jwt::JwsCompact;
4use crypto_glue::{s256::Sha256Output, x509::Certificate};
5use kanidm_proto::{
6    internal::UserAuthToken,
7    oauth2::{AccessTokenRequest, AccessTokenResponse, AuthorisationRequest},
8    v1::{
9        AuthAllowed, AuthCredential as ProtoAuthCredential, AuthIssueSession, AuthMech,
10        AuthStep as ProtoAuthStep,
11    },
12};
13use std::fmt;
14use webauthn_rs::prelude::PublicKeyCredential;
15
16#[derive(Debug)]
17pub enum AuthStep {
18    Init(String),
19    Init2 {
20        username: String,
21        issue: AuthIssueSession,
22        privileged: bool,
23    },
24    Begin(AuthMech),
25    Cred(AuthCredential),
26}
27
28impl From<ProtoAuthStep> for AuthStep {
29    fn from(proto: ProtoAuthStep) -> Self {
30        match proto {
31            ProtoAuthStep::Init(name) => Self::Init(name),
32            ProtoAuthStep::Init2 {
33                username,
34                issue,
35                privileged,
36            } => Self::Init2 {
37                username,
38                issue,
39                privileged,
40            },
41            ProtoAuthStep::Begin(mech) => Self::Begin(mech),
42            ProtoAuthStep::Cred(proto_cred) => Self::Cred(AuthCredential::from(proto_cred)),
43        }
44    }
45}
46
47pub enum AuthExternal {
48    OAuth2AuthorisationRequest {
49        authorisation_url: Url,
50        request: AuthorisationRequest,
51    },
52    OAuth2AccessTokenRequest {
53        token_url: Url,
54        client_id: String,
55        client_secret: String,
56        request: AccessTokenRequest,
57    },
58}
59
60impl fmt::Debug for AuthExternal {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::OAuth2AuthorisationRequest { .. } => write!(f, "OAuth2AuthorisationRequest"),
64            Self::OAuth2AccessTokenRequest { .. } => write!(f, "OAuth2AccessTokenRequest"),
65        }
66    }
67}
68
69// We have to allow large enum variant here because else we can't match on External
70// due to boxing.
71#[allow(clippy::large_enum_variant)]
72pub enum AuthState {
73    Choose(Vec<AuthMech>),
74    Continue(Vec<AuthAllowed>),
75
76    /// Execute an authentication flow via an external provider.
77    /// For example, we may need to issue a redirect to an external OAuth2.
78    /// provider, or we may need to do a background query of some kind to proceed.
79    External(AuthExternal),
80
81    Denied(String),
82    Success(Box<JwsCompact>, AuthIssueSession),
83}
84
85impl fmt::Debug for AuthState {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            AuthState::Choose(mechs) => write!(f, "AuthState::Choose({mechs:?})"),
89            AuthState::Continue(allow) => write!(f, "AuthState::Continue({allow:?})"),
90            AuthState::External(allow) => write!(f, "AuthState::External({allow:?})"),
91            AuthState::Denied(reason) => write!(f, "AuthState::Denied({reason:?})"),
92            AuthState::Success(_token, issue) => write!(f, "AuthState::Success({issue:?})"),
93        }
94    }
95}
96
97pub enum AuthCredential {
98    Anonymous,
99    Password(String),
100    Totp(u32),
101    SecurityKey(Box<PublicKeyCredential>),
102    BackupCode(String),
103    Passkey(Box<PublicKeyCredential>),
104
105    // Internal Credential Types
106    OAuth2AuthorisationResponse { code: String, state: Option<String> },
107    OAuth2AccessTokenResponse { response: AccessTokenResponse },
108}
109
110impl From<ProtoAuthCredential> for AuthCredential {
111    fn from(proto: ProtoAuthCredential) -> Self {
112        match proto {
113            ProtoAuthCredential::Anonymous => AuthCredential::Anonymous,
114            ProtoAuthCredential::Password(p) => AuthCredential::Password(p),
115            ProtoAuthCredential::Totp(t) => AuthCredential::Totp(t),
116            ProtoAuthCredential::SecurityKey(sk) => AuthCredential::SecurityKey(sk),
117            ProtoAuthCredential::BackupCode(bc) => AuthCredential::BackupCode(bc),
118            ProtoAuthCredential::Passkey(pkc) => AuthCredential::Passkey(pkc),
119        }
120    }
121}
122
123impl fmt::Debug for AuthCredential {
124    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
125        match self {
126            AuthCredential::Anonymous => write!(fmt, "Anonymous"),
127            AuthCredential::Password(_) => write!(fmt, "Password(_)"),
128            AuthCredential::Totp(_) => write!(fmt, "TOTP(_)"),
129            AuthCredential::SecurityKey(_) => write!(fmt, "SecurityKey(_)"),
130            AuthCredential::BackupCode(_) => write!(fmt, "BackupCode(_)"),
131            AuthCredential::Passkey(_) => write!(fmt, "Passkey(_)"),
132            AuthCredential::OAuth2AuthorisationResponse { .. } => {
133                write!(fmt, "OAuth2AuthorisationResponse{{..}}")
134            }
135            AuthCredential::OAuth2AccessTokenResponse { .. } => {
136                write!(fmt, "OAuth2AccessTokenResponse{{..}}")
137            }
138        }
139    }
140}
141
142#[derive(Debug, Clone, Default)]
143pub(crate) enum PreValidatedTokenStatus {
144    #[default]
145    None,
146    Valid(Box<UserAuthToken>),
147    NotAuthenticated,
148    SessionExpired,
149}
150
151#[derive(Debug, Clone)]
152pub struct ClientAuthInfo {
153    pub(crate) source: Source,
154    pub(crate) client_cert: Option<ClientCertInfo>,
155    pub(crate) bearer_token: Option<JwsCompact>,
156    pub(crate) basic_authz: Option<String>,
157    pub(crate) pre_validated_token: PreValidatedTokenStatus,
158}
159
160impl ClientAuthInfo {
161    pub fn new(
162        source: Source,
163        client_cert: Option<ClientCertInfo>,
164        bearer_token: Option<JwsCompact>,
165        basic_authz: Option<String>,
166    ) -> Self {
167        Self {
168            source,
169            client_cert,
170            bearer_token,
171            basic_authz,
172            pre_validated_token: Default::default(),
173        }
174    }
175
176    pub fn bearer_token(&self) -> Option<&JwsCompact> {
177        self.bearer_token.as_ref()
178    }
179
180    pub fn pre_validated_uat(&self) -> Result<&UserAuthToken, OperationError> {
181        match &self.pre_validated_token {
182            PreValidatedTokenStatus::Valid(uat) => Ok(uat),
183            PreValidatedTokenStatus::None => Err(OperationError::AU0008ClientAuthInfoPrevalidation),
184            PreValidatedTokenStatus::NotAuthenticated => Err(OperationError::NotAuthenticated),
185            PreValidatedTokenStatus::SessionExpired => Err(OperationError::SessionExpired),
186        }
187    }
188
189    pub(crate) fn set_pre_validated_uat(&mut self, status: PreValidatedTokenStatus) {
190        self.pre_validated_token = status
191    }
192}
193
194#[derive(Debug, Clone)]
195pub struct ClientCertInfo {
196    pub public_key_s256: Sha256Output,
197    pub certificate: Certificate,
198}
199
200#[cfg(test)]
201impl ClientAuthInfo {
202    pub(crate) fn none() -> Self {
203        ClientAuthInfo {
204            source: Source::Internal,
205            client_cert: None,
206            bearer_token: None,
207            basic_authz: None,
208            pre_validated_token: Default::default(),
209        }
210    }
211}
212
213#[cfg(test)]
214impl From<Source> for ClientAuthInfo {
215    fn from(value: Source) -> ClientAuthInfo {
216        ClientAuthInfo {
217            source: value,
218            client_cert: None,
219            bearer_token: None,
220            basic_authz: None,
221            pre_validated_token: Default::default(),
222        }
223    }
224}
225
226#[cfg(test)]
227impl From<JwsCompact> for ClientAuthInfo {
228    fn from(value: JwsCompact) -> ClientAuthInfo {
229        ClientAuthInfo {
230            source: Source::Internal,
231            client_cert: None,
232            bearer_token: Some(value),
233            basic_authz: None,
234            pre_validated_token: Default::default(),
235        }
236    }
237}
238
239#[cfg(test)]
240impl From<ClientCertInfo> for ClientAuthInfo {
241    fn from(value: ClientCertInfo) -> ClientAuthInfo {
242        ClientAuthInfo {
243            source: Source::Internal,
244            client_cert: Some(value),
245            bearer_token: None,
246            basic_authz: None,
247            pre_validated_token: Default::default(),
248        }
249    }
250}
251
252#[cfg(test)]
253impl From<&str> for ClientAuthInfo {
254    fn from(value: &str) -> ClientAuthInfo {
255        ClientAuthInfo {
256            source: Source::Internal,
257            client_cert: None,
258            bearer_token: None,
259            basic_authz: Some(value.to_string()),
260            pre_validated_token: Default::default(),
261        }
262    }
263}
264
265#[cfg(test)]
266impl ClientAuthInfo {
267    pub(crate) fn encode_basic(id: &str, secret: &str) -> ClientAuthInfo {
268        use base64::{engine::general_purpose, Engine as _};
269        let value = format!("{id}:{secret}");
270        let value = general_purpose::STANDARD.encode(&value);
271        ClientAuthInfo {
272            source: Source::Internal,
273            client_cert: None,
274            bearer_token: None,
275            basic_authz: Some(value),
276            pre_validated_token: Default::default(),
277        }
278    }
279}