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;
6use std::fmt;
7use zeroize::Zeroizing;
8
9/// Represents different types of credentials that can be used for authentication.
10///
11/// Does not derive `Debug`: several variants carry raw secret material
12/// (passwords, private keys, tokens), and a derived `Debug` would print it
13/// verbatim on any accidental `{:?}`. The manual impl below delegates to
14/// [`Credential::safe_display`], which already existed as the intended
15/// redacted representation -- this restores that as the actual `Debug`
16/// output rather than leaving the derive as an unused, unsafe alternative
17/// path nobody deleted after `safe_display` was written.
18///
19/// Does not derive `Serialize`/`Deserialize`: several variants carry raw
20/// secret material in plain `String`/`Vec<u8>` fields, and a derived
21/// `Serialize` would write it verbatim into any JSON/CBOR/etc. output
22/// produced from this type. There is no in-tree persistence need for
23/// `Credential` -- nothing in this crate serializes it -- so the derive
24/// is removed outright rather than replaced with a redacting impl,
25/// which would silently produce a structurally-valid-but-wrong value.
26/// A consumer that genuinely needs to persist a `Credential` should
27/// serialize its own explicit, reviewed representation instead.
28#[derive(Clone)]
29pub enum Credential {
30    /// Username and password credentials
31    Password { username: String, password: String },
32
33    /// OAuth authorization code flow
34    OAuth {
35        authorization_code: String,
36        redirect_uri: Option<String>,
37        code_verifier: Option<String>, // For PKCE
38        state: Option<String>,
39    },
40
41    /// OAuth refresh token
42    OAuthRefresh { refresh_token: String },
43
44    /// API key authentication
45    ApiKey { key: String },
46
47    /// JSON Web Token
48    Jwt { token: String },
49
50    /// Bearer token (generic)
51    Bearer { token: String },
52
53    /// Basic authentication (username:password base64 encoded)
54    Basic { credentials: String },
55
56    /// Custom authentication with flexible key-value pairs
57    Custom {
58        method: String,
59        data: HashMap<String, String>,
60    },
61
62    /// Multi-factor authentication token
63    Mfa {
64        primary_credential: Box<Credential>,
65        mfa_code: String,
66        challenge_id: String,
67    },
68
69    /// Certificate-based authentication
70    Certificate {
71        certificate: Vec<u8>,
72        private_key: Zeroizing<Vec<u8>>,
73        passphrase: Option<String>,
74    },
75
76    /// SAML assertion with secure XML signature validation
77    #[cfg(feature = "saml")]
78    Saml { assertion: String },
79
80    /// OpenID Connect ID token
81    OpenIdConnect {
82        id_token: String,
83        access_token: Option<String>,
84        refresh_token: Option<String>,
85    },
86
87    /// Device flow credentials (device code polling)
88    DeviceCode {
89        device_code: String,
90        client_id: String,
91        user_code: Option<String>,
92        verification_uri: Option<String>,
93        verification_uri_complete: Option<String>,
94        expires_in: Option<u64>,
95        interval: Option<u64>,
96    },
97
98    /// Enhanced device flow credentials with full OAuth device flow support
99    EnhancedDeviceFlow {
100        device_code: String,
101        user_code: String,
102        verification_uri: String,
103        verification_uri_complete: Option<String>,
104        expires_in: u64,
105        interval: u64,
106        client_id: String,
107        client_secret: Option<String>,
108        scopes: Vec<String>,
109    },
110
111    /// WebAuthn/FIDO2 Passkey authentication using pure Rust implementation
112    #[cfg(feature = "passkeys")]
113    Passkey {
114        credential_id: Vec<u8>,
115        assertion_response: String, // JSON-serialized AuthenticatorAssertionResponse
116    },
117}
118
119impl fmt::Debug for Credential {
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        f.write_str(&self.safe_display())
122    }
123}
124
125impl Credential {
126    /// Create password credentials.
127    ///
128    /// # Example
129    ///
130    /// ```rust
131    /// # use auth_framework::authentication::credentials::Credential;
132    /// let cred = Credential::password("alice", "s3cret!");
133    /// assert_eq!(cred.credential_type(), "password");
134    /// ```
135    pub fn password(username: impl Into<String>, password: impl Into<String>) -> Self {
136        Self::Password {
137            username: username.into(),
138            password: password.into(),
139        }
140    }
141
142    /// Create OAuth authorization code credentials.
143    ///
144    /// Start with the authorization code only; attach optional fields like
145    /// `redirect_uri` via the `OAuth` variant's public fields.
146    pub fn oauth_code(authorization_code: impl Into<String>) -> Self {
147        Self::OAuth {
148            authorization_code: authorization_code.into(),
149            redirect_uri: None,
150            code_verifier: None,
151            state: None,
152        }
153    }
154
155    /// Create OAuth authorization code credentials with PKCE.
156    ///
157    /// Includes a code verifier for the Proof Key for Code Exchange flow.
158    pub fn oauth_code_with_pkce(
159        authorization_code: impl Into<String>,
160        code_verifier: impl Into<String>,
161    ) -> Self {
162        Self::OAuth {
163            authorization_code: authorization_code.into(),
164            redirect_uri: None,
165            code_verifier: Some(code_verifier.into()),
166            state: None,
167        }
168    }
169
170    /// Create OAuth refresh token credentials
171    pub fn oauth_refresh(refresh_token: impl Into<String>) -> Self {
172        Self::OAuthRefresh {
173            refresh_token: refresh_token.into(),
174        }
175    }
176
177    /// Create device code credentials for device flow.
178    ///
179    /// Starts a device authorization grant with just the device code and
180    /// client ID.  Optional fields (`user_code`, `verification_uri`, etc.)
181    /// are available on the `DeviceCode` variant.
182    pub fn device_code(device_code: impl Into<String>, client_id: impl Into<String>) -> Self {
183        Self::DeviceCode {
184            device_code: device_code.into(),
185            client_id: client_id.into(),
186            user_code: None,
187            verification_uri: None,
188            verification_uri_complete: None,
189            expires_in: None,
190            interval: None,
191        }
192    }
193
194    /// Create API key credentials
195    pub fn api_key(key: impl Into<String>) -> Self {
196        Self::ApiKey { key: key.into() }
197    }
198
199    /// Create JWT credentials
200    pub fn jwt(token: impl Into<String>) -> Self {
201        Self::Jwt {
202            token: token.into(),
203        }
204    }
205
206    /// Create bearer token credentials
207    pub fn bearer(token: impl Into<String>) -> Self {
208        Self::Bearer {
209            token: token.into(),
210        }
211    }
212
213    /// Create basic authentication credentials
214    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
215        let credentials = format!("{}:{}", username.into(), password.into());
216        let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
217
218        Self::Basic {
219            credentials: encoded,
220        }
221    }
222
223    /// Create custom credentials with arbitrary key-value data.
224    ///
225    /// The `method` string identifies the custom auth method, while
226    /// `data` carries method-specific fields.
227    ///
228    /// # Example
229    ///
230    /// ```rust
231    /// # use auth_framework::authentication::credentials::Credential;
232    /// use std::collections::HashMap;
233    ///
234    /// let mut data = HashMap::new();
235    /// data.insert("hardware_token".into(), "ABC123".into());
236    /// let cred = Credential::custom("hardware", data);
237    /// ```
238    pub fn custom(method: impl Into<String>, data: HashMap<String, String>) -> Self {
239        Self::Custom {
240            method: method.into(),
241            data,
242        }
243    }
244
245    /// Create MFA credentials that wrap a primary credential with a
246    /// second-factor code and challenge identifier.
247    pub fn mfa(
248        primary_credential: Credential,
249        mfa_code: impl Into<String>,
250        challenge_id: impl Into<String>,
251    ) -> Self {
252        Self::Mfa {
253            primary_credential: Box::new(primary_credential),
254            mfa_code: mfa_code.into(),
255            challenge_id: challenge_id.into(),
256        }
257    }
258
259    /// Create certificate credentials from raw DER-encoded bytes.
260    ///
261    /// For certificates already verified by TLS, consider
262    /// [`client_cert_from_tls`](Self::client_cert_from_tls) instead.
263    pub fn certificate(
264        certificate: Vec<u8>,
265        private_key: Vec<u8>,
266        passphrase: Option<String>,
267    ) -> Self {
268        Self::Certificate {
269            certificate,
270            private_key: Zeroizing::new(private_key),
271            passphrase,
272        }
273    }
274
275    /// Create credentials representing a client certificate that was already
276    /// verified by the mTLS handshake.  The private key is **not** required —
277    /// key possession was proved by TLS; supplying one has no effect.
278    pub fn client_cert_from_tls(der_certificate: Vec<u8>) -> Self {
279        Self::Certificate {
280            certificate: der_certificate,
281            private_key: Zeroizing::new(vec![]),
282            passphrase: None,
283        }
284    }
285
286    /// Create SAML assertion credentials - REMOVED for security
287    ///
288    /// Create OpenID Connect credentials
289    pub fn openid_connect(id_token: impl Into<String>) -> Self {
290        Self::OpenIdConnect {
291            id_token: id_token.into(),
292            access_token: None,
293            refresh_token: None,
294        }
295    }
296
297    /// Create passkey credentials (WebAuthn/FIDO2)
298    #[cfg(feature = "passkeys")]
299    pub fn passkey(credential_id: Vec<u8>, assertion_response: impl Into<String>) -> Self {
300        Self::Passkey {
301            credential_id,
302            assertion_response: assertion_response.into(),
303        }
304    }
305
306    /// Get the credential type as a string
307    pub fn credential_type(&self) -> &str {
308        match self {
309            Self::Password { .. } => "password",
310            Self::OAuth { .. } => "oauth",
311            Self::OAuthRefresh { .. } => "oauth_refresh",
312            Self::ApiKey { .. } => "api_key",
313            Self::Jwt { .. } => "jwt",
314            Self::Bearer { .. } => "bearer",
315            Self::Basic { .. } => "basic",
316            Self::Custom { method, .. } => method.as_str(),
317            Self::Mfa { .. } => "mfa",
318            Self::Certificate { .. } => "certificate",
319            #[cfg(feature = "saml")]
320            Self::Saml { .. } => "saml",
321            Self::OpenIdConnect { .. } => "openid_connect",
322            Self::DeviceCode { .. } => "device_code",
323            Self::EnhancedDeviceFlow { .. } => "enhanced_device_flow",
324            #[cfg(feature = "passkeys")]
325            Self::Passkey { .. } => "passkey",
326        }
327    }
328
329    /// Check if this credential supports refresh
330    pub fn supports_refresh(&self) -> bool {
331        matches!(
332            self,
333            Self::OAuth { .. } | Self::OAuthRefresh { .. } | Self::OpenIdConnect { .. }
334        )
335    }
336
337    /// Extract refresh token if available
338    pub fn refresh_token(&self) -> Option<&str> {
339        match self {
340            Self::OAuthRefresh { refresh_token } => Some(refresh_token),
341            Self::OpenIdConnect { refresh_token, .. } => refresh_token.as_deref(),
342            _ => None,
343        }
344    }
345
346    /// Check if this credential is sensitive and should be masked in logs
347    pub fn is_sensitive(&self) -> bool {
348        matches!(
349            self,
350            Self::Password { .. }
351                | Self::ApiKey { .. }
352                | Self::Jwt { .. }
353                | Self::Bearer { .. }
354                | Self::Basic { .. }
355                | Self::Certificate { .. }
356                | Self::Mfa { .. }
357        )
358    }
359
360    /// Get a safe representation for logging (masks sensitive data)
361    pub fn safe_display(&self) -> String {
362        match self {
363            Self::Password { username, .. } => {
364                format!("Password(username: {username})")
365            }
366            Self::OAuth { .. } => "OAuth(authorization_code)".to_string(),
367            Self::OAuthRefresh { .. } => "OAuthRefresh(refresh_token)".to_string(),
368            Self::ApiKey { .. } => "ApiKey(****)".to_string(),
369            Self::Jwt { .. } => "Jwt(****)".to_string(),
370            Self::Bearer { .. } => "Bearer(****)".to_string(),
371            Self::Basic { .. } => "Basic(****)".to_string(),
372            Self::Custom { method, .. } => format!("Custom(method: {method})"),
373            Self::Mfa { challenge_id, .. } => {
374                format!("Mfa(challenge_id: {challenge_id})")
375            }
376            Self::Certificate { .. } => "Certificate(****)".to_string(),
377            #[cfg(feature = "saml")]
378            Self::Saml { .. } => "Saml(****)".to_string(),
379            Self::OpenIdConnect { .. } => "OpenIdConnect(id_token)".to_string(),
380            Self::DeviceCode { .. } => "DeviceCode(****)".to_string(),
381            Self::EnhancedDeviceFlow { .. } => "EnhancedDeviceFlow(****)".to_string(),
382            #[cfg(feature = "passkeys")]
383            Self::Passkey { .. } => "Passkey(****)".to_string(),
384        }
385    }
386}
387
388/// Additional credential metadata that can be attached to any credential type.
389///
390/// Use the builder methods to construct metadata fluently:
391///
392/// ```rust
393/// # use auth_framework::authentication::credentials::CredentialMetadata;
394/// let meta = CredentialMetadata::new()
395///     .client_id("my-app")
396///     .client_ip("10.0.0.1")
397///     .scope("read")
398///     .scope("write");
399/// ```
400#[derive(Debug, Clone, Serialize, Deserialize, Default)]
401pub struct CredentialMetadata {
402    /// Client identifier (for OAuth flows).
403    pub client_id: Option<String>,
404
405    /// Requested scopes (e.g. `["read", "write"]`).
406    pub scopes: Vec<String>,
407
408    /// User-Agent string from the HTTP request, if available.
409    pub user_agent: Option<String>,
410
411    /// IP address of the authenticating client, if available.
412    pub client_ip: Option<String>,
413
414    /// Additional custom metadata key-value pairs.
415    pub custom: HashMap<String, String>,
416}
417
418impl CredentialMetadata {
419    /// Create empty credential metadata.
420    pub fn new() -> Self {
421        Self::default()
422    }
423
424    /// Set the OAuth client identifier.
425    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
426        self.client_id = Some(client_id.into());
427        self
428    }
429
430    /// Append a single scope to the requested scopes.
431    pub fn scope(mut self, scope: impl Into<String>) -> Self {
432        self.scopes.push(scope.into());
433        self
434    }
435
436    /// Replace the requested scopes with the given list.
437    pub fn scopes(mut self, scopes: Vec<String>) -> Self {
438        self.scopes = scopes;
439        self
440    }
441
442    /// Set the User-Agent header value from the HTTP request.
443    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
444        self.user_agent = Some(user_agent.into());
445        self
446    }
447
448    /// Set the IP address of the authenticating client.
449    pub fn client_ip(mut self, client_ip: impl Into<String>) -> Self {
450        self.client_ip = Some(client_ip.into());
451        self
452    }
453
454    /// Add a custom metadata key-value pair.
455    pub fn custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
456        self.custom.insert(key.into(), value.into());
457        self
458    }
459}
460
461/// A complete authentication request with credentials and metadata.
462///
463/// Does not derive `Serialize`/`Deserialize`: it embeds [`Credential`],
464/// which does not derive them either -- see that type's doc comment.
465#[derive(Debug, Clone)]
466pub struct AuthRequest {
467    /// The credentials to authenticate with
468    pub credential: Credential,
469
470    /// Additional metadata
471    pub metadata: CredentialMetadata,
472
473    /// Timestamp of the request
474    pub timestamp: chrono::DateTime<chrono::Utc>,
475}
476
477impl AuthRequest {
478    /// Create a new authentication request
479    pub fn new(credential: Credential) -> Self {
480        Self {
481            credential,
482            metadata: CredentialMetadata::default(),
483            timestamp: chrono::Utc::now(),
484        }
485    }
486
487    /// Create a new authentication request with metadata
488    pub fn with_metadata(credential: Credential, metadata: CredentialMetadata) -> Self {
489        Self {
490            credential,
491            metadata,
492            timestamp: chrono::Utc::now(),
493        }
494    }
495
496    /// Get a safe representation for logging
497    pub fn safe_display(&self) -> String {
498        format!(
499            "AuthRequest(credential: {}, client_id: {:?}, timestamp: {})",
500            self.credential.safe_display(),
501            self.metadata.client_id,
502            self.timestamp
503        )
504    }
505}