Skip to main content

auth_framework/authentication/
credentials.rs

1//! Credential types for various authentication methods.
2
3use base64::Engine;
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7/// Represents different types of credentials that can be used for authentication.
8#[derive(Clone, Serialize, Deserialize)]
9#[serde(tag = "type", content = "data")]
10pub enum Credential {
11    /// Username and password credentials
12    Password { username: String, password: String },
13
14    /// OAuth authorization code flow
15    OAuth {
16        authorization_code: String,
17        redirect_uri: Option<String>,
18        code_verifier: Option<String>, // For PKCE
19        state: Option<String>,
20    },
21
22    /// OAuth refresh token
23    OAuthRefresh { refresh_token: String },
24
25    /// API key authentication
26    ApiKey { key: String },
27
28    /// JSON Web Token
29    Jwt { token: String },
30
31    /// Bearer token (generic)
32    Bearer { token: String },
33
34    /// Basic authentication (username:password base64 encoded)
35    Basic { credentials: String },
36
37    /// Custom authentication with flexible key-value pairs
38    Custom {
39        method: String,
40        data: HashMap<String, String>,
41    },
42
43    /// Multi-factor authentication token
44    Mfa {
45        primary_credential: Box<Credential>,
46        mfa_code: String,
47        challenge_id: String,
48    },
49
50    /// Certificate-based authentication
51    Certificate {
52        certificate: Vec<u8>,
53        private_key: Vec<u8>,
54        passphrase: Option<String>,
55    },
56
57    /// SAML assertion with secure XML signature validation
58    #[cfg(feature = "saml")]
59    Saml { assertion: String },
60
61    /// OpenID Connect ID token
62    OpenIdConnect {
63        id_token: String,
64        access_token: Option<String>,
65        refresh_token: Option<String>,
66    },
67
68    /// Device flow credentials (device code polling)
69    DeviceCode {
70        device_code: String,
71        client_id: String,
72        user_code: Option<String>,
73        verification_uri: Option<String>,
74        verification_uri_complete: Option<String>,
75        expires_in: Option<u64>,
76        interval: Option<u64>,
77    },
78
79    /// Enhanced device flow credentials with full OAuth device flow support
80    EnhancedDeviceFlow {
81        device_code: String,
82        user_code: String,
83        verification_uri: String,
84        verification_uri_complete: Option<String>,
85        expires_in: u64,
86        interval: u64,
87        client_id: String,
88        client_secret: Option<String>,
89        scopes: Vec<String>,
90    },
91
92    /// WebAuthn/FIDO2 Passkey authentication using pure Rust implementation
93    #[cfg(feature = "passkeys")]
94    Passkey {
95        credential_id: Vec<u8>,
96        assertion_response: String, // JSON-serialized AuthenticatorAssertionResponse
97    },
98}
99
100impl std::fmt::Debug for Credential {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.write_str(&self.safe_display())
103    }
104}
105
106impl Credential {
107    /// Create password credentials
108    pub fn password(username: impl Into<String>, password: impl Into<String>) -> Self {
109        Self::Password {
110            username: username.into(),
111            password: password.into(),
112        }
113    }
114
115    /// Create OAuth authorization code credentials
116    pub fn oauth_code(authorization_code: impl Into<String>) -> Self {
117        Self::OAuth {
118            authorization_code: authorization_code.into(),
119            redirect_uri: None,
120            code_verifier: None,
121            state: None,
122        }
123    }
124
125    /// Create OAuth authorization code credentials with PKCE
126    pub fn oauth_code_with_pkce(
127        authorization_code: impl Into<String>,
128        code_verifier: impl Into<String>,
129    ) -> Self {
130        Self::OAuth {
131            authorization_code: authorization_code.into(),
132            redirect_uri: None,
133            code_verifier: Some(code_verifier.into()),
134            state: None,
135        }
136    }
137
138    /// Create OAuth refresh token credentials
139    pub fn oauth_refresh(refresh_token: impl Into<String>) -> Self {
140        Self::OAuthRefresh {
141            refresh_token: refresh_token.into(),
142        }
143    }
144
145    /// Create device code credentials for device flow
146    pub fn device_code(device_code: impl Into<String>, client_id: impl Into<String>) -> Self {
147        Self::DeviceCode {
148            device_code: device_code.into(),
149            client_id: client_id.into(),
150            user_code: None,
151            verification_uri: None,
152            verification_uri_complete: None,
153            expires_in: None,
154            interval: None,
155        }
156    }
157
158    /// Create API key credentials
159    pub fn api_key(key: impl Into<String>) -> Self {
160        Self::ApiKey { key: key.into() }
161    }
162
163    /// Create JWT credentials
164    pub fn jwt(token: impl Into<String>) -> Self {
165        Self::Jwt {
166            token: token.into(),
167        }
168    }
169
170    /// Create bearer token credentials
171    pub fn bearer(token: impl Into<String>) -> Self {
172        Self::Bearer {
173            token: token.into(),
174        }
175    }
176
177    /// Create basic authentication credentials
178    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
179        let credentials = format!("{}:{}", username.into(), password.into());
180        let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
181
182        Self::Basic {
183            credentials: encoded,
184        }
185    }
186
187    /// Create custom credentials
188    pub fn custom(method: impl Into<String>, data: HashMap<String, String>) -> Self {
189        Self::Custom {
190            method: method.into(),
191            data,
192        }
193    }
194
195    /// Create MFA credentials
196    pub fn mfa(
197        primary_credential: Credential,
198        mfa_code: impl Into<String>,
199        challenge_id: impl Into<String>,
200    ) -> Self {
201        Self::Mfa {
202            primary_credential: Box::new(primary_credential),
203            mfa_code: mfa_code.into(),
204            challenge_id: challenge_id.into(),
205        }
206    }
207
208    /// Create certificate credentials
209    pub fn certificate(
210        certificate: Vec<u8>,
211        private_key: Vec<u8>,
212        passphrase: Option<String>,
213    ) -> Self {
214        Self::Certificate {
215            certificate,
216            private_key,
217            passphrase,
218        }
219    }
220
221    /// Create SAML assertion credentials - REMOVED for security
222    ///
223    /// Create OpenID Connect credentials
224    pub fn openid_connect(id_token: impl Into<String>) -> Self {
225        Self::OpenIdConnect {
226            id_token: id_token.into(),
227            access_token: None,
228            refresh_token: None,
229        }
230    }
231
232    /// Create passkey credentials (WebAuthn/FIDO2)
233    #[cfg(feature = "passkeys")]
234    pub fn passkey(credential_id: Vec<u8>, assertion_response: impl Into<String>) -> Self {
235        Self::Passkey {
236            credential_id,
237            assertion_response: assertion_response.into(),
238        }
239    }
240
241    /// Get the credential type as a string
242    pub fn credential_type(&self) -> &str {
243        match self {
244            Self::Password { .. } => "password",
245            Self::OAuth { .. } => "oauth",
246            Self::OAuthRefresh { .. } => "oauth_refresh",
247            Self::ApiKey { .. } => "api_key",
248            Self::Jwt { .. } => "jwt",
249            Self::Bearer { .. } => "bearer",
250            Self::Basic { .. } => "basic",
251            Self::Custom { method, .. } => method.as_str(),
252            Self::Mfa { .. } => "mfa",
253            Self::Certificate { .. } => "certificate",
254            #[cfg(feature = "saml")]
255            Self::Saml { .. } => "saml",
256            Self::OpenIdConnect { .. } => "openid_connect",
257            Self::DeviceCode { .. } => "device_code",
258            Self::EnhancedDeviceFlow { .. } => "enhanced_device_flow",
259            #[cfg(feature = "passkeys")]
260            Self::Passkey { .. } => "passkey",
261        }
262    }
263
264    /// Check if this credential supports refresh
265    pub fn supports_refresh(&self) -> bool {
266        matches!(
267            self,
268            Self::OAuth { .. } | Self::OAuthRefresh { .. } | Self::OpenIdConnect { .. }
269        )
270    }
271
272    /// Extract refresh token if available
273    pub fn refresh_token(&self) -> Option<&str> {
274        match self {
275            Self::OAuthRefresh { refresh_token } => Some(refresh_token),
276            Self::OpenIdConnect { refresh_token, .. } => refresh_token.as_deref(),
277            _ => None,
278        }
279    }
280
281    /// Check if this credential is sensitive and should be masked in logs
282    pub fn is_sensitive(&self) -> bool {
283        matches!(
284            self,
285            Self::Password { .. }
286                | Self::ApiKey { .. }
287                | Self::Jwt { .. }
288                | Self::Bearer { .. }
289                | Self::Basic { .. }
290                | Self::Certificate { .. }
291                | Self::Mfa { .. }
292        )
293    }
294
295    /// Get a safe representation for logging (masks sensitive data)
296    pub fn safe_display(&self) -> String {
297        match self {
298            Self::Password { username, .. } => {
299                format!("Password(username: {username})")
300            }
301            Self::OAuth { .. } => "OAuth(authorization_code)".to_string(),
302            Self::OAuthRefresh { .. } => "OAuthRefresh(refresh_token)".to_string(),
303            Self::ApiKey { .. } => "ApiKey(****)".to_string(),
304            Self::Jwt { .. } => "Jwt(****)".to_string(),
305            Self::Bearer { .. } => "Bearer(****)".to_string(),
306            Self::Basic { .. } => "Basic(****)".to_string(),
307            Self::Custom { method, .. } => format!("Custom(method: {method})"),
308            Self::Mfa { challenge_id, .. } => {
309                format!("Mfa(challenge_id: {challenge_id})")
310            }
311            Self::Certificate { .. } => "Certificate(****)".to_string(),
312            #[cfg(feature = "saml")]
313            Self::Saml { .. } => "Saml(****)".to_string(),
314            Self::OpenIdConnect { .. } => "OpenIdConnect(id_token)".to_string(),
315            Self::DeviceCode { .. } => "DeviceCode(****)".to_string(),
316            Self::EnhancedDeviceFlow { .. } => "EnhancedDeviceFlow(****)".to_string(),
317            #[cfg(feature = "passkeys")]
318            Self::Passkey { .. } => "Passkey(****)".to_string(),
319        }
320    }
321}
322
323/// Additional credential metadata that can be attached to any credential type.
324#[derive(Debug, Clone, Serialize, Deserialize, Default)]
325pub struct CredentialMetadata {
326    /// Client identifier (for OAuth flows)
327    pub client_id: Option<String>,
328
329    /// Requested scopes
330    pub scopes: Vec<String>,
331
332    /// User agent string
333    pub user_agent: Option<String>,
334
335    /// IP address of the client
336    pub client_ip: Option<String>,
337
338    /// Additional custom metadata
339    pub custom: HashMap<String, String>,
340}
341
342impl CredentialMetadata {
343    /// Create new credential metadata
344    pub fn new() -> Self {
345        Self::default()
346    }
347
348    /// Set the client ID
349    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
350        self.client_id = Some(client_id.into());
351        self
352    }
353
354    /// Add a scope
355    pub fn scope(mut self, scope: impl Into<String>) -> Self {
356        self.scopes.push(scope.into());
357        self
358    }
359
360    /// Set multiple scopes
361    pub fn scopes(mut self, scopes: Vec<String>) -> Self {
362        self.scopes = scopes;
363        self
364    }
365
366    /// Set the user agent
367    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
368        self.user_agent = Some(user_agent.into());
369        self
370    }
371
372    /// Set the client IP
373    pub fn client_ip(mut self, client_ip: impl Into<String>) -> Self {
374        self.client_ip = Some(client_ip.into());
375        self
376    }
377
378    /// Add custom metadata
379    pub fn custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
380        self.custom.insert(key.into(), value.into());
381        self
382    }
383}
384
385/// A complete authentication request with credentials and metadata.
386#[derive(Debug, Clone, Serialize, Deserialize)]
387pub struct AuthRequest {
388    /// The credentials to authenticate with
389    pub credential: Credential,
390
391    /// Additional metadata
392    pub metadata: CredentialMetadata,
393
394    /// Timestamp of the request
395    pub timestamp: chrono::DateTime<chrono::Utc>,
396}
397
398impl AuthRequest {
399    /// Create a new authentication request
400    pub fn new(credential: Credential) -> Self {
401        Self {
402            credential,
403            metadata: CredentialMetadata::default(),
404            timestamp: chrono::Utc::now(),
405        }
406    }
407
408    /// Create a new authentication request with metadata
409    pub fn with_metadata(credential: Credential, metadata: CredentialMetadata) -> Self {
410        Self {
411            credential,
412            metadata,
413            timestamp: chrono::Utc::now(),
414        }
415    }
416
417    /// Get a safe representation for logging
418    pub fn safe_display(&self) -> String {
419        format!(
420            "AuthRequest(credential: {}, client_id: {:?}, timestamp: {})",
421            self.credential.safe_display(),
422            self.metadata.client_id,
423            self.timestamp
424        )
425    }
426}