cedros-login-server 0.0.45

Authentication server for cedros-login with email/password, Google OAuth, and Solana wallet sign-in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! WebAuthn credential repository
//!
//! Storage for WebAuthn passkeys and security keys.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::sync::RwLock;
use uuid::Uuid;

use crate::errors::AppError;

/// WebAuthn credential entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAuthnCredential {
    pub id: Uuid,
    pub user_id: Uuid,
    /// Base64URL-encoded credential ID from authenticator
    pub credential_id: String,
    /// Base64URL-encoded public key (COSE format)
    pub public_key: String,
    /// Signature counter for replay attack prevention
    pub sign_count: u32,
    /// Transport hints (usb, nfc, ble, internal, hybrid)
    pub transports: Option<Vec<String>>,
    /// Authenticator AAGUID (identifies authenticator model)
    pub aaguid: Option<String>,
    /// Whether this is a discoverable/resident credential (passkey)
    pub is_discoverable: bool,
    /// Whether the credential is backup eligible
    pub backup_eligible: bool,
    /// Whether the credential is currently backed up
    pub backup_state: bool,
    /// User-friendly label (e.g., "MacBook Pro", "YubiKey")
    pub label: Option<String>,
    pub created_at: DateTime<Utc>,
    pub last_used_at: Option<DateTime<Utc>>,
}

impl WebAuthnCredential {
    /// Create a new WebAuthn credential
    pub fn new(
        user_id: Uuid,
        credential_id: String,
        public_key: String,
        sign_count: u32,
        is_discoverable: bool,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            credential_id,
            public_key,
            sign_count,
            transports: None,
            aaguid: None,
            is_discoverable,
            backup_eligible: false,
            backup_state: false,
            label: None,
            created_at: Utc::now(),
            last_used_at: None,
        }
    }
}

/// WebAuthn challenge state for registration/authentication
/// This is stored temporarily during the ceremony
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebAuthnChallenge {
    pub challenge_id: Uuid,
    pub user_id: Option<Uuid>,
    /// The serialized passkey registration/authentication state
    pub state: String,
    /// Challenge type: "register" or "authenticate"
    pub challenge_type: String,
    pub created_at: DateTime<Utc>,
    pub expires_at: DateTime<Utc>,
}

/// WebAuthn repository trait
#[async_trait]
pub trait WebAuthnRepository: Send + Sync {
    // Credential operations

    /// Create a new WebAuthn credential
    async fn create_credential(
        &self,
        credential: WebAuthnCredential,
    ) -> Result<WebAuthnCredential, AppError>;

    /// Find credential by ID
    async fn find_credential_by_id(&self, id: Uuid)
        -> Result<Option<WebAuthnCredential>, AppError>;

    /// Find credential by credential_id (from authenticator)
    async fn find_by_credential_id(
        &self,
        credential_id: &str,
    ) -> Result<Option<WebAuthnCredential>, AppError>;

    /// Find all credentials for a user
    async fn find_by_user(&self, user_id: Uuid) -> Result<Vec<WebAuthnCredential>, AppError>;

    /// Find discoverable credentials for a user (passkeys that can be used for username-less auth)
    async fn find_discoverable_by_user(
        &self,
        user_id: Uuid,
    ) -> Result<Vec<WebAuthnCredential>, AppError>;

    /// Update sign count after successful authentication
    async fn update_sign_count(&self, id: Uuid, sign_count: u32) -> Result<(), AppError>;

    /// Update last_used_at timestamp
    async fn update_last_used(&self, id: Uuid) -> Result<(), AppError>;

    /// SEC-05: Atomically record successful authentication
    ///
    /// Updates both sign_count and last_used_at in a single atomic operation.
    /// This prevents race conditions where counter update might succeed but
    /// timestamp update fails (or vice versa).
    async fn record_successful_auth(&self, id: Uuid, sign_count: u32) -> Result<(), AppError>;

    /// Update credential label
    async fn update_label(&self, id: Uuid, label: Option<String>) -> Result<(), AppError>;

    /// Delete a credential
    async fn delete_credential(&self, id: Uuid) -> Result<(), AppError>;

    /// Delete all credentials for a user
    async fn delete_by_user(&self, user_id: Uuid) -> Result<u64, AppError>;

    // Challenge operations

    /// Store a challenge for registration/authentication ceremony
    async fn store_challenge(&self, challenge: WebAuthnChallenge) -> Result<(), AppError>;

    /// S-16: Find a challenge without consuming it (for checking challenge type)
    async fn find_challenge(
        &self,
        challenge_id: Uuid,
    ) -> Result<Option<WebAuthnChallenge>, AppError>;

    /// Get and consume a challenge (returns None if expired or not found)
    async fn consume_challenge(
        &self,
        challenge_id: Uuid,
    ) -> Result<Option<WebAuthnChallenge>, AppError>;

    /// Delete expired challenges
    async fn delete_expired_challenges(&self) -> Result<u64, AppError>;

    /// Fetch all credential IDs (for excludeCredentials in signup options).
    /// Returns base64url-encoded credential IDs, capped at `limit`.
    async fn find_all_credential_ids(&self, limit: i64) -> Result<Vec<String>, AppError>;
}

/// In-memory WebAuthn repository for development/testing
pub struct InMemoryWebAuthnRepository {
    credentials: RwLock<HashMap<Uuid, WebAuthnCredential>>,
    challenges: RwLock<HashMap<Uuid, WebAuthnChallenge>>,
}

impl InMemoryWebAuthnRepository {
    pub fn new() -> Self {
        Self {
            credentials: RwLock::new(HashMap::new()),
            challenges: RwLock::new(HashMap::new()),
        }
    }
}

impl Default for InMemoryWebAuthnRepository {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl WebAuthnRepository for InMemoryWebAuthnRepository {
    async fn create_credential(
        &self,
        credential: WebAuthnCredential,
    ) -> Result<WebAuthnCredential, AppError> {
        let mut credentials = self.credentials.write().await;

        // Check for duplicate credential_id
        for existing in credentials.values() {
            if existing.credential_id == credential.credential_id {
                return Err(AppError::Validation("Credential already registered".into()));
            }
        }

        credentials.insert(credential.id, credential.clone());
        Ok(credential)
    }

    async fn find_credential_by_id(
        &self,
        id: Uuid,
    ) -> Result<Option<WebAuthnCredential>, AppError> {
        let credentials = self.credentials.read().await;
        Ok(credentials.get(&id).cloned())
    }

    async fn find_by_credential_id(
        &self,
        credential_id: &str,
    ) -> Result<Option<WebAuthnCredential>, AppError> {
        let credentials = self.credentials.read().await;
        Ok(credentials
            .values()
            .find(|c| c.credential_id == credential_id)
            .cloned())
    }

    async fn find_by_user(&self, user_id: Uuid) -> Result<Vec<WebAuthnCredential>, AppError> {
        let credentials = self.credentials.read().await;
        let mut result: Vec<_> = credentials
            .values()
            .filter(|c| c.user_id == user_id)
            .cloned()
            .collect();
        result.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(result)
    }

    async fn find_discoverable_by_user(
        &self,
        user_id: Uuid,
    ) -> Result<Vec<WebAuthnCredential>, AppError> {
        let credentials = self.credentials.read().await;
        let mut result: Vec<_> = credentials
            .values()
            .filter(|c| c.user_id == user_id && c.is_discoverable)
            .cloned()
            .collect();
        result.sort_by(|a, b| b.created_at.cmp(&a.created_at));
        Ok(result)
    }

    async fn update_sign_count(&self, id: Uuid, sign_count: u32) -> Result<(), AppError> {
        let mut credentials = self.credentials.write().await;
        if let Some(cred) = credentials.get_mut(&id) {
            cred.sign_count = sign_count;
        }
        Ok(())
    }

    async fn update_last_used(&self, id: Uuid) -> Result<(), AppError> {
        let mut credentials = self.credentials.write().await;
        if let Some(cred) = credentials.get_mut(&id) {
            cred.last_used_at = Some(Utc::now());
        }
        Ok(())
    }

    async fn record_successful_auth(&self, id: Uuid, sign_count: u32) -> Result<(), AppError> {
        // SEC-05: Atomic update of both sign_count and last_used_at
        let mut credentials = self.credentials.write().await;
        if let Some(cred) = credentials.get_mut(&id) {
            cred.sign_count = sign_count;
            cred.last_used_at = Some(Utc::now());
        }
        Ok(())
    }

    async fn update_label(&self, id: Uuid, label: Option<String>) -> Result<(), AppError> {
        let mut credentials = self.credentials.write().await;
        if let Some(cred) = credentials.get_mut(&id) {
            cred.label = label;
        }
        Ok(())
    }

    async fn delete_credential(&self, id: Uuid) -> Result<(), AppError> {
        let mut credentials = self.credentials.write().await;
        credentials.remove(&id);
        Ok(())
    }

    async fn delete_by_user(&self, user_id: Uuid) -> Result<u64, AppError> {
        let mut credentials = self.credentials.write().await;
        let to_remove: Vec<Uuid> = credentials
            .values()
            .filter(|c| c.user_id == user_id)
            .map(|c| c.id)
            .collect();
        let count = to_remove.len() as u64;
        for id in to_remove {
            credentials.remove(&id);
        }
        Ok(count)
    }

    async fn store_challenge(&self, challenge: WebAuthnChallenge) -> Result<(), AppError> {
        let mut challenges = self.challenges.write().await;
        challenges.insert(challenge.challenge_id, challenge);
        Ok(())
    }

    async fn find_challenge(
        &self,
        challenge_id: Uuid,
    ) -> Result<Option<WebAuthnChallenge>, AppError> {
        let challenges = self.challenges.read().await;
        let challenge = challenges.get(&challenge_id).cloned();

        // Check expiration
        if let Some(ref c) = challenge {
            if c.expires_at < Utc::now() {
                return Ok(None);
            }
        }

        Ok(challenge)
    }

    async fn consume_challenge(
        &self,
        challenge_id: Uuid,
    ) -> Result<Option<WebAuthnChallenge>, AppError> {
        let mut challenges = self.challenges.write().await;
        let challenge = challenges.remove(&challenge_id);

        // Check expiration
        if let Some(ref c) = challenge {
            if c.expires_at < Utc::now() {
                return Ok(None);
            }
        }

        Ok(challenge)
    }

    async fn delete_expired_challenges(&self) -> Result<u64, AppError> {
        let mut challenges = self.challenges.write().await;
        let now = Utc::now();
        let to_remove: Vec<Uuid> = challenges
            .values()
            .filter(|c| c.expires_at < now)
            .map(|c| c.challenge_id)
            .collect();
        let count = to_remove.len() as u64;
        for id in to_remove {
            challenges.remove(&id);
        }
        Ok(count)
    }

    async fn find_all_credential_ids(&self, limit: i64) -> Result<Vec<String>, AppError> {
        let credentials = self.credentials.read().await;
        Ok(credentials
            .values()
            .take(limit as usize)
            .map(|c| c.credential_id.clone())
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    #[tokio::test]
    async fn test_create_and_find_credential() {
        let repo = InMemoryWebAuthnRepository::new();
        let user_id = Uuid::new_v4();

        let cred = WebAuthnCredential::new(
            user_id,
            "cred_id_123".to_string(),
            "public_key_data".to_string(),
            0,
            true,
        );
        let cred_id = cred.id;

        repo.create_credential(cred).await.unwrap();

        let found = repo.find_credential_by_id(cred_id).await.unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().credential_id, "cred_id_123");
    }

    #[tokio::test]
    async fn test_find_by_user() {
        let repo = InMemoryWebAuthnRepository::new();
        let user_id = Uuid::new_v4();

        repo.create_credential(WebAuthnCredential::new(
            user_id,
            "cred_1".to_string(),
            "pk1".to_string(),
            0,
            true,
        ))
        .await
        .unwrap();

        repo.create_credential(WebAuthnCredential::new(
            user_id,
            "cred_2".to_string(),
            "pk2".to_string(),
            0,
            false,
        ))
        .await
        .unwrap();

        let creds = repo.find_by_user(user_id).await.unwrap();
        assert_eq!(creds.len(), 2);

        let discoverable = repo.find_discoverable_by_user(user_id).await.unwrap();
        assert_eq!(discoverable.len(), 1);
    }

    #[tokio::test]
    async fn test_challenge_expiration() {
        let repo = InMemoryWebAuthnRepository::new();
        let challenge_id = Uuid::new_v4();

        let challenge = WebAuthnChallenge {
            challenge_id,
            user_id: Some(Uuid::new_v4()),
            state: "state_data".to_string(),
            challenge_type: "register".to_string(),
            created_at: Utc::now(),
            expires_at: Utc::now() - Duration::seconds(10), // Already expired
        };

        repo.store_challenge(challenge).await.unwrap();

        // Expired challenge should not be returned
        let result = repo.consume_challenge(challenge_id).await.unwrap();
        assert!(result.is_none());
    }
}