authrs 0.1.2

A comprehensive authentication library for Rust
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! WebAuthn 认证流程模块
//!
//! 提供 Passkey 凭证认证的完整流程支持。

use std::collections::HashMap;
use std::sync::RwLock;

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use webauthn_rs::prelude::*;

use super::credential::CredentialStore;
use super::registration::UserVerification;

// ============================================================================
// 认证配置
// ============================================================================

/// 认证配置
#[derive(Debug, Clone)]
pub struct AuthenticationConfig {
    /// 用户验证要求
    pub user_verification: UserVerification,

    /// 认证超时时间(毫秒)
    pub timeout_ms: u32,

    /// 是否允许空凭证列表(用于可发现凭证 / Discoverable Credentials)
    pub allow_empty_credentials: bool,
}

impl Default for AuthenticationConfig {
    fn default() -> Self {
        Self {
            user_verification: UserVerification::Preferred,
            timeout_ms: 60000, // 60 秒
            allow_empty_credentials: false,
        }
    }
}

impl AuthenticationConfig {
    /// 创建高安全性配置(要求用户验证)
    pub fn high_security() -> Self {
        Self {
            user_verification: UserVerification::Required,
            ..Default::default()
        }
    }

    /// 创建可发现凭证配置(无需提供用户名)
    pub fn discoverable() -> Self {
        Self {
            allow_empty_credentials: true,
            ..Default::default()
        }
    }
}

// ============================================================================
// 认证状态
// ============================================================================

/// 认证会话状态
///
/// 在开始认证和完成认证之间需要保存此状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthenticationState {
    /// 用户唯一标识(可能为空,用于可发现凭证场景)
    pub user_id: Option<String>,

    /// 底层 Passkey 认证状态
    pub passkey_authentication: PasskeyAuthentication,

    /// 会话创建时间
    pub created_at: DateTime<Utc>,

    /// 会话过期时间
    pub expires_at: DateTime<Utc>,
}

impl AuthenticationState {
    /// 检查会话是否已过期
    pub fn is_expired(&self) -> bool {
        Utc::now() > self.expires_at
    }
}

// ============================================================================
// 认证结果
// ============================================================================

/// 认证结果
#[derive(Debug, Clone)]
pub struct WebAuthnAuthenticationResult {
    /// 认证成功的凭证 ID
    pub credential_id: String,

    /// 用户 ID
    pub user_id: String,

    /// 用户是否进行了验证(如指纹、PIN)
    pub user_verified: bool,

    /// 认证计数器(用于检测克隆攻击)
    pub counter: u32,

    /// 认证时间
    pub authenticated_at: DateTime<Utc>,
}

// ============================================================================
// 认证管理器
// ============================================================================

/// WebAuthn 认证管理器
///
/// 管理 Passkey 凭证的认证流程
pub struct AuthenticationManager<'a> {
    webauthn: &'a Webauthn,
    config: AuthenticationConfig,
}

impl<'a> AuthenticationManager<'a> {
    /// 创建新的认证管理器
    pub fn new(webauthn: &'a Webauthn) -> Self {
        Self {
            webauthn,
            config: AuthenticationConfig::default(),
        }
    }

    /// 使用自定义配置创建认证管理器
    pub fn with_config(webauthn: &'a Webauthn, config: AuthenticationConfig) -> Self {
        Self { webauthn, config }
    }

    /// 开始认证流程
    ///
    /// # 参数
    /// - `user_id`: 用户唯一标识
    /// - `credentials`: 用户已注册的凭证列表
    ///
    /// # 返回
    /// - `RequestChallengeResponse`: 发送给客户端的挑战数据
    /// - `AuthenticationState`: 需要保存的认证状态
    pub fn start_authentication(
        &self,
        user_id: Option<String>,
        credentials: Vec<Passkey>,
    ) -> Result<(RequestChallengeResponse, AuthenticationState), AuthenticationError> {
        // 检查凭证列表
        if credentials.is_empty() && !self.config.allow_empty_credentials {
            return Err(AuthenticationError::NoCredentials);
        }

        // 开始认证流程
        let (rcr, passkey_authentication) = self
            .webauthn
            .start_passkey_authentication(&credentials)
            .map_err(|e| AuthenticationError::WebAuthnError(e.to_string()))?;

        // 创建认证状态
        let now = Utc::now();
        let expires_at = now + chrono::Duration::milliseconds(i64::from(self.config.timeout_ms));

        let state = AuthenticationState {
            user_id,
            passkey_authentication,
            created_at: now,
            expires_at,
        };

        Ok((rcr, state))
    }

    /// 完成认证流程
    ///
    /// # 参数
    /// - `state`: 之前保存的认证状态
    /// - `response`: 客户端返回的认证响应
    /// - `credentials`: 用户已注册的凭证列表(用于验证和更新)
    ///
    /// # 返回
    /// - `WebAuthnAuthenticationResult`: 认证结果
    /// - `Option<Passkey>`: 更新后的 Passkey(如果计数器有变化)
    pub fn finish_authentication(
        &self,
        state: &AuthenticationState,
        response: &PublicKeyCredential,
        credentials: &[Passkey],
    ) -> Result<(WebAuthnAuthenticationResult, Option<Passkey>), AuthenticationError> {
        // 检查会话是否过期
        if state.is_expired() {
            return Err(AuthenticationError::SessionExpired);
        }

        // 完成认证
        let auth_result = self
            .webauthn
            .finish_passkey_authentication(response, &state.passkey_authentication)
            .map_err(|e| AuthenticationError::WebAuthnError(e.to_string()))?;

        // 查找匹配的凭证
        let cred_id_bytes = auth_result.cred_id();
        let credential_id = base64_url_encode(cred_id_bytes.as_ref());

        // 查找并更新凭证
        let updated_passkey = credentials
            .iter()
            .find(|c| c.cred_id() == cred_id_bytes)
            .cloned()
            .map(|mut pk| {
                pk.update_credential(&auth_result);
                pk
            });

        let user_id = state
            .user_id
            .clone()
            .unwrap_or_else(|| credential_id.clone());

        let result = WebAuthnAuthenticationResult {
            credential_id,
            user_id,
            user_verified: auth_result.user_verified(),
            counter: auth_result.counter(),
            authenticated_at: Utc::now(),
        };

        Ok((result, updated_passkey))
    }

    /// 使用存储开始认证
    ///
    /// 便捷方法,自动从存储中获取用户凭证
    pub async fn start_authentication_with_store<S: CredentialStore>(
        &self,
        user_id: impl Into<String>,
        store: &S,
    ) -> Result<(RequestChallengeResponse, AuthenticationState), AuthenticationError> {
        let user_id = user_id.into();
        let credentials = store.get_passkeys_for_user(&user_id).await;

        if credentials.is_empty() {
            return Err(AuthenticationError::NoCredentials);
        }

        self.start_authentication(Some(user_id), credentials)
    }

    /// 完成认证并更新凭证
    ///
    /// 便捷方法,自动更新存储中的凭证
    pub async fn finish_authentication_and_update<S: CredentialStore>(
        &self,
        state: &AuthenticationState,
        response: &PublicKeyCredential,
        store: &S,
    ) -> Result<WebAuthnAuthenticationResult, AuthenticationError> {
        // 获取用户凭证
        let user_id = state
            .user_id
            .as_ref()
            .ok_or(AuthenticationError::MissingUserId)?;

        let credentials = store.get_passkeys_for_user(user_id).await;

        // 完成认证
        let (result, updated_passkey) =
            self.finish_authentication(state, response, &credentials)?;

        // 更新凭证(如果有变化)
        if let Some(passkey) = updated_passkey {
            if let Some(mut stored) = store.find_by_id(&result.credential_id).await {
                stored.update_passkey(passkey);
                stored.record_use();
                store
                    .update(stored)
                    .await
                    .map_err(|e| AuthenticationError::StorageError(e.to_string()))?;
            }
        }

        Ok(result)
    }
}

// ============================================================================
// 认证状态存储
// ============================================================================

/// 认证状态存储 Trait
///
/// 用于在认证流程中保存临时状态
#[async_trait]
pub trait AuthenticationStateStore: Send + Sync {
    /// 保存认证状态
    async fn save_state(
        &self,
        session_id: &str,
        state: AuthenticationState,
    ) -> Result<(), AuthenticationError>;

    /// 获取并移除认证状态
    async fn take_state(&self, session_id: &str) -> Option<AuthenticationState>;

    /// 清理过期状态
    async fn cleanup_expired(&self);
}

/// 内存认证状态存储
#[derive(Debug, Default)]
pub struct InMemoryAuthenticationStateStore {
    states: RwLock<HashMap<String, AuthenticationState>>,
}

impl InMemoryAuthenticationStateStore {
    /// 创建新的内存存储
    pub fn new() -> Self {
        Self::default()
    }
}

#[async_trait]
impl AuthenticationStateStore for InMemoryAuthenticationStateStore {
    async fn save_state(
        &self,
        session_id: &str,
        state: AuthenticationState,
    ) -> Result<(), AuthenticationError> {
        if let Ok(mut states) = self.states.write() {
            states.insert(session_id.to_string(), state);
        }
        Ok(())
    }

    async fn take_state(&self, session_id: &str) -> Option<AuthenticationState> {
        self.states
            .write()
            .ok()
            .and_then(|mut states| states.remove(session_id))
    }

    async fn cleanup_expired(&self) {
        if let Ok(mut states) = self.states.write() {
            states.retain(|_, state| !state.is_expired());
        }
    }
}

// ============================================================================
// 错误类型
// ============================================================================

/// 认证错误
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthenticationError {
    /// WebAuthn 操作错误
    WebAuthnError(String),

    /// 会话已过期
    SessionExpired,

    /// 没有可用的凭证
    NoCredentials,

    /// 凭证未找到
    CredentialNotFound,

    /// 缺少用户 ID
    MissingUserId,

    /// 存储错误
    StorageError(String),

    /// 凭证已被撤销
    CredentialRevoked,

    /// 计数器回滚(可能的克隆攻击)
    CounterRollback {
        /// 存储的计数器值
        stored: u32,
        /// 收到的计数器值
        received: u32,
    },
}

impl std::fmt::Display for AuthenticationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WebAuthnError(e) => write!(f, "WebAuthn 错误: {}", e),
            Self::SessionExpired => write!(f, "认证会话已过期"),
            Self::NoCredentials => write!(f, "没有可用的凭证"),
            Self::CredentialNotFound => write!(f, "凭证未找到"),
            Self::MissingUserId => write!(f, "缺少用户 ID"),
            Self::StorageError(e) => write!(f, "存储错误: {}", e),
            Self::CredentialRevoked => write!(f, "凭证已被撤销"),
            Self::CounterRollback { stored, received } => {
                write!(
                    f,
                    "检测到计数器回滚(可能的克隆攻击):存储值={}, 收到值={}",
                    stored, received
                )
            }
        }
    }
}

impl std::error::Error for AuthenticationError {}

// ============================================================================
// 辅助函数
// ============================================================================

/// Base64 URL 安全编码(无填充)
fn base64_url_encode(data: &[u8]) -> String {
    use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
    URL_SAFE_NO_PAD.encode(data)
}

// ============================================================================
// 测试
// ============================================================================

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

    #[test]
    fn test_authentication_config_default() {
        let config = AuthenticationConfig::default();
        assert_eq!(config.timeout_ms, 60000);
        assert!(!config.allow_empty_credentials);
    }

    #[test]
    fn test_authentication_config_high_security() {
        let config = AuthenticationConfig::high_security();
        assert_eq!(config.user_verification, UserVerification::Required);
    }

    #[test]
    fn test_authentication_config_discoverable() {
        let config = AuthenticationConfig::discoverable();
        assert!(config.allow_empty_credentials);
    }

    #[test]
    fn test_authentication_error_display() {
        assert_eq!(
            AuthenticationError::SessionExpired.to_string(),
            "认证会话已过期"
        );
        assert_eq!(
            AuthenticationError::NoCredentials.to_string(),
            "没有可用的凭证"
        );
        assert_eq!(
            AuthenticationError::CounterRollback {
                stored: 10,
                received: 5
            }
            .to_string(),
            "检测到计数器回滚(可能的克隆攻击):存储值=10, 收到值=5"
        );
    }

    #[tokio::test]
    async fn test_in_memory_authentication_state_store() {
        let store = InMemoryAuthenticationStateStore::new();

        // 测试获取不存在的状态
        assert!(store.take_state("nonexistent").await.is_none());
    }

    #[test]
    fn test_base64_url_encode() {
        let data = b"hello world";
        let encoded = base64_url_encode(data);
        // URL 安全编码不应包含 +, /, =
        assert!(!encoded.contains('+'));
        assert!(!encoded.contains('/'));
        assert!(!encoded.contains('='));
    }
}