authrs/lib.rs
1//! # AuthRS
2//!
3//! 一个全面的 Rust 认证库。
4//!
5//! ## 功能特性
6//!
7//! - **密码哈希**: 使用 Argon2、bcrypt、scrypt 进行安全的密码哈希
8//! - **密码强度检查**: 密码强度评估与验证
9//! - **安全随机数**: 密码学安全的随机数生成
10//! - **JWT Token**: JSON Web Token 的生成、验证和刷新
11//! - **Session 管理**: 安全的 Session 创建、验证和存储
12//! - **Refresh Token**: Token 轮换和重用检测
13//! - **MFA**: TOTP/HOTP 多因素认证
14//! - **速率限制**: 防止暴力破解攻击
15//! - **CSRF 防护**: 跨站请求伪造防护
16//! - **OAuth 2.0**: OAuth 客户端、PKCE、Token 内省
17//! - **API Key 管理**: 完整的 API Key 生命周期管理
18//! - **账户安全**: 账户锁定、登录追踪、递增延迟
19//! - **WebAuthn / Passkeys**: 无密码认证支持
20//! - **RBAC**: 角色权限管理、策略引擎
21//! - **审计日志**: 安全事件记录与查询
22//! - **安全 Cookie**: Cookie 签名、验证与安全属性管理
23//! - **密钥派生**: HKDF-SHA256/SHA512 密钥派生函数
24//! - **Passwordless**: Magic Link 与 OTP 支持
25//! - **API Key 管理**: API Key 生命周期管理与校验
26//!
27//! ## Features
28//!
29//! 本库使用 Cargo features 来允许用户选择性地启用功能:
30//!
31//! - `argon2` - 启用 Argon2id 密码哈希支持(默认启用)
32//! - `bcrypt` - 启用 bcrypt 密码哈希支持
33//! - `scrypt` - 启用 scrypt 密码哈希支持
34//! - `jwt` - 启用 JWT 支持(默认启用)
35//! - `mfa` - 启用 TOTP/HOTP 多因素认证(默认启用)
36//! - `oauth` - 启用 OAuth 2.0 支持(PKCE、客户端管理、Token 内省)
37//! - `rbac` - 启用 RBAC 角色权限管理支持
38//! - `webauthn` - 启用 WebAuthn / Passkeys 支持
39//! - `passwordless` - 启用 Magic Link / OTP 无密码认证支持
40//! - `crypto` - 启用密码学工具(HKDF 等)
41//! - `api-key` - 启用 API Key 管理支持
42//! - `full` - 启用所有功能
43//!
44//! 默认启用的 features: `argon2`, `jwt`, `mfa`
45//!
46//! ## 密码哈希示例
47//!
48//! ```rust
49//! use authrs::password::{hash_password, verify_password};
50//!
51//! // 哈希密码
52//! let hash = hash_password("my_secure_password").unwrap();
53//!
54//! // 验证密码
55//! let is_valid = verify_password("my_secure_password", &hash).unwrap();
56//! assert!(is_valid);
57//! ```
58//!
59//! ## 密码强度检查
60//!
61//! ```rust
62//! use authrs::password::{validate_password_strength, PasswordRequirements};
63//!
64//! // 使用默认要求
65//! let result = validate_password_strength("Str0ng_P@ssword!");
66//! assert!(result.is_ok());
67//!
68//! // 使用严格要求
69//! let requirements = PasswordRequirements::strict();
70//! ```
71//!
72//! ## JWT Token 示例
73//!
74#![cfg_attr(feature = "jwt", doc = "```rust")]
75#![cfg_attr(not(feature = "jwt"), doc = "```rust,ignore")]
76//! use authrs::token::jwt::{JwtBuilder, JwtValidator};
77//!
78//! // 创建 JWT
79//! let secret = b"my-secret-key-at-least-32-bytes!";
80//! let token = JwtBuilder::new()
81//! .subject("user123")
82//! .issuer("my-app")
83//! .expires_in_hours(24)
84//! .build_with_secret(secret)
85//! .unwrap();
86//!
87//! // 验证 JWT
88//! let validator = JwtValidator::new(secret);
89//! let claims = validator.validate(&token).unwrap();
90//! ```
91//!
92//! ## Session 管理示例
93//!
94//! ```rust
95//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
96//! use authrs::token::session::{SessionManager, SessionConfig};
97//!
98//! // 创建 Session 管理器
99//! let manager = SessionManager::new(SessionConfig::default());
100//!
101//! // 创建 Session
102//! let session = manager.create("user123").await.unwrap();
103//!
104//! // 获取 Session
105//! if let Some(s) = manager.get(&session.id).await {
106//! println!("User: {}", s.user_id);
107//! }
108//! # });
109//! ```
110//!
111//! ## OAuth 2.0 示例
112//!
113#![cfg_attr(feature = "oauth", doc = "```rust")]
114#![cfg_attr(not(feature = "oauth"), doc = "```rust,ignore")]
115//! use authrs::oauth::{OAuthClient, ClientType, GrantType, PkceChallenge, PkceMethod};
116//!
117//! // 创建 OAuth 客户端
118//! let (client, secret) = OAuthClient::builder()
119//! .name("My Application")
120//! .client_type(ClientType::Confidential)
121//! .redirect_uri("https://example.com/callback")
122//! .grant_type(GrantType::AuthorizationCode)
123//! .scope("read")
124//! .build()
125//! .unwrap();
126//!
127//! // 生成 PKCE challenge
128//! let pkce = PkceChallenge::new(PkceMethod::S256).unwrap();
129//! let (code_challenge, method) = pkce.authorization_params();
130//! ```
131//!
132//! ## API Key 管理示例
133//!
134#![cfg_attr(feature = "api-key", doc = "```rust")]
135#![cfg_attr(not(feature = "api-key"), doc = "```rust,ignore")]
136//! use authrs::api_key::{ApiKeyManager, ApiKeyConfig};
137//!
138//! // 创建管理器
139//! let mut manager = ApiKeyManager::with_default_config();
140//!
141//! // 创建 API Key
142//! let (key, plain_key) = manager.create_key("my-service")
143//! .with_prefix("sk_live")
144//! .with_scope("read")
145//! .with_expires_in_days(90)
146//! .build()
147//! .unwrap();
148//!
149//! manager.add_key(key);
150//!
151//! // 验证 API Key
152//! if let Some(validated) = manager.validate(&plain_key) {
153//! println!("Key is valid, owner: {}", validated.owner);
154//! }
155//! ```
156//!
157//! ## 账户锁定示例
158//!
159//! ```rust
160//! use authrs::security::account::{LoginAttemptTracker, AccountLockoutConfig, LoginCheckResult};
161//!
162//! // 创建追踪器
163//! let mut tracker = LoginAttemptTracker::with_default_config();
164//!
165//! // 检查是否允许登录
166//! match tracker.check_login_allowed("user123", None) {
167//! LoginCheckResult::Allowed => {
168//! // 允许登录尝试
169//! // 如果登录失败:
170//! tracker.record_failed_attempt("user123", None);
171//! // 如果登录成功:
172//! // tracker.record_successful_login("user123", None);
173//! }
174//! LoginCheckResult::Locked { reason, remaining } => {
175//! println!("账户已锁定: {:?}", reason);
176//! }
177//! LoginCheckResult::DelayRequired { wait_time } => {
178//! println!("请等待 {:?} 后重试", wait_time);
179//! }
180//! LoginCheckResult::IpBanned { ip } => {
181//! println!("IP {} 已被封禁", ip);
182//! }
183//! }
184//! ```
185//!
186//! ## WebAuthn / Passkeys 示例
187//!
188#![cfg_attr(feature = "webauthn", doc = "```rust,ignore")]
189#![cfg_attr(not(feature = "webauthn"), doc = "```rust,ignore")]
190//! use authrs::webauthn::{WebAuthnService, RegistrationManager, InMemoryCredentialStore};
191//!
192//! // 创建 WebAuthn 服务
193//! let service = WebAuthnService::new(
194//! "example.com",
195//! "https://example.com",
196//! "My Application",
197//! ).unwrap();
198//!
199//! // 开始注册流程
200//! let reg_manager = service.registration_manager();
201//! let (challenge, state) = reg_manager.start_registration(
202//! "user123",
203//! "alice",
204//! "Alice",
205//! "My Passkey",
206//! None,
207//! ).unwrap();
208//!
209//! // 将 challenge 发送给客户端进行处理...
210//! // 客户端完成后,使用 finish_registration 完成注册
211//! ```
212//!
213//! ## RBAC 角色权限示例
214//!
215#![cfg_attr(feature = "rbac", doc = "```rust")]
216#![cfg_attr(not(feature = "rbac"), doc = "```rust,ignore")]
217//! use authrs::rbac::{Permission, Role, RoleBuilder, RoleManager, PolicyEngine, Policy, Subject, Resource, Action};
218//!
219//! // 创建角色管理器
220//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
221//! let manager = RoleManager::new();
222//!
223//! // 创建角色
224//! let viewer = RoleBuilder::new("viewer")
225//! .permission(Permission::new("posts", "read"))
226//! .build();
227//!
228//! let editor = RoleBuilder::new("editor")
229//! .inherit("viewer")
230//! .permission(Permission::new("posts", "write"))
231//! .build();
232//!
233//! manager.add_role(viewer).await;
234//! manager.add_role(editor).await;
235//!
236//! // 检查权限
237//! assert!(
238//! manager
239//! .role_has_permission("editor", &Permission::new("posts", "read"))
240//! .await
241//! );
242//! assert!(
243//! manager
244//! .role_has_permission("editor", &Permission::new("posts", "write"))
245//! .await
246//! );
247//!
248//! // 使用策略引擎
249//! let mut engine = PolicyEngine::new();
250//! engine.add_policy(
251//! Policy::allow("editor-posts")
252//! .role("editor")
253//! .resource("posts")
254//! .actions(["read", "write"])
255//! .build()
256//! );
257//!
258//! let user = Subject::new("user1").with_role("editor");
259//! assert!(engine.check_permission(&user, "posts", "read"));
260//! # });
261//! ```
262
263#[cfg(feature = "api-key")]
264pub mod api_key;
265pub mod audit;
266#[cfg(feature = "crypto")]
267pub mod crypto;
268pub mod error;
269pub mod mfa;
270#[cfg(feature = "oauth")]
271pub mod oauth;
272pub mod password;
273#[cfg(feature = "passwordless")]
274pub mod passwordless;
275pub mod random;
276#[cfg(feature = "rbac")]
277pub mod rbac;
278pub mod security;
279pub mod token;
280#[cfg(feature = "webauthn")]
281pub mod webauthn;
282
283pub use error::{Error, Result};
284
285// ============================================================================
286// 密码相关导出
287// ============================================================================
288
289pub use password::{Algorithm, PasswordHasher, hash_password, verify_password};
290
291// ============================================================================
292// 随机数生成函数导出
293// ============================================================================
294
295pub use random::{
296 constant_time_compare, constant_time_compare_str, generate_api_key, generate_csrf_token,
297 generate_random_alphanumeric, generate_random_base64_url, generate_random_bytes,
298 generate_random_hex, generate_recovery_codes, generate_reset_token, generate_session_token,
299};
300
301// ============================================================================
302// Token 相关导出
303// ============================================================================
304
305#[cfg(feature = "jwt")]
306pub use token::jwt::{
307 Claims, JwtAlgorithm, JwtBuilder, JwtValidator, TokenPair, TokenPairGenerator,
308};
309pub use token::refresh::{
310 RefreshConfig, RefreshToken, RefreshTokenManager, RefreshTokenStore, TokenUseResult,
311};
312pub use token::session::{
313 CreateSessionOptions, InMemorySessionStore, Session, SessionConfig, SessionManager,
314 SessionStore,
315};
316
317// ============================================================================
318// MFA 相关导出
319// ============================================================================
320
321#[cfg(feature = "mfa")]
322pub use mfa::hotp::{HotpConfig, HotpGenerator};
323#[cfg(feature = "mfa")]
324pub use mfa::recovery::{RecoveryCodeManager, RecoveryCodeSet, RecoveryConfig};
325#[cfg(feature = "mfa")]
326pub use mfa::totp::{TotpConfig, TotpManager, TotpSecret};
327
328// ============================================================================
329// 安全防护相关导出
330// ============================================================================
331
332pub use security::account::{
333 AccountLockStatus, AccountLockStore, AccountLockoutConfig, InMemoryAccountLockStore,
334 LockReason, LoginAttempt, LoginAttemptTracker, LoginCheckResult, TrackerStats,
335};
336pub use security::cookie::{
337 SameSite, SecureCookie, delete_cookie_header, sign_cookie, verify_cookie,
338};
339pub use security::csrf::{CsrfConfig, CsrfProtection, CsrfToken};
340pub use security::rate_limit::{RateLimitConfig, RateLimitInfo, RateLimiter};
341
342// ============================================================================
343// 审计日志相关导出
344// ============================================================================
345
346pub use audit::{
347 AuditLogger, AuditStats, EventSeverity, EventType, InMemoryAuditLogger, NoOpAuditLogger,
348 SecurityEvent,
349};
350
351// ============================================================================
352// OAuth 2.0 相关导出
353// ============================================================================
354
355#[cfg(feature = "oauth")]
356pub use oauth::{
357 // Token
358 AccessToken,
359 // Client
360 ClientType,
361 GrantType,
362 InMemoryClientStore,
363 // Introspection
364 IntrospectionRequest,
365 IntrospectionResponse,
366 IntrospectionResponseBuilder,
367 OAuthClient,
368 OAuthClientBuilder,
369 OAuthClientStore,
370 OAuthError,
371 OAuthErrorCode,
372 OAuthRefreshToken,
373 // PKCE
374 PkceChallenge,
375 PkceCodeChallenge,
376 PkceConfig,
377 PkceMethod,
378 PkceVerifier,
379 TokenIntrospector,
380 TokenResponse,
381 TokenType,
382 TokenTypeHint,
383};
384
385// ============================================================================
386// API Key 管理相关导出
387// ============================================================================
388
389#[cfg(feature = "api-key")]
390pub use api_key::{
391 ApiKey, ApiKeyBuilder, ApiKeyConfig, ApiKeyManager, ApiKeyStats, ApiKeyStatus, ApiKeyStore,
392 InMemoryApiKeyStore,
393};
394
395// ============================================================================
396// WebAuthn / Passkeys 相关导出
397// ============================================================================
398
399#[cfg(feature = "webauthn")]
400pub use webauthn::{
401 // 认证流程
402 AuthenticationConfig,
403 AuthenticationError,
404 AuthenticationManager,
405 AuthenticationState,
406 AuthenticationStateStore,
407 // Re-exports from webauthn-rs
408 AuthenticatorAttachment,
409 CreationChallengeResponse,
410 // 凭证管理
411 CredentialStore,
412 CredentialStoreError,
413 InMemoryAuthenticationStateStore,
414 InMemoryCredentialStore,
415 // 注册流程
416 InMemoryRegistrationStateStore,
417 Passkey,
418 PublicKeyCredential,
419 RegisterPublicKeyCredential,
420 RegistrationConfig,
421 RegistrationError,
422 RegistrationManager,
423 RegistrationState,
424 RegistrationStateStore,
425 RequestChallengeResponse,
426 StoredCredential,
427 UserVerification,
428 Uuid,
429 WebAuthnAuthenticationResult,
430 // 服务封装
431 WebAuthnService,
432 WebAuthnServiceError,
433 Webauthn,
434 WebauthnBuilder,
435};
436
437// ============================================================================
438// 密码学工具相关导出
439// ============================================================================
440
441#[cfg(feature = "crypto")]
442pub use crypto::kdf::{
443 Hkdf, HkdfAlgorithm, derive_key_from_password, derive_subkeys, hkdf_sha256, hkdf_sha512,
444};
445
446// ============================================================================
447// Passwordless 认证相关导出
448// ============================================================================
449
450#[cfg(feature = "passwordless")]
451pub use passwordless::{
452 // Magic Link
453 InMemoryMagicLinkStore,
454 // OTP
455 InMemoryOtpStore,
456 MagicLinkConfig,
457 MagicLinkData,
458 MagicLinkManager,
459 MagicLinkStore,
460 OtpConfig,
461 OtpData,
462 OtpManager,
463 OtpPurpose,
464 OtpStore,
465};
466
467// ============================================================================
468// RBAC 相关导出
469// ============================================================================
470
471#[cfg(feature = "rbac")]
472pub use rbac::{
473 // 权限
474 Action,
475 // 策略
476 Decision,
477 DecisionReason,
478 // 角色
479 InMemoryRoleStore,
480 Permission,
481 PermissionSet,
482 Policy,
483 PolicyBuilder,
484 PolicyEffect,
485 PolicyEngine,
486 PolicyEvaluator,
487 Resource,
488 Role,
489 RoleBuilder,
490 RoleManager,
491 RoleStore,
492 Subject,
493};