Skip to main content

kanidmd_lib/idm/
event.rs

1use crate::{
2    idm::authentication::{AuthCredential, AuthState, AuthStep},
3    prelude::*,
4};
5use compact_jwt::JwsCompact;
6use kanidm_proto::v1::{AuthIssueSession, AuthMech};
7
8#[cfg(test)]
9use std::sync::Arc;
10#[cfg(test)]
11use webauthn_rs::prelude::PublicKeyCredential;
12
13#[cfg(test)]
14pub(crate) struct PasswordChangeEvent {
15    pub ident: Identity,
16    pub target: Uuid,
17    pub cleartext: String,
18}
19
20#[cfg(test)]
21impl PasswordChangeEvent {
22    pub fn new_internal(target: Uuid, cleartext: &str) -> Self {
23        PasswordChangeEvent {
24            ident: Identity::from_internal(),
25            target,
26            cleartext: cleartext.to_string(),
27        }
28    }
29}
30
31pub struct UnixPasswordChangeEvent {
32    pub ident: Identity,
33    pub target: Uuid,
34    pub cleartext: String,
35}
36
37impl UnixPasswordChangeEvent {
38    #[cfg(test)]
39    pub fn new_internal(target: Uuid, cleartext: &str) -> Self {
40        UnixPasswordChangeEvent {
41            ident: Identity::from_internal(),
42            target,
43            cleartext: cleartext.to_string(),
44        }
45    }
46
47    pub fn from_parts(
48        // qs: &QueryServerWriteTransaction,
49        ident: Identity,
50        target: Uuid,
51        cleartext: String,
52    ) -> Result<Self, OperationError> {
53        Ok(UnixPasswordChangeEvent {
54            ident,
55            target,
56            cleartext,
57        })
58    }
59}
60
61#[derive(Debug)]
62pub struct GeneratePasswordEvent {
63    pub ident: Identity,
64    pub target: Uuid,
65}
66
67impl GeneratePasswordEvent {
68    pub fn from_parts(
69        // qs: &QueryServerWriteTransaction,
70        ident: Identity,
71        target: Uuid,
72    ) -> Result<Self, OperationError> {
73        Ok(GeneratePasswordEvent { ident, target })
74    }
75}
76
77#[derive(Debug)]
78pub struct RegenerateRadiusSecretEvent {
79    pub ident: Identity,
80    pub target: Uuid,
81}
82
83impl RegenerateRadiusSecretEvent {
84    pub fn from_parts(
85        // qs: &QueryServerWriteTransaction,
86        ident: Identity,
87        target: Uuid,
88    ) -> Result<Self, OperationError> {
89        Ok(RegenerateRadiusSecretEvent { ident, target })
90    }
91
92    #[cfg(test)]
93    pub fn new_internal(target: Uuid) -> Self {
94        let ident = Identity::from_internal();
95
96        RegenerateRadiusSecretEvent { ident, target }
97    }
98}
99
100#[derive(Debug)]
101pub struct RadiusAuthTokenEvent {
102    pub ident: Identity,
103    pub target: Uuid,
104}
105
106impl RadiusAuthTokenEvent {
107    pub fn from_parts(
108        // qs: &QueryServerReadTransaction,
109        ident: Identity,
110        target: Uuid,
111    ) -> Result<Self, OperationError> {
112        Ok(RadiusAuthTokenEvent { ident, target })
113    }
114
115    #[cfg(test)]
116    pub fn new_impersonate(e: Arc<Entry<EntrySealed, EntryCommitted>>, target: Uuid) -> Self {
117        let ident = Identity::from_impersonate_entry_readonly(e);
118
119        RadiusAuthTokenEvent { ident, target }
120    }
121}
122
123#[derive(Debug)]
124pub struct UnixUserTokenEvent {
125    pub ident: Identity,
126    pub target: Uuid,
127}
128
129impl UnixUserTokenEvent {
130    pub fn from_parts(
131        // qs: &QueryServerReadTransaction,
132        ident: Identity,
133        target: Uuid,
134    ) -> Result<Self, OperationError> {
135        Ok(UnixUserTokenEvent { ident, target })
136    }
137
138    #[cfg(test)]
139    pub fn new_internal(target: Uuid) -> Self {
140        let ident = Identity::from_internal();
141
142        UnixUserTokenEvent { ident, target }
143    }
144}
145
146#[derive(Debug)]
147pub struct UnixGroupTokenEvent {
148    pub ident: Identity,
149    pub target: Uuid,
150}
151
152impl UnixGroupTokenEvent {
153    pub fn from_parts(
154        // qs: &QueryServerReadTransaction,
155        ident: Identity,
156        target: Uuid,
157    ) -> Result<Self, OperationError> {
158        Ok(UnixGroupTokenEvent { ident, target })
159    }
160
161    #[cfg(test)]
162    pub fn new_impersonate(e: Arc<Entry<EntrySealed, EntryCommitted>>, target: Uuid) -> Self {
163        let ident = Identity::from_impersonate_entry_readonly(e);
164
165        UnixGroupTokenEvent { ident, target }
166    }
167}
168
169pub struct UnixUserAuthEvent {
170    pub ident: Identity,
171    pub target: Uuid,
172    pub cleartext: String,
173}
174
175impl std::fmt::Debug for UnixUserAuthEvent {
176    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
177        f.debug_struct("UnixUserAuthEvent")
178            .field("ident", &self.ident)
179            .field("target", &self.target)
180            .finish()
181    }
182}
183
184impl UnixUserAuthEvent {
185    #[cfg(test)]
186    pub fn new_internal(target: Uuid, cleartext: &str) -> Self {
187        UnixUserAuthEvent {
188            ident: Identity::from_internal(),
189            target,
190            cleartext: cleartext.to_string(),
191        }
192    }
193
194    pub fn from_parts(
195        ident: Identity,
196        target: Uuid,
197        cleartext: String,
198    ) -> Result<Self, OperationError> {
199        Ok(UnixUserAuthEvent {
200            ident,
201            target,
202            cleartext,
203        })
204    }
205}
206
207#[derive(Debug)]
208pub struct CredentialStatusEvent {
209    pub ident: Identity,
210    pub target: Uuid,
211}
212
213impl CredentialStatusEvent {
214    pub fn from_parts(
215        // qs: &QueryServerReadTransaction,
216        ident: Identity,
217        target: Uuid,
218    ) -> Result<Self, OperationError> {
219        Ok(CredentialStatusEvent { ident, target })
220    }
221
222    #[cfg(test)]
223    pub fn new_internal(target: Uuid) -> Self {
224        let ident = Identity::from_internal();
225
226        CredentialStatusEvent { ident, target }
227    }
228}
229
230pub struct LdapAuthEvent {
231    // pub ident: Identity,
232    pub target: Uuid,
233    pub cleartext: String,
234}
235
236impl LdapAuthEvent {
237    pub fn from_parts(target: Uuid, cleartext: String) -> Result<Self, OperationError> {
238        // let e = Event::from_ro_uat(audit, qs, uat)?;
239
240        Ok(LdapAuthEvent {
241            // event: e,
242            target,
243            cleartext,
244        })
245    }
246}
247
248pub struct LdapTokenAuthEvent {
249    pub token: JwsCompact,
250}
251
252impl LdapTokenAuthEvent {
253    pub fn from_parts(token: JwsCompact) -> Result<Self, OperationError> {
254        Ok(LdapTokenAuthEvent { token })
255    }
256}
257
258pub struct LdapApplicationAuthEvent {
259    pub application: String,
260    pub target: Uuid,
261    pub cleartext: String,
262}
263
264impl LdapApplicationAuthEvent {
265    pub fn new(app_name: &str, usr_uuid: Uuid, cleartext: String) -> Result<Self, OperationError> {
266        Ok(LdapApplicationAuthEvent {
267            application: app_name.to_string(),
268            target: usr_uuid,
269            cleartext,
270        })
271    }
272}
273
274#[derive(Debug)]
275pub struct AuthEventStepInit {
276    pub username: String,
277    pub issue: AuthIssueSession,
278    pub privileged: bool,
279}
280
281#[derive(Debug)]
282pub struct AuthEventStepCred {
283    pub sessionid: Uuid,
284    pub cred: AuthCredential,
285}
286
287#[derive(Debug)]
288pub struct AuthEventStepMech {
289    pub sessionid: Uuid,
290    pub mech: AuthMech,
291}
292
293#[derive(Debug)]
294pub enum AuthEventStep {
295    Init(AuthEventStepInit),
296    Begin(AuthEventStepMech),
297    Cred(AuthEventStepCred),
298}
299
300impl AuthEventStep {
301    fn from_authstep(aus: AuthStep, sid: Option<Uuid>) -> Result<Self, OperationError> {
302        match aus {
303            AuthStep::Init(username) => {
304                if username.trim().is_empty() {
305                    Err(OperationError::EmptyRequest)
306                } else {
307                    Ok(AuthEventStep::Init(AuthEventStepInit {
308                        username,
309                        issue: AuthIssueSession::Token,
310                        privileged: false,
311                    }))
312                }
313            }
314            AuthStep::Init2 {
315                username,
316                issue,
317                privileged,
318            } => {
319                if username.trim().is_empty() {
320                    Err(OperationError::EmptyRequest)
321                } else {
322                    Ok(AuthEventStep::Init(AuthEventStepInit {
323                        username,
324                        issue,
325                        privileged,
326                    }))
327                }
328            }
329
330            AuthStep::Begin(mech) => match sid {
331                Some(sessionid) => Ok(AuthEventStep::Begin(AuthEventStepMech { sessionid, mech })),
332                None => Err(OperationError::InvalidAuthState(
333                    "session id not present in cred presented to 'begin' step".to_string(),
334                )),
335            },
336            AuthStep::Cred(cred) => match sid {
337                Some(sessionid) => Ok(AuthEventStep::Cred(AuthEventStepCred { sessionid, cred })),
338                None => Err(OperationError::InvalidAuthState(
339                    "session id not present in cred to 'cred' step".to_string(),
340                )),
341            },
342        }
343    }
344
345    #[cfg(test)]
346    pub fn anonymous_init() -> Self {
347        AuthEventStep::Init(AuthEventStepInit {
348            username: "anonymous".to_string(),
349            issue: AuthIssueSession::Token,
350            privileged: false,
351        })
352    }
353
354    #[cfg(test)]
355    pub fn named_init(name: &str) -> Self {
356        AuthEventStep::Init(AuthEventStepInit {
357            username: name.to_string(),
358            issue: AuthIssueSession::Token,
359            privileged: false,
360        })
361    }
362
363    #[cfg(test)]
364    pub fn begin_mech(sessionid: Uuid, mech: AuthMech) -> Self {
365        AuthEventStep::Begin(AuthEventStepMech { sessionid, mech })
366    }
367
368    #[cfg(test)]
369    pub fn cred_step_anonymous(sid: Uuid) -> Self {
370        AuthEventStep::Cred(AuthEventStepCred {
371            sessionid: sid,
372            cred: AuthCredential::Anonymous,
373        })
374    }
375
376    #[cfg(test)]
377    pub fn cred_step_password(sid: Uuid, pw: &str) -> Self {
378        AuthEventStep::Cred(AuthEventStepCred {
379            sessionid: sid,
380            cred: AuthCredential::Password(pw.to_string()),
381        })
382    }
383
384    #[cfg(test)]
385    pub fn cred_step_totp(sid: Uuid, totp: u32) -> Self {
386        AuthEventStep::Cred(AuthEventStepCred {
387            sessionid: sid,
388            cred: AuthCredential::Totp(totp),
389        })
390    }
391
392    #[cfg(test)]
393    pub fn cred_step_backup_code(sid: Uuid, code: &str) -> Self {
394        AuthEventStep::Cred(AuthEventStepCred {
395            sessionid: sid,
396            cred: AuthCredential::BackupCode(code.to_string()),
397        })
398    }
399
400    #[cfg(test)]
401    pub fn cred_step_passkey(sid: Uuid, passkey_response: PublicKeyCredential) -> Self {
402        AuthEventStep::Cred(AuthEventStepCred {
403            sessionid: sid,
404            cred: AuthCredential::Passkey(Box::new(passkey_response)),
405        })
406    }
407}
408
409#[derive(Debug)]
410pub struct AuthEvent {
411    pub ident: Option<Identity>,
412    pub step: AuthEventStep,
413    // pub sessionid: Option<Uuid>,
414}
415
416impl AuthEvent {
417    pub fn from_message(
418        sessionid: Option<Uuid>,
419        req_step: AuthStep,
420    ) -> Result<Self, OperationError> {
421        Ok(AuthEvent {
422            ident: None,
423            step: AuthEventStep::from_authstep(req_step, sessionid)?,
424        })
425    }
426
427    #[cfg(test)]
428    pub fn anonymous_init() -> Self {
429        AuthEvent {
430            ident: None,
431            step: AuthEventStep::anonymous_init(),
432        }
433    }
434
435    #[cfg(test)]
436    pub fn named_init(name: &str) -> Self {
437        AuthEvent {
438            ident: None,
439            step: AuthEventStep::named_init(name),
440        }
441    }
442
443    #[cfg(test)]
444    pub fn begin_mech(sessionid: Uuid, mech: AuthMech) -> Self {
445        AuthEvent {
446            ident: None,
447            step: AuthEventStep::begin_mech(sessionid, mech),
448        }
449    }
450
451    #[cfg(test)]
452    pub fn cred_step_anonymous(sid: Uuid) -> Self {
453        AuthEvent {
454            ident: None,
455            step: AuthEventStep::cred_step_anonymous(sid),
456        }
457    }
458
459    #[cfg(test)]
460    pub fn cred_step_password(sid: Uuid, pw: &str) -> Self {
461        AuthEvent {
462            ident: None,
463            step: AuthEventStep::cred_step_password(sid, pw),
464        }
465    }
466
467    #[cfg(test)]
468    pub fn cred_step_totp(sid: Uuid, totp: u32) -> Self {
469        AuthEvent {
470            ident: None,
471            step: AuthEventStep::cred_step_totp(sid, totp),
472        }
473    }
474
475    #[cfg(test)]
476    pub fn cred_step_backup_code(sid: Uuid, code: &str) -> Self {
477        AuthEvent {
478            ident: None,
479            step: AuthEventStep::cred_step_backup_code(sid, code),
480        }
481    }
482
483    #[cfg(test)]
484    pub fn cred_step_passkey(sid: Uuid, passkey_response: PublicKeyCredential) -> Self {
485        AuthEvent {
486            ident: None,
487            step: AuthEventStep::cred_step_passkey(sid, passkey_response),
488        }
489    }
490}
491
492// Probably should be a struct with the session id present.
493#[derive(Debug)]
494pub struct AuthResult {
495    pub sessionid: Uuid,
496    pub state: AuthState,
497}
498
499impl std::fmt::Display for AuthResult {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        match &self.state {
502            AuthState::Choose(auth_mechs) => write!(
503                f,
504                "Choose({})",
505                auth_mechs
506                    .iter()
507                    .map(|m| m.to_value())
508                    .collect::<Vec<_>>()
509                    .join(",")
510            ),
511            AuthState::Continue(auth_alloweds) => write!(
512                f,
513                "Continue ({})",
514                auth_alloweds
515                    .iter()
516                    .map(|a| a.to_string())
517                    .collect::<Vec<_>>()
518                    .join(",")
519            ),
520            AuthState::External(auth_external) => write!(f, "External({:?})", auth_external),
521            AuthState::Denied(reason) => write!(f, "Denied: {}", reason),
522            AuthState::Success(_jws_compact, auth_issue_session) => {
523                write!(f, "Success({})", auth_issue_session)
524            }
525        }
526    }
527}
528
529/*
530impl AuthResult {
531    pub fn response(self) -> AuthResponse {
532        AuthResponse {
533            sessionid: self.sessionid,
534            state: self.state,
535        }
536    }
537}
538*/