Skip to main content

kanidm_proto/v1/
auth.rs

1use serde::{Deserialize, Serialize};
2use std::{cmp::Ordering, fmt};
3use utoipa::ToSchema;
4use uuid::Uuid;
5
6use webauthn_rs_proto::{PublicKeyCredential, RequestChallengeResponse};
7
8/// Authentication to Kanidm is a stepped process.
9///
10/// The session is first initialised with the requested username.
11///
12/// In response the list of supported authentication mechanisms is provided.
13///
14/// The user chooses the authentication mechanism to proceed with.
15///
16/// The server responds with a challenge that the user provides a credential
17/// to satisfy. This challenge and response process continues until a credential
18/// fails to validate, an error occurs, or successful authentication is complete.
19#[derive(Debug, Serialize, Deserialize, ToSchema)]
20#[serde(rename_all = "lowercase")]
21pub enum AuthStep {
22    /// Initialise a new authentication session
23    Init(String),
24    /// Initialise a new authentication session with extra flags
25    /// for requesting different types of session tokens or
26    /// immediate access to privileges.
27    Init2 {
28        username: String,
29        issue: AuthIssueSession,
30        #[serde(default)]
31        /// If true, the session will have r/w access.
32        privileged: bool,
33    },
34    /// Request the named authentication mechanism to proceed
35    Begin(AuthMech),
36    /// Provide a credential in response to a challenge
37    Cred(AuthCredential),
38}
39
40/// The response to an AuthStep request.
41#[derive(Debug, Serialize, Deserialize, ToSchema)]
42#[serde(rename_all = "lowercase")]
43pub enum AuthState {
44    /// You need to select how you want to proceed.
45    Choose(Vec<AuthMech>),
46    /// Continue to auth, allowed mechanisms/challenges listed.
47    Continue(Vec<AuthAllowed>),
48    /// Something was bad, your session is terminated and no cookie.
49    Denied(String),
50    /// Everything is good, your bearer token has been issued and is within.
51    Success(String),
52}
53
54/// The credential challenge provided by a user.
55#[derive(Serialize, Deserialize, ToSchema)]
56#[serde(rename_all = "lowercase")]
57pub enum AuthCredential {
58    Anonymous,
59    Password(String),
60    Totp(u32),
61
62    #[schema(value_type = HashMap<String, Value>)]
63    SecurityKey(Box<PublicKeyCredential>),
64    BackupCode(String),
65    // Should this just be discoverable?
66    #[schema(value_type = String)]
67    Passkey(Box<PublicKeyCredential>),
68}
69
70impl fmt::Debug for AuthCredential {
71    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
72        match self {
73            AuthCredential::Anonymous => write!(fmt, "Anonymous"),
74            AuthCredential::Password(_) => write!(fmt, "Password(_)"),
75            AuthCredential::Totp(_) => write!(fmt, "TOTP(_)"),
76            AuthCredential::SecurityKey(_) => write!(fmt, "SecurityKey(_)"),
77            AuthCredential::BackupCode(_) => write!(fmt, "BackupCode(_)"),
78            AuthCredential::Passkey(_) => write!(fmt, "Passkey(_)"),
79        }
80    }
81}
82
83/// The mechanisms that may proceed in this authentication
84#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialOrd, Ord, ToSchema)]
85#[serde(rename_all = "lowercase")]
86pub enum AuthMech {
87    Anonymous,
88    Password,
89    PasswordBackupCode,
90    // Now represents TOTP.
91    #[serde(rename = "passwordmfa")]
92    PasswordTotp,
93    PasswordSecurityKey,
94    Passkey,
95    OAuth2Trust,
96}
97
98impl AuthMech {
99    pub fn to_value(&self) -> &'static str {
100        match self {
101            AuthMech::Anonymous => "anonymous",
102            AuthMech::Password => "password",
103            AuthMech::PasswordTotp => "passwordmfa",
104            AuthMech::PasswordBackupCode => "passwordbackupcode",
105            AuthMech::PasswordSecurityKey => "passwordsecuritykey",
106            AuthMech::Passkey => "passkey",
107            AuthMech::OAuth2Trust => "oauth2trust",
108        }
109    }
110}
111
112impl PartialEq for AuthMech {
113    fn eq(&self, other: &Self) -> bool {
114        std::mem::discriminant(self) == std::mem::discriminant(other)
115    }
116}
117
118impl fmt::Display for AuthMech {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            AuthMech::Anonymous => write!(f, "Anonymous (no credentials)"),
122            AuthMech::Password => write!(f, "Password"),
123            AuthMech::PasswordTotp => write!(f, "TOTP and Password"),
124            AuthMech::PasswordBackupCode => write!(f, "Backup Code and Password"),
125            AuthMech::PasswordSecurityKey => write!(f, "Security Key and Password"),
126            AuthMech::Passkey => write!(f, "Passkey"),
127            AuthMech::OAuth2Trust => write!(f, "OAuth2 Trust"),
128        }
129    }
130}
131
132/// The type of session that should be issued to the client.
133#[derive(Debug, Serialize, Deserialize, Copy, Clone, ToSchema)]
134#[serde(rename_all = "lowercase")]
135pub enum AuthIssueSession {
136    /// Issue a bearer token for this client. This is the default.
137    Token,
138    /// Issue a cookie for this client.
139    Cookie,
140}
141
142impl std::fmt::Display for AuthIssueSession {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match self {
145            AuthIssueSession::Token => write!(f, "Token"),
146            AuthIssueSession::Cookie => write!(f, "Cookie"),
147        }
148    }
149}
150
151/// A request for the next step of an authentication.
152#[derive(Debug, Serialize, Deserialize, ToSchema)]
153pub struct AuthRequest {
154    pub step: AuthStep,
155}
156
157/// A challenge containing the list of allowed authentication types
158/// that can satisfy the next step. These may have inner types with
159/// required context.
160#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
161#[serde(rename_all = "lowercase")]
162pub enum AuthAllowed {
163    Anonymous,
164    BackupCode,
165    Password,
166    Totp,
167
168    #[schema(value_type = HashMap<String, Value>)]
169    SecurityKey(RequestChallengeResponse),
170    #[schema(value_type = HashMap<String, Value>)]
171    Passkey(RequestChallengeResponse),
172}
173
174impl PartialEq for AuthAllowed {
175    fn eq(&self, other: &Self) -> bool {
176        std::mem::discriminant(self) == std::mem::discriminant(other)
177    }
178}
179
180impl From<&AuthAllowed> for u8 {
181    fn from(a: &AuthAllowed) -> u8 {
182        match a {
183            AuthAllowed::Anonymous => 0,
184            AuthAllowed::Password => 1,
185            AuthAllowed::BackupCode => 2,
186            AuthAllowed::Totp => 3,
187            AuthAllowed::Passkey(_) => 4,
188            AuthAllowed::SecurityKey(_) => 5,
189        }
190    }
191}
192
193impl Eq for AuthAllowed {}
194
195impl Ord for AuthAllowed {
196    fn cmp(&self, other: &Self) -> Ordering {
197        let self_ord: u8 = self.into();
198        let other_ord: u8 = other.into();
199        self_ord.cmp(&other_ord)
200    }
201}
202
203impl PartialOrd for AuthAllowed {
204    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
205        Some(self.cmp(other))
206    }
207}
208
209impl fmt::Display for AuthAllowed {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        match self {
212            AuthAllowed::Anonymous => write!(f, "Anonymous (no credentials)"),
213            AuthAllowed::Password => write!(f, "Password"),
214            AuthAllowed::BackupCode => write!(f, "Backup Code"),
215            AuthAllowed::Totp => write!(f, "TOTP"),
216            AuthAllowed::SecurityKey(_) => write!(f, "Security Token"),
217            AuthAllowed::Passkey(_) => write!(f, "Passkey"),
218        }
219    }
220}
221
222#[derive(Debug, Serialize, Deserialize, ToSchema)]
223pub struct AuthResponse {
224    pub sessionid: Uuid,
225    pub state: AuthState,
226}