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
488
489
490
491
492
493
//! # AuthRS
//!
//! 一个全面的 Rust 认证库。
//!
//! ## 功能特性
//!
//! - **密码哈希**: 使用 Argon2、bcrypt、scrypt 进行安全的密码哈希
//! - **密码强度检查**: 密码强度评估与验证
//! - **安全随机数**: 密码学安全的随机数生成
//! - **JWT Token**: JSON Web Token 的生成、验证和刷新
//! - **Session 管理**: 安全的 Session 创建、验证和存储
//! - **Refresh Token**: Token 轮换和重用检测
//! - **MFA**: TOTP/HOTP 多因素认证
//! - **速率限制**: 防止暴力破解攻击
//! - **CSRF 防护**: 跨站请求伪造防护
//! - **OAuth 2.0**: OAuth 客户端、PKCE、Token 内省
//! - **API Key 管理**: 完整的 API Key 生命周期管理
//! - **账户安全**: 账户锁定、登录追踪、递增延迟
//! - **WebAuthn / Passkeys**: 无密码认证支持
//! - **RBAC**: 角色权限管理、策略引擎
//! - **审计日志**: 安全事件记录与查询
//! - **安全 Cookie**: Cookie 签名、验证与安全属性管理
//! - **密钥派生**: HKDF-SHA256/SHA512 密钥派生函数
//! - **Passwordless**: Magic Link 与 OTP 支持
//! - **API Key 管理**: API Key 生命周期管理与校验
//!
//! ## Features
//!
//! 本库使用 Cargo features 来允许用户选择性地启用功能:
//!
//! - `argon2` - 启用 Argon2id 密码哈希支持(默认启用)
//! - `bcrypt` - 启用 bcrypt 密码哈希支持
//! - `scrypt` - 启用 scrypt 密码哈希支持
//! - `jwt` - 启用 JWT 支持(默认启用)
//! - `mfa` - 启用 TOTP/HOTP 多因素认证(默认启用)
//! - `oauth` - 启用 OAuth 2.0 支持(PKCE、客户端管理、Token 内省)
//! - `rbac` - 启用 RBAC 角色权限管理支持
//! - `webauthn` - 启用 WebAuthn / Passkeys 支持
//! - `passwordless` - 启用 Magic Link / OTP 无密码认证支持
//! - `crypto` - 启用密码学工具(HKDF 等)
//! - `api-key` - 启用 API Key 管理支持
//! - `full` - 启用所有功能
//!
//! 默认启用的 features: `argon2`, `jwt`, `mfa`
//!
//! ## 密码哈希示例
//!
//! ```rust
//! use authrs::password::{hash_password, verify_password};
//!
//! // 哈希密码
//! let hash = hash_password("my_secure_password").unwrap();
//!
//! // 验证密码
//! let is_valid = verify_password("my_secure_password", &hash).unwrap();
//! assert!(is_valid);
//! ```
//!
//! ## 密码强度检查
//!
//! ```rust
//! use authrs::password::{validate_password_strength, PasswordRequirements};
//!
//! // 使用默认要求
//! let result = validate_password_strength("Str0ng_P@ssword!");
//! assert!(result.is_ok());
//!
//! // 使用严格要求
//! let requirements = PasswordRequirements::strict();
//! ```
//!
//! ## JWT Token 示例
//!
#![cfg_attr(feature = "jwt", doc = "```rust")]
#![cfg_attr(not(feature = "jwt"), doc = "```rust,ignore")]
//! use authrs::token::jwt::{JwtBuilder, JwtValidator};
//!
//! // 创建 JWT
//! let secret = b"my-secret-key-at-least-32-bytes!";
//! let token = JwtBuilder::new()
//!     .subject("user123")
//!     .issuer("my-app")
//!     .expires_in_hours(24)
//!     .build_with_secret(secret)
//!     .unwrap();
//!
//! // 验证 JWT
//! let validator = JwtValidator::new(secret);
//! let claims = validator.validate(&token).unwrap();
//! ```
//!
//! ## Session 管理示例
//!
//! ```rust
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! use authrs::token::session::{SessionManager, SessionConfig};
//!
//! // 创建 Session 管理器
//! let manager = SessionManager::new(SessionConfig::default());
//!
//! // 创建 Session
//! let session = manager.create("user123").await.unwrap();
//!
//! // 获取 Session
//! if let Some(s) = manager.get(&session.id).await {
//!     println!("User: {}", s.user_id);
//! }
//! # });
//! ```
//!
//! ## OAuth 2.0 示例
//!
#![cfg_attr(feature = "oauth", doc = "```rust")]
#![cfg_attr(not(feature = "oauth"), doc = "```rust,ignore")]
//! use authrs::oauth::{OAuthClient, ClientType, GrantType, PkceChallenge, PkceMethod};
//!
//! // 创建 OAuth 客户端
//! let (client, secret) = OAuthClient::builder()
//!     .name("My Application")
//!     .client_type(ClientType::Confidential)
//!     .redirect_uri("https://example.com/callback")
//!     .grant_type(GrantType::AuthorizationCode)
//!     .scope("read")
//!     .build()
//!     .unwrap();
//!
//! // 生成 PKCE challenge
//! let pkce = PkceChallenge::new(PkceMethod::S256).unwrap();
//! let (code_challenge, method) = pkce.authorization_params();
//! ```
//!
//! ## API Key 管理示例
//!
#![cfg_attr(feature = "api-key", doc = "```rust")]
#![cfg_attr(not(feature = "api-key"), doc = "```rust,ignore")]
//! use authrs::api_key::{ApiKeyManager, ApiKeyConfig};
//!
//! // 创建管理器
//! let mut manager = ApiKeyManager::with_default_config();
//!
//! // 创建 API Key
//! let (key, plain_key) = manager.create_key("my-service")
//!     .with_prefix("sk_live")
//!     .with_scope("read")
//!     .with_expires_in_days(90)
//!     .build()
//!     .unwrap();
//!
//! manager.add_key(key);
//!
//! // 验证 API Key
//! if let Some(validated) = manager.validate(&plain_key) {
//!     println!("Key is valid, owner: {}", validated.owner);
//! }
//! ```
//!
//! ## 账户锁定示例
//!
//! ```rust
//! use authrs::security::account::{LoginAttemptTracker, AccountLockoutConfig, LoginCheckResult};
//!
//! // 创建追踪器
//! let mut tracker = LoginAttemptTracker::with_default_config();
//!
//! // 检查是否允许登录
//! match tracker.check_login_allowed("user123", None) {
//!     LoginCheckResult::Allowed => {
//!         // 允许登录尝试
//!         // 如果登录失败:
//!         tracker.record_failed_attempt("user123", None);
//!         // 如果登录成功:
//!         // tracker.record_successful_login("user123", None);
//!     }
//!     LoginCheckResult::Locked { reason, remaining } => {
//!         println!("账户已锁定: {:?}", reason);
//!     }
//!     LoginCheckResult::DelayRequired { wait_time } => {
//!         println!("请等待 {:?} 后重试", wait_time);
//!     }
//!     LoginCheckResult::IpBanned { ip } => {
//!         println!("IP {} 已被封禁", ip);
//!     }
//! }
//! ```
//!
//! ## WebAuthn / Passkeys 示例
//!
#![cfg_attr(feature = "webauthn", doc = "```rust,ignore")]
#![cfg_attr(not(feature = "webauthn"), doc = "```rust,ignore")]
//! use authrs::webauthn::{WebAuthnService, RegistrationManager, InMemoryCredentialStore};
//!
//! // 创建 WebAuthn 服务
//! let service = WebAuthnService::new(
//!     "example.com",
//!     "https://example.com",
//!     "My Application",
//! ).unwrap();
//!
//! // 开始注册流程
//! let reg_manager = service.registration_manager();
//! let (challenge, state) = reg_manager.start_registration(
//!     "user123",
//!     "alice",
//!     "Alice",
//!     "My Passkey",
//!     None,
//! ).unwrap();
//!
//! // 将 challenge 发送给客户端进行处理...
//! // 客户端完成后,使用 finish_registration 完成注册
//! ```
//!
//! ## RBAC 角色权限示例
//!
#![cfg_attr(feature = "rbac", doc = "```rust")]
#![cfg_attr(not(feature = "rbac"), doc = "```rust,ignore")]
//! use authrs::rbac::{Permission, Role, RoleBuilder, RoleManager, PolicyEngine, Policy, Subject, Resource, Action};
//!
//! // 创建角色管理器
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let manager = RoleManager::new();
//!
//! // 创建角色
//! let viewer = RoleBuilder::new("viewer")
//!     .permission(Permission::new("posts", "read"))
//!     .build();
//!
//! let editor = RoleBuilder::new("editor")
//!     .inherit("viewer")
//!     .permission(Permission::new("posts", "write"))
//!     .build();
//!
//! manager.add_role(viewer).await;
//! manager.add_role(editor).await;
//!
//! // 检查权限
//! assert!(
//!     manager
//!         .role_has_permission("editor", &Permission::new("posts", "read"))
//!         .await
//! );
//! assert!(
//!     manager
//!         .role_has_permission("editor", &Permission::new("posts", "write"))
//!         .await
//! );
//!
//! // 使用策略引擎
//! let mut engine = PolicyEngine::new();
//! engine.add_policy(
//!     Policy::allow("editor-posts")
//!         .role("editor")
//!         .resource("posts")
//!         .actions(["read", "write"])
//!         .build()
//! );
//!
//! let user = Subject::new("user1").with_role("editor");
//! assert!(engine.check_permission(&user, "posts", "read"));
//! # });
//! ```

#[cfg(feature = "api-key")]
pub mod api_key;
pub mod audit;
#[cfg(feature = "crypto")]
pub mod crypto;
pub mod error;
pub mod mfa;
#[cfg(feature = "oauth")]
pub mod oauth;
pub mod password;
#[cfg(feature = "passwordless")]
pub mod passwordless;
pub mod random;
#[cfg(feature = "rbac")]
pub mod rbac;
pub mod security;
pub mod token;
#[cfg(feature = "webauthn")]
pub mod webauthn;

pub use error::{Error, Result};

// ============================================================================
// 密码相关导出
// ============================================================================

pub use password::{Algorithm, PasswordHasher, hash_password, verify_password};

// ============================================================================
// 随机数生成函数导出
// ============================================================================

pub use random::{
    constant_time_compare, constant_time_compare_str, generate_api_key, generate_csrf_token,
    generate_random_alphanumeric, generate_random_base64_url, generate_random_bytes,
    generate_random_hex, generate_recovery_codes, generate_reset_token, generate_session_token,
};

// ============================================================================
// Token 相关导出
// ============================================================================

#[cfg(feature = "jwt")]
pub use token::jwt::{
    Claims, JwtAlgorithm, JwtBuilder, JwtValidator, TokenPair, TokenPairGenerator,
};
pub use token::refresh::{
    RefreshConfig, RefreshToken, RefreshTokenManager, RefreshTokenStore, TokenUseResult,
};
pub use token::session::{
    CreateSessionOptions, InMemorySessionStore, Session, SessionConfig, SessionManager,
    SessionStore,
};

// ============================================================================
// MFA 相关导出
// ============================================================================

#[cfg(feature = "mfa")]
pub use mfa::hotp::{HotpConfig, HotpGenerator};
#[cfg(feature = "mfa")]
pub use mfa::recovery::{RecoveryCodeManager, RecoveryCodeSet, RecoveryConfig};
#[cfg(feature = "mfa")]
pub use mfa::totp::{TotpConfig, TotpManager, TotpSecret};

// ============================================================================
// 安全防护相关导出
// ============================================================================

pub use security::account::{
    AccountLockStatus, AccountLockStore, AccountLockoutConfig, InMemoryAccountLockStore,
    LockReason, LoginAttempt, LoginAttemptTracker, LoginCheckResult, TrackerStats,
};
pub use security::cookie::{
    SameSite, SecureCookie, delete_cookie_header, sign_cookie, verify_cookie,
};
pub use security::csrf::{CsrfConfig, CsrfProtection, CsrfToken};
pub use security::rate_limit::{RateLimitConfig, RateLimitInfo, RateLimiter};

// ============================================================================
// 审计日志相关导出
// ============================================================================

pub use audit::{
    AuditLogger, AuditStats, EventSeverity, EventType, InMemoryAuditLogger, NoOpAuditLogger,
    SecurityEvent,
};

// ============================================================================
// OAuth 2.0 相关导出
// ============================================================================

#[cfg(feature = "oauth")]
pub use oauth::{
    // Token
    AccessToken,
    // Client
    ClientType,
    GrantType,
    InMemoryClientStore,
    // Introspection
    IntrospectionRequest,
    IntrospectionResponse,
    IntrospectionResponseBuilder,
    OAuthClient,
    OAuthClientBuilder,
    OAuthClientStore,
    OAuthError,
    OAuthErrorCode,
    OAuthRefreshToken,
    // PKCE
    PkceChallenge,
    PkceCodeChallenge,
    PkceConfig,
    PkceMethod,
    PkceVerifier,
    TokenIntrospector,
    TokenResponse,
    TokenType,
    TokenTypeHint,
};

// ============================================================================
// API Key 管理相关导出
// ============================================================================

#[cfg(feature = "api-key")]
pub use api_key::{
    ApiKey, ApiKeyBuilder, ApiKeyConfig, ApiKeyManager, ApiKeyStats, ApiKeyStatus, ApiKeyStore,
    InMemoryApiKeyStore,
};

// ============================================================================
// WebAuthn / Passkeys 相关导出
// ============================================================================

#[cfg(feature = "webauthn")]
pub use webauthn::{
    // 认证流程
    AuthenticationConfig,
    AuthenticationError,
    AuthenticationManager,
    AuthenticationState,
    AuthenticationStateStore,
    // Re-exports from webauthn-rs
    AuthenticatorAttachment,
    CreationChallengeResponse,
    // 凭证管理
    CredentialStore,
    CredentialStoreError,
    InMemoryAuthenticationStateStore,
    InMemoryCredentialStore,
    // 注册流程
    InMemoryRegistrationStateStore,
    Passkey,
    PublicKeyCredential,
    RegisterPublicKeyCredential,
    RegistrationConfig,
    RegistrationError,
    RegistrationManager,
    RegistrationState,
    RegistrationStateStore,
    RequestChallengeResponse,
    StoredCredential,
    UserVerification,
    Uuid,
    WebAuthnAuthenticationResult,
    // 服务封装
    WebAuthnService,
    WebAuthnServiceError,
    Webauthn,
    WebauthnBuilder,
};

// ============================================================================
// 密码学工具相关导出
// ============================================================================

#[cfg(feature = "crypto")]
pub use crypto::kdf::{
    Hkdf, HkdfAlgorithm, derive_key_from_password, derive_subkeys, hkdf_sha256, hkdf_sha512,
};

// ============================================================================
// Passwordless 认证相关导出
// ============================================================================

#[cfg(feature = "passwordless")]
pub use passwordless::{
    // Magic Link
    InMemoryMagicLinkStore,
    // OTP
    InMemoryOtpStore,
    MagicLinkConfig,
    MagicLinkData,
    MagicLinkManager,
    MagicLinkStore,
    OtpConfig,
    OtpData,
    OtpManager,
    OtpPurpose,
    OtpStore,
};

// ============================================================================
// RBAC 相关导出
// ============================================================================

#[cfg(feature = "rbac")]
pub use rbac::{
    // 权限
    Action,
    // 策略
    Decision,
    DecisionReason,
    // 角色
    InMemoryRoleStore,
    Permission,
    PermissionSet,
    Policy,
    PolicyBuilder,
    PolicyEffect,
    PolicyEngine,
    PolicyEvaluator,
    Resource,
    Role,
    RoleBuilder,
    RoleManager,
    RoleStore,
    Subject,
};