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    ///
109    /// # Example
110    ///
111    /// ```rust
112    /// # use auth_framework::authentication::credentials::Credential;
113    /// let cred = Credential::password("alice", "s3cret!");
114    /// assert_eq!(cred.credential_type(), "password");
115    /// ```
116    pub fn password(username: impl Into<String>, password: impl Into<String>) -> Self {
117        Self::Password {
118            username: username.into(),
119            password: password.into(),
120        }
121    }
122
123    /// Create OAuth authorization code credentials.
124    ///
125    /// Start with the authorization code only; attach optional fields like
126    /// `redirect_uri` via the `OAuth` variant's public fields.
127    pub fn oauth_code(authorization_code: impl Into<String>) -> Self {
128        Self::OAuth {
129            authorization_code: authorization_code.into(),
130            redirect_uri: None,
131            code_verifier: None,
132            state: None,
133        }
134    }
135
136    /// Create OAuth authorization code credentials with PKCE.
137    ///
138    /// Includes a code verifier for the Proof Key for Code Exchange flow.
139    pub fn oauth_code_with_pkce(
140        authorization_code: impl Into<String>,
141        code_verifier: impl Into<String>,
142    ) -> Self {
143        Self::OAuth {
144            authorization_code: authorization_code.into(),
145            redirect_uri: None,
146            code_verifier: Some(code_verifier.into()),
147            state: None,
148        }
149    }
150
151    /// Create OAuth refresh token credentials
152    pub fn oauth_refresh(refresh_token: impl Into<String>) -> Self {
153        Self::OAuthRefresh {
154            refresh_token: refresh_token.into(),
155        }
156    }
157
158    /// Create device code credentials for device flow.
159    ///
160    /// Starts a device authorization grant with just the device code and
161    /// client ID.  Optional fields (`user_code`, `verification_uri`, etc.)
162    /// are available on the `DeviceCode` variant.
163    pub fn device_code(device_code: impl Into<String>, client_id: impl Into<String>) -> Self {
164        Self::DeviceCode {
165            device_code: device_code.into(),
166            client_id: client_id.into(),
167            user_code: None,
168            verification_uri: None,
169            verification_uri_complete: None,
170            expires_in: None,
171            interval: None,
172        }
173    }
174
175    /// Create API key credentials
176    pub fn api_key(key: impl Into<String>) -> Self {
177        Self::ApiKey { key: key.into() }
178    }
179
180    /// Create JWT credentials
181    pub fn jwt(token: impl Into<String>) -> Self {
182        Self::Jwt {
183            token: token.into(),
184        }
185    }
186
187    /// Create bearer token credentials
188    pub fn bearer(token: impl Into<String>) -> Self {
189        Self::Bearer {
190            token: token.into(),
191        }
192    }
193
194    /// Create basic authentication credentials
195    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
196        let credentials = format!("{}:{}", username.into(), password.into());
197        let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
198
199        Self::Basic {
200            credentials: encoded,
201        }
202    }
203
204    /// Create custom credentials with arbitrary key-value data.
205    ///
206    /// The `method` string identifies the custom auth method, while
207    /// `data` carries method-specific fields.
208    ///
209    /// # Example
210    ///
211    /// ```rust
212    /// # use auth_framework::authentication::credentials::Credential;
213    /// use std::collections::HashMap;
214    ///
215    /// let mut data = HashMap::new();
216    /// data.insert("hardware_token".into(), "ABC123".into());
217    /// let cred = Credential::custom("hardware", data);
218    /// ```
219    pub fn custom(method: impl Into<String>, data: HashMap<String, String>) -> Self {
220        Self::Custom {
221            method: method.into(),
222            data,
223        }
224    }
225
226    /// Create MFA credentials that wrap a primary credential with a
227    /// second-factor code and challenge identifier.
228    pub fn mfa(
229        primary_credential: Credential,
230        mfa_code: impl Into<String>,
231        challenge_id: impl Into<String>,
232    ) -> Self {
233        Self::Mfa {
234            primary_credential: Box::new(primary_credential),
235            mfa_code: mfa_code.into(),
236            challenge_id: challenge_id.into(),
237        }
238    }
239
240    /// Create certificate credentials from raw DER-encoded bytes.
241    ///
242    /// For certificates already verified by TLS, consider
243    /// [`client_cert_from_tls`](Self::client_cert_from_tls) instead.
244    pub fn certificate(
245        certificate: Vec<u8>,
246        private_key: Vec<u8>,
247        passphrase: Option<String>,
248    ) -> Self {
249        Self::Certificate {
250            certificate,
251            private_key,
252            passphrase,
253        }
254    }
255
256    /// Create credentials representing a client certificate that was already
257    /// verified by the mTLS handshake.  The private key is **not** required —
258    /// key possession was proved by TLS; supplying one has no effect.
259    pub fn client_cert_from_tls(der_certificate: Vec<u8>) -> Self {
260        Self::Certificate {
261            certificate: der_certificate,
262            private_key: vec![],
263            passphrase: None,
264        }
265    }
266
267    /// Create SAML assertion credentials - REMOVED for security
268    ///
269    /// Create OpenID Connect credentials
270    pub fn openid_connect(id_token: impl Into<String>) -> Self {
271        Self::OpenIdConnect {
272            id_token: id_token.into(),
273            access_token: None,
274            refresh_token: None,
275        }
276    }
277
278    /// Create passkey credentials (WebAuthn/FIDO2)
279    #[cfg(feature = "passkeys")]
280    pub fn passkey(credential_id: Vec<u8>, assertion_response: impl Into<String>) -> Self {
281        Self::Passkey {
282            credential_id,
283            assertion_response: assertion_response.into(),
284        }
285    }
286
287    /// Get the credential type as a string
288    pub fn credential_type(&self) -> &str {
289        match self {
290            Self::Password { .. } => "password",
291            Self::OAuth { .. } => "oauth",
292            Self::OAuthRefresh { .. } => "oauth_refresh",
293            Self::ApiKey { .. } => "api_key",
294            Self::Jwt { .. } => "jwt",
295            Self::Bearer { .. } => "bearer",
296            Self::Basic { .. } => "basic",
297            Self::Custom { method, .. } => method.as_str(),
298            Self::Mfa { .. } => "mfa",
299            Self::Certificate { .. } => "certificate",
300            #[cfg(feature = "saml")]
301            Self::Saml { .. } => "saml",
302            Self::OpenIdConnect { .. } => "openid_connect",
303            Self::DeviceCode { .. } => "device_code",
304            Self::EnhancedDeviceFlow { .. } => "enhanced_device_flow",
305            #[cfg(feature = "passkeys")]
306            Self::Passkey { .. } => "passkey",
307        }
308    }
309
310    /// Check if this credential supports refresh
311    pub fn supports_refresh(&self) -> bool {
312        matches!(
313            self,
314            Self::OAuth { .. } | Self::OAuthRefresh { .. } | Self::OpenIdConnect { .. }
315        )
316    }
317
318    /// Extract refresh token if available
319    pub fn refresh_token(&self) -> Option<&str> {
320        match self {
321            Self::OAuthRefresh { refresh_token } => Some(refresh_token),
322            Self::OpenIdConnect { refresh_token, .. } => refresh_token.as_deref(),
323            _ => None,
324        }
325    }
326
327    /// Check if this credential is sensitive and should be masked in logs
328    pub fn is_sensitive(&self) -> bool {
329        matches!(
330            self,
331            Self::Password { .. }
332                | Self::ApiKey { .. }
333                | Self::Jwt { .. }
334                | Self::Bearer { .. }
335                | Self::Basic { .. }
336                | Self::Certificate { .. }
337                | Self::Mfa { .. }
338        )
339    }
340
341    /// Get a safe representation for logging (masks sensitive data)
342    pub fn safe_display(&self) -> String {
343        match self {
344            Self::Password { username, .. } => {
345                format!("Password(username: {username})")
346            }
347            Self::OAuth { .. } => "OAuth(authorization_code)".to_string(),
348            Self::OAuthRefresh { .. } => "OAuthRefresh(refresh_token)".to_string(),
349            Self::ApiKey { .. } => "ApiKey(****)".to_string(),
350            Self::Jwt { .. } => "Jwt(****)".to_string(),
351            Self::Bearer { .. } => "Bearer(****)".to_string(),
352            Self::Basic { .. } => "Basic(****)".to_string(),
353            Self::Custom { method, .. } => format!("Custom(method: {method})"),
354            Self::Mfa { challenge_id, .. } => {
355                format!("Mfa(challenge_id: {challenge_id})")
356            }
357            Self::Certificate { .. } => "Certificate(****)".to_string(),
358            #[cfg(feature = "saml")]
359            Self::Saml { .. } => "Saml(****)".to_string(),
360            Self::OpenIdConnect { .. } => "OpenIdConnect(id_token)".to_string(),
361            Self::DeviceCode { .. } => "DeviceCode(****)".to_string(),
362            Self::EnhancedDeviceFlow { .. } => "EnhancedDeviceFlow(****)".to_string(),
363            #[cfg(feature = "passkeys")]
364            Self::Passkey { .. } => "Passkey(****)".to_string(),
365        }
366    }
367}
368
369/// Additional credential metadata that can be attached to any credential type.
370///
371/// Use the builder methods to construct metadata fluently:
372///
373/// ```rust
374/// # use auth_framework::authentication::credentials::CredentialMetadata;
375/// let meta = CredentialMetadata::new()
376///     .client_id("my-app")
377///     .client_ip("10.0.0.1")
378///     .scope("read")
379///     .scope("write");
380/// ```
381#[derive(Debug, Clone, Serialize, Deserialize, Default)]
382pub struct CredentialMetadata {
383    /// Client identifier (for OAuth flows).
384    pub client_id: Option<String>,
385
386    /// Requested scopes (e.g. `["read", "write"]`).
387    pub scopes: Vec<String>,
388
389    /// User-Agent string from the HTTP request, if available.
390    pub user_agent: Option<String>,
391
392    /// IP address of the authenticating client, if available.
393    pub client_ip: Option<String>,
394
395    /// Additional custom metadata key-value pairs.
396    pub custom: HashMap<String, String>,
397}
398
399impl CredentialMetadata {
400    /// Create empty credential metadata.
401    pub fn new() -> Self {
402        Self::default()
403    }
404
405    /// Set the OAuth client identifier.
406    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
407        self.client_id = Some(client_id.into());
408        self
409    }
410
411    /// Append a single scope to the requested scopes.
412    pub fn scope(mut self, scope: impl Into<String>) -> Self {
413        self.scopes.push(scope.into());
414        self
415    }
416
417    /// Replace the requested scopes with the given list.
418    pub fn scopes(mut self, scopes: Vec<String>) -> Self {
419        self.scopes = scopes;
420        self
421    }
422
423    /// Set the User-Agent header value from the HTTP request.
424    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
425        self.user_agent = Some(user_agent.into());
426        self
427    }
428
429    /// Set the IP address of the authenticating client.
430    pub fn client_ip(mut self, client_ip: impl Into<String>) -> Self {
431        self.client_ip = Some(client_ip.into());
432        self
433    }
434
435    /// Add a custom metadata key-value pair.
436    pub fn custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
437        self.custom.insert(key.into(), value.into());
438        self
439    }
440}
441
442/// A complete authentication request with credentials and metadata.
443#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct AuthRequest {
445    /// The credentials to authenticate with
446    pub credential: Credential,
447
448    /// Additional metadata
449    pub metadata: CredentialMetadata,
450
451    /// Timestamp of the request
452    pub timestamp: chrono::DateTime<chrono::Utc>,
453}
454
455impl AuthRequest {
456    /// Create a new authentication request
457    pub fn new(credential: Credential) -> Self {
458        Self {
459            credential,
460            metadata: CredentialMetadata::default(),
461            timestamp: chrono::Utc::now(),
462        }
463    }
464
465    /// Create a new authentication request with metadata
466    pub fn with_metadata(credential: Credential, metadata: CredentialMetadata) -> Self {
467        Self {
468            credential,
469            metadata,
470            timestamp: chrono::Utc::now(),
471        }
472    }
473
474    /// Get a safe representation for logging
475    pub fn safe_display(&self) -> String {
476        format!(
477            "AuthRequest(credential: {}, client_id: {:?}, timestamp: {})",
478            self.credential.safe_display(),
479            self.metadata.client_id,
480            self.timestamp
481        )
482    }
483}